@emberbox/ui 0.7.0 → 0.8.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emberbox/ui",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Shared look and building blocks of the Emberbox tools, built on Nuxt UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -55,7 +55,7 @@
55
55
  "vue": "^3.5.0"
56
56
  },
57
57
  "devDependencies": {
58
- "@emberbox/lint": "^0.2.0",
58
+ "@emberbox/lint": "^0.3.0",
59
59
  "@types/node": "^24.0.0",
60
60
  "@vitejs/plugin-vue": "^6.0.11",
61
61
  "@vue/tsconfig": "^0.9.1",
@@ -1,91 +1,17 @@
1
- import {onBeforeUnmount, onMounted, ref} from 'vue'
2
-
3
- /** How a tool polls the server. */
4
- export interface PollingOptions {
5
- /** Delay between two requests while the server answers. */
6
- intervalMs?: number
7
- /** Longest delay the wait grows to after failures. */
8
- maxIntervalMs?: number
9
- }
1
+ import {onBeforeUnmount, onMounted} from 'vue'
2
+ import {createPoller, type PollingOptions} from '../poller'
10
3
 
11
4
  /**
12
- * Polls regularly while the page is visible. When a request fails, the delay doubles up to
13
- * `maxIntervalMs`, so a server that is down is not hit every second; the first successful request
14
- * resets it. A hidden tab does not poll, and coming back polls at once.
15
- *
16
- * Never more than one request runs at a time, so a late older answer cannot overwrite a newer one.
17
- * A trigger during a running request queues exactly one more request after it.
5
+ * Polls while the component is mounted, with the loop of `createPoller`: backoff after failures,
6
+ * one request at a time, and a hidden tab that pauses or, with `hiddenIntervalMs`, polls slower.
18
7
  *
19
8
  * @param request fetches the state; an error counts as a lost connection
20
- * @returns whether the last request succeeded, and `refresh`, which polls immediately
9
+ * @param options the delays
10
+ * @returns whether the last request succeeded, `refresh`, which polls immediately, and `stop`
21
11
  */
22
12
  export function usePolling(request: () => Promise<unknown>, options: PollingOptions = {}) {
23
- const intervalMs = options.intervalMs ?? 2_000
24
- const maxIntervalMs = options.maxIntervalMs ?? 30_000
25
- const connected = ref(false)
26
- let delay = intervalMs
27
- let timer: ReturnType<typeof setTimeout> | undefined
28
- let active = false
29
- let running = false
30
- let again = false
31
-
32
- function schedule(): void {
33
- clearTimeout(timer)
34
- if (active && document.visibilityState === 'visible') {
35
- timer = setTimeout(() => void poll(), delay)
36
- }
37
- }
38
-
39
- async function poll(): Promise<void> {
40
- if (running) {
41
- again = true
42
- return
43
- }
44
- running = true
45
- clearTimeout(timer)
46
- try {
47
- await request()
48
- connected.value = true
49
- delay = intervalMs
50
- } catch {
51
- connected.value = false
52
- delay = Math.min(delay * 2, maxIntervalMs)
53
- } finally {
54
- running = false
55
- }
56
- if (again && active) {
57
- again = false
58
- void poll()
59
- return
60
- }
61
- schedule()
62
- }
63
-
64
- function onVisibilityChange(): void {
65
- if (document.visibilityState === 'visible') {
66
- void poll()
67
- } else {
68
- clearTimeout(timer)
69
- }
70
- }
71
-
72
- function refresh(): void {
73
- delay = intervalMs
74
- void poll()
75
- }
76
-
77
- onMounted(() => {
78
- active = true
79
- document.addEventListener('visibilitychange', onVisibilityChange)
80
- void poll()
81
- })
82
-
83
- onBeforeUnmount(() => {
84
- active = false
85
- again = false
86
- clearTimeout(timer)
87
- document.removeEventListener('visibilitychange', onVisibilityChange)
88
- })
89
-
90
- return {connected, refresh}
13
+ const poller = createPoller(request, options)
14
+ onMounted(poller.start)
15
+ onBeforeUnmount(poller.stop)
16
+ return {connected: poller.connected, refresh: poller.refresh, stop: poller.stop}
91
17
  }
package/src/index.ts CHANGED
@@ -8,7 +8,9 @@ export {createToolApp} from './create-app'
8
8
  export {copyToClipboard} from './clipboard'
9
9
  export {SITE_URL, usePage, webApplicationData, type PageMeta, type WebApplicationInfo} from './page'
10
10
  export {useNewBuild} from './composables/useNewBuild'
11
- export {usePolling, type PollingOptions} from './composables/usePolling'
11
+ export {usePolling} from './composables/usePolling'
12
+ export {createPoller, type Poller, type PollingOptions} from './poller'
13
+ export {cleanUpStorage, type StorageCleanUp} from './storage'
12
14
  export {useConfirm, type ConfirmOptions} from './composables/useConfirm'
13
15
  export {default as EmberboxApp} from './components/EmberboxApp.vue'
14
16
  export {default as AppHeader} from './components/AppHeader.vue'
package/src/poller.ts ADDED
@@ -0,0 +1,125 @@
1
+ import {readonly, ref, type Ref} from 'vue'
2
+
3
+ /** How a tool polls the server. */
4
+ export interface PollingOptions {
5
+ /** Delay between two requests while the server answers. */
6
+ intervalMs?: number
7
+ /** Longest delay the wait grows to after failures. */
8
+ maxIntervalMs?: number
9
+ /**
10
+ * Delay between two requests while the tab is hidden. Without it a hidden tab does not poll at
11
+ * all; with it the tab keeps polling at this slower pace, for state that must stay alive in the
12
+ * background, such as a heartbeat.
13
+ */
14
+ hiddenIntervalMs?: number
15
+ }
16
+
17
+ /** A running poll loop, controlled without a component. */
18
+ export interface Poller {
19
+ /** Whether the last request succeeded. */
20
+ connected: Readonly<Ref<boolean>>
21
+ /** Polls at once and then on schedule, and follows the tab's visibility. */
22
+ start(): void
23
+ /** Ends polling until the next `start`; a request already running still completes, a queued one is dropped. */
24
+ stop(): void
25
+ /**
26
+ * Polls at once and resolves once a request started after this call has completed. On a stopped
27
+ * poller it still fetches once if no request is running, without scheduling more.
28
+ */
29
+ refresh(): Promise<void>
30
+ }
31
+
32
+ /**
33
+ * Whether the page is hidden; outside a browser, while prerendering, it counts as visible.
34
+ *
35
+ * @returns true for a hidden tab
36
+ */
37
+ function pageHidden(): boolean {
38
+ return typeof document !== 'undefined' && document.visibilityState === 'hidden'
39
+ }
40
+
41
+ /**
42
+ * Creates a poll loop. When a request fails, the delay doubles up to `maxIntervalMs`, so a server
43
+ * that is down is not hit every second; the first successful request resets it. A hidden tab
44
+ * pauses, or polls every `hiddenIntervalMs` when that is set; coming back polls at once.
45
+ *
46
+ * Never more than one request runs at a time, so a late older answer cannot overwrite a newer one.
47
+ * A trigger during a running request queues exactly one more request after it. The request may call
48
+ * `stop` itself, for example when the server says the thing polled for no longer exists.
49
+ *
50
+ * @param request fetches the state; an error counts as a lost connection
51
+ * @param options the delays
52
+ * @returns the poller, not yet started
53
+ */
54
+ export function createPoller(request: () => Promise<unknown>, options: PollingOptions = {}): Poller {
55
+ const intervalMs = options.intervalMs ?? 2_000
56
+ const maxIntervalMs = options.maxIntervalMs ?? 30_000
57
+ const hiddenIntervalMs = options.hiddenIntervalMs
58
+ const connected = ref(false)
59
+ let delay = intervalMs
60
+ let timer: ReturnType<typeof setTimeout> | undefined
61
+ let active = false
62
+ let running: Promise<void> | null = null
63
+ let queued: Promise<void> | null = null
64
+
65
+ function schedule(): void {
66
+ clearTimeout(timer)
67
+ if (!active) return
68
+ if (!pageHidden()) {
69
+ timer = setTimeout(() => void poll(), delay)
70
+ } else if (hiddenIntervalMs !== undefined) {
71
+ timer = setTimeout(() => void poll(), Math.max(delay, hiddenIntervalMs))
72
+ }
73
+ }
74
+
75
+ async function once(): Promise<void> {
76
+ clearTimeout(timer)
77
+ try {
78
+ await request()
79
+ connected.value = true
80
+ delay = intervalMs
81
+ } catch {
82
+ connected.value = false
83
+ delay = Math.min(delay * 2, maxIntervalMs)
84
+ }
85
+ }
86
+
87
+ function poll(): Promise<void> {
88
+ if (running) {
89
+ queued ??= running.then(() => {
90
+ queued = null
91
+ return active ? poll() : undefined
92
+ })
93
+ return queued
94
+ }
95
+ running = once().finally(() => {
96
+ running = null
97
+ schedule()
98
+ })
99
+ return running
100
+ }
101
+
102
+ function onVisibilityChange(): void {
103
+ if (pageHidden()) schedule()
104
+ else void poll()
105
+ }
106
+
107
+ return {
108
+ connected: readonly(connected),
109
+ start() {
110
+ if (active) return
111
+ active = true
112
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisibilityChange)
113
+ void poll()
114
+ },
115
+ stop() {
116
+ active = false
117
+ clearTimeout(timer)
118
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibilityChange)
119
+ },
120
+ refresh() {
121
+ delay = intervalMs
122
+ return poll()
123
+ },
124
+ }
125
+ }
package/src/storage.ts ADDED
@@ -0,0 +1,45 @@
1
+ /** Which browser storage entries a tool no longer wants under their current names. */
2
+ export interface StorageCleanUp {
3
+ /** Keys to delete; a key ending in `*` deletes every key starting with the part before it. */
4
+ remove?: string[]
5
+ /** Old key to new key: the value moves over unless the new key already holds one. */
6
+ move?: Record<string, string>
7
+ }
8
+
9
+ /**
10
+ * Whether a stored key matches a key or a prefix pattern ending in `*`.
11
+ *
12
+ * @param key the stored key
13
+ * @param pattern a key or a prefix pattern
14
+ * @returns true when it matches
15
+ */
16
+ function matches(key: string, pattern: string): boolean {
17
+ return pattern.endsWith('*') ? key.startsWith(pattern.slice(0, -1)) : key === pattern
18
+ }
19
+
20
+ /**
21
+ * Tidies a tool's browser storage at startup: moves values from retired keys to their new names and
22
+ * deletes keys the tool no longer reads. A storage the browser refuses, as in some private modes,
23
+ * is left alone.
24
+ *
25
+ * @param cleanUp what to delete and what to move
26
+ * @param storage the storage to tidy, `localStorage` by default
27
+ */
28
+ export function cleanUpStorage(cleanUp: StorageCleanUp, storage?: Storage): void {
29
+ try {
30
+ const target = storage ?? localStorage
31
+ for (const [from, to] of Object.entries(cleanUp.move ?? {})) {
32
+ if (from === to) continue
33
+ const value = target.getItem(from)
34
+ if (value !== null && target.getItem(to) === null) target.setItem(to, value)
35
+ target.removeItem(from)
36
+ }
37
+ const patterns = cleanUp.remove ?? []
38
+ const keys = Array.from({length: target.length}, (_, index) => target.key(index))
39
+ for (const key of keys) {
40
+ if (key !== null && patterns.some(pattern => matches(key, pattern))) target.removeItem(key)
41
+ }
42
+ } catch {
43
+ return
44
+ }
45
+ }