ember-joinery 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,305 @@
1
+ import Component from '@glimmer/component'
2
+ import { hash } from '@ember/helper'
3
+ import { on } from '@ember/modifier'
4
+ import { registerDestructor } from '@ember/destroyable'
5
+ import { isTesting } from '@ember/debug'
6
+ import { renderSettled } from '@ember/renderer'
7
+ import type { TOC } from '@ember/component/template-only'
8
+ import type Owner from '@ember/owner'
9
+ import type RouterService from '@ember/routing/router-service'
10
+ import type Transition from '@ember/routing/transition'
11
+ import type { WithBoundArgs } from '@glint/template'
12
+ import { ChevronLeft } from 'lucide'
13
+ import { isUndefined } from '@sindresorhus/is'
14
+ import { isRTL } from '@ember-joinery/primitives/direction'
15
+ import { t } from '@ember-joinery/primitives/i18n'
16
+ import { part, type PartModifier } from '@ember-joinery/primitives/part'
17
+ import { findOwner } from '@ember-joinery/primitives/store'
18
+ import Button from './button.gts'
19
+ import Icon from './icon.gts'
20
+ import { messages } from '../messages.ts'
21
+
22
+ /** Which way the last change of depth went: `push` to a deeper screen, `pop` back from one. */
23
+ export type NavigationStackDirection = 'push' | 'pop'
24
+
25
+ /**
26
+ * When a swipe from the inline-start edge goes back: `auto` only in an installed app (in a
27
+ * browser tab the browser's own back gesture stays in control), `true` always, `false` never.
28
+ */
29
+ export type NavigationStackEdgeSwipe = 'auto' | boolean
30
+
31
+ /** How far from the inline-start edge a swipe can start, and how far it moves to go back. */
32
+ const EDGE = 20
33
+ const SWIPE = 80
34
+
35
+ /** A document runs one view transition at a time, so every stack shares this. */
36
+ let running = false
37
+
38
+ const withoutIndex = (name: string): string => name.replace(/(^|\.)index$/, '')
39
+
40
+ /**
41
+ * Which way the depth last changed. It is a memory and not tracked state: for the same depths
42
+ * in the same order it gives the same answer, so the template can ask in each render.
43
+ */
44
+ class Direction {
45
+ #depth: number | undefined
46
+ #direction: NavigationStackDirection = 'push'
47
+
48
+ of(depth: number): NavigationStackDirection {
49
+ if (this.#depth !== undefined && depth !== this.#depth) {
50
+ this.#direction = depth < this.#depth ? 'pop' : 'push'
51
+ }
52
+ this.#depth = depth
53
+ return this.#direction
54
+ }
55
+ }
56
+
57
+ /** How many route segments `name` is below `root` (the application, without one). */
58
+ function depthOf(name: string | null | undefined, root: string | undefined): number {
59
+ const route = withoutIndex(name ?? '')
60
+ if (!root) return route ? route.split('.').length : 0
61
+ return route.startsWith(`${root}.`) ? route.slice(root.length + 1).split('.').length : 0
62
+ }
63
+
64
+ /** Whether the app runs as an installed app: a standalone PWA, or an Electron or Tauri window. */
65
+ function isStandalone(): boolean {
66
+ if (isUndefined(globalThis.matchMedia)) return false // A render on a server.
67
+ return (
68
+ matchMedia('(display-mode: standalone)').matches ||
69
+ (navigator as Navigator & { standalone?: boolean }).standalone === true ||
70
+ navigator.userAgent.includes('Electron') ||
71
+ '__TAURI_INTERNALS__' in window ||
72
+ '__TAURI__' in window
73
+ )
74
+ }
75
+
76
+ export interface NavigationStackBackButtonSignature {
77
+ Args: {
78
+ /** Its text. Default `Back`. */
79
+ label?: string
80
+ /** Whether it renders on the first screen too. Default `false`: only when there is a back. */
81
+ always?: boolean
82
+ /** Set by the stack: whether there is a screen to go back to. */
83
+ canGoBack: boolean
84
+ /** Set by the stack: goes back. */
85
+ back: () => void
86
+ }
87
+ Element: HTMLButtonElement | HTMLAnchorElement
88
+ }
89
+
90
+ const BackButton: TOC<NavigationStackBackButtonSignature> = <template>
91
+ {{#if (either @always @canGoBack)}}
92
+ <Button
93
+ @variant="ghost"
94
+ @size="sm"
95
+ type="button"
96
+ data-jn-navigation-stack-back
97
+ ...attributes
98
+ {{on "click" @back}}
99
+ >
100
+ <Icon @icon={{ChevronLeft}} data-icon="inline-start" class="jn-rtl-flip" />
101
+ {{if @label @label (t messages.navigationStackBack)}}
102
+ </Button>
103
+ {{/if}}
104
+ </template>
105
+
106
+ function either(a: unknown, b: unknown): boolean {
107
+ return Boolean(a) || Boolean(b)
108
+ }
109
+
110
+ /** What a navigation stack yields. */
111
+ export interface NavigationStackParts {
112
+ /** How many screens are below the current screen: 0 on the first screen. */
113
+ depth: number
114
+ /** Whether there is a screen to go back to: `depth` is more than 0. */
115
+ canGoBack: boolean
116
+ /** Goes back: `@onBack`, or a transition to the parent route of the current route. */
117
+ back: () => void
118
+ /** Which way the last change of depth went. */
119
+ direction: NavigationStackDirection
120
+ /** A ghost `Button` with a chevron that calls `back`. It renders only when `canGoBack`. */
121
+ BackButton: WithBoundArgs<typeof BackButton, 'canGoBack' | 'back'>
122
+ }
123
+
124
+ export interface NavigationStackSignature {
125
+ Args: {
126
+ /**
127
+ * The route that is the first screen of the stack, such as `contacts`. The depth is the
128
+ * number of route segments below it; a last `index` does not count. Default: the
129
+ * application route.
130
+ */
131
+ root?: string
132
+ /** The depth, controlled, for a stack without routes (in a sheet). It replaces the router's. */
133
+ depth?: number
134
+ /** Called to go back, in place of the transition to the parent route. */
135
+ onBack?: () => void
136
+ /** Whether a change of depth between routes runs in a view transition. Default `true`. */
137
+ animated?: boolean
138
+ /** When a swipe from the inline-start edge goes back. Default `auto`: in an installed app. */
139
+ edgeSwipe?: NavigationStackEdgeSwipe
140
+ /** Its name, for `NavigationStackHarness` (`data-test-jn-name`). */
141
+ name?: string
142
+ }
143
+ Blocks: {
144
+ /** The screens: the `{{outlet}}`, with the stack's state and its back button. */
145
+ default: [NavigationStackParts]
146
+ }
147
+ Element: HTMLDivElement
148
+ }
149
+
150
+ /**
151
+ * Push and pop navigation, as SwiftUI's `NavigationStack`, where the nested routes are the
152
+ * stack. Joinery's own (shadcn/ui has none). A deep link and the browser's back button work,
153
+ * because the router owns the state.
154
+ *
155
+ * <NavigationStack @root="contacts" as |stack|>
156
+ * <stack.BackButton />
157
+ * {{outlet}}
158
+ * </NavigationStack>
159
+ *
160
+ * Where the browser has View Transitions and the user did not ask for reduced motion, a change
161
+ * of depth slides the old screen out and the new screen in. For that, the stack aborts the
162
+ * transition and tries it again inside the view transition, so the browser can draw the old
163
+ * screen first. The root has `data-transitioning` only during that view transition, so a view
164
+ * transition of the app, or of a different stack, does not slide this stack.
165
+ * `@animated={{false}}` leaves the transition alone, and so does a test.
166
+ *
167
+ * It wraps the screens, so it is a wrapper for the harnesses (`data-test-jn-wrapper`), and its
168
+ * elements are styled by `data-jn-navigation-stack-*` attributes.
169
+ */
170
+ export default class NavigationStack extends Component<NavigationStackSignature> {
171
+ #direction = new Direction()
172
+ #swipeFrom: number | undefined
173
+ #root: HTMLElement | undefined
174
+
175
+ /** @internal Keeps the root, which has `data-transitioning` during a view transition. */
176
+ setup: PartModifier = part(() => ({ element: element => void (this.#root = element) }))
177
+
178
+ constructor(owner: Owner, args: NavigationStackSignature['Args']) {
179
+ super(owner, args)
180
+ const router = this.router
181
+ router?.on('routeWillChange', this.#animate)
182
+ registerDestructor(this, () => router?.off('routeWillChange', this.#animate))
183
+ }
184
+
185
+ /** The app's router. A test that renders the component alone has one that never started. */
186
+ get router(): RouterService | undefined {
187
+ return findOwner(this)?.lookup('service:router') as RouterService | undefined
188
+ }
189
+
190
+ get depth(): number {
191
+ return this.args.depth ?? depthOf(this.router?.currentRouteName, this.args.root)
192
+ }
193
+
194
+ get canGoBack(): boolean {
195
+ return this.depth > 0
196
+ }
197
+
198
+ /** Follows the depth, so it is correct in the same render as the new screen. */
199
+ get direction(): NavigationStackDirection {
200
+ return this.#direction.of(this.depth)
201
+ }
202
+
203
+ get edgeSwipe(): boolean {
204
+ const edgeSwipe = this.args.edgeSwipe ?? 'auto'
205
+ return edgeSwipe === 'auto' ? isStandalone() : edgeSwipe
206
+ }
207
+
208
+ back = (): void => {
209
+ if (this.args.onBack) return this.args.onBack()
210
+ const route = withoutIndex(this.router?.currentRouteName ?? '')
211
+ if (!this.canGoBack || !route) return
212
+ // The parent's dynamic segments stay: the router keeps the models of the active routes.
213
+ this.router?.transitionTo(route.includes('.') ? route.replace(/\.[^.]*$/, '') : 'application')
214
+ }
215
+
216
+ /** Runs a change of depth between two routes of the stack inside a view transition. */
217
+ #animate = (transition: Transition): void => {
218
+ const { root, animated, depth } = this.args
219
+ const { from, to } = transition
220
+ // A test's settled() cannot wait for the browser to start a view transition: none in a test.
221
+ if (running || isTesting() || animated === false || depth !== undefined || !from || !to) return
222
+ if (depthOf(from.name, root) === depthOf(to.name, root)) return
223
+ if (
224
+ !('startViewTransition' in document) ||
225
+ matchMedia('(prefers-reduced-motion: reduce)').matches
226
+ ) {
227
+ return
228
+ }
229
+ running = true
230
+ // The CSS gives the content its view transition name, and the slide, only with this.
231
+ const element = this.#root
232
+ element?.setAttribute('data-transitioning', '')
233
+ transition.abort()
234
+ const viewTransition = document.startViewTransition(async () => {
235
+ try {
236
+ await transition.retry().followRedirects()
237
+ } catch {
238
+ // An abort or an error: the view transition ends with the screen that is there.
239
+ }
240
+ await renderSettled()
241
+ })
242
+ // `ready` rejects when the browser skips the animation (a hidden page): the change is done.
243
+ viewTransition.ready.catch(() => {})
244
+ void viewTransition.finished.finally(() => {
245
+ running = false
246
+ element?.removeAttribute('data-transitioning')
247
+ })
248
+ }
249
+
250
+ swipeStart = (event: PointerEvent): void => {
251
+ this.#swipeFrom = undefined
252
+ if (!this.edgeSwipe || !this.canGoBack || event.pointerType === 'mouse') return
253
+ const root = event.currentTarget as HTMLElement
254
+ const { left, right } = root.getBoundingClientRect()
255
+ const fromEdge = isRTL(root) ? right - event.clientX : event.clientX - left
256
+ if (fromEdge >= 0 && fromEdge <= EDGE) this.#swipeFrom = event.clientX
257
+ }
258
+
259
+ swipeMove = (event: PointerEvent): void => {
260
+ if (this.#swipeFrom === undefined) return
261
+ const moved = event.clientX - this.#swipeFrom
262
+ if ((isRTL(event.currentTarget as HTMLElement) ? -moved : moved) <= SWIPE) return
263
+ this.#swipeFrom = undefined
264
+ this.back()
265
+ }
266
+
267
+ swipeEnd = (): void => {
268
+ this.#swipeFrom = undefined
269
+ }
270
+
271
+ <template>
272
+ <div
273
+ data-jn-navigation-stack
274
+ data-depth={{this.depth}}
275
+ data-direction={{this.direction}}
276
+ data-edge-swipe={{if this.edgeSwipe ""}}
277
+ data-animated={{if (isFalse @animated) "false"}}
278
+ data-test-jn="navigation-stack"
279
+ data-test-jn-wrapper
280
+ data-test-jn-name={{@name}}
281
+ ...attributes
282
+ {{this.setup}}
283
+ {{on "pointerdown" this.swipeStart}}
284
+ {{on "pointermove" this.swipeMove}}
285
+ {{on "pointerup" this.swipeEnd}}
286
+ {{on "pointercancel" this.swipeEnd}}
287
+ >
288
+ <div data-jn-navigation-stack-content>
289
+ {{yield
290
+ (hash
291
+ depth=this.depth
292
+ canGoBack=this.canGoBack
293
+ back=this.back
294
+ direction=this.direction
295
+ BackButton=(component BackButton canGoBack=this.canGoBack back=this.back)
296
+ )
297
+ }}
298
+ </div>
299
+ </div>
300
+ </template>
301
+ }
302
+
303
+ function isFalse(value: unknown): boolean {
304
+ return value === false
305
+ }
@@ -0,0 +1,134 @@
1
+ import type { TOC } from '@ember/component/template-only'
2
+ import { As, type TagName } from '@ember-joinery/primitives/as'
3
+
4
+ /**
5
+ * What a page is for: `panel` (the default) gives its body the full width; `settings` keeps the
6
+ * header's text and the body in a readable column, centred.
7
+ */
8
+ export type PageVariant = 'panel' | 'settings'
9
+
10
+ export interface PagePartSignature {
11
+ Args: {
12
+ /** The tag to render instead of the part's own. */
13
+ as?: TagName
14
+ }
15
+ Blocks: { default: [] }
16
+ Element: HTMLElement
17
+ }
18
+
19
+ export interface PageHeaderSignature {
20
+ Args: {
21
+ /**
22
+ * Whether it stays at the top while the body scrolls under it, as a material
23
+ * (`jn-material`), below an app shell's header. Default `false`.
24
+ */
25
+ sticky?: boolean
26
+ /** The tag to render instead of `header`. */
27
+ as?: TagName
28
+ }
29
+ Blocks: { default: [] }
30
+ Element: HTMLElement
31
+ }
32
+
33
+ const Header: TOC<PageHeaderSignature> = <template>
34
+ <As
35
+ @as={{if @as @as "header"}}
36
+ class={{if @sticky "jn-material"}}
37
+ data-material="bar"
38
+ data-scroll-edge="hard"
39
+ data-sticky={{if @sticky ""}}
40
+ data-jn-page-header
41
+ ...attributes
42
+ >{{yield}}</As>
43
+ </template>
44
+
45
+ const Nav: TOC<PagePartSignature> = <template>
46
+ <As @as={{if @as @as "div"}} data-jn-page-nav ...attributes>{{yield}}</As>
47
+ </template>
48
+
49
+ const Title: TOC<PagePartSignature> = <template>
50
+ <As @as={{if @as @as "h1"}} data-jn-page-title ...attributes>{{yield}}</As>
51
+ </template>
52
+
53
+ const Description: TOC<PagePartSignature> = <template>
54
+ <As @as={{if @as @as "p"}} data-jn-page-description ...attributes>{{yield}}</As>
55
+ </template>
56
+
57
+ const Actions: TOC<PagePartSignature> = <template>
58
+ <As @as={{if @as @as "div"}} data-jn-page-actions ...attributes>{{yield}}</As>
59
+ </template>
60
+
61
+ const HeaderFooter: TOC<PagePartSignature> = <template>
62
+ <As @as={{if @as @as "div"}} data-jn-page-header-footer ...attributes>{{yield}}</As>
63
+ </template>
64
+
65
+ const Body: TOC<PagePartSignature> = <template>
66
+ <As @as={{if @as @as "div"}} data-jn-page-body ...attributes>{{yield}}</As>
67
+ </template>
68
+
69
+ /** What a page yields: its parts. */
70
+ export interface PageParts {
71
+ /** The page's header: its nav, title, description, actions and footer. A `<header>`. */
72
+ Header: typeof Header
73
+ /** Before the title: a back button, or a sidebar's trigger. */
74
+ Nav: typeof Nav
75
+ /** The page's title: an `<h1>`. */
76
+ Title: typeof Title
77
+ /** A line under the title, muted. */
78
+ Description: typeof Description
79
+ /** The page's buttons, at the end of the header. */
80
+ Actions: typeof Actions
81
+ /** A row under the header's text: tabs, or a filter bar. */
82
+ HeaderFooter: typeof HeaderFooter
83
+ /** The page's content. */
84
+ Body: typeof Body
85
+ }
86
+
87
+ const PARTS: PageParts = { Header, Nav, Title, Description, Actions, HeaderFooter, Body }
88
+
89
+ export interface PageSignature {
90
+ Args: {
91
+ /** Default `panel`. `settings` keeps the body in a readable column. */
92
+ variant?: PageVariant
93
+ /** The tag to render instead of `div`, such as `section` or `article`. */
94
+ as?: TagName
95
+ /** Its name, for `PageHarness` (`data-test-jn-name`). */
96
+ name?: string
97
+ }
98
+ Blocks: { default: [PageParts] }
99
+ Element: HTMLElement
100
+ }
101
+
102
+ /**
103
+ * One screen of an app: a header (a title, what it is, and its actions) over a body. Joinery's
104
+ * own (shadcn/ui has none): Saas UI's `Page`, in Joinery's terms. It goes in an app shell's
105
+ * `Main`.
106
+ *
107
+ * <Page as |page|>
108
+ * <page.Header>
109
+ * <page.Title>Contacts</page.Title>
110
+ * <page.Description>Everyone you have talked to.</page.Description>
111
+ * <page.Actions><Button>Add contact</Button></page.Actions>
112
+ * </page.Header>
113
+ * <page.Body>…</page.Body>
114
+ * </Page>
115
+ *
116
+ * Don't name the block's parameter `p`: a binding by that name turns every `<p>` in the
117
+ * template into a call to it.
118
+ *
119
+ * It wraps the screen's content, so it is a wrapper for the harnesses (`data-test-jn-wrapper`),
120
+ * and its elements are styled by `data-jn-page-*` attributes.
121
+ */
122
+ const Page: TOC<PageSignature> = <template>
123
+ <As
124
+ @as={{@as}}
125
+ data-jn-page
126
+ data-variant={{if @variant @variant "panel"}}
127
+ data-test-jn="page"
128
+ data-test-jn-wrapper
129
+ data-test-jn-name={{@name}}
130
+ ...attributes
131
+ >{{yield PARTS}}</As>
132
+ </template>
133
+
134
+ export default Page
@@ -0,0 +1,227 @@
1
+ import Component from '@glimmer/component'
2
+ import { tracked } from '@glimmer/tracking'
3
+ import { hash } from '@ember/helper'
4
+ import { isDestroyed, isDestroying } from '@ember/destroyable'
5
+ import { ArrowDown } from 'lucide'
6
+ import { translate } from '@ember-joinery/primitives/i18n'
7
+ import { part } from '@ember-joinery/primitives/part'
8
+ import Icon from './icon.gts'
9
+ import Spinner from './spinner.gts'
10
+ import { messages } from '../messages.ts'
11
+
12
+ /** Where a pull is: at rest, under the threshold, past it, or in a refresh. */
13
+ export type PullToRefreshState = 'idle' | 'pulling' | 'armed' | 'refreshing'
14
+
15
+ /** How much of the finger's movement the indicator follows. */
16
+ const RESISTANCE = 0.5
17
+
18
+ export interface PullToRefreshSignature {
19
+ Args: {
20
+ /** Called when a pull past the threshold ends, and by `refresh`. It can return a promise. */
21
+ onRefresh?: () => unknown
22
+ /** How far the pull must go, in CSS pixels (after the resistance). Default `64`. */
23
+ threshold?: number
24
+ /** With `window`, the window scrolls the content, not the root. */
25
+ scroll?: 'window'
26
+ /** Another scroll container around the content. The root then does not scroll. */
27
+ scrollElement?: HTMLElement | null
28
+ /** Whether it ignores a pull and `refresh`. Default `false`. */
29
+ disabled?: boolean
30
+ /** What it announces when a refresh starts. Default `Refreshing`. */
31
+ refreshingLabel?: string
32
+ /** What it announces when a refresh ends. Default `Updated`. */
33
+ updatedLabel?: string
34
+ /** Its name, for `PullToRefreshHarness` (`data-test-jn-name`). */
35
+ name?: string
36
+ }
37
+ Blocks: {
38
+ /**
39
+ * The content. It gets `refresh` (an action that starts a refresh), `isRefreshing` and
40
+ * `state`, for a button: a touch gesture alone is not enough.
41
+ */
42
+ default: [{ refresh: () => Promise<void>; isRefreshing: boolean; state: PullToRefreshState }]
43
+ /** Replaces the arrow and the spinner. It gets the state, and the progress from 0 to 1. */
44
+ indicator: [{ state: PullToRefreshState; progress: number }]
45
+ }
46
+ Element: HTMLDivElement
47
+ }
48
+
49
+ /**
50
+ * Refreshes scrolling content when a touch or a pen pulls it down from the top. Joinery's own
51
+ * (shadcn/ui has none).
52
+ *
53
+ * <PullToRefresh @onRefresh={{this.reload}} class="h-full" as |pull|>
54
+ * <Button disabled={{pull.isRefreshing}} {{on "click" pull.refresh}}>Refresh</Button>
55
+ * …
56
+ * </PullToRefresh>
57
+ *
58
+ * The root has `data-state` and `--jn-pull-distance`. A polite live region announces the start
59
+ * and the end of a refresh. It wraps the content, so it is a wrapper for the harnesses
60
+ * (`data-test-jn-wrapper`), and its elements are styled by `data-jn-pull-to-refresh-*`
61
+ * attributes.
62
+ */
63
+ export default class PullToRefresh extends Component<PullToRefreshSignature> {
64
+ @tracked distance = 0
65
+ @tracked refreshing = false
66
+ @tracked announcement = ''
67
+
68
+ #root: HTMLElement | undefined
69
+ /** Where the touch went down, while a pull is possible. */
70
+ #startY: number | undefined
71
+ /** The scroll containers it changed, with the `overscroll-behavior-y` each one had. */
72
+ #contained = new Map<HTMLElement, string>()
73
+
74
+ root = part<HTMLElement>(() => ({
75
+ on: {
76
+ pointerdown: this.#down,
77
+ pointermove: this.#move,
78
+ pointerup: this.#up,
79
+ pointercancel: this.#cancel,
80
+ },
81
+ element: element => {
82
+ this.#root = element
83
+ this.#contain()
84
+ // Without this, a browser scrolls (and sends `pointercancel`) when the pull starts.
85
+ const hold = (event: TouchEvent): void => {
86
+ const y = event.touches[0]?.clientY ?? 0
87
+ if (this.#startY !== undefined && y > this.#startY && this.#atTop && event.cancelable) {
88
+ event.preventDefault()
89
+ }
90
+ }
91
+ element.addEventListener('touchmove', hold, { passive: false })
92
+ return () => {
93
+ element.removeEventListener('touchmove', hold)
94
+ for (const [scroller, previous] of this.#contained) {
95
+ scroller.style.overscrollBehaviorY = previous
96
+ }
97
+ }
98
+ },
99
+ }))
100
+
101
+ get threshold(): number {
102
+ return this.args.threshold ?? 64
103
+ }
104
+
105
+ get scrollMode(): 'root' | 'window' | 'element' {
106
+ if (this.args.scrollElement) return 'element'
107
+ return this.args.scroll === 'window' ? 'window' : 'root'
108
+ }
109
+
110
+ get state(): PullToRefreshState {
111
+ if (this.refreshing) return 'refreshing'
112
+ if (this.distance <= 0) return 'idle'
113
+ return this.distance >= this.threshold ? 'armed' : 'pulling'
114
+ }
115
+
116
+ get progress(): number {
117
+ return Math.min(this.distance / this.threshold, 1)
118
+ }
119
+
120
+ get #scroller(): HTMLElement | undefined {
121
+ if (this.args.scrollElement) return this.args.scrollElement
122
+ if (this.args.scroll !== 'window') return this.#root
123
+ return (this.#root?.ownerDocument.scrollingElement as HTMLElement | null) ?? undefined
124
+ }
125
+
126
+ get #atTop(): boolean {
127
+ return (this.#scroller?.scrollTop ?? 0) <= 0
128
+ }
129
+
130
+ /** Stops the browser's own pull to refresh on a scroll container that is not the root. */
131
+ #contain(): void {
132
+ const scroller = this.#scroller
133
+ if (!scroller || scroller === this.#root || this.#contained.has(scroller)) return
134
+ this.#contained.set(scroller, scroller.style.overscrollBehaviorY)
135
+ scroller.style.overscrollBehaviorY = 'contain'
136
+ }
137
+
138
+ #pull(distance: number): void {
139
+ this.distance = distance
140
+ this.#root?.style.setProperty('--jn-pull-distance', `${distance}px`)
141
+ }
142
+
143
+ // shortcut: a pull that starts in a nested scroll container also counts, check the event's
144
+ // path when an app needs one inside the content.
145
+ #down = (event: PointerEvent): void => {
146
+ this.#startY = undefined
147
+ if (this.args.disabled || this.refreshing) return
148
+ if (event.pointerType === 'mouse' || !event.isPrimary) return
149
+ this.#contain()
150
+ if (this.#atTop) this.#startY = event.clientY
151
+ }
152
+
153
+ #move = (event: PointerEvent): void => {
154
+ if (this.#startY === undefined) return
155
+ this.#pull(Math.max(0, (event.clientY - this.#startY) * RESISTANCE))
156
+ }
157
+
158
+ #up = (): void => {
159
+ if (this.#startY === undefined) return
160
+ const armed = this.state === 'armed'
161
+ this.#cancel()
162
+ // A pull has no caller to take a failure of `@onRefresh`, and `refresh` ends the state.
163
+ if (armed) this.refresh().catch(() => {})
164
+ }
165
+
166
+ #cancel = (): void => {
167
+ if (this.#startY === undefined) return
168
+ this.#startY = undefined
169
+ this.#pull(0)
170
+ }
171
+
172
+ /** Starts a refresh, as a pull does. A failure of `@onRefresh` is the caller's to handle. */
173
+ refresh = async (): Promise<void> => {
174
+ if (this.args.disabled || this.refreshing) return
175
+ this.refreshing = true
176
+ this.#pull(this.threshold)
177
+ this.announcement =
178
+ this.args.refreshingLabel ?? translate(this, messages.pullToRefreshRefreshing)
179
+ let failed = false
180
+ try {
181
+ await this.args.onRefresh?.()
182
+ } catch (error) {
183
+ failed = true
184
+ throw error
185
+ } finally {
186
+ // The component can go while the app refreshes.
187
+ if (!isDestroying(this) && !isDestroyed(this)) {
188
+ this.refreshing = false
189
+ this.#pull(0)
190
+ this.announcement = failed
191
+ ? ''
192
+ : (this.args.updatedLabel ?? translate(this, messages.pullToRefreshUpdated))
193
+ }
194
+ }
195
+ }
196
+
197
+ <template>
198
+ <div
199
+ data-jn-pull-to-refresh
200
+ data-state={{this.state}}
201
+ data-scroll={{this.scrollMode}}
202
+ data-disabled={{if @disabled ""}}
203
+ data-test-jn="pull-to-refresh"
204
+ data-test-jn-wrapper
205
+ data-test-jn-name={{@name}}
206
+ ...attributes
207
+ {{this.root}}
208
+ >
209
+ {{! The live region speaks for it, so the indicator is for the eye only. }}
210
+ <div data-jn-pull-to-refresh-indicator aria-hidden="true">
211
+ {{#if (has-block "indicator")}}
212
+ {{yield (hash state=this.state progress=this.progress) to="indicator"}}
213
+ {{else if this.refreshing}}
214
+ <Spinner />
215
+ {{else}}
216
+ <Icon @icon={{ArrowDown}} data-jn-pull-to-refresh-arrow />
217
+ {{/if}}
218
+ </div>
219
+ <div
220
+ data-jn-pull-to-refresh-status
221
+ role="status"
222
+ aria-live="polite"
223
+ >{{this.announcement}}</div>
224
+ {{yield (hash refresh=this.refresh isRefreshing=this.refreshing state=this.state)}}
225
+ </div>
226
+ </template>
227
+ }