@ng-native/device 0.4.0 → 0.6.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.
@@ -1,5 +1,6 @@
1
1
  import { accessibilitySource } from "./accessibility.js";
2
2
  import { colorSchemeSource } from "./color-scheme.js";
3
+ import { directionSource } from "./direction.js";
3
4
  import { screenSource } from "./screen.js";
4
5
  import { reactNative } from "./react-native.js";
5
6
  /** The system text size, as a multiplier. One off a device. */
@@ -17,6 +18,8 @@ export function currentConditions() {
17
18
  // already on screen, so nothing is lost by learning it a tick late.
18
19
  reducedMotion: false,
19
20
  fontScale: fontScale(),
21
+ // Settled while the native side starts up, and fixed until the app restarts.
22
+ direction: directionSource().current(),
20
23
  };
21
24
  }
22
25
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"conditions.js","sourceRoot":"","sources":["../src/conditions.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAYhD,+DAA+D;AAC/D,SAAS,SAAS;IAChB,OAAO,WAAW,EAAE,EAAE,UAAU,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAWD,MAAM,UAAU,iBAAiB;IAC/B,MAAM,EAAE,MAAM,EAAE,GAAG,YAAY,EAAE,CAAC,OAAO,EAAE,CAAC;IAC5C,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,WAAW,EAAE,iBAAiB,EAAE,CAAC,OAAO,EAAE;QAC1C,8FAA8F;QAC9F,2FAA2F;QAC3F,oEAAoE;QACpE,aAAa,EAAE,KAAK;QACpB,SAAS,EAAE,SAAS,EAAE;KACvB,CA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AAE,CAAC;IACb,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * What the engine evaluates media queries against, kept in step with the device.\n *\n * Not a service, because the engine is not injectable and has no reason to be: it is handed to\n * `mount` and handed back, and this connects the two. An app that wants `@media` to keep working\n * after a rotation or a theme change calls `watchConditions` once and never thinks about it again.\n *\n * A rotation changes no component and no binding, so nothing would be dirty and nothing would\n * re-render. The engine re-resolves and commits on its own when the conditions change.\n */\nimport type { Conditions, TokenValue } from '@ng-native/fabric';\nimport { accessibilitySource } from './accessibility.ts';\nimport { colorSchemeSource } from './color-scheme.ts';\nimport { screenSource } from './screen.ts';\nimport { reactNative } from './react-native.ts';\n\n/** Just enough of the engine to be told. */\ninterface Resolves<Node = unknown> {\n readonly root: Node;\n updateConditions(conditions: Conditions): void;\n addClass(node: Node, name: string): void;\n removeClass(node: Node, name: string): void;\n /** Measure every text again, after the system text size changed. */\n remeasureText?(): void;\n}\n\n/** The system text size, as a multiplier. One off a device. */\nfunction fontScale(): number {\n return reactNative()?.PixelRatio.getFontScale() ?? 1;\n}\n\nexport interface WatchOptions {\n /**\n * Keep a `dark` class on the root in step with the system scheme, which is what\n * `@ng-native/tailwind`'s `dark:` variant matches. On by default; an app with its own theme\n * switch turns it off and puts `dark` on its own root view instead.\n */\n readonly darkClass?: boolean;\n}\n\nexport function currentConditions(): Conditions {\n const { window } = screenSource().current();\n return {\n width: window.width,\n height: window.height,\n colorScheme: colorSchemeSource().current(),\n // Asynchronous on both platforms, so the first paint says no preference and `watchConditions`\n // corrects it. Reduced motion is a preference about what happens next, not about the frame\n // already on screen, so nothing is lost by learning it a tick late.\n reducedMotion: false,\n fontScale: fontScale(),\n };\n}\n\n/**\n * Custom properties the device settles before the first frame, for `mount`'s `tokens` option.\n *\n * Only the hairline so far: the thinnest line the screen can draw, which is a third of a point on\n * a 3x phone and half of one on a 2x. `1px` is what a browser would give and is a visibly fat\n * divider on a modern screen, so a native-looking rule has to ask. React Native works the number\n * out from the pixel ratio; off a device there is no answer, and inventing one would be a line of\n * the wrong weight in every test that draws one.\n *\n * Not watched, unlike the conditions: the pixel density of a screen does not change while an app\n * is open. The safe-area insets are the opposite case and arrive through `updateTokens`.\n */\nexport function deviceTokens(): Record<string, TokenValue> {\n const native = reactNative();\n return native ? { '--hairline': { length: native.StyleSheet.hairlineWidth } } : {};\n}\n\n/**\n * Keep the engine's conditions current. Returns an unsubscribe, though an app that calls this at\n * bootstrap will never use it.\n */\nexport function watchConditions<Node>(\n engine: Resolves<Node>,\n options: WatchOptions = {},\n): () => void {\n const screen = screenSource();\n const colors = colorSchemeSource();\n const accessibility = accessibilitySource();\n\n let conditions = currentConditions();\n const push = (change: Partial<Conditions>) => {\n conditions = { ...conditions, ...change };\n if (options.darkClass !== false) {\n if (conditions.colorScheme === 'dark') engine.addClass(engine.root, 'dark');\n else engine.removeClass(engine.root, 'dark');\n }\n engine.updateConditions(conditions);\n };\n // The class for the scheme the app started in, committed at once. Light needs nothing: an app\n // starting light is exactly what it already rendered.\n if (options.darkClass !== false && conditions.colorScheme === 'dark') push({});\n\n // The system text size. Every text on screen was measured at the old one, and keeps that box\n // until it is measured again, so a change goes into the conditions and then re-measures them\n // all. A change arrives as a `Dimensions` change on both platforms; the app coming back to the\n // foreground is checked as well, and the same change reported by both is re-measured once.\n let scale = conditions.fontScale ?? 1;\n const resize = (change: Partial<Conditions>, next: number) => {\n const rescaled = next !== scale;\n scale = next;\n push({ ...change, fontScale: next });\n if (rescaled) engine.remeasureText?.();\n };\n\n const sizes = screen.subscribe(({ window }) =>\n resize({ width: window.width, height: window.height }, fontScale()),\n );\n const scheme = colors.subscribe((colorScheme) => push({ colorScheme }));\n const settings = accessibility.subscribe((change) => {\n if (change.fontScale !== undefined && change.fontScale !== scale) resize({}, change.fontScale);\n if (change.reduceMotion !== undefined) push({ reducedMotion: change.reduceMotion });\n });\n void accessibility\n .current()\n .then(({ reduceMotion }) => reduceMotion && push({ reducedMotion: true }));\n\n return () => {\n sizes();\n scheme();\n settings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EAAE,CAC5C,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,CAAC,CACpE,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC;IACxE,MAAM,QAAQ,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;QAClD,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,IAAI,MAAM,CAAC,SAAS,KAAK,KAAK;YAAE,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;QAC/F,IAAI,MAAM,CAAC,YAAY,KAAK,SAAS;YAAE,IAAI,CAAC,EAAE,aAAa,EAAE,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;IACtF,CAAC,CAAC,CAAC;IACH,KAAK,aAAa;SACf,OAAO,EAAE;SACT,IAAI,CAAC,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CAAC,YAAY,IAAI,IAAI,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAE7E,OAAO,GAAG,EAAE;QACV,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,QAAQ,EAAE,CAAC;IACb,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * What the engine evaluates media queries against, kept in step with the device.\n *\n * Not a service, because the engine is not injectable and has no reason to be: it is handed to\n * `mount` and handed back, and this connects the two. An app that wants `@media` to keep working\n * after a rotation or a theme change calls `watchConditions` once and never thinks about it again.\n *\n * A rotation changes no component and no binding, so nothing would be dirty and nothing would\n * re-render. The engine re-resolves and commits on its own when the conditions change.\n */\nimport type { Conditions, TokenValue } from '@ng-native/fabric';\nimport { accessibilitySource } from './accessibility.ts';\nimport { colorSchemeSource } from './color-scheme.ts';\nimport { directionSource } from './direction.ts';\nimport { screenSource } from './screen.ts';\nimport { reactNative } from './react-native.ts';\n\n/** Just enough of the engine to be told. */\ninterface Resolves<Node = unknown> {\n readonly root: Node;\n updateConditions(conditions: Conditions): void;\n addClass(node: Node, name: string): void;\n removeClass(node: Node, name: string): void;\n /** Measure every text again, after the system text size changed. */\n remeasureText?(): void;\n}\n\n/** The system text size, as a multiplier. One off a device. */\nfunction fontScale(): number {\n return reactNative()?.PixelRatio.getFontScale() ?? 1;\n}\n\nexport interface WatchOptions {\n /**\n * Keep a `dark` class on the root in step with the system scheme, which is what\n * `@ng-native/tailwind`'s `dark:` variant matches. On by default; an app with its own theme\n * switch turns it off and puts `dark` on its own root view instead.\n */\n readonly darkClass?: boolean;\n}\n\nexport function currentConditions(): Conditions {\n const { window } = screenSource().current();\n return {\n width: window.width,\n height: window.height,\n colorScheme: colorSchemeSource().current(),\n // Asynchronous on both platforms, so the first paint says no preference and `watchConditions`\n // corrects it. Reduced motion is a preference about what happens next, not about the frame\n // already on screen, so nothing is lost by learning it a tick late.\n reducedMotion: false,\n fontScale: fontScale(),\n // Settled while the native side starts up, and fixed until the app restarts.\n direction: directionSource().current(),\n };\n}\n\n/**\n * Custom properties the device settles before the first frame, for `mount`'s `tokens` option.\n *\n * Only the hairline so far: the thinnest line the screen can draw, which is a third of a point on\n * a 3x phone and half of one on a 2x. `1px` is what a browser would give and is a visibly fat\n * divider on a modern screen, so a native-looking rule has to ask. React Native works the number\n * out from the pixel ratio; off a device there is no answer, and inventing one would be a line of\n * the wrong weight in every test that draws one.\n *\n * Not watched, unlike the conditions: the pixel density of a screen does not change while an app\n * is open. The safe-area insets are the opposite case and arrive through `updateTokens`.\n */\nexport function deviceTokens(): Record<string, TokenValue> {\n const native = reactNative();\n return native ? { '--hairline': { length: native.StyleSheet.hairlineWidth } } : {};\n}\n\n/**\n * Keep the engine's conditions current. Returns an unsubscribe, though an app that calls this at\n * bootstrap will never use it.\n */\nexport function watchConditions<Node>(\n engine: Resolves<Node>,\n options: WatchOptions = {},\n): () => void {\n const screen = screenSource();\n const colors = colorSchemeSource();\n const accessibility = accessibilitySource();\n\n let conditions = currentConditions();\n const push = (change: Partial<Conditions>) => {\n conditions = { ...conditions, ...change };\n if (options.darkClass !== false) {\n if (conditions.colorScheme === 'dark') engine.addClass(engine.root, 'dark');\n else engine.removeClass(engine.root, 'dark');\n }\n engine.updateConditions(conditions);\n };\n // The class for the scheme the app started in, committed at once. Light needs nothing: an app\n // starting light is exactly what it already rendered.\n if (options.darkClass !== false && conditions.colorScheme === 'dark') push({});\n\n // The system text size. Every text on screen was measured at the old one, and keeps that box\n // until it is measured again, so a change goes into the conditions and then re-measures them\n // all. A change arrives as a `Dimensions` change on both platforms; the app coming back to the\n // foreground is checked as well, and the same change reported by both is re-measured once.\n let scale = conditions.fontScale ?? 1;\n const resize = (change: Partial<Conditions>, next: number) => {\n const rescaled = next !== scale;\n scale = next;\n push({ ...change, fontScale: next });\n if (rescaled) engine.remeasureText?.();\n };\n\n const sizes = screen.subscribe(({ window }) =>\n resize({ width: window.width, height: window.height }, fontScale()),\n );\n const scheme = colors.subscribe((colorScheme) => push({ colorScheme }));\n const settings = accessibility.subscribe((change) => {\n if (change.fontScale !== undefined && change.fontScale !== scale) resize({}, change.fontScale);\n if (change.reduceMotion !== undefined) push({ reducedMotion: change.reduceMotion });\n });\n void accessibility\n .current()\n .then(({ reduceMotion }) => reduceMotion && push({ reducedMotion: true }));\n\n return () => {\n sizes();\n scheme();\n settings();\n };\n}\n"]}
@@ -9,8 +9,9 @@
9
9
  *
