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.
@@ -0,0 +1,39 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { join, relative, sep } from "node:path";
3
+ const IMAGE_TYPES = {
4
+ png: "image/png",
5
+ jpg: "image/jpeg",
6
+ jpeg: "image/jpeg",
7
+ webp: "image/webp",
8
+ gif: "image/gif",
9
+ avif: "image/avif"
10
+ };
11
+ function publicImages(cwd) {
12
+ const root = join(cwd, "public");
13
+ const found = [];
14
+ const visit = (dir) => {
15
+ for (const name of readdirSync(dir).sort()) {
16
+ const full = join(dir, name);
17
+ if (statSync(full).isDirectory()) {
18
+ visit(full);
19
+ continue;
20
+ }
21
+ const ext = name.split(".").pop()?.toLowerCase() ?? "";
22
+ if (IMAGE_TYPES[ext]) found.push({ path: "/" + relative(root, full).split(sep).join("/"), file: full });
23
+ }
24
+ };
25
+ if (existsSync(root)) visit(root);
26
+ return found;
27
+ }
28
+ function nativeAssetPrelude(cwd) {
29
+ return `globalThis.__orvynAssets = ${JSON.stringify(publicImages(cwd).map((image) => image.path))};
30
+ `;
31
+ }
32
+ function bundledImages(cwd, folder) {
33
+ return publicImages(cwd).map((image) => ({ path: folder + image.path, content: "", copyFrom: image.file }));
34
+ }
35
+ export {
36
+ bundledImages,
37
+ nativeAssetPrelude,
38
+ publicImages
39
+ };
@@ -7,6 +7,8 @@ import { loadEnv } from "../env.js";
7
7
  import { loadNativeConfig, releaseProblems } from "./config.js";
8
8
  import { generateIOSProject, iosTargetName } from "./ios.js";
9
9
  import { generateAndroidProject } from "./android.js";
10
+ import { bundledImages, nativeAssetPrelude } from "./assets.js";
11
+ import { checkNativeProject } from "./compatibility.js";
10
12
  function writeFiles(outDir, files) {
11
13
  rmSync(outDir, { recursive: true, force: true });
12
14
  for (const file of files) {
@@ -33,20 +35,23 @@ ${problems.map((p) => ` - ${p}`).join("\n")}
33
35
  }
34
36
  }
35
37
  const env = await loadEnv(cwd, options.defaultEnv ?? "prod");
38
+ for (const warning of checkNativeProject(resolve(cwd, entry))) {
39
+ log(`[Orvyn] \u26A0 ${warning.file}:${warning.line}:${warning.col} ${warning.message}`);
40
+ }
36
41
  log(`[Orvyn] Compiling ${entry} for ${target === "ios" ? "iOS" : "Android"} (${env.name})...`);
37
- const appJs = await bundleNative(resolve(cwd, entry), { appId: config.appId, env });
42
+ const appJs = nativeAssetPrelude(cwd) + await bundleNative(resolve(cwd, entry), { appId: config.appId, env });
38
43
  for (const [, need] of appJs.matchAll(/__orvyn_needs_(camera|location)/g)) {
39
44
  if (!(need in (config.permissions ?? {}))) {
40
45
  throw new Error(`This app uses the ${need}. Add to orvyn.config.js: native: { permissions: { ${need}: "Why you need it" } }`);
41
46
  }
42
47
  }
43
48
  if (target === "ios") {
44
- writeFiles(outDir, generateIOSProject(appJs, config));
49
+ writeFiles(outDir, [...generateIOSProject(appJs, config), ...bundledImages(cwd, `${iosTargetName(config.appName)}/public`)]);
45
50
  const name = iosTargetName(config.appName);
46
51
  log(`[Orvyn] \u2713 Xcode project \u2192 dist/ios/${name}.xcodeproj`);
47
52
  return options.release ? releaseIOS(outDir, name, config, log) : compileIOS(outDir, name, log);
48
53
  }
49
- writeFiles(outDir, generateAndroidProject(appJs, config));
54
+ writeFiles(outDir, [...generateAndroidProject(appJs, config), ...bundledImages(cwd, "app/src/main/assets/public")]);
50
55
  log("[Orvyn] \u2713 Android Studio project \u2192 dist/android/");
