orvyn-lang 0.2.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.
Files changed (63) hide show
  1. package/GUIDE.md +198 -0
  2. package/LANGUAGE.md +818 -30
  3. package/README.md +211 -250
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +207 -16
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +152 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +615 -58
  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 +69 -8
  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 +65 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +176 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +970 -50
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/assets.js +39 -0
  27. package/src/lang/native/build.js +140 -63
  28. package/src/lang/native/compatibility.js +57 -0
  29. package/src/lang/native/config.js +108 -0
  30. package/src/lang/native/ios/OrvynApp.swift +6 -0
  31. package/src/lang/native/ios/OrvynEngine.swift +291 -4
  32. package/src/lang/native/ios/OrvynViews.swift +769 -41
  33. package/src/lang/native/ios.js +81 -2
  34. package/src/lang/native-runtime.js +541 -55
  35. package/src/lang/native-size.js +53 -0
  36. package/src/lang/page-files.js +71 -0
  37. package/src/lang/page.js +63 -0
  38. package/src/lang/parser.js +278 -15
  39. package/src/lang/prerender.js +300 -0
  40. package/src/lang/read-import.js +12 -0
  41. package/src/lang/router.js +266 -0
  42. package/src/lang/runtime-shared.js +796 -10
  43. package/src/lang/runtime.js +399 -51
  44. package/src/lang/select.js +13 -0
  45. package/src/lang/server-code.js +233 -0
  46. package/src/lang/server-export.js +78 -0
  47. package/src/lang/server-libs.js +53 -0
  48. package/src/lang/server.js +409 -0
  49. package/src/lang/style-check.js +60 -0
  50. package/src/lang/test-runner.js +134 -0
  51. package/src/lang/types.js +317 -0
  52. package/src/lang/vite-plugin.js +108 -6
  53. package/src/lang/web-overlay.js +578 -0
  54. package/src/lang/widgets.js +94 -0
  55. package/src/lang/words.js +38 -0
  56. package/src/runtime/animations.js +24 -0
  57. package/src/runtime/appear.js +73 -0
  58. package/src/runtime/marquee.js +57 -0
  59. package/src/runtime/mount.js +120 -27
  60. package/src/runtime/patch.js +90 -11
  61. package/src/runtime/style.js +50 -9
  62. package/src/styling/fluid.js +129 -6
  63. package/src/styling/spec.js +319 -0
@@ -2,12 +2,28 @@
2
2
  //
3
3
  // Turns the Orvyn UI tree into native SwiftUI views.
4
4
 
5
+ import MapKit
5
6
  import SwiftUI
6
7
 
