orvyn-lang 0.3.0 → 0.4.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.
@@ -1,5 +1,6 @@
1
1
  import { OrvynSyntaxError } from "./lexer.js";
2
2
  import { LIST_WORDS } from "./words.js";
3
+ import { parse } from "./parser.js";
3
4
  const LIST_METHODS = /* @__PURE__ */ new Set(["add", "remove", "removeAt", "clear", "update"]);
4
5
  const BUILTINS = {
5
6
  Column: { tag: "div", props: { flex: true, direction: "column" } },
@@ -24,6 +25,7 @@ const EVENTS = {
24
25
  onChange: "onInput",
25
26
  onSubmit: "onSubmit",
26
27
  onError: "onError",
28
+ onVisible: "onVisible",
27
29
  onHover: "onMouseenter",
28
30
  onLeave: "onMouseleave"
29
31
  };
@@ -40,6 +42,9 @@ const GLOBALS = {
40
42
  back: "__o.back",
41
43
  canGoBack: "__o.canGoBack",
42
44
  openUrl: "__o.openUrl",
45
+ scrollTo: "__o.scrollTo",
46
+ defineAnimation: "__o.defineAnimation",
47
+ platform: "__o.platform",
43
48
  sleep: "__o.sleep",
44
49
  random: "__o.random",
45
50
  len: "__o.len",
@@ -179,6 +184,8 @@ const NEEDS = { takePhoto: "camera", getLocation: "location" };
179
184
  class Generator {
180
185
  currentView = "";
181
186
  fnParams = /* @__PURE__ */ new Map();
187
+ asyncFns = /* @__PURE__ */ new Set();
188
+ importedAsyncFns = /* @__PURE__ */ new Set();
182
189
  formId = 0;
183
190
  needs = /* @__PURE__ */ new Set();
184
191
  inTest = false;
@@ -192,8 +199,167 @@ class Generator {
192
199
  this.program = program;
193
200
  this.options = options;
194
201
  }
202
+ analyzeAsyncFns() {
203
+ const cache = /* @__PURE__ */ new Map();
204
+ const analyzeProgram = (prog, resolve) => {
205
+ const importedAsync = /* @__PURE__ */ new Set();
206
+ for (const decl of prog.body) {
207
+ if (decl.kind !== "Use" || !resolve || /\.(m?js|ts)$/.test(decl.path) || !/^[./]/.test(decl.path)) continue;
208
+ const found = resolve(decl.path);
209
+ if (!found) continue;
210
+ const { source, resolve: nextResolve } = typeof found === "string" ? { source: found, resolve } : found;
211
+ let childAsync = cache.get(source);
212
+ if (!childAsync) {
213
+ cache.set(source, /* @__PURE__ */ new Set());
214
+ try {
215
+ childAsync = analyzeProgram(parse(source), nextResolve);
216
+ } catch {
217
+ childAsync = /* @__PURE__ */ new Set();
218
+ }
219
+ cache.set(source, childAsync);
220
+ }
221
+ for (const name of decl.names) {
222
+ if (childAsync.has(name)) importedAsync.add(name);
223
+ }
224
+ }
225
+ const fnNames = new Set(prog.body.filter((d) => d.kind === "Fn").map((d) => d.name));
226
+ const topShadowed = new Set(prog.body.flatMap((d) => {
227
+ if (d.kind === "State" || d.kind === "Const" || d.kind === "Screen") return [d.name];
228
+ if (d.kind === "Use") return d.names;
229
+ return [];
230
+ }));
231
+ const asyncSet = /* @__PURE__ */ new Set();
232
+ const edges = /* @__PURE__ */ new Map();
233
+ const walkExpr = (expr, locals, fnName) => {
234
+ switch (expr.kind) {
235
+ case "Wait":
236
+ asyncSet.add(fnName);
237
+ walkExpr(expr.expr, locals, fnName);
238
+ return;
239
+ case "Call":
240
+ if (expr.callee.kind === "Ident") {
241
+ const name = expr.callee.name;
242
+ if (!locals.has(name)) {
243
+ if (fnNames.has(name)) {
244
+ let list = edges.get(fnName);
245
+ if (!list) {
246
+ list = /* @__PURE__ */ new Set();
247
+ edges.set(fnName, list);
248
+ }
249
+ list.add(name);
250
+ } else if (importedAsync.has(name)) {
251
+ asyncSet.add(fnName);
252
+ } else if (ASYNC_GLOBALS.has(name) && !topShadowed.has(name)) {
253
+ asyncSet.add(fnName);
254
+ }
255
+ }
256
+ }
257
+ walkExpr(expr.callee, locals, fnName);
258
+ expr.args.forEach((a) => walkExpr(a, locals, fnName));
259
+ return;
260
+ case "String":
261
+ expr.parts.forEach((p) => {
262
+ if (typeof p !== "string") walkExpr(p, locals, fnName);
263
+ });
264
+ return;
265
+ case "List":
266
+ expr.items.forEach((i) => walkExpr(i, locals, fnName));
267
+ return;
268
+ case "Object":
269
+ expr.entries.forEach((e) => walkExpr(e.value, locals, fnName));
270
+ return;
271
+ case "Member":
272
+ walkExpr(expr.object, locals, fnName);
273
+ return;
274
+ case "Index":
275
+ walkExpr(expr.object, locals, fnName);
276
+ walkExpr(expr.index, locals, fnName);
277
+ return;
278
+ case "New":
279
+ walkExpr(expr.callee, locals, fnName);
280
+ expr.args.forEach((a) => walkExpr(a, locals, fnName));
281
+ return;
282
+ case "Unary":
283
+ walkExpr(expr.operand, locals, fnName);
284
+ return;
285
+ case "Binary":
286
+ walkExpr(expr.left, locals, fnName);
287
+ walkExpr(expr.right, locals, fnName);
288
+ return;
289
+ case "Ternary":
290
+ walkExpr(expr.cond, locals, fnName);
291
+ walkExpr(expr.then, locals, fnName);
292
+ walkExpr(expr.else, locals, fnName);
293
+ return;
294
+ case "Lambda":
295
+ return;
296
+ }
297
+ };
298
+ const walkStmts = (stmts, locals, fnName) => {
299
+ const inner = new Set(locals);
300
+ for (const stmt of stmts) {
301
+ switch (stmt.kind) {
302
+ case "Let":
303
+ walkExpr(stmt.init, inner, fnName);
304
+ inner.add(stmt.name);
305
+ break;
306
+ case "Assign":
307
+ walkExpr(stmt.target, inner, fnName);
308
+ walkExpr(stmt.value, inner, fnName);
309
+ break;
310
+ case "ExprStmt":
311
+ walkExpr(stmt.expr, inner, fnName);
312
+ break;
313
+ case "Return":
314
+ if (stmt.value) walkExpr(stmt.value, inner, fnName);
315
+ break;
316
+ case "If":
317
+ walkExpr(stmt.cond, inner, fnName);
318
+ walkStmts(stmt.then, inner, fnName);
319
+ if (stmt.else) walkStmts(stmt.else, inner, fnName);
320
+ break;
321
+ case "For": {
322
+ walkExpr(stmt.iter, inner, fnName);
323
+ const loopLocals = new Set(inner);
324
+ loopLocals.add(stmt.name);
325
+ walkStmts(stmt.body, loopLocals, fnName);
326
+ break;
327
+ }
328
+ case "Try":
329
+ walkStmts(stmt.body, inner, fnName);
330
+ const catchLocals = new Set(inner);
331
+ if (stmt.catchName) catchLocals.add(stmt.catchName);
332
+ walkStmts(stmt.catchBody, catchLocals, fnName);
333
+ break;
334
+ }
335
+ }
336
+ };
337
+ for (const decl of prog.body) {
338
+ if (decl.kind !== "Fn") continue;
339
+ walkStmts(decl.body, new Set(decl.params), decl.name);
340
+ }
341
+ let changed = true;
342
+ while (changed) {
343
+ changed = false;
344
+ for (const [caller, callees] of edges) {
345
+ if (asyncSet.has(caller)) continue;
346
+ for (const callee of callees) {
347
+ if (asyncSet.has(callee)) {
348
+ asyncSet.add(caller);
349
+ changed = true;
350
+ break;
351
+ }
352
+ }
353
+ }
354
+ }
355
+ if (prog === this.program) this.importedAsyncFns = importedAsync;
356
+ return asyncSet;
357
+ };
358
+ this.asyncFns = analyzeProgram(this.program, this.options.resolveImport);
359
+ }
195
360
  generate() {
196
361
  const runtime = this.options.runtime ?? "orvyn";
362
+ this.analyzeAsyncFns();
197
363
  const imports = [];
198
364
  const starts = [];
199
365
  for (const decl of this.program.body) {
@@ -267,16 +433,19 @@ ${body.join("\n")}
267
433
  const screens = this.program.body.filter(
268
434
  (d) => d.kind === "Screen" && d.type === "screen"
269
435
  );
436
+ const importedNames = this.program.body.flatMap((d) => d.kind === "Use" && !/\.(m?js|ts)$/.test(d.path) && /^[./]/.test(d.path) ? d.names.map(jsName) : []);
270
437
  const entry = screens.find((s) => s.name === "App") ?? screens.find((s) => s.name !== "NotFound" && s.name !== "ErrorPage") ?? screens[0];
271
438
  if (screens.some((s) => s.name === "ErrorPage")) {
272
439
  this.line("__o.setErrorPage(ErrorPage)");
273
440
  this.line("");
274
441
  }
275
442
  if (screens.length) this.line(`__o.registerScreens?.({ ${screens.map((s) => s.name).join(", ")} })`);
276
- this.line(`export const screens = { ${screens.map((s) => s.name).join(", ")} }`);
443
+ const localScreens = screens.map((s) => s.name).join(", ");
444
+ const importedScreens = importedNames.length ? `...__o.registeredScreens(), ...Object.fromEntries([${importedNames.map((n) => `() => ${n}`).join(", ")}].map(read => { try { return read() } catch { return undefined } }).filter(value => value?.__name).map(value => [value.__name, value]))` : "";
445
+ this.line(`export const screens = { ${[localScreens, importedScreens, localScreens && importedScreens ? localScreens : ""].filter(Boolean).join(", ")} }`);
277
446
  this.line("");
278
447
  this.line("export function mountApp(target, screen, params) {");
279
- this.line(` return __o.startApp(target, screen ? screens[screen] : ${entry ? entry.name : "null"}, ${starts.length > 0 ? `__o.guard(__start, "start", __F, ${starts[0][0]?.line ?? 0}, "start")` : "null"}, screens, params)`);
448
+ this.line(` return __o.startApp(target, screen ? screens[screen] : ${entry ? entry.name : '(screens.App ?? screens.Home ?? Object.entries(screens).find(([name]) => name !== "NotFound" && name !== "ErrorPage")?.[1] ?? null)'}, ${starts.length > 0 ? `__o.guard(__start, "start", __F, ${starts[0][0]?.line ?? 0}, "start")` : "null"}, screens, params)`);
280
449
  this.line("}");
281
450
  this.line("");
282
451
  this.line(`export default ${entry ? entry.name : "null"}`);
@@ -542,6 +711,7 @@ ${body.join("\n")}
542
711
  if (binding === "imported") return `__o.readImported(${jsName(expr.name)})`;
543
712
  if (binding !== void 0) return jsName(expr.name);
544
713
  if (Object.hasOwn(GLOBALS, expr.name)) return GLOBALS[expr.name];
714
+ if (this.options.projectScreens?.includes(expr.name)) return `__o.registeredScreens()[${JSON.stringify(expr.name)}]`;
545
715
  if (bareWords) return JSON.stringify(expr.name);
546
716
  {
547
717
  const hint = suggest(expr.name, [...scope.names(), ...Object.keys(GLOBALS)]);
@@ -572,6 +742,8 @@ ${body.join("\n")}
572
742
  const inner = this.expr(expr.expr, scope);
573
743
  return inner.startsWith("__o.resume(await ") ? inner : `__o.resume(await __o.track(${inner}))`;
574
744
  }
745
+ case "New":
746
+ return `new (${this.expr(expr.callee, scope)})(${expr.args.map((a) => this.expr(a, scope)).join(", ")})`;
575
747
  case "Call": {
576
748
  if (this.inTest && expr.callee.kind === "Ident" && TEST_GLOBALS.has(expr.callee.name) && scope.lookup(expr.callee.name) === void 0) {
577
749
  const name = expr.callee.name;
@@ -586,6 +758,14 @@ ${body.join("\n")}
586
758
  return `__o.words(${target}, ${JSON.stringify(expr.callee.property)}, [${expr.args.map((a) => this.expr(a, scope)).join(", ")}])`;
587
759
  }
588
760
  const call = `${this.postfix(expr.callee, scope)}(${expr.args.map((a) => this.expr(a, scope)).join(", ")})`;
761
+ const calleeBinding = expr.callee.kind === "Ident" ? scope.lookup(expr.callee.name) : void 0;
762
+ if (expr.callee.kind === "Ident" && scope.awaitAllowed && (calleeBinding === "fn" && this.asyncFns.has(expr.callee.name) || calleeBinding === "imported" && this.importedAsyncFns.has(expr.callee.name))) {
763
+ scope.markAwait();
764
+ return `__o.resume(await __o.track(${call}))`;
765
+ }
766
+ if (expr.callee.kind === "Ident" && !scope.awaitAllowed && (calleeBinding === "fn" && this.asyncFns.has(expr.callee.name) || calleeBinding === "imported" && this.importedAsyncFns.has(expr.callee.name))) {
767
+ fail(`${expr.callee.name}() waits for something (it uses wait, or calls a function that does), so its answer isn't ready here. Call it inside fn, start, or an event handler, and keep the result in a state`, expr);
768
+ }
589
769
  if (expr.callee.kind === "Ident" && ASYNC_GLOBALS.has(expr.callee.name) && scope.lookup(expr.callee.name) === void 0) {
590
770
  if (NEEDS[expr.callee.name]) this.needs.add(NEEDS[expr.callee.name]);
591
771
  if (!scope.awaitAllowed) {
@@ -630,12 +810,12 @@ ${body.join("\n")}
630
810
  if (name === "go" && !target) fail("go() needs a screen, like go(Home)", expr);
631
811
  if (target?.kind === "Ident") {
632
812
  const kind = scope.lookup(target.name);
633
- if (kind === void 0) {
813
+ if (kind === void 0 && !this.options.projectScreens?.includes(target.name)) {
634
814
  const screens = this.program.body.flatMap((d) => d.kind === "Screen" && d.type === "screen" ? [d.name] : []);
635
815
  fail(`There is no screen called "${target.name}".${suggest(target.name, screens) || (screens.length ? ` Screens: ${screens.join(", ")}` : "")}`, target);
636
816
  }
637
817
  if (kind === "component") fail(`${target.name} is a component, not a screen. Use "screen ${target.name}" to navigate to it`, target);
638
- if (kind !== "screen" && kind !== "imported" && kind !== "local") fail(`${name}() needs a screen, but "${target.name}" is a ${kind}`, target);
818
+ if (kind !== void 0 && kind !== "screen" && kind !== "imported" && kind !== "local") fail(`${name}() needs a screen, but "${target.name}" is a ${kind}`, target);
639
819
  }
640
820
  }
641
821
  }
@@ -757,13 +937,19 @@ ${body.join("\n")}
757
937
  }
758
938
  }
759
939
  element(node, scope) {
940
+ if (node.name === "Slot") return "(children ?? [])";
760
941
  if (node.name === "List" && !this.components.has("List")) return this.list(node, scope);
761
942
  if (node.name === "Question" && !this.components.has("Question")) {
762
943
  if (!node.arg || !node.children.length) fail(`Question needs text and an answer, like: Question "Is it free?" { Text "Yes" }`, node);
763
944
  const asked = this.expr(node.arg, scope);
764
- const props2 = node.props.map((p) => this.prop(p, "Question", scope));
945
+ const hasHeadingSize = node.props.some((p) => p.key === "size");
946
+ const headingProps = node.props.filter((p) => ["size", "weight", "fontWeight", "color"].includes(p.key)).map((p) => this.prop(p, "Question", scope));
947
+ const props2 = node.props.filter((p) => !["size", "weight", "fontWeight", "color", "layout"].includes(p.key)).map((p) => this.prop(p, "Question", scope));
948
+ const layout = node.props.find((p) => p.key === "layout");
949
+ const direction = layout?.value.kind === "Expr" ? this.expr(layout.value.expr, scope, true) : '"column"';
765
950
  const answer = node.children.map((c) => this.view(c, scope)).join(", ");
766
- return `__h("section", { ${[`flex: true`, `direction: "column"`, `gap: 8`, `"data-orvyn-question": ${asked}`, ...props2].join(", ")} }, [__h("h2", { size: 20 }, [${asked}]), ${answer}])`;
951
+ const headingAttrs = [...hasHeadingSize ? [] : ["size: 20"], ...headingProps].join(", ");
952
+ return `__h("section", { ${[`flex: true`, `direction: ${direction}`, `gap: 8`, `"data-orvyn-question": ${asked}`, ...props2].join(", ")} }, [__h("h2", { ${headingAttrs} }, [${asked}]), ${answer}])`;
767
953
  }
768
954
  if ((node.name === "Checkbox" || node.name === "Switch") && !this.components.has(node.name)) return this.toggle(node, scope);
769
955
  if (node.name === "Select" && !this.components.has("Select")) return this.select(node, scope);
@@ -9,6 +9,7 @@ import android.graphics.Color
9
9
  import android.os.Bundle
10
10
  import android.os.Handler
11
11
  import android.os.Looper
12
+ import android.view.View
12
13
  import android.view.ViewGroup
13
14
  import android.widget.FrameLayout
14
15
  import android.widget.ScrollView
@@ -70,6 +71,27 @@ class MainActivity : Activity() {
70
71
  super.onBackPressed()
71
72
  }
72
73
 
74
+ // scrollTo("section-about") in .orv code: find the view with that label
75
+ fun scrollToLabel(label: String) {
76
+ if (label == "top") { scroll.smoothScrollTo(0, 0); return }
77
+ val target = findLabelled(container, label) ?: return
78
+ var top = 0
79
+ var view: View? = target
80
+ while (view != null && view !== container) {
81
+ top += view.top
82
+ view = view.parent as? View
83
+ }
84
+ scroll.smoothScrollTo(0, top)
85
+ }
86
+
87
+ private fun findLabelled(view: View, label: String): View? {
88
+ if (view.contentDescription?.toString() == label) return view
89
+ if (view is ViewGroup) {
90
+ for (i in 0 until view.childCount) findLabelled(view.getChildAt(i), label)?.let { return it }
91
+ }
92
+ return null
93
+ }
94
+
73
95
  private fun showTree(tree: JSONObject) {
74
96
  lastTree = tree
75
97
  val theme = tree.optJSONObject("theme")
@@ -7,6 +7,8 @@ package dev.orvyn.runtime
7
7
 
8
8
  import android.annotation.SuppressLint
9
9
  import android.app.Activity
10
+ import android.content.Intent
11
+ import android.net.Uri
10
12
  import android.os.Handler
11
13
  import android.os.Looper
12
14
  import android.security.keystore.KeyGenParameterSpec
@@ -124,12 +126,19 @@ class OrvynEngine(
124
126
  // a fresh page, so nothing from the previous version keeps running
125
127
  private fun load(code: String, initialUrl: String?) {
126
128
  val app = code.replace("</script", "<\\/script")
129
+ val metrics = activity.resources.displayMetrics
130
+ val viewportWidth = metrics.widthPixels / metrics.density
131
+ val viewportHeight = metrics.heightPixels / metrics.density
127
132
 
128
133
  val initialUrlJs = if (initialUrl != null) "window.__orvynInitialUrl = ${JSONObject.quote(initialUrl)};" else ""
129
134
  val shim = """
130
135
  $initialUrlJs
136
+ window.__orvynPlatform = "android";
137
+ window.__orvynViewport = { width: $viewportWidth, height: $viewportHeight };
131
138
  window.__orvynRender = function (json) { OrvynHost.render(json) };
132
139
  window.__orvynDevice = function (id, kind) { OrvynHost.device(id, kind) };
140
+ window.__orvynOpenExternal = function (url) { OrvynHost.openExternal(url) };
141
+ window.__orvynScrollTo = function (label) { OrvynHost.scrollTo(String(label)) };
133
142
  window.__orvynFetch = function (id, url, method, body, headers) {
134
143
  OrvynHost.fetch(id, url, method, body == null ? null : String(body), headers)
135
144
  };
@@ -174,6 +183,19 @@ class OrvynEngine(
174
183
  }
175
184
 
176
185
  inner class Bridge {
186
+ @JavascriptInterface
187
+ fun scrollTo(label: String) {
188
+ main.post { (activity as? MainActivity)?.scrollToLabel(label) }
189
+ }
190
+
191
+ @JavascriptInterface
192
+ fun openExternal(url: String) {
193
+ main.post {
194
+ try { activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) }
195
+ catch (error: Exception) { Log.w("Orvyn", "Could not open link", error) }
196
+ }
197
+ }
198
+
177
199
  @JavascriptInterface
178
200
  fun render(json: String) {
179
201
  val tree = JSONObject(json)