orvyn-lang 0.1.1 → 0.3.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.
Files changed (74) hide show
  1. package/GUIDE.md +149 -0
  2. package/LANGUAGE.md +877 -24
  3. package/README.md +227 -131
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +216 -489
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +102 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +498 -64
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +160 -0
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +43 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +154 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +519 -40
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/build.js +130 -60
  27. package/src/lang/native/config.js +108 -0
  28. package/src/lang/native/ios/OrvynApp.swift +6 -0
  29. package/src/lang/native/ios/OrvynEngine.swift +268 -4
  30. package/src/lang/native/ios/OrvynViews.swift +429 -31
  31. package/src/lang/native/ios.js +75 -2
  32. package/src/lang/native-runtime.js +423 -57
  33. package/src/lang/page.js +52 -0
  34. package/src/lang/parser.js +243 -15
  35. package/src/lang/prerender.js +300 -0
  36. package/src/lang/read-import.js +11 -0
  37. package/src/lang/router.js +266 -0
  38. package/src/lang/runtime-shared.js +820 -10
  39. package/src/lang/runtime.js +375 -52
  40. package/src/lang/select.js +13 -0
  41. package/src/lang/server-code.js +233 -0
  42. package/src/lang/server-export.js +78 -0
  43. package/src/lang/server-libs.js +53 -0
  44. package/src/lang/server.js +409 -0
  45. package/src/lang/test-runner.js +134 -0
  46. package/src/lang/types.js +312 -0
  47. package/src/lang/validation.js +55 -0
  48. package/src/lang/vite-plugin.js +82 -3
  49. package/src/lang/web-overlay.js +578 -0
  50. package/src/lang/widgets.js +94 -0
  51. package/src/lang/words.js +38 -0
  52. package/src/runtime/mount.js +116 -27
  53. package/src/runtime/patch.js +90 -11
  54. package/src/runtime/style.js +11 -1
  55. package/src/styling/fluid.js +91 -4
  56. package/src/styling/spec.js +306 -0
  57. package/src/core/context.js +0 -19
  58. package/src/core/lifecycle.js +0 -8
  59. package/src/core/resource.js +0 -27
  60. package/src/core/router.js +0 -20
  61. package/src/core/theme.js +0 -10
  62. package/src/devtools/devicePreview/PreviewFrame.js +0 -214
  63. package/src/devtools/devicePreview/index.js +0 -6
  64. package/src/devtools/overlay.js +0 -105
  65. package/src/runtime/createRenderer.js +0 -22
  66. package/src/runtime/h.js +0 -93
  67. package/src/runtime/hydrate.js +0 -59
  68. package/src/runtime/jsx-dev-runtime.js +0 -7
  69. package/src/runtime/jsx-runtime.js +0 -13
  70. package/src/runtime/partialHydration.js +0 -154
  71. package/src/runtime/platform.js +0 -135
  72. package/src/runtime/renderToStream.js +0 -127
  73. package/src/runtime/renderToString.js +0 -121
  74. package/src/runtime/resume.js +0 -62