10
10
  * So this is not a nicer `LayoutAnimation` - it is the only way to say the thing at all. What it
11
11
  * adds is the promise, and the scope: `configureNext` applies to the next commit *whenever that
12
- * happens*, so a call that is not immediately followed by a change animates whatever change comes
13
- * next, which may be an unrelated screen appearing.
12
+ * happens* and whatever makes it, a frame of a CSS animation or an unrelated screen appearing as
13
+ * much as the change meant. Here the animation is configured as the change's own commit is handed
14
+ * over, and not at all when the change commits nothing.
14
15
  */
15
16
  import { InjectionToken } from '@angular/core';
16
17
  import * as i0 from "@angular/core";
@@ -40,15 +41,27 @@ export declare class LayoutAnimation {
40
41
  /** Overridden in a test to watch a configuration without one being applied. */
41
42
  static readonly SOURCE: InjectionToken<NativeLayoutAnimation | null>;
42
43
  private readonly native;
44
+ private readonly engine;
45
+ private readonly application;
43
46
  /**
44
- * Animate the layout the next commit produces, and run `change` to cause it.
47
+ * Run `change` and animate the layout its commit produces.
45
48
  *
46
- * The change is taken rather than left to the caller because the two have to be adjacent: a
47
- * `configureNext` with nothing after it animates whatever commit happens next, which may be a
48
- * different screen entirely. Resolves when the animation ends, or immediately where the platform
49
- * does not report that.
49
+ * The change is taken rather than left to the caller because the platform animates whatever
50
+ * commit comes next, and only this can make that the change's own: change detection runs and
51
+ * the change commits before `animate` returns, with the animation configured as that commit is
52
+ * handed over. A frame of another animation cannot land in between and take it, and a change
53
+ * that commits nothing configures nothing, so no later commit is animated in its place. Resolves
54
+ * when the animation ends, once its duration has passed where the platform does not report
55
+ * that, or at once when there was nothing to animate.
50
56
  */
51
57
  animate(change: () => void, options?: LayoutChange): Promise<void>;
58
+ /** The changes whose commit has not come yet: more than one only inside a pass. */
59
+ private readonly waiting;
60
+ /**
61
+ * Run change detection now and say so, or say that a pass is already running and will reach
62
+ * the change.
63
+ */
64
+ private detectChanges;
52
65
  static ɵfac: i0.ɵɵFactoryDeclaration<LayoutAnimation, never>;
53
66
  static ɵprov: i0.ɵɵInjectableDeclaration<any>;
54
67
  }
