@modelform/react-native 0.13.0 → 0.14.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
@@ -148,6 +148,30 @@ const speech: SpeechRecognizer = {
148
148
  forms by other means. The native recognizer is shared, so a real adapter should also wait for the previous session's
149
149
  `end` before starting the next one; otherwise that late event ends the new session too.
150
150
 
151
+ ### Filling the whole form by voice
152
+
153
+ With a recognizer, the form also gets a microphone beside Save. Say several values in one go ("weight seventy two
154
+ point five, slept seven hours, mood four, went for a swim"), tap again to stop, and the form fills what it understood.
155
+ Filled inputs are outlined and marked "From voice" until edited; nothing is recorded until Save, and Undo puts the form
156
+ back as it was before the fill. Listening is `continuous`, so pauses don't cut it off: an adapter should pass that on
157
+ (expo-speech-recognition takes `continuous: true`) and deliver the whole transcript as one final `onText` when it
158
+ stops.
159
+
160
+ What was said goes to a `FormFiller`, `(form, said) => Promise<FillResult>`. The default, `ruleFiller`, needs no model:
161
+ a value is what follows a field's name, and fields not named are found by unit ("72.5 kilos") or by a choice only one
162
+ field has. To use a model, wrap whatever generates text in `modelFiller`; it prompts with `fillPrompt`, passes
163
+ `fillSchema` for guided generation, reads the reply with `readFill` (so a model can only enter what typing could), and
164
+ with a fallback fills what the model left out:
165
+
166
+ ```tsx
167
+ import { modelFiller, ruleFiller } from '@modelform/react-native';
168
+
169
+ const filler = modelFiller((instructions, prompt, schema) => myModel.generate({ instructions, prompt, schema }), ruleFiller);
170
+ <InputForm dashboard={form} store={store} speech={speech} filler={filler} />;
171
+ ```
172
+
173
+ `filler={null}` turns whole-form filling off and keeps per-field dictation. Groups' fields and counters aren't filled.
174
+
151
175
  ## Bundled dashboards
152
176
 
153
177
  `modelform dashboards [dir] [--watch]` writes an `index.ts` that imports every `.json` file in a folder, so
@@ -1807,6 +1807,241 @@ function dictationHints(panel, choices2) {
1807
1807
  return out;
1808
1808
  }
1809
1809
 
1810
+ // src/core/formFill.ts
1811
+ var choicesOf = (p, runtime) => (p.options.choicesFrom ? runtime[p.options.choicesFrom] : p.options.choices) ?? [];
1812
+ function fillForm(dashboard, choices2 = {}) {
1813
+ const fields = [];
1814
+ const panels = {};
1815
+ for (const p of plainInputPanels(dashboard)) {
1816
+ const o = p.options;
1817
+ if (p.type === "input-counter" || panels[o.metric]) continue;
1818
+ const base = { key: o.metric, label: p.title || o.metric };
1819
+ let field2;
1820
+ switch (p.type) {
1821
+ case "input-number":
1822
+ field2 = { ...base, type: "number", unit: o.unit, min: o.min, max: o.max };
1823
+ break;
1824
+ case "input-rating":
1825
+ field2 = { ...base, type: "number", min: Math.round(o.min ?? 1), max: Math.round(o.max ?? 5) };
1826
+ break;
1827
+ case "input-slider":
1828
+ field2 = { ...base, type: "number", unit: o.unit, min: o.min ?? 0, max: o.max ?? 10, choices: o.labels?.length ? o.labels : void 0 };
1829
+ break;
1830
+ case "input-duration":
1831
+ field2 = { ...base, type: "duration" };
1832
+ break;
1833
+ case "input-select": {
1834
+ const labels = choicesOf(p, choices2).map((c) => c.label);
1835
+ if (!labels.length) continue;
1836
+ field2 = { ...base, type: o.multi ? "choices" : "choice", choices: labels };
1837
+ break;
1838
+ }
1839
+ case "input-toggle":
1840
+ field2 = { ...base, type: "boolean" };
1841
+ break;
1842
+ case "input-text":
1843
+ field2 = { ...base, type: "text" };
1844
+ break;
1845
+ default:
1846
+ continue;
1847
+ }
1848
+ fields.push(Object.fromEntries(Object.entries(field2).filter(([, v]) => v !== void 0)));
1849
+ panels[o.metric] = p;
1850
+ }
1851
+ return { fields, panels, choices: choices2 };
1852
+ }
1853
+ function describe(f) {
1854
+ const range = f.min != null && f.max != null ? `, from ${f.min} to ${f.max}` : f.min != null ? `, ${f.min} or more` : f.max != null ? `, at most ${f.max}` : "";
1855
+ switch (f.type) {
1856
+ case "number":
1857
+ return `a number${f.unit ? ` in ${f.unit}` : ""}${range}${f.choices ? ` (${f.choices.join(" \u2026 ")} along the scale)` : ""}`;
1858
+ case "duration":
1859
+ return "a duration in seconds";
1860
+ case "choice":
1861
+ return `one of: ${f.choices.map((c) => JSON.stringify(c)).join(", ")}`;
1862
+ case "choices":
1863
+ return `a list of any of: ${f.choices.map((c) => JSON.stringify(c)).join(", ")}`;
1864
+ case "boolean":
1865
+ return "true or false";
1866
+ case "text":
1867
+ return "text, in the user\u2019s words";
1868
+ }
1869
+ }
1870
+ function fillSchema(form) {
1871
+ const properties = {};
1872
+ for (const f of form.fields) {
1873
+ const description = `${f.label}: ${describe(f)}`;
1874
+ switch (f.type) {
1875
+ case "number":
1876
+ case "duration":
1877
+ properties[f.key] = { type: "number", description, ...f.min != null && { minimum: f.min }, ...f.max != null && { maximum: f.max } };
1878
+ break;
1879
+ case "choice":
1880
+ properties[f.key] = { type: "string", enum: f.choices, description };
1881
+ break;
1882
+ case "choices":
1883
+ properties[f.key] = { type: "array", items: { type: "string", enum: f.choices }, description };
1884
+ break;
1885
+ case "boolean":
1886
+ properties[f.key] = { type: "boolean", description };
1887
+ break;
1888
+ case "text":
1889
+ properties[f.key] = { type: "string", description };
1890
+ break;
1891
+ }
1892
+ }
1893
+ return { type: "object", properties, required: [], additionalProperties: false };
1894
+ }
1895
+ function fillPrompt(form, said) {
1896
+ const instructions = [
1897
+ "You fill in a form from what the user said.",
1898
+ "Reply with one JSON object and nothing else. Its keys are field keys from the list below.",
1899
+ "Only include fields the user gave a value for; leave the others out. Never guess or make up values.",
1900
+ "Numbers are plain numbers without units. Choices use the exact text listed."
1901
+ ].join(" ");
1902
+ const list = form.fields.map((f) => `- ${f.key}: ${f.label}, ${describe(f)}`).join("\n");
1903
+ const example = form.fields.find((f) => f.type === "number");
1904
+ const prompt = [
1905
+ `Fields:
1906
+ ${list}`,
1907
+ example ? `Example: if the user said "${example.label.toLowerCase()} 3" the answer is {"${example.key}": 3}` : "",
1908
+ `The user said: "${said.replace(/"/g, "'")}"`,
1909
+ "JSON:"
1910
+ ].filter(Boolean).join("\n\n");
1911
+ return { instructions, prompt };
1912
+ }
1913
+ function parseFillAnswer(answer) {
1914
+ if (answer && typeof answer === "object" && !Array.isArray(answer)) return answer;
1915
+ if (typeof answer !== "string") return null;
1916
+ const start = answer.indexOf("{");
1917
+ const end = answer.lastIndexOf("}");
1918
+ if (start < 0 || end <= start) return null;
1919
+ try {
1920
+ const v = JSON.parse(answer.slice(start, end + 1));
1921
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
1922
+ } catch {
1923
+ return null;
1924
+ }
1925
+ }
1926
+ function asSaid(v) {
1927
+ if (v == null) return null;
1928
+ if (typeof v === "boolean") return v ? "yes" : "no";
1929
+ if (typeof v === "number") return Number.isFinite(v) ? String(v) : null;
1930
+ if (typeof v === "string") return v.trim() || null;
1931
+ if (Array.isArray(v)) return v.map(asSaid).filter(Boolean).join(", ") || null;
1932
+ return null;
1933
+ }
1934
+ function readFill(form, answer) {
1935
+ const result = { values: {}, problems: [] };
1936
+ const obj = parseFillAnswer(answer);
1937
+ if (!obj) return { values: {}, problems: [{ key: "", problem: "The answer wasn\u2019t a JSON object" }] };
1938
+ for (const f of form.fields) {
1939
+ const raw = obj[f.key];
1940
+ const panel = form.panels[f.key];
1941
+ const choices2 = choicesOf(panel, form.choices);
1942
+ if (panel.type === "input-select" && !panel.options.multi) {
1943
+ const byValue = choices2.find((c) => c.value === raw);
1944
+ if (byValue) {
1945
+ result.values[f.key] = byValue.value;
1946
+ continue;
1947
+ }
1948
+ }
1949
+ const said = asSaid(raw);
1950
+ if (said == null) continue;
1951
+ const r = spokenValue(panel, said, null, choices2);
1952
+ if ("value" in r) result.values[f.key] = r.value;
1953
+ else result.problems.push({ key: f.key, problem: r.problem });
1954
+ }
1955
+ return result;
1956
+ }
1957
+ var UNIT_WORDS = {
1958
+ kg: ["kg", "kgs", "kilo", "kilos", "kilogram", "kilograms"],
1959
+ lb: ["lb", "lbs", "pound", "pounds"],
1960
+ h: ["h", "hr", "hrs", "hour", "hours"],
1961
+ min: ["min", "mins", "minute", "minutes"],
1962
+ s: ["s", "sec", "secs", "second", "seconds"],
1963
+ km: ["km", "kms", "kilometer", "kilometers", "kilometre", "kilometres", "k"],
1964
+ mi: ["mi", "mile", "miles"],
1965
+ m: ["m", "meter", "meters", "metre", "metres"]
1966
+ };
1967
+ var NUMBER_WORD = "(?:-?\\d+(?:[.,]\\d+)?|zero|oh|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|point|and|a|half|quarter|minus)";
1968
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1969
+ function namesOf(f) {
1970
+ const names = /* @__PURE__ */ new Set([f.label.toLowerCase(), f.key.toLowerCase().replace(/[-_]+/g, " ")]);
1971
+ return [...names].filter((n) => n.trim().length > 1);
1972
+ }
1973
+ var LEAD = /^[\s,:;.-]*(?:(?:is|was|were|of|at|about|around|to|=)\b[\s,:;.-]*)*/i;
1974
+ function ruleFill(form, said) {
1975
+ const lower = said.toLowerCase();
1976
+ const hits = [];
1977
+ for (const f of form.fields)
1978
+ for (const name of namesOf(f)) {
1979
+ const re = new RegExp(`(?<![\\p{L}\\p{N}])${escape(name)}(?![\\p{L}\\p{N}])`, "gu");
1980
+ for (const m of lower.matchAll(re)) {
1981
+ const at = m.index;
1982
+ const end = at + m[0].length;
1983
+ if (!hits.some((h) => at < h.end && end > h.at)) hits.push({ key: f.key, at, end });
1984
+ }
1985
+ }
1986
+ hits.sort((a, b) => a.at - b.at);
1987
+ const segments = {};
1988
+ const used = [];
1989
+ hits.forEach((h, i) => {
1990
+ const stop = i + 1 < hits.length ? hits[i + 1].at : said.length;
1991
+ if (h.key in segments) return;
1992
+ segments[h.key] = said.slice(h.end, stop).replace(LEAD, "").replace(/[\s,;.]+$/, "");
1993
+ used.push([h.at, stop]);
1994
+ });
1995
+ const answer = {};
1996
+ for (const f of form.fields) if (segments[f.key]) answer[f.key] = segments[f.key];
1997
+ const rest = used.reduceRight((text, [a, b]) => text.slice(0, a) + " ".repeat(b - a) + text.slice(b), said);
1998
+ for (const f of form.fields) {
1999
+ if (f.key in answer) continue;
2000
+ if (f.type === "number" && f.unit) {
2001
+ const words2 = UNIT_WORDS[f.unit.toLowerCase()] ?? [f.unit.toLowerCase()];
2002
+ const unitRe = new RegExp(`(?<![\\p{L}\\p{N}])((?:${NUMBER_WORD}[\\s-]+)+)(?:${words2.map(escape).join("|")})(?![\\p{L}\\p{N}])`, "iu");
2003
+ const m = unitRe.exec(rest);
2004
+ if (m && m[1].trim()) answer[f.key] = m[1];
2005
+ } else if ((f.type === "choice" || f.type === "choices") && f.choices) {
2006
+ const options = f.choices.map((label) => ({ label, value: label }));
2007
+ const hits2 = matchChoices(rest, options);
2008
+ const shared = form.fields.some(
2009
+ (g) => g !== f && !(g.key in answer) && (g.type === "choice" || g.type === "choices") && matchChoices(rest, (g.choices ?? []).map((l) => ({ label: l, value: l }))).length
2010
+ );
2011
+ if (hits2.length && !shared) answer[f.key] = f.type === "choices" ? hits2 : hits2[0];
2012
+ }
2013
+ }
2014
+ return readFill(form, answer);
2015
+ }
2016
+ var ruleFiller = async (form, said) => ruleFill(form, said);
2017
+ function modelFiller(generate, fallback) {
2018
+ return async (form, said) => {
2019
+ let result = null;
2020
+ try {
2021
+ const { instructions, prompt } = fillPrompt(form, said);
2022
+ result = readFill(form, await generate(instructions, prompt, fillSchema(form)));
2023
+ if (result.problems.some((p) => p.key === "")) result = null;
2024
+ } catch {
2025
+ result = null;
2026
+ }
2027
+ if (!fallback) return result ?? { values: {}, problems: [{ key: "", problem: "The model couldn\u2019t fill the form" }] };
2028
+ const rules = await fallback(form, said);
2029
+ if (!result) return rules;
2030
+ const values = { ...rules.values, ...result.values };
2031
+ const problems = [...result.problems, ...rules.problems.filter((p) => !(p.key in values))];
2032
+ return { values, problems };
2033
+ };
2034
+ }
2035
+ function fillHints(form) {
2036
+ const out = /* @__PURE__ */ new Set();
2037
+ for (const f of form.fields) {
2038
+ out.add(f.label);
2039
+ if (f.unit) out.add(f.unit);
2040
+ for (const c of f.choices ?? []) out.add(c);
2041
+ }
2042
+ return [...out];
2043
+ }
2044
+
1810
2045
  // src/core/local.ts
1811
2046
  var LOCAL_DATASOURCE_TYPE = "modelform-local";
1812
2047
  var LEGACY_LOCAL_DATASOURCE_TYPE = "dashkit-local";
@@ -12244,6 +12479,15 @@ export {
12244
12479
  DICTATION_TYPES,
12245
12480
  takesDictation,
12246
12481
  dictationHints,
12482
+ fillForm,
12483
+ fillSchema,
12484
+ fillPrompt,
12485
+ parseFillAnswer,
12486
+ readFill,
12487
+ ruleFill,
12488
+ ruleFiller,
12489
+ modelFiller,
12490
+ fillHints,
12247
12491
  LOCAL_DATASOURCE_TYPE,
12248
12492
  isLocalDatasource,
12249
12493
  LocalDataSource,