@pritzlaff/nano-app 0.5.1 → 0.5.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.
@@ -1,11 +1,20 @@
1
- import{Coord as Q}from"@pritzlaff/nano-core";import{Type as h}from"typebox";import{Coord as U}from"@pritzlaff/nano-core";import{Type as a}from"typebox";import{Coord as L,Schema as v,Op as n}from"@pritzlaff/nano-core";var k=L.namespace("acme.template"),V=a.Union([a.Literal("+"),a.Literal("-"),a.Literal("*"),a.Literal("/")]),M=v.define(a.Object({a:a.Number(),op:V,b:a.Number()}),"Sum"),f=v.define(a.Object({a:a.Number(),op:V,b:a.Number(),result:a.Number()}),"Calculated"),c=k.interface("Calculator",{calculate:n.action(M,f),calculated:n.event(f)}),w=k.interface("History",{save:n.action(f,a.Null()),load:n.action(a.Null(),a.Array(f))});var j=U.namespace("acme.template"),q=(t)=>Object.assign(Error(t),{fail:{type:"invalid-input",reason:t}}),_=c.impl(j.implementationId("calculator")).config(h.Union([h.Object({precision:h.Optional(h.Integer({minimum:0,maximum:15}))}),h.Undefined()])).make((t)=>({async calculate({a:i,op:e,b:r}){if(e==="/"&&r===0)throw q("division by zero");let m=e==="+"?i+r:e==="-"?i-r:e==="*"?i*r:i/r,u=t.config?.precision,p=u===void 0?m:Number(m.toFixed(u));return await t.publish(c.ops.calculated,{a:i,op:e,b:r,result:p}),{a:i,op:e,b:r,result:p}},async*calculated(){}}));import{html as d}from"lit";import{LitElement as B,html as E}from"lit";import{base as D,kit as F}from"@pritzlaff/nano-elements";class s extends B{static properties={target:{attribute:!1}};static styles=[D,F];off;watching;connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.off?.(),this.off=this.watching=void 0}willUpdate(t){if(t.has("target"))this.watch()}watch(){let t=this.target;if(!t||!this.isConnected||this.watching===t)return;this.off?.(),this.watching=t,this.off=t.app.listen((i)=>this.hear(i,t)),this.started(t)}pod(t){return t.app.call(t.runtime,t.pod)}started(t){}hear(t,i){}face(t){return E``}render(){return this.target?this.face(this.target):E``}}var G=["+","-","*","/"];class g extends s{static properties={...s.properties,a:{state:!0},op:{state:!0},b:{state:!0},result:{state:!0},error:{state:!0},saved:{state:!0}};constructor(){super();this.a=this.b="",this.op="+",this.saved=[]}iter;disconnectedCallback(){super.disconnectedCallback(),this.end()}end(){this.iter?.return?.(),this.iter=void 0}async started(t){this.end(),this.load(t);let i=this.iter=t.app.runtime(t.runtime).get(c,{pod:t.pod}).calculated()[Symbol.asyncIterator]();try{while(!(await i.next()).done&&this.iter===i)await this.load(t)}catch{}}async load(t){try{this.saved=await t.app.runtime(t.runtime).get(w).load()}catch{this.saved=[]}}async equals(t){let i=await this.pod(t).calculate({a:Number(this.a),op:this.op,b:Number(this.b)});if(i.ok)this.result=i.value.result,this.error=void 0;else this.result=void 0,this.error=i.fail.reason}face(t){let i=(e)=>{if(e.key==="Enter")this.equals(t)};return d`<div class="row">
2
- <input class="input" type="number" aria-label="a" .value=${this.a} @input=${(e)=>{this.a=e.target.value}} @keydown=${i}>
3
- <select class="input" aria-label="operator" .value=${this.op} @change=${(e)=>{this.op=e.target.value}}>
4
- ${G.map((e)=>d`<option value=${e} ?selected=${e===this.op}>${e}</option>`)}</select>
5
- <input class="input" type="number" aria-label="b" .value=${this.b} @input=${(e)=>{this.b=e.target.value}} @keydown=${i}>
6
- <button class="btn" aria-label="equals" @click=${()=>this.equals(t)}>=</button>
1
+ import{Nano as f}from"@pritzlaff/nano-core";import{Nano as w}from"@pritzlaff/nano-core";import{Type as J}from"typebox";import{Schema as G}from"@pritzlaff/nano-core";var W=J.Union([J.Literal("+"),J.Literal("-"),J.Literal("*"),J.Literal("/")]),V=G.define(J.Object({a:J.Number(),op:W,b:J.Number()}),"Sum"),Q=G.define(J.Object({a:J.Number(),op:W,b:J.Number(),result:J.Number()}),"Calculated"),z=G.define(J.Union([J.Object({precision:J.Integer({minimum:0,maximum:100})}),J.Undefined()]),"Precision");var v=(q)=>Object.assign(Error(q),{fail:{type:"invalid-input",reason:q}}),E=({a:q,op:D,b:I},{config:U})=>{if(D==="/"&&I===0)throw v("division by zero");let j=D==="+"?q+I:D==="-"?q-I:D==="*"?q*I:q/I;return{a:q,op:D,b:I,result:Number(j.toFixed(U?.precision??6))}},Z=w.create("acme.template.Calculator").config(z,{precision:6}).emit("calculated",Q).action("evaluate",V,Q,E).action("calculate",V,Q,async(q,D)=>{let I=E(q,D);return await D.publish("calculated",I),I});import{Type as X}from"typebox";import{Nano as b}from"@pritzlaff/nano-core";var C="acme.template:history",T=()=>{try{return globalThis.localStorage??void 0}catch{return}},_=b.create("acme.template.History").state(()=>({ls:T(),memory:[]})).action("save",Q,X.Null(),(q,{state:D})=>{let I=[...k(D),q];if(D.ls)D.ls.setItem(C,JSON.stringify(I));else D.memory=I;return null}).action("load",X.Null(),X.Array(Q),(q,{state:D})=>k(D));function k(q){return q.ls?JSON.parse(q.ls.getItem(C)??"[]"):q.memory}var H=f.app("acme.template").use({calculator:Z,history:_}).subscribe(Z.events.calculated.andThen(_.actions.save));import{LitElement as m,html as A}from"lit";import{base as y,kit as u}from"@pritzlaff/nano-elements";var g=["+","-","*","/"],K=(q)=>q.fail?.reason??(q instanceof Error?q.message:String(q));class L extends m{static properties={calc:{attribute:!1},history:{attribute:!1},a:{state:!0},op:{state:!0},b:{state:!0},result:{state:!0},error:{state:!0},saved:{state:!0}};static styles=[y,u];constructor(){super();this.a=this.b="",this.op="+",this.saved=[]}iter;connectedCallback(){if(super.connectedCallback(),this.calc&&!this.iter)this.listen()}disconnectedCallback(){super.disconnectedCallback(),this.end()}willUpdate(q){if(q.has("calc")||q.has("history"))this.listen()}end(){this.iter?.return?.(),this.iter=void 0}async listen(){if(this.end(),!this.calc||!this.isConnected)return;this.load();let q=this.iter=this.calc.calculated()[Symbol.asyncIterator]();try{while(!(await q.next()).done&&this.iter===q)await this.load()}catch{}}async load(){try{this.saved=this.history?await this.history.load():[]}catch{this.saved=[]}}async equals(){if(!this.calc)return;try{this.result=(await this.calc.calculate({a:Number(this.a),op:this.op,b:Number(this.b)})).result,this.error=void 0}catch(q){this.result=void 0,this.error=K(q)}}render(){let q=(D)=>{if(D.key==="Enter")this.equals()};return A`<div class="row">
2
+ <input class="input" type="number" aria-label="a" .value=${this.a} @input=${(D)=>{this.a=D.target.value}} @keydown=${q}>
3
+ <select class="input" aria-label="operator" .value=${this.op} @change=${(D)=>{this.op=D.target.value}}>
4
+ ${g.map((D)=>A`<option value=${D} ?selected=${D===this.op}>${D}</option>`)}</select>
5
+ <input class="input" type="number" aria-label="b" .value=${this.b} @input=${(D)=>{this.b=D.target.value}} @keydown=${q}>
6
+ <button class="btn" aria-label="equals" @click=${()=>this.equals()}>=</button>
7
7
  <output class="badge accent" aria-label="result">${this.result??""}</output></div>
8
- ${this.error?d`<p class="alert bad" role="alert">${this.error}</p>`:""}
9
- <ol aria-label="history">${this.saved.map((e)=>d`<li>${e.a} ${e.op} ${e.b} = ${e.result}</li>`)}</ol>`}}import{Coord as I}from"@pritzlaff/nano-core";var J=I.namespace("acme.template"),A="acme.template:history",N=()=>{try{return globalThis.localStorage??void 0}catch{return}},o=w.impl(J.implementationId("history")).make(()=>{let t=N(),i=[],e=()=>t?JSON.parse(t.getItem(A)??"[]"):i;return{async save(r){let m=[...e(),r];if(t)t.setItem(A,JSON.stringify(m));else i=m},async load(){return e()}}});var R=Q.namespace("acme.template"),rt=R.provider([_,o]),mt={"acme.template/calculator":"nano-calculator"};if(!customElements.get("nano-calculator"))customElements.define("nano-calculator",g);export{mt as views,rt as default};
8
+ ${this.error?A`<p class="alert bad" role="alert">${this.error}</p>`:""}
9
+ <ol aria-label="history">${this.saved.map((D)=>A`<li>${D.a} ${D.op} ${D.b} = ${D.result}</li>`)}</ol>`}}import{LitElement as d,css as h,html as Y,svg as p}from"lit";import{base as i,kit as c,t as x,tv as B}from"@pritzlaff/nano-elements";var r=[...Array(21)].map((q,D)=>D-10),n=["+","-","*","/"],$=200,R=120;class N extends d{static properties={calc:{attribute:!1},op:{state:!0},b:{state:!0},points:{state:!0},error:{state:!0}};static styles=[i,c,h`svg { width: 100%; max-width: 480px; background: ${x("surface")}; border-radius: ${x("radius")} }`];constructor(){super();this.op="+",this.b="1",this.points=[]}run=0;willUpdate(q){if(q.has("calc")||q.has("op")||q.has("b"))this.plot()}async plot(){let q=this.calc,D=++this.run,I=this.op,U=Number(this.b);if(!q)return;let j=await Promise.all(r.map((M)=>q.evaluate({a:M,op:I,b:U}).then((F)=>[M,F.result],(F)=>F)));if(D!==this.run)return;let O=j.filter((M)=>Array.isArray(M)&&Number.isFinite(M[1]));this.points=O,this.error=O.length?void 0:K(j.find((M)=>!Array.isArray(M))??"no points")}line(){let q=Math.max(1,...this.points.map(([,I])=>Math.abs(I))),D=([I,U])=>`${(I+10)/20*$},${R/2-U/q*(R/2-4)}`;return p`<polyline points=${this.points.map(D).join(" ")} fill="none" stroke=${B("accent")} stroke-width="2"/>`}render(){return Y`<div class="row">
10
+ <span>y = x</span>
11
+ <select class="input" aria-label="operator" .value=${this.op} @change=${(q)=>{this.op=q.target.value}}>
12
+ ${n.map((q)=>Y`<option value=${q} ?selected=${q===this.op}>${q}</option>`)}</select>
13
+ <input class="input" type="number" aria-label="b" .value=${this.b} @input=${(q)=>{this.b=q.target.value}}></div>
14
+ ${this.error?Y`<p class="alert bad" role="alert">${this.error}</p>`:""}
15
+ <svg aria-label="graph" viewBox="0 0 ${$} ${R}">
16
+ <line x1="0" y1=${R/2} x2=${$} y2=${R/2} stroke=${B("border")}/><line x1=${$/2} y1="0" x2=${$/2} y2=${R} stroke=${B("border")}/>
17
+ ${this.points.length?this.line():""}
18
+ </svg>`}}var S=(q)=>{try{return q()}catch{return}};function P(q){return class extends q{#q;get target(){return this.#q}set target(D){if(this.#q=D,!D)return;let I=D.app.runtime(D.runtime);if(this.calc=S(()=>I.get(Z.interface,{pod:D.pod})),"history"in this)this.history=S(()=>I.get(_.interface))}}}var Oq=H.provider,Wq={"acme.template/calculator":["nano-calculator","nano-graph-calculator"]};if(!customElements.get("nano-calculator"))customElements.define("nano-calculator",P(L));if(!customElements.get("nano-graph-calculator"))customElements.define("nano-graph-calculator",P(N));export{Wq as views,Oq as default};
10
19
 
11
- export const built = {"@pritzlaff/nano-core":"0.5.0"}
20
+ export const built = {"@pritzlaff/nano-core":"0.5.1"}
@@ -1,94 +1,75 @@
1
- // ../../templates/nano-template/src/index.ts
2
- import { Coord as Coord4 } from "@pritzlaff/nano-core";
1
+ // ../../templates/nano-template/src/app.ts
2
+ import { Nano as Nano3 } from "@pritzlaff/nano-core";
3
3
 
4
4
  // ../../templates/nano-template/src/calculator.ts
5
- import { Type as Type2 } from "typebox";
6
- import { Coord as Coord2 } from "@pritzlaff/nano-core";
5
+ import { Nano } from "@pritzlaff/nano-core";
7
6
 
8
- // ../../templates/nano-template/src/interfaces.ts
7
+ // ../../templates/nano-template/src/schemas.ts
9
8
  import { Type } from "typebox";
10
- import { Coord, Schema, Op } from "@pritzlaff/nano-core";
11
- var ns = Coord.namespace("acme.template");
9
+ import { Schema } from "@pritzlaff/nano-core";
12
10
  var Operator = Type.Union([Type.Literal("+"), Type.Literal("-"), Type.Literal("*"), Type.Literal("/")]);
13
11
  var Sum = Schema.define(Type.Object({ a: Type.Number(), op: Operator, b: Type.Number() }), "Sum");
14
12
  var Calculated = Schema.define(Type.Object({ a: Type.Number(), op: Operator, b: Type.Number(), result: Type.Number() }), "Calculated");
15
- var Calculator = ns.interface("Calculator", {
16
- calculate: Op.action(Sum, Calculated),
17
- calculated: Op.event(Calculated)
18
- });
19
- var History = ns.interface("History", {
20
- save: Op.action(Calculated, Type.Null()),
21
- load: Op.action(Type.Null(), Type.Array(Calculated))
22
- });
13
+ var Precision = Schema.define(Type.Union([Type.Object({ precision: Type.Integer({ minimum: 0, maximum: 100 }) }), Type.Undefined()]), "Precision");
23
14
 
24
15
  // ../../templates/nano-template/src/calculator.ts
25
- var ns2 = Coord2.namespace("acme.template");
26
16
  var invalid = (reason) => Object.assign(new Error(reason), { fail: { type: "invalid-input", reason } });
27
- var calculator = Calculator.impl(ns2.implementationId("calculator")).config(Type2.Union([Type2.Object({ precision: Type2.Optional(Type2.Integer({ minimum: 0, maximum: 15 })) }), Type2.Undefined()])).make((ctx) => ({
28
- async calculate({ a, op, b }) {
29
- if (op === "/" && b === 0)
30
- throw invalid("division by zero");
31
- const exact = op === "+" ? a + b : op === "-" ? a - b : op === "*" ? a * b : a / b;
32
- const p = ctx.config?.precision;
33
- const result = p === undefined ? exact : Number(exact.toFixed(p));
34
- await ctx.publish(Calculator.ops.calculated, { a, op, b, result });
35
- return { a, op, b, result };
36
- },
37
- async* calculated() {}
38
- }));
39
-
40
- // ../../templates/nano-template/src/calculator-view.ts
41
- import { html as html2 } from "lit";
42
-
43
- // ../../templates/nano-template/src/view.ts
44
- import { LitElement, html } from "lit";
45
- import { base, kit } from "@pritzlaff/nano-elements";
17
+ var evaluate = ({ a, op, b }, { config }) => {
18
+ if (op === "/" && b === 0)
19
+ throw invalid("division by zero");
20
+ const result = op === "+" ? a + b : op === "-" ? a - b : op === "*" ? a * b : a / b;
21
+ return { a, op, b, result: Number(result.toFixed(config?.precision ?? 6)) };
22
+ };
23
+ var calculator = Nano.create("acme.template.Calculator").config(Precision, { precision: 6 }).emit("calculated", Calculated).action("evaluate", Sum, Calculated, evaluate).action("calculate", Sum, Calculated, async (sum, ctx) => {
24
+ const done = evaluate(sum, ctx);
25
+ await ctx.publish("calculated", done);
26
+ return done;
27
+ });
46
28
 
47
- class View extends LitElement {
48
- static properties = { target: { attribute: false } };
49
- static styles = [base, kit];
50
- off;
51
- watching;
52
- connectedCallback() {
53
- super.connectedCallback();
54
- this.watch();
55
- }
56
- disconnectedCallback() {
57
- super.disconnectedCallback();
58
- this.off?.();
59
- this.off = this.watching = undefined;
60
- }
61
- willUpdate(changed) {
62
- if (changed.has("target"))
63
- this.watch();
64
- }
65
- watch() {
66
- const t = this.target;
67
- if (!t || !this.isConnected || this.watching === t)
68
- return;
69
- this.off?.();
70
- this.watching = t;
71
- this.off = t.app.listen((e) => this.hear(e, t));
72
- this.started(t);
73
- }
74
- pod(t) {
75
- return t.app.call(t.runtime, t.pod);
76
- }
77
- started(_t) {}
78
- hear(_e, _t) {}
79
- face(_t) {
80
- return html``;
81
- }
82
- render() {
83
- return this.target ? this.face(this.target) : html``;
29
+ // ../../templates/nano-template/src/history.ts
30
+ import { Type as Type2 } from "typebox";
31
+ import { Nano as Nano2 } from "@pritzlaff/nano-core";
32
+ var KEY = "acme.template:history";
33
+ var local = () => {
34
+ try {
35
+ return globalThis.localStorage ?? undefined;
36
+ } catch {
37
+ return;
84
38
  }
39
+ };
40
+ var history = Nano2.create("acme.template.History").state(() => ({ ls: local(), memory: [] })).action("save", Calculated, Type2.Null(), (c, { state }) => {
41
+ const all = [...load(state), c];
42
+ if (state.ls)
43
+ state.ls.setItem(KEY, JSON.stringify(all));
44
+ else
45
+ state.memory = all;
46
+ return null;
47
+ }).action("load", Type2.Null(), Type2.Array(Calculated), (_, { state }) => load(state));
48
+ function load(s) {
49
+ return s.ls ? JSON.parse(s.ls.getItem(KEY) ?? "[]") : s.memory;
85
50
  }
86
51
 
87
- // ../../templates/nano-template/src/calculator-view.ts
52
+ // ../../templates/nano-template/src/app.ts
53
+ var app = Nano3.app("acme.template").use({ calculator, history }).subscribe(calculator.events.calculated.andThen(history.actions.save));
54
+
55
+ // ../../templates/nano-template/src/basic-calculator.ts
56
+ import { LitElement, html } from "lit";
57
+ import { base, kit } from "@pritzlaff/nano-elements";
88
58
  var OPS = ["+", "-", "*", "/"];
59
+ var reason = (e) => e.fail?.reason ?? (e instanceof Error ? e.message : String(e));
89
60
 
90
- class CalculatorView extends View {
91
- static properties = { ...View.properties, a: { state: true }, op: { state: true }, b: { state: true }, result: { state: true }, error: { state: true }, saved: { state: true } };
61
+ class BasicCalculator extends LitElement {
62
+ static properties = {
63
+ calc: { attribute: false },
64
+ history: { attribute: false },
65
+ a: { state: true },
66
+ op: { state: true },
67
+ b: { state: true },
68
+ result: { state: true },
69
+ error: { state: true },
70
+ saved: { state: true }
71
+ };
72
+ static styles = [base, kit];
92
73
  constructor() {
93
74
  super();
94
75
  this.a = this.b = "";
@@ -96,98 +77,164 @@ class CalculatorView extends View {
96
77
  this.saved = [];
97
78
  }
98
79
  iter;
80
+ connectedCallback() {
81
+ super.connectedCallback();
82
+ if (this.calc && !this.iter)
83
+ this.listen();
84
+ }
99
85
  disconnectedCallback() {
100
86
  super.disconnectedCallback();
101
87
  this.end();
102
88
  }
89
+ willUpdate(changed) {
90
+ if (changed.has("calc") || changed.has("history"))
91
+ this.listen();
92
+ }
103
93
  end() {
104
94
  this.iter?.return?.();
105
95
  this.iter = undefined;
106
96
  }
107
- async started(t) {
97
+ async listen() {
108
98
  this.end();
109
- this.load(t);
110
- const it = this.iter = t.app.runtime(t.runtime).get(Calculator, { pod: t.pod }).calculated()[Symbol.asyncIterator]();
99
+ if (!this.calc || !this.isConnected)
100
+ return;
101
+ this.load();
102
+ const it = this.iter = this.calc.calculated()[Symbol.asyncIterator]();
111
103
  try {
112
104
  while (!(await it.next()).done && this.iter === it)
113
- await this.load(t);
105
+ await this.load();
114
106
  } catch {}
115
107
  }
116
- async load(t) {
108
+ async load() {
117
109
  try {
118
- this.saved = await t.app.runtime(t.runtime).get(History).load();
110
+ this.saved = this.history ? await this.history.load() : [];
119
111
  } catch {
120
112
  this.saved = [];
121
113
  }
122
114
  }
123
- async equals(t) {
124
- const r = await this.pod(t).calculate({ a: Number(this.a), op: this.op, b: Number(this.b) });
125
- if (r.ok) {
126
- this.result = r.value.result;
115
+ async equals() {
116
+ if (!this.calc)
117
+ return;
118
+ try {
119
+ this.result = (await this.calc.calculate({ a: Number(this.a), op: this.op, b: Number(this.b) })).result;
127
120
  this.error = undefined;
128
- } else {
121
+ } catch (e) {
129
122
  this.result = undefined;
130
- this.error = r.fail.reason;
123
+ this.error = reason(e);
131
124
  }
132
125
  }
133
- face(t) {
126
+ render() {
134
127
  const enter = (e) => {
135
128
  if (e.key === "Enter")
136
- this.equals(t);
129
+ this.equals();
137
130
  };
138
- return html2`<div class="row">
131
+ return html`<div class="row">
139
132
  <input class="input" type="number" aria-label="a" .value=${this.a} @input=${(e) => {
140
133
  this.a = e.target.value;
141
134
  }} @keydown=${enter}>
142
135
  <select class="input" aria-label="operator" .value=${this.op} @change=${(e) => {
143
136
  this.op = e.target.value;
144
137
  }}>
145
- ${OPS.map((o) => html2`<option value=${o} ?selected=${o === this.op}>${o}</option>`)}</select>
138
+ ${OPS.map((o) => html`<option value=${o} ?selected=${o === this.op}>${o}</option>`)}</select>
146
139
  <input class="input" type="number" aria-label="b" .value=${this.b} @input=${(e) => {
147
140
  this.b = e.target.value;
148
141
  }} @keydown=${enter}>
149
- <button class="btn" aria-label="equals" @click=${() => this.equals(t)}>=</button>
142
+ <button class="btn" aria-label="equals" @click=${() => this.equals()}>=</button>
150
143
  <output class="badge accent" aria-label="result">${this.result ?? ""}</output></div>
144
+ ${this.error ? html`<p class="alert bad" role="alert">${this.error}</p>` : ""}
145
+ <ol aria-label="history">${this.saved.map((s) => html`<li>${s.a} ${s.op} ${s.b} = ${s.result}</li>`)}</ol>`;
146
+ }
147
+ }
148
+
149
+ // ../../templates/nano-template/src/graph-calculator.ts
150
+ import { LitElement as LitElement2, css, html as html2, svg } from "lit";
151
+ import { base as base2, kit as kit2, t, tv } from "@pritzlaff/nano-elements";
152
+ var XS = [...Array(21)].map((_, i) => i - 10);
153
+ var OPS2 = ["+", "-", "*", "/"];
154
+ var W = 200;
155
+ var H = 120;
156
+
157
+ class GraphCalculator extends LitElement2 {
158
+ static properties = { calc: { attribute: false }, op: { state: true }, b: { state: true }, points: { state: true }, error: { state: true } };
159
+ static styles = [base2, kit2, css`svg { width: 100%; max-width: 480px; background: ${t("surface")}; border-radius: ${t("radius")} }`];
160
+ constructor() {
161
+ super();
162
+ this.op = "+";
163
+ this.b = "1";
164
+ this.points = [];
165
+ }
166
+ run = 0;
167
+ willUpdate(changed) {
168
+ if (changed.has("calc") || changed.has("op") || changed.has("b"))
169
+ this.plot();
170
+ }
171
+ async plot() {
172
+ const calc = this.calc, run = ++this.run, op = this.op, b = Number(this.b);
173
+ if (!calc)
174
+ return;
175
+ const got = await Promise.all(XS.map((a) => calc.evaluate({ a, op, b }).then((r) => [a, r.result], (e) => e)));
176
+ if (run !== this.run)
177
+ return;
178
+ const ok = got.filter((g) => Array.isArray(g) && Number.isFinite(g[1]));
179
+ this.points = ok;
180
+ this.error = ok.length ? undefined : reason(got.find((g) => !Array.isArray(g)) ?? "no points");
181
+ }
182
+ line() {
183
+ const top = Math.max(1, ...this.points.map(([, y]) => Math.abs(y)));
184
+ const at = ([x, y]) => `${(x + 10) / 20 * W},${H / 2 - y / top * (H / 2 - 4)}`;
185
+ return svg`<polyline points=${this.points.map(at).join(" ")} fill="none" stroke=${tv("accent")} stroke-width="2"/>`;
186
+ }
187
+ render() {
188
+ return html2`<div class="row">
189
+ <span>y = x</span>
190
+ <select class="input" aria-label="operator" .value=${this.op} @change=${(e) => {
191
+ this.op = e.target.value;
192
+ }}>
193
+ ${OPS2.map((o) => html2`<option value=${o} ?selected=${o === this.op}>${o}</option>`)}</select>
194
+ <input class="input" type="number" aria-label="b" .value=${this.b} @input=${(e) => {
195
+ this.b = e.target.value;
196
+ }}></div>
151
197
  ${this.error ? html2`<p class="alert bad" role="alert">${this.error}</p>` : ""}
152
- <ol aria-label="history">${this.saved.map((s) => html2`<li>${s.a} ${s.op} ${s.b} = ${s.result}</li>`)}</ol>`;
198
+ <svg aria-label="graph" viewBox="0 0 ${W} ${H}">
199
+ <line x1="0" y1=${H / 2} x2=${W} y2=${H / 2} stroke=${tv("border")}/><line x1=${W / 2} y1="0" x2=${W / 2} y2=${H} stroke=${tv("border")}/>
200
+ ${this.points.length ? this.line() : ""}
201
+ </svg>`;
153
202
  }
154
203
  }
155
204
 
156
- // ../../templates/nano-template/src/history.ts
157
- import { Coord as Coord3 } from "@pritzlaff/nano-core";
158
- var ns3 = Coord3.namespace("acme.template");
159
- var KEY = "acme.template:history";
160
- var local = () => {
205
+ // ../../templates/nano-template/src/hosted.ts
206
+ var one = (get) => {
161
207
  try {
162
- return globalThis.localStorage ?? undefined;
208
+ return get();
163
209
  } catch {
164
210
  return;
165
211
  }
166
212
  };
167
- var history = History.impl(ns3.implementationId("history")).make(() => {
168
- const ls = local();
169
- let memory = [];
170
- const load = () => ls ? JSON.parse(ls.getItem(KEY) ?? "[]") : memory;
171
- return {
172
- async save(c) {
173
- const all = [...load(), c];
174
- if (ls)
175
- ls.setItem(KEY, JSON.stringify(all));
176
- else
177
- memory = all;
178
- },
179
- async load() {
180
- return load();
213
+ function hosted(Base) {
214
+ return class extends Base {
215
+ #target;
216
+ get target() {
217
+ return this.#target;
218
+ }
219
+ set target(t2) {
220
+ this.#target = t2;
221
+ if (!t2)
222
+ return;
223
+ const at = t2.app.runtime(t2.runtime);
224
+ this.calc = one(() => at.get(calculator.interface, { pod: t2.pod }));
225
+ if ("history" in this)
226
+ this.history = one(() => at.get(history.interface));
181
227
  }
182
228
  };
183
- });
229
+ }
184
230
 
185
231
  // ../../templates/nano-template/src/index.ts
186
- var ns4 = Coord4.namespace("acme.template");
187
- var src_default = ns4.provider([calculator, history]);
188
- var views = { "acme.template/calculator": "nano-calculator" };
232
+ var src_default = app.provider;
233
+ var views = { "acme.template/calculator": ["nano-calculator", "nano-graph-calculator"] };
189
234
  if (!customElements.get("nano-calculator"))
190
- customElements.define("nano-calculator", CalculatorView);
235
+ customElements.define("nano-calculator", hosted(BasicCalculator));
236
+ if (!customElements.get("nano-graph-calculator"))
237
+ customElements.define("nano-graph-calculator", hosted(GraphCalculator));
191
238
  export {
192
239
  views,
193
240
  src_default as default
@@ -2,6 +2,9 @@
2
2
  "pods": {
3
3
  "calculator": {
4
4
  "implementation": "acme.template/calculator",
5
+ "config": {
6
+ "precision": 6
7
+ },
5
8
  "eager": false
6
9
  },
7
10
  "history": {
@@ -5,4 +5,4 @@ import{LitElement as q,css as C,html as X}from"lit";import{base as E,kit as b}fr
5
5
  <span>${w.title}</span>
6
6
  <button class="btn small" aria-label="Remove ${w.title}" @click=${()=>this.run(B.remove(w.id))}>×</button></li>`)}</ul></div>`}}import{Implementation as z}from"@pritzlaff/nano-core";import{Type as M}from"typebox";import{Coord as v,Op as Y,Schema as _}from"@pritzlaff/nano-core";var U;((F)=>(F.ns=v.namespace("example.kv"),F.Path=_.define(M.Array(M.String())),F.Value=_.define(M.Unsafe(M.Unknown())),F.Entry=_.define(M.Object({key:F.Path,value:F.Value})),F.api=F.ns.interface("KeyValueStore",{get:Y.action(F.Path,F.Value),put:Y.action(F.Entry,M.Null()),delete:Y.action(F.Path,M.Null()),list:Y.action(M.Object({prefix:F.Path}),M.Array(F.Entry))})))(U||={});var Q=U.api.ops,W=(j)=>["todos",j],I=0,P=()=>`${Date.now().toString(36).padStart(9,"0")}${(I++%1679616).toString(36).padStart(4,"0")}-${crypto.randomUUID().slice(0,8)}`;function g(j,B=P){return{async add(w){let A={id:B(),title:w,done:!1};return await j.put({key:W(A.id),value:A}),A},async list(){return(await j.list({prefix:["todos"]})).map((w)=>w.value)},async put(w){return await j.put({key:W(w.id),value:w}),w},async update(w){let A=await j.get(W(w.id));if(!A)return null;let G={...A,...w.title!==void 0&&{title:w.title},...w.done!==void 0&&{done:w.done}};return await j.put({key:W(w.id),value:G}),G},async remove(w){if(await j.get(W(w))===null)return!1;return await j.delete(W(w)),!0}}}var m=z.define(N.ns.implementationId("kv"),{provides:[N.api],description:"Todos kept in whichever KeyValueStore its call edge reaches.",dependencies:{store:U.api},calls:{add:{store:[Q.put]},list:{store:[Q.list]},put:{store:[Q.put]},update:{store:[Q.get,Q.put]},remove:{store:[Q.get,Q.delete]}},make:(j)=>{let B=setInterval(()=>{j.deps.store.list({prefix:["todos"]}).catch(()=>{})},1000);j.addOnCloseListener(()=>clearInterval(B));let w=(A)=>g(A.deps.store);return{add:(A,G)=>w(G).add(A),list:(A,G)=>w(G).list(),put:(A,G)=>w(G).put(A),update:(A,G)=>w(G).update(A),remove:(A,G)=>w(G).remove(A),async*items(){let A=j.one(U.api);if(A.ok){for await(let{input:G}of A.value.on(U.api.ops.put))if(G.key[0]==="todos")yield G.value}}}}}),L=N.ns.provider([m]);var p={"example.todo/kv":"todo-list"};if(!customElements.get("todo-list"))customElements.define("todo-list",Z);export{p as views,L as default};
7
7
 
8
- export const built = {"@pritzlaff/nano-core":"0.5.0"}
8
+ export const built = {"@pritzlaff/nano-core":"0.5.1"}
package/app/main.js CHANGED
@@ -1083,7 +1083,7 @@ import { toast as toast3 } from "@pritzlaff/nano-elements";
1083
1083
  // src/import.ts
1084
1084
  import { failure as failure9, Registry as Registry2, success as success8 } from "@pritzlaff/nano-core";
1085
1085
  // ../nano/package.json
1086
- var version = "0.5.0";
1086
+ var version = "0.5.1";
1087
1087
 
1088
1088
  // src/built.ts
1089
1089
  var minor = (v) => {
@@ -1676,7 +1676,7 @@ function implError(i) {
1676
1676
  }
1677
1677
  return schema(i.config, `${i.coord} config`);
1678
1678
  }
1679
- var described = (p) => !obj3(p) || !str2(p.coord) || !obj3(p.meta) || !Object.values(p.meta).every(str2) || !obj3(p.views) || !Object.values(p.views).every(str2) || !Array.isArray(p.implementations) || p.built !== undefined && (!obj3(p.built) || !Object.values(p.built).every(str2)) ? "a provider needs coord, meta, views and implementations (and a built, if any, of strings)" : p.implementations.map(implError).find((w) => w !== undefined);
1679
+ var described = (p) => !obj3(p) || !str2(p.coord) || !obj3(p.meta) || !Object.values(p.meta).every(str2) || !obj3(p.views) || !Object.values(p.views).every((v) => str2(v) || Array.isArray(v) && v.every(str2)) || !Array.isArray(p.implementations) || p.built !== undefined && (!obj3(p.built) || !Object.values(p.built).every(str2)) ? "a provider needs coord, meta, views (tags, or lists of tags) and implementations (and a built, if any, of strings)" : p.implementations.map(implError).find((w) => w !== undefined);
1680
1680
  var result = (v) => isNanoResult(v);
1681
1681
  var FIELDS = {
1682
1682
  build: { pod: str2, runtimes: strs, coord: str2, url: str2, config: any, edges: arrOf(edge) },
@@ -1972,10 +1972,12 @@ function described2(d) {
1972
1972
  throw new Error(`${i.coord} was only probed`);
1973
1973
  }
1974
1974
  }));
1975
- const own2 = new Set(impls.map((i) => i.coord)), ok = ([c, tag]) => own2.has(c) && TAG.test(tag);
1975
+ const own2 = new Set(impls.map((i) => i.coord));
1976
+ const valid = (v) => typeof v === "string" ? TAG.test(v) ? v : [] : v.filter((t) => TAG.test(t));
1977
+ const views = Object.fromEntries(Object.entries(d.views).map(([c, v]) => [c, own2.has(c) ? valid(v) : []]).filter(([, v]) => v.length));
1976
1978
  return success10({
1977
1979
  provider: Provider2.define(d.coord, impls, { ...d.meta }),
1978
- views: Object.fromEntries(Object.entries(d.views).filter(ok)),
1980
+ views,
1979
1981
  ...d.built && { built: { ...d.built } }
1980
1982
  });
1981
1983
  } catch (e) {
@@ -2957,7 +2959,7 @@ var chosen = (h, pod) => {
2957
2959
  const views = h.document().host?.views ?? {};
2958
2960
  return away(h, pod) && !customElements.get(views[pod] ?? "") ? "nano-sandboxed" : viewFor(pod, h.data(), h.defaults(), views);
2959
2961
  };
2960
- var viewTags = (h, pod, impl) => [...new Set([away(h, pod) && "nano-sandboxed", h.defaults()[impl], "nano-pod-view"].filter((x) => !!x))];
2962
+ var viewTags = (h, pod, impl) => [...new Set([away(h, pod) && "nano-sandboxed", ...[h.defaults()[impl] ?? []].flat(), "nano-pod-view"].filter((x) => !!x))];
2961
2963
  function pagePods(outline, id, quiet) {
2962
2964
  let opened2 = {}, running = false, again = false;
2963
2965
  const heard = new Set;