51
56
  return compileAndroid(outDir, log, Boolean(options.release));
52
57
  }
@@ -205,10 +210,12 @@ async function devNativeApp(target, entry, options) {
205
210
  const { cwd, log } = options;
206
211
  let code = "";
207
212
  let version = 0;
213
+ const launchAssets = nativeAssetPrelude(cwd);
208
214
  const rebuild = async (reason) => {
209
215
  const started = Date.now();
210
216
  try {
211
- code = await bundleNative(resolve(cwd, entry), { dev: true, env: await loadEnv(cwd, "dev") });
217
+ if (nativeAssetPrelude(cwd) !== launchAssets) log("[Orvyn] public/ images changed. Restart `orvyn dev` to put them in the app");
218
+ code = launchAssets + await bundleNative(resolve(cwd, entry), { dev: true, env: await loadEnv(cwd, "dev") });
212
219
  version++;
213
220
  log(`[Orvyn] ${reason} \u2192 reloaded in ${Date.now() - started}ms`);
214
221
  } catch (error) {
@@ -244,7 +251,7 @@ async function devNativeApp(target, entry, options) {
244
251
  const watchDir = dirname(resolve(cwd, entry));
245
252
  let timer = null;
246
253
  watch(watchDir, { recursive: true }, (_event, file) => {
247
- if (!file || !String(file).endsWith(".orv")) return;
254
+ if (!file || !/\.(orv|m?js|ts)$/.test(String(file))) return;
248
255
  if (timer) clearTimeout(timer);
249
256
  timer = setTimeout(() => rebuild(`${file} changed`), 80);
250
257
  });
@@ -0,0 +1,57 @@
1
+ import { STYLE_SPEC } from "../../styling/spec.js";
2
+ import { collectProjectPrograms } from "../page-files.js";
3
+ import { nativeSize } from "../native-size.js";
4
+ const SIZE_PROPS = /* @__PURE__ */ new Set(["width", "height", "minWidth", "minHeight", "maxWidth", "maxHeight", "size"]);
5
+ function textIn(value) {
6
+ if (!value || typeof value !== "object") return [];
7
+ if (Array.isArray(value)) return value.flatMap(textIn);
8
+ const node = value;
9
+ const own = node.kind === "String" && Array.isArray(node.parts) ? node.parts.filter((p) => typeof p === "string") : [];
10
+ return [...own, ...Object.values(node).flatMap((child) => typeof child === "object" ? textIn(child) : [])];
11
+ }
12
+ function checkNativeCompatibility(program) {
13
+ const warnings = [];
14
+ const visit = (node) => {
15
+ if (node.kind === "ViewIf") {
16
+ node.then.forEach(visit);
17
+ node.else?.forEach(visit);
18
+ return;
19
+ }
20
+ if (node.kind === "ViewFor") {
21
+ node.body.forEach(visit);
22
+ return;
23
+ }
24
+ if (node.name === "Image" && node.arg && textIn(node.arg).some((text) => /\.svg(\?|#|$)/i.test(text))) {
25
+ warnings.push({ line: node.line, col: node.col, message: `Native: SVG images don't show in the installed app. Use a .png or .jpg copy.` });
26
+ }
27
+ for (const prop of node.props) {
28
+ const name = prop.key;
29
+ if (STYLE_SPEC[name]?.support === "web") {
30
+ warnings.push({ line: node.line, col: node.col, message: `Native: "${name}" only works on the web; the installed app ignores it.` });
31
+ }
32
+ const expr = prop.value.kind === "Expr" ? prop.value.expr : null;
33
+ if (SIZE_PROPS.has(name) && expr?.kind === "String" && expr.parts.length === 1 && typeof expr.parts[0] === "string") {
34
+ const raw = expr.parts[0];
35
+ if (/\bclamp\(/.test(raw)) {
36
+ warnings.push({ line: node.line, col: node.col, message: `Native: ${name}: "${raw}" uses clamp(), which the installed app cannot calculate. Use a number or a mobile value.` });
37
+ } else if (/\b(?:calc|min|max)\(|\d+(?:vw|vh|rem|em)\b/.test(raw)) {
38
+ if (nativeSize(raw, { width: 390, height: 844 }) === void 0) {
39
+ warnings.push({ line: node.line, col: node.col, message: `Native: ${name}: "${raw}" cannot be calculated on phones. Use a number or a mobile value.` });
40
+ }
41
+ }
42
+ }
43
+ }
44
+ node.children.forEach(visit);
45
+ };
46
+ for (const decl of program.body) if (decl.kind === "Screen") decl.body.forEach(visit);
47
+ return warnings;
48
+ }
49
+ function checkNativeProject(entry) {
50
+ return collectProjectPrograms(entry).flatMap(
51
+ ({ file, program }) => checkNativeCompatibility(program).map((warning) => ({ ...warning, file }))
52
+ );
53
+ }
54
+ export {
55
+ checkNativeCompatibility,
56
+ checkNativeProject
57
+ };
@@ -27,6 +27,7 @@ struct ONode: Identifiable {
27
27
  let o: [String]
28
28
  let tap: Int?
29
29
  let change: Int?
30
+ let visible: Int?
30
31
  let c: [ONode]
31
32
  let theme: [String: Any]?
32
33
  let canGoBack: Bool
@@ -47,6 +48,7 @@ struct ONode: Identifiable {
47
48
  let e = d["e"] as? [String: Any] ?? [:]
48
49
  tap = (e["tap"] as? NSNumber)?.intValue
49
50
  change = (e["change"] as? NSNumber)?.intValue
51
+ visible = (e["visible"] as? NSNumber)?.intValue
50
52
  c = (d["c"] as? [[String: Any]] ?? []).map(ONode.init)
51
53
  theme = d["theme"] as? [String: Any]
52
54
  canGoBack = d["canGoBack"] as? Bool ?? false
@@ -56,6 +58,10 @@ struct ONode: Identifiable {
56
58
  final class OrvynEngine: ObservableObject {
57
59
  @Published var root: ONode?
58
60
  @Published var error: String?
61
+ /// scrollTo("section-about") asks the page to scroll to that label;
62
+ /// `scrollTick` makes the same label work twice in a row
63
+ @Published var scrollTarget: String?
64
+ @Published var scrollTick = 0
59
65
 
60
66
  /// Set by `orvyn dev ios` (e.g. http://127.0.0.1:8790). When present the app
61
67
  /// loads its code from your Mac and reloads when you save a .orv file.
@@ -147,6 +153,11 @@ final class OrvynEngine: ObservableObject {
147
153
  self.context = context
148
154
 
149
155
  installHost(context, generation)
156
+ context.setObject("ios", forKeyedSubscript: "__orvynPlatform" as NSString)
157
+ context.setObject([
158
+ "width": UIScreen.main.bounds.width,
159
+ "height": UIScreen.main.bounds.height
160
+ ], forKeyedSubscript: "__orvynViewport" as NSString)
150
161
  if let initialURL {
151
162
  context.setObject(initialURL, forKeyedSubscript: "__orvynInitialUrl" as NSString)
152
163
  }
@@ -198,6 +209,20 @@ final class OrvynEngine: ObservableObject {
198
209
  }
199
210
  context.setObject(render, forKeyedSubscript: "__orvynRender" as NSString)
200
211
 
212
+ let openExternal: @convention(block) (String) -> Void = { address in
213
+ guard let url = URL(string: address) else { return }
214
+ DispatchQueue.main.async { UIApplication.shared.open(url) }
215
+ }
216
+ context.setObject(openExternal, forKeyedSubscript: "__orvynOpenExternal" as NSString)
217
+
218
+ let scrollTo: @convention(block) (String) -> Void = { [weak self] label in
219
+ DispatchQueue.main.async {
220
+ self?.scrollTarget = label
221
+ self?.scrollTick += 1
222
+ }
223
+ }
224
+ context.setObject(scrollTo, forKeyedSubscript: "__orvynScrollTo" as NSString)
225
+
201
226
  let device: @convention(block) (Int, String) -> Void = { [weak self] id, kind in
202
227
  DispatchQueue.main.async {
203
228
  self?.device.ask(kind) { json, error in