@@ -9,19 +9,25 @@
9
9
  *
10
10
  * So this is not a nicer `LayoutAnimation` - it is the only way to say the thing at all. What it
11
11
  * adds is the promise, and the scope: `configureNext` applies to the next commit *whenever that
12
- * happens*, so a call that is not immediately followed by a change animates whatever change comes
13
- * next, which may be an unrelated screen appearing.
12
+ * happens* and whatever makes it, a frame of a CSS animation or an unrelated screen appearing as
13
+ * much as the change meant. Here the animation is configured as the change's own commit is handed
14
+ * over, and not at all when the change commits nothing.
14
15
  */
15
- import { InjectionToken, Service, inject } from '@angular/core';
16
+ import { ApplicationRef, InjectionToken, Service, inject } from '@angular/core';
17
+ import { Engine } from '@ng-native/fabric';
16
18
  import { reactNative } from "./react-native.js";
17
19
  import * as i0 from "@angular/core";
18
20
  const DEFAULTS = { duration: 300, easing: 'easeInEaseOut' };
19
21
  /**
20
22
  * How long past its duration an animation is given before `animate` resolves without its
21
- * completion, which Android never calls: a few frames of slack, so that on iOS its own completion,
22
- * which lands at the end of the duration, is the one that resolves it.
23
+ * completion: a few frames of slack, so that the completion is the one that resolves it wherever
24
+ * one comes. React Native calls it at the end of the animation, or from a timer of its own a frame
25
+ * after the duration where native reports nothing, as on Android with layout animations off. It
26
+ * calls nothing at all where animations are disabled.
23
27
  */
