-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgridsetProcessor.ts
More file actions
2279 lines (2072 loc) · 85.7 KB
/
Copy pathgridsetProcessor.ts
File metadata and controls
2279 lines (2072 loc) · 85.7 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
import {
BaseProcessor,
ProcessorOptions,
ExtractStringsResult,
TranslatedString,
SourceString,
} from '../core/baseProcessor';
import {
AACTree,
AACPage,
AACButton,
AACSemanticAction,
AACSemanticCategory,
AACSemanticIntent,
GridSetMetadata,
} from '../core/treeStructure';
import { AACStyle } from '../types/aac';
import { XMLParser, XMLBuilder } from 'fast-xml-parser';
import { resolveGrid3CellImage } from './gridset/resolver';
import {
extractAllButtonsForTranslation,
validateTranslationResults,
type ButtonForTranslation,
type LLMLTranslationResult,
} from '../utilities/translation/translationProcessor';
import {
getZipEntriesFromAdapter,
resolveGridsetPassword,
type ZipEntry,
} from './gridset/password';
import { decryptGridsetEntry } from './gridset/crypto';
import { GridsetValidator } from '../validation/gridsetValidator';
import { ValidationResult } from '../validation/validationTypes';
// New imports for enhanced Grid 3 support
import { detectPluginCellType, Grid3CellType } from './gridset/pluginTypes';
import { detectCommand } from './gridset/commands';
import { type SymbolReference, parseSymbolReference } from './gridset/symbols';
import { isSymbolLibraryReference } from './gridset/resolver';
import { generateCloneId } from '../utilities/analytics/utils/idGenerator';
import { translateWithSymbols, extractSymbolsFromButton } from './gridset/symbolAlignment';
import {
ProcessorInput,
readBinaryFromInput,
decodeText,
writeBinaryToPath,
getNodeRequire,
isNodeRuntime,
} from '../utils/io';
import { openZipFromInput } from '../utils/zip';
class GridsetProcessor extends BaseProcessor {
constructor(options?: ProcessorOptions) {
super(options);
}
// Determine password to use when opening encrypted gridset archives (.gridsetx)
private getGridsetPassword(source?: ProcessorInput): string | undefined {
return resolveGridsetPassword(this.options, source);
}
// Helper function to ensure color has alpha channel (Grid3 format)
private ensureAlphaChannel(color: string | undefined): string {
if (!color) return '#FFFFFFFF';
// Handle rgb() and rgba() formats
const rgbMatch = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
if (rgbMatch) {
const r = parseInt(rgbMatch[1]);
const g = parseInt(rgbMatch[2]);
const b = parseInt(rgbMatch[3]);
const a = rgbMatch[4] !== undefined ? parseFloat(rgbMatch[4]) : 1.0;
const alphaHex = Math.round(a * 255)
.toString(16)
.toUpperCase()
.padStart(2, '0');
return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}${alphaHex}`;
}
// If already 8 digits (with alpha), return as is
if (color.match(/^#[0-9A-Fa-f]{8}$/)) return color;
// If 6 digits (no alpha), add FF for fully opaque
if (color.match(/^#[0-9A-Fa-f]{6}$/)) return color + 'FF';
// If 3 digits (shorthand), expand to 8
if (color.match(/^#[0-9A-Fa-f]{3}$/)) {
const r = color[1];
const g = color[2];
const b = color[3];
return `#${r}${r}${g}${g}${b}${b}FF`;
}
// Invalid or unknown format, return white
return '#FFFFFFFF';
}
/**
* Calculate appropriate font color (black or white) based on background brightness
* Uses WCAG relative luminance formula to determine contrast
*/
private getContrastFontColor(backgroundColor: string | undefined): string {
if (!backgroundColor) return '#FF000000FF'; // Default to black
// Parse color from various formats
let r = 255,
g = 255,
b = 255;
// Handle hex colors
const hexMatch = backgroundColor.match(/#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/);
if (hexMatch) {
r = parseInt(hexMatch[1], 16);
g = parseInt(hexMatch[2], 16);
b = parseInt(hexMatch[3], 16);
} else {
// Handle rgb() format
const rgbMatch = backgroundColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (rgbMatch) {
r = parseInt(rgbMatch[1]);
g = parseInt(rgbMatch[2]);
b = parseInt(rgbMatch[3]);
}
}
// Calculate relative luminance using WCAG formula
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// Use white text for dark backgrounds (luminance < 0.5), black for light backgrounds
// Return 6-digit hex (ensureAlphaChannel will add FF for alpha)
return luminance < 0.5 ? '#FFFFFF' : '#000000';
}
/**
* Extract words from Grid3 WordList structure
*/
private _extractWordsFromWordList(param: any): string[] {
if (!param) return [];
// Sometimes the param itself is the WordList, sometimes it has a WordList property
const wordList =
param.WordList || param.wordlist || (param.Items || param.items ? param : undefined);
if (!wordList || !(wordList.Items || wordList.items)) return [];
const items = wordList.Items?.WordListItem || wordList.items?.wordlistitem || [];
const itemArr = Array.isArray(items) ? items : [items];
const words: string[] = [];
for (const item of itemArr) {
const text = item.Text || item.text;
if (text) {
const val = this.textOf(text);
if (val) words.push(val);
} else if (item['#text'] !== undefined) {
words.push(String(item['#text']));
} else if (typeof item === 'string') {
words.push(item);
}
}
return words;
}
// Helper function to generate Grid3 commands from semantic actions
private generateCommandsFromSemanticAction(button: AACButton, tree?: AACTree): any {
const semanticAction = button.semanticAction;
if (!semanticAction) {
// Default to insert text action with structured XML format
// Use two <s> elements: one for the word, one for the space (CDATA preserves whitespace)
let text = button.message || button.label || '';
// Remove trailing space from message if present (we'll add it as separate segment)
if (text.endsWith(' ')) {
text = text.slice(0, -1);
}
return {
Command: {
'@_ID': 'Action.InsertText',
Parameter: {
'@_Key': 'text',
p: {
s: [
{
r: text,
},
{
r: { __cdata: ' ' },
},
],
},
},
},
};
}
// Use platform-specific Grid3 data if available
if (semanticAction.platformData?.grid3) {
const grid3Data = semanticAction.platformData.grid3;
const params = Object.entries(grid3Data.parameters || {}).map(([key, value]) => ({
'@_Key': key,
'#text': String(value),
}));
return {
Command: {
'@_ID': grid3Data.commandId,
...(params.length > 0 ? { Parameter: params } : {}),
},
};
}
// Convert semantic actions to Grid3 commands
const intentStr = String(semanticAction.intent);
switch (intentStr) {
case 'NAVIGATE_TO': {
// For Grid3, we need to use the grid name, not the ID
let targetGridName = semanticAction.targetId || '';
if (tree && semanticAction.targetId) {
const targetPage = tree.getPage(semanticAction.targetId);
if (targetPage) {
targetGridName = targetPage.name || targetPage.id;
}
}
return {
Command: {
'@_ID': 'Jump.To',
Parameter: {
'@_Key': 'grid',
'#text': targetGridName,
},
},
};
}
case 'GO_BACK':
return {
Command: {
'@_ID': 'Jump.Back',
},
};
case 'GO_HOME':
return {
Command: {
'@_ID': 'Jump.Home',
},
};
case 'DELETE_WORD':
return {
Command: {
'@_ID': 'Action.DeleteWord',
},
};
case 'DELETE_CHARACTER':
return {
Command: {
'@_ID': 'Action.DeleteLetter',
},
};
case 'CLEAR_TEXT':
return {
Command: {
'@_ID': 'Action.Clear',
},
};
case 'SPEAK_TEXT':
case 'SPEAK_IMMEDIATE': {
// Users can speak the complete sentence with a dedicated Speak button // Use two <s> elements: one for the word, one for the space (CDATA preserves whitespace) // Grid3 requires explicit trailing space for automatic word spacing // For communication buttons, insert text into message bar (sentence building)
let text = semanticAction.text || button.message || button.label || '';
// Remove trailing space from message if present (we'll add it as separate segment)
if (text.endsWith(' ')) {
text = text.slice(0, -1);
}
return {
Command: {
'@_ID': 'Action.InsertText',
Parameter: {
'@_Key': 'text',
p: {
s: [
{
r: text,
},
{
r: { __cdata: ' ' },
},
],
},
},
},
};
}
case 'INSERT_TEXT': {
// Use two <s> elements: one for the word, one for the space (CDATA preserves whitespace) // Add trailing space for word buttons to enable sentence building
let text = semanticAction.text || button.message || button.label || '';
// Remove trailing space from message if present (we'll add it as separate segment)
if (text.endsWith(' ')) {
text = text.slice(0, -1);
}
return {
Command: {
'@_ID': 'Action.InsertText',
Parameter: {
'@_Key': 'text',
p: {
s: [
{
r: text,
},
{
r: { __cdata: ' ' },
},
],
},
},
},
};
}
default: {
// Use two <s> elements: one for the word, one for the space (CDATA preserves whitespace)
// Fallback to insert text with structured XML format
let text = semanticAction.text || button.message || button.label || '';
// Remove trailing space from message if present (we'll add it as separate segment)
if (text.endsWith(' ')) {
text = text.slice(0, -1);
}
return {
Command: {
'@_ID': 'Action.InsertText',
Parameter: {
'@_Key': 'text',
p: {
s: [
{
r: text,
},
{
r: { __cdata: ' ' },
},
],
},
},
},
};
}
}
}
// Helper function to convert Grid 3 style to AACStyle
private convertGrid3StyleToAACStyle(grid3Style: any): any {
if (!grid3Style) return {};
return {
backgroundColor: grid3Style.BackColour || grid3Style.TileColour,
borderColor: grid3Style.BorderColour,
fontColor: grid3Style.FontColour,
fontFamily: grid3Style.FontName,
fontSize: grid3Style.FontSize ? parseInt(String(grid3Style.FontSize)) : undefined,
backgroundShape:
grid3Style.BackgroundShape !== undefined
? parseInt(String(grid3Style.BackgroundShape))
: undefined,
};
}
// Helper function to get style by ID or return default
private getStyleById(styles: Map<string, any>, styleId?: string): any {
if (!styleId || !styles.has(styleId)) {
return {};
}
return this.convertGrid3StyleToAACStyle(styles.get(styleId));
}
// Helper to safely extract text from XML parser values
private textOf(val: any): string | undefined {
if (!val) return undefined;
if (typeof val === 'string') return val;
if (typeof val === 'number') return String(val);
if (typeof val === 'object') {
if ('#text' in val) return String(val['#text']);
// Handle Grid3 structured format <p><s><r>text</r></s></p>
// Can start at p, s, or r level
const parts: string[] = [];
const processS = (s: any): void => {
if (!s) return;
if (s.r !== undefined) {
const rElements = Array.isArray(s.r) ? s.r : [s.r];
for (const r of rElements) {
if (typeof r === 'number') {
if (r !== 0) {
parts.push(String(r));
}
continue;
}
if (typeof r === 'object' && r !== null && '#text' in r) {
parts.push(String(r['#text']));
} else {
parts.push(String(r));
}
}
}
};
if (val.p) {
const p = val.p;
const sElements = Array.isArray(p.s) ? p.s : p.s ? [p.s] : [];
sElements.forEach(processS);
} else if (val.s) {
const sElements = Array.isArray(val.s) ? val.s : [val.s];
sElements.forEach(processS);
} else if (val.r !== undefined) {
processS(val);
}
if (parts.length > 0) {
return parts.join('').trim();
}
}
return undefined;
}
async extractTexts(filePathOrBuffer: ProcessorInput): Promise<string[]> {
const tree = await this.loadIntoTree(filePathOrBuffer);
const texts: string[] = [];
for (const pageId in tree.pages) {
const page = tree.pages[pageId];
if (page.name) texts.push(page.name);
page.buttons.forEach((btn) => {
if (btn.label) texts.push(btn.label);
if (btn.message && btn.message !== btn.label) texts.push(btn.message);
});
}
return texts;
}
async loadIntoTree(filePathOrBuffer: ProcessorInput): Promise<AACTree> {
const tree = new AACTree();
let zipResult: Awaited<ReturnType<typeof openZipFromInput>>;
try {
zipResult = await openZipFromInput(readBinaryFromInput(filePathOrBuffer));
} catch (error: any) {
throw new Error(`Invalid ZIP file format: ${error.message}`);
}
const password = this.getGridsetPassword(filePathOrBuffer);
const entries = getZipEntriesFromAdapter(zipResult.zip, password);
const parser = new XMLParser({ ignoreAttributes: false });
const isEncryptedArchive =
typeof filePathOrBuffer === 'string' && filePathOrBuffer.toLowerCase().endsWith('.gridsetx');
const encryptedContentPassword = this.getGridsetPassword(filePathOrBuffer);
// Initialize metadata
const metadata: GridSetMetadata = {
format: 'gridset',
isSmartBox: isEncryptedArchive, // SmartBox files are .gridsetx encrypted archives
passwordProtected: !!password,
};
const readEntryBuffer = async (entry: ZipEntry): Promise<Uint8Array> => {
const raw = await entry.getData();
if (!isEncryptedArchive) {
return raw;
}
return decryptGridsetEntry(Buffer.from(raw), encryptedContentPassword);
};
// Parse FileMap.xml if present to index dynamic files per grid
const fileMapIndex = new Map<string, string[]>();
try {
const fmEntry = entries.find((e) => e.entryName.endsWith('FileMap.xml'));
if (fmEntry) {
const fmXml = decodeText(await readEntryBuffer(fmEntry));
const fmData = parser.parse(fmXml);
const entries = fmData?.FileMap?.Entries?.Entry || fmData?.fileMap?.entries?.entry;
if (entries) {
const arr = Array.isArray(entries) ? entries : [entries];
for (const ent of arr) {
const rawStaticFile = ent['@_StaticFile'] || ent.StaticFile || ent.staticFile;
const staticFile =
typeof rawStaticFile === 'string' ? rawStaticFile.replace(/\\/g, '/') : '';
if (!staticFile) continue;
const df = ent.DynamicFiles || ent.dynamicFiles;
const candidates = df?.File || df?.file || df?.Files || df?.files;
const list = Array.isArray(candidates) ? candidates : candidates ? [candidates] : [];
const files: string[] = [];
for (const v of list) {
if (!v) continue;
if (typeof v === 'string') files.push(v.replace(/\\/g, '/'));
else if (typeof v === 'object' && '#text' in v)
files.push(String(v['#text']).replace(/\\/g, '/'));
}
fileMapIndex.set(staticFile, files);
}
}
}
} catch (e) {
/* ignore: optional FileMap.xml may be missing or malformed */
}
// First, load styles from Settings0/Styles/styles.xml (Grid3 format)
const styles = new Map<string, any>();
const styleEntry = entries.find(
(entry) => entry.entryName.endsWith('styles.xml') || entry.entryName.endsWith('style.xml')
);
if (styleEntry) {
try {
const styleXmlContent = decodeText(await readEntryBuffer(styleEntry));
const styleData = parser.parse(styleXmlContent);
// Parse styles and store them in the map
// Grid3 uses StyleData.Styles.Style with Key attribute
if (styleData.StyleData?.Styles?.Style) {
const styleArray = Array.isArray(styleData.StyleData.Styles.Style)
? styleData.StyleData.Styles.Style
: [styleData.StyleData.Styles.Style];
styleArray.forEach((style: any) => {
if (style['@_Key']) {
styles.set(String(style['@_Key']), style);
}
});
}
// Also handle legacy format with @_ID
else if (styleData.Styles?.Style) {
const styleArray = Array.isArray(styleData.Styles.Style)
? styleData.Styles.Style
: [styleData.Styles.Style];
styleArray.forEach((style: any) => {
if (style['@_ID']) {
styles.set(String(style['@_ID']), style);
}
});
}
} catch (e) {
console.warn('Failed to parse styles.xml:', e);
}
}
// Debug: log all entry names
console.log('[Gridset] Total zip entries:', entries.length);
const normalizeEntryName = (entryName: string): string =>
entryName.replace(/\\/g, '/').toLowerCase();
const isGridXmlEntry = (entryName: string): boolean => {
const normalized = normalizeEntryName(entryName);
if (!normalized.endsWith('grid.xml')) return false;
return normalized.startsWith('grids/') || normalized.includes('/grids/');
};
const gridEntries = entries.filter((e) => isGridXmlEntry(e.entryName));
console.log('[Gridset] Grid XML entries found:', gridEntries.length);
if (gridEntries.length > 0) {
console.log(
'[Gridset] First few grid entries:',
gridEntries.slice(0, 3).map((e) => e.entryName)
);
}
// First pass: collect all grid names and IDs for navigation resolution
const gridNameToIdMap = new Map<string, string>();
const gridIdToNameMap = new Map<string, string>();
for (const entry of entries) {
if (isGridXmlEntry(entry.entryName)) {
try {
const xmlContent = decodeText(await readEntryBuffer(entry));
const data = parser.parse(xmlContent);
const grid = data.Grid || data.grid;
if (!grid) continue;
const gridId = this.textOf(grid.GridGuid || grid.gridGuid || grid.id);
const gridName =
this.textOf(grid.Name) || this.textOf(grid.name) || this.textOf(grid['@_Name']);
const folderMatch = entry.entryName.match(/^Grids\/([^/]+)\//);
const folderName = folderMatch ? folderMatch[1] : undefined;
if (gridId) {
if (gridName) {
gridNameToIdMap.set(gridName, gridId);
gridIdToNameMap.set(gridId, gridName);
}
if (folderName) {
// Folder name is often used as the grid name in Jump.To commands
gridNameToIdMap.set(folderName, gridId);
if (!gridName) {
gridIdToNameMap.set(gridId, folderName);
}
}
}
} catch (e) {
// Skip errors in first pass
}
}
}
// Second pass: process each grid file in the gridset
for (const entry of entries) {
// Only process files named grid.xml under Grids/ (any subdir)
if (isGridXmlEntry(entry.entryName)) {
let xmlContent: string;
try {
const buffer = await readEntryBuffer(entry);
xmlContent = decodeText(buffer);
console.log(
`[Gridset] Raw XML content (first 200 chars) for ${entry.entryName}:`,
xmlContent.substring(0, 200)
);
} catch (e) {
// Skip unreadable files
continue;
}
let data: Record<string, unknown>;
try {
data = parser.parse(xmlContent) as Record<string, unknown>;
console.log(`[Gridset] Parsed ${entry.entryName}, root keys:`, Object.keys(data));
} catch (error: any) {
// Skip malformed XML but log the specific error
console.warn(`Malformed XML in ${entry.entryName}: ${error.message}`);
continue;
}
// Grid3 XML: <Grid> root
const grid = (data as { Grid?: any; grid?: any }).Grid || (data as { grid?: any }).grid;
if (!grid) {
console.warn(`[Gridset] No Grid/grid found in ${entry.entryName}`);
continue;
}
// Defensive: GridGuid and Name required
const gridId = this.textOf(grid.GridGuid || grid.gridGuid || grid.id);
let gridName =
this.textOf(grid.Name) || this.textOf(grid.name) || this.textOf(grid['@_Name']);
if (!gridName) {
// Fallback: get folder name from entry path
const match = entry.entryName.match(/^Grids\/([^/]+)\//);
if (match) gridName = match[1];
}
if (!gridId || !gridName) {
continue;
}
const page = new AACPage({
id: String(gridId),
name: String(gridName),
grid: [],
buttons: [],
parentId: null,
style: {
backgroundColor: grid.BackgroundColour || grid.backgroundColour,
},
});
// Calculate grid dimensions from ColumnDefinitions and RowDefinitions
const columnDefs = grid.ColumnDefinitions?.ColumnDefinition || [];
const rowDefs = grid.RowDefinitions?.RowDefinition || [];
const maxCols = Array.isArray(columnDefs) ? columnDefs.length : columnDefs ? 1 : 5;
const maxRows = Array.isArray(rowDefs) ? rowDefs.length : rowDefs ? 1 : 4;
// Process buttons: <Cells><Cell>
const cells = grid.Cells?.Cell || grid.cells?.cell;
if (cells) {
// Cells may be array or single object
const cellArr = Array.isArray(cells) ? cells : [cells];
// Create a 2D grid to track button positions
const gridLayout: (AACButton | null)[][] = [];
for (let r = 0; r < maxRows; r++) {
gridLayout[r] = new Array(maxCols).fill(null);
}
// Track grid-level prediction wordlists so we can attach them to AutoContent
const gridPredictionWords: string[] = [];
let predictionCellCounter = 0;
// Extract words from grid-level AutoContentCommands (e.g., Prediction Bar)
if (grid.AutoContentCommands) {
const collections = grid.AutoContentCommands.AutoContentCommandCollection;
const collectionArr = Array.isArray(collections)
? collections
: collections
? [collections]
: [];
collectionArr.forEach((collection: any) => {
const commands = collection.Commands?.Command;
const commandArr = Array.isArray(commands) ? commands : commands ? [commands] : [];
commandArr.forEach((command: any) => {
const commandId = command['@_ID'] || command.ID || command.id;
if (commandId === 'Prediction.PredictThis') {
const params = command.Parameter;
const paramArr = Array.isArray(params) ? params : params ? [params] : [];
const wordListParam = paramArr.find(
(p: any) => (p['@_Key'] || p.Key || p.key) === 'wordlist'
);
if (wordListParam) {
const words = this._extractWordsFromWordList(wordListParam);
gridPredictionWords.push(...words);
}
}
});
});
}
cellArr.forEach((cell: any, idx: number) => {
if (!cell || !cell.Content) return;
// Extract position information from cell attributes
// Grid3 uses 1-based coordinates, convert to 0-based for internal use
const cellX = Math.max(0, parseInt(String(cell['@_X'] || '1'), 10) - 1);
const cellY = Math.max(0, parseInt(String(cell['@_Y'] || '1'), 10) - 1);
const colSpan = parseInt(String(cell['@_ColumnSpan'] || '1'), 10);
const rowSpan = parseInt(String(cell['@_RowSpan'] || '1'), 10);
// Extract scan block number (1-8) for block scanning support
const scanBlock = parseInt(String(cell['@_ScanBlock'] || '1'), 10);
// Extract visibility from Grid 3's <Visibility> child element
// Grid 3 stores visibility as a child element, not an attribute
// Valid values: Visible, Hidden, Disabled, PointerAndTouchOnly, TouchOnly, PointerOnly
const grid3Visibility = cell.Visibility || cell.visibility;
// Map Grid 3 visibility values to AAC standard values
// Grid 3 can have additional values like TouchOnly, PointerOnly that map to PointerAndTouchOnly
let cellVisibility:
| 'Visible'
| 'Hidden'
| 'Disabled'
| 'PointerAndTouchOnly'
| 'Empty'
| undefined;
if (grid3Visibility) {
const vis = String(grid3Visibility);
// Direct mapping for standard values
if (
vis === 'Visible' ||
vis === 'Hidden' ||
vis === 'Disabled' ||
vis === 'PointerAndTouchOnly'
) {
cellVisibility = vis;
}
// Map Grid 3 specific values to AAC standard
else if (vis === 'TouchOnly' || vis === 'PointerOnly') {
cellVisibility = 'PointerAndTouchOnly';
}
// Grid 3 may use 'Empty' for cells that exist but have no content
else if (vis === 'Empty') {
cellVisibility = 'Empty';
}
// Unknown visibility - default to Visible
else {
cellVisibility = undefined; // Let it default
}
}
// Extract label from CaptionAndImage/Caption
const content = cell.Content;
const captionAndImage = content.CaptionAndImage || content.captionAndImage;
let label = this.textOf(captionAndImage?.Caption || captionAndImage?.caption) || '';
// Check if cell has an image/symbol (needed to decide if we should keep it)
const hasImageCandidate = !!(
captionAndImage?.Image ||
captionAndImage?.image ||
captionAndImage?.ImageName ||
captionAndImage?.imageName ||
captionAndImage?.Symbol ||
captionAndImage?.symbol
);
// If no caption, try other sources or create a placeholder
if (!label) {
// For cells without captions, check if they have images/symbols before skipping
if (content.ContentType === 'AutoContent') {
label = `AutoContent_${idx}`;
} else if (
hasImageCandidate ||
content.ContentType === 'Workspace' ||
content.ContentType === 'LiveCell'
) {
// Keep cells with images/symbols even if no caption
label = `Cell_${idx}`;
} else {
return; // Skip cells without labels AND without images/symbols
}
}
const message = label; // Use caption as message
// Detect plugin cell type (Workspace, LiveCell, AutoContent)
const pluginMetadata = detectPluginCellType(content);
// Friendly labels for workspace/prediction cells when captions are missing
if (pluginMetadata.cellType === Grid3CellType.Workspace) {
if (!label || label.startsWith('Cell_')) {
label =
pluginMetadata.displayName ||
pluginMetadata.subType ||
pluginMetadata.pluginId ||
'Workspace';
}
}
if (
pluginMetadata.cellType === Grid3CellType.AutoContent &&
pluginMetadata.autoContentType === 'Prediction'
) {
predictionCellCounter += 1;
// Always surface a friendly label for predictions even if a placeholder exists
label = `Prediction ${predictionCellCounter}`;
}
// Parse all command types from Grid3 and create semantic actions
let semanticAction: AACSemanticAction | undefined;
let legacyAction: any = null;
// infer action type implicitly from commands; no explicit enum needed
let navigationTarget: string | undefined;
let detectedCommands: any[] = []; // Store detected command metadata
const commands = content.Commands?.Command || content.commands?.command;
let predictionWords: string[] | undefined;
// Resolve image for this cell using FileMap and coordinate heuristics
const imageCandidate =
captionAndImage?.Image ||
captionAndImage?.image ||
captionAndImage?.ImageName ||
captionAndImage?.imageName ||
captionAndImage?.Symbol ||
captionAndImage?.symbol;
const declaredImageName = imageCandidate ? this.textOf(imageCandidate) : undefined;
const gridEntryPath = entry.entryName.replace(/\\/g, '/');
const baseDir = gridEntryPath.replace(/\/grid\.xml$/, '/');
const dynamicFiles = fileMapIndex.get(gridEntryPath) || [];
const resolvedImageEntry =
resolveGrid3CellImage(
null,
{
baseDir,
imageName: declaredImageName,
x: cellX + 1,
y: cellY + 1,
dynamicFiles,
},
entries
) || undefined;
// Check if image is a symbol library reference
let symbolLibraryRef: SymbolReference | null = null;
if (declaredImageName && isSymbolLibraryReference(declaredImageName)) {
symbolLibraryRef = parseSymbolReference(declaredImageName);
}
if (commands) {
const commandArr = Array.isArray(commands) ? commands : [commands];
detectedCommands = commandArr.map((cmd) => detectCommand(cmd));
// Scan all commands for vocabulary (predictions) before identifying primary action
commandArr.forEach((cmd) => {
const id = cmd['@_ID'] || cmd.ID || cmd.id;
if (id === 'Prediction.PredictThis') {
const params = cmd.Parameter || cmd.parameter;
const pArr = params ? (Array.isArray(params) ? params : [params]) : [];
let wlP: any;
for (const p of pArr) {
if (p['@_Key'] === 'wordlist' || p.Key === 'wordlist' || p.key === 'wordlist') {
wlP = p;
break;
}
}
if (wlP) {
const words = this._extractWordsFromWordList(wlP);
if (words.length > 0) {
predictionWords = words;
}
}
}
});
for (const command of commandArr) {
const commandId = command['@_ID'] || command.ID || command.id;
const parameters = command.Parameter || command.parameter;
const paramArr = parameters
? Array.isArray(parameters)
? parameters
: [parameters]
: [];
// Helper to get raw parameter object
const getRawParam = (key: string): any | undefined => {
for (const param of paramArr) {
if (param['@_Key'] === key || param.Key === key || param.key === key) {
return param;
}
}
return undefined;
};
// Helper to get parameter value
const getParam = (key: string): string | undefined => {
const param = getRawParam(key);
if (param === undefined) return undefined;
const simpleValue = param['#text'] ?? param.text ?? param.value;
if (typeof simpleValue === 'string') return simpleValue;
if (typeof simpleValue === 'number') return String(simpleValue);
const structuredValue = this.textOf(param);
if (structuredValue !== undefined) return structuredValue;
if (typeof param === 'string') return param;
return undefined;
};
// Skip PredictThis in primary action loop as it was handled in pre-pass
// unless we need a primary action and nothing else exists
if (commandId === 'Prediction.PredictThis') {
const wlParam = getRawParam('wordlist');
const words = wlParam ? this._extractWordsFromWordList(wlParam) : [];
if (words.length > 0) {
predictionWords = words;
}
if (!semanticAction && words.length > 0) {
semanticAction = {
category: AACSemanticCategory.COMMUNICATION,
intent: AACSemanticIntent.PLATFORM_SPECIFIC,
text: words.slice(0, 3).join(', '),
platformData: {
grid3: { commandId, parameters: { wordlist: words } },
},
fallback: { type: 'ACTION', message: 'Predict words' },
};
}
continue;
}
switch (commandId) {
case 'Jump.To': {
const gridTarget = getParam('grid');
if (gridTarget) {
// Resolve grid name to grid ID for navigation
const targetGridId = gridNameToIdMap.get(gridTarget) || gridTarget;
navigationTarget = targetGridId;
// navigate action
semanticAction = {
category: AACSemanticCategory.NAVIGATION,
intent: AACSemanticIntent.NAVIGATE_TO,
targetId: targetGridId,
platformData: {
grid3: {
commandId,
parameters: { grid: gridTarget },
},
},
fallback: {
type: 'NAVIGATE',
targetPageId: targetGridId,
},
};
legacyAction = {
type: 'NAVIGATE',
targetPageId: targetGridId,
};
}
break;
}
case 'Jump.Back':
// action
semanticAction = {
category: AACSemanticCategory.NAVIGATION,
intent: AACSemanticIntent.GO_BACK,
platformData: {
grid3: {
commandId,
parameters: {},
},
},
fallback: {
type: 'ACTION',
message: 'Go back',
},
};
legacyAction = {
type: 'GO_BACK',
};
break;
case 'Jump.Home':
case 'Jump.SetHome':
// action
navigationTarget = tree.rootId || undefined;
semanticAction = {
category: AACSemanticCategory.NAVIGATION,
intent: AACSemanticIntent.GO_HOME,
targetId: tree.rootId || undefined,
platformData: {
grid3: {
commandId,
parameters: {},