@xeplr/ui-utils 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -186,6 +186,8 @@ url.set({ widget: id, drawer: null })
186
186
 
187
187
  - **Opening or closing** something adds a history entry; **switching** a tab or step, or typing, replaces it (`replace: true`).
188
188
  - `null`, `''`, `false` and a value equal to its default are removed from the URL; `true` is written as `1`.
189
+ - **Writes start from the live address** (with `BrowserRouter`), so a write from a handler that ran after an `await`, or a second write in the same click, never puts back what an earlier write removed. Under a router that doesn't mirror the address (e.g. `MemoryRouter`), writes in one render are chained instead.
190
+ - **In memory, same rules:** with no router above, or `useUrlParams(defaults, { inUrl: false })` / `useUrlState(key, { inUrl: false })`, state lives in the component, e.g. for an editor embedded in a page whose URL and keys belong to that page.
189
191
  - Imported from `src/url/useUrlState.js`, not the package root, because it needs `react-router-dom` (an optional peer) and a consumer without a router shouldn't have to install one. The pure rule is `src/url/urlState.js` (`patchSearch`, `readSearch`), tested in `test/urlState.test.js`.
190
192
 
191
193
  ## DropdownPage
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-utils",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "UI utility components: file upload with progress, snackbar, static data (countries/states)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -31,3 +31,28 @@ export function readSearch(params, key, fallback) {
31
31
  const v = params.get(key)
32
32
  return v === null || v === '' ? (fallback === undefined ? null : fallback) : v
33
33
  }
34
+
35
+ // TWO WRITES IN ONE CLICK MUST BOTH LAND. react-router builds each
36
+ // setSearchParams from the query the last render saw, so a second write in
37
+ // the same handler — from this hook or another one on the page — would start
38
+ // from the old query and undo the first. Each write is chained onto the one
39
+ // before it while the page has not re-rendered: `pending` is the query last
40
+ // written, `pendingFrom` the rendered query it was built on. Once the URL
41
+ // has moved on, they no longer match and are ignored.
42
+ let pending = null
43
+ let pendingFrom = null
44
+
45
+ export function writeFrom(rendered, patch, defaults) {
46
+ const seen = rendered.toString()
47
+ const base = pending !== null && pendingFrom === seen ? pending : rendered
48
+ const next = patchSearch(base, patch, defaults)
49
+ pending = next
50
+ pendingFrom = seen
51
+ return next
52
+ }
53
+
54
+ /** The query a write in this click should read from (see writeFrom). */
55
+ export function pendingBase(rendered) {
56
+ return pending !== null && pendingFrom === rendered.toString() ? pending : rendered
57
+ }
58
+
@@ -1,6 +1,23 @@
1
- import { useCallback } from 'react'
2
- import { useSearchParams } from 'react-router-dom'
3
- import { patchSearch, readSearch } from './urlState.js'
1
+ import { useCallback, useState } from 'react'
2
+ import { useInRouterContext, useSearchParams } from 'react-router-dom'
3
+ import { patchSearch, readSearch, writeFrom, pendingBase } from './urlState.js'
4
+
5
+ // THE QUERY A WRITE STARTS FROM — the LIVE one. react-router builds each
6
+ // setSearchParams from the query the last render saw, so a write from a
7
+ // handler whose closure predates another write — after an `await`, or a
8
+ // second write in the same click — would put back what that write removed (a
9
+ // closed dialog reopening itself). When the router mirrors the browser's
10
+ // address (BrowserRouter), the address bar is the latest query there is; a
11
+ // router that does not (MemoryRouter in a test) falls back to chaining writes
12
+ // within one render (writeFrom).
13
+ function liveBase(rendered, mirrorsBrowser) {
14
+ if (mirrorsBrowser && typeof window !== 'undefined') return new URLSearchParams(window.location.search)
15
+ return pendingBase(rendered)
16
+ }
17
+
18
+ function mirrors(params) {
19
+ return typeof window !== 'undefined' && window.location && ('?' + params.toString()).replace(/^\?$/, '') === window.location.search.replace(/^\?$/, '')
20
+ }
4
21
 