24
28
  const COMPLETION_GRACE_MS = 50;
29
+ /** Angular's NG0101, `ApplicationRef.tick()` called while it is running. */
30
+ const RECURSIVE_TICK = 101;
25
31
  /**
26
32
  * `inject(LayoutAnimation).animate(() => this.rows.update(...))`.
27
33
  *
@@ -32,26 +38,84 @@ export class LayoutAnimation {
32
38
  /** Overridden in a test to watch a configuration without one being applied. */
33
39
  static SOURCE = new InjectionToken('angular-native.layoutAnimationSource', { factory: () => reactNative()?.LayoutAnimation ?? null });
34
40
  native = inject(LayoutAnimation.SOURCE);
41
+ engine = inject(Engine, { optional: true });
42
+ application = inject(ApplicationRef, { optional: true });
35
43
  /**
36
- * Animate the layout the next commit produces, and run `change` to cause it.
44
+ * Run `change` and animate the layout its commit produces.
37
45
  *
38
- * The change is taken rather than left to the caller because the two have to be adjacent: a
39
- * `configureNext` with nothing after it animates whatever commit happens next, which may be a
40
- * different screen entirely. Resolves when the animation ends, or immediately where the platform
41
- * does not report that.
46
+ * The change is taken rather than left to the caller because the platform animates whatever
47
+ * commit comes next, and only this can make that the change's own: change detection runs and
48
+ * the change commits before `animate` returns, with the animation configured as that commit is
49
+ * handed over. A frame of another animation cannot land in between and take it, and a change
50
+ * that commits nothing configures nothing, so no later commit is animated in its place. Resolves
51
+ * when the animation ends, once its duration has passed where the platform does not report
52
+ * that, or at once when there was nothing to animate.
42
53
  */