@@ -0,0 +1,160 @@
1
+ import { onCleanup, signal } from "../core/signal.js";
2
+ import { createVNode } from "../runtime/vnode.js";
3
+ import { validate } from "./validation.js";
4
+ import { currentComponentInstance, errorText } from "./runtime-shared.js";
5
+ const RULE_KEYS = ["required", "minLength", "maxLength", "email", "label", "message"];
6
+ const stateIds = /* @__PURE__ */ new WeakMap();
7
+ let nextId = 0;
8
+ function formCache() {
9
+ return /* @__PURE__ */ new Map();
10
+ }
11
+ function createForm(cache, slot, props, children) {
12
+ const fields = [];
13
+ const collect = (value, path) => {
14
+ if (Array.isArray(value)) return value.forEach((child, i) => collect(child, `${path}.${i}`));
15
+ if (!value || typeof value !== "object" || !value.tag || value.tag === "form") return;
16
+ if (value.tag === "input" || value.tag === "textarea" || value.tag === "select") {
17
+ const rules2 = {};
18
+ for (const key2 of RULE_KEYS) if (value.props[key2] !== void 0) rules2[key2] = value.props[key2];
19
+ if (value.props.type === "email") rules2.email = true;
20
+ if (Object.keys(rules2).length) {
21
+ if (!value.props.onInput) {
22
+ throw new Error('[Orvyn] A validated Input needs bind, like Input "Name", bind: name, required: true');
23
+ }
24
+ rules2.label ??= value.props.placeholder || "This field";
25
+ fields.push({ id: path, props: value.props, binding: value.props.onInput?.binding, rules: rules2 });
26
+ }
27
+ }
28
+ collect(value.children, `${path}.c`);
29
+ };
30
+ collect(children, "field");
31
+ const identity = fields.map((field) => {
32
+ const binding = field.binding;
33
+ if (!binding) return field.id;
34
+ if (!stateIds.has(binding.state)) stateIds.set(binding.state, ++nextId);
35
+ return [stateIds.get(binding.state), binding.key, binding.indexed];
36
+ });
37
+ const key = JSON.stringify([currentComponentInstance(), slot, props.key ?? identity]);
38
+ let errors = cache.get(key);
39
+ if (!errors) {
40
+ errors = {
41
+ errors: signal({}),
42
+ pending: signal(false),
43
+ submitError: signal(""),
44
+ attempted: false,
45
+ disposed: false,
46
+ id: ++nextId,
47
+ users: 0
48
+ };
49
+ cache.set(key, errors);
50
+ }
51
+ const entry = errors;
52
+ entry.users++;
53
+ onCleanup(() => {
54
+ entry.users--;
55
+ queueMicrotask(() => {
56
+ if (entry.users === 0 && cache.get(key) === entry) {
57
+ entry.disposed = true;
58
+ cache.delete(key);
59
+ entry.errors.dispose();
60
+ entry.pending.dispose();
61
+ entry.submitError.dispose();
62
+ }
63
+ });
64
+ });
65
+ const currentErrors = errors.errors.get();
66
+ const isPending = errors.pending.get();
67
+ const submitError = errors.submitError.get();
68
+ const byPath = new Map(fields.map((field) => [field.id, field]));
69
+ const values = () => Object.fromEntries(fields.map((field) => [
70
+ field.id,
71
+ field.binding ? field.binding.read() : field.props.value
72
+ ]));
73
+ const rules = Object.fromEntries(fields.map((field) => [field.id, field.rules]));
74
+ validate(values(), rules);
75
+ const decorate = (value, path) => {
76
+ if (Array.isArray(value)) return value.map((child, i) => decorate(child, `${path}.${i}`));
77
+ if (!value || typeof value !== "object" || !value.tag || value.tag === "form") return value;
78
+ const field = byPath.get(path);
79
+ if (field) {
80
+ const inputProps = { ...value.props };
81
+ for (const key2 of RULE_KEYS) delete inputProps[key2];
82
+ inputProps["aria-invalid"] = !!currentErrors[field.id];
83
+ if (currentErrors[field.id]) inputProps.error = currentErrors[field.id];
84
+ inputProps["aria-required"] = !!field.rules.required;
85
+ inputProps["aria-label"] ??= field.rules.label;
86
+ const errorId = `orvyn-form-${errors.id}-${field.id}-error`;
87
+ inputProps["aria-describedby"] = [inputProps["aria-describedby"], errorId].filter(Boolean).join(" ");
88
+ const original = inputProps.onInput;
89
+ if (original) inputProps.onInput = (event) => {
90
+ const result = original(event);
91
+ if (errors.attempted) {
92
+ const checked = validate(
93
+ { [field.id]: field.binding ? field.binding.read() : event.target.value },
94
+ { [field.id]: field.rules }
95
+ );
96
+ const next = { ...errors.errors.get() };
97
+ if (checked.valid) delete next[field.id];
98
+ else next[field.id] = checked.errors[field.id];
99
+ errors.errors.set(next);
100
+ }
101
+ return result;
102
+ };
103
+ return createVNode("div", { key: value.props.key ?? path, flex: true, direction: "column", gap: 4 }, [
104
+ createVNode(value.tag, inputProps, value.children),
105
+ createVNode("span", { id: errorId, color: "red", role: "alert" }, [currentErrors[field.id] ?? ""])
106
+ ]);
107
+ }
108
+ if (value.tag === "button" && value.props.type === "submit" && value.props.loading === void 0) {
109
+ return createVNode(value.tag, { ...value.props, loading: isPending }, decorate(value.children, `${path}.c`));
110
+ }
111
+ return createVNode(value.tag, value.props, decorate(value.children, `${path}.c`));
112
+ };
113
+ const { onError, ...formProps } = props;
114
+ const decorated = decorate(children, "field");
115
+ const formChildren = submitError ? [...decorated, createVNode("span", { key: `orvyn-form-err-${errors.id}`, color: "red", role: "alert" }, [submitError])] : decorated;
116
+ return createVNode("form", {
117
+ ...formProps,
118
+ noValidate: true,
119
+ onSubmit: (event) => {
120
+ event?.preventDefault?.();
121
+ if (entry.pending.get()) return;
122
+ const result = validate(values(), rules);
123
+ errors.attempted = true;
124
+ errors.errors.set(result.errors);
125
+ if (!result.valid) return;
126
+ entry.submitError.set("");
127
+ try {
128
+ const outcome = props.onSubmit();
129
+ if (outcome && typeof outcome.then === "function") {
130
+ entry.pending.set(true);
131
+ return Promise.resolve(outcome).then(
132
+ (value) => {
133
+ if (!entry.disposed) entry.pending.set(false);
134
+ return value;
135
+ },
136
+ (error) => {
137
+ if (!entry.disposed) {
138
+ entry.pending.set(false);
139
+ const message = errorText(error);
140
+ entry.submitError.set(message);
141
+ onError?.(message);
142
+ }
143
+ }
144
+ );
145
+ }
146
+ return outcome;
147
+ } catch (error) {
148
+ if (!entry.disposed) {
149
+ const message = errorText(error);
150
+ entry.submitError.set(message);
151
+ onError?.(message);
152
+ }
153
+ }
154
+ }
155
+ }, formChildren);
156
+ }
157
+ export {
158
+ createForm,
159
+ formCache
160
+ };
package/src/lang/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { parse } from "./parser.js";
2
2
  import { generate } from "./codegen.js";