5
22
  /**
6
23
  * Read and write screen state in the URL's query (see urlState.js).
@@ -18,13 +35,32 @@ import { patchSearch, readSearch } from './urlState.js'
18
35
  * '@xeplr/ui-utils/src/url/useUrlState.js' rather than the package root, so a
19
36
  * consumer without a router is not made to install one.
20
37
  */
21
- export function useUrlParams(defaults) {
22
- const [params, setParams] = useSearchParams()
38
+ export function useUrlParams(defaults, options) {
39
+ // IN MEMORY, with the very same rules, when there is no router above (a
40
+ // component that promises to work without one) or the caller says so
41
+ // (`inUrl: false`: an editor embedded in a page whose URL — and keys —
42
+ // belong to that page). Whether a router is there does not change during a
43
+ // component's life, so the hook order below is stable.
44
+ const inRouter = useInRouterContext()
45
+ const inUrl = inRouter && !(options && options.inUrl === false)
46
+ const [local, setLocal] = useState(() => new URLSearchParams())
47
+ // eslint-disable-next-line react-hooks/rules-of-hooks -- fixed per component (see above)
48
+ const router = inRouter ? useSearchParams() : [null, null]
49
+ const params = inUrl ? router[0] : local
50
+ const setParams = router[1]
51
+ // Decided at RENDER, when the router's query and the address bar can be
52
+ // compared like for like — by the time a handler runs, an earlier write may
53
+ // already have moved the address on.
54
+ const browserBacked = inUrl && mirrors(params)
23
55
  const get = useCallback((key) => readSearch(params, key, defaults ? defaults[key] : undefined), [params, defaults])
24
56
  const set = useCallback((patch, opts) => {
25
- setParams((prev) => patchSearch(prev, patch, defaults), { replace: Boolean(opts && opts.replace) })
26
- }, [setParams, defaults])
27
- return { get: get, set: set, params: params }
57
+ if (!inUrl) { setLocal((prev) => patchSearch(prev, patch, defaults)); return }
58
+ const base = liveBase(params, browserBacked)
59
+ const next = browserBacked ? patchSearch(base, patch, defaults) : writeFrom(params, patch, defaults)
60
+ if (next.toString() === base.toString()) return
61
+ setParams(next, { replace: Boolean(opts && opts.replace) })
62
+ }, [inUrl, browserBacked, params, setParams, defaults])
63
+ return { get: get, set: set, params: params, inUrl: inUrl, browserBacked: browserBacked }
28
64
  }
29
65
 
30
66
  /**
@@ -34,16 +70,17 @@ export function useUrlParams(defaults) {
34
70
  */
35
71
  export function useUrlState(key, opts) {
36
72
  const o = opts || {}
37
- const [params, setParams] = useSearchParams()
38
- const value = readSearch(params, key, o.default)
73
+ const defaults = o.default !== undefined ? { [key]: o.default } : undefined
74
+ const url = useUrlParams(defaults, { inUrl: o.inUrl })
75
+ const value = url.get(key)
76
+ const live = url.params
77
+ const set = url.set
39
78
  const setValue = useCallback((v, callOpts) => {
40
79
  const replace = callOpts && callOpts.replace !== undefined ? callOpts.replace : Boolean(o.replace)
41
- setParams((prev) => {
42
- const current = readSearch(prev, key, o.default)
43
- const next = typeof v === 'function' ? v(current) : v
44
- const defaults = o.default !== undefined ? { [key]: o.default } : undefined
45
- return patchSearch(prev, { [key]: next }, defaults)
46
- }, { replace: replace })
47
- }, [setParams, key, o.default, o.replace])
80
+ const current = typeof v === 'function'
81
+ ? readSearch(url.inUrl ? liveBase(live, url.browserBacked) : live, key, o.default)
82
+ : null
83
+ set({ [key]: typeof v === 'function' ? v(current) : v }, { replace: replace })
84
+ }, [set, live, url.inUrl, url.browserBacked, key, o.default, o.replace])
48
85
  return [value, setValue]
49
86
  }