@modelform/react-native 0.9.0 → 0.11.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
@@ -14,6 +14,9 @@ same format. One JSON model describes both what an app records and how it charts
14
14
  instance's HTTP API. You can also implement your own.
15
15
  - **Configs:** a manifest format for whole apps (tabs, forms and dashboards), with JSON Schemas, validation that
16
16
  reports issues instead of throwing, and a loader with caching and last-good fallback.
17
+ - **AI assistants:** `templatePrompt()` writes a prompt for making a template with any assistant (Claude, ChatGPT…),
18
+ and `readTemplateAnswer()` reads the template back out of its reply. `documentPrompt()` and `readDocumentAnswer()` do
19
+ the same for changing one form or dashboard, and `documentChanges()` lists what a change does. Nothing calls a model.
17
20
 
18
21
  modelform is not affiliated with or endorsed by Grafana Labs. It reads the dashboard JSON model that Grafana
19
22
  exports, and ignores keys it doesn't understand.
@@ -11377,10 +11377,10 @@ function mergeVariables(existing, incoming) {
11377
11377
  const renamed = {};
11378
11378
  const out = [...existing];
11379
11379
  for (const v of incoming) {
11380
- const same = existing.find((e) => e.name === v.name);
11381
- if (same && sameVariable(same, v)) continue;
11380
+ const same2 = existing.find((e) => e.name === v.name);
11381
+ if (same2 && sameVariable(same2, v)) continue;
11382
11382
  let name = v.name;
11383
- if (same) {
11383
+ if (same2) {
11384
11384
  let n = 2;
11385
11385
  while (taken.has(`${v.name}_${n}`)) n++;
11386
11386
  name = `${v.name}_${n}`;
@@ -11567,6 +11567,314 @@ function applyTemplate(manifestText, paths, template, options = {}) {
11567
11567
  return { manifest: applyJsonEdits(manifestText, edits), files: out, ids, tabs: added };
11568
11568
  }
11569
11569
 
11570
+ // src/core/authoring.ts
11571
+ var DOCUMENT_GUIDE = `## Documents
11572
+
11573
+ A document is a subset of Grafana's dashboard JSON: \`{ "kind": "form" | "dashboard", "title": "\u2026", "panels": [ \u2026 ] }\`, and dashboards add \`"time": { "from": "now-30d", "to": "now" }\`.
11574
+
11575
+ Every panel has an \`id\` (a number, unique in its document), a \`type\`, a \`title\`, and a \`gridPos\` \`{ "x", "y", "w", "h" }\` on a 24-column grid: \`w: 24\` is full width, \`w: 12\` half. Stack panels top to bottom with no gaps or overlaps (each \`y\` is the previous \`y + h\` unless they sit side by side). On phones panels show full width in that order.
11576
+
11577
+ A \`"row"\` panel (\`h: 1\`, no options) is a section heading for the panels under it, in forms and dashboards.
11578
+
11579
+ ## Forms
11580
+
11581
+ Forms hold input panels. Each records to a \`metric\` (lowercase words joined with dashes, e.g. \`"body-weight"\`), and charts read entries by that metric. Two inputs never share a metric. Use \`h: 3\` for inputs.
11582
+
11583
+ | type | what | options besides metric |
11584
+ |---|---|---|
11585
+ | input-number | a number typed or stepped with + and \u2212 | unit, step, min, max |
11586
+ | input-slider | a value dragged along a range | min, max, step, unit, labels (text spread along the track) |
11587
+ | input-select | one of a set of choices | choices: [{ "label", "value" }], multi (allow several) |
11588
+ | input-toggle | yes or no (records 1 or 0) | |
11589
+ | input-rating | a score, e.g. 1 to 5 | min, max |
11590
+ | input-text | free text | placeholder, suggest (offer earlier values) |
11591
+ | input-counter | taps that add up, e.g. glasses of water | increment, unit |
11592
+ | input-duration | a length of time, recorded in seconds | placeholder |
11593
+
11594
+ Any input (not counter) can also take \`required: true\`, \`default\` (a value, or \`"last"\` for the last one saved), and \`record: "always"\` to record its value on every save even when it wasn't changed.
11595
+
11596
+ \`input-group\` repeats fields once per item, for things like the sets of a workout or the dishes of a meal. Give it \`h: 12\` and options \`{ "itemTitle": "Set", "titleFrom": "<a field's metric>", "start": 1 | "last", "min", "max", "fields": [ { "type": "input-\u2026", "title", "span": 1\u201324, "options": { "metric", \u2026 } } ] }\`. Fields can be any input but input-counter.
11597
+
11598
+ ## Dashboards
11599
+
11600
+ Chart panels read the app's entries with \`"datasource": { "type": "modelform-local" }\` and \`"targets": [ { "refId": "A", "metric": "\u2026" } ]\` (refIds A, B, C\u2026 for more series). A target can also have:
11601
+
11602
+ - \`aggregate\`: "sum", "avg", "min", "max", "count" or "last", with \`bucket\`: "1h", "1d", "1w" or "1M". Without them each entry is a point.
11603
+ - \`groupBy\`: "text" for one series per text or choice value; \`{ "field": "<metric>" }\` for one series per value of another input saved at the same time (in an input-group, of the same item, e.g. weight per exercise).
11604
+ - \`alias\`: the series name. \`fillZero: false\` leaves empty buckets out.
11605
+
11606
+ | type | use for | h |
11607
+ |---|---|---|
11608
+ | timeseries | values over time | 7\u20138 |
11609
+ | barchart | totals per day, week or category | 7\u20138 |
11610
+ | stat | one big number; \`"options": { "reduceOptions": { "calcs": ["lastNotNull" or "mean" or "sum"] } }\` | 4 |
11611
+ | gauge, bargauge | a value against a range (set min and max) | 5\u20136 |
11612
+ | piechart | how a total splits, e.g. by choice with groupBy "text" and aggregate "count" | 8 |
11613
+ | table | rows of values | 8 |
11614
+ | text | markdown notes: \`"options": { "content": "\u2026" }\`, no targets | 3\u20134 |
11615
+
11616
+ Units and ranges go in \`"fieldConfig": { "defaults": { "unit": "\u2026", "min", "max", "decimals" } }\`. Units are Grafana's, e.g. "percent", "masskg", "lengthkm", "s", or "suffix: <text>" for anything else (\`"suffix: glasses"\`). Don't use trend, xychart or geomap panels.
11617
+
11618
+ Charts can't do arithmetic across metrics (weight \xD7 reps, a ratio of two inputs). Chart what's recorded instead, or add an input for the combined value, and say which you did in the sentence before the JSON.
11619
+
11620
+ `;
11621
+ var AUTHORING_GUIDE = `# modelform templates
11622
+
11623
+ A template is JSON that adds forms (for recording entries) and dashboards (for charting them) to an app, plus tabs to show them.
11624
+
11625
+ \`\`\`
11626
+ {
11627
+ "$modelform": "template",
11628
+ "version": 1,
11629
+ "title": "Short name",
11630
+ "description": "One sentence on what it's for.",
11631
+ "documents": [ { "kind": "form" | "dashboard", "id": "letters-digits-dashes", "dashboard": { ...document } } ],
11632
+ "tabs": [ ...tabs ]
11633
+ }
11634
+ \`\`\`
11635
+
11636
+ Each document's \`kind\` matches its entry in \`documents\`.
11637
+
11638
+ ${DOCUMENT_GUIDE}## Tabs
11639
+
11640
+ \`{ "id": "\u2026", "title": "\u2026", "icon": "\u2026", "screen": \u2026 }\`, where the screen is one of:
11641
+
11642
+ - \`{ "type": "forms", "forms": ["<form id>", \u2026] }\`
11643
+ - \`{ "type": "dashboard", "dashboard": "<dashboard id>" }\`
11644
+ - \`{ "type": "menu", "items": [ { "form": "<id>" } or { "dashboard": "<id>", "description": "\u2026" } ] }\`
11645
+
11646
+ Usually one tab for the forms and one per dashboard.
11647
+ `;
11648
+ var EXAMPLE = {
11649
+ $modelform: "template",
11650
+ version: 1,
11651
+ title: "Water and sleep",
11652
+ description: "Count glasses of water and log sleep, and see both by day.",
11653
+ documents: [
11654
+ {
11655
+ kind: "form",
11656
+ id: "today",
11657
+ dashboard: {
11658
+ kind: "form",
11659
+ title: "Today",
11660
+ panels: [
11661
+ { id: 1, type: "input-counter", title: "Water", gridPos: { x: 0, y: 0, w: 24, h: 3 }, options: { metric: "water", unit: "glasses" } },
11662
+ { id: 2, type: "input-duration", title: "Sleep", gridPos: { x: 0, y: 3, w: 12, h: 3 }, options: { metric: "sleep" } },
11663
+ { id: 3, type: "input-rating", title: "Sleep quality", gridPos: { x: 12, y: 3, w: 12, h: 3 }, options: { metric: "sleep-quality", min: 1, max: 5 } }
11664
+ ]
11665
+ }
11666
+ },
11667
+ {
11668
+ kind: "dashboard",
11669
+ id: "by-day",
11670
+ dashboard: {
11671
+ kind: "dashboard",
11672
+ title: "By day",
11673
+ time: { from: "now-30d", to: "now" },
11674
+ panels: [
11675
+ {
11676
+ id: 1,
11677
+ type: "stat",
11678
+ title: "Average sleep",
11679
+ gridPos: { x: 0, y: 0, w: 12, h: 4 },
11680
+ datasource: { type: "modelform-local" },
11681
+ targets: [{ refId: "A", metric: "sleep" }],
11682
+ fieldConfig: { defaults: { unit: "s" } },
11683
+ options: { reduceOptions: { calcs: ["mean"] } }
11684
+ },
11685
+ {
11686
+ id: 2,
11687
+ type: "stat",
11688
+ title: "Water today",
11689
+ gridPos: { x: 12, y: 0, w: 12, h: 4 },
11690
+ datasource: { type: "modelform-local" },
11691
+ targets: [{ refId: "A", metric: "water", aggregate: "sum", bucket: "1d" }],
11692
+ fieldConfig: { defaults: { unit: "suffix: glasses", decimals: 0 } },
11693
+ options: { reduceOptions: { calcs: ["lastNotNull"] } }
11694
+ },
11695
+ {
11696
+ id: 3,
11697
+ type: "barchart",
11698
+ title: "Water per day",
11699
+ gridPos: { x: 0, y: 4, w: 24, h: 7 },
11700
+ datasource: { type: "modelform-local" },
11701
+ targets: [{ refId: "A", metric: "water", alias: "Glasses", aggregate: "sum", bucket: "1d" }],
11702
+ fieldConfig: { defaults: { min: 0, decimals: 0 } }
11703
+ },
11704
+ {
11705
+ id: 4,
11706
+ type: "timeseries",
11707
+ title: "Sleep quality",
11708
+ gridPos: { x: 0, y: 11, w: 24, h: 7 },
11709
+ datasource: { type: "modelform-local" },
11710
+ targets: [{ refId: "A", metric: "sleep-quality", alias: "Quality", aggregate: "avg", bucket: "1d", fillZero: false }],
11711
+ fieldConfig: { defaults: { min: 1, max: 5 } }
11712
+ }
11713
+ ]
11714
+ }
11715
+ }
11716
+ ],
11717
+ tabs: [
11718
+ { id: "today", title: "Today", icon: "edit", screen: { type: "forms", forms: ["today"] } },
11719
+ { id: "by-day", title: "By day", icon: "chart", screen: { type: "dashboard", dashboard: "by-day" } }
11720
+ ],
11721
+ metrics: ["water", "sleep", "sleep-quality"]
11722
+ };
11723
+ var EXAMPLE_TEMPLATE = EXAMPLE;
11724
+ function templatePrompt(request, { recorded = [], icons = [] } = {}) {
11725
+ const context = [
11726
+ recorded.length ? `The app already records these metrics: ${recorded.map((m) => `\`${m}\``).join(", ")}. Charts can read them. A new form should only record one of them if it's for the same thing; otherwise pick new names.` : "The app doesn\u2019t record anything yet.",
11727
+ icons.length ? `Tab icons can be: ${icons.map((i) => `\`${i}\``).join(", ")}.` : ""
11728
+ ].filter(Boolean);
11729
+ return [
11730
+ "I\u2019m building an app with modelform studio. Make me a modelform template for this:",
11731
+ "",
11732
+ request.trim().replace(/^/gm, "> "),
11733
+ "",
11734
+ ...context,
11735
+ "",
11736
+ "Reply with the template as one ```json code block. A sentence before it is fine; nothing after it.",
11737
+ "",
11738
+ AUTHORING_GUIDE,
11739
+ "## Example",
11740
+ "",
11741
+ "```json",
11742
+ JSON.stringify(EXAMPLE),
11743
+ "```"
11744
+ ].join("\n");
11745
+ }
11746
+ function jsonFromAnswer(text) {
11747
+ const blocks = [...text.matchAll(/```(?:json|JSON)?[ \t]*\r?\n([\s\S]*?)```/g)].map((m) => m[1]);
11748
+ const start = text.indexOf("{");
11749
+ const end = text.lastIndexOf("}");
11750
+ if (start >= 0 && end > start) blocks.push(text.slice(start, end + 1));
11751
+ for (const block of blocks.reverse()) {
11752
+ try {
11753
+ return JSON.parse(block);
11754
+ } catch {
11755
+ }
11756
+ }
11757
+ throw new Error("There\u2019s no JSON in that answer");
11758
+ }
11759
+ function readTemplateAnswer(text) {
11760
+ let json;
11761
+ try {
11762
+ json = jsonFromAnswer(text);
11763
+ } catch (e) {
11764
+ return { error: e.message };
11765
+ }
11766
+ const parsed = parseTemplate(JSON.stringify(json));
11767
+ if ("error" in parsed) return parsed;
11768
+ const { template } = parsed;
11769
+ const raw = json;
11770
+ const warnings = raw.documents.flatMap(
11771
+ (d) => prepareDashboard(d.dashboard, d.id).issues.filter((i) => i.severity === "warning").map((i) => `${i.path}: ${i.message}`)
11772
+ );
11773
+ const kept = new Set(template.tabs.map((t) => t.id));
11774
+ for (const [i, tab] of (Array.isArray(raw.tabs) ? raw.tabs : []).entries()) {
11775
+ const id = tab?.id;
11776
+ if (typeof id !== "string" || !kept.has(id)) warnings.push(`tabs[${i}] was left out: it needs an id, a title and a screen showing only this template\u2019s documents`);
11777
+ }
11778
+ const kinds = new Map(template.documents.map((d) => [d.id, d.kind]));
11779
+ for (const tab of template.tabs)
11780
+ for (const ref of screenDocuments(tab.screen)) {
11781
+ const kind = kinds.get(ref.id);
11782
+ if (kind && kind !== ref.kind) warnings.push(`tab "${tab.id}" shows "${ref.id}" as a ${ref.kind}, but it\u2019s a ${kind}`);
11783
+ }
11784
+ return { template, warnings };
11785
+ }
11786
+ function fixTemplatePrompt(problems) {
11787
+ return [
11788
+ "modelform couldn\u2019t use that template as it was:",
11789
+ "",
11790
+ ...problems.map((p) => `- ${p}`),
11791
+ "",
11792
+ "Fix these and reply with the whole corrected template as one ```json code block."
11793
+ ].join("\n");
11794
+ }
11795
+ function documentPrompt(request, document, { recorded = [] } = {}) {
11796
+ const kind = document.kind ?? "dashboard";
11797
+ return [
11798
+ `I\u2019m building an app with modelform studio. Change this ${kind} for me:`,
11799
+ "",
11800
+ request.trim().replace(/^/gm, "> "),
11801
+ "",
11802
+ recorded.length ? `The app records these metrics: ${recorded.map((m) => `\`${m}\``).join(", ")}. Charts can read any of them.` : "",
11803
+ "Keep the ids of panels you keep and give new panels ids not used yet. Don\u2019t change an existing input\u2019s metric unless I asked: entries saved under the old name would stop showing up.",
11804
+ `Keep \`"kind": "${kind}"\`. Reply with the whole changed ${kind} as one \`\`\`json code block, not just the parts that changed. A sentence before it is fine; nothing after it.`,
11805
+ "",
11806
+ `## The ${kind} now`,
11807
+ "",
11808
+ "```json",
11809
+ JSON.stringify(document, null, 2),
11810
+ "```",
11811
+ "",
11812
+ DOCUMENT_GUIDE
11813
+ ].filter((line, i, all) => line !== "" || all[i - 1] !== "").join("\n");
11814
+ }
11815
+ function readDocumentAnswer(text, kind) {
11816
+ let json;
11817
+ try {
11818
+ json = jsonFromAnswer(text);
11819
+ } catch (e) {
11820
+ return { error: e.message };
11821
+ }
11822
+ const wrapper = json;
11823
+ if (wrapper?.$modelform === "template") {
11824
+ if (!Array.isArray(wrapper.documents) || wrapper.documents.length !== 1) return { error: `That\u2019s a template, not one ${kind}` };
11825
+ json = wrapper.documents[0]?.dashboard;
11826
+ }
11827
+ if (!json || typeof json !== "object" || Array.isArray(json)) return { error: `That isn\u2019t a ${kind}` };
11828
+ const raw = json;
11829
+ const stated = raw.kind ?? (Array.isArray(raw.panels) ? documentKind(raw) : void 0);
11830
+ if (stated !== void 0 && stated !== kind)
11831
+ return { error: raw.kind === void 0 ? kind === "form" ? "That has no inputs, so it isn\u2019t a form" : "That has inputs, so it\u2019s a form, not a dashboard" : `That\u2019s a ${String(raw.kind)}, not a ${kind}` };
11832
+ const { dashboard, issues } = prepareDashboard(raw, kind);
11833
+ if (!dashboard) return { error: issues.filter((i) => i.severity === "error").map((i) => `${i.path}: ${i.message}`).join("; ") || `That isn\u2019t a ${kind}` };
11834
+ const document = { kind, ...raw };
11835
+ return { document, warnings: issues.filter((i) => i.severity === "warning").map((i) => `${i.path}: ${i.message}`) };
11836
+ }
11837
+ function fixDocumentPrompt(problems, kind) {
11838
+ return [
11839
+ `modelform couldn\u2019t use that ${kind} as it was:`,
11840
+ "",
11841
+ ...problems.map((p) => `- ${p}`),
11842
+ "",
11843
+ `Fix these and reply with the whole corrected ${kind} as one \`\`\`json code block.`
11844
+ ].join("\n");
11845
+ }
11846
+ var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
11847
+ var flat = (d) => (d.panels ?? []).flatMap((p) => p.type === "row" && p.panels ? [p, ...p.panels] : [p]);
11848
+ function documentChanges(before, after) {
11849
+ const labels = [["kind", "kind"], ["title", "title"], ["description", "description"], ["time", "time range"], ["templating", "variables"], ["timezone", "time zone"], ["refresh", "refresh"]];
11850
+ const document = labels.filter(([key]) => !same(before[key], after[key])).map(([, label]) => label);
11851
+ const old = new Map(flat(before).map((p) => [p.id, p]));
11852
+ const now = new Map(flat(after).map((p) => [p.id, p]));
11853
+ const info = (p) => ({ id: p.id, title: p.title || p.type, type: p.type });
11854
+ const panels = [];
11855
+ for (const p of flat(after)) {
11856
+ const was = old.get(p.id);
11857
+ if (!was) {
11858
+ panels.push({ change: "added", ...info(p), what: [] });
11859
+ continue;
11860
+ }
11861
+ const what = [];
11862
+ if (was.title !== p.title) what.push("title");
11863
+ if (was.type !== p.type) what.push("type");
11864
+ if (was.gridPos?.x !== p.gridPos?.x || was.gridPos?.y !== p.gridPos?.y) what.push("position");
11865
+ if (was.gridPos?.w !== p.gridPos?.w || was.gridPos?.h !== p.gridPos?.h) what.push("size");
11866
+ if (!same(was.options, p.options)) what.push("options");
11867
+ if (!same(was.targets, p.targets) || !same(was.datasource, p.datasource) || !same(was.transformations, p.transformations)) what.push("queries");
11868
+ if (!same(was.fieldConfig, p.fieldConfig)) what.push("field config");
11869
+ const known = /* @__PURE__ */ new Set(["id", "title", "type", "gridPos", "options", "targets", "datasource", "transformations", "fieldConfig", "panels"]);
11870
+ const rest = (q) => Object.fromEntries(Object.entries(q).filter(([k]) => !known.has(k)).sort(([a], [b]) => a.localeCompare(b)));
11871
+ if (!same(rest(was), rest(p))) what.push("other");
11872
+ if (what.length) panels.push({ change: "changed", ...info(p), what });
11873
+ }
11874
+ for (const p of flat(before)) if (!now.has(p.id)) panels.push({ change: "removed", ...info(p), what: [] });
11875
+ return { document, panels };
11876
+ }
11877
+
11570
11878
  export {
11571
11879
  frameLength,
11572
11880
  timeField,
@@ -11790,5 +12098,16 @@ export {
11790
12098
  makeTemplate,
11791
12099
  parseTemplate,
11792
12100
  templateNeeds,
11793
- applyTemplate
12101
+ applyTemplate,
12102
+ DOCUMENT_GUIDE,
12103
+ AUTHORING_GUIDE,
12104
+ EXAMPLE_TEMPLATE,
12105
+ templatePrompt,
12106
+ jsonFromAnswer,
12107
+ readTemplateAnswer,
12108
+ fixTemplatePrompt,
12109
+ documentPrompt,
12110
+ readDocumentAnswer,
12111
+ fixDocumentPrompt,
12112
+ documentChanges
11794
12113
  };