3
+ import { checkTypes } from "./types.js";
3
4
  import { tokenize, OrvynSyntaxError } from "./lexer.js";
4
5
  import { parse as parse2 } from "./parser.js";
5
6
  function compile(source, options = {}) {
6
- return generate(parse(source), options);
7
+ return generate(checkTypes(parse(source), options.resolveImport), options);
7
8
  }
8
9
  export {
9
10
  OrvynSyntaxError,
package/src/lang/lexer.js CHANGED
@@ -13,6 +13,8 @@ const KEYWORDS = /* @__PURE__ */ new Set([
13
13
  "use",
14
14
  "from",
15
15
  "start",
16
+ "try",
17
+ "catch",
16
18
  "true",
17
19
  "false",
18
20
  "null"
@@ -0,0 +1,44 @@
1
+ import { createVNode } from "../runtime/vnode.js";
2
+ import { componentState } from "./runtime-shared.js";
3
+ const OVERSCAN = 5;
4
+ function createList(windowed) {
5
+ return function List(props) {
6
+ const { items, row, rowHeight = 48, height = 480, keyOf, children: _children, ...style } = props;
7
+ const all = Array.from(items ?? []);
8
+ const make = (item, index) => createVNode("div", {
9
+ key: keyOf ? `k:${keyOf(item)}` : `i:${index}`,
10
+ flex: true,
11
+ direction: "column",
12
+ justify: "center",
13
+ height: rowHeight,
14
+ shrink: 0,
15
+ overflow: "hidden"
16
+ }, row(item));
17
+ if (!windowed) {
18
+ return [createVNode("div", { ...style, height, nativeRole: "list", rowHeight }, all.map(make))];
19
+ }
20
+ const scroll = componentState()(0, () => 0);
21
+ const visible = Math.ceil(Number(height) / rowHeight) || 20;
22
+ const first = Math.max(0, Math.min(Math.floor(scroll.get() / rowHeight) - OVERSCAN, all.length - visible));
23
+ const end = Math.min(all.length, first + visible + OVERSCAN * 2);
24
+ const spacer = (key, rows) => createVNode("div", { key, height: rows * rowHeight, shrink: 0 }, []);
25
+ return [createVNode("div", {
26
+ ...style,
27
+ height,
28
+ overflowY: "auto",
29
+ role: "list",
30
+ onScroll: (event) => scroll.set(event.target.scrollTop)
31
+ }, [
32
+ spacer("before", first),
33
+ ...all.slice(first, end).map((item, i) => make(item, first + i)),
34
+ spacer("after", all.length - end)
35
+ ])];
36
+ };
37
+ }
38
+ function keyed(key, nodes) {
39
+ return nodes.flat(Infinity).map((node, i) => node && typeof node === "object" && "props" in node ? { ...node, props: { ...node.props, key: `${String(key)}:${i}` } } : node);
40
+ }
41
+ export {
42
+ createList,
43
+ keyed
44
+ };
@@ -3,6 +3,8 @@
3
3
  package dev.orvyn.runtime
4
4
 
5
5
  import android.app.Activity
6
+ import android.content.Intent
7
+ import android.content.pm.ApplicationInfo
6
8
  import android.graphics.Color
7
9
  import android.os.Bundle
8
10
  import android.os.Handler
@@ -17,13 +19,14 @@ class MainActivity : Activity() {
17
19
  private lateinit var engine: OrvynEngine
18
20
  private lateinit var renderer: OrvynRenderer
19
21
  private lateinit var container: FrameLayout
22
+ private lateinit var scroll: ScrollView
20
23
  private var lastTree: JSONObject? = null
21
24
 
22
25
  override fun onCreate(savedInstanceState: Bundle?) {
23
26
  super.onCreate(savedInstanceState)
24
27
 
25
28
  container = FrameLayout(this)
26
- val scroll = ScrollView(this).apply {
29
+ scroll = ScrollView(this).apply {
27
30
  fitsSystemWindows = true
28
31
  setBackgroundColor(Color.WHITE)
29
32
  addView(container, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
@@ -32,15 +35,51 @@ class MainActivity : Activity() {
32
35
 
33
36
  renderer = OrvynRenderer(this) { handler, value -> engine.fire(handler, value) }
34
37
  engine = OrvynEngine(this, ::showTree, ::showError)
35
- engine.start()
38
+ // Test and live reload hooks work in debug builds only: any app can send
39
+ // intent extras, so a released app must ignore them.
40
+ val debuggable = applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
41
+ engine.start(intent?.dataString, if (debuggable) intent?.getStringExtra("orvynDevServer") else null)
36
42
 
37
- intent.getStringExtra("orvynTest")?.let { runTestScript(it) }
43
+ if (debuggable) intent.getStringExtra("orvynTest")?.let { runTestScript(it) }
44
+ }
45
+
46
+ @Deprecated("Deprecated in Java")
47
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
48
+ @Suppress("DEPRECATION")
49
+ super.onActivityResult(requestCode, resultCode, data)
50
+ engine.device.result(requestCode, resultCode, data)
51
+ }
52
+
53
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
54
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)
55
+ engine.device.permission(requestCode, grantResults)
56
+ }
57
+
58
+ override fun onNewIntent(intent: Intent) {
59
+ super.onNewIntent(intent)
60
+ intent.dataString?.let { engine.openUrl(it) }
61
+ }
62
+
63
+ @Deprecated("Deprecated in Java")
64
+ override fun onBackPressed() {
65
+ if (lastTree?.optBoolean("canGoBack", false) == true) {
66
+ engine.goBack()
67
+ return
68
+ }
69
+ @Suppress("DEPRECATION")
70
+ super.onBackPressed()
38
71
  }
39
72
 
40
73
  private fun showTree(tree: JSONObject) {
41
74
  lastTree = tree
75
+ val theme = tree.optJSONObject("theme")
76
+ renderer.setTheme(theme)
77
+ theme?.optString("bg")?.let { bg ->
78
+ try { scroll.setBackgroundColor(Color.parseColor(bg)) } catch (_: Exception) {}
79
+ }
80
+ val availableWidth = if (container.width > 0) container.width else resources.displayMetrics.widthPixels
42
81
  val existing = if (container.childCount > 0) container.getChildAt(0) else null
43
- val view = renderer.render(tree, existing, parentType = "root")
82
+ val view = renderer.render(tree, existing, parentType = "root", availableWidthPx = availableWidth)
44
83
  if (view !== existing) {
45
84
  container.removeAllViews()
46
85
  container.addView(view)
@@ -0,0 +1,163 @@
1
+ // Generated by Orvyn. Do not edit; rebuild with `orvyn build android app.orv`.
2
+ //
3
+ // Camera, photos, files and location. One request at a time.
4
+
5
+ package dev.orvyn.runtime
6
+
7
+ import android.Manifest
8
+ import android.app.Activity
9
+ import android.content.ActivityNotFoundException
10
+ import android.content.Intent
11
+ import android.content.pm.PackageManager
12
+ import android.graphics.Bitmap
13
+ import android.graphics.BitmapFactory
14
+ import android.location.Location
15
+ import android.location.LocationListener
16
+ import android.location.LocationManager
17
+ import android.os.Handler
18
+ import android.os.Looper
19
+ import android.provider.MediaStore
20
+ import android.provider.OpenableColumns
21
+ import android.util.Base64
22
+ import org.json.JSONObject
23
+ import java.io.ByteArrayOutputStream
24
+ import kotlin.concurrent.thread
25
+
26
+ class OrvynDevice(private val activity: Activity, private val done: (Int, String, String) -> Unit) {
27
+ private val main = Handler(Looper.getMainLooper())
28
+ private var waiting: Int? = null
29
+ private var kind = ""
30
+
31
+ private val pickCode = 7001
32
+ private val cameraCode = 7002
33
+ private val permissionCode = 7003
34
+
35
+ fun ask(id: Int, what: String) {
36
+ if (waiting != null) return done(id, "", "Already waiting for another choice")
37
+ waiting = id
38
+ kind = what
39
+ when (what) {
40
+ "photo", "file" -> open(Intent(Intent.ACTION_GET_CONTENT).apply {
41
+ type = if (what == "photo") "image/*" else "*/*"
42
+ addCategory(Intent.CATEGORY_OPENABLE)
43
+ }, pickCode)
44
+ "camera" -> withPermission(Manifest.permission.CAMERA)
45
+ "location" -> withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
46
+ else -> finish(error = "Unknown request: $what")
47
+ }
48
+ }
49
+
50
+ private fun withPermission(permission: String) {
51
+ if (activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) return go()
52
+ val wanted = if (kind == "location") {
53
+ arrayOf(permission, Manifest.permission.ACCESS_COARSE_LOCATION)
54
+ } else arrayOf(permission)
55
+ activity.requestPermissions(wanted, permissionCode)
56
+ }
57
+
58
+ fun permission(code: Int, results: IntArray) {
59
+ if (code != permissionCode || waiting == null) return
60
+ if (results.any { it == PackageManager.PERMISSION_GRANTED }) go()
61
+ else finish(error = if (kind == "camera") "The camera was not allowed" else "Location was not allowed")
62
+ }
63
+
64
+ private fun go() {
65
+ // the camera hands back a small preview picture
66
+ if (kind == "camera") return open(Intent(MediaStore.ACTION_IMAGE_CAPTURE), cameraCode)
67
+ locate()
68
+ }
69
+
70
+ private fun open(intent: Intent, code: Int) {
71
+ try {
72
+ @Suppress("DEPRECATION")
73
+ activity.startActivityForResult(intent, code)
74
+ } catch (_: ActivityNotFoundException) {
75
+ finish(error = "No app on this phone can do that")
76
+ }
77
+ }
78
+
79
+ @Suppress("MissingPermission")
80
+ private fun locate() {
81
+ val manager = activity.getSystemService(Activity.LOCATION_SERVICE) as LocationManager
82
+ val provider = listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER)
83
+ .firstOrNull { manager.isProviderEnabled(it) } ?: return finish(error = "Turn on location on this phone")
84
+ val id = waiting
85
+ val listener = object : LocationListener {
86
+ override fun onLocationChanged(place: Location) {
87
+ manager.removeUpdates(this)
88
+ if (waiting != id) return
89
+ finish(JSONObject().put("latitude", place.latitude).put("longitude", place.longitude)
90
+ .put("accuracy", place.accuracy.toDouble()).toString())
91
+ }
92
+
93
+ @Deprecated("Deprecated in Java")
94
+ override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}
95
+ override fun onProviderEnabled(provider: String) {}
96
+ override fun onProviderDisabled(provider: String) {}
97
+ }
98
+ try {
99
+ manager.requestLocationUpdates(provider, 0L, 0f, listener, Looper.getMainLooper())
100
+ } catch (_: SecurityException) {
101
+ return finish(error = "Location was not allowed")
102
+ }
103
+ main.postDelayed({
104
+ if (waiting == id) {
105
+ manager.removeUpdates(listener)
106
+ finish(error = "Could not get the location")
107
+ }
108
+ }, 15000)
109
+ }
110
+
111
+ fun result(code: Int, resultCode: Int, data: Intent?) {
112
+ if ((code != pickCode && code != cameraCode) || waiting == null) return
113
+ if (resultCode != Activity.RESULT_OK) return finish()
114
+ if (code == cameraCode) {
115
+ @Suppress("DEPRECATION")
116
+ val picture = data?.extras?.get("data") as? Bitmap ?: return finish(error = "The camera gave no picture")
117
+ return finish(jpeg(picture))
118
+ }
119
+ val uri = data?.data ?: return finish()
120
+ val photo = kind == "photo"
121
+ thread {
122
+ try {
123
+ val bytes = activity.contentResolver.openInputStream(uri)!!.use { it.readBytes() }
124
+ val result = if (photo) {
125
+ // large photos are scaled down so the app stays quick
126
+ val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
127
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, size)
128
+ val options = BitmapFactory.Options().apply {
129
+ inSampleSize = 1
130
+ while (maxOf(size.outWidth, size.outHeight) / inSampleSize > 1600) inSampleSize *= 2
131
+ }
132
+ jpeg(BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)!!)
133
+ } else {
134
+ var name = "file"
135
+ activity.contentResolver.query(uri, null, null, null, null)?.use {
136
+ val column = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
137
+ if (column >= 0 && it.moveToFirst()) name = it.getString(column)
138
+ }
139
+ file(name, activity.contentResolver.getType(uri) ?: "application/octet-stream", bytes)
140
+ }
141
+ main.post { finish(result) }
142
+ } catch (_: Throwable) {
143
+ main.post { finish(error = "Could not read the file") }
144
+ }
145
+ }
146
+ }
147
+
148
+ private fun jpeg(picture: Bitmap): String {
149
+ val out = ByteArrayOutputStream()
150
+ picture.compress(Bitmap.CompressFormat.JPEG, 85, out)
151
+ return file("photo.jpg", "image/jpeg", out.toByteArray())
152
+ }
153
+
154
+ private fun file(name: String, type: String, bytes: ByteArray): String =
155
+ JSONObject().put("name", name).put("type", type).put("size", bytes.size)
156
+ .put("dataUrl", "data:$type;base64," + Base64.encodeToString(bytes, Base64.NO_WRAP)).toString()
157
+
158
+ private fun finish(json: String = "", error: String = "") {
159
+ val id = waiting ?: return
160
+ waiting = null
161
+ done(id, json, error)
162
+ }
163
+ }