Repository navigation
Expand file tree
/
Copy pathcode.js
More file actions
1409 lines (1293 loc) · 51 KB
/
Copy pathcode.js
File metadata and controls
1409 lines (1293 loc) · 51 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
// VoiceOver Annotator — Figma plugin (main thread)
// Stores iOS accessibility annotations on nodes via pluginData and drives the UI.
const PLUGIN_DATA_KEY = "a11y";
const HIGHLIGHT_LAYER_NAME = "♿︎ VoiceOver Annotations";
figma.showUI(__html__, { width: 380, height: 900, themeColors: true });
const SIZE_KEY = "a11y-window-size";
const MIN_W = 320;
const MIN_H = 360;
// AI settings — stored locally per user via figma.clientStorage (never in the file).
const AI_PROVIDER_KEY = "a11y-ai-provider";
const ANTHROPIC_KEY = "a11y-anthropic-key";
const OPENAI_KEY = "a11y-openai-key";
// PNG export scale for .vodesign — the same value is written as info.imageScale
// so the overlays always line up with the exported image.
const EXPORT_SCALE = 3;
// restore the last window size the user dragged to
figma.clientStorage
.getAsync(SIZE_KEY)
.then((s) => {
if (s && s.w && s.h) figma.ui.resize(s.w, s.h);
})
.catch(() => {});
// ---------------------------------------------------------------------------
// Annotation read / write
// ---------------------------------------------------------------------------
function readAnnotation(node) {
const raw = node.getPluginData(PLUGIN_DATA_KEY);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch (e) {
return null;
}
}
function writeAnnotation(node, annotation) {
if (annotation == null) {
node.setPluginData(PLUGIN_DATA_KEY, "");
} else {
node.setPluginData(PLUGIN_DATA_KEY, JSON.stringify(annotation));
}
}
// ---------------------------------------------------------------------------
// VoiceOver utterance generation (kept in sync with ui.html)
// ---------------------------------------------------------------------------
// "element" (accessible) | "container" | "ignored" (non-accessible)
function annKind(a) {
if (!a) return "element";
if (a.kind) return a.kind;
return a.isAccessible === false ? "ignored" : "element";
}
function resolveValue(a) {
if (a.adjustable && a.values && a.values.length) {
const idx = Math.min(Math.max(a.selectedIndex || 0, 0), a.values.length - 1);
return a.values[idx] || "";
}
return (a.value || "").trim();
}
// custom descriptions are { label, value } pairs; migrate the old single string
function getDescriptions(a) {
if (Array.isArray(a.customDescriptions)) return a.customDescriptions;
if (a.customDescription && a.customDescription.trim()) {
return [{ label: "", value: a.customDescription }];
}
return [];
}
// spoken form of one custom description: "value, label"
function descText(d) {
const v = (d.value || "").trim();
const l = (d.label || "").trim();
if (v && l) return v + ", " + l;
return v || l;
}
function utteranceParts(a) {
if (!a) return null;
const kind = annKind(a);
if (kind === "ignored") return null;
if (kind === "container") {
const label = (a.label || "").trim();
if (!label) return null;
return { main: label, traits: [], hint: "", container: true };
}
const label = (a.label || "").trim();
const value = resolveValue(a);
let main = label && value ? label + ": " + value : label || value;
if (a.adjustable && a.enumerated && a.values && a.values.length > 1) {
const pos = Math.min(Math.max(a.selectedIndex || 0, 0), a.values.length - 1) + 1;
main += ", " + pos + " of " + a.values.length;
}
const traits = [];
const t = a.traits || [];
const tt = a.textTraits || [];
if (t.indexOf("selected") !== -1) traits.push("Selected");
if (tt.indexOf("header") !== -1) traits.push("Heading");
if (a.adjustable) traits.push("Adjustable");
if (t.indexOf("button") !== -1) traits.push("Button");
if (t.indexOf("switcher") !== -1) traits.push("Switch Button");
if (t.indexOf("link") !== -1) traits.push("Link");
if (t.indexOf("image") !== -1) traits.push("Image");
if (tt.indexOf("searchField") !== -1) traits.push("Search Field");
if (tt.indexOf("textInput") !== -1) traits.push("Text Field");
if (t.indexOf("disabled") !== -1) traits.push("Dimmed");
return { main, traits, hint: (a.hint || "").trim() };
}
// Custom descriptions ("value, label") and custom actions, shown as indented
// sub-lines beneath the element. Elements only (not containers/ignored).
function subLinesOf(a) {
if (annKind(a) !== "element") return [];
const out = [];
getDescriptions(a).map(descText).filter(Boolean).forEach((s) => out.push(s));
(a.customActions || []).map((s) => (s || "").trim()).filter(Boolean).forEach((s) => out.push(s));
return out;
}
// returns { text, traitRanges:[{start,end}], hintRange } with char offsets
function buildUtterance(a) {
const p = utteranceParts(a);
if (!p) return null;
let text = p.main;
const traitRanges = [];
for (const tr of p.traits) {
text += ". ";
const start = text.length;
text += tr;
traitRanges.push({ start, end: text.length });
}
if (p.traits.length) text += ".";
let hintRange = null;
if (p.hint) {
text += text.endsWith(".") || text === "" ? " " : ". ";
const start = text.length;
text += p.hint;
hintRange = { start, end: text.length };
}
return { text: text.trim(), traitRanges, hintRange, container: !!p.container };
}
// ---------------------------------------------------------------------------
// Frame discovery + reading order
// ---------------------------------------------------------------------------
// Walk up to the outermost FRAME / COMPONENT that lives directly on the page.
function topLevelFrameOf(node) {
let current = node;
let candidate = null;
while (current && current.parent) {
if (
current.type === "FRAME" ||
current.type === "COMPONENT" ||
current.type === "COMPONENT_SET" ||
current.type === "INSTANCE" ||
current.type === "SECTION"
) {
candidate = current;
}
if (current.parent.type === "PAGE") break;
current = current.parent;
}
return candidate || node;
}
// Collect the text of every visible descendant TEXT layer, in reading order.
// Used to suggest a Label (first text layer) and Value (the rest, combined).
function innerTextParts(node) {
const parts = [];
const visit = (n) => {
if (n.visible === false) return;
if (n.type === "TEXT" && typeof n.characters === "string") {
const t = n.characters.replace(/\s+/g, " ").trim();
if (t) parts.push(t);
}
if ("children" in n) {
for (const child of n.children) visit(child);
}
};
visit(node);
return parts;
}
function annotatedDescendants(root) {
const out = [];
const visit = (node) => {
const ann = readAnnotation(node);
if (ann) out.push({ node, ann });
if ("children" in node) {
for (const child of node.children) visit(child);
}
};
visit(root);
return out;
}
// iOS VoiceOver default order: top-to-bottom, then leading-to-trailing.
function readingOrderSort(a, b) {
const ba = a.node.absoluteBoundingBox;
const bb = b.node.absoluteBoundingBox;
if (!ba && !bb) return 0;
if (!ba) return 1; // nodes without a rendered box sort deterministically last
if (!bb) return -1;
const rowThreshold = 8; // px tolerance so items roughly on one line keep L→R order
if (Math.abs(ba.y - bb.y) > rowThreshold) return ba.y - bb.y;
return ba.x - bb.x;
}
// Hierarchical reading order: every annotated element is nested under its
// nearest container-annotated ancestor. A container is emitted immediately
// above the first of its members (by reading order) and all its members follow
// contiguously. Within a level, items are sorted by the manual `order` field if
// set, otherwise by geometry. Returns a flat list with a `depth` per item.
function hierarchicalItems(frame) {
const raw = annotatedDescendants(frame).filter((x) => annKind(x.ann) !== "ignored");
if (raw.length === 0) return [];
// geometry rank (a single comparable number per node)
const geomRank = {};
raw.slice().sort(readingOrderSort).forEach((x, i) => (geomRank[x.node.id] = i));
const itemById = {};
raw.forEach((x) => (itemById[x.node.id] = x));
const isContainer = (x) => annKind(x.ann) === "container";
// explicit order wins; un-ordered (newly annotated) items fall back to their
// geometry rank so they interleave by on-screen position instead of always
// sorting after every manually-ordered item.
const keyOf = (x) => (typeof x.ann.order === "number" ? x.ann.order : geomRank[x.node.id]);
// nearest annotated-container ancestor within the frame
const parentOf = {};
for (const x of raw) {
let p = x.node.parent;
let found = null;
while (p && "id" in p) {
const cand = itemById[p.id];
if (cand && isContainer(cand)) { found = cand.node.id; break; }
if (p.id === frame.id) break;
p = p.parent;
}
parentOf[x.node.id] = found;
}
const children = {};
const roots = [];
for (const x of raw) {
const pid = parentOf[x.node.id];
if (pid) (children[pid] = children[pid] || []).push(x);
else roots.push(x);
}
// a container sorts at the minimum key of its whole subtree, so it lands
// right above its first member
const minKeyCache = {};
const subtreeMinKey = (x) => {
if (minKeyCache[x.node.id] !== undefined) return minKeyCache[x.node.id];
let m = keyOf(x);
for (const c of children[x.node.id] || []) m = Math.min(m, subtreeMinKey(c));
return (minKeyCache[x.node.id] = m);
};
const sortSiblings = (list) =>
list.slice().sort((a, b) => {
const ka = subtreeMinKey(a), kb = subtreeMinKey(b);
if (ka !== kb) return ka - kb;
return (isContainer(a) ? 0 : 1) - (isContainer(b) ? 0 : 1); // container before its first member on ties
});
const out = [];
const walk = (list, depth, parentId) => {
for (const x of sortSiblings(list)) {
out.push({ node: x.node, ann: x.ann, depth, parentId });
if (isContainer(x)) walk(children[x.node.id] || [], depth + 1, x.node.id);
}
};
walk(roots, 0, null);
return out;
}
function buildList(frame) {
return hierarchicalItems(frame).map(({ node, ann, depth, parentId }) => ({
id: node.id,
name: node.name,
ann,
depth,
parentId: parentId || null, // reading-order parent container, for same-parent reordering
}));
}
// ---------------------------------------------------------------------------
// Sync helpers — push current state to the UI
// ---------------------------------------------------------------------------
// Which annotation outputs already exist for a frame (drives button "on" state):
// panel — a description panel next to the frame ("Below frame")
// native — native Figma annotations present on any element ("Dev Mode")
async function frameAnnotationState(frame) {
let panel = false;
try { panel = !!(await getExistingPanel(frame)); } catch (e) {}
const native = hasNativeAnnotations(frame);
return { panel, native };
}
async function pushFrameState(frame) {
const s = frame ? await frameAnnotationState(frame) : { panel: false, native: false };
figma.ui.postMessage({ type: "frame-state", panel: s.panel, native: s.native });
}
// Monotonic token: rapid selection changes run pushSelection concurrently, and
// a slower earlier call must not post after a newer one and show the wrong node.
let selectionSeq = 0;
async function pushSelection() {
const seq = ++selectionSeq;
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({ type: "selection", node: null, list: [] });
figma.ui.postMessage({ type: "frame-state", panel: false, native: false });
return;
}
let node = selection[0];
// If a row of the description panel is selected, hop to the layer it describes
// so the inspector shows (and edits) the real annotated element.
if ("getPluginData" in node) {
const linkId = node.getPluginData(LINK_KEY);
if (linkId) {
const src = await figma.getNodeByIdAsync(linkId);
if (src && !src.removed) {
figma.currentPage.selection = [src]; // re-fires selectionchange → posts for src
return;
}
}
}
const frame = topLevelFrameOf(node);
const textParts = innerTextParts(node);
if (seq !== selectionSeq) return; // a newer selection superseded this one
figma.ui.postMessage({
type: "selection",
node: {
id: node.id,
name: node.name,
type: node.type,
ann: readAnnotation(node),
// Label ← first text layer; Value ← the remaining text layers, one per row.
labelText: textParts[0] || "",
valueText: textParts.slice(1).join("\n"),
},
frame: { id: frame.id, name: frame.name },
list: buildList(frame),
});
if (seq !== selectionSeq) return;
await pushFrameState(frame);
}
async function pushList() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.ui.postMessage({ type: "list", list: [] });
return;
}
const frame = topLevelFrameOf(selection[0]);
figma.ui.postMessage({ type: "list", list: buildList(frame) });
await pushFrameState(frame);
}
// ---------------------------------------------------------------------------
// On-canvas highlights
// ---------------------------------------------------------------------------
const HIGHLIGHT_COLORS = [
{ r: 0.4, g: 0.78, b: 0.55 }, // green — text / static
{ r: 0.55, g: 0.66, b: 0.96 }, // blue — buttons
{ r: 0.74, g: 0.55, b: 0.86 }, // purple — adjustable
{ r: 0.95, g: 0.75, b: 0.42 }, // orange — image / header
];
function colorForAnnotation(ann) {
const traits = ann.traits || [];
if (ann.adjustable) return HIGHLIGHT_COLORS[2];
if (traits.indexOf("button") !== -1 || traits.indexOf("link") !== -1) return HIGHLIGHT_COLORS[1];
if (traits.indexOf("image") !== -1) return HIGHLIGHT_COLORS[3];
return HIGHLIGHT_COLORS[0];
}
async function drawHighlights() {
const selection = figma.currentPage.selection;
if (selection.length === 0) {
figma.notify("Select a frame to highlight its annotations.");
return;
}
const frame = topLevelFrameOf(selection[0]);
const items = hierarchicalItems(frame);
if (items.length === 0) {
figma.notify("No annotations found in this frame.");
return;
}
await figma.loadFontAsync({ family: "Inter", style: "Semi Bold" });
// Remove only THIS frame's previous highlight layer (not other frames').
clearHighlightsForFrame(frame);
const overlays = [];
items.forEach((item, index) => {
const node = item.node;
const box = node.absoluteBoundingBox;
if (!box) return;
const color = colorForAnnotation(item.ann);
const rect = figma.createRectangle();
rect.name = `a11y-overlay-${index + 1}`;
// Match the node's own size + absolute rotation/position so rotated elements
// get a tight, rotated overlay instead of an inflated axis-aligned box.
rect.resize(Math.max(node.width, 1), Math.max(node.height, 1));
if (node.absoluteTransform) {
rect.relativeTransform = node.absoluteTransform; // rect is page-parented → relative == absolute
} else {
rect.x = box.x;
rect.y = box.y;
}
rect.fills = [{ type: "SOLID", color, opacity: 0.45 }];
rect.strokes = [{ type: "SOLID", color }];
rect.strokeWeight = 1.5;
rect.cornerRadius = 4;
overlays.push(rect);
const badge = figma.createText();
badge.fontName = { family: "Inter", style: "Semi Bold" };
badge.fontSize = 12;
badge.characters = String(index + 1);
badge.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }];
badge.x = box.x + 4; // badge stays upright at the element's top-left corner
badge.y = box.y + 4;
overlays.push(badge);
});
if (overlays.length === 0) return;
const group = figma.group(overlays, frame.parent || figma.currentPage);
group.name = HIGHLIGHT_LAYER_NAME;
group.setPluginData(HIGHLIGHT_FRAME_KEY, frame.id); // scope so redraws only clear this frame
group.locked = true;
group.expanded = false;
figma.notify(
`Highlighted ${items.length} annotated element${items.length === 1 ? "" : "s"} — re-run after moving layers.`
);
}
const HIGHLIGHT_FRAME_KEY = "a11yHlFrame";
// Remove only the highlight group belonging to a specific frame.
function clearHighlightsForFrame(frame) {
const existing = figma.currentPage.findAll(
(n) =>
n.type === "GROUP" && n.name === HIGHLIGHT_LAYER_NAME &&
"getPluginData" in n && n.getPluginData(HIGHLIGHT_FRAME_KEY) === frame.id
);
for (const layer of existing) layer.remove();
}
// Remove every highlight group on the page (the explicit "Clear" action).
function clearHighlights() {
const existing = figma.currentPage.findAll(
(n) => n.name === HIGHLIGHT_LAYER_NAME && n.type === "GROUP"
);
for (const layer of existing) layer.remove();
}
// ---------------------------------------------------------------------------
// Accumulated description panel next to the frame (left-sidebar mirror)
// ---------------------------------------------------------------------------
const PANEL_KEY = "a11yPanelId";
const LINK_KEY = "a11ySource";
const COL = {
text: { r: 0.12, g: 0.12, b: 0.12 },
trait: { r: 0.59, g: 0.28, b: 1 },
hint: { r: 0.46, g: 0.46, b: 0.46 },
num: { r: 0.6, g: 0.6, b: 0.6 },
};
async function getExistingPanel(frame) {
const id = frame.getPluginData(PANEL_KEY);
if (!id) return null;
try {
const node = await figma.getNodeByIdAsync(id);
if (node && !node.removed) return node;
} catch (e) {}
return null;
}
// forceCreate=false -> only refresh a panel that already exists (live accumulate)
// Debounced live-panel refresh: coalesce rapid saves (typing) into one rebuild.
let panelTimer = null;
function schedulePanelRegen(frame) {
if (panelTimer) clearTimeout(panelTimer);
panelTimer = setTimeout(() => {
panelTimer = null;
regeneratePanel(frame, false);
}, 600);
}
async function regeneratePanel(frame, forceCreate) {
const prev = await getExistingPanel(frame);
if (!prev && !forceCreate) return false;
const items = hierarchicalItems(frame)
.map((x) => ({
id: x.node.id,
name: x.node.name,
depth: x.depth,
u: buildUtterance(x.ann),
sublines: subLinesOf(x.ann),
}))
.filter((x) => x.u && x.u.text);
if (items.length === 0) {
if (prev) prev.remove();
frame.setPluginData(PANEL_KEY, "");
if (forceCreate) figma.notify("No annotations in this frame yet.");
return false;
}
await figma.loadFontAsync({ family: "Inter", style: "Regular" });
await figma.loadFontAsync({ family: "Inter", style: "Medium" });
await figma.loadFontAsync({ family: "Inter", style: "Semi Bold" });
// keep position if a panel already exists, else park it just below the frame
let px = frame.x;
let py = frame.y + frame.height + 48;
if (prev) {
px = prev.x;
py = prev.y;
prev.remove();
}
const panel = figma.createFrame();
panel.name = "♿︎ " + frame.name + " — VoiceOver";
(frame.parent || figma.currentPage).appendChild(panel);
panel.layoutMode = "VERTICAL";
panel.primaryAxisSizingMode = "AUTO";
panel.counterAxisSizingMode = "FIXED";
panel.resize(Math.max(frame.width, 200), 100); // match the frame's width
panel.itemSpacing = 7;
panel.paddingTop = 24;
panel.paddingBottom = 24;
panel.paddingLeft = 24;
panel.paddingRight = 24;
panel.fills = [{ type: "SOLID", color: { r: 1, g: 1, b: 1 } }];
panel.cornerRadius = 14;
panel.x = px;
panel.y = py;
const title = figma.createText();
title.fontName = { family: "Inter", style: "Semi Bold" };
title.fontSize = 17;
title.characters = "VoiceOver — " + frame.name;
title.fills = [{ type: "SOLID", color: COL.text }];
panel.appendChild(title);
title.layoutSizingHorizontal = "FILL"; // fill panel width (after it's in the layout)
title.textAutoResize = "HEIGHT";
const appendLine = (opts) => {
const t = figma.createText();
t.fontName = { family: "Inter", style: opts.container ? "Semi Bold" : "Regular" };
t.fontSize = opts.container ? 15 : opts.sub ? 13 : 14;
t.lineHeight = { value: 150, unit: "PERCENT" };
t.characters = opts.text;
t.fills = [{ type: "SOLID", color: opts.sub ? COL.hint : COL.text }];
for (const r of opts.traitRanges || []) {
t.setRangeFontName(r.start, r.end, { family: "Inter", style: "Medium" });
t.setRangeFills(r.start, r.end, [{ type: "SOLID", color: COL.trait }]);
}
if (opts.hintRange) {
t.setRangeFills(opts.hintRange.start, opts.hintRange.end, [{ type: "SOLID", color: COL.hint }]);
}
if (opts.depth > 0) {
// wrap in a transparent auto-layout frame to indent the whole block
const rowFrame = figma.createFrame();
rowFrame.name = "row";
panel.appendChild(rowFrame);
rowFrame.layoutMode = "HORIZONTAL";
rowFrame.counterAxisSizingMode = "AUTO";
rowFrame.fills = [];
rowFrame.paddingLeft = opts.depth * 20;
rowFrame.layoutSizingHorizontal = "FILL";
rowFrame.appendChild(t);
t.layoutSizingHorizontal = "FILL";
} else {
panel.appendChild(t);
t.layoutSizingHorizontal = "FILL";
}
t.textAutoResize = "HEIGHT";
t.setPluginData(LINK_KEY, opts.linkId); // back-reference to the annotated source layer
};
items.forEach((item) => {
const u = item.u;
appendLine({
text: u.text,
depth: item.depth,
container: u.container,
traitRanges: u.traitRanges,
hintRange: u.hintRange,
linkId: item.id,
});
// custom descriptions + actions as indented sub-lines
for (const sl of item.sublines) {
appendLine({ text: sl, depth: item.depth + 1, sub: true, linkId: item.id });
}
});
frame.setPluginData(PANEL_KEY, panel.id);
return true;
}
// ---------------------------------------------------------------------------
// .vodesign export (VoiceOver Designer markup)
// ---------------------------------------------------------------------------
// this plugin's string trait keys -> VoiceOver Designer numeric trait bitmask
// Switch Button lives at bit 53 (2^53) — beyond JS 32-bit bitwise ops, so trait
// bitmasks are combined by ADDITION (distinct powers of two) and this high bit
// is read arithmetically.
const SWITCH_TRAIT = 9007199254740992; // 2^53
const TRAIT_BITS = {
button: 1, header: 2, adjustable: 4, switcher: SWITCH_TRAIT, link: 8, selected: 16,
image: 32, staticText: 64, summaryElement: 128, updatesFrequently: 256,
playsSound: 512, startsMediaSession: 1024, allowsDirectInteraction: 2048,
causesPageTurn: 4096, textInput: 8192, isEditing: 16384, searchField: 32768,
keyboardKey: 65536, disabled: 131072,
};
// Returns a BigInt so switch(2^53) combined with odd low bits (e.g. + button)
// stays exact — a JS Number would round 2^53+1 down to 2^53.
function traitsToBitmask(a) {
let bits = 0n;
const added = {};
const add = (k) => {
const v = TRAIT_BITS[k];
if (v && !added[v]) { bits += BigInt(v); added[v] = 1; }
};
(a.traits || []).forEach(add);
(a.textTraits || []).forEach(add);
if (a.adjustable) add("adjustable");
return bits;
}
// JSON.stringify can't serialize BigInt, so encode any BigInt as a sentinel
// string, then unquote it back to an exact integer literal (VoiceOver Designer
// decodes it losslessly into a 64-bit trait).
function stringifyControls(controls) {
const json = JSON.stringify(
controls,
(k, v) => (typeof v === "bigint" ? "@@int:" + v.toString() + "@@" : v),
2
);
return json.replace(/"@@int:(\d+)@@"/g, "$1");
}
// hex-only UUID (VoiceOver Designer requires 0-9 A-F)
function newUUID() {
const chars = "0123456789ABCDEF";
let s = "";
for (let i = 0; i < 36; i++) {
s += i === 8 || i === 13 || i === 18 || i === 23 ? "-" : chars[Math.floor(Math.random() * 16)];
}
return s;
}
// Build controls.json in the reading order the user set (manual `order`),
// elements only — containers are intentionally skipped for now (see issue).
function buildControls(frame) {
const fb = frame.absoluteBoundingBox;
return hierarchicalItems(frame)
.filter((x) => annKind(x.ann) === "element")
.map(({ node, ann }) => {
const b = node.absoluteBoundingBox;
const x = fb && b ? Math.round(b.x - fb.x) : 0;
const y = fb && b ? Math.round(b.y - fb.y) : 0;
const w = b ? Math.round(b.width) : 0;
const h = b ? Math.round(b.height) : 0;
const enumerated = !!(ann.adjustable && ann.enumerated);
const options = enumerated ? (ann.values || []).slice() : [];
const currentIndex = options.length
? Math.min(Math.max(ann.selectedIndex || 0, 0), options.length - 1)
: 0;
const descriptions = getDescriptions(ann)
.map((d) => ({ label: (d.label || "").trim(), value: (d.value || "").trim() }))
.filter((d) => d.label || d.value);
return {
hint: (ann.hint || "").trim(),
id: newUUID(),
frame: [[x, y], [w, h]],
customActions: {
names: (ann.customActions || []).map((s) => (s || "").trim()).filter(Boolean),
},
isAccessibilityElement: true,
customDescriptions: { descriptions: descriptions },
label: (ann.label || "").trim(),
adjustableOptions: {
options: options,
isEnumerated: !!ann.enumerated,
currentIndex: currentIndex,
},
value: resolveValue(ann),
trait: traitsToBitmask(ann),
};
});
}
// ---------------------------------------------------------------------------
// Native Figma annotations (shown in Dev Mode)
// ---------------------------------------------------------------------------
// pluginData marker storing the exact native-annotation label this plugin
// wrote on a node, so we can update/remove only our own — never the user's.
const NATIVE_KEY = "a11yNativeLabel";
// Walk every node in a frame, including nodes that are no longer annotated.
// This lets native sync remove a stale annotation after its source annotation
// is deleted or changed to Non-accessible.
function frameDescendants(frame) {
const out = [];
const visit = (node) => {
out.push(node);
if ("children" in node) {
for (const child of node.children) visit(child);
}
};
visit(frame);
return out;
}
function hasNativeAnnotations(frame) {
return frameDescendants(frame).some(
(node) => "getPluginData" in node && !!node.getPluginData(NATIVE_KEY)
);
}
// Find the built-in "Accessibility" annotation category. Returns undefined
// (no category) rather than guessing a wrong one when none matches.
async function accessibilityCategoryId() {
if (!figma.annotations || !figma.annotations.getAnnotationCategoriesAsync) return undefined;
try {
const cats = await figma.annotations.getAnnotationCategoriesAsync();
const a11y = cats.find((c) => /accessib/i.test(c.label || ""));
return a11y ? a11y.id : undefined;
} catch (e) {
return undefined;
}
}
// Write each annotated element/container's utterance as a native Figma
// annotation (visible in Dev Mode), preserving any annotations the plugin
// didn't create and replacing only its own previous one (idempotent).
async function syncNativeAnnotations(frame) {
// Clear all of this plugin's previous native annotations first. In addition
// to replacing changed labels, this removes stale output from elements that
// were deleted from the reading order or changed to Non-accessible.
removeNativeAnnotations(frame);
const categoryId = await accessibilityCategoryId();
let count = 0;
for (const { node, ann } of hierarchicalItems(frame)) {
if (!("annotations" in node)) continue;
const u = buildUtterance(ann);
if (!u || !u.text) continue;
const subs = subLinesOf(ann);
const label = u.text + subs.map((s) => "\n• " + s).join("");
const prev = "getPluginData" in node ? node.getPluginData(NATIVE_KEY) : "";
const others = (node.annotations || []).filter((a) => !(prev && a.label === prev));
try {
node.annotations = others.concat([categoryId ? { label, categoryId } : { label }]);
if ("setPluginData" in node) node.setPluginData(NATIVE_KEY, label);
count++;
} catch (e) {}
}
return count;
}
// Remove only the native annotations this plugin created for the frame.
function removeNativeAnnotations(frame) {
let removed = 0;
for (const node of frameDescendants(frame)) {
if (!("annotations" in node) || !("getPluginData" in node)) continue;
const prev = node.getPluginData(NATIVE_KEY);
if (!prev) continue;
const kept = (node.annotations || []).filter((a) => a.label !== prev);
if (kept.length !== (node.annotations || []).length) {
try { node.annotations = kept; removed++; } catch (e) {}
}
node.setPluginData(NATIVE_KEY, "");
}
return removed;
}
async function syncNativeAnnotationsIfEnabled(frame) {
if (hasNativeAnnotations(frame)) await syncNativeAnnotations(frame);
}
// ---------------------------------------------------------------------------
// Auto-annotation — local heuristic + AI (Anthropic / OpenAI)
// ---------------------------------------------------------------------------
// VoiceOver Designer numeric trait bitmask -> this plugin's string trait model.
function bitmaskToAnn(trait) {
trait = trait || 0;
const traits = [];
const textTraits = [];
const low = trait % SWITCH_TRAIT; // 32-bit-safe portion (all defined low bits < 2^18)
const has = (bit) => (low & bit) !== 0;
if (has(1)) traits.push("button");
if (has(8)) traits.push("link");
if (has(16)) traits.push("selected");
if (has(32)) traits.push("image");
if (has(128)) traits.push("summaryElement");
if (has(256)) traits.push("updatesFrequently");
if (has(512)) traits.push("playsSound");
if (has(1024)) traits.push("startsMediaSession");
if (has(2048)) traits.push("allowsDirectInteraction");
if (has(4096)) traits.push("causesPageTurn");
if (has(131072)) traits.push("disabled");
if (Math.floor(trait / SWITCH_TRAIT) % 2 === 1) traits.push("switcher");
if (has(2)) textTraits.push("header");
if (has(64)) textTraits.push("staticText");
if (has(8192)) textTraits.push("textInput");
if (has(16384)) textTraits.push("isEditing");
if (has(32768)) textTraits.push("searchField");
if (has(65536)) textTraits.push("keyboardKey");
return { traits, textTraits, adjustable: has(4) };
}
// Local, name-based fallback analyzer. Returns [{ node, ann }] in our model.
// Defaults to static text (not button) when nothing signals interactivity.
function guessTraits(name, type) {
if (/header|title|заголовок|название/.test(name)) return { traits: [], textTraits: ["header"] };
if (/tab/.test(name)) return { traits: ["button", "causesPageTurn"], textTraits: [] };
if (/button|btn|back|cell|ячейка|кнопка|item|элемент/.test(name)) return { traits: ["button"], textTraits: [] };
return { traits: [], textTraits: ["staticText"] };
}
function heuristicAnnotations(frame) {
const out = [];
const visit = (n) => {
if (n.visible === false) return;
const name = (n.name || "").toLowerCase();
if (name.includes("status bar")) return;
const interactiveName = /cell|button|btn|tab|header|title|back|ячейка|кнопка|заголовок/.test(name);
const parts = innerTextParts(n);
const box = n.absoluteBoundingBox;
const small = !!(box && box.width <= 48 && box.height <= 48);
const include = interactiveName || n.type === "TEXT" || n.type === "INSTANCE";
let decorative =
/background|container|wrapper/.test(name) ||
(name.includes("icon") && !name.includes("button"));
// an unlabeled, small instance is almost certainly decorative (icon/avatar/chevron)
if (n.type === "INSTANCE" && !interactiveName && parts.length === 0 && small) decorative = true;
if (include && !decorative) {
const t = guessTraits(name, n.type);
out.push({
node: n,
ann: {
kind: "element",
label: (parts[0] || n.name || "").trim(),
value: parts.slice(1).join(" ").trim(),
hint: "",
adjustable: false,
enumerated: false,
values: [],
selectedIndex: 0,
traits: t.traits,
textTraits: t.textTraits,
customActions: [],
customDescriptions: [],
},
});
return; // treat as one element; don't descend into it
}
if ("children" in n) for (const c of n.children) visit(c);
};
if ("children" in frame) for (const c of frame.children) visit(c);
return out;
}
// Layer tree (with nodeId + frame-relative coords + text) sent to the AI.
function collectFrameData(frame) {
const fb = frame.absoluteBoundingBox;
const visit = (n) => {
if (n.visible === false) return null;
if ((n.name || "").toLowerCase().includes("status bar")) return null;
const b = n.absoluteBoundingBox;
const d = {
nodeId: n.id,
name: n.name,
type: n.type,
x: fb && b ? Math.round(b.x - fb.x) : 0,
y: fb && b ? Math.round(b.y - fb.y) : 0,
width: b ? Math.round(b.width) : 0,
height: b ? Math.round(b.height) : 0,
};
if (n.type === "TEXT" && typeof n.characters === "string") {
const t = n.characters.replace(/\s+/g, " ").trim();
if (t) d.text = t;
}
if ("children" in n) {
const kids = [];
for (const c of n.children) {
const cd = visit(c);
if (cd) kids.push(cd);
}
if (kids.length) d.children = kids;
}
return d;
};
const out = [];
if ("children" in frame) {
for (const c of frame.children) {
const cd = visit(c);
if (cd) out.push(cd);
}
}
return out;
}
// Distilled from the iOS Accessibility Skill (github.com/akaDuality/iOSAccessibilitySkill).
const AI_SKILL =
'Follow the iOS Accessibility Skill (github.com/akaDuality/iOSAccessibilitySkill), based on the book "About accessibility on iOS" by Mikhail Rubanov.\n\n' +
"Structure every element as label -> value -> trait:\n" +
'- label: the name / main content the user scans for. Keep it short. NEVER put the element type ("button", "cell", "image") in the label — the trait already says it.\n' +
'- value: secondary or additional content, or the current state (e.g. "On", "3 of 5"). Empty if there is none.\n' +
"- trait: the role/state as a bitmask, summed: button 1, header 2, adjustable 4, link 8, selected 16, image 32, static text 64, updates frequently 256, text input 8192, is editing 16384, search field 32768, disabled 131072, switch button 9007199254740992. Combine by summing, e.g. selected button = 17.\n" +
"- hint: what happens on activation (optional, starts with a verb).\n\n" +
"Rules:\n" +
"- One accessibility element per meaningful control. Collapse a cell/row into ONE element (label = title, value = subtitle/detail).\n" +
"- Interactive layers (buttons, cells, tabs, links) set the button/link bit.\n" +
"- Headings and section titles set the header bit (2).\n" +
"- Adjustable controls (segmented, stepper, slider) set bit 4 with the choices in options and isEnumerated true. A switch/toggle uses the switch-button trait (9007199254740992).\n" +
"- Hide decorative layers (icons, avatars, chevrons, backgrounds) — do NOT emit them.\n" +
"- Skip the status bar.";
function buildAIPrompt(frameName, frameData) {
return (
AI_SKILL +
'\n\nAnalyze the Figma frame "' + frameName + '" and produce VoiceOver annotations.\n' +
"Layer tree (JSON; coordinates are relative to the frame):\n" +
JSON.stringify(frameData) +
"\n\nReturn ONLY a JSON object of exactly this shape, no prose:\n" +
'{"elements":[{"nodeId":"<echo this layer\'s nodeId>","label":"","value":"","hint":"","trait":1,"options":[],"isEnumerated":false,"actions":[]}]}'
);
}
// JSON Schema for structured output (guarantees parseable results).
const AI_SCHEMA = {
type: "object",
additionalProperties: false,
required: ["elements"],
properties: {
elements: {
type: "array",
items: {
type: "object",
additionalProperties: false,
required: ["nodeId", "label", "value", "hint", "trait", "options", "isEnumerated", "actions"],
properties: {
nodeId: { type: "string" },
label: { type: "string" },
value: { type: "string" },
hint: { type: "string" },
trait: { type: "integer" },
options: { type: "array", items: { type: "string" } },
isEnumerated: { type: "boolean" },
actions: { type: "array", items: { type: "string" } },
},
},
},
},
};
function fetchWithTimeout(url, options, ms) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject(new Error("Request timed out")), ms)),
]);
}
// One retry on rate-limit / overload, honouring Retry-After.