@xeplr/ui-jobs 1.3.0 → 1.5.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/README.md CHANGED
@@ -107,6 +107,7 @@ Every call goes through `authFetch`, which prefixes the base URL `@xeplr/ui-acco
107
107
  | pause / resume | `POST /jobs/:id/pause`, `POST /jobs/:id/resume` |
108
108
  | a run's log lines | `GET /logs?referenceId=<occurrenceId>` — **not** under `apiBase` |
109
109
  | an option list | `GET <source.url>?limit=0` — under `apiBase` |
110
+ | name suggestions | `GET <source.url>?limit=0&<param>=<value>…` for each of the field's `suggestWith` — under `apiBase` |
110
111
  | a job's "After this job" rules | `GET` / `PUT <chainsApiBase>/job-chains/:jobId` with `{ rules, jobName }` — **not** under `apiBase` |
111
112
 
112
113
  `/logs` is the platform's generic log route, not part of `@xeplr/jobs`. A host without it answers 404 and the panel shows an error in place of the log. Log lines are keyed by occurrence id because an action writes under the `referenceId` it is handed.
@@ -134,9 +135,9 @@ Three steps (four with `chainsApiBase`), all reachable at any time, with **Save
134
135
 
135
136
  The period this job ran for passes to the next job by itself. Text that is not JSON, a missing job, or an "otherwise" that is not last is refused before anything is saved; the server checks the meaning and names the rule. An existing job's rules are saved before the job, and a new job's right after it (it needs its id).
136
137
 
137
- An input the action marks `control: 'parameters'` (a procedure's parameters) is shown as rows, not JSON (`ParametersField`, `lib/parametersModel.js`): a parameter's name, and where its value comes from: **Start of the window**, **End of the window** (saved as `{window.from}` / `{window.to}`, which `@xeplr/jobs` fills in with the run's dates) or a **Fixed value**. The choices are the jobs package's run contract (`GET /jobs/run-contract`, `useRunContract`), grouped: **This run** (start / end of the window) and **The job before** (the range it was given and the range it actually used, start / end). A job with no parameters yet starts with the two window rows, and one whose name is left empty is not saved. An input marked `hidden` (the procedure's old **Window**) is shown only when a job already holds one.
138
+ An input the action marks `control: 'parameters'` (a procedure's parameters) is shown as rows, not JSON (`ParametersField`, `lib/parametersModel.js`): a parameter's name, and where its value comes from: **Start of the window**, **End of the window** (saved as `{window.from}` / `{window.to}`, which `@xeplr/jobs` fills in with the run's dates) or a **Fixed value**. The choices are the jobs package's run contract (`GET /jobs/run-contract`, `useRunContract`), grouped: **This run** (start / end of the window) and **The job before** (the range it was given and the range it actually used, start / end). A job with no parameters starts with none (**+ Add parameter**). When the action names a `suggestFrom` source (`db-procedure`: `procedureParams`, asked with the connection, database and procedure), clicking a name box opens a list of the procedure's own parameter names (`NameBox`), minus those already used and narrowed by what is typed; when it cannot have them yet it says which of connection, database and procedure is still to be chosen. A row with neither name nor value is not saved. An input marked `hidden` (the procedure's old **Window**) is shown only when a job already holds one.
138
139
 
139
- With `chainsApiBase`, **Inputs** also has **From the job before**: tickboxes for the inputs another job may fill when it runs this one (the job's `acceptsInputs`). No field is ticked by default, and a field naming a connection is never offered.
140
+ A job's saved `acceptsInputs` (what the job before may fill) is kept as it is but no longer edited here: a job takes what it needs from the job before through its parameters. The **After this job** rules offer a condition, the job to run and values to **carry** for later jobs.
140
141
 
141
142
  A new job with a schedule defaults to **Paused**, so it can be written now and started later. A job with no schedule is saved as `ready` and runs only when triggered.
142
143
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-jobs",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "The screens for @xeplr/jobs — schedule, run, pause and watch jobs — as routes a host app registers, or a standalone app",
5
5
  "type": "module",
6
6
  "main": "src/index.jsx",
package/src/api/jobs.js CHANGED
@@ -90,6 +90,22 @@ export function hasOptionSource(kind) {
90
90
  * be narrowed — databases on the chosen connection, rather than every database
91
91
  * on every connection.
92
92
  */
93
+ /**
94
+ * Fetch suggestions from an option source, asked with several values at once
95
+ * — `query` is { param: value }. Answers the list of values (strings), empty
96
+ * when the source is not configured or something it needs is not chosen yet.
97
+ */
98
+ export async function fetchSuggestions(kind, query) {
99
+ const src = _optionSources[kind]
100
+ if (!src) return []
101
+ const pairs = Object.entries(query || {})
102
+ if (pairs.some(([, v]) => v === undefined || v === null || v === '')) return []
103
+ const q = pairs.map(([k, v]) => `&${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('')
104
+ const res = await authFetch(url(`${src.url}?limit=0${q}`))
105
+ const list = (res && res[src.key || 'dataArray']) || []
106
+ return list.map((o) => String(o[src.value || 'value'])).filter(Boolean)
107
+ }
108
+
93
109
  export async function fetchOptions(kind, filter) {
94
110
  const src = _optionSources[kind]
95
111
  if (!src) return []
@@ -65,18 +65,8 @@ export default function JobChainSection({ chain, jobs, jobId }) {
65
65
  </select>
66
66
  </div>
67
67
 
68
- <details className="jb-advanced" open={Boolean(row.inputs || row.carry)}>
68
+ <details className="jb-advanced" open={Boolean(row.carry)}>
69
69
  <summary>Pass values on <span className="jb-dim">— optional</span></summary>
70
- <div className="jb-field">
71
- <label htmlFor={`jb-chain-inputs-${i}`}>Inputs of the next job <span className="jb-type">· JSON</span></label>
72
- <textarea id={`jb-chain-inputs-${i}`} className="jb-chain-json" rows={3}
73
- placeholder={'{ "region": "{output.region}" }'} value={row.inputs}
74
- onChange={(e) => chain.updateRow(i, { inputs: e.target.value })} />
75
- <span className="jb-help">
76
- Only inputs the next job accepts (its Inputs step lists them). Leave out
77
- <code className="jb-code">window</code> to pass this job's period on unchanged.
78
- </span>
79
- </div>
80
70
  <div className="jb-field">
81
71
  <label htmlFor={`jb-chain-carry-${i}`}>Carry for later jobs <span className="jb-type">· JSON</span></label>
82
72
  <textarea id={`jb-chain-carry-${i}`} className="jb-chain-json" rows={3}
@@ -18,3 +18,18 @@
18
18
  .jb-param { grid-template-columns: 1fr auto; }
19
19
  .jb-param-arrow { display: none; }
20
20
  }
21
+ /* The name box and its list, which opens on click. */
22
+ .jb-namebox { position: relative; min-width: 0; }
23
+ .jb-namebox-list {
24
+ position: absolute; z-index: 20; top: calc(100% + 4px); left: 0; right: 0; margin: 0; padding: 4px;
25
+ list-style: none; max-height: 220px; overflow: auto;
26
+ background: var(--surface, #ffffff); border: 1px solid var(--hair, #e2e1d9); border-radius: 8px;
27
+ box-shadow: 0 6px 18px rgba(0, 0, 0, .12);
28
+ }
29
+ .jb-namebox-list li {
30
+ padding: 6px 8px; border-radius: 6px; cursor: pointer;
31
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; color: var(--ink, #1a1a19);
32
+ }
33
+ .jb-namebox-list li:hover, .jb-namebox-list li[aria-selected="true"] { background: var(--xeplr-hover, #f0efe9); }
34
+ .jb-namebox-list .jb-namebox-note { cursor: default; font-family: inherit; font-size: 12px; color: var(--muted, #6b6a63); }
35
+ .jb-namebox-list .jb-namebox-note:hover { background: none; }
@@ -1,5 +1,6 @@
1
- import { useState } from 'react'
2
- import { FIXED, groupedChoices, rowsFromText, rowsToText, sourceOf, valueForSource } from '../lib/parametersModel.js'
1
+ import { useEffect, useState } from 'react'
2
+ import { fetchSuggestions } from '../api/jobs.js'
3
+ import { FIXED, groupedChoices, rowsFromText, rowsToText, sourceOf, unusedNames, valueForSource } from '../lib/parametersModel.js'
3
4
  import './ParametersField.css'
4
5
 
5
6
  /**
@@ -14,11 +15,73 @@ import './ParametersField.css'
14
15
  * @param {string} props.value saved JSON text
15
16
  * @param {Function} props.onChange
16
17
  * @param {object[]} props.contract what every run receives (useRunContract)
18
+ * @param {object} props.inputs the job's other inputs — what the name
19
+ * suggestions are asked with (field.suggestWith)
17
20
  */
18
- export default function ParametersField({ field, value, onChange, contract }) {
21
+ // What each input the suggestions depend on is called, for "choose the … above".
22
+ const WHAT = { connectionInfoId: 'connection', dbInfoId: 'database', procedure: 'procedure' }
23
+
24
+ /**
25
+ * A name box whose list OPENS ON CLICK — the procedure's parameter names,
26
+ * narrowed by what is typed — and says why when it has none. A plain
27
+ * <datalist> shows nothing until something is typed in several browsers.
28
+ */
29
+ function NameBox({ label, value, names, emptyNote, onChange }) {
30
+ const [open, setOpen] = useState(false)
31
+ const typed = String(value || '').trim().toLowerCase()
32
+ const shown = names.filter((n) => !typed || n.toLowerCase().includes(typed))
33
+ return (
34
+ <div className="jb-namebox">
35
+ <input aria-label={label} className="jb-param-name" value={value} placeholder="name" autoComplete="off"
36
+ role="combobox" aria-expanded={open}
37
+ onFocus={() => setOpen(true)} onClick={() => setOpen(true)}
38
+ onBlur={() => setOpen(false)}
39
+ onKeyDown={(e) => { if (e.key === 'Escape') setOpen(false) }}
40
+ onChange={(e) => { onChange(e.target.value); setOpen(true) }} />
41
+ {open && (
42
+ <ul className="jb-namebox-list" role="listbox">
43
+ {shown.length ? shown.map((n) => (
44
+ <li key={n} role="option" aria-selected={n === value}
45
+ onMouseDown={(e) => { e.preventDefault(); onChange(n); setOpen(false) }}>{n}</li>
46
+ )) : (
47
+ <li className="jb-namebox-note">{names.length ? 'No parameter matches what is typed.' : (emptyNote || 'Type the name.')}</li>
48
+ )}
49
+ </ul>
50
+ )}
51
+ </div>
52
+ )
53
+ }
54
+
55
+ export default function ParametersField({ field, value, onChange, contract, inputs }) {
19
56
  const [rows, setRows] = useState(() => rowsFromText(value, contract))
20
57
  const id = `jb-in-${field.name}`
21
58
 
59
+ // THE PROCEDURE'S OWN PARAMETER NAMES, offered when a name box is clicked —
60
+ // asked again whenever the connection, database or procedure changes.
61
+ const query = Object.fromEntries(Object.entries(field.suggestWith || {}).map(([k, from]) => [k, inputs?.[from]]))
62
+ const queryKey = JSON.stringify(query)
63
+ // What the name list says when it has nothing: which choice above is still
64
+ // missing, that it is looking, or that the procedure has none.
65
+ const missing = Object.entries(field.suggestWith || {}).filter(([k]) => !query[k]).map(([, from]) => WHAT[from] || from)
66
+ const [names, setNames] = useState([])
67
+ const [state, setState] = useState('idle')
68
+ useEffect(() => {
69
+ if (!field.suggestFrom) return undefined
70
+ const q = JSON.parse(queryKey)
71
+ if (Object.values(q).some((v) => v === undefined || v === null || v === '')) { setNames([]); setState('idle'); return undefined }
72
+ let live = true
73
+ setState('loading')
74
+ fetchSuggestions(field.suggestFrom, q)
75
+ .then((n) => { if (live) { setNames(n); setState('ready') } })
76
+ .catch(() => { if (live) { setNames([]); setState('failed') } })
77
+ return () => { live = false }
78
+ }, [field.suggestFrom, queryKey])
79
+ const emptyNote = !field.suggestFrom ? null
80
+ : missing.length ? `Choose the ${missing.join(', ')} above to see this procedure's parameters.`
81
+ : state === 'loading' ? 'Reading the procedure\'s parameters…'
82
+ : state === 'failed' ? 'Could not read the procedure\'s parameters. Type the name.'
83
+ : 'This procedure has no parameters to fill, or it was not found. Type the name.'
84
+
22
85
  // Saved text that is not a list (typed by hand before this control
23
86
  // existed) is shown as it is rather than guessed at.
24
87
  if (rows === null) {
@@ -52,9 +115,9 @@ export default function ParametersField({ field, value, onChange, contract }) {
52
115
  const source = sourceOf(r.value, contract)
53
116
  return (
54
117
  <div key={i} className="jb-param">
55
- <input aria-label={`Parameter ${i + 1} name`} className="jb-param-name" value={r.name}
56
- placeholder={source === FIXED ? 'name' : 'e.g. startDate'}
57
- onChange={(e) => patchRow(i, { name: e.target.value })} />
118
+ <NameBox label={`Parameter ${i + 1} name`} value={r.name}
119
+ names={unusedNames(names, rows, i)} emptyNote={emptyNote}
120
+ onChange={(name) => patchRow(i, { name })} />
58
121
  <span className="jb-param-arrow" aria-hidden="true">←</span>
59
122
  <select aria-label={`Parameter ${i + 1} value`} value={source}
60
123
  onChange={(e) => patchRow(i, { value: valueForSource(e.target.value, r.value, contract) })}>
@@ -77,8 +140,8 @@ export default function ParametersField({ field, value, onChange, contract }) {
77
140
  </div>
78
141
  <button type="button" className="jb-param-add" onClick={() => update([...rows, { name: '', value: '' }])}>+ Add parameter</button>
79
142
  <span className="jb-help">
80
- The name is the procedure's own parameter name. On MySQL, parameters go by position, so keep
81
- them in the order the procedure declares them.
143
+ Click a name box to pick one of the procedure's parameters, or type your own.
144
+ {' '}On MySQL, parameters go by position, so keep them in the order the procedure declares them.
82
145
  </span>
83
146
  </div>
84
147
  )
@@ -35,36 +35,35 @@ export function groupedChoices(contract) {
35
35
  }
36
36
 
37
37
  /**
38
- * Saved text → rows. A job with no parameters yet starts with one row for
39
- * this run's window start and one for its end, named by the person — the
40
- * period is what nearly every scheduled procedure takes. The job before's
41
- * ranges are in every row's dropdown, but not rows of their own.
38
+ * Saved text → rows. A job with no parameters yet has none: the person adds
39
+ * them, picking each name from the procedure's own (see ParametersField).
42
40
  */
43
41
  export function rowsFromText(text, contract) {
44
42
  let list = []
45
43
  try { list = text ? JSON.parse(text) : [] } catch (e) { list = null }
46
44
  if (!Array.isArray(list)) return null
47
- if (!list.length) {
48
- return (contract || []).filter((c) => /^window\./.test(c.key))
49
- .map((c) => ({ name: '', value: bindingFor(c.key), starter: true }))
50
- }
51
45
  return list.map((p) => (p && typeof p === 'object' && !Array.isArray(p)
52
46
  ? { name: p.name == null ? '' : String(p.name), value: p.value == null ? '' : p.value }
53
47
  : { name: '', value: p == null ? '' : p, bare: true }))
54
48
  }
55
49
 
56
50
  /**
57
- * Rows → the text the form saves. A starter row nobody named is left out, so
58
- * a procedure with no date parameters gets none. A row with no name is kept
59
- * as a bare (positional) value.
51
+ * Rows → the text the form saves. A row with no name is kept as a bare
52
+ * (positional) value; a row with neither name nor value is left out.
60
53
  */
61
54
  export function rowsToText(rows) {
62
55
  const list = (rows || [])
63
- .filter((r) => !(r.starter && !String(r.name || '').trim()))
56
+ .filter((r) => String(r.name || '').trim() || (r.value !== '' && r.value != null))
64
57
  .map((r) => (String(r.name || '').trim() ? { name: String(r.name).trim(), value: r.value } : r.value))
65
58
  return list.length ? JSON.stringify(list, null, 2) : ''
66
59
  }
67
60
 
61
+ /** Suggested names not already used by another row. */
62
+ export function unusedNames(names, rows, index) {
63
+ const taken = new Set((rows || []).filter((_, i) => i !== index).map((r) => String(r.name || '').trim()).filter(Boolean))
64
+ return (names || []).filter((n) => !taken.has(n))
65
+ }
66
+
68
67
  /** A row's value when its source changes: a binding, or empty fixed text. */
69
68
  export function valueForSource(source, current, contract) {
70
69
  if (source === FIXED) return sourceOf(current, contract) === FIXED ? current : ''
@@ -15,7 +15,7 @@ import JobChainSection from '../components/JobChainSection.jsx'
15
15
  import ParametersField from '../components/ParametersField.jsx'
16
16
  import { useRunContract } from '../useRunContract.js'
17
17
  import { useJobChainController } from '../useJobChainController.js'
18
- import { acceptableFields, toggleAccepted } from '../lib/jobChainModel.js'
18
+ import { acceptableFields } from '../lib/jobChainModel.js'
19
19
  import './Jobs.css'
20
20
 
21
21
  // SCHEDULED JOBS — @xeplr/jobs, in this product's chrome.
@@ -448,7 +448,7 @@ function ActionInput({ field, value, onChange, inputs, contract }) {
448
448
 
449
449
  // Rows rather than JSON, for an input the action marks as parameters.
450
450
  if (field.control === 'parameters') {
451
- return <ParametersField field={field} value={value} onChange={onChange} contract={contract || []} />
451
+ return <ParametersField field={field} value={value} onChange={onChange} contract={contract || []} inputs={inputs} />
452
452
  }
453
453
  const common = { id, value, onChange: (e) => onChange(e.target.value) }
454
454
 
@@ -536,7 +536,8 @@ function JobEditor({ job, jobs, actions, onCancel, onSaved }) {
536
536
  Object.entries(job?.inputs || {}).map(([k, v]) => [k, toFieldValue(v)])
537
537
  ),
538
538
  // Inputs the job BEFORE this one in a chain may fill (@xeplr/jobs'
539
- // acceptsInputs). `window` always may, so it is not listed.
539
+ // acceptsInputs). No longer edited here — a job takes what it needs from
540
+ // the job before through its parameters — but kept as saved.
540
541
  acceptsInputs: Array.isArray(job?.acceptsInputs) ? job.acceptsInputs : []
541
542
  }))
542
543
  const [saving, setSaving] = useState(false)
@@ -697,35 +698,9 @@ function JobEditor({ job, jobs, actions, onCancel, onSaved }) {
697
698
  onChange={(v) => patch({ inputs: { ...draft.inputs, [f.name]: v } })}
698
699
  />
699
700
  )
700
- const acceptable = acceptableFields(fields)
701
701
  return (
702
702
  <>
703
703
  <div className="jb-grid">{primary.map(render)}</div>
704
- {chain.enabled && acceptable.length > 0 && (
705
- /* WHAT THE JOB BEFORE THIS ONE MAY FILL. Off for every
706
- field until ticked: a chain may otherwise only pass the
707
- period (window), never this job's SQL or connection. */
708
- <details className="jb-advanced" open={draft.acceptsInputs.length > 0}>
709
- <summary>
710
- From the job before
711
- <span className="jb-dim">
712
- {' — '}
713
- {draft.acceptsInputs.length ? draft.acceptsInputs.map((n) => fieldLabel(acceptable.find((f) => f.name === n) || { name: n })).join(' · ') : 'only the period'}
714
- </span>
715
- </summary>
716
- <p className="jb-help">
717
- When another job runs this one, it always passes the period it ran for. Tick the inputs
718
- it may also fill; everything else stays as saved here.
719
- </p>
720
- {acceptable.map((f) => (
721
- <label key={f.name} className="jb-chain-toggle">
722
- <input type="checkbox" checked={draft.acceptsInputs.includes(f.name)}
723
- onChange={(e) => patch({ acceptsInputs: toggleAccepted(draft.acceptsInputs, f.name, e.target.checked) })} />
724
- {fieldLabel(f)}
725
- </label>
726
- ))}
727
- </details>
728
- )}
729
704
  {advanced.length > 0 && (
730
705
  /* COLLAPSED, NOT HIDDEN. The summary names every field in
731
706
  here and its current value, so closing it never conceals