Repository navigation
Expand file tree
/
Copy pathxml.lua
More file actions
2783 lines (2616 loc) · 102 KB
/
Copy pathxml.lua
File metadata and controls
2783 lines (2616 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
ui/xml.lua — cross-platform XML template renderer.
Usage:
local xml = require("ui.xml")
local view = xml.render(xmlString, data, ns)
The `ns` argument is the platform module (AppKit or UIKit). When omitted,
require("AppKit") is used. This lets the same XML file produce NSText on
macOS or UILabel on iOS without any conditionals in the template.
Workflow for file-based templates:
local view = xml.renderFile("demo/mail/views/MailRow.etlua", rowData, ns)
etlua is applied to the XML source before parsing, so you can embed data
with <%= expr %> or execute logic with <% if cond then %> ... <% end %>.
Tag-to-component mapping lives in the registry table at the bottom.
Adding a new cross-platform tag is one line:
registry["Icon"] = function(ns, attrs, children) ... end
--]]
local etlua = require("etlua")
local renderData = nil
local padLeaf
-- A template is Lua, so it runs in an environment of its own, not in _G: the
-- template data, `partial` and the other helpers the caller put in the data,
-- and the pure standard functions below. No io, os, require, load, debug or
-- network, which is what lets an app's views be treated as data (they cannot
-- open a file or a socket). etlua's own `run` falls back to _G for any name
-- the data lacks, so the template function is run here instead.
local loadChunk = load
local SANDBOX = {
assert = assert, error = error, ipairs = ipairs, next = next, pairs = pairs,
pcall = pcall, select = select, tonumber = tonumber, tostring = tostring,
type = type, unpack = table.unpack,
math = math, string = string, table = table, utf8 = utf8,
}
local HTML_ENTITIES = { ["&"] = "&", ["<"] = "<", [">"] = ">", ['"'] = """, ["'"] = "'" }
local function escapeHTML(text) return (tostring(text):gsub("[\"><'&]", HTML_ENTITIES)) end
local function renderTemplate(src, data, sourceName)
local parser = etlua.Parser()
local code, err = parser:compile_to_lua(src)
if not code then return nil, err end
local env = setmetatable({}, { __index = function(_, name)
local value = data[name]
if value == nil then value = SANDBOX[name] end
return value
end })
local chunkName = sourceName and ("@" .. sourceName) or "etlua"
local fn = loadChunk(code, chunkName, "t", env)
if not fn then
-- etlua maps a compile error back to the template's source line.
local _, mapped = parser:load(code, chunkName)
return nil, mapped
end
local ok, buffer = pcall(fn, tostring, escapeHTML, {}, 0)
if not ok then return nil, buffer end
return table.concat(buffer)
end
local function decodeXMLText(value)
if type(value) ~= "string" or value == "" then return value end
value = value:gsub("&#x([%da-fA-F]+);", function(hex)
local code = tonumber(hex, 16)
return code and utf8.char(code) or "&#x" .. hex .. ";"
end)
value = value:gsub("&#(%d+);", function(decimal)
local code = tonumber(decimal, 10)
return code and utf8.char(code) or "&#" .. decimal .. ";"
end)
return (value
:gsub(""", '"')
:gsub("'", "'")
:gsub("<", "<")
:gsub(">", ">")
:gsub("&", "&"))
end
-- ── Minimal XML parser ────────────────────────────────────────────────────
local function parseAttrs(attrStr)
local attrs = {}
for key, val in attrStr:gmatch('%s+([%w_:%-]+)%s*=%s*"([^"]*)"') do
attrs[key] = decodeXMLText(val)
end
for key, val in attrStr:gmatch("%s+([%w_:%-]+)%s*=%s*'([^']*)'") do
attrs[key] = decodeXMLText(val)
end
return attrs
end
local function parseXML(src, opts)
opts = opts or {}
local trimText = opts.trimText ~= false
local decodeText = opts.decodeText ~= false
local nodes = {}
local stack = { { tag = "__root__", attrs = {}, children = nodes } }
local pos = 1
local len = #src
local function current() return stack[#stack] end
local function pushText(text, isCdata)
if not isCdata and decodeText then
text = decodeXMLText(text)
end
if trimText and not isCdata then
text = text:match("^%s*(.-)%s*$")
end
if #text > 0 then
table.insert(current().children, { kind = "text", value = text })
end
end
while pos <= len do
local lt = src:find("<", pos, true)
if not lt then
pushText(src:sub(pos))
break
end
if lt > pos then
pushText(src:sub(pos, lt - 1))
end
-- comment
if src:sub(lt, lt + 3) == "<!--" then
local ce = src:find("-->", lt + 4, true)
pos = ce and (ce + 3) or (len + 1)
-- CDATA block
elseif src:sub(lt, lt + 8) == "<![CDATA[" then
local ce = src:find("]]>", lt + 9, true)
if not ce then error("xml: unclosed CDATA near pos " .. lt) end
pushText(src:sub(lt + 9, ce - 1), true)
pos = ce + 3
-- processing instruction
elseif src:sub(lt, lt + 1) == "<?" then
local pe = src:find("?>", lt + 2, true)
pos = pe and (pe + 2) or (len + 1)
-- doctype/declaration
elseif src:sub(lt, lt + 8):upper() == "<!DOCTYPE" then
local de = src:find(">", lt + 9, true)
pos = de and (de + 1) or (len + 1)
-- closing tag
elseif src:sub(lt + 1, lt + 1) == "/" then
local gt = src:find(">", lt + 2, true)
if not gt then error("xml: unclosed closing tag near pos " .. lt) end
if #stack > 1 then table.remove(stack) end
pos = gt + 1
-- self-closing or opening tag
else
local gt = src:find(">", lt + 1, true)
if not gt then error("xml: unclosed tag near pos " .. lt) end
local inner = src:sub(lt + 1, gt - 1)
local selfClose = inner:sub(-1) == "/"
if selfClose then inner = inner:sub(1, -2) end
local tag, rest = inner:match("^([%w_%-%.]+)(.*)$")
if not tag then error("xml: bad tag near pos " .. lt) end
local attrs = parseAttrs(rest or "")
local node = { kind = "element", tag = tag, attrs = attrs, children = {} }
table.insert(current().children, node)
if not selfClose then
table.insert(stack, node)
end
pos = gt + 1
end
end
return nodes
end
-- ── XML data decoding (schema-driven) ─────────────────────────────────────
local function splitPath(path)
local parts = {}
for seg in tostring(path):gmatch("[^/]+") do
if seg ~= "" and seg ~= "." then table.insert(parts, seg) end
end
return parts
end
local function elementChildren(node)
local out = {}
for _, child in ipairs(node.children or {}) do
if child.kind == "element" then table.insert(out, child) end
end
return out
end
local function selectNodes(node, path)
if not path or path == "" or path == "." then
return { node }
end
local current = { node }
for _, seg in ipairs(splitPath(path)) do
local nextNodes = {}
for _, parent in ipairs(current) do
for _, child in ipairs(parent.children or {}) do
if child.kind == "element" and child.tag == seg then
table.insert(nextNodes, child)
end
end
end
current = nextNodes
if #current == 0 then break end
end
return current
end
local function collectText(node)
local parts = {}
local function walk(n)
for _, child in ipairs(n.children or {}) do
if child.kind == "text" then
table.insert(parts, child.value)
elseif child.kind == "element" then
walk(child)
end
end
end
walk(node)
return table.concat(parts)
end
local function toBoolean(value)
if type(value) == "boolean" then return value end
if value == nil then return nil end
local s = tostring(value):lower()
if s == "true" or s == "1" or s == "yes" then return true end
if s == "false" or s == "0" or s == "no" then return false end
return nil
end
local function coerceType(value, typeName)
if value == nil or typeName == nil then return value end
if type(typeName) == "function" then return typeName(value) end
if typeName == "string" then return tostring(value) end
if typeName == "number" then return tonumber(value) end
if typeName == "integer" then
local n = tonumber(value)
if not n then return nil end
local i = math.tointeger and math.tointeger(n) or (n % 1 == 0 and n or nil)
return i
end
if typeName == "boolean" then return toBoolean(value) end
return value
end
local function normalizeFieldSpec(spec)
if type(spec) == "string" then
if spec:sub(1, 1) == "@" then
return { attr = spec:sub(2) }
end
if spec == "#text" then
return { text = true }
end
return { path = spec, text = true }
end
return spec
end
local decodeWithSchema
local function decodeScalar(node, spec)
local target = node
if spec.path then
target = selectNodes(node, spec.path)[1]
end
local value
if target then
if spec.attr then
value = target.attrs and target.attrs[spec.attr] or nil
else
value = collectText(target)
if spec.trim ~= false and type(value) == "string" then
value = value:match("^%s*(.-)%s*$")
end
if spec.text == false then value = nil end
end
end
value = coerceType(value, spec.type)
if value == nil and spec.default ~= nil then return spec.default end
return value
end
decodeWithSchema = function(node, spec)
spec = normalizeFieldSpec(spec)
if type(spec) ~= "table" then return spec end
if spec.array then
local nodes
if spec.path then
nodes = selectNodes(node, spec.path)
elseif spec.tag then
nodes = selectNodes(node, spec.tag)
else
nodes = elementChildren(node)
end
local itemSpec
if spec.of ~= nil then
itemSpec = spec.of
elseif spec.fields ~= nil then
itemSpec = { fields = spec.fields }
else
itemSpec = { text = true, type = spec.type }
end
local out = {}
for _, child in ipairs(nodes) do
table.insert(out, (decodeWithSchema(child, itemSpec)))
end
if #out == 0 and spec.default ~= nil then return spec.default end
return out
end
if spec.fields then
local target = node
if spec.path then
target = selectNodes(node, spec.path)[1]
end
if not target then
if spec.default ~= nil then return spec.default end
return nil
end
local out = {}
for key, fieldSpec in pairs(spec.fields) do
out[key] = decodeWithSchema(target, fieldSpec)
end
return out
end
return decodeScalar(node, spec)
end
-- ── Attribute coercion helpers ────────────────────────────────────────────
local function num(v) return tonumber(v) end
local function bool(v) return v == "true" or v == "1" end
local function coerce(v)
if v == "true" then return true end
if v == "false" then return false end
local n = tonumber(v)
if n then return n end
return v
end
-- Event attributes name controller actions. When a controller supplies
-- actions, a misspelt name fails at render time instead of silently leaving
-- the control unbound; static renders (previews, layout tests) have none.
local function bindActions(props, attrs, names)
local actions = renderData and renderData.actions
if not actions then return end
for _, name in ipairs(names) do
if attrs[name] then
local action = actions[attrs[name]]
if type(action) ~= "function" then
error("xml: " .. name .. "=\"" .. attrs[name] .. "\" requires a controller action")
end
props[name] = action
end
end
end
-- A toolbar item's `action`, and its `validate`, which names an action
-- returning whether the item is enabled whenever AppKit validates the
-- toolbar (as MenuItem's `validate` does for the menu bar).
local function bindToolbarActions(item)
local names = {}
for _, name in ipairs({ "action", "validate" }) do
if type(item[name]) == "string" then names[name] = item[name] end
end
bindActions(item, names, { "action", "validate" })
end
-- SwiftUI `.fixedSize(horizontal:vertical:)`: the axes that keep their
-- content size instead of taking the proposal.
local FIXED_SIZES = { horizontal = true, vertical = true, both = true }
local function layoutProps(attrs)
local lp = {
"padding", "paddingHorizontal", "paddingVertical", "paddingLeading", "paddingTrailing", "paddingTop", "paddingBottom",
"spacing", "alignment", "maxRows", "fixedSize",
"flexGrow", "flexShrink", "flexBasis",
"containerRelativeWidth", "trailingMaxWidthFraction", "hidden", "allowsHitTesting", "background", "tint", "cornerRadius", "clipsToBounds", "ignoresSafeArea", "contentMode", "onClick", "onTap", "onDrag", "onEdgeSwipe", "onScroll",
"opacity", "offsetX", "offsetY", "colorScheme",
"help", "dropExternalOnly",
}
local props = {}
for _, k in ipairs(lp) do
if attrs[k] then props[k] = coerce(attrs[k]) end
end
if attrs.fixedSize and not FIXED_SIZES[attrs.fixedSize] then
error("xml: fixedSize must be horizontal, vertical or both")
end
-- Templates use SwiftUI dimension names; fixed/fill flags belong to the
-- native layout engine. Infinity is a proposal, never a native frame size.
for _, axis in ipairs({ "Width", "Height" }) do
local dimension = axis:lower()
if attrs[dimension] then
local value = tonumber(attrs[dimension])
if not value or value < 0 or value ~= value or value == math.huge then
error("xml: " .. dimension .. " requires a nonnegative finite number")
end
props["fixed" .. axis] = value
end
local maximum = "max" .. axis
local minimum = "min" .. axis
for _, key in ipairs({ minimum, maximum }) do
if attrs[key] == "infinity" and key == maximum then
props["fill" .. axis] = true
elseif attrs[key] then
local value = tonumber(attrs[key])
if not value or value < 0 or value ~= value or value == math.huge then
error("xml: " .. key .. " requires a nonnegative finite number"
.. (key == maximum and " or infinity" or ""))
end
props[key] = value
end
end
if props[minimum] and props[maximum] and props[minimum] > props[maximum] then
error("xml: " .. minimum .. " exceeds " .. maximum)
end
end
if attrs.onClick and type(attrs.onClick) == "string"
and renderData and renderData.actions then
props.onClick = renderData.actions[attrs.onClick]
end
bindActions(props, attrs, { "onDrop", "onFileDragChanged", "onScroll" })
for _, key in ipairs({ "onTap", "onDrag", "onEdgeSwipe" }) do
if attrs[key] and type(attrs[key]) == "string" and renderData and renderData.actions then
props[key] = renderData.actions[attrs[key]]
end
end
return props
end
-- SwiftUI applies .padding to any view. Stacks inset their children
-- natively, but a leaf (a label, a paragraph, an image) draws edge to edge in
-- its frame, so a padded leaf is wrapped in a stack that carries the padding
-- and the leaf's expansion. The leaf keeps its id, so refs still reach it.
local paddedLeaves = setmetatable({}, { __mode = "k" })
local PADDING_KEYS = { "padding", "paddingHorizontal", "paddingVertical", "paddingLeading",
"paddingTrailing", "paddingTop", "paddingBottom" }
padLeaf = function(view, props, ns)
if type(view) ~= "userdata" or type(ns._hasLayoutAxis) ~= "function" then return view end
local wrapper = { spacing = 0, alignment = "leading" }
local padded = false
for _, key in ipairs(PADDING_KEYS) do
if props[key] ~= nil then wrapper[key] = props[key]; padded = true end
end
if not padded or ns._hasLayoutAxis(view) then return view end
for _, key in ipairs({ "fillWidth", "fillHeight", "flexGrow", "containerRelativeWidth" }) do
wrapper[key] = props[key]
end
view.containerRelativeWidth = 0
table.insert(wrapper, view)
local stack = ns.VStack(wrapper)
paddedLeaves[stack] = view
return stack
end
-- ── Node → view compilation ───────────────────────────────────────────────
--
-- refs: table populated during compile; any view with an id="name" attr
-- has its produced view stored as refs[name]. Callers use refs to attach
-- callbacks after rendering without scanning the view tree.
-- While a retained template compiles (xml.mount, xml.reconcile), each element
-- node records the view it produced and renders its callbacks in its own
-- Scope, so the reconciler can replace or remove one node's subtree and
-- dispose exactly the callbacks it owned.
local tracking = false
local compile
compile = function(nodes, ns, registry, refs)
local views = {}
for _, node in ipairs(nodes) do
if node.kind == "element" then
for _, key in ipairs({ "fillWidth", "fillHeight", "fixedWidth", "fixedHeight" }) do
if node.attrs[key] ~= nil then
error("xml: " .. key .. " was removed; use width/height or maxWidth/maxHeight=\"infinity\"")
end
end
local handler = registry[node.tag]
if not handler then
error("xml: unknown tag <" .. node.tag .. ">")
end
local lazy = node.tag == "LazyVStack" or node.tag == "LazyVGrid"
local attrs = node.attrs
local children
if node.tag == "Column" then
-- A cell is one of the table's native kinds, chosen by the
-- column's key attributes; rows are data, not views.
for _, child in ipairs(node.children) do
if child.kind == "element" then
error("xml: <Column> takes no content; describe the cell with its key attributes")
end
end
end
if lazy then
local itemNodes = {}
for _, child in ipairs(node.children) do
if child.kind == "element" then itemNodes[#itemNodes + 1] = child end
end
local itemData = renderData
children = {
count = #itemNodes,
factory = function(index)
local previous = renderData
renderData = itemData
local ok, item = pcall(function()
return compile({ itemNodes[index] }, ns, registry, {})[1]
end)
renderData = previous
if not ok then error(item) end
if type(item) ~= "userdata" then
error("xml: lazy collection items must render one native view")
end
return item
end,
}
end
local nodeScope
if tracking then
nodeScope = ns.Scope.new()
local parent = ns.Scope.current()
if parent then
parent:add(nodeScope)
-- Callbacks this node fires register what they start in
-- the template's scope (see lua_reg_push).
nodeScope.enclosing = parent.enclosing or parent
end
end
local view
if nodeScope then
if not children then children = ns.Scope.withScope(nodeScope, compile, node.children, ns, registry, refs) end
view = ns.Scope.withScope(nodeScope, handler, ns, attrs, children)
else
if not children then children = compile(node.children, ns, registry, refs) end
view = handler(ns, attrs, children)
end
-- SwiftUI's `.accessibilityLabel` applies to any view: tags whose
-- constructor does not take the label still carry it.
if attrs.accessibilityLabel and type(view) == "userdata" then
local target = paddedLeaves[view] or view
if target.accessibilityLabel ~= attrs.accessibilityLabel then
target.accessibilityLabel = attrs.accessibilityLabel
end
end
if view then
if node.attrs.reorderable == "true" and node.tag ~= "List" and not lazy then
local name = node.attrs.reorderContainer
local action = name and renderData and renderData.actions
and renderData.actions[name]
if type(action) ~= "function" then
error("xml: reorderable <" .. node.tag ..
"> requires a valid reorderContainer action")
end
local items = {}
local function append(childrenToAdd)
for _, child in ipairs(childrenToAdd) do
if type(child) == "table" and child.__appkitGroup then
append(child)
else
items[#items + 1] = child
end
end
end
append(children)
view = ns.attachReorder(view, items, action)
end
if tracking then
node.view, node.target, node.scope = view, paddedLeaves[view] or view, nodeScope
end
if node.attrs.id and type(view) == "userdata" then
local target = paddedLeaves[view] or view
refs[node.attrs.id] = target
-- Keep the declarative identity on the native view as well as
-- in the returned refs table. Diagnostics and accessibility
-- tooling can then locate the same semantic node without
-- depending on child order or implementation classes.
pcall(function()
target.accessibilityIdentifier = node.attrs.id
end)
end
table.insert(views, view)
end
end
end
return views
end
-- ── Declarative Tag Schema ────────────────────────────────────────────────
--
-- Tags are defined as data-driven schema tables:
-- kind: nil (visual view) | "record" (table data / config)
-- constructor: name of constructor on platform module `ns` (defaults to tag name)
-- flag: table marker for records (e.g. "__toolbarItem", "__isWindowConfig")
-- children: "array" (props[1..n] = children) | "content" (props.content = children[1]) | "items" (props.items = children)
-- positional: ordered attribute names mapped to props[1] (with optional .default)
-- directArg: "positional" -> passes props[1] directly to ctor instead of props table
-- props: attribute definitions table:
-- propName = "type" (types: "num", "bool", "str")
-- or propName = { prop = "targetName", type = "...", aliases = {...}, default = ... }
-- collect: optional child aggregation hook: fn(targetTable, children)
-- transform: optional hook for platform quirks: fn(props, attrs, children, ns) -> optional view
local TAG_SCHEMA = {
-- Layout containers
VStack = {
constructor = "VStack",
children = "array",
props = {
},
},
LazyVStack = {
constructor = "LazyVStack",
props = { rowHeight = "num", reorderable = "bool", reorderContainer = "str" },
collect = function(props, children)
props.itemCount, props.itemFactory = children.count, children.factory
end,
transform = function(props, attrs)
if attrs.reorderable == "true" then
props.onReorder = attrs.reorderContainer and renderData
and renderData.actions and renderData.actions[attrs.reorderContainer]
if type(props.onReorder) ~= "function" then
error("xml: reorderable <LazyVStack> requires a valid reorderContainer action")
end
end
end,
},
LazyVGrid = {
constructor = "LazyVGrid",
props = { columns = "num", rowHeight = "num", reorderable = "bool",
reorderContainer = "str" },
collect = function(props, children)
props.itemCount, props.itemFactory = children.count, children.factory
end,
transform = function(props, attrs)
if attrs.reorderable == "true" then
props.onReorder = attrs.reorderContainer and renderData
and renderData.actions and renderData.actions[attrs.reorderContainer]
if type(props.onReorder) ~= "function" then
error("xml: reorderable <LazyVGrid> requires a valid reorderContainer action")
end
end
end,
},
FlowStack = {
constructor = "FlowStack",
children = "array",
},
HStack = {
constructor = "HStack",
children = "array",
props = {
},
},
Section = {
constructor = "Section",
children = "array",
props = { header = "str" },
},
GroupBox = {
constructor = "GroupBox",
children = "array",
props = { header = "str" },
},
Form = {
constructor = "Form",
children = "array",
props = { spacing = "num", alignment = "str" },
},
LabeledContent = {
constructor = "LabeledContent",
children = "array",
props = { label = "str", labelWeight = "str", spacing = "num" },
},
ControlGroup = {
constructor = "ControlGroup",
children = "array",
props = { spacing = "num", alignment = "str" },
},
DisclosureGroup = {
constructor = "DisclosureGroup",
children = "array",
props = {
label = "str",
header = "str",
expanded = "bool",
labelWeight = "str",
labelSize = "num",
indicatorWidth = "num",
indicatorSpacing = "num",
},
},
Grid = {
constructor = "Grid",
children = "array",
},
GridRow = {
constructor = "Group",
children = "array",
},
ZStack = {
constructor = "ZStack",
children = "array",
},
HSplit = {
constructor = "HSplit",
children = "array",
},
Spacer = {
constructor = "Spacer",
},
PageControl = {
constructor = "PageControl",
props = {
numberOfPages = "num",
currentPage = "num",
},
transform = function(props, attrs)
bindActions(props, attrs, { "onChange" })
end,
},
ProgressView = {
constructor = "ProgressView",
props = {
value = "num",
indeterminate = "bool",
tint = "str",
controlSize = "str",
},
},
-- SwiftUI Gauge (linear capacity style).
Gauge = {
constructor = "Gauge",
props = { value = "num", minValue = "num", maxValue = "num", tint = "str", thickness = "num", accessibilityLabel = "str" },
},
Divider = {
constructor = "Divider",
props = {
orientation = "str",
},
},
ScrollView = {
constructor = "ScrollView",
children = "content",
props = {
contentWidth = "num",
contentHeight = "num",
horizontal = "bool",
vertical = "bool",
scrollOnKeyboard = "bool",
scrollDismissesKeyboard = "str",
scrollTargetBehavior = "str",
},
},
-- SwiftUI Charts SectorMark: a pie or donut built from native arcs.
-- Non-mark children are centered over the chart.
SectorChart = {
constructor = "SectorChart",
children = "array",
props = { innerRadius = "num", angularInset = "num", scalable = "bool", diameter = "num", accessibilityLabel = "str" },
transform = function(props, attrs)
bindActions(props, attrs, { "onSelect", "onHover", "onCenter", "onBack", "dragItem" })
end,
},
-- `ring` 2+ with a `parent` id draws a sunburst level inside the parent.
SectorMark = {
kind = "record", flag = "__sectorMark",
props = { id = "str", value = "num", color = "str", label = "str", ring = "num", parent = "str", opacity = "num", cornerRadius = "num" },
},
-- SwiftUI SceneView over SceneKit. Its records are the scene graph and
-- reconcile in place by id (see src/shared/scene_view.m).
SceneView = {
constructor = "SceneView",
children = "array",
props = { background = "str", showsStatistics = "bool", virtualGamepad = "bool" },
updateRecords = function(view, records) return require("AppKit").sceneGraph(view, records) end,
transform = function(props, attrs)
bindActions(props, attrs, { "onKey", "onFrame", "onSwipe", "onTap" })
end,
},
-- A scene node: a model file or a primitive geometry, posed by
-- position/rotation (degrees)/scale, with idle `spin` (degrees per
-- second about y, or "x y z") and `bob` behaviours and an insertion/removal `transition` (pop, rise, fade).
-- Child records hang from it and move with it.
Node = {
kind = "record", children = "items",
props = { id = "str", model = "str", geometry = "str", position = "str", rotation = "str", scale = "str",
width = "num", height = "num", length = "num", radius = "num", chamfer = "num", color = "str",
hidden = "bool", opacity = "num", castsShadow = "bool", spin = "str", bob = "num", bobPeriod = "num",
transition = "str", lookAt = "str" },
transform = function(rec) rec.sceneKind = "node" end,
},
-- The first camera is the view's point of view. `fieldOfViewAxis`
-- "horizontal" keeps the width framed whatever the view's shape.
Camera = {
kind = "record", children = "items",
props = { id = "str", position = "str", rotation = "str", lookAt = "str", fieldOfView = "num", fieldOfViewAxis = "str",
zNear = "num", zFar = "num", orthographicScale = "num" },
transform = function(rec) rec.sceneKind = "camera" end,
},
-- `type` is directional (default), ambient, omni or spot.
Light = {
kind = "record", children = "items",
props = { id = "str", type = "str", position = "str", rotation = "str", lookAt = "str", intensity = "num",
color = "str", castsShadow = "bool", shadowRadius = "num", shadowOpacity = "num",
shadowMapSize = "num", shadowSampleCount = "num", shadowBias = "num",
automaticallyAdjustsShadowProjection = "bool", orthographicScale = "num", zNear = "num", zFar = "num" },
transform = function(rec) rec.sceneKind = "light" end,
},
-- Squarified treemap; nested nodes name their `parent`.
Treemap = {
constructor = "Treemap",
children = "array",
props = { selected = "str", accessibilityLabel = "str" },
transform = function(props, attrs)
bindActions(props, attrs, { "onSelect", "onHover", "onBack", "dragItem" })
end,
},
Waveform = {
constructor = "Waveform",
children = "array",
props = { source = "str", bpm = "num", beatsPerBar = "num", division = "num", gridOffset = "num",
selected = "str", playFrom = "num", playTo = "num", playState = "str", accessibilityLabel = "str" },
updateRecords = function(view, records) return require("AppKit").waveformMarkers(view, records) end,
transform = function(props, attrs)
bindActions(props, attrs, { "onAdd", "onSelect", "onMove", "onKey", "onZoom" })
end,
},
WaveformMarker = {
kind = "record", flag = "__waveformMarker",
props = { id = "str", time = "num" },
},
TreemapNode = {
kind = "record", flag = "__treemapNode",
props = { id = "str", parent = "str", value = "num", color = "str", label = "str", detail = "str", hatched = "bool" },
},
Arc = {
constructor = "Arc",
props = {
startAngle = "num",
endAngle = "num",
lineWidth = "num",
stroke = "str",
strokeAlpha = "num",
lineCap = "str",
},
},
SafeAreaInset = {
constructor = "SafeAreaInset",
children = "array",
props = { edge = "str", minimumBottomInset = "num", keyboardBottomInset = "num",
horizontalInset = "num", matchBottomHorizontalInset = "bool" },
},
-- Text & Typography
Label = {
constructor = "Text",
positional = { "text", "value", default = "" },
props = {
size = "num",
weight = "str",
design = "str",
fontName = "str",
italic = "bool",
systemImage = "str",
iconSize = "num",
iconWeight = "str",
spacing = "num",
alignment = "str",
color = "str",
accessibilityLabel = "str",
lines = { prop = "lineLimit", type = "num" },
reservesSpace = "bool",
underlinesOnHover = "bool",
truncation = "str",
wrapping = "str",
monospacedDigit = "bool",
smallCaps = "bool",
minimumScaleFactor = "num",
},
transform = function(props, a)
if a.lines and (num(a.lines) or 0) > 1 then
props.lineBreakMode = 0
end
end,
},
-- Long-form prose: selectable, with leading, hyphenation and drop caps.
Paragraph = {
constructor = "Paragraph",
positional = { "text", "value", default = "" },
props = {
size = "num", weight = "str", design = "str", fontName = "str", italic = "bool",
smallCaps = "bool", color = "str", lineSpacing = "num", alignment = "str",
hyphenation = "bool", selectable = "bool", accessibilityLabel = "str",
figure = "str", figureLines = "num",
revealedCharacters = "num", linkColor = "str",
},
-- <Hyperlink> children mark the words a reader can act on.
collect = function(props, children)
if #children == 0 then return end
props.links = {}
for _, child in ipairs(children) do
if type(child) ~= "table" or not child.__hyperlink then
error("xml: <Paragraph> accepts only <Hyperlink> children")
end
table.insert(props.links, child)
end
end,
updateRecords = function(view, records)
for _, name in ipairs({ "UIKitNative", "AppKitNative" }) do
local ok, native = pcall(require, name)
if ok and type(native) == "table" and type(native._paragraphSetLinks) == "function" then
native._paragraphSetLinks(view, records)
return true
end
end
return false
end,
},
-- A run of a <Paragraph> that opens a menu when tapped (WPF Hyperlink
-- inside a TextBlock). `location` counts characters from 0 as
-- `utf8.len` does; <MenuItem> children are what the reader can do.
Hyperlink = {
kind = "record",
flag = "__hyperlink",
props = { location = "num", length = "num", label = "str" },
collect = function(rec, children)
rec.items = children
end,
},
Title = {
constructor = "Title",
positional = { "text", "value", default = "" },
directArg = "positional",
},
Preview = { constructor = "Preview" },
TextEditor = {
constructor = "TextEditor",
props = {
text = { aliases = { "value" }, default = "", type = "str" },
size = "num",
weight = "str",
design = "str",
editable = "bool",
selectable = "bool",
wrapMode = "bool",
drawsBackground = "bool",
placeholder = "str",
accessibilityLabel = "str",
},
transform = function(props, attrs)
if attrs.onChange and renderData and renderData.actions then
props.onChange = renderData.actions[attrs.onChange]
end
end,
},
CodeView = {
constructor = "CodeView",
props = {
text = { aliases = { "value" }, default = "", type = "str" },
language = { default = "lua", type = "str" },
syntaxRules = "str",
size = "num",
wrapMode = "bool",
drawsBackground = "bool",
},
transform = function(props, attrs)
if renderData and attrs.syntaxRules then props.syntaxRules = renderData[attrs.syntaxRules] end
end,
},
SearchField = {
constructor = "SearchField",
props = {