8
+ private struct OrvynWidthKey: EnvironmentKey {
9
+ static let defaultValue: CGFloat = 0
10
+ }
11
+
12
+ private extension EnvironmentValues {
13
+ var orvynWidth: CGFloat {
14
+ get { self[OrvynWidthKey.self] }
15
+ set { self[OrvynWidthKey.self] = newValue }
16
+ }
17
+ }
18
+
7
19
  struct OrvynRootView: View {
8
20
  @StateObject private var engine = OrvynEngine()
9
21
 
10
22
  var body: some View {
23
+ let rootTheme = engine.root?.theme
24
+ let isDark = (rootTheme?["dark"] as? Bool) ?? false
25
+ let bgColor = OStyle.color(rootTheme?["bg"]) ?? Color(.systemBackground)
26
+
11
27
  Group {
12
28
  if let error = engine.error {
13
29
  ScrollView {
@@ -17,14 +33,48 @@ struct OrvynRootView: View {
17
33
  .padding()
18
34
  }
19
35
  } else if let root = engine.root {
20
- ScrollView {
21
- ONodeView(node: root)
22
- .frame(maxWidth: .infinity, alignment: .topLeading)
36
+ GeometryReader { geo in
37
+ ScrollViewReader { proxy in
38
+ ScrollView {
39
+ ONodeView(node: root)
40
+ .frame(maxWidth: .infinity, alignment: .topLeading)
41
+ .environment(\.orvynWidth, geo.size.width)
42
+ .id("top")
43
+ }
44
+ .overlay(alignment: .top) {
45
+ if let sticky = OSticky.find(root) {
46
+ ONodeView(node: sticky, stretch: true, pinned: true)
47
+ .frame(maxWidth: .infinity)
48
+ .environment(\.orvynWidth, geo.size.width)
49
+ }
50
+ }
51
+ .onChange(of: engine.scrollTick) { _ in
52
+ guard let target = engine.scrollTarget else { return }
53
+ withAnimation(.easeInOut(duration: 0.5)) { proxy.scrollTo(target, anchor: .top) }
54
+ }
55
+ .onAppear {
56
+ // for screenshots and tests: start at a section
57
+ if let start = ProcessInfo.processInfo.environment["ORVYN_SCROLL_TO"] {
58
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { proxy.scrollTo(start, anchor: .top) }
59
+ }
60
+ }
61
+ }
23
62
  }
24
63
  } else {
25
64
  ProgressView()
26
65
  }
27
66
  }
67
+ .background(bgColor.ignoresSafeArea())
68
+ .preferredColorScheme(rootTheme != nil ? (isDark ? .dark : .light) : nil)
69
+ .onOpenURL { url in engine.openURL(url.absoluteString) }
70
+ .simultaneousGesture(
71
+ DragGesture(minimumDistance: 24)
72
+ .onEnded { value in
73
+ if engine.root?.canGoBack == true && value.startLocation.x < 28 && value.translation.width > 64 {
74
+ engine.goBack()
75
+ }
76
+ }
77
+ )
28
78
  .environmentObject(engine)
29
79
  // Cmd+R in the simulator reloads the app while `orvyn dev ios` runs
30
80
  .background(
@@ -40,16 +90,93 @@ struct ONodeView: View {
40
90
  let node: ONode
41
91
  // containers inside a Column fill the width, like on the web
42
92
  var stretch = false
93
+ /// the pinned copy of a sticky element; the one in the page keeps its space but is hidden
94
+ var pinned = false
43
95
  @EnvironmentObject private var engine: OrvynEngine
96
+ @Environment(\.orvynWidth) private var parentWidth
44
97
 
45
98
  var body: some View {
99
+ let rtl = node.s["rtl"] as? Bool
100
+ let content = coreView
101
+ .environment(\.orvynWidth, innerWidth)
102
+ .modifier(OCenterSelf(enabled: (node.s["centerSelf"] as? Bool) == true))
103
+ .modifier(OStickyPlaceholder(hidden: !pinned && (node.s["position"] as? String) == "sticky"))
104
+ .modifier(OLabel(text: node.a))
105
+ .modifier(OScrollAnchor(label: ["col", "box", "row"].contains(node.t) ? node.a : nil))
106
+ .modifier(OAppear(spec: node.s["appear"] as? String, from: node.s["appearFrom"] as? [String: Any], onShow: node.visible.map { handler in { engine.fire(handler) } }))
107
+
108
+ if let rtl {
109
+ content.environment(\.layoutDirection, rtl ? .rightToLeft : .leftToRight)
110
+ } else {
111
+ content
112
+ }
113
+ }
114
+
115
+ // position: "absolute" children float over their parent, like on the web
116
+ private var flowChildren: [ONode] { node.c.filter { ($0.s["position"] as? String) != "absolute" } }
117
+ private var absoluteChildren: [ONode] { node.c.filter { ($0.s["position"] as? String) == "absolute" } }
118
+
119
+ @ViewBuilder
120
+ private var absoluteLayer: some View {
121
+ if !absoluteChildren.isEmpty {
122
+ GeometryReader { geo in
123
+ ZStack(alignment: .topLeading) {
124
+ ForEach(absoluteChildren) { child in
125
+ let left = OStyle.offset(child.s["left"], of: geo.size.width)
126
+ let right = OStyle.offset(child.s["right"], of: geo.size.width)
127
+ let top = OStyle.offset(child.s["top"], of: geo.size.height)
128
+ let bottom = OStyle.offset(child.s["bottom"], of: geo.size.height)
129
+ ONodeView(node: child)
130
+ .fixedSize()
131
+ .padding(.leading, left ?? 0)
132
+ .padding(.trailing, left == nil ? (right ?? 0) : 0)
133
+ .padding(.top, top ?? 0)
134
+ .padding(.bottom, top == nil ? (bottom ?? 0) : 0)
135
+ .frame(width: geo.size.width, height: geo.size.height,
136
+ alignment: Alignment(horizontal: left == nil && right != nil ? .trailing : .leading,
137
+ vertical: top == nil && bottom != nil ? .bottom : .top))
138
+ }
139
+ }
140
+ }
141
+ }
142
+ }
143
+
144
+ @ViewBuilder
145
+ private var coreView: some View {
46
146
  switch node.t {
147
+ case "list":
148
+ // LazyVStack only builds the rows near the screen
149
+ ScrollView(.vertical) {
150
+ LazyVStack(spacing: 0) {
151
+ ForEach(node.c) { child in
152
+ ONodeView(node: child, stretch: true)
153
+ }
154
+ }
155
+ }
156
+ .modifier(OBoxStyle(s: node.s, stretch: true))
157
+
47
158
  case "row":
48
- // if a row is wider than the screen, it scrolls sideways instead of squashing
159
+ let gap = OStyle.number(node.s["gap"]) ?? 0
160
+ let isWrapped = (node.s["wrap"] as? Bool) == true
161
+ let scrollMode = node.s["scroll"]
162
+ let isScrollable = (scrollMode as? Bool) == true || (scrollMode as? String) == "horizontal" || (scrollMode as? String) == "both"
163
+
49
164
  Group {
50
- // rows of simple items (chips, buttons) scroll sideways when too wide;
51
- // rows holding a column (cards) let their text wrap instead
52
- if #available(iOS 16.0, *), !node.c.contains(where: { ["col", "box"].contains($0.t) }) {
165
+ if let marquee = OMarqueeSpec(node.s["marquee"]) {
166
+ OMarquee(spec: marquee) { rowContent }
167
+ } else if isWrapped {
168
+ OFlowLayout(spacing: gap, lineSpacing: gap,
169
+ centered: (node.s["justify"] as? String) == "center" || (node.s["center"] as? Bool) == true,
170
+ spaced: (node.s["justify"] as? String) == "between",
171
+ alignEnd: (node.s["align"] as? String) == "end") {
172
+ ForEach(node.c) { child in
173
+ ONodeView(node: child)
174
+ .layoutValue(key: OFillShare.self, value: OFillShare.of(child))
175
+ }
176
+ }
177
+ } else if isScrollable {
178
+ ScrollView(.horizontal, showsIndicators: false) { rowContent }
179
+ } else if !node.c.contains(where: { ["col", "box", "text", "heading"].contains($0.t) }) {
53
180
  ViewThatFits(in: .horizontal) {
54
181
  rowContent
55
182
  ScrollView(.horizontal, showsIndicators: false) { rowContent }
@@ -61,8 +188,35 @@ struct ONodeView: View {
61
188
  .modifier(OBoxStyle(s: node.s, stretch: stretch, isRow: true))
62
189
 
63
190
  case "col", "box":
64
- VStack(alignment: OStyle.horizontalAlignment(node.s["align"]), spacing: OStyle.number(node.s["gap"]) ?? 0) {
65
- children
191
+ let gap = OStyle.number(node.s["gap"]) ?? 0
192
+ let justify = (node.s["justify"] as? String) ?? ""
193
+ let isCentered = (node.s["center"] as? Bool) == true
194
+ let alignment: HorizontalAlignment = isCentered ? .center : OStyle.horizontalAlignment(node.s["align"])
195
+ let stack = VStack(alignment: alignment, spacing: gap) {
196
+ if isCentered || justify == "center" || justify == "end" || justify == "around" || justify == "evenly" {
197
+ Spacer(minLength: 0)
198
+ }
199
+ ForEach(Array(flowChildren.enumerated()), id: \.element.id) { idx, child in
200
+ if idx > 0 && (justify == "between" || justify == "around" || justify == "evenly") {
201
+ Spacer(minLength: 0)
202
+ }
203
+ // like a web column: boxes always fill it, buttons too unless the column aligns its items
204
+ ONodeView(node: child, stretch: ["row", "col", "box"].contains(child.t)
205
+ || (child.t == "button" && node.s["align"] == nil && (node.s["center"] as? Bool) != true))
206
+ }
207
+ if isCentered || justify == "center" || justify == "around" || justify == "evenly" {
208
+ Spacer(minLength: 0)
209
+ }
210
+ }
211
+
212
+ let scrollMode = node.s["scroll"]
213
+ let isScrollable = (scrollMode as? Bool) == true || (scrollMode as? String) == "vertical" || (scrollMode as? String) == "both"
214
+ Group {
215
+ if isScrollable {
216
+ ScrollView(.vertical) { stack.overlay { absoluteLayer } }
217
+ } else {
218
+ stack.overlay { absoluteLayer }
219
+ }
66
220
  }
67
221
  .modifier(OBoxStyle(s: node.s, stretch: stretch))
68
222
 
@@ -80,55 +234,269 @@ struct ONodeView: View {
80
234
  .buttonStyle(.plain)
81
235
 
82
236
  case "button":
237
+ let isDisabled = (node.s["disabled"] as? Bool) == true
238
+ let isLoading = (node.s["loading"] as? Bool) == true
239
+ let pressedStyle = node.s["pressed"] as? [String: Any] ?? node.s["active"] as? [String: Any]
240
+
83
241
  Button {
84
- engine.fire(node.tap)
242
+ if !isDisabled && !isLoading {
243
+ engine.fire(node.tap)
244
+ }
85
245
  } label: {
86
- label
246
+ HStack(spacing: 6) {
247
+ if isLoading {
248
+ ProgressView()
249
+ .scaleEffect(0.8)
250
+ }
251
+ label
252
+ }
87
253
  }
88
- .buttonStyle(.plain)
89
- .fixedSize(horizontal: node.c.isEmpty && (node.x ?? "").count <= 24, vertical: false)
254
+ .buttonStyle(OButtonStyle(pressed: pressedStyle))
255
+ .disabled(isDisabled || isLoading)
256
+ .opacity(isDisabled ? 0.5 : (isLoading ? 0.75 : 1))
257
+ .fixedSize(horizontal: !isWideButton && node.c.isEmpty && (node.x ?? "").count <= 24 && !isLoading, vertical: false)
90
258
 
91
259
  case "input":
92
260
  OInput(node: node)
93
261
 
262
+ case "toggle":
263
+ let isOn = node.v == "true"
264
+ let flip = Binding(get: { isOn }, set: { engine.fire(node.change, $0 ? "true" : "false") })
265
+ Group {
266
+ if node.inputType == "switch" {
267
+ Toggle(node.x ?? "", isOn: flip)
268
+ } else {
269
+ Button { flip.wrappedValue = !isOn } label: {
270
+ HStack(spacing: 8) {
271
+ Image(systemName: isOn ? "checkmark.square.fill" : "square")
272
+ Text(node.x ?? "").foregroundColor(.primary)
273
+ }
274
+ }
275
+ .accessibilityAddTraits(isOn ? .isSelected : [])
276
+ }
277
+ }
278
+ .disabled((node.s["disabled"] as? Bool) == true)
279
+ .modifier(OBoxStyle(s: node.s, stretch: stretch))
280
+
281
+ case "modal":
282
+ // the card is the only child; the dimmed background is the sheet itself
283
+ Color.clear
284
+ .frame(width: 0, height: 0)
285
+ .sheet(isPresented: Binding(get: { true }, set: { open in if !open { engine.fire(node.tap) } })) {
286
+ ScrollView {
287
+ ForEach(node.c) { child in
288
+ ONodeView(node: child, stretch: true)
289
+ }
290
+ .padding()
291
+ }
292
+ .environmentObject(engine)
293
+ }
294
+
295
+ case "map":
296
+ OMap(place: node.v ?? "")
297
+ .frame(height: OStyle.number(node.s["height"]) ?? 240)
298
+ .modifier(OBoxStyle(s: node.s.filter { $0.key != "height" }, stretch: true))
299
+
300
+ case "select":
301
+ let choice = Binding(get: { node.v ?? "" }, set: { engine.fire(node.change, $0) })
302
+ Picker(node.ph ?? "", selection: choice) {
303
+ Text(node.ph ?? "").tag("")
304
+ ForEach(node.o, id: \.self) { item in
305
+ Text(item).tag(item)
306
+ }
307
+ }
308
+ .pickerStyle(.menu)
309
+ .disabled((node.s["disabled"] as? Bool) == true)
310
+ .modifier(OBoxStyle(s: node.s, stretch: stretch))
311
+
94
312
  case "image":
95
- AsyncImage(url: URL(string: node.src ?? "")) { image in
96
- image.resizable().scaledToFit()
97
- } placeholder: {
98
- ProgressView()
313
+ if let src = node.src, src.hasPrefix("asset:"), let image = OBundledImage.load(src) {
314
+ Image(uiImage: image).resizable().scaledToFit()
315
+ .modifier(OBoxStyle(s: node.s))
316
+ } else if let src = node.src, src.hasPrefix("data:"),
317
+ let comma = src.firstIndex(of: ","),
318
+ let data = Data(base64Encoded: String(src[src.index(after: comma)...])),
319
+ let image = UIImage(data: data) {
320
+ Image(uiImage: image).resizable().scaledToFit()
321
+ .modifier(OBoxStyle(s: node.s))
322
+ } else {
323
+ AsyncImage(url: URL(string: node.src ?? "")) { image in
324
+ image.resizable().scaledToFit()
325
+ } placeholder: {
326
+ ProgressView()
327
+ }
328
+ .modifier(OBoxStyle(s: node.s))
99
329
  }
100
- .modifier(OBoxStyle(s: node.s))
101
330
 
102
331
  default:
103
332
  EmptyView()
104
333
  }
105
334
  }
106
335
 
336
+ private var innerWidth: CGFloat {
337
+ let base = OStyle.resolvedWidth(node.s["width"], parentWidth: parentWidth) ?? parentWidth
338
+ let capped = OStyle.number(node.s["maxWidth"]).map { min(base > 0 ? base : $0, $0) } ?? base
339
+ let px = OStyle.number(node.s["paddingX"]) ?? OStyle.number(node.s["padding"]) ?? 0
340
+ let margin = OStyle.number(node.s["margin"]) ?? 0
341
+ return max(0, capped - (px * 2) - (margin * 2))
342
+ }
343
+
107
344
  private var rowContent: some View {
108
- HStack(alignment: .center, spacing: OStyle.number(node.s["gap"]) ?? 0) {
109
- ForEach(node.c) { child in
345
+ let gap = OStyle.number(node.s["gap"]) ?? 0
346
+ let justify = (node.s["justify"] as? String) ?? ""
347
+ let isCentered = (node.s["center"] as? Bool) == true
348
+ let verticalAlign = isCentered ? VerticalAlignment.center : OStyle.verticalAlignment(node.s["align"])
349
+
350
+ return HStack(alignment: verticalAlign, spacing: gap) {
351
+ if isCentered || justify == "center" || justify == "end" || justify == "around" || justify == "evenly" {
352
+ Spacer(minLength: 0)
353
+ }
354
+ ForEach(Array(node.c.enumerated()), id: \.element.id) { idx, child in
355
+ if idx > 0 && (justify == "between" || justify == "around" || justify == "evenly") {
356
+ Spacer(minLength: 0)
357
+ }
110
358
  ONodeView(node: child)
111
359
  }
360
+ if isCentered || justify == "center" || justify == "around" || justify == "evenly" {
361
+ Spacer(minLength: 0)
362
+ }
112
363
  }
113
364
  }
114
365
 
115
- private var children: some View {
116
- ForEach(node.c) { child in
117
- ONodeView(node: child, stretch: ["row", "col", "box"].contains(child.t))
118
- }
366
+ /// a button fills its column on the web (and with width: "100%"); its words are centred
367
+ private var isWideButton: Bool {
368
+ node.t == "button" && (stretch || (node.s["width"] as? String)?.trimmingCharacters(in: .whitespaces) == "100%")
119
369
  }
120
370
 
121
371
  private var label: some View {
122
372
  let isHeading = node.t == "heading"
123
373
  let isButton = node.t == "button"
124
- let size = OStyle.number(node.s["size"]) ?? (isHeading ? 28 : 17)
125
- let weight = OStyle.weight(node.s["weight"]) ?? (isHeading ? .bold : (isButton ? .semibold : .regular))
374
+ let boxStyle: [String: Any] = isButton && node.s["textAlign"] == nil
375
+ ? node.s.merging(["center": true]) { own, _ in own }
376
+ : node.s
377
+ let baseSize = OStyle.number(node.s["size"]) ?? (isHeading ? 28 : 17)
378
+ let weight = OStyle.weight(node.s["weight"] ?? node.s["fontWeight"]) ?? (isHeading ? .bold : (isButton ? .semibold : .regular))
126
379
  let fallbackColor: Color = isButton || node.t == "link" ? .accentColor : .primary
380
+ let lineHeight = OStyle.number(node.s["lineHeight"])
381
+ let lineSpacing: CGFloat = {
382
+ guard let lh = lineHeight else { return 0 }
383
+ return lh <= 4 ? max(0, baseSize * (lh - 1)) : max(0, lh - baseSize)
384
+ }()
127
385
 
128
386
  return Text(node.x ?? "")
129
- .font(.system(size: size, weight: weight))
387
+ .font(OStyle.font(node.s["font"], size: baseSize, weight: weight))
388
+ .lineSpacing(lineSpacing)
389
+ .tracking(OStyle.letterSpacing(node.s["letterSpacing"], size: baseSize))
390
+ .multilineTextAlignment(OStyle.textAlign(boxStyle["textAlign"] ?? ((boxStyle["center"] as? Bool) == true ? "center" : nil)))
130
391
  .foregroundColor(OStyle.color(node.s["color"]) ?? fallbackColor)
131
- .modifier(OBoxStyle(s: node.s))
392
+ .fixedSize(horizontal: false, vertical: true)
393
+ .modifier(OBoxStyle(s: boxStyle, stretch: isWideButton))
394
+ }
395
+ }
396
+
397
+ // `label:` is what VoiceOver says; label: "" hides a decorative element
398
+ struct OLabel: ViewModifier {
399
+ let text: String?
400
+
401
+ func body(content: Content) -> some View {
402
+ if let text {
403
+ if text.isEmpty {
404
+ content.accessibilityHidden(true)
405
+ } else {
406
+ content.accessibilityLabel(text)
407
+ }
408
+ } else {
409
+ content
410
+ }
411
+ }
412
+ }
413
+
414
+ struct OButtonStyle: ButtonStyle {
415
+ let pressed: [String: Any]?
416
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
417
+
418
+ func makeBody(configuration: Configuration) -> some View {
419
+ let pressedOpacity = OStyle.number(pressed?["opacity"]).map { Double($0) } ?? 0.72
420
+ return configuration.label
421
+ .opacity(configuration.isPressed ? pressedOpacity : 1)
422
+ .scaleEffect(configuration.isPressed && !reduceMotion ? 0.98 : 1)
423
+ .animation(reduceMotion ? nil : .easeOut(duration: 0.12), value: configuration.isPressed)
424
+ }
425
+ }
426
+
427
+ struct OFlowLayout: Layout {
428
+ var spacing: CGFloat = 8
429
+ var lineSpacing: CGFloat = 8
430
+ var centered = false
431
+ var spaced = false
432
+ var alignEnd = false
433
+
434
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
435
+ let maxWidth = proposal.width ?? .infinity
436
+ var x: CGFloat = 0
437
+ var y: CGFloat = 0
438
+ var rowHeight: CGFloat = 0
439
+ var maxUsedWidth: CGFloat = 0
440
+
441
+ for subview in subviews {
442
+ let size = Self.measure(subview, maxWidth: maxWidth)
443
+ if x > 0 && x + size.width > maxWidth {
444
+ x = 0
445
+ y += rowHeight + lineSpacing
446
+ rowHeight = 0
447
+ }
448
+ x += size.width + (x > 0 ? spacing : 0)
449
+ rowHeight = max(rowHeight, size.height)
450
+ maxUsedWidth = max(maxUsedWidth, x)
451
+ }
452
+ return CGSize(width: proposal.width ?? maxUsedWidth, height: y + rowHeight)
453
+ }
454
+
455
+ /// an item is never wider than the row: long text wraps inside it, like on the web
456
+ static func measure(_ subview: LayoutSubview, maxWidth: CGFloat) -> CGSize {
457
+ let ideal = subview.sizeThatFits(.unspecified)
458
+ guard maxWidth.isFinite else { return ideal }
459
+ // width: "100%" (or grow) takes the whole row, like a wrapped item on a phone-size web page
460
+ if let share = subview[OFillShare.self] {
461
+ let width = maxWidth * share
462
+ let fitted = subview.sizeThatFits(ProposedViewSize(width: width, height: nil))
463
+ return CGSize(width: width, height: fitted.height)
464
+ }
465
+ // keep the item's own width (never wider than the row), then measure its
466
+ // height at that width so wrapped text gets the lines it needs
467
+ let width = min(ideal.width, maxWidth)
468
+ let fitted = subview.sizeThatFits(ProposedViewSize(width: width, height: nil))
469
+ return CGSize(width: width, height: fitted.height)
470
+ }
471
+
472
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
473
+ // group items into lines first, so a centred row can centre each line
474
+ var lines: [[(LayoutSubview, CGSize)]] = [[]]
475
+ var x: CGFloat = 0
476
+ for subview in subviews {
477
+ let size = Self.measure(subview, maxWidth: bounds.width)
478
+ if x > 0 && x + size.width > bounds.width {
479
+ lines.append([])
480
+ x = 0
481
+ }
482
+ lines[lines.count - 1].append((subview, size))
483
+ x += size.width + spacing
484
+ }
485
+ var y = bounds.minY
486
+ for line in lines where !line.isEmpty {
487
+ let used = line.map { $0.1.width }.reduce(0, +) + spacing * CGFloat(line.count - 1)
488
+ var lineX = bounds.minX + (centered ? max(0, (bounds.width - used) / 2) : 0)
489
+ // justify: between spreads the items of a line to both edges
490
+ let extra = spaced && line.count > 1 ? max(0, (bounds.width - used) / CGFloat(line.count - 1)) : 0
491
+ let lineHeight = line.map { $0.1.height }.max() ?? 0
492
+ for (subview, size) in line {
493
+ // align: end puts shorter items on the line's bottom edge
494
+ let dy = alignEnd ? lineHeight - size.height : 0
495
+ subview.place(at: CGPoint(x: lineX, y: y + dy), proposal: ProposedViewSize(size))
496
+ lineX += size.width + spacing + extra
497
+ }
498
+ y += lineHeight + lineSpacing
499
+ }
132
500
  }
133
501
  }
134
502
 
@@ -136,17 +504,52 @@ struct OInput: View {
136
504
  let node: ONode
137
505
  @EnvironmentObject private var engine: OrvynEngine
138
506
  @State private var text = ""
507
+ @FocusState private var focused: Bool
139
508
 
140
509
  var body: some View {
141
- TextField(node.ph ?? "", text: $text)
142
- .keyboardType(node.inputType == "email" ? .emailAddress : .default)
143
- .textInputAutocapitalization(node.inputType == "email" ? .never : .sentences)
144
- .disableAutocorrection(node.inputType == "email")
510
+ let isDisabled = (node.s["disabled"] as? Bool) == true
511
+ let hasError = node.s["error"] != nil && (node.s["error"] as? Bool) != false
512
+ let border = OStyle.border(node.s["border"])
513
+ let strokeColor: Color = hasError
514
+ ? .red
515
+ : (focused ? .accentColor : (border?.color ?? Color.gray.opacity(0.4)))
516
+ let strokeWidth: CGFloat = hasError || focused ? max(1.5, border?.width ?? 1.5) : (border?.width ?? 1)
517
+
518
+ if node.inputType == "date" {
519
+ ODate(node: node)
520
+ } else {
521
+ field(isDisabled: isDisabled, strokeColor: strokeColor, strokeWidth: strokeWidth)
522
+ }
523
+ }
524
+
525
+ @ViewBuilder
526
+ private func field(isDisabled: Bool, strokeColor: Color, strokeWidth: CGFloat) -> some View {
527
+ Group {
528
+ if node.inputType == "password" {
529
+ // never show what is typed
530
+ SecureField(node.ph ?? "", text: $text)
531
+ .textContentType(.password)
532
+ } else if node.inputType == "multiline" {
533
+ TextField(node.ph ?? "", text: $text, axis: .vertical)
534
+ .lineLimit(4...10)
535
+ } else {
536
+ TextField(node.ph ?? "", text: $text)
537
+ }
538
+ }
539
+ .focused($focused)
540
+ .disabled(isDisabled)
541
+ .opacity(isDisabled ? 0.5 : 1)
542
+ .keyboardType(OStyle.keyboard(node.inputType))
543
+ .textInputAutocapitalization(node.inputType == "email" || node.inputType == "password" ? .never : .sentences)
544
+ .disableAutocorrection(node.inputType == "email" || node.inputType == "password")
145
545
  .padding(OStyle.number(node.s["padding"]) ?? 10)
146
546
  .background(
147
547
  RoundedRectangle(cornerRadius: OStyle.number(node.s["radius"]) ?? 8)
148
- .stroke(OStyle.border(node.s["border"])?.color ?? Color.gray.opacity(0.4),
149
- lineWidth: OStyle.border(node.s["border"])?.width ?? 1)
548
+ .fill(OStyle.color(node.s["bg"]) ?? Color.clear)
549
+ )
550
+ .overlay(
551
+ RoundedRectangle(cornerRadius: OStyle.number(node.s["radius"]) ?? 8)
552
+ .stroke(strokeColor, lineWidth: strokeWidth)
150
553
  )
151
554
  .onAppear { text = node.v ?? "" }
152
555
  .onChange(of: text) { value in
@@ -158,6 +561,57 @@ struct OInput: View {
158
561
  }
159
562
  }
160
563
 
564
+ // the value is text like "2000-01-31"; empty until a date is chosen
565
+ struct ODate: View {
566
+ let node: ONode
567
+ @EnvironmentObject private var engine: OrvynEngine
568
+
569
+ private static let format: DateFormatter = {
570
+ let formatter = DateFormatter()
571
+ formatter.locale = Locale(identifier: "en_US_POSIX")
572
+ formatter.dateFormat = "yyyy-MM-dd"
573
+ return formatter
574
+ }()
575
+
576
+ var body: some View {
577
+ let chosen = Self.format.date(from: node.v ?? "")
578
+ if let chosen {
579
+ DatePicker(node.ph ?? "Date", selection: Binding(
580
+ get: { chosen },
581
+ set: { engine.fire(node.change, Self.format.string(from: $0)) }
582
+ ), displayedComponents: .date)
583
+ } else {
584
+ Button("\(node.ph ?? "Date"): choose") {
585
+ engine.fire(node.change, Self.format.string(from: Date()))
586
+ }
587
+ }
588
+ }
589
+ }
590
+
591
+ private struct OPin: Identifiable {
592
+ let id = 0
593
+ let coordinate: CLLocationCoordinate2D
594
+ }
595
+
596
+ // "latitude,longitude,zoom"
597
+ struct OMap: View {
598
+ let place: String
599
+
600
+ var body: some View {
601
+ let parts = place.split(separator: ",").compactMap { Double($0) }
602
+ if parts.count == 3 {
603
+ let center = CLLocationCoordinate2D(latitude: parts[0], longitude: parts[1])
604
+ let span = 360 / pow(2, parts[2])
605
+ Map(
606
+ coordinateRegion: .constant(MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: span, longitudeDelta: span))),
607
+ annotationItems: [OPin(coordinate: center)]
608
+ ) { pin in
609
+ MapMarker(coordinate: pin.coordinate)
610
+ }
611
+ }
612
+ }
613
+ }
614
+
161
615
  // MARK: - Styles
162
616
 
163
617
  struct OBoxStyle: ViewModifier {
@@ -165,45 +619,119 @@ struct OBoxStyle: ViewModifier {
165
619
  var stretch = false
166
620
  // in a row, `align` means vertical alignment, so the row itself stays left
167
621
  var isRow = false
622
+ @Environment(\.orvynWidth) private var parentWidth
168
623
 
169
624
  func body(content: Content) -> some View {
170
625
  let radius = OStyle.number(s["radius"]) ?? 0
171
626
  let border = OStyle.border(s["border"])
172
627
  let shadow = OStyle.number(s["shadow"]) ?? 0
173
- let fullWidth = (s["width"] as? String)?.hasSuffix("%") == true
628
+ let widthString = s["width"] as? String
629
+ let isFullPercent = widthString?.trimmingCharacters(in: .whitespaces) == "100%"
630
+ let resolvedWidth = OStyle.resolvedWidth(s["width"], parentWidth: parentWidth)
631
+ let isCentered = (s["center"] as? Bool) == true
632
+ let align = isCentered ? Alignment.center : (isRow ? .leading : OStyle.frameAlignment(s["align"]))
174
633
 
175
634
  return content
176
- .padding(.horizontal, OStyle.number(s["paddingX"]) ?? OStyle.number(s["padding"]) ?? 0)
177
- .padding(.vertical, OStyle.number(s["paddingY"]) ?? OStyle.number(s["padding"]) ?? 0)
178
- .frame(width: fullWidth ? nil : OStyle.number(s["width"]),
635
+ .padding(.leading, OStyle.number(s["paddingLeft"]) ?? OStyle.number(s["paddingX"]) ?? OStyle.number(s["padding"]) ?? 0)
636
+ .padding(.trailing, OStyle.number(s["paddingRight"]) ?? OStyle.number(s["paddingX"]) ?? OStyle.number(s["padding"]) ?? 0)
637
+ .padding(.top, OStyle.number(s["paddingTop"]) ?? OStyle.number(s["paddingY"]) ?? OStyle.number(s["padding"]) ?? 0)
638
+ .padding(.bottom, OStyle.number(s["paddingBottom"]) ?? OStyle.number(s["paddingY"]) ?? OStyle.number(s["padding"]) ?? 0)
639
+ .frame(width: isFullPercent ? nil : resolvedWidth,
179
640
  height: OStyle.number(s["height"]))
180
- .frame(maxWidth: fullWidth || stretch ? .infinity : OStyle.number(s["maxWidth"]),
641
+ .frame(minWidth: OStyle.number(s["minWidth"]),
642
+ maxWidth: isFullPercent || stretch ? (OStyle.number(s["maxWidth"]) ?? .infinity) : OStyle.number(s["maxWidth"]),
181
643
  minHeight: OStyle.number(s["minHeight"]),
182
- alignment: isRow ? .leading : OStyle.frameAlignment(s["align"]))
183
- .background(OStyle.color(s["bg"]) ?? Color.clear)
644
+ maxHeight: OStyle.number(s["maxHeight"]),
645
+ alignment: align)
646
+ .background(OBackground(s: s))
184
647
  .clipShape(RoundedRectangle(cornerRadius: radius))
648
+ .modifier(OClip(enabled: (s["overflow"] as? String) == "hidden"))
185
649
  .overlay(
186
650
  RoundedRectangle(cornerRadius: radius)
187
651
  .stroke(border?.color ?? .clear, lineWidth: border?.width ?? 0)
188
652
  )
189
653
  .shadow(color: .black.opacity(shadow > 0 ? 0.08 * shadow : 0), radius: 4 * shadow, y: 2 * shadow)
190
654
  .opacity(OStyle.number(s["opacity"]).map { Double($0) } ?? 1)
655
+ .animation(OStyle.animation(s["animate"]), value: String(describing: s))
191
656
  .padding(OStyle.number(s["margin"]) ?? 0)
192
657
  }
193
658
  }
194
659
 
195
660
  enum OStyle {
661
+ static func animation(_ value: Any?) -> Animation? {
662
+ guard let text = value as? String else { return nil }
663
+ let parts = text.split(separator: " ")
664
+ let seconds = Double(parts.last?.replacingOccurrences(of: "s", with: "") ?? "") ?? 0.3
665
+ switch parts.first {
666
+ case "linear": return .linear(duration: seconds)
667
+ case "spring": return .spring(response: seconds, dampingFraction: 0.8)
668
+ case "ease": return .easeInOut(duration: seconds)
669
+ default: return nil
670
+ }
671
+ }
672
+ static func keyboard(_ kind: String?) -> UIKeyboardType {
673
+ switch kind {
674
+ case "email": return .emailAddress
675
+ case "number": return .numbersAndPunctuation
676
+ case "tel": return .phonePad
677
+ default: return .default
678
+ }
679
+ }
680
+
681
+ /// letterSpacing: points, or "-0.04em" (a share of the text size)
682
+ static func letterSpacing(_ value: Any?, size: CGFloat) -> CGFloat {
683
+ if let string = (value as? String)?.trimmingCharacters(in: .whitespaces), string.hasSuffix("em"),
684
+ let em = Double(string.dropLast(2)) {
685
+ return size * CGFloat(em)
686
+ }
687
+ return number(value) ?? 0
688
+ }
689
+
690
+ /// top/left/right/bottom: points, or a percent of the parent
691
+ static func offset(_ value: Any?, of size: CGFloat) -> CGFloat? {
692
+ if let string = value as? String, string.hasSuffix("%"),
693
+ let pct = Double(string.dropLast().trimmingCharacters(in: .whitespaces)) {
694
+ return size * CGFloat(pct / 100)
695
+ }
696
+ return number(value)
697
+ }
698
+
196
699
  static func number(_ value: Any?) -> CGFloat? {
197
700
  if let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() {
198
701
  return CGFloat(truncating: number)
199
702
  }
200
703
  if let string = value as? String {
704
+ if string.contains("%") { return nil }
201
705
  let cleaned = string.replacingOccurrences(of: "px", with: "").trimmingCharacters(in: .whitespaces)
202
706
  if let double = Double(cleaned) { return CGFloat(double) }
203
707
  }
204
708
  return nil
205
709
  }
206
710
 
711
+ static func resolvedWidth(_ value: Any?, parentWidth: CGFloat) -> CGFloat? {
712
+ if let string = value as? String {
713
+ let trimmed = string.trimmingCharacters(in: .whitespaces)
714
+ if trimmed.hasSuffix("%"), let pct = Double(trimmed.dropLast()), parentWidth > 0 {
715
+ return max(0, parentWidth * CGFloat(pct / 100.0))
716
+ }
717
+ }
718
+ return number(value)
719
+ }
720
+
721
+ static func font(_ value: Any?, size: CGFloat, weight: Font.Weight) -> Font {
722
+ let scaled = UIFontMetrics.default.scaledValue(for: size)
723
+ switch (value as? String)?.trimmingCharacters(in: .whitespaces) {
724
+ case "mono":
725
+ return .system(size: scaled, weight: weight, design: .monospaced)
726
+ case "serif":
727
+ return .system(size: scaled, weight: weight, design: .serif)
728
+ case "sans", nil, "":
729
+ return .system(size: scaled, weight: weight)
730
+ case let custom?:
731
+ return .custom(custom, size: size, relativeTo: .body)
732
+ }
733
+ }
734
+
207
735
  static func weight(_ value: Any?) -> Font.Weight? {
208
736
  if let n = number(value) {
209
737
  switch n {
@@ -233,6 +761,14 @@ enum OStyle {
233
761
  }
234
762
  }
235
763
 
764
+ static func verticalAlignment(_ value: Any?) -> VerticalAlignment {
765
+ switch value as? String {
766
+ case "start", "flex-start", "top": return .top
767
+ case "end", "flex-end", "bottom": return .bottom
768
+ default: return .center
769
+ }
770
+ }
771
+
236
772
  static func frameAlignment(_ value: Any?) -> Alignment {
237
773
  switch value as? String {
238
774
  case "center": return .center
@@ -241,6 +777,14 @@ enum OStyle {
241
777
  }
242
778
  }
243
779
 
780
+ static func textAlign(_ value: Any?) -> TextAlignment {
781
+ switch value as? String {
782
+ case "center": return .center
783
+ case "right", "end": return .trailing
784
+ default: return .leading
785
+ }
786
+ }
787
+
244
788
  static func border(_ value: Any?) -> (width: CGFloat, color: Color)? {
245
789
  guard let string = value as? String else { return nil }
246
790
  let parts = string.split(separator: " ").map(String.init)
@@ -276,3 +820,187 @@ enum OStyle {
276
820
  return Color(.sRGB, red: r, green: g, blue: b, opacity: a)
277
821
  }
278
822
  }
823
+
824
+ // Images from public/ ship in the app's "public" folder. Each one is read
825
+ // from disk once; screen updates reuse the decoded picture.
826
+ enum OBundledImage {
827
+ private static let cache = NSCache<NSString, UIImage>()
828
+
829
+ static func load(_ src: String) -> UIImage? {
830
+ let key = src as NSString
831
+ if let image = cache.object(forKey: key) { return image }
832
+ let path = String(src.dropFirst("asset:/".count))
833
+ guard let folder = Bundle.main.resourceURL?.appendingPathComponent("public"),
834
+ let image = UIImage(contentsOfFile: folder.appendingPathComponent(path).path) else { return nil }
835
+ cache.setObject(image, forKey: key)
836
+ return image
837
+ }
838
+ }
839
+
840
+ // `appear: "fade-up 0.6s 0.2s"` plays once when the element is first shown;
841
+ // `onVisible:` runs at the same moment.
842
+ struct OAppear: ViewModifier {
843
+ let spec: String?
844
+ /// animation pop { opacity: 0, y: 30, scale: 0.8, rotate: -6 }: the start state
845
+ let from: [String: Any]?
846
+ let onShow: (() -> Void)?
847
+ @State private var shown = false
848
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
849
+
850
+ func body(content: Content) -> some View {
851
+ let parts = (spec ?? "").split(separator: " ").map(String.init)
852
+ let preset = parts.first ?? ""
853
+ let seconds = parts.count > 1 ? Double(parts[1].replacingOccurrences(of: "s", with: "")) ?? 0.5 : 0.5
854
+ let delay = parts.count > 2 ? Double(parts[2].replacingOccurrences(of: "s", with: "")) ?? 0 : 0
855
+ let hidden = !(spec ?? "").isEmpty && !shown && !reduceMotion
856
+ let distance: CGFloat = 24
857
+ func custom(_ key: String) -> CGFloat? { (from?[key] as? NSNumber).map { CGFloat($0.doubleValue) } }
858
+ let startOpacity = from != nil ? (custom("opacity") ?? 1) : 0
859
+ let startScale = from != nil ? (custom("scale") ?? 1) : (preset == "scale" ? 0.9 : 1)
860
+ let startX = from != nil ? (custom("x") ?? 0) : (preset == "slide-left" ? distance : preset == "slide-right" ? -distance : 0)
861
+ let startY = from != nil ? (custom("y") ?? 0) : (preset == "fade-up" ? distance : preset == "fade-down" ? -distance : 0)
862
+ return content
863
+ .opacity(hidden ? startOpacity : 1)
864
+ .scaleEffect(hidden ? startScale : 1)
865
+ .rotationEffect(.degrees(hidden ? Double(custom("rotate") ?? 0) : 0))
866
+ .offset(x: hidden ? startX : 0, y: hidden ? startY : 0)
867
+ // like the web: play once the element has scrolled onto the screen,
868
+ // not when the page is first built (that happens for the whole page at once)
869
+ .background(GeometryReader { geo in
870
+ let frame = geo.frame(in: .global)
871
+ Color.clear
872
+ .onAppear { reveal(frame, seconds: seconds, delay: delay) }
873
+ .onChange(of: frame.minY) { _ in reveal(geo.frame(in: .global), seconds: seconds, delay: delay) }
874
+ })
875
+ }
876
+
877
+ private func reveal(_ frame: CGRect, seconds: Double, delay: Double) {
878
+ guard !shown else { return }
879
+ let screen = UIScreen.main.bounds.height
880
+ // at least a little of it is inside the screen
881
+ guard frame.minY < screen * 0.9, frame.maxY > 0 else { return }
882
+ withAnimation(.timingCurve(0.2, 0.8, 0.2, 1, duration: seconds).delay(delay)) { shown = true }
883
+ onShow?()
884
+ }
885
+ }
886
+
887
+ /// lets scrollTo(label) find this element
888
+ struct OScrollAnchor: ViewModifier {
889
+ let label: String?
890
+ func body(content: Content) -> some View {
891
+ if let label, !label.isEmpty { content.id(label) } else { content }
892
+ }
893
+ }
894
+
895
+ /// overflow: "hidden" cuts off whatever sticks out of the box
896
+ struct OClip: ViewModifier {
897
+ let enabled: Bool
898
+ func body(content: Content) -> some View {
899
+ if enabled { content.clipped() } else { content }
900
+ }
901
+ }
902
+
903
+ /// bg: a colour, or a photo from `url(...)` filling the box (cover) with an optional dark tint
904
+ struct OBackground: View {
905
+ let s: [String: Any]
906
+ var body: some View {
907
+ ZStack {
908
+ OStyle.color(s["bg"]) ?? Color.clear
909
+ if let src = s["bgImage"] as? String {
910
+ Color.clear.overlay {
911
+ if src.hasPrefix("asset:"), let image = OBundledImage.load(src) {
912
+ Image(uiImage: image).resizable().scaledToFill()
913
+ } else if let url = URL(string: src) {
914
+ AsyncImage(url: url) { image in image.resizable().scaledToFill() } placeholder: { Color.clear }
915
+ }
916
+ }
917
+ .clipped()
918
+ Color.black.opacity((s["bgDim"] as? Double) ?? 0)
919
+ }
920
+ }
921
+ }
922
+ }
923
+
924
+ /// how much of a wrapping row an item asks for: 1 for width "100%" or grow, 0.5 for "50%"
925
+ struct OFillShare: LayoutValueKey {
926
+ static let defaultValue: CGFloat? = nil
927
+ static func of(_ node: ONode) -> CGFloat? {
928
+ if let width = (node.s["width"] as? String)?.trimmingCharacters(in: .whitespaces), width.hasSuffix("%"),
929
+ let pct = Double(width.dropLast()) {
930
+ return CGFloat(min(100, max(0, pct)) / 100)
931
+ }
932
+ if (node.s["centerSelf"] as? Bool) == true { return 1 }
933
+ if node.s["width"] == nil, let grow = OStyle.number(node.s["grow"]), grow > 0 { return 1 }
934
+ // a component's plain wrapper takes the size its one child asks for
935
+ if node.s.isEmpty, node.c.count == 1 { return of(node.c[0]) }
936
+ return nil
937
+ }
938
+ }
939
+
940
+ /// margin: "0 auto": centre the element in the space it is given
941
+ struct OCenterSelf: ViewModifier {
942
+ let enabled: Bool
943
+ func body(content: Content) -> some View {
944
+ if enabled { content.frame(maxWidth: .infinity, alignment: .center) } else { content }
945
+ }
946
+ }
947
+
948
+ /// position: "sticky" — the first sticky element stays pinned to the top while the page scrolls
949
+ enum OSticky {
950
+ static func find(_ node: ONode) -> ONode? {
951
+ if (node.s["position"] as? String) == "sticky" { return node }
952
+ for child in node.c { if let found = find(child) { return found } }
953
+ return nil
954
+ }
955
+ }
956
+
957
+ struct OStickyPlaceholder: ViewModifier {
958
+ let hidden: Bool
959
+ func body(content: Content) -> some View {
960
+ if hidden { content.opacity(0).allowsHitTesting(false).accessibilityHidden(true) } else { content }
961
+ }
962
+ }
963
+
964
+ /// marquee: "left 30s" — the row's items slide in an endless loop (two copies, so no gap)
965
+ struct OMarqueeSpec {
966
+ var left = true
967
+ var seconds: Double = 30
968
+ init?(_ value: Any?) {
969
+ if let flag = value as? Bool { if !flag { return nil }; return }
970
+ guard let text = value as? String, !text.isEmpty else { return nil }
971
+ for part in text.split(separator: " ") {
972
+ if part == "left" { left = true }
973
+ else if part == "right" { left = false }
974
+ else if part.hasSuffix("s"), let n = Double(part.dropLast()), n > 0 { seconds = n }
975
+ }
976
+ }
977
+ }
978
+
979
+ struct OMarquee<Content: View>: View {
980
+ let spec: OMarqueeSpec
981
+ @ViewBuilder let content: () -> Content
982
+ @State private var width: CGFloat = 0
983
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
984
+ @Environment(\.orvynWidth) private var available
985
+
986
+ var body: some View {
987
+ TimelineView(.animation(paused: reduceMotion)) { context in
988
+ let progress = CGFloat(context.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: spec.seconds) / spec.seconds)
989
+ let shift = reduceMotion || width == 0 ? 0 : progress * width
990
+ HStack(spacing: 0) {
991
+ content()
992
+ .fixedSize()
993
+ .background(GeometryReader { geo in
994
+ Color.clear
995
+ .onAppear { width = geo.size.width }
996
+ .onChange(of: geo.size.width) { width = $0 }
997
+ })
998
+ content().fixedSize().accessibilityHidden(true)
999
+ }
1000
+ .offset(x: spec.left ? -shift : shift - width)
1001
+ }
1002
+ // only as wide as the space it is in: the long strip must not widen the page
1003
+ .frame(width: available > 0 ? available : nil, alignment: .leading)
1004
+ .clipped()
1005
+ }
1006
+ }