@xeplr/ui-utils 1.1.1 → 1.1.3
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 +26 -0
- package/package.json +1 -1
- package/src/index.js +4 -0
- package/src/optionSources/optionSources.js +66 -0
- package/src/url/useUrlState.js +54 -15
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
|
|
@@ -498,6 +500,30 @@ Event contract: `{ key, continue: true | false, status?, data }`. `continue: fal
|
|
|
498
500
|
|
|
499
501
|
With no source attached, every notifier renders `idle` and nothing else.
|
|
500
502
|
|
|
503
|
+
## Option sources: `createOptionSources`
|
|
504
|
+
|
|
505
|
+
An action's input can name a KIND of thing to choose from (`optionsFrom: 'connections'`). The host says once where each kind lives, and a screen offers a list instead of a box to type an id into. Used by `@xeplr/ui-jobs`' job editor and X-Flow's step editor.
|
|
506
|
+
|
|
507
|
+
```js
|
|
508
|
+
import { createOptionSources } from '@xeplr/ui-utils'
|
|
509
|
+
import { authFetch } from '@xeplr/ui-account'
|
|
510
|
+
|
|
511
|
+
const sources = createOptionSources({
|
|
512
|
+
connections: { url: '/connectioninfo', value: 'id', label: 'label' },
|
|
513
|
+
databases: { url: '/dbinfo', value: 'id', label: 'dbName' },
|
|
514
|
+
tables: { url: '/warehouse/tables', value: 'id', label: 'name', key: 'tables' }
|
|
515
|
+
}, (path) => authFetch(path))
|
|
516
|
+
|
|
517
|
+
sources.has('connections') // true: show a list
|
|
518
|
+
await sources.fetchOptions('connections') // [{ value, label }]
|
|
519
|
+
await sources.fetchOptions('databases', { name: 'connectionId', value: 'c1', clientKey: 'connectionId' })
|
|
520
|
+
await sources.fetchSuggestions('procedureParams', { connectionId, procedure }) // ['from', 'to']
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
- **A kind nobody configured** is `has() === false`: show a text box. An empty dropdown looks broken.
|
|
524
|
+
- **`key`** names the list in a hand-written endpoint's answer (default `dataArray`). Guessing it wrong would show an empty list and no error.
|
|
525
|
+
- **Pure, no React, no login of its own:** the host passes its own fetch.
|
|
526
|
+
|
|
501
527
|
## raiseSnackbar, raiseConfirm, raiseChoice
|
|
502
528
|
|
|
503
529
|
```js
|
package/package.json
CHANGED
package/src/index.js
CHANGED
|
@@ -237,3 +237,7 @@ export { useSettingsTreeController } from './panel/useSettingsTreeController.js'
|
|
|
237
237
|
export { EXPANDERS_RULES, SETTINGS_TREE_RULES } from './panel/validateDesign.js';
|
|
238
238
|
export { PanelSection, PanelField, ExpandersSample, SettingsTreeSample } from './panel/designs/index.js';
|
|
239
239
|
export { ExpandersPage, SettingsTreePage } from './panel/pages.jsx';
|
|
240
|
+
|
|
241
|
+
// Option sources — where a KIND of thing an input names (`optionsFrom`) is
|
|
242
|
+
// listed. Shared by @xeplr/ui-jobs and X-Flow's step editor.
|
|
243
|
+
export { createOptionSources } from './optionSources/optionSources.js';
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// WHERE A KIND OF THING IS LISTED, for an input that says `optionsFrom`.
|
|
2
|
+
//
|
|
3
|
+
// An action's input can name a KIND of thing to choose from
|
|
4
|
+
// (`optionsFrom: 'connections'`), and the host says once where that kind
|
|
5
|
+
// lives: { connections: { url: '/connectioninfo', value: 'id', label: 'label' } }.
|
|
6
|
+
// A screen then offers a list to pick from instead of a box to type a
|
|
7
|
+
// 25-character id into. This module never learns what a connection is, nor
|
|
8
|
+
// which URL serves one: it knows only "fetch this list, show labels, store ids".
|
|
9
|
+
//
|
|
10
|
+
// One copy, used by @xeplr/ui-jobs' job editor and X-Flow's step editor.
|
|
11
|
+
//
|
|
12
|
+
// Nothing configured for a kind → `has(kind)` is false, and the screen shows a
|
|
13
|
+
// plain text box: an empty dropdown looks broken, a text box is simply what
|
|
14
|
+
// you have when there is no catalogue to pick from.
|
|
15
|
+
//
|
|
16
|
+
// Pure: no React. `fetchJson(path)` is the host's own authenticated fetch
|
|
17
|
+
// (@xeplr/ui-account's authFetch), so this package never learns about logins.
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} sources { kind: { url, value?='id', label?, key?='dataArray' } }
|
|
21
|
+
* @param {Function} fetchJson (path) → Promise of the parsed answer
|
|
22
|
+
*/
|
|
23
|
+
export function createOptionSources(sources, fetchJson) {
|
|
24
|
+
const all = sources || {}
|
|
25
|
+
|
|
26
|
+
function has(kind) {
|
|
27
|
+
return Boolean(kind && all[kind])
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* One list, as [{ value, label }]. `filter` narrows a dependent list — the
|
|
32
|
+
* databases on the chosen connection — as a query parameter, and, with
|
|
33
|
+
* `clientKey`, again in the browser for an endpoint that ignores it.
|
|
34
|
+
*/
|
|
35
|
+
async function fetchOptions(kind, filter) {
|
|
36
|
+
const src = all[kind]
|
|
37
|
+
if (!src) return []
|
|
38
|
+
const q = filter && filter.value ? `&${encodeURIComponent(filter.name)}=${encodeURIComponent(filter.value)}` : ''
|
|
39
|
+
const res = await fetchJson(`${src.url}?limit=0${q}`)
|
|
40
|
+
// `dataArray` is what a generic route answers; a hand-written endpoint
|
|
41
|
+
// answers with its own key, which the host names. Guessing wrong would
|
|
42
|
+
// give an empty list and no error, which reads as "you have none".
|
|
43
|
+
const rows = (res && res[src.key || 'dataArray']) || []
|
|
44
|
+
return rows
|
|
45
|
+
.filter((r) => (filter && filter.clientKey ? r[filter.clientKey] === filter.value : true))
|
|
46
|
+
.map((r) => ({ value: r[src.value || 'id'], label: r[src.label] || r[src.value || 'id'] }))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Suggestions asked with several values at once (`query` is { param: value }),
|
|
51
|
+
* as a list of strings. Empty when the source is not configured or something
|
|
52
|
+
* it needs is not chosen yet.
|
|
53
|
+
*/
|
|
54
|
+
async function fetchSuggestions(kind, query) {
|
|
55
|
+
const src = all[kind]
|
|
56
|
+
if (!src) return []
|
|
57
|
+
const pairs = Object.entries(query || {})
|
|
58
|
+
if (pairs.some(([, v]) => v === undefined || v === null || v === '')) return []
|
|
59
|
+
const q = pairs.map(([k, v]) => `&${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('')
|
|
60
|
+
const res = await fetchJson(`${src.url}?limit=0${q}`)
|
|
61
|
+
const list = (res && res[src.key || 'dataArray']) || []
|
|
62
|
+
return list.map((o) => String(o[src.value || 'value'])).filter(Boolean)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return { has, fetchOptions, fetchSuggestions }
|
|
66
|
+
}
|
package/src/url/useUrlState.js
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
|
-
import { useCallback } from 'react'
|
|
2
|
-
import { useSearchParams } from 'react-router-dom'
|
|
3
|
-
import { readSearch, writeFrom, pendingBase } 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 { readSearch, writeFrom, pendingBase } 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
|
-
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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,14 +70,17 @@ export function useUrlParams(defaults) {
|
|
|
34
70
|
*/
|
|
35
71
|
export function useUrlState(key, opts) {
|
|
36
72
|
const o = opts || {}
|
|
37
|
-
const [
|
|
38
|
-
const
|
|
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
|
-
const current =
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}, [
|
|
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])
|
|
46
85
|
return [value, setValue]
|
|
47
86
|
}
|