ember-nativescript 0.1.2 → 0.3.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.
Files changed (96) hide show
  1. package/README.md +16 -3
  2. package/dist/components/Platform.d.ts +7 -0
  3. package/dist/components/Platform.d.ts.map +1 -1
  4. package/dist/components/Platform.js +9 -2
  5. package/dist/components/Platform.js.map +1 -1
  6. package/dist/components/RouteError.d.ts +8 -0
  7. package/dist/components/RouteError.d.ts.map +1 -0
  8. package/dist/components/RouteError.js +13 -0
  9. package/dist/components/RouteError.js.map +1 -0
  10. package/dist/src/adapter.d.ts +3 -2
  11. package/dist/src/adapter.d.ts.map +1 -1
  12. package/dist/src/application-entry.d.ts +4 -0
  13. package/dist/src/application-entry.d.ts.map +1 -0
  14. package/dist/src/application-entry.js +4 -0
  15. package/dist/src/application-testing.d.ts +19 -0
  16. package/dist/src/application-testing.d.ts.map +1 -0
  17. package/dist/src/application-testing.js +32 -0
  18. package/dist/src/application-testing.js.map +1 -0
  19. package/dist/src/application.d.ts +45 -0
  20. package/dist/src/application.d.ts.map +1 -0
  21. package/dist/src/application.js +136 -0
  22. package/dist/src/application.js.map +1 -0
  23. package/dist/src/dom.js +1 -1
  24. package/dist/src/dom.js.map +1 -1
  25. package/dist/src/index.d.ts +2 -2
  26. package/dist/src/index.d.ts.map +1 -1
  27. package/dist/src/index.js +3 -3
  28. package/dist/src/nativescript-application.d.ts +8 -0
  29. package/dist/src/nativescript-application.d.ts.map +1 -0
  30. package/dist/src/nativescript-application.js +23 -0
  31. package/dist/src/nativescript-application.js.map +1 -0
  32. package/dist/src/navigator.d.ts +6 -0
  33. package/dist/src/navigator.d.ts.map +1 -1
  34. package/dist/src/navigator.js +6 -1
  35. package/dist/src/navigator.js.map +1 -1
  36. package/dist/src/platform.d.ts +4 -2
  37. package/dist/src/platform.d.ts.map +1 -1
  38. package/dist/src/platform.js +2 -1
  39. package/dist/src/platform.js.map +1 -1
  40. package/dist/src/render.d.ts.map +1 -1
  41. package/dist/src/render.js.map +1 -1
  42. package/dist/src/testing.d.ts +2 -0
  43. package/dist/src/testing.d.ts.map +1 -1
  44. package/dist/src/testing.js +7 -2
  45. package/dist/src/testing.js.map +1 -1
  46. package/dist/src/vite-web.d.ts +5 -0
  47. package/dist/src/vite-web.d.ts.map +1 -0
  48. package/dist/src/vite-web.js +41 -0
  49. package/dist/src/vite-web.js.map +1 -0
  50. package/dist/src/vite.d.ts.map +1 -1
  51. package/dist/src/vite.js +4 -1
  52. package/dist/src/vite.js.map +1 -1
  53. package/dist/src/vitest.d.ts.map +1 -1
  54. package/dist/src/vitest.js +1 -0
  55. package/dist/src/vitest.js.map +1 -1
  56. package/dist/src/web-adapter.d.ts +31 -0
  57. package/dist/src/web-adapter.d.ts.map +1 -0
  58. package/dist/src/web-adapter.js +664 -0
  59. package/dist/src/web-adapter.js.map +1 -0
  60. package/dist/src/web-app.d.ts +29 -0
  61. package/dist/src/web-app.d.ts.map +1 -0
  62. package/dist/src/web-app.js +61 -0
  63. package/dist/src/web-app.js.map +1 -0
  64. package/dist/src/web-application.d.ts +10 -0
  65. package/dist/src/web-application.d.ts.map +1 -0
  66. package/dist/src/web-application.js +37 -0
  67. package/dist/src/web-application.js.map +1 -0
  68. package/dist/src/web-core.d.ts +56 -0
  69. package/dist/src/web-core.d.ts.map +1 -0
  70. package/dist/src/web-core.js +84 -0
  71. package/dist/src/web-core.js.map +1 -0
  72. package/dist/src/web-css.d.ts +7 -0
  73. package/dist/src/web-css.d.ts.map +1 -0
  74. package/dist/src/web-css.js +118 -0
  75. package/dist/src/web-css.js.map +1 -0
  76. package/dist/src/web-host.d.ts +25 -0
  77. package/dist/src/web-host.d.ts.map +1 -0
  78. package/dist/src/web-host.js +172 -0
  79. package/dist/src/web-host.js.map +1 -0
  80. package/dist/src/web-list.d.ts +18 -0
  81. package/dist/src/web-list.d.ts.map +1 -0
  82. package/dist/src/web-list.js +224 -0
  83. package/dist/src/web-list.js.map +1 -0
  84. package/dist/src/web-router.d.ts +51 -0
  85. package/dist/src/web-router.d.ts.map +1 -0
  86. package/dist/src/web-router.js +83 -0
  87. package/dist/src/web-router.js.map +1 -0
  88. package/dist/src/web-styles.d.ts +4 -0
  89. package/dist/src/web-styles.d.ts.map +1 -0
  90. package/dist/src/web-styles.js +160 -0
  91. package/dist/src/web-styles.js.map +1 -0
  92. package/dist/src/web.d.ts +7 -0
  93. package/dist/src/web.d.ts.map +1 -0
  94. package/dist/src/web.js +7 -0
  95. package/dist/types/glint.d.ts +6 -1
  96. package/package.json +35 -16
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-host.d.ts","sourceRoot":"","sources":["../../src/web-host.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE/E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,6GAA6G;AAC7G,MAAM,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,EAAE,SAAS,GAAG,UAAU,GAAG,MAAM,CAAC,GAAG;IAC1E,qGAAqG;IACrG,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC;CAChE,CAAC;AAEF,KAAK,IAAI,GAAG,WAAW,CAAC;AA0BxB,6GAA6G;AAC7G,qBAAa,YAAa,YAAW,SAAS,CAAC,IAAI,CAAC;;IAUhD,QAAQ,CAAC,KAAK,EAAE,IAAI;IACpB,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU;gBADnB,KAAK,EAAE,IAAI,EACX,MAAM,CAAC,EAAE,UAAU,YAAA;IAK9B,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,GAAG,IAAI;IA+B5C,IAAI,IAAI,IAAI;IA4BZ,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI;IAuBtD,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IA6E7C,6CAA6C;IAC7C,OAAO,IAAI,IAAI;CAGhB"}
@@ -0,0 +1,172 @@
1
+ import { emit, emitLoaded } from "./web-adapter.js";
2
+ // src/web-host.ts
3
+ var DURATION = 280;
4
+ var EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";
5
+ /** Moves between screens in a browser. With a router, it keeps the URL and the browser's history in step. */
6
+ var WebFrameHost = class {
7
+ frame;
8
+ router;
9
+ #stack = [];
10
+ #modals = [];
11
+ #app = Math.random().toString(36).slice(2);
12
+ #ignorePops = 0;
13
+ #restoring = false;
14
+ constructor(frame, router) {
15
+ this.frame = frame;
16
+ this.router = router;
17
+ if (router) addEventListener("popstate", this.#onPopState);
18
+ }
19
+ show(page, options) {
20
+ const previous = this.#stack.at(-1);
21
+ const dropped = options.clearHistory ? this.#stack.splice(0) : previous && !previous.backstackVisible ? [this.#stack.pop()] : [];
22
+ this.#stack.push({
23
+ page,
24
+ backstackVisible: options.backstackVisible
25
+ });
26
+ if (this.router) this.#record(options);
27
+ page.classList.add("ns-current");
28
+ this.frame.append(page);
29
+ emitLoaded(page);
30
+ if (previous) emit(previous.page, "navigatingFrom", { isBackNavigation: false });
31
+ emit(page, "navigatingTo", { isBackNavigation: false });
32
+ const finish = () => {
33
+ if (previous) {
34
+ previous.page.classList.remove("ns-current");
35
+ previous.page.inert = true;
36
+ emit(previous.page, "navigatedFrom", { isBackNavigation: false });
37
+ }
38
+ for (const entry of dropped) entry.page.remove();
39
+ emit(page, "navigatedTo", { isBackNavigation: false });
40
+ };
41
+ if (!options.animated || !previous || prefersLessMotion()) return finish();
42
+ slide(page, ["100%", "0%"], previous.page, ["0%", "-30%"]).then(finish);
43
+ }
44
+ back() {
45
+ if (this.#stack.length < 2) return;
46
+ if (this.router && history.state?.app === this.#app) history.back();
47
+ else this.#pop(true);
48
+ }
49
+ #pop(animated) {
50
+ const leaving = this.#stack.pop();
51
+ const showing = this.#stack.at(-1);
52
+ if (!leaving || !showing) return;
53
+ showing.page.inert = false;
54
+ showing.page.classList.add("ns-current");
55
+ if (showing.title) document.title = showing.title;
56
+ emit(leaving.page, "navigatingFrom", { isBackNavigation: true });
57
+ emit(showing.page, "navigatingTo", { isBackNavigation: true });
58
+ const finish = () => {
59
+ leaving.page.remove();
60
+ emit(leaving.page, "navigatedFrom", { isBackNavigation: true });
61
+ emit(showing.page, "navigatedTo", { isBackNavigation: true });
62
+ };
63
+ if (!animated || prefersLessMotion()) return finish();
64
+ slide(leaving.page, ["0%", "100%"], showing.page, ["-30%", "0%"]).then(finish);
65
+ }
66
+ showModal(view, options) {
67
+ const backdrop = document.createElement("div");
68
+ backdrop.className = "ns-modal-backdrop";
69
+ view.classList.add(options.fullscreen ? "ns-modal-fullscreen" : "ns-modal");
70
+ backdrop.append(view);
71
+ backdrop.addEventListener("click", (click) => {
72
+ if (click.target === backdrop) this.#dismiss(view, void 0, true);
73
+ });
74
+ (this.frame.closest(".ns-app") ?? document.body).append(backdrop);
75
+ this.#modals.push({
76
+ view,
77
+ backdrop,
78
+ onClose: options.onClose
79
+ });
80
+ if (this.router) history.pushState(this.#state(this.#stack.length, true), "", location.href);
81
+ emitLoaded(view);
82
+ if (options.animated && !prefersLessMotion()) {
83
+ view.animate([{ transform: "translateY(100%)" }, { transform: "translateY(0)" }], {
84
+ duration: DURATION,
85
+ easing: EASE
86
+ });
87
+ backdrop.animate([{ opacity: 0 }, { opacity: 1 }], { duration: DURATION });
88
+ }
89
+ }
90
+ closeModal(view, result) {
91
+ this.#dismiss(view, result, true);
92
+ }
93
+ #dismiss(view, result, fromApp) {
94
+ const index = this.#modals.findIndex((modal) => modal.view === view);
95
+ if (index === -1) return;
96
+ const [modal] = this.#modals.splice(index, 1);
97
+ if (fromApp && this.router && history.state?.modal && history.state.app === this.#app) {
98
+ this.#ignorePops++;
99
+ history.back();
100
+ }
101
+ const done = () => modal.backdrop.remove();
102
+ if (prefersLessMotion()) done();
103
+ else Promise.all([modal.view.animate([{ transform: "translateY(0)" }, { transform: "translateY(100%)" }], {
104
+ duration: DURATION,
105
+ easing: EASE
106
+ }).finished, modal.backdrop.animate([{ opacity: 1 }, { opacity: 0 }], { duration: DURATION }).finished]).then(done, done);
107
+ modal.onClose(result);
108
+ }
109
+ #onPopState = (event) => {
110
+ if (this.#ignorePops > 0) {
111
+ this.#ignorePops--;
112
+ return;
113
+ }
114
+ const state = event.state;
115
+ const top = this.#modals.at(-1);
116
+ if (top) return this.#dismiss(top.view, void 0, false);
117
+ if (!state || state.app !== this.#app) {
118
+ this.router?.open(location.pathname, { replace: true });
119
+ return;
120
+ }
121
+ if (state.depth < this.#stack.length) while (this.#stack.length > Math.max(state.depth, 1)) this.#pop(this.#stack.length === state.depth + 1);
122
+ else if (state.depth > this.#stack.length) {
123
+ this.#restoring = true;
124
+ const done = () => {
125
+ this.#restoring = false;
126
+ };
127
+ let opening;
128
+ try {
129
+ opening = this.router?.open(location.pathname, { replace: false });
130
+ } finally {
131
+ if (isThenable(opening)) opening.then(done, done);
132
+ else done();
133
+ }
134
+ }
135
+ };
136
+ #record(options) {
137
+ const path = this.router.pathFor(options.screen) ?? location.pathname;
138
+ const state = this.#state(this.#stack.length);
139
+ const replace = this.#restoring || this.#stack.length === 1 || options.clearHistory;
140
+ if (options.clearHistory) this.#app = state.app = Math.random().toString(36).slice(2);
141
+ if (replace) history.replaceState(state, "", this.router.href(path));
142
+ else history.pushState(state, "", this.router.href(path));
143
+ const title = this.router.titleFor(options.screen);
144
+ if (title) document.title = this.#stack.at(-1).title = title;
145
+ }
146
+ #state(depth, modal = false) {
147
+ return {
148
+ app: this.#app,
149
+ depth,
150
+ ...modal ? { modal } : {}
151
+ };
152
+ }
153
+ /** Stops following the browser's history. */
154
+ destroy() {
155
+ removeEventListener("popstate", this.#onPopState);
156
+ }
157
+ };
158
+ var isThenable = (value) => value !== null && typeof value === "object" && typeof value.then === "function";
159
+ function prefersLessMotion() {
160
+ return matchMedia("(prefers-reduced-motion: reduce)").matches;
161
+ }
162
+ function slide(moving, movingX, under, underX) {
163
+ const timing = {
164
+ duration: DURATION,
165
+ easing: EASE
166
+ };
167
+ const frames = ([from, to]) => [{ transform: `translateX(${from})` }, { transform: `translateX(${to})` }];
168
+ return Promise.all([moving.animate(frames(movingX), timing).finished, under.animate(frames(underX), timing).finished]).catch(() => void 0);
169
+ }
170
+ export { WebFrameHost };
171
+
172
+ //# sourceMappingURL=web-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-host.js","names":[],"sources":["../../src/web-host.ts"],"sourcesContent":["// Shows screens in a browser the way NativeScript's Frame does on a phone: a stack of pages, the new one sliding in\n// over the last, back sliding it out; modals as a sheet over the page. The root frame also keeps the browser's history\n// in step: each screen is a history entry, so the browser's back button is a back, and a screen with a route has its\n// own URL (see web-router.ts). Frames inside a screen (a tab's) keep their stack to themselves.\n\nimport type { FrameHost, ModalHostOptions, ShowOptions } from './navigator.ts';\nimport { emit, emitLoaded } from './web-adapter.ts';\nimport type { WebRouter } from './web-router.ts';\n\n/** What the host asks of a router: a WebRouter's routes table, or Ember's router in the full Application. */\nexport type ScreenUrls = Pick<WebRouter, 'pathFor' | 'titleFor' | 'href'> & {\n /** Shows the screen a URL names. May finish later, as Ember's router does: the host waits for it. */\n open(pathname: string, options: { replace: boolean }): unknown;\n};\n\ntype View = HTMLElement;\n\ninterface Entry {\n page: View;\n backstackVisible: boolean;\n /** The document's title on this screen, put back when a back shows it again. */\n title?: string;\n}\n\ninterface Modal {\n view: View;\n backdrop: HTMLElement;\n onClose: (result?: unknown) => void;\n}\n\ninterface HistoryState {\n /** Which app's entries these are: entries from before a reload or a clearHistory aren't ours. */\n app: string;\n /** How many screens deep this entry is, from 1. */\n depth: number;\n modal?: boolean;\n}\n\nconst DURATION = 280;\nconst EASE = 'cubic-bezier(0.2, 0.8, 0.2, 1)';\n\n/** Moves between screens in a browser. With a router, it keeps the URL and the browser's history in step. */\nexport class WebFrameHost implements FrameHost<View> {\n readonly #stack: Entry[] = [];\n readonly #modals: Modal[] = [];\n #app = Math.random().toString(36).slice(2);\n // A back the host started itself through history.back(): its popstate is already handled.\n #ignorePops = 0;\n // Set while the browser's forward button re-opens a screen: the history entry is already there.\n #restoring = false;\n\n constructor(\n readonly frame: View,\n readonly router?: ScreenUrls,\n ) {\n if (router) addEventListener('popstate', this.#onPopState);\n }\n\n show(page: View, options: ShowOptions): void {\n const previous = this.#stack.at(-1);\n const dropped = options.clearHistory\n ? this.#stack.splice(0)\n : previous && !previous.backstackVisible\n ? [this.#stack.pop()!]\n : [];\n this.#stack.push({ page, backstackVisible: options.backstackVisible });\n\n if (this.router) this.#record(options);\n\n page.classList.add('ns-current');\n this.frame.append(page);\n emitLoaded(page);\n if (previous) emit(previous.page, 'navigatingFrom', { isBackNavigation: false });\n emit(page, 'navigatingTo', { isBackNavigation: false });\n\n const finish = (): void => {\n if (previous) {\n previous.page.classList.remove('ns-current');\n previous.page.inert = true;\n emit(previous.page, 'navigatedFrom', { isBackNavigation: false });\n }\n for (const entry of dropped) entry.page.remove();\n emit(page, 'navigatedTo', { isBackNavigation: false });\n };\n\n if (!options.animated || !previous || prefersLessMotion()) return finish();\n slide(page, ['100%', '0%'], previous.page, ['0%', '-30%']).then(finish);\n }\n\n back(): void {\n if (this.#stack.length < 2) return;\n // With history, the browser goes back and the popstate does the rest, as when the user presses back.\n if (this.router && history.state?.app === this.#app) history.back();\n else this.#pop(true);\n }\n\n // The top page leaves: it's destroyed by the navigator on navigatedFrom with isBackNavigation.\n #pop(animated: boolean): void {\n const leaving = this.#stack.pop();\n const showing = this.#stack.at(-1);\n if (!leaving || !showing) return;\n\n showing.page.inert = false;\n showing.page.classList.add('ns-current');\n if (showing.title) document.title = showing.title;\n emit(leaving.page, 'navigatingFrom', { isBackNavigation: true });\n emit(showing.page, 'navigatingTo', { isBackNavigation: true });\n\n const finish = (): void => {\n leaving.page.remove();\n emit(leaving.page, 'navigatedFrom', { isBackNavigation: true });\n emit(showing.page, 'navigatedTo', { isBackNavigation: true });\n };\n if (!animated || prefersLessMotion()) return finish();\n slide(leaving.page, ['0%', '100%'], showing.page, ['-30%', '0%']).then(finish);\n }\n\n showModal(view: View, options: ModalHostOptions): void {\n const backdrop = document.createElement('div');\n backdrop.className = 'ns-modal-backdrop';\n view.classList.add(options.fullscreen ? 'ns-modal-fullscreen' : 'ns-modal');\n backdrop.append(view);\n // A tap outside the sheet dismisses it, as a swipe down does on iOS.\n backdrop.addEventListener('click', (click) => {\n if (click.target === backdrop) this.#dismiss(view, undefined, true);\n });\n (this.frame.closest('.ns-app') ?? document.body).append(backdrop);\n this.#modals.push({ view, backdrop, onClose: options.onClose });\n\n if (this.router) history.pushState(this.#state(this.#stack.length, true), '', location.href);\n emitLoaded(view);\n if (options.animated && !prefersLessMotion()) {\n view.animate([{ transform: 'translateY(100%)' }, { transform: 'translateY(0)' }], {\n duration: DURATION,\n easing: EASE,\n });\n backdrop.animate([{ opacity: 0 }, { opacity: 1 }], { duration: DURATION });\n }\n }\n\n closeModal(view: View, result: unknown): void {\n this.#dismiss(view, result, true);\n }\n\n // Closes a modal. `fromApp` when the app or a tap closed it: then its history entry goes too.\n #dismiss(view: View, result: unknown, fromApp: boolean): void {\n const index = this.#modals.findIndex((modal) => modal.view === view);\n if (index === -1) return;\n const [modal] = this.#modals.splice(index, 1);\n if (fromApp && this.router && history.state?.modal && history.state.app === this.#app) {\n this.#ignorePops++;\n history.back();\n }\n const done = (): void => modal!.backdrop.remove();\n if (prefersLessMotion()) done();\n else\n Promise.all([\n modal!.view.animate([{ transform: 'translateY(0)' }, { transform: 'translateY(100%)' }], {\n duration: DURATION,\n easing: EASE,\n }).finished,\n modal!.backdrop.animate([{ opacity: 1 }, { opacity: 0 }], { duration: DURATION }).finished,\n ]).then(done, done);\n modal!.onClose(result);\n }\n\n // The browser's back or forward button.\n #onPopState = (event: PopStateEvent): void => {\n if (this.#ignorePops > 0) {\n this.#ignorePops--;\n return;\n }\n const state = event.state as HistoryState | null;\n const top = this.#modals.at(-1);\n if (top) return this.#dismiss(top.view, undefined, false);\n\n if (!state || state.app !== this.#app) {\n // An entry from before a reload or a clearHistory: there's no screen for it, so show what the URL says.\n this.router?.open(location.pathname, { replace: true });\n return;\n }\n if (state.depth < this.#stack.length) {\n while (this.#stack.length > Math.max(state.depth, 1)) this.#pop(this.#stack.length === state.depth + 1);\n } else if (state.depth > this.#stack.length) {\n // Forward: open the screen the URL names again. Its history entry is already there, so the screen replaces it,\n // whenever it arrives.\n this.#restoring = true;\n const done = (): void => {\n this.#restoring = false;\n };\n let opening: unknown;\n try {\n opening = this.router?.open(location.pathname, { replace: false });\n } finally {\n if (isThenable(opening)) opening.then(done, done);\n else done();\n }\n }\n };\n\n // The history entry for a screen just shown: pushed, or replacing the current one for the first screen, after\n // clearHistory, and when the browser already moved (forward).\n #record(options: ShowOptions): void {\n const path = this.router!.pathFor(options.screen) ?? location.pathname;\n const state = this.#state(this.#stack.length);\n const replace = this.#restoring || this.#stack.length === 1 || options.clearHistory;\n if (options.clearHistory) this.#app = state.app = Math.random().toString(36).slice(2);\n if (replace) history.replaceState(state, '', this.router!.href(path));\n else history.pushState(state, '', this.router!.href(path));\n const title = this.router!.titleFor(options.screen);\n if (title) document.title = this.#stack.at(-1)!.title = title;\n }\n\n #state(depth: number, modal = false): HistoryState {\n return { app: this.#app, depth, ...(modal ? { modal } : {}) };\n }\n\n /** Stops following the browser's history. */\n destroy(): void {\n removeEventListener('popstate', this.#onPopState);\n }\n}\n\nconst isThenable = (value: unknown): value is PromiseLike<unknown> =>\n value !== null && typeof value === 'object' && typeof (value as PromiseLike<unknown>).then === 'function';\n\nfunction prefersLessMotion(): boolean {\n return matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n// The incoming page slides over the outgoing one, which moves a little the other way, as UINavigationController does.\nfunction slide(moving: View, movingX: [string, string], under: View, underX: [string, string]): Promise<unknown> {\n const timing = { duration: DURATION, easing: EASE };\n const frames = ([from, to]: [string, string]) => [\n { transform: `translateX(${from})` },\n { transform: `translateX(${to})` },\n ];\n return Promise.all([\n moving.animate(frames(movingX), timing).finished,\n under.animate(frames(underX), timing).finished,\n ]).catch(() => undefined);\n}\n"],"mappings":";;AAsCA,IAAM,WAAW;AACjB,IAAM,OAAO;;AAGb,IAAa,eAAb,MAAqD;CAUxC;CACA;CAVF,SAAkB,CAAC;CACnB,UAAmB,CAAC;CAC7B,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CAEzC,cAAc;CAEd,aAAa;CAEb,YACW,OACA,QACT;EAFS,KAAA,QAAA;EACA,KAAA,SAAA;EAET,IAAI,QAAQ,iBAAiB,YAAY,KAAK,WAAW;CAC3D;CAEA,KAAK,MAAY,SAA4B;EAC3C,MAAM,WAAW,KAAK,OAAO,GAAG,EAAE;EAClC,MAAM,UAAU,QAAQ,eACpB,KAAK,OAAO,OAAO,CAAC,IACpB,YAAY,CAAC,SAAS,mBACpB,CAAC,KAAK,OAAO,IAAI,CAAE,IACnB,CAAC;EACP,KAAK,OAAO,KAAK;GAAE;GAAM,kBAAkB,QAAQ;EAAiB,CAAC;EAErE,IAAI,KAAK,QAAQ,KAAK,QAAQ,OAAO;EAErC,KAAK,UAAU,IAAI,YAAY;EAC/B,KAAK,MAAM,OAAO,IAAI;EACtB,WAAW,IAAI;EACf,IAAI,UAAU,KAAK,SAAS,MAAM,kBAAkB,EAAE,kBAAkB,MAAM,CAAC;EAC/E,KAAK,MAAM,gBAAgB,EAAE,kBAAkB,MAAM,CAAC;EAEtD,MAAM,eAAqB;GACzB,IAAI,UAAU;IACZ,SAAS,KAAK,UAAU,OAAO,YAAY;IAC3C,SAAS,KAAK,QAAQ;IACtB,KAAK,SAAS,MAAM,iBAAiB,EAAE,kBAAkB,MAAM,CAAC;GAClE;GACA,KAAK,MAAM,SAAS,SAAS,MAAM,KAAK,OA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AAO,MAAM,MAAM,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;EACpF,IAAI,SAAS,QAAQ,aAAa,OAAO,IAAI,KAAK,OAAQ,KAAK,IAAI,CAAC;OAC/D,QAAQ,UAAU,OAAO,IAAI,KAAK,OAAQ,KAAK,IAAI,CAAC;EACzD,MAAM,QAAQ,KAAK,OAAQ,SAAS,QAAQ,MAAM;EAClD,IAAI,OAAO,SAAS,QAAQ,KAAK,OAAO,GAAG,EAAE,CAAC,CAAE,QAAQ;CAC1D;CAEA,OAAO,OAAe,QAAQ,OAAqB;EACjD,OAAO;GAAE,KAAK,KAAK;GAAM;GAAO,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EAAG;CAC9D;;CAGA,UAAgB;EACd,oBAAoB,YAAY,KAAK,WAAW;CAClD;AACF;AAEA,IAAM,cAAc,UAClB,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAQ,MAA+B,SAAS;AAEjG,SAAS,oBAA6B;CACpC,OAAO,WAAW,kCAAkC,CAAC,CAAC;AACxD;AAGA,SAAS,MAAM,QAAc,SAA2B,OAAa,QAA4C;CAC/G,MAAM,SAAS;EAAE,UAAU;EAAU,QAAQ;CAAK;CAClD,MAAM,UAAU,CAAC,MAAM,QAA0B,CAC/C,EAAE,WAAW,cAAc,KAAK,GAAG,GACnC,EAAE,WAAW,cAAc,GAAG,GAAG,CACnC;CACA,OAAO,QAAQ,IAAI,CACjB,OAAO,QAAQ,OAAO,OAAO,GAAG,MAAM,CAAC,CAAC,UACxC,MAAM,QAAQ,OAAO,MAAM,GAAG,MAAM,CAAC,CAAC,QACxC,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;AAC1B"}
@@ -0,0 +1,18 @@
1
+ import type { ListBinding, ListOptions } from './adapter.js';
2
+ type View = HTMLElement;
3
+ export interface WebListHooks {
4
+ /** A new, empty container for a cell. */
5
+ createCell(): View;
6
+ /** Raises a NativeScript event on the list (itemTap, loadMoreItems). */
7
+ emit(name: string, data?: Record<string, unknown>): void;
8
+ }
9
+ export declare class WebList implements ListBinding {
10
+ #private;
11
+ constructor(view: View, show: (container: View, index: number) => void, options: ListOptions, hooks: WebListHooks);
12
+ setCount(count: number): void;
13
+ release(): void;
14
+ /** How many cells exist, on screen or waiting in a pool. */
15
+ get cellCount(): number;
16
+ }
17
+ export {};
18
+ //# sourceMappingURL=web-list.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-list.d.ts","sourceRoot":"","sources":["../../src/web-list.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE7D,KAAK,IAAI,GAAG,WAAW,CAAC;AAexB,MAAM,WAAW,YAAY;IAC3B,yCAAyC;IACzC,UAAU,IAAI,IAAI,CAAC;IACnB,wEAAwE;IACxE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC1D;AAED,qBAAa,OAAQ,YAAW,WAAW;;gBA2B7B,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,YAAY;IA+BjH,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAe7B,OAAO,IAAI,IAAI;IAOf,4DAA4D;IAC5D,IAAI,SAAS,IAAI,MAAM,CAItB;CAyKF"}
@@ -0,0 +1,224 @@
1
+ // src/web-list.ts
2
+ /** How far past the screen, above and below, rows are kept ready, in pixels. */
3
+ var MARGIN = 600;
4
+ /** The height of a row until one of its kind is measured. */
5
+ var FIRST_ESTIMATE = 44;
6
+ /** How close to the end a scroll asks for more rows, in pixels. */
7
+ var LOAD_MORE_WITHIN = 400;
8
+ var WebList = class {
9
+ #view;
10
+ #content;
11
+ #show;
12
+ #kindOf;
13
+ #hooks;
14
+ #count = 0;
15
+ /** Each row's measured height; a hole for a row not measured yet. */
16
+ #measured = [];
17
+ /** Each row's top, and the end of the last row at `#offsets[count]`. Rebuilt when `#dirty`. */
18
+ #offsets = [0];
19
+ #dirty = true;
20
+ /** Running mean of measured heights per kind, for rows not shown yet. */
21
+ #means = /* @__PURE__ */ new Map();
22
+ #active = /* @__PURE__ */ new Map();
23
+ #free = /* @__PURE__ */ new Map();
24
+ #cells = /* @__PURE__ */ new WeakMap();
25
+ /** Pixels to scroll by on the next layout, from rows above the screen that changed height. */
26
+ #anchor = 0;
27
+ #frame = 0;
28
+ #askedAt = -1;
29
+ #released = false;
30
+ #resizes;
31
+ constructor(view, show, options, hooks) {
32
+ this.#view = view;
33
+ this.#show = show;
34
+ this.#hooks = hooks;
35
+ const kindOf = options.kindOf;
36
+ this.#kindOf = kindOf ? (index) => kindOf(index) : () => "row";
37
+ this.#content = document.createElement("div");
38
+ this.#content.className = "ns-listView-content";
39
+ view.append(this.#content);
40
+ view.addEventListener("scroll", this.#schedule, { passive: true });
41
+ this.#resizes = typeof ResizeObserver === "undefined" ? void 0 : new ResizeObserver((entries) => {
42
+ for (const entry of entries) {
43
+ if (entry.target === view) {
44
+ this.#schedule();
45
+ continue;
46
+ }
47
+ const cell = this.#cells.get(entry.target);
48
+ if (!cell || !this.#active.has(cell.index) || this.#active.get(cell.index) !== cell) continue;
49
+ const height = entry.borderBoxSize?.[0]?.blockSize ?? entry.target.offsetHeight;
50
+ if (this.#record(cell, height)) this.#schedule();
51
+ }
52
+ });
53
+ this.#resizes?.observe(view);
54
+ }
55
+ setCount(count) {
56
+ this.#count = count;
57
+ this.#measured.length = Math.min(this.#measured.length, count);
58
+ if (this.#askedAt >= count) this.#askedAt = -1;
59
+ for (const [index, cell] of [...this.#active]) if (index >= count || this.#kindOf(index) !== cell.kind) this.#release(cell);
60
+ else this.#show(cell.container, index);
61
+ this.#dirty = true;
62
+ this.#layout();
63
+ this.#schedule();
64
+ }
65
+ release() {
66
+ this.#released = true;
67
+ cancelAnimationFrame(this.#frame);
68
+ this.#view.removeEventListener("scroll", this.#schedule);
69
+ this.#resizes?.disconnect();
70
+ }
71
+ /** How many cells exist, on screen or waiting in a pool. */
72
+ get cellCount() {
73
+ let pooled = 0;
74
+ for (const cells of this.#free.values()) pooled += cells.length;
75
+ return this.#active.size + pooled;
76
+ }
77
+ #schedule = () => {
78
+ if (this.#frame || this.#released) return;
79
+ this.#frame = requestAnimationFrame(() => {
80
+ this.#frame = 0;
81
+ this.#layout();
82
+ this.#maybeLoadMore();
83
+ });
84
+ };
85
+ #layout() {
86
+ if (this.#released) return;
87
+ for (let pass = 0; pass < 4; pass++) if (!this.#place()) break;
88
+ }
89
+ /** Shows the rows in view and places them. True if what was measured calls for another pass. */
90
+ #place() {
91
+ const view = this.#view;
92
+ this.#rebuild();
93
+ if (this.#anchor !== 0) {
94
+ this.#content.style.height = `${this.#offsets[this.#count]}px`;
95
+ view.scrollTop += this.#anchor;
96
+ this.#anchor = 0;
97
+ }
98
+ const top = view.scrollTop;
99
+ const height = this.#screen();
100
+ const count = this.#count;
101
+ const first = count === 0 ? 0 : this.#rowAt(Math.max(0, top - MARGIN));
102
+ const last = count === 0 ? -1 : this.#rowAt(top + height + MARGIN);
103
+ for (const [index, cell] of [...this.#active]) if (index < first || index > last) this.#release(cell);
104
+ const shown = [];
105
+ for (let index = first; index <= last; index++) {
106
+ if (this.#active.has(index)) continue;
107
+ const cell = this.#take(this.#kindOf(index), index);
108
+ this.#active.set(index, cell);
109
+ this.#show(cell.container, index);
110
+ shown.push(cell);
111
+ }
112
+ let changed = false;
113
+ for (const cell of shown) changed = this.#record(cell, cell.container.getBoundingClientRect().height) || changed;
114
+ this.#rebuild();
115
+ this.#content.style.height = `${this.#offsets[count]}px`;
116
+ for (const [index, cell] of this.#active) {
117
+ cell.container.style.transform = `translateY(${this.#offsets[index]}px)`;
118
+ cell.container.setAttribute("aria-posinset", String(index + 1));
119
+ cell.container.setAttribute("aria-setsize", String(count));
120
+ }
121
+ const end = this.#offsets[Math.min(last + 1, count)];
122
+ return this.#anchor !== 0 || changed && last < count - 1 && end < top + height + MARGIN;
123
+ }
124
+ #maybeLoadMore() {
125
+ const view = this.#view;
126
+ const count = this.#count;
127
+ if (count === 0 || this.#askedAt === count || !view.isConnected || view.clientHeight === 0) return;
128
+ if (!this.#active.has(count - 1)) return;
129
+ if (view.scrollTop + this.#screen() < this.#offsets[count] - LOAD_MORE_WITHIN) return;
130
+ this.#askedAt = count;
131
+ this.#hooks.emit("loadMoreItems");
132
+ }
133
+ #screen() {
134
+ return Math.min(this.#view.clientHeight || innerHeight, innerHeight);
135
+ }
136
+ #take(kind, index) {
137
+ const pooled = this.#free.get(kind)?.pop();
138
+ if (pooled) {
139
+ pooled.index = index;
140
+ pooled.container.hidden = false;
141
+ return pooled;
142
+ }
143
+ const container = this.#hooks.createCell();
144
+ container.classList.add("ns-listView-cell");
145
+ container.setAttribute("role", "listitem");
146
+ const cell = {
147
+ container,
148
+ kind,
149
+ index
150
+ };
151
+ this.#cells.set(container, cell);
152
+ container.addEventListener("click", (click) => {
153
+ if (click.target.closest("button, input, select, textarea, a") !== null) return;
154
+ this.#hooks.emit("itemTap", { index: cell.index });
155
+ });
156
+ this.#content.append(container);
157
+ this.#resizes?.observe(container);
158
+ return cell;
159
+ }
160
+ #release(cell) {
161
+ this.#active.delete(cell.index);
162
+ cell.container.hidden = true;
163
+ cell.container.removeAttribute("aria-posinset");
164
+ cell.container.removeAttribute("aria-setsize");
165
+ const pool = this.#free.get(cell.kind) ?? [];
166
+ pool.push(cell);
167
+ this.#free.set(cell.kind, pool);
168
+ }
169
+ #record(cell, height) {
170
+ if (height <= 0 || cell.index >= this.#count) return false;
171
+ const before = this.#heightOf(cell.index);
172
+ const known = this.#measured[cell.index] !== void 0;
173
+ this.#measured[cell.index] = height;
174
+ if (!known) {
175
+ const mean = this.#means.get(cell.kind) ?? {
176
+ total: 0,
177
+ rows: 0
178
+ };
179
+ mean.total += height;
180
+ mean.rows += 1;
181
+ this.#means.set(cell.kind, mean);
182
+ }
183
+ if (Math.abs(height - before) < .01) return false;
184
+ const top = this.#offsets[cell.index];
185
+ if (top !== void 0 && top + before <= this.#view.scrollTop) this.#anchor += height - before;
186
+ this.#dirty = true;
187
+ return true;
188
+ }
189
+ #heightOf(index) {
190
+ const measured = this.#measured[index];
191
+ if (measured !== void 0) return measured;
192
+ const mean = this.#means.get(this.#kindOf(index));
193
+ if (mean) return mean.total / mean.rows;
194
+ let total = 0;
195
+ let rows = 0;
196
+ for (const each of this.#means.values()) {
197
+ total += each.total;
198
+ rows += each.rows;
199
+ }
200
+ return rows > 0 ? total / rows : FIRST_ESTIMATE;
201
+ }
202
+ #rebuild() {
203
+ if (!this.#dirty) return;
204
+ const offsets = new Array(this.#count + 1);
205
+ offsets[0] = 0;
206
+ for (let index = 0; index < this.#count; index++) offsets[index + 1] = offsets[index] + this.#heightOf(index);
207
+ this.#offsets = offsets;
208
+ this.#dirty = false;
209
+ }
210
+ #rowAt(y) {
211
+ const offsets = this.#offsets;
212
+ let low = 0;
213
+ let high = this.#count - 1;
214
+ while (low < high) {
215
+ const middle = low + high + 1 >> 1;
216
+ if (offsets[middle] <= y) low = middle;
217
+ else high = middle - 1;
218
+ }
219
+ return low;
220
+ }
221
+ };
222
+ export { WebList };
223
+
224
+ //# sourceMappingURL=web-list.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-list.js","names":[],"sources":["../../src/web-list.ts"],"sourcesContent":["// A ListView in a browser that keeps only the rows on screen, as UITableView and RecyclerView do. The list holds an\n// element as tall as all its rows; each row on screen (plus a margin above and below) is a cell placed at its row's\n// offset. A cell that scrolls out goes to a pool for its kind of row, and the next row of that kind to scroll in\n// takes it: `cell(container, index)` re-renders it with the new row, which Glimmer does in place.\n//\n// Rows can be of any height. A row not yet shown counts as the average height of the rows of its kind shown so far,\n// and as it's shown it's measured, and remeasured whenever its size changes (an image loading, text wrapping). When a\n// row above the screen turns out taller or shorter than estimated, the list scrolls by the difference, so what's on\n// screen stays put.\n//\n// Like NativeScript's, the list scrolls itself: it needs a height from its parent (a `*` row in a GridLayout, the\n// rest of a page), not one that grows with its rows.\n\nimport type { ListBinding, ListOptions } from './adapter.ts';\n\ntype View = HTMLElement;\n\ninterface Cell {\n container: View;\n kind: string;\n index: number;\n}\n\n/** How far past the screen, above and below, rows are kept ready, in pixels. */\nconst MARGIN = 600;\n/** The height of a row until one of its kind is measured. */\nconst FIRST_ESTIMATE = 44;\n/** How close to the end a scroll asks for more rows, in pixels. */\nconst LOAD_MORE_WITHIN = 400;\n\nexport interface WebListHooks {\n /** A new, empty container for a cell. */\n createCell(): View;\n /** Raises a NativeScript event on the list (itemTap, loadMoreItems). */\n emit(name: string, data?: Record<string, unknown>): void;\n}\n\nexport class WebList implements ListBinding {\n readonly #view: View;\n readonly #content: View;\n readonly #show: (container: View, index: number) => void;\n readonly #kindOf: (index: number) => string;\n readonly #hooks: WebListHooks;\n\n #count = 0;\n /** Each row's measured height; a hole for a row not measured yet. */\n #measured: number[] = [];\n /** Each row's top, and the end of the last row at `#offsets[count]`. Rebuilt when `#dirty`. */\n #offsets: number[] = [0];\n #dirty = true;\n /** Running mean of measured heights per kind, for rows not shown yet. */\n readonly #means = new Map<string, { total: number; rows: number }>();\n\n readonly #active = new Map<number, Cell>();\n readonly #free = new Map<string, Cell[]>();\n readonly #cells = new WeakMap<Element, Cell>();\n\n /** Pixels to scroll by on the next layout, from rows above the screen that changed height. */\n #anchor = 0;\n #frame = 0;\n #askedAt = -1;\n #released = false;\n readonly #resizes: ResizeObserver | undefined;\n\n constructor(view: View, show: (container: View, index: number) => void, options: ListOptions, hooks: WebListHooks) {\n this.#view = view;\n this.#show = show;\n this.#hooks = hooks;\n const kindOf = options.kindOf;\n this.#kindOf = kindOf ? (index) => kindOf(index) : () => 'row';\n\n this.#content = document.createElement('div');\n this.#content.className = 'ns-listView-content';\n view.append(this.#content);\n\n view.addEventListener('scroll', this.#schedule, { passive: true });\n // A cell's height changes (an image loads) and the list's size changes (a rotation, a resize): lay out again.\n this.#resizes =\n typeof ResizeObserver === 'undefined'\n ? undefined\n : new ResizeObserver((entries) => {\n for (const entry of entries) {\n if (entry.target === view) {\n this.#schedule();\n continue;\n }\n const cell = this.#cells.get(entry.target);\n if (!cell || !this.#active.has(cell.index) || this.#active.get(cell.index) !== cell) continue;\n const height = entry.borderBoxSize?.[0]?.blockSize ?? (entry.target as View).offsetHeight;\n if (this.#record(cell, height)) this.#schedule();\n }\n });\n this.#resizes?.observe(view);\n }\n\n setCount(count: number): void {\n this.#count = count;\n this.#measured.length = Math.min(this.#measured.length, count);\n if (this.#askedAt >= count) this.#askedAt = -1;\n // The cells on screen show their (maybe new) rows; those past the end, or now of another kind, go.\n for (const [index, cell] of [...this.#active]) {\n if (index >= count || this.#kindOf(index) !== cell.kind) this.#release(cell);\n else this.#show(cell.container, index);\n }\n this.#dirty = true;\n this.#layout();\n // Asking for more waits for a frame: the list is in the document by then, and `{{on 'loadMoreItems'}}` set up.\n this.#schedule();\n }\n\n release(): void {\n this.#released = true;\n cancelAnimationFrame(this.#frame);\n this.#view.removeEventListener('scroll', this.#schedule);\n this.#resizes?.disconnect();\n }\n\n /** How many cells exist, on screen or waiting in a pool. */\n get cellCount(): number {\n let pooled = 0;\n for (const cells of this.#free.values()) pooled += cells.length;\n return this.#active.size + pooled;\n }\n\n #schedule = (): void => {\n if (this.#frame || this.#released) return;\n this.#frame = requestAnimationFrame(() => {\n this.#frame = 0;\n this.#layout();\n // Only from a frame: during setCount, Ember is rendering, and loading more there would change what it just read.\n this.#maybeLoadMore();\n });\n };\n\n #layout(): void {\n if (this.#released) return;\n // Measuring can show that rows are shorter than estimated, which leaves room for more: a few passes fill it.\n for (let pass = 0; pass < 4; pass++) if (!this.#place()) break;\n }\n\n /** Shows the rows in view and places them. True if what was measured calls for another pass. */\n #place(): boolean {\n const view = this.#view;\n this.#rebuild();\n if (this.#anchor !== 0) {\n // The new height first, so the browser doesn't cap the scroll at the old end.\n this.#content.style.height = `${this.#offsets[this.#count]}px`;\n view.scrollTop += this.#anchor;\n this.#anchor = 0;\n }\n\n const top = view.scrollTop;\n const height = this.#screen();\n const count = this.#count;\n const first = count === 0 ? 0 : this.#rowAt(Math.max(0, top - MARGIN));\n const last = count === 0 ? -1 : this.#rowAt(top + height + MARGIN);\n\n for (const [index, cell] of [...this.#active]) if (index < first || index > last) this.#release(cell);\n\n // Writes first (render the new rows), then reads (measure them), so the browser lays out once.\n const shown: Cell[] = [];\n for (let index = first; index <= last; index++) {\n if (this.#active.has(index)) continue;\n const cell = this.#take(this.#kindOf(index), index);\n this.#active.set(index, cell);\n this.#show(cell.container, index);\n shown.push(cell);\n }\n let changed = false;\n for (const cell of shown) changed = this.#record(cell, cell.container.getBoundingClientRect().height) || changed;\n this.#rebuild();\n\n this.#content.style.height = `${this.#offsets[count]}px`;\n for (const [index, cell] of this.#active) {\n cell.container.style.transform = `translateY(${this.#offsets[index]}px)`;\n cell.container.setAttribute('aria-posinset', String(index + 1));\n cell.container.setAttribute('aria-setsize', String(count));\n }\n\n // Another pass if the rows shown don't reach the bottom of the margin any more, or one above changed height.\n const end = this.#offsets[Math.min(last + 1, count)]!;\n return this.#anchor !== 0 || (changed && last < count - 1 && end < top + height + MARGIN);\n }\n\n #maybeLoadMore(): void {\n const view = this.#view;\n const count = this.#count;\n if (count === 0 || this.#askedAt === count || !view.isConnected || view.clientHeight === 0) return;\n if (!this.#active.has(count - 1)) return;\n const bottom = view.scrollTop + this.#screen();\n if (bottom < this.#offsets[count]! - LOAD_MORE_WITHIN) return;\n this.#askedAt = count;\n this.#hooks.emit('loadMoreItems');\n }\n\n // The height of the list on screen. Before it's in the document it has none, and in a parent that lets it grow with\n // its rows (a StackLayout) it's as tall as all of them: either way, at most the window's.\n #screen(): number {\n return Math.min(this.#view.clientHeight || innerHeight, innerHeight);\n }\n\n // A cell for a row: one of its kind from the pool, or a new one.\n #take(kind: string, index: number): Cell {\n const pooled = this.#free.get(kind)?.pop();\n if (pooled) {\n pooled.index = index;\n pooled.container.hidden = false;\n return pooled;\n }\n const container = this.#hooks.createCell();\n container.classList.add('ns-listView-cell');\n container.setAttribute('role', 'listitem');\n const cell: Cell = { container, kind, index };\n this.#cells.set(container, cell);\n container.addEventListener('click', (click) => {\n // A tap on a button or a field inside the row is theirs.\n if ((click.target as HTMLElement).closest('button, input, select, textarea, a') !== null) return;\n this.#hooks.emit('itemTap', { index: cell.index });\n });\n this.#content.append(container);\n this.#resizes?.observe(container);\n return cell;\n }\n\n #release(cell: Cell): void {\n this.#active.delete(cell.index);\n cell.container.hidden = true;\n cell.container.removeAttribute('aria-posinset');\n cell.container.removeAttribute('aria-setsize');\n const pool = this.#free.get(cell.kind) ?? [];\n pool.push(cell);\n this.#free.set(cell.kind, pool);\n }\n\n // A row's height as measured. True if it differs from what the layout used.\n #record(cell: Cell, height: number): boolean {\n if (height <= 0 || cell.index >= this.#count) return false;\n const before = this.#heightOf(cell.index);\n const known = this.#measured[cell.index] !== undefined;\n this.#measured[cell.index] = height;\n if (!known) {\n const mean = this.#means.get(cell.kind) ?? { total: 0, rows: 0 };\n mean.total += height;\n mean.rows += 1;\n this.#means.set(cell.kind, mean);\n }\n if (Math.abs(height - before) < 0.01) return false;\n // A row above the top of the screen changed: keep what's on screen where it is.\n // The offsets are the ones on screen, from the last layout, until the next one rebuilds them.\n const top = this.#offsets[cell.index];\n if (top !== undefined && top + before <= this.#view.scrollTop) this.#anchor += height - before;\n this.#dirty = true;\n return true;\n }\n\n #heightOf(index: number): number {\n const measured = this.#measured[index];\n if (measured !== undefined) return measured;\n const mean = this.#means.get(this.#kindOf(index));\n if (mean) return mean.total / mean.rows;\n // No row of this kind measured yet: the mean of all of them.\n let total = 0;\n let rows = 0;\n for (const each of this.#means.values()) {\n total += each.total;\n rows += each.rows;\n }\n return rows > 0 ? total / rows : FIRST_ESTIMATE;\n }\n\n #rebuild(): void {\n if (!this.#dirty) return;\n const offsets = new Array<number>(this.#count + 1);\n offsets[0] = 0;\n for (let index = 0; index < this.#count; index++) offsets[index + 1] = offsets[index]! + this.#heightOf(index);\n this.#offsets = offsets;\n this.#dirty = false;\n }\n\n // The row at a height from the top: the last whose top is at or above it.\n #rowAt(y: number): number {\n const offsets = this.#offsets;\n let low = 0;\n let high = this.#count - 1;\n while (low < high) {\n const middle = (low + high + 1) >> 1;\n if (offsets[middle]! <= y) low = middle;\n else high = middle - 1;\n }\n return low;\n }\n}\n"],"mappings":";;AAwBA,IAAM,SAAS;;AAEf,IAAM,iBAAiB;;AAEvB,IAAM,mBAAmB;AASzB,IAAa,UAAb,MAA4C;CACjC;CACA;CACA;CACA;CACA;CAET,SAAS;;CAET,YAAsB,CAAC;;CAEvB,WAAqB,CAAC,CAAC;CACvB,SAAS;;CAEA,yBAAS,IAAI,IAA6C;CAE1D,0BAAU,IAAI,IAAkB;CAChC,wBAAQ,IAAI,IAAoB;CAChC,yBAAS,IAAI,QAAuB;;CAG7C,UAAU;CACV,SAAS;CACT,WAAW;CACX,YAAY;CACH;CAET,YAAY,MAAY,MAAgD,SAAsB,OAAqB;EACjH,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,KAAK,SAAS;EACd,MAAM,SAAS,QAAQ;EACvB,KAAK,UAAU,UAAU,UAAU,OAAO,KAAK,UAAU;EAEzD,KAAK,WAAW,SAAS,cAAc,KAAK;EAC5C,KAAK,SAAS,YAAY;EAC1B,KAAK,OAAO,KAAK,QAAQ;EAEzB,KAAK,iBAAiB,UAAU,KAAK,WAAW,EAAE,SAAS,KAAK,CAAC;EAEjE,KAAK,WACH,OAAO,mBAAmB,cACtB,KAAA,IACA,IAAI,gBAAgB,YAAY;GAC9B,KAAK,MAAM,SAAS,SAAS;IAC3B,IAAI,MAAM,WAAW,MAAM;KACzB,KAAK,UAAU;KACf;IACF;IACA,MAAM,OAAO,KAAK,OAAO,IAAI,MAAM,MAAM;IACzC,IAAI,CAAC,QA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AAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,QAAQ,QAAQ,KAAK,QAAQ,SAAU,KAAK,UAAU,KAAK;EAC7G,KAAK,WAAW;EAChB,KAAK,SAAS;CAChB;CAGA,OAAO,GAAmB;EACxB,MAAM,UAAU,KAAK;EACrB,IAAI,MAAM;EACV,IAAI,OAAO,KAAK,SAAS;EACzB,OAAO,MAAM,MAAM;GACjB,MAAM,SAAU,MAAM,OAAO,KAAM;GACnC,IAAI,QAAQ,WAAY,GAAG,MAAM;QAC5B,OAAO,SAAS;EACvB;EACA,OAAO;CACT;AACF"}
@@ -0,0 +1,51 @@
1
+ import type { Navigator } from './navigator.js';
2
+ export type RouteParams = Record<string, string>;
3
+ export interface RouteDefinition {
4
+ screen: object;
5
+ /** The screen's arguments from the path's parameters. Without it, the parameters as strings. */
6
+ args?: (params: RouteParams) => Record<string, unknown>;
7
+ /** The document's title on this screen. */
8
+ title?: string | ((args: Record<string, unknown>) => string);
9
+ }
10
+ export type Routes = Record<string, object | RouteDefinition>;
11
+ interface Route extends RouteDefinition {
12
+ path: string;
13
+ keys: string[];
14
+ pattern: RegExp;
15
+ }
16
+ interface ScreenShown {
17
+ component: object;
18
+ args?: Record<string, unknown>;
19
+ }
20
+ export declare class WebRouter {
21
+ #private;
22
+ /** Where the app is served from, such as `/app`; paths in routes are below it. */
23
+ readonly base: string;
24
+ readonly routes: Route[];
25
+ /** The app's navigator, set when the app starts. */
26
+ navigator?: Navigator;
27
+ constructor(routes: Routes,
28
+ /** Where the app is served from, such as `/app`; paths in routes are below it. */
29
+ base?: string);
30
+ /** The route and parameters for a path (without the base), if one matches. */
31
+ match(pathname: string): {
32
+ route: Route;
33
+ params: RouteParams;
34
+ } | undefined;
35
+ /** The path for a screen being shown, when it has a route and its arguments fill the route's parameters. */
36
+ pathFor(screen: ScreenShown | undefined): string | undefined;
37
+ titleFor(screen: ScreenShown | undefined): string | undefined;
38
+ /** A path as the browser's URL, below the base. */
39
+ href(path: string): string;
40
+ /** The screen's arguments from a matched route. */
41
+ argsFor(route: Route, params: RouteParams): Record<string, unknown>;
42
+ /**
43
+ * Shows the screen a URL names. `replace` for a URL the history has no screen for (from before a reload): the stack
44
+ * starts again from it. Otherwise it goes on top, as the browser's forward button does.
45
+ */
46
+ open(pathname: string, { replace }: {
47
+ replace: boolean;
48
+ }): void;
49
+ }
50
+ export {};
51
+ //# sourceMappingURL=web-router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-router.d.ts","sourceRoot":"","sources":["../../src/web-router.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAEjD,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,gGAAgG;IAChG,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACxD,2CAA2C;IAC3C,KAAK,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC,CAAC;CAC9D;AAED,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CAAC,CAAC;AAE9D,UAAU,KAAM,SAAQ,eAAe;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,WAAW;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAID,qBAAa,SAAS;;IAOlB,kFAAkF;IAClF,QAAQ,CAAC,IAAI;IAPf,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC;IACzB,oDAAoD;IACpD,SAAS,CAAC,EAAE,SAAS,CAAC;gBAGpB,MAAM,EAAE,MAAM;IACd,kFAAkF;IACzE,IAAI,SAAK;IAkBpB,8EAA8E;IAC9E,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG;QAAE,KAAK,EAAE,KAAK,CAAC;QAAC,MAAM,EAAE,WAAW,CAAA;KAAE,GAAG,SAAS;IAY1E,4GAA4G;IAC5G,OAAO,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS;IAW5D,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS;IAO7D,mDAAmD;IACnD,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;IAI1B,mDAAmD;IACnD,OAAO,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAInE;;;OAGG;IACH,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI;CAgBhE"}
@@ -0,0 +1,83 @@
1
+ // src/web-router.ts
2
+ var isDefinition = (value) => "screen" in value;
3
+ var WebRouter = class {
4
+ base;
5
+ routes;
6
+ /** The app's navigator, set when the app starts. */
7
+ navigator;
8
+ constructor(routes, base = "") {
9
+ this.base = base;
10
+ this.base = base.replace(/\/$/, "");
11
+ this.routes = Object.entries(routes).map(([path, value]) => {
12
+ const definition = isDefinition(value) ? value : { screen: value };
13
+ const keys = [];
14
+ const source = path.split("/").map((part) => {
15
+ if (!part.startsWith(":")) return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16
+ keys.push(part.slice(1));
17
+ return "([^/]+)";
18
+ }).join("/");
19
+ return {
20
+ ...definition,
21
+ path,
22
+ keys,
23
+ pattern: new RegExp(`^${source || "/"}/?$`)
24
+ };
25
+ });
26
+ }
27
+ /** The route and parameters for a path (without the base), if one matches. */
28
+ match(pathname) {
29
+ const path = this.#strip(pathname);
30
+ for (const route of this.routes) {
31
+ const found = route.pattern.exec(path);
32
+ if (found) return {
33
+ route,
34
+ params: Object.fromEntries(route.keys.map((key, index) => [key, decodeURIComponent(found[index + 1])]))
35
+ };
36
+ }
37
+ }
38
+ /** The path for a screen being shown, when it has a route and its arguments fill the route's parameters. */
39
+ pathFor(screen) {
40
+ if (!screen) return void 0;
41
+ for (const route of this.routes) {
42
+ if (route.screen !== screen.component) continue;
43
+ const args = screen.args ?? {};
44
+ if (route.keys.some((key) => args[key] === void 0 || args[key] === null)) continue;
45
+ return route.path.replace(/:([^/]+)/g, (_, key) => encodeURIComponent(String(args[key])));
46
+ }
47
+ }
48
+ titleFor(screen) {
49
+ if (!screen) return void 0;
50
+ const route = this.routes.find((each) => each.screen === screen.component);
51
+ if (!route?.title) return void 0;
52
+ return typeof route.title === "string" ? route.title : route.title(screen.args ?? {});
53
+ }
54
+ /** A path as the browser's URL, below the base. */
55
+ href(path) {
56
+ return `${this.base}${path.startsWith("/") ? path : `/${path}`}${path === location.pathname ? location.search : ""}`;
57
+ }
58
+ /** The screen's arguments from a matched route. */
59
+ argsFor(route, params) {
60
+ return route.args ? route.args(params) : { ...params };
61
+ }
62
+ /**
63
+ * Shows the screen a URL names. `replace` for a URL the history has no screen for (from before a reload): the stack
64
+ * starts again from it. Otherwise it goes on top, as the browser's forward button does.
65
+ */
66
+ open(pathname, { replace }) {
67
+ const navigator = this.navigator;
68
+ if (!navigator) return;
69
+ const found = this.match(pathname);
70
+ if (!found) return;
71
+ navigator.navigate(found.route.screen, {
72
+ args: this.argsFor(found.route, found.params),
73
+ animated: !replace,
74
+ clearHistory: replace
75
+ });
76
+ }
77
+ #strip(pathname) {
78
+ return (this.base && pathname.startsWith(this.base) ? pathname.slice(this.base.length) : pathname) || "/";
79
+ }
80
+ };
81
+ export { WebRouter };
82
+
83
+ //# sourceMappingURL=web-router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-router.js","names":[],"sources":["../../src/web-router.ts"],"sourcesContent":["// URLs for screens, in the browser. A route names a screen and how its arguments read from the path:\n//\n// routes: {\n// '/': Home,\n// '/todos/:id': { screen: TodoScreen, args: ({ id }) => ({ id: Number(id) }), title: ({ id }) => `To-do ${id}` },\n// }\n//\n// Navigating to a screen with a route puts its path in the address bar, filling `:id` from the screen's `id`\n// argument; opening that URL shows the screen, over the first screen so back goes there. A screen without a route\n// keeps the URL it was opened from. Arguments that aren't in the path (an object, a callback) aren't in the URL either,\n// so a screen opened from a URL only gets what the path says.\n\nimport type { Navigator } from './navigator.ts';\n\nexport type RouteParams = Record<string, string>;\n\nexport interface RouteDefinition {\n screen: object;\n /** The screen's arguments from the path's parameters. Without it, the parameters as strings. */\n args?: (params: RouteParams) => Record<string, unknown>;\n /** The document's title on this screen. */\n title?: string | ((args: Record<string, unknown>) => string);\n}\n\nexport type Routes = Record<string, object | RouteDefinition>;\n\ninterface Route extends RouteDefinition {\n path: string;\n keys: string[];\n pattern: RegExp;\n}\n\ninterface ScreenShown {\n component: object;\n args?: Record<string, unknown>;\n}\n\nconst isDefinition = (value: object): value is RouteDefinition => 'screen' in value;\n\nexport class WebRouter {\n readonly routes: Route[];\n /** The app's navigator, set when the app starts. */\n navigator?: Navigator;\n\n constructor(\n routes: Routes,\n /** Where the app is served from, such as `/app`; paths in routes are below it. */\n readonly base = '',\n ) {\n this.base = base.replace(/\\/$/, '');\n this.routes = Object.entries(routes).map(([path, value]) => {\n const definition = isDefinition(value) ? value : { screen: value };\n const keys: string[] = [];\n const source = path\n .split('/')\n .map((part) => {\n if (!part.startsWith(':')) return part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n keys.push(part.slice(1));\n return '([^/]+)';\n })\n .join('/');\n return { ...definition, path, keys, pattern: new RegExp(`^${source || '/'}/?$`) };\n });\n }\n\n /** The route and parameters for a path (without the base), if one matches. */\n match(pathname: string): { route: Route; params: RouteParams } | undefined {\n const path = this.#strip(pathname);\n for (const route of this.routes) {\n const found = route.pattern.exec(path);\n if (found) {\n const params = Object.fromEntries(route.keys.map((key, index) => [key, decodeURIComponent(found[index + 1]!)]));\n return { route, params };\n }\n }\n return undefined;\n }\n\n /** The path for a screen being shown, when it has a route and its arguments fill the route's parameters. */\n pathFor(screen: ScreenShown | undefined): string | undefined {\n if (!screen) return undefined;\n for (const route of this.routes) {\n if (route.screen !== screen.component) continue;\n const args = screen.args ?? {};\n if (route.keys.some((key) => args[key] === undefined || args[key] === null)) continue;\n return route.path.replace(/:([^/]+)/g, (_, key: string) => encodeURIComponent(String(args[key])));\n }\n return undefined;\n }\n\n titleFor(screen: ScreenShown | undefined): string | undefined {\n if (!screen) return undefined;\n const route = this.routes.find((each) => each.screen === screen.component);\n if (!route?.title) return undefined;\n return typeof route.title === 'string' ? route.title : route.title(screen.args ?? {});\n }\n\n /** A path as the browser's URL, below the base. */\n href(path: string): string {\n return `${this.base}${path.startsWith('/') ? path : `/${path}`}${path === location.pathname ? location.search : ''}`;\n }\n\n /** The screen's arguments from a matched route. */\n argsFor(route: Route, params: RouteParams): Record<string, unknown> {\n return route.args ? route.args(params) : { ...params };\n }\n\n /**\n * Shows the screen a URL names. `replace` for a URL the history has no screen for (from before a reload): the stack\n * starts again from it. Otherwise it goes on top, as the browser's forward button does.\n */\n open(pathname: string, { replace }: { replace: boolean }): void {\n const navigator = this.navigator;\n if (!navigator) return;\n const found = this.match(pathname);\n if (!found) return;\n navigator.navigate(found.route.screen, {\n args: this.argsFor(found.route, found.params),\n animated: !replace,\n clearHistory: replace,\n });\n }\n\n #strip(pathname: string): string {\n const path = this.base && pathname.startsWith(this.base) ? pathname.slice(this.base.length) : pathname;\n return path || '/';\n }\n}\n"],"mappings":";AAqCA,IAAM,gBAAgB,UAA4C,YAAY;AAE9E,IAAa,YAAb,MAAuB;CAQV;CAPF;;CAET;CAEA,YACE,QAES,OAAO,IAChB;EADS,KAAA,O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