43
54
  async animate(change, options = {}) {
44
- if (!this.native) {
55
+ const native = this.native;
56
+ if (!native) {
45
57
  change();
46
58
  return;
47
59
  }
48
- const done = new Promise((resolve) => {
49
- this.native.configureNext(config(options), resolve);
50
- // Android does not call the completion, so nothing should wait on it forever.
51
- setTimeout(resolve, (options.duration ?? DEFAULTS.duration) + COMPLETION_GRACE_MS);
52
- });
53
- change();
54
- await done;
60
+ const own = { configured: false, finish: () => { } };
61
+ const done = new Promise((resolve) => (own.finish = resolve));
62
+ const configure = () => {
63
+ // Every change still waiting is in this commit: one a pass makes together with this one.
64
+ const together = new Set([...this.waiting, own]);
65
+ const finish = () => together.forEach((change) => change.finish());
66
+ for (const change of together)
67
+ change.configured = true;
68
+ native.configureNext(config(options), finish);
69
+ // React Native calls no completion where animations are disabled, so nothing should wait
70
+ // on it forever.
71
+ setTimeout(finish, (options.duration ?? DEFAULTS.duration) + COMPLETION_GRACE_MS);
72
+ };
73
+ // With no engine there is no commit to wait for: a service built on its own, as in a test.
74
+ if (!this.engine) {
75
+ configure();
76
+ change();
77
+ return done;
78
+ }
79
+ const withdraw = this.engine.beforeNextCommit(configure);
80
+ const settle = () => {
81
+ withdraw();
82
+ this.waiting.delete(own);
83
+ if (!own.configured)
84
+ own.finish();
85
+ };
86
+ this.waiting.add(own);
87
+ try {
88
+ change();
89
+ // Called from inside a pass, the commit is that pass's own, which ends before any microtask.
90
+ if (this.detectChanges())
91
+ settle();
92
+ else
93
+ queueMicrotask(settle);
94
+ }
95
+ catch (error) {
96
+ // Nothing was changed, so nothing is to be animated, not even a commit made in this turn.
97
+ withdraw();
98
+ this.waiting.delete(own);
99
+ throw error;
100
+ }
101
+ return done;
102
+ }
103
+ /** The changes whose commit has not come yet: more than one only inside a pass. */
104
+ waiting = new Set();
105
+ /**
106
+ * Run change detection now and say so, or say that a pass is already running and will reach
107
+ * the change.
108
+ */
109
+ detectChanges() {
110
+ try {
111
+ this.application?.tick();
112
+ return true;
113
+ }
114
+ catch (error) {
115
+ if (error.code !== RECURSIVE_TICK)
116
+ throw error;
117
+ return false;
118
+ }
55
119
  }
56
120
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: LayoutAnimation, deps: [], target: i0.ɵɵFactoryTarget.Service });
57
121
  static ɵprov = i0.ɵɵngDeclareService({ minVersion: "22.0.0", version: "22.2.0", ngImport: i0, type: LayoutAnimation });
@@ -1 +1 @@
1
- {"version":3,"file":"layout-animation.js","sourceRoot":"","sources":["../src/layout-animation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAsBhD,MAAM,QAAQ,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,EAAE,eAA+B,EAAE,CAAC;AAE5E;;;;GAIG;AACH,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAE/B;;;;;GAKG;AAEH,MAAM,OAAO,eAAe;IAC1B,+EAA+E;IAC/E,MAAM,CAAU,MAAM,GAAG,IAAI,cAAc,CACzC,sCAAsC,EACtC,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,eAAe,IAAI,IAAI,EAAE,CAC1D,CAAC;IAEe,MAAM,GAAG,MAAM,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;IAEzD;;;;;;;OAOG;IACH,KAAK,CAAC,OAAO,CAAC,MAAkB,EAAE,UAAwB,EAAE;QAC1D,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,EAAE,CAAC;YACT,OAAO;QACT,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,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esContent":["/**\n * Animating a layout *change*, which CSS cannot express.\n *\n * A transition animates a property from one value to another, and the engine already does that. It\n * cannot animate a layout: when a row is removed and the rows below move up, nothing about those\n * rows changed - their `top` was never set, Yoga computed it, and there is no old value to\n * transition from. The web solves this with FLIP, measuring before and after in JavaScript; native\n * solves it in the shadow tree, which is where the two layouts both exist.\n *\n * So this is not a nicer `LayoutAnimation` - it is the only way to say the thing at all. What it\n * adds is the promise, and the scope: `configureNext` applies to the next commit *whenever that\n * happens*, so a call that is not immediately followed by a change animates whatever change comes\n * next, which may be an unrelated screen appearing.\n */\n\nimport { InjectionToken, Service, inject } from '@angular/core';\nimport { reactNative } from './react-native.ts';\n\n/**\n * How a change is eased. `spring` is the platform's own, and is what a native list uses.\n * `keyboard` is the curve iOS moves its keyboard on, which a keyboard event reports by that name.\n */\nexport type LayoutEasing =\n 'spring' | 'linear' | 'easeInEaseOut' | 'easeIn' | 'easeOut' | 'keyboard';\n\nexport interface LayoutChange {\n readonly duration?: number;\n readonly easing?: LayoutEasing;\n /** What a view appearing does. `opacity` fades it in; the default is to scale it up. */\n readonly appear?: 'opacity' | 'scaleXY' | 'none';\n /** What a view leaving does. */\n readonly leave?: 'opacity' | 'scaleXY' | 'none';\n}\n\nexport interface NativeLayoutAnimation {\n configureNext(config: object, onDone?: () => void): void;\n}\n\nconst DEFAULTS = { duration: 300, easing: 'easeInEaseOut' as LayoutEasing };\n\n/**\n * How long past its duration an animation is given before `animate` resolves without its\n * completion, which Android never calls: a few frames of slack, so that on iOS its own completion,\n * which lands at the end of the duration, is the one that resolves it.\n */\nconst COMPLETION_GRACE_MS = 50;\n\n/**\n * `inject(LayoutAnimation).animate(() => this.rows.update(...))`.\n *\n * The only way to say \"animate the layout this change produces\": a transition needs a value to\n * animate from, and a row that moves up because the one above it left never had one.\n */\n@Service()\nexport class LayoutAnimation {\n /** Overridden in a test to watch a configuration without one being applied. */\n static readonly SOURCE = new InjectionToken<NativeLayoutAnimation | null>(\n 'angular-native.layoutAnimationSource',\n { factory: () => reactNative()?.LayoutAnimation ?? null },\n );\n\n private readonly native = inject(LayoutAnimation.SOURCE);\n\n /**\n * Animate the layout the next commit produces, and run `change` to cause it.\n *\n * The change is taken rather than left to the caller because the two have to be adjacent: a\n * `configureNext` with nothing after it animates whatever commit happens next, which may be a\n * different screen entirely. Resolves when the animation ends, or immediately where the platform\n * does not report that.\n */\n async animate(change: () => void, options: LayoutChange = {}): Promise<void> {\n if (!this.native) {\n change();\n return;\n }\n\n const done = new Promise<void>((resolve) => {\n this.native!.configureNext(config(options), resolve);\n // Android does not call the completion, so nothing should wait on it forever.\n setTimeout(resolve, (options.duration ?? DEFAULTS.duration) + COMPLETION_GRACE_MS);\n });\n\n change();\n await done;\n }\n}\n\n/**\n * The config React Native takes, from the three things worth naming.\n *\n * `create` and `delete` need a `property` as well as a type, because a view appearing has no\n * previous size to animate from - it has to be told what to animate *of*. Leaving that out is the\n * most common way one of these does nothing.\n */\nfunction config(options: LayoutChange): object {\n const duration = options.duration ?? DEFAULTS.duration;\n const easing = options.easing ?? DEFAULTS.easing;\n const appear = options.appear ?? 'opacity';\n const leave = options.leave ?? 'opacity';\n\n return {\n duration,\n update: { type: easing, ...(easing === 'spring' ? { springDamping: 0.7 } : {}) },\n ...(appear === 'none' ? {} : { create: { type: easing, property: appear } }),\n ...(leave === 'none' ? {} : { delete: { type: easing, property: leave } }),\n };\n}\n"]}
1
+ {"version":3,"file":"layout-animation.js","sourceRoot":"","sources":["../src/layout-animation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAChF,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAsBhD,MAAM,QAAQ,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,EAAE,eA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E,CAAC;KAC3E,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Animating a layout *change*, which CSS cannot express.\n *\n * A transition animates a property from one value to another, and the engine already does that. It\n * cannot animate a layout: when a row is removed and the rows below move up, nothing about those\n * rows changed - their `top` was never set, Yoga computed it, and there is no old value to\n * transition from. The web solves this with FLIP, measuring before and after in JavaScript; native\n * solves it in the shadow tree, which is where the two layouts both exist.\n *\n * So this is not a nicer `LayoutAnimation` - it is the only way to say the thing at all. What it\n * adds is the promise, and the scope: `configureNext` applies to the next commit *whenever that\n * happens* and whatever makes it, a frame of a CSS animation or an unrelated screen appearing as\n * much as the change meant. Here the animation is configured as the change's own commit is handed\n * over, and not at all when the change commits nothing.\n */\n\nimport { ApplicationRef, InjectionToken, Service, inject } from '@angular/core';\nimport { Engine } from '@ng-native/fabric';\nimport { reactNative } from './react-native.ts';\n\n/**\n * How a change is eased. `spring` is the platform's own, and is what a native list uses.\n * `keyboard` is the curve iOS moves its keyboard on, which a keyboard event reports by that name.\n */\nexport type LayoutEasing =\n 'spring' | 'linear' | 'easeInEaseOut' | 'easeIn' | 'easeOut' | 'keyboard';\n\nexport interface LayoutChange {\n readonly duration?: number;\n readonly easing?: LayoutEasing;\n /** What a view appearing does. `opacity` fades it in; the default is to scale it up. */\n readonly appear?: 'opacity' | 'scaleXY' | 'none';\n /** What a view leaving does. */\n readonly leave?: 'opacity' | 'scaleXY' | 'none';\n}\n\nexport interface NativeLayoutAnimation {\n configureNext(config: object, onDone?: () => void): void;\n}\n\nconst DEFAULTS = { duration: 300, easing: 'easeInEaseOut' as LayoutEasing };\n\n/**\n * How long past its duration an animation is given before `animate` resolves without its\n * completion: a few frames of slack, so that the completion is the one that resolves it wherever\n * one comes. React Native calls it at the end of the animation, or from a timer of its own a frame\n * after the duration where native reports nothing, as on Android with layout animations off. It\n * calls nothing at all where animations are disabled.\n */\nconst COMPLETION_GRACE_MS = 50;\n\n/** Angular's NG0101, `ApplicationRef.tick()` called while it is running. */\nconst RECURSIVE_TICK = 101;\n\n/**\n * `inject(LayoutAnimation).animate(() => this.rows.update(...))`.\n *\n * The only way to say \"animate the layout this change produces\": a transition needs a value to\n * animate from, and a row that moves up because the one above it left never had one.\n */\n@Service()\nexport class LayoutAnimation {\n /** Overridden in a test to watch a configuration without one being applied. */\n static readonly SOURCE = new InjectionToken<NativeLayoutAnimation | null>(\n 'angular-native.layoutAnimationSource',\n { factory: () => reactNative()?.LayoutAnimation ?? null },\n );\n\n private readonly native = inject(LayoutAnimation.SOURCE);\n private readonly engine = inject(Engine, { optional: true });\n private readonly application = inject(ApplicationRef, { optional: true });\n\n /**\n * Run `change` and animate the layout its commit produces.\n *\n * The change is taken rather than left to the caller because the platform animates whatever\n * commit comes next, and only this can make that the change's own: change detection runs and\n * the change commits before `animate` returns, with the animation configured as that commit is\n * handed over. A frame of another animation cannot land in between and take it, and a change\n * that commits nothing configures nothing, so no later commit is animated in its place. Resolves\n * when the animation ends, once its duration has passed where the platform does not report\n * that, or at once when there was nothing to animate.\n */\n async animate(change: () => void, options: LayoutChange = {}): Promise<void> {\n const native = this.native;\n if (!native) {\n change();\n return;\n }\n\n const own: Waiting = { configured: false, finish: () => {} };\n const done = new Promise<void>((resolve) => (own.finish = resolve));\n const configure = (): void => {\n // Every change still waiting is in this commit: one a pass makes together with this one.\n const together = new Set([...this.waiting, own]);\n const finish = (): void => together.forEach((change) => change.finish());\n for (const change of together) change.configured = true;\n native.configureNext(config(options), finish);\n // React Native calls no completion where animations are disabled, so nothing should wait\n // on it forever.\n setTimeout(finish, (options.duration ?? DEFAULTS.duration) + COMPLETION_GRACE_MS);\n };\n\n // With no engine there is no commit to wait for: a service built on its own, as in a test.\n if (!this.engine) {\n configure();\n change();\n return done;\n }\n\n const withdraw = this.engine.beforeNextCommit(configure);\n const settle = (): void => {\n withdraw();\n this.waiting.delete(own);\n if (!own.configured) own.finish();\n };\n this.waiting.add(own);\n try {\n change();\n // Called from inside a pass, the commit is that pass's own, which ends before any microtask.\n if (this.detectChanges()) settle();\n else queueMicrotask(settle);\n } catch (error) {\n // Nothing was changed, so nothing is to be animated, not even a commit made in this turn.\n withdraw();\n this.waiting.delete(own);\n throw error;\n }\n return done;\n }\n\n /** The changes whose commit has not come yet: more than one only inside a pass. */\n private readonly waiting = new Set<Waiting>();\n\n /**\n * Run change detection now and say so, or say that a pass is already running and will reach\n * the change.\n */\n private detectChanges(): boolean {\n try {\n this.application?.tick();\n return true;\n } catch (error) {\n if ((error as { code?: number }).code !== RECURSIVE_TICK) throw error;\n return false;\n }\n }\n}\n\n/** One `animate()` call: whether its commit was configured, and what resolves it. */\ninterface Waiting {\n configured: boolean;\n finish: () => void;\n}\n\n/**\n * The config React Native takes, from the three things worth naming.\n *\n * `create` and `delete` need a `property` as well as a type, because a view appearing has no\n * previous size to animate from - it has to be told what to animate *of*. Leaving that out is the\n * most common way one of these does nothing.\n */\nfunction config(options: LayoutChange): object {\n const duration = options.duration ?? DEFAULTS.duration;\n const easing = options.easing ?? DEFAULTS.easing;\n const appear = options.appear ?? 'opacity';\n const leave = options.leave ?? 'opacity';\n\n return {\n duration,\n update: { type: easing, ...(easing === 'spring' ? { springDamping: 0.7 } : {}) },\n ...(appear === 'none' ? {} : { create: { type: easing, property: appear } }),\n ...(leave === 'none' ? {} : { delete: { type: easing, property: leave } }),\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ng-native/device",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Angular Native device services: keyboard, screen, color scheme, app state, accessibility, hardware back and deep links.",
5
5
  "keywords": [
6
6
  "angular",
@@ -17,7 +17,7 @@
17
17
  "type": "module",
18
18
  "main": "dist/index.js",
19
19
  "dependencies": {
20
- "@ng-native/fabric": "0.4.0"
20
+ "@ng-native/fabric": "0.6.0"
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@angular/core": "^22.0.0",