@dioramajs/core 0.1.1 → 0.1.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dioramajs/core",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "The core of Diorama: app, plugins, signals, frame loop, stage, scroll and pointer.",
5
5
  "keywords": [
6
6
  "diorama",
package/src/index.ts CHANGED
@@ -32,7 +32,7 @@ export {
32
32
  type ScrollState,
33
33
  scroll,
34
34
  } from './web/scroll'
35
- export { type StageApi, type StageOptions, stage } from './web/stage'
35
+ export { type ScrollSpan, type StageApi, type StageOptions, stage } from './web/stage'
36
36
  export { type VisibilityApi, type VisibilityOptions, visibility } from './web/visibility'
37
37
 
38
38
  /** Built-in web layer, in start order. Disable one with `disable`, or all with `defaults: false`. */
package/src/web/follow.ts CHANGED
@@ -3,12 +3,19 @@ import type { AppCore, Off } from '../kernel/types'
3
3
  const KEYFRAMES = 'dio-stage-scroll'
4
4
  /** Scroll covered by the follow animation, px. Past it the canvas stays put. */
5
5
  const RANGE = 1_000_000
6
+ /** Spans that moved less than this, px, keep their keyframes. */
7
+ const SPAN_TOLERANCE = 0.5
6
8
  let sheet: CSSStyleSheet | undefined
9
+ let instances = 0
10
+
11
+ /** A span of page scroll, px from the top, over which content on screen stands still. */
12
+ export type ScrollSpan = readonly [start: number, end: number]
7
13
 
8
14
  /** Starts following a canvas; `hold` keeps it still while a predicate is true. */
9
15
  export interface Follow {
10
16
  (canvas: HTMLCanvasElement): void
11
17
  hold(held: () => boolean): Off
18
+ pin(spans: () => readonly ScrollSpan[]): Off
12
19
  }
13
20
 
14
21
  /**
@@ -17,15 +24,18 @@ export interface Follow {
17
24
  * `translate`, the scroll it drew at. Between frames the canvas moves with the page by the
18
25
  * scroll the frame has not seen yet.
19
26
  *
20
- * Content that stands still on screen (a pinned sticky stage) would ride that scroll and jump
21
- * back when the frame lands, so while any `hold` predicate is true the canvas drops the
22
- * animation and stays fixed to the viewport, and frames draw at scroll 0. Predicates run in
23
- * `afterRender`, after the frame's layout reads, and the animation and the offset switch in
24
- * that same frame. Needs a DOM.
27
+ * Content that stands still on screen would ride that scroll and jump back when the frame lands.
28
+ * `pin` spans (a pinned sticky stage) go into the keyframes: the timeline stops moving the canvas
29
+ * inside them, so it stops and starts on the compositor where CSS sticky does, between frames.
30
+ * A `hold` predicate (content fixed to the viewport) drops the animation while true, and frames
31
+ * draw at scroll 0. Both are read in `afterRender`, after the frame's layout reads, and the
32
+ * animation and the offset switch in that same frame. Needs a DOM.
25
33
  */
26
- export function followScroll(app: Pick<AppCore, 'system'>): Follow {
34
+ export function followScroll(app: Pick<AppCore, 'system' | 'onDispose'>): Follow {
27
35
  const root = document.documentElement
28
36
  const holds = new Set<() => boolean>()
37
+ const pins = new Set<() => readonly ScrollSpan[]>()
38
+ const id = ++instances
29
39
  let followed: { canvas: HTMLCanvasElement; computed: CSSStyleDeclaration } | undefined
30
40
  /** The site's styles keep the animation. */
31
41
  let animated = false
@@ -35,19 +45,27 @@ export function followScroll(app: Pick<AppCore, 'system'>): Follow {
35
45
  let held = false
36
46
  /** The offset last written to `translate`. */
37
47
  let written = 0
48
+ /** The spans in the keyframes and the animation name that carries them. */
49
+ let spans: ScrollSpan[] = []
50
+ let name = KEYFRAMES
51
+ let version = 0
52
+ let own: CSSStyleSheet | undefined
38
53
  app.system(
39
54
  'layout',
40
55
  () => {
41
56
  if (!followed) return
42
- adoptKeyframes()
57
+ adoptKeyframes(own)
43
58
  // A stylesheet that drops the animation (`animation: none !important`) turns following
44
59
  // off. While held the computed name is the hold's own `none`, so the last reading stays.
45
60
  if (!held) {
46
61
  const { animationName, animationTimeline } = followed.computed
47
- animated = animationName === KEYFRAMES && animationTimeline?.startsWith('scroll(') !== false
62
+ animated =
63
+ animationName.startsWith(KEYFRAMES) && animationTimeline?.startsWith('scroll(') !== false
48
64
  }
49
- // The timeline is clamped to the scroll range, rubber-band overscroll is not.
50
- const max = root.scrollHeight - root.clientHeight
65
+ // The timeline is clamped to the scroll range, rubber-band overscroll is not. The range
66
+ // ends one visible viewport short of the bottom; on phones that grows as the toolbar hides.
67
+ const viewport = window.visualViewport?.height ?? root.clientHeight
68
+ const max = root.scrollHeight - Math.max(viewport, 0)
51
69
  drawnAt = animated ? Math.max(0, Math.min(window.scrollY, max, RANGE)) : 0
52
70
  },
53
71
  { name: 'stage' },
@@ -56,21 +74,40 @@ export function followScroll(app: Pick<AppCore, 'system'>): Follow {
56
74
  'afterRender',
57
75
  () => {
58
76
  if (!followed) return
77
+ const { canvas } = followed
59
78
  let hold = false
60
79
  if (animated) {
61
80
  for (const predicate of holds) if (predicate()) hold = true
62
81
  }
63
- if (hold !== held) {
64
- held = hold
65
- followed.canvas.style.animationName = hold ? 'none' : KEYFRAMES
82
+ if (animated && !hold) {
83
+ const next = collect(pins)
84
+ if (!sameSpans(next, spans)) {
85
+ spans = next
86
+ if (spans.length) {
87
+ // A new name restarts the animation on the new keyframes in every engine.
88
+ name = `${KEYFRAMES}-${id}-${++version % 2}`
89
+ own ??= new CSSStyleSheet()
90
+ own.replaceSync(pinnedKeyframes(name, spans))
91
+ adoptKeyframes(own)
92
+ } else {
93
+ name = KEYFRAMES
94
+ }
95
+ }
66
96
  }
67
- const offset = hold ? 0 : drawnAt
97
+ const wanted = hold ? 'none' : name
98
+ if (held !== hold || canvas.style.animationName !== wanted)
99
+ canvas.style.animationName = wanted
100
+ held = hold
101
+ const offset = hold ? 0 : drawnAt - covered(spans, drawnAt)
68
102
  if (offset === written) return
69
103
  written = offset
70
- followed.canvas.style.translate = offset ? `0px ${offset}px` : ''
104
+ canvas.style.translate = offset ? `0px ${offset}px` : ''
71
105
  },
72
106
  { name: 'stage' },
73
107
  )
108
+ app.onDispose(() => {
109
+ if (own) document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== own)
110
+ })
74
111
  const follow = ((canvas) => {
75
112
  const computed = startAnimation(canvas)
76
113
  if (computed) followed = { canvas, computed }
@@ -81,17 +118,72 @@ export function followScroll(app: Pick<AppCore, 'system'>): Follow {
81
118
  holds.add(entry)
82
119
  return () => void holds.delete(entry)
83
120
  }
121
+ follow.pin = (source) => {
122
+ const entry = (): readonly ScrollSpan[] => source()
123
+ pins.add(entry)
124
+ return () => void pins.delete(entry)
125
+ }
84
126
  return follow
85
127
  }
86
128
 
129
+ /** All spans, clipped to the animation range, sorted, overlaps merged. */
130
+ function collect(pins: Set<() => readonly ScrollSpan[]>): ScrollSpan[] {
131
+ const all: [number, number][] = []
132
+ for (const source of pins) {
133
+ for (const [start, end] of source()) {
134
+ const from = Math.max(0, start)
135
+ const to = Math.min(RANGE, end)
136
+ if (to > from) all.push([from, to])
137
+ }
138
+ }
139
+ all.sort((a, b) => a[0] - b[0])
140
+ const merged: [number, number][] = []
141
+ for (const span of all) {
142
+ const last = merged.at(-1)
143
+ if (last && span[0] <= last[1]) last[1] = Math.max(last[1], span[1])
144
+ else merged.push(span)
145
+ }
146
+ return merged
147
+ }
148
+
149
+ const sameSpans = (a: readonly ScrollSpan[], b: readonly ScrollSpan[]): boolean =>
150
+ a.length === b.length &&
151
+ a.every(([start, end], i) => {
152
+ const [from, to] = b[i] as ScrollSpan
153
+ return Math.abs(start - from) < SPAN_TOLERANCE && Math.abs(end - to) < SPAN_TOLERANCE
154
+ })
155
+
156
+ /** Scroll below `at` that falls inside the spans. */
157
+ function covered(spans: readonly ScrollSpan[], at: number): number {
158
+ let sum = 0
159
+ for (const [start, end] of spans) sum += Math.max(0, Math.min(at, end) - start)
160
+ return sum
161
+ }
162
+
163
+ /** Keyframes that move by the scroll outside the spans and stand still inside them. */
164
+ function pinnedKeyframes(name: string, spans: readonly ScrollSpan[]): string {
165
+ const frame = (at: number, by: number): string =>
166
+ `${((at / RANGE) * 100).toFixed(6)}%{transform:translateY(${-by}px)}`
167
+ const frames = [frame(0, 0)]
168
+ let still = 0
169
+ for (const [start, end] of spans) {
170
+ frames.push(frame(start, start - still))
171
+ still += end - start
172
+ frames.push(frame(end, end - still))
173
+ }
174
+ frames.push(frame(RANGE, RANGE - still))
175
+ return `@keyframes ${name}{${frames.join('')}}`
176
+ }
177
+
87
178
  /** Adopts the keyframes, again if a site reassigns `document.adoptedStyleSheets`. */
88
- function adoptKeyframes(): void {
179
+ function adoptKeyframes(own?: CSSStyleSheet): void {
89
180
  if (!sheet) {
90
181
  sheet = new CSSStyleSheet()
91
182
  sheet.replaceSync(`@keyframes ${KEYFRAMES} { to { transform: translateY(-${RANGE}px) } }`)
92
183
  }
93
184
  const sheets = document.adoptedStyleSheets
94
- if (!sheets.includes(sheet)) document.adoptedStyleSheets = [...sheets, sheet]
185
+ const missing = [sheet, own].filter((s): s is CSSStyleSheet => !!s && !sheets.includes(s))
186
+ if (missing.length) document.adoptedStyleSheets = [...sheets, ...missing]
95
187
  }
96
188
 
97
189
  /** Starts the scroll-timeline animation on `canvas`. `undefined` if the engine lacks it. */
package/src/web/stage.ts CHANGED
@@ -4,7 +4,9 @@ import { batch, signal } from '../kernel/signals'
4
4
  import type { Off, Plugin, ReadonlySignal } from '../kernel/types'
5
5
  import { noop } from '../kernel/util'
6
6
  import { onBodySwap } from './body'
7
- import { followScroll } from './follow'
7
+ import { followScroll, type ScrollSpan } from './follow'
8
+
9
+ export type { ScrollSpan } from './follow'
8
10
 
9
11
  /** Options of the `stage` plugin. */
10
12
  export interface StageOptions {
@@ -21,9 +23,9 @@ export interface StageOptions {
21
23
  * Keeps GL copies on their elements while the browser scrolls the page ahead of the next frame
22
24
  * (keyboard, scrollbar, native wheel, touch). The created canvas moves with the page on the
23
25
  * compositor until the frame lands, and GL content fixed to the viewport moves with it for that
24
- * time. While a `stage.hold` predicate is true (effects: a pinned sticky stage of a scroll
25
- * section) the canvas stays fixed to the viewport instead. Vertical page scroll only. Needs CSS
26
- * scroll-driven animations. Default true.
26
+ * time. Inside `stage.pin` spans (effects: a pinned sticky stage of a scroll section) and while
27
+ * a `stage.hold` predicate is true the canvas stays fixed to the viewport instead. Vertical page
28
+ * scroll only. Needs CSS scroll-driven animations. Default true.
27
29
  */
28
30
  readonly followScroll: boolean
29
31
  }
@@ -32,9 +34,13 @@ export interface StageOptions {
32
34
  export interface StageApi {
33
35
  /** The page-wide canvas, created on first access. `undefined` without a DOM. */
34
36
  readonly canvas: HTMLCanvasElement | undefined
35
- /** Viewport size in CSS px, excluding scrollbars. */
37
+ /** Viewport width in CSS px, excluding scrollbars. */
36
38
  readonly width: ReadonlySignal<number>
37
- /** Viewport height in CSS px, excluding scrollbars. */
39
+ /**
40
+ * Viewport height in CSS px: the large viewport of CSS `100lvh` (`100vh`), so on phones the
41
+ * height with the browser toolbar hidden. It stays put while the toolbar slides, and the
42
+ * created canvas is that tall.
43
+ */
38
44
  readonly height: ReadonlySignal<number>
39
45
  /** Device pixel ratio, capped by `maxPixelRatio`. */
40
46
  readonly pixelRatio: ReadonlySignal<number>
@@ -42,11 +48,19 @@ export interface StageApi {
42
48
  readonly reducedMotion: ReadonlySignal<boolean>
43
49
  /**
44
50
  * Keeps the created canvas from following scroll (`followScroll`) while `held()` is true:
45
- * for content that stands still on screen as the page scrolls, such as a pinned sticky stage.
46
- * Read once per frame after the frame is drawn; the switch lands with that frame. Returns a
47
- * function that removes the predicate. Without following it does nothing.
51
+ * for content fixed to the viewport. Read once per frame after the frame is drawn; the switch
52
+ * lands with that frame. Returns a function that removes the predicate. Without following it
53
+ * does nothing.
48
54
  */
49
55
  hold(held: () => boolean): Off
56
+ /**
57
+ * Scroll spans, in page px from the top, over which content on screen stands still, such as a
58
+ * pinned sticky stage from where it sticks to where it lets go. The created canvas stops
59
+ * following inside them on the compositor, so it stops and starts where CSS sticky does, also
60
+ * between frames. Read once per frame after the frame is drawn. Returns a function that
61
+ * removes the source. Without following it does nothing.
62
+ */
63
+ pin(spans: () => readonly ScrollSpan[]): Off
50
64
  }
51
65
 
52
66
  const defaults: StageOptions = {
@@ -56,6 +70,20 @@ const defaults: StageOptions = {
56
70
  followScroll: true,
57
71
  }
58
72
 
73
+ /** The large viewport, with the fallback for engines without `lvh` first. */
74
+ const LARGE = ['100vh', '100lvh'] as const
75
+
76
+ /** Height of the large viewport in CSS px, 0 where it cannot be measured. */
77
+ function largeViewport(): number {
78
+ const probe = document.createElement('div')
79
+ probe.style.cssText = `position:fixed;top:0;left:0;width:0;visibility:hidden;pointer-events:none;height:${LARGE[0]};height:${LARGE[1]}`
80
+ // Outside <body>, so routers that swap it and observers of it never see the probe.
81
+ document.documentElement.append(probe)
82
+ const { height } = probe.getBoundingClientRect()
83
+ probe.remove()
84
+ return height
85
+ }
86
+
59
87
  /** Canvases created by live apps. Any other `canvas[data-dio-canvas]` is a stale clone. */
60
88
  const liveCanvases = new WeakSet<Element>()
61
89
 
@@ -75,6 +103,7 @@ export const stage: Plugin<'stage', StageOptions> = /*#__PURE__*/ definePlugin({
75
103
  pixelRatio,
76
104
  reducedMotion,
77
105
  hold: () => noop,
106
+ pin: () => noop,
78
107
  }
79
108
  if (typeof document === 'undefined') return api
80
109
 
@@ -82,7 +111,7 @@ export const stage: Plugin<'stage', StageOptions> = /*#__PURE__*/ definePlugin({
82
111
  const measure = (): void => {
83
112
  batch(() => {
84
113
  width.value = root.clientWidth
85
- height.value = root.clientHeight
114
+ height.value = Math.max(root.clientHeight, largeViewport())
86
115
  pixelRatio.value = Math.min(window.devicePixelRatio || 1, options.maxPixelRatio)
87
116
  })
88
117
  app.invalidate()
@@ -124,6 +153,7 @@ export const stage: Plugin<'stage', StageOptions> = /*#__PURE__*/ definePlugin({
124
153
  return {
125
154
  ...api,
126
155
  hold: follow.hold,
156
+ pin: follow.pin,
127
157
  get canvas() {
128
158
  canvas ??= resolveCanvas(options, adopt)
129
159
  return canvas
@@ -153,10 +183,12 @@ function resolveCanvas(
153
183
  position: 'fixed',
154
184
  inset: '0',
155
185
  width: '100%',
156
- height: '100%',
186
+ height: LARGE[0],
157
187
  pointerEvents: 'none',
158
188
  zIndex: String(options.zIndex),
159
189
  })
190
+ // On phones a full-height fixed box resizes as the toolbar slides; the large viewport does not.
191
+ created.style.height = LARGE[1]
160
192
  document.body.append(created)
161
193
  adopt(created)
162
194
  return created