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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable max-classes-per-file */

import { Transform, Type, plainToClass } from "class-transformer";

import { type PopoverButtonStyle, type IconName, type IconSize } from "@graphite/utility-functions/icons";
import { type EditorHandle } from "@graphite-frontend/wasm/pkg/graphite_wasm.js";

export class JsMessage {
	// The marker provides a way to check if an object is a sub-class constructor for a jsMessage.
	static readonly jsMessageMarker = true;
}

const TupleToVec2 = Transform(({ value }: { value: [number, number] | undefined }) => (value === undefined ? undefined : { x: value[0], y: value[1] }));
const ImportsToVec2Array = Transform(({ obj: { imports } }: { obj: { imports: [FrontendGraphOutput, number, number][] } }) =>
	imports.map(([outputMetadata, x, y]) => ({ outputMetadata, position: { x, y } })),
);
const ExportsToVec2Array = Transform(({ obj: { exports } }: { obj: { exports: [FrontendGraphInput, number, number][] } }) =>
	exports.map(([inputMetadata, x, y]) => ({ inputMetadata, position: { x, y } })),
);

// const BigIntTupleToVec2 = Transform(({ value }: { value: [bigint, bigint] | undefined }) => (value === undefined ? undefined : { x: Number(value[0]), y: Number(value[1]) }));

export type XY = { x: number; y: number };

// ============================================================================
// Add additional classes below to replicate Rust's `FrontendMessage`s and data structures.
//
// Remember to add each message to the `messageConstructors` export at the bottom of the file.
//
// Read class-transformer docs at https://github.com/typestack/class-transformer#table-of-contents
// for details about how to transform the JSON from wasm-bindgen into classes.
// ============================================================================

export class UpdateBox extends JsMessage {
	readonly box!: Box | undefined;
}

export class UpdateClickTargets extends JsMessage {
	readonly clickTargets!: FrontendClickTargets | undefined;
}

const ContextTupleToVec2 = Transform((data) => {
	if (data.obj.contextMenuInformation === undefined) return undefined;
	const contextMenuCoordinates = { x: data.obj.contextMenuInformation.contextMenuCoordinates[0], y: data.obj.contextMenuInformation.contextMenuCoordinates[1] };
	let contextMenuData = data.obj.contextMenuInformation.contextMenuData;
	if (contextMenuData.ToggleLayer !== undefined) {
		contextMenuData = { nodeId: contextMenuData.ToggleLayer.nodeId, currentlyIsNode: contextMenuData.ToggleLayer.currentlyIsNode };
	} else if (contextMenuData.CreateNode !== undefined) {
		contextMenuData = { type: "CreateNode", compatibleType: contextMenuData.CreateNode.compatibleType };
	}
	return { contextMenuCoordinates, contextMenuData };
});

export class UpdateContextMenuInformation extends JsMessage {
	@ContextTupleToVec2
	readonly contextMenuInformation!: ContextMenuInformation | undefined;
}

export class UpdateImportsExports extends JsMessage {
	@ImportsToVec2Array
	readonly imports!: { outputMetadata: FrontendGraphOutput; position: XY }[];

	@ExportsToVec2Array
	readonly exports!: { inputMetadata: FrontendGraphInput; position: XY }[];

	@TupleToVec2
	readonly addImport!: XY | undefined;

	@TupleToVec2
	readonly addExport!: XY | undefined;
}

export class UpdateInSelectedNetwork extends JsMessage {
	readonly inSelectedNetwork!: boolean;
}

export class UpdateImportReorderIndex extends JsMessage {
	readonly importIndex!: number | undefined;
}

export class UpdateExportReorderIndex extends JsMessage {
	readonly exportIndex!: number | undefined;
}

const LayerWidths = Transform(({ obj }) => obj.layerWidths);
const ChainWidths = Transform(({ obj }) => obj.chainWidths);
const HasLeftInputWire = Transform(({ obj }) => obj.hasLeftInputWire);

export class UpdateLayerWidths extends JsMessage {
	@LayerWidths
	readonly layerWidths!: Map<bigint, number>;
	@ChainWidths
	readonly chainWidths!: Map<bigint, number>;
	@HasLeftInputWire
	readonly hasLeftInputWire!: Map<bigint, boolean>;
}

export class UpdateNodeGraphNodes extends JsMessage {
	@Type(() => FrontendNode)
	readonly nodes!: FrontendNode[];
}

export class UpdateVisibleNodes extends JsMessage {
	readonly nodes!: bigint[];
}

export class UpdateNodeGraphWires extends JsMessage {
	readonly wires!: WireUpdate[];
}

export class ClearAllNodeGraphWires extends JsMessage {}

export class UpdateNodeGraphTransform extends JsMessage {
	readonly transform!: NodeGraphTransform;
}

const NodeDescriptions = Transform(({ obj }) => new Map(obj.nodeDescriptions));

export class SendUIMetadata extends JsMessage {
	@NodeDescriptions
	readonly nodeDescriptions!: Map<string, string>;
	@Type(() => FrontendNode)
	readonly nodeTypes!: FrontendNodeType[];
}

export class UpdateNodeThumbnail extends JsMessage {
	readonly id!: bigint;

	readonly value!: string;
}

export class UpdateNodeGraphSelection extends JsMessage {
	@Type(() => BigInt)
	readonly selected!: bigint[];
}

export class UpdateOpenDocumentsList extends JsMessage {
	@Type(() => FrontendDocumentDetails)
	readonly openDocuments!: FrontendDocumentDetails[];
}

export class UpdateWirePathInProgress extends JsMessage {
	readonly wirePath!: WirePath | undefined;
}

// Allows the auto save system to use a string for the id rather than a BigInt.
// IndexedDb does not allow for BigInts as primary keys.
// TypeScript does not allow subclasses to change the type of class variables in subclasses.
// It is an abstract class to point out that it should not be instantiated directly.
export abstract class DocumentDetails {
	readonly name!: string;

	readonly isAutoSaved!: boolean;

	readonly isSaved!: boolean;

	// This field must be provided by the subclass implementation
	// readonly id!: bigint | string;

	get displayName(): string {
		return `${this.name}${this.isSaved ? "" : "*"}`;
	}
}

export class FrontendDocumentDetails extends DocumentDetails {
	readonly id!: bigint;
}

export class Box {
	readonly startX!: number;

	readonly startY!: number;

	readonly endX!: number;

	readonly endY!: number;
}

export type FrontendClickTargets = {
	readonly nodeClickTargets: string[];
	readonly layerClickTargets: string[];
	readonly portClickTargets: string[];
	readonly iconClickTargets: string[];
	readonly allNodesBoundingBox: string;
	readonly importExportsBoundingBox: string;
	readonly modifyImportExport: string[];
};

export type ContextMenuInformation = {
	contextMenuCoordinates: XY;
	contextMenuData: "CreateNode" | { type: "CreateNode"; compatibleType: string } | { nodeId: bigint; currentlyIsNode: boolean };
};

export type FrontendGraphDataType = "General" | "Raster" | "VectorData" | "Number" | "Group" | "Artboard";

export class Node {
	readonly index!: bigint;
	// Omitted if this Node is an Import or Export to/from the node network
	readonly nodeId?: bigint;
}

const CreateOutputConnectorOptional = Transform(({ obj }) => {
	if (obj.connectedTo == undefined) {
		return undefined;
	}
	if (obj.connectedTo?.export !== undefined) {
		return { index: obj.connectedTo?.export };
	} else if (obj.connectedTo?.import !== undefined) {
		return { index: obj.connectedTo?.import };
	} else {
		if (obj.connectedTo?.node.inputIndex !== undefined) {
			return { nodeId: obj.connectedTo?.node.nodeId, index: obj.connectedTo?.node.inputIndex };
		} else {
			return { nodeId: obj.connectedTo?.node.nodeId, index: obj.connectedTo?.node.outputIndex };
		}
	}
});

export class FrontendGraphInput {
	readonly dataType!: FrontendGraphDataType;

	readonly name!: string;

	readonly description!: string;

	readonly resolvedType!: string;

	readonly validTypes!: string[];

	@CreateOutputConnectorOptional
	connectedTo!: Node | undefined;
}

const CreateInputConnectorArray = Transform(({ obj }) => {
	const newInputConnectors: Node[] = [];
	obj.connectedTo.forEach((connector: any) => {
		if (connector.export !== undefined) {
			newInputConnectors.push({ index: connector.export });
		} else if (connector.import !== undefined) {
			newInputConnectors.push({ index: connector.import });
		} else {
			if (connector.node.inputIndex !== undefined) {
				newInputConnectors.push({ nodeId: connector.node.nodeId, index: connector.node.inputIndex });
			} else {
				newInputConnectors.push({ nodeId: connector.node.nodeId, index: connector.node.outputIndex });
			}
		}
	});
	return newInputConnectors;
});

export class FrontendGraphOutput {
	readonly dataType!: FrontendGraphDataType;

	readonly name!: string;

	readonly description!: string;

	readonly resolvedType!: string;

	@CreateInputConnectorArray
	connectedTo!: Node[];
}

export class FrontendNode {
	readonly isLayer!: boolean;

	readonly canBeLayer!: boolean;

	readonly id!: bigint;

	readonly reference!: string | undefined;

	readonly displayName!: string;

	@Type(() => FrontendGraphInput)
	readonly primaryInput!: FrontendGraphInput | undefined;

	@Type(() => FrontendGraphInput)
	readonly exposedInputs!: FrontendGraphInput[];

	@Type(() => FrontendGraphOutput)
	readonly primaryOutput!: FrontendGraphOutput | undefined;

	@Type(() => FrontendGraphOutput)
	readonly exposedOutputs!: FrontendGraphOutput[];

	@TupleToVec2
	readonly position!: XY | undefined;

	// TODO: Store field for the width of the left node chain

	readonly previewed!: boolean;

	readonly visible!: boolean;

	readonly unlocked!: boolean;

	readonly errors!: string | undefined;

	readonly uiOnly!: boolean;
}

export class FrontendNodeType {
	readonly name!: string;

	readonly category!: string;

	readonly inputTypes!: string[];
}

export class NodeGraphTransform {
	readonly scale!: number;
	readonly x!: number;
	readonly y!: number;
}

export class WirePath {
	readonly pathString!: string;
	readonly dataType!: FrontendGraphDataType;
	readonly thick!: boolean;
	readonly dashed!: boolean;
}

export class WireUpdate {
	readonly id!: bigint;
	readonly inputIndex!: number;
	readonly wirePathUpdate!: WirePath | undefined;
}

export class IndexedDbDocumentDetails extends DocumentDetails {
	@Transform(({ value }: { value: bigint }) => value.toString())
	id!: string;
}

export class TriggerIndexedDbWriteDocument extends JsMessage {
	document!: string;

	@Type(() => IndexedDbDocumentDetails)
	details!: IndexedDbDocumentDetails;

	version!: string;
}

export class TriggerIndexedDbRemoveDocument extends JsMessage {
	// Use a string since IndexedDB can not use BigInts for keys
	@Transform(({ value }: { value: bigint }) => value.toString())
	documentId!: string;
}

export class UpdateInputHints extends JsMessage {
	@Type(() => HintInfo)
	readonly hintData!: HintData;
}

export type HintData = HintGroup[];

export type HintGroup = HintInfo[];

export class HintInfo {
	readonly keyGroups!: LayoutKeysGroup[];

	readonly keyGroupsMac!: LayoutKeysGroup[] | undefined;

	readonly mouse!: MouseMotion | undefined;

	readonly label!: string;

	readonly plus!: boolean;

	readonly slash!: boolean;
}

// Rust enum `Key`
export type KeyRaw = string;
// Serde converts a Rust `Key` enum variant into this format (via a custom serializer) with both the `Key` variant name (called `RawKey` in TS) and the localized `label` for the key
export type Key = { key: KeyRaw; label: string };
export type LayoutKeysGroup = Key[];
export type ActionKeys = { keys: LayoutKeysGroup };

export type MouseMotion = string;

// Channels can have any range (0-1, 0-255, 0-100, 0-360) in the context they are being used in, these are just containers for the numbers
export type HSVA = { h: number; s: number; v: number; a: number };
export type HSV = { h: number; s: number; v: number };
export type RGBA = { r: number; g: number; b: number; a: number };
export type RGB = { r: number; g: number; b: number };

export class Gradient {
	readonly stops!: { position: number; color: Color }[];

	constructor(stops: { position: number; color: Color }[]) {
		this.stops = stops;
	}

	toLinearGradientCSS(): string {
		if (this.stops.length === 1) {
			return `linear-gradient(to right, ${this.stops[0].color.toHexOptionalAlpha()} 0%, ${this.stops[0].color.toHexOptionalAlpha()} 100%)`;
		}
		const pieces = this.stops.map((stop) => `${stop.color.toHexOptionalAlpha()} ${stop.position * 100}%`);
		return `linear-gradient(to right, ${pieces.join(", ")})`;
	}

	toLinearGradientCSSNoAlpha(): string {
		if (this.stops.length === 1) {
			return `linear-gradient(to right, ${this.stops[0].color.toHexNoAlpha()} 0%, ${this.stops[0].color.toHexNoAlpha()} 100%)`;
		}
		const pieces = this.stops.map((stop) => `${stop.color.toHexNoAlpha()} ${stop.position * 100}%`);
		return `linear-gradient(to right, ${pieces.join(", ")})`;
	}

	firstColor(): Color | undefined {
		return this.stops[0]?.color;
	}

	lastColor(): Color | undefined {
		return this.stops[this.stops.length - 1]?.color;
	}

	atIndex(index: number): { position: number; color: Color } | undefined {
		return this.stops[index];
	}

	colorAtIndex(index: number): Color | undefined {
		return this.stops[index]?.color;
	}

	positionAtIndex(index: number): number | undefined {
		return this.stops[index]?.position;
	}
}

// All channels range are represented by 0-1, sRGB, gamma.
export class Color {
	readonly red!: number;

	readonly green!: number;

	readonly blue!: number;

	readonly alpha!: number;

	readonly none!: boolean;

	constructor();

	constructor(none: "none");

	constructor(hsva: HSVA);

	constructor(red: number, green: number, blue: number, alpha: number);

	constructor(firstArg?: "none" | HSVA | number, green?: number, blue?: number, alpha?: number) {
		// Empty constructor
		if (firstArg === undefined) {
			this.red = 0;
			this.green = 0;
			this.blue = 0;
			this.alpha = 1;
			this.none = false;
		} else if (firstArg === "none") {
			this.red = 0;
			this.green = 0;
			this.blue = 0;
			this.alpha = 1;
			this.none = true;
		}
		// HSVA constructor
		else if (typeof firstArg === "object" && green === undefined && blue === undefined && alpha === undefined) {
			const { h, s, v } = firstArg;
			const convert = (n: number): number => {
				const k = (n + h * 6) % 6;
				return v - v * s * Math.max(Math.min(...[k, 4 - k, 1]), 0);
			};

			this.red = convert(5);
			this.green = convert(3);
			this.blue = convert(1);
			this.alpha = firstArg.a;
			this.none = false;
		}
		// RGBA constructor
		else if (typeof firstArg === "number" && typeof green === "number" && typeof blue === "number" && typeof alpha === "number") {
			this.red = firstArg;
			this.green = green;
			this.blue = blue;
			this.alpha = alpha;
			this.none = false;
		}
	}

	static fromCSS(colorCode: string): Color | undefined {
		// Allow single-digit hex value inputs
		let colorValue = colorCode.trim();
		if (colorValue.length === 2 && colorValue.charAt(0) === "#" && /[0-9a-f]/i.test(colorValue.charAt(1))) {
			const digit = colorValue.charAt(1);
			colorValue = `#${digit}${digit}${digit}`;
		}

		const canvas = document.createElement("canvas");
		canvas.width = 1;
		canvas.height = 1;
		const context = canvas.getContext("2d");
		if (!context) return undefined;

		context.clearRect(0, 0, 1, 1);

		context.fillStyle = "black";
		context.fillStyle = colorValue;
		const comparisonA = context.fillStyle;

		context.fillStyle = "white";
		context.fillStyle = colorValue;
		const comparisonB = context.fillStyle;

		// Invalid color
		if (comparisonA !== comparisonB) {
			// If this color code didn't start with a #, add it and try again
			if (colorValue.trim().charAt(0) !== "#") return Color.fromCSS(`#${colorValue.trim()}`);
			return undefined;
		}

		context.fillRect(0, 0, 1, 1);

		const [r, g, b, a] = [...context.getImageData(0, 0, 1, 1).data];
		return new Color(r / 255, g / 255, b / 255, a / 255);
	}

	equals(other: Color): boolean {
		if (this.none && other.none) return true;
		return Math.abs(this.red - other.red) < 1e-6 && Math.abs(this.green - other.green) < 1e-6 && Math.abs(this.blue - other.blue) < 1e-6 && Math.abs(this.alpha - other.alpha) < 1e-6;
	}

	lerp(other: Color, t: number): Color {
		return new Color(this.red * (1 - t) + other.red * t, this.green * (1 - t) + other.green * t, this.blue * (1 - t) + other.blue * t, this.alpha * (1 - t) + other.alpha * t);
	}

	toHexNoAlpha(): string | undefined {
		if (this.none) return undefined;

		const r = Math.round(this.red * 255)
			.toString(16)
			.padStart(2, "0");
		const g = Math.round(this.green * 255)
			.toString(16)
			.padStart(2, "0");
		const b = Math.round(this.blue * 255)
			.toString(16)
			.padStart(2, "0");

		return `#${r}${g}${b}`;
	}

	toHexOptionalAlpha(): string | undefined {
		if (this.none) return undefined;

		const hex = this.toHexNoAlpha();
		const a = Math.round(this.alpha * 255)
			.toString(16)
			.padStart(2, "0");

		return a === "ff" ? hex : `${hex}${a}`;
	}

	toRgb255(): RGB | undefined {
		if (this.none) return undefined;

		return {
			r: Math.round(this.red * 255),
			g: Math.round(this.green * 255),
			b: Math.round(this.blue * 255),
		};
	}

	toRgbCSS(): string | undefined {
		const rgb = this.toRgb255();
		if (!rgb) return undefined;

		return `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
	}

	toRgbaCSS(): string | undefined {
		const rgb = this.toRgb255();
		if (!rgb) return undefined;

		return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${this.alpha})`;
	}

	toHSV(): HSV | undefined {
		const hsva = this.toHSVA();
		if (!hsva) return undefined;

		return { h: hsva.h, s: hsva.s, v: hsva.v };
	}

	toHSVA(): HSVA | undefined {
		if (this.none) return undefined;

		const { red: r, green: g, blue: b, alpha: a } = this;

		const max = Math.max(r, g, b);
		const min = Math.min(r, g, b);

		const d = max - min;
		const s = max === 0 ? 0 : d / max;
		const v = max;

		let h = 0;
		if (max !== min) {
			switch (max) {
				case r:
					h = (g - b) / d + (g < b ? 6 : 0);
					break;
				case g:
					h = (b - r) / d + 2;
					break;
				case b:
					h = (r - g) / d + 4;
					break;
				default:
			}
			h /= 6;
		}

		return { h, s, v, a };
	}

	toHsvDegreesAndPercent(): HSV | undefined {
		const hsva = this.toHSVA();
		if (!hsva) return undefined;

		return { h: hsva.h * 360, s: hsva.s * 100, v: hsva.v * 100 };
	}

	toHsvaDegreesAndPercent(): HSVA | undefined {
		const hsva = this.toHSVA();
		if (!hsva) return undefined;

		return { h: hsva.h * 360, s: hsva.s * 100, v: hsva.v * 100, a: hsva.a * 100 };
	}

	opaque(): Color | undefined {
		if (this.none) return undefined;

		return new Color(this.red, this.green, this.blue, 1);
	}

	luminance(): number | undefined {
		if (this.none) return undefined;

		// Convert alpha into white
		const r = this.red * this.alpha + (1 - this.alpha);
		const g = this.green * this.alpha + (1 - this.alpha);
		const b = this.blue * this.alpha + (1 - this.alpha);

		// https://stackoverflow.com/a/3943023/775283

		const linearR = r <= 0.04045 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
		const linearG = g <= 0.04045 ? g / 12.92 : ((g + 0.055) / 1.055) ** 2.4;
		const linearB = b <= 0.04045 ? b / 12.92 : ((b + 0.055) / 1.055) ** 2.4;

		return linearR * 0.2126 + linearG * 0.7152 + linearB * 0.0722;
	}

	contrastingColor(): "black" | "white" {
		if (this.none) return "black";

		const luminance = this.luminance();

		return luminance && luminance > Math.sqrt(1.05 * 0.05) - 0.05 ? "black" : "white";
	}
}

export class UpdateActiveDocument extends JsMessage {
	readonly documentId!: bigint;
}

export class DisplayDialogPanic extends JsMessage {
	readonly panicInfo!: string;
}

export class DisplayDialog extends JsMessage {
	readonly title!: string;
	readonly icon!: IconName;
}

export class UpdateDocumentArtwork extends JsMessage {
	readonly svg!: string;
}

export class UpdateDocumentScrollbars extends JsMessage {
	@TupleToVec2
	readonly position!: XY;

	@TupleToVec2
	readonly size!: XY;

	@TupleToVec2
	readonly multiplier!: XY;
}

export class UpdateDocumentRulers extends JsMessage {
	@TupleToVec2
	readonly origin!: XY;

	readonly spacing!: number;

	readonly interval!: number;

	readonly visible!: boolean;
}

export class UpdateEyedropperSamplingState extends JsMessage {
	@TupleToVec2
	readonly mousePosition!: XY | undefined;

	readonly primaryColor!: string;

	readonly secondaryColor!: string;

	readonly setColorChoice!: "Primary" | "Secondary" | undefined;
}

const mouseCursorIconCSSNames = {
	Default: "default",
	None: "none",
	ZoomIn: "zoom-in",
	ZoomOut: "zoom-out",
	Grabbing: "grabbing",
	Crosshair: "crosshair",
	Text: "text",
	Move: "move",
	NSResize: "ns-resize",
	EWResize: "ew-resize",
	NESWResize: "nesw-resize",
	NWSEResize: "nwse-resize",
	Rotate: "custom-rotate",
} as const;
export type MouseCursor = keyof typeof mouseCursorIconCSSNames;
export type MouseCursorIcon = (typeof mouseCursorIconCSSNames)[MouseCursor];

export class UpdateGraphViewOverlay extends JsMessage {
	open!: boolean;
}

export class UpdateGraphFadeArtwork extends JsMessage {
	readonly percentage!: number;
}

export class UpdateSpreadsheetState extends JsMessage {
	readonly open!: boolean;

	readonly node!: bigint | undefined;
}

export class UpdateMouseCursor extends JsMessage {
	@Transform(({ value }: { value: MouseCursor }) => mouseCursorIconCSSNames[value] || "alias")
	readonly cursor!: MouseCursorIcon;
}

export class TriggerLoadFirstAutoSaveDocument extends JsMessage {}
export class TriggerLoadRestAutoSaveDocuments extends JsMessage {}

export class TriggerLoadPreferences extends JsMessage {}

export class TriggerFetchAndOpenDocument extends JsMessage {
	readonly name!: string;

	readonly filename!: string;
}

export class TriggerOpenDocument extends JsMessage {}

export class TriggerImport extends JsMessage {}

export class TriggerPaste extends JsMessage {}

export class TriggerDelayedZoomCanvasToFitAll extends JsMessage {}

export class TriggerDownloadImage extends JsMessage {
	readonly svg!: string;

	readonly name!: string;

	readonly mime!: string;

	@TupleToVec2
	readonly size!: XY;
}

export class TriggerDownloadTextFile extends JsMessage {
	readonly document!: string;

	readonly name!: string;
}

export class TriggerSavePreferences extends JsMessage {
	readonly preferences!: Record<string, unknown>;
}

export class TriggerSaveActiveDocument extends JsMessage {
	readonly documentId!: bigint;
}

export class DocumentChanged extends JsMessage {}

export type DataBuffer = {
	pointer: bigint;
	length: bigint;
};

export class UpdateDocumentLayerStructureJs extends JsMessage {
	readonly dataBuffer!: DataBuffer;
}

export class DisplayEditableTextbox extends JsMessage {
	readonly text!: string;

	readonly lineHeightRatio!: number;

	readonly fontSize!: number;

	@Type(() => Color)
	readonly color!: Color;

	readonly url!: string;

	readonly transform!: number[];

	readonly maxWidth!: undefined | number;

	readonly maxHeight!: undefined | number;
}

export class DisplayEditableTextboxTransform extends JsMessage {
	readonly transform!: number[];
}

export class DisplayRemoveEditableTextbox extends JsMessage {}

export class UpdateDocumentLayerDetails extends JsMessage {
	@Type(() => LayerPanelEntry)
	readonly data!: LayerPanelEntry;
}

export class LayerPanelEntry {
	id!: bigint;

	name!: string;

	alias!: string;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;

	inSelectedNetwork!: boolean;

	childrenAllowed!: boolean;

	childrenPresent!: boolean;

	expanded!: boolean;

	@Transform(({ value }: { value: bigint }) => Number(value))
	depth!: number;

	visible!: boolean;

	parentsVisible!: boolean;

	unlocked!: boolean;

	parentsUnlocked!: boolean;

	parentId!: bigint | undefined;

	selected!: boolean;

	ancestorOfSelected!: boolean;

	descendantOfSelected!: boolean;

	clipped!: boolean;

	clippable!: boolean;
}

export class DisplayDialogDismiss extends JsMessage {}

export class Font {
	fontFamily!: string;

	fontStyle!: string;
}

export class TriggerFontLoad extends JsMessage {
	@Type(() => Font)
	font!: Font;
}

export class TriggerVisitLink extends JsMessage {
	url!: string;
}

export class TriggerTextCommit extends JsMessage {}

export class TriggerTextCopy extends JsMessage {
	readonly copyText!: string;
}

export class TriggerAboutGraphiteLocalizedCommitDate extends JsMessage {
	readonly commitDate!: string;
}

// WIDGET PROPS

export abstract class WidgetProps {
	kind!: WidgetPropsNames;
}

export class CheckboxInput extends WidgetProps {
	checked!: boolean;

	disabled!: boolean;

	icon!: IconName;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;

	forLabel!: bigint | undefined;
}

export class ColorInput extends WidgetProps {
	@Transform(({ value }) => {
		if (value instanceof Gradient) return value;
		const gradient = value["Gradient"];
		if (gradient) {
			const stops = gradient.map(([position, color]: [number, color: { red: number; green: number; blue: number; alpha: number }]) => ({
				position,
				color: new Color(color.red, color.green, color.blue, color.alpha),
			}));
			return new Gradient(stops);
		}

		if (value instanceof Color) return value;
		const solid = value["Solid"];
		if (solid) {
			return new Color(solid.red, solid.green, solid.blue, solid.alpha);
		}

		return new Color("none");
	})
	value!: FillChoice;

	disabled!: boolean;

	allowNone!: boolean;

	// allowTransparency!: boolean; // TODO: Implement

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export type FillChoice = Color | Gradient;

export function contrastingOutlineFactor(value: FillChoice, proximityColor: string | [string, string], proximityRange: number): number {
	const pair = Array.isArray(proximityColor) ? [proximityColor[0], proximityColor[1]] : [proximityColor, proximityColor];
	const [range1, range2] = pair.map((color) => Color.fromCSS(window.getComputedStyle(document.body).getPropertyValue(color)) || new Color("none"));

	const contrast = (color: Color): number => {
		const colorLuminance = color.luminance() || 0;
		let rangeLuminance1 = range1.luminance() || 0;
		let rangeLuminance2 = range2.luminance() || 0;
		[rangeLuminance1, rangeLuminance2] = [Math.min(rangeLuminance1, rangeLuminance2), Math.max(rangeLuminance1, rangeLuminance2)];

		const distance = (() => {
			if (colorLuminance < rangeLuminance1) return rangeLuminance1 - colorLuminance;
			if (colorLuminance > rangeLuminance2) return colorLuminance - rangeLuminance2;
			return 0;
		})();

		return (1 - Math.min(distance / proximityRange, 1)) * (1 - (color.toHSV()?.s || 0));
	};

	if (value instanceof Gradient) {
		if (value.stops.length === 0) return 0;

		const first = contrast(value.stops[0].color);
		const last = contrast(value.stops[value.stops.length - 1].color);

		return Math.min(first, last);
	}

	return contrast(value);
}

type MenuEntryCommon = {
	label: string;
	icon?: IconName;
	shortcut?: ActionKeys;
};

// The entry in the expanded menu or a sub-menu as received from the Rust backend
export type MenuBarEntry = MenuEntryCommon & {
	action: Widget;
	children?: MenuBarEntry[][];
	disabled?: boolean;
};

// An entry in the all-encompassing MenuList component which defines all types of menus (which are spawned by widgets like `TextButton` and `DropdownInput`)
export type MenuListEntry = MenuEntryCommon & {
	action?: () => void;
	children?: MenuListEntry[][];

	value: string;
	shortcutRequiresLock?: boolean;
	disabled?: boolean;
	tooltip?: string;
	font?: URL;
};

export class CurveManipulatorGroup {
	anchor!: [number, number];
	handles!: [[number, number], [number, number]];
}

export class Curve {
	manipulatorGroups!: CurveManipulatorGroup[];
	firstHandle!: [number, number];
	lastHandle!: [number, number];
}

export class CurveInput extends WidgetProps {
	value!: Curve;

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class DropdownInput extends WidgetProps {
	entries!: MenuListEntry[][];

	selectedIndex!: number | undefined;

	drawIcon!: boolean;

	interactive!: boolean;

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;

	// Styling

	minWidth!: number;

	maxWidth!: number;
}

export class FontInput extends WidgetProps {
	fontFamily!: string;

	fontStyle!: string;

	isStyle!: boolean;

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class IconButton extends WidgetProps {
	icon!: IconName;

	hoverIcon!: IconName | undefined;

	size!: IconSize;

	disabled!: boolean;

	active!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class IconLabel extends WidgetProps {
	icon!: IconName;

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class ImageButton extends WidgetProps {
	image!: IconName;

	@Transform(({ value }: { value: string }) => value || undefined)
	width!: string | undefined;

	@Transform(({ value }: { value: string }) => value || undefined)
	height!: string | undefined;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export type NumberInputIncrementBehavior = "Add" | "Multiply" | "Callback" | "None";
export type NumberInputMode = "Increment" | "Range";

export class NumberInput extends WidgetProps {
	// Label

	label!: string | undefined;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;

	// Disabled

	disabled!: boolean;

	// Value

	value!: number | undefined;

	min!: number | undefined;

	max!: number | undefined;

	isInteger!: boolean;

	// Number presentation

	displayDecimalPlaces!: number;

	unit!: string;

	unitIsHiddenWhenEditing!: boolean;

	// Mode behavior

	mode!: NumberInputMode;

	incrementBehavior!: NumberInputIncrementBehavior;

	step!: number;

	rangeMin!: number | undefined;

	rangeMax!: number | undefined;

	// Styling

	minWidth!: number;

	maxWidth!: number;
}

export class NodeCatalog extends WidgetProps {
	disabled!: boolean;
}

export class PopoverButton extends WidgetProps {
	style!: PopoverButtonStyle | undefined;

	menuDirection!: MenuDirection | undefined;

	icon!: IconName | undefined;

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;

	// Body
	popoverLayout!: LayoutGroup[];

	popoverMinWidth: number | undefined;
}

export type MenuDirection = "Top" | "Bottom" | "Left" | "Right" | "TopLeft" | "TopRight" | "BottomLeft" | "BottomRight" | "Center";

export type RadioEntryData = {
	value?: string;
	label?: string;
	icon?: IconName;
	tooltip?: string;

	// Callbacks
	action?: () => void;
};
export type RadioEntries = RadioEntryData[];

export class RadioInput extends WidgetProps {
	entries!: RadioEntries;

	disabled!: boolean;

	selectedIndex!: number | undefined;

	minWidth!: number;
}

export type SeparatorDirection = "Horizontal" | "Vertical";
export type SeparatorType = "Related" | "Unrelated" | "Section";

export class Separator extends WidgetProps {
	direction!: SeparatorDirection;

	type!: SeparatorType;
}

export class WorkingColorsInput extends WidgetProps {
	@Type(() => Color)
	primary!: Color;

	@Type(() => Color)
	secondary!: Color;
}

export class TextAreaInput extends WidgetProps {
	value!: string;

	label!: string | undefined;

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class ParameterExposeButton extends WidgetProps {
	exposed!: boolean;

	dataType!: FrontendGraphDataType;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class TextButton extends WidgetProps {
	label!: string;

	icon!: IconName | undefined;

	hoverIcon!: IconName | undefined;

	emphasized!: boolean;

	flush!: boolean;

	minWidth!: number;

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;

	menuListChildren!: MenuListEntry[][];
}

export type TextButtonWidget = {
	tooltip?: string;
	message?: string | object;
	callback?: () => void;
	props: {
		kind: "TextButton";
		label: string;
		icon?: IconName;
		emphasized?: boolean;
		flush?: boolean;
		minWidth?: number;
		disabled?: boolean;
		tooltip?: string;

		// Callbacks
		// `action` is used via `IconButtonWidget.callback`
	};
};

export class BreadcrumbTrailButtons extends WidgetProps {
	labels!: string[];

	disabled!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class TextInput extends WidgetProps {
	value!: string;

	label!: string | undefined;

	disabled!: boolean;

	minWidth!: number;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;
}

export class TextLabel extends WidgetProps {
	// Body
	value!: string;

	// Props
	disabled!: boolean;

	bold!: boolean;

	italic!: boolean;

	centerAlign!: boolean;

	tableAlign!: boolean;

	minWidth!: number;

	multiline!: boolean;

	@Transform(({ value }: { value: string }) => value || undefined)
	tooltip!: string | undefined;

	checkboxId!: bigint | undefined;
}

export type ReferencePoint = "None" | "TopLeft" | "TopCenter" | "TopRight" | "CenterLeft" | "Center" | "CenterRight" | "BottomLeft" | "BottomCenter" | "BottomRight";

export class ReferencePointInput extends WidgetProps {
	value!: ReferencePoint;

	disabled!: boolean;
}

// WIDGET

const widgetSubTypes = [
	{ value: BreadcrumbTrailButtons, name: "BreadcrumbTrailButtons" },
	{ value: CheckboxInput, name: "CheckboxInput" },
	{ value: ColorInput, name: "ColorInput" },
	{ value: CurveInput, name: "CurveInput" },
	{ value: DropdownInput, name: "DropdownInput" },
	{ value: FontInput, name: "FontInput" },
	{ value: IconButton, name: "IconButton" },
	{ value: ImageButton, name: "ImageButton" },
	{ value: IconLabel, name: "IconLabel" },
	{ value: NodeCatalog, name: "NodeCatalog" },
	{ value: NumberInput, name: "NumberInput" },
	{ value: ParameterExposeButton, name: "ParameterExposeButton" },
	{ value: ReferencePointInput, name: "ReferencePointInput" },
	{ value: PopoverButton, name: "PopoverButton" },
	{ value: RadioInput, name: "RadioInput" },
	{ value: Separator, name: "Separator" },
	{ value: WorkingColorsInput, name: "WorkingColorsInput" },
	{ value: TextAreaInput, name: "TextAreaInput" },
	{ value: TextButton, name: "TextButton" },
	{ value: TextInput, name: "TextInput" },
	{ value: TextLabel, name: "TextLabel" },
] as const;

type WidgetSubTypes = (typeof widgetSubTypes)[number];
type WidgetKindMap = { [T in WidgetSubTypes as T["name"]]: InstanceType<T["value"]> };
export type WidgetPropsNames = keyof WidgetKindMap;
export type WidgetPropsSet = WidgetKindMap[WidgetPropsNames];

export function narrowWidgetProps<K extends WidgetPropsNames>(props: WidgetPropsSet, kind: K) {
	if (props.kind === kind) return props as WidgetKindMap[K];
	else return undefined;
}

export class Widget {
	constructor(props: WidgetPropsSet, widgetId: bigint) {
		this.props = props;
		this.widgetId = widgetId;
	}

	@Type(() => WidgetProps, { discriminator: { property: "kind", subTypes: [...widgetSubTypes] }, keepDiscriminatorProperty: true })
	props!: WidgetPropsSet;

	widgetId!: bigint;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hoistWidgetHolder(widgetHolder: any): Widget {
	const kind = Object.keys(widgetHolder.widget)[0];
	const props = widgetHolder.widget[kind];
	props.kind = kind;

	if (kind === "PopoverButton") {
		props.popoverLayout = props.popoverLayout.map(createLayoutGroup);
	}

	const { widgetId } = widgetHolder;

	return plainToClass(Widget, { props, widgetId });
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hoistWidgetHolders(widgetHolders: any[]): Widget[] {
	return widgetHolders.map(hoistWidgetHolder);
}

// WIDGET LAYOUT

export type WidgetLayout = {
	layoutTarget: unknown;
	layout: LayoutGroup[];
};

export class WidgetDiffUpdate extends JsMessage {
	layoutTarget!: unknown;

	// TODO: Replace `any` with correct typing
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	@Transform(({ value }: { value: any }) => createWidgetDiff(value))
	diff!: WidgetDiff[];
}

type UIItem = LayoutGroup[] | LayoutGroup | Widget | Widget[] | MenuBarEntry[] | MenuBarEntry;
type WidgetDiff = { widgetPath: number[]; newValue: UIItem };

export function defaultWidgetLayout(): WidgetLayout {
	return {
		layoutTarget: undefined,
		layout: [],
	};
}

// Updates a widget layout based on a list of updates, giving the new layout by mutating the `layout` argument
export function patchWidgetLayout(layout: /* &mut */ WidgetLayout, updates: WidgetDiffUpdate) {
	layout.layoutTarget = updates.layoutTarget;

	updates.diff.forEach((update) => {
		// Find the object where the diff applies to
		const diffObject = update.widgetPath.reduce((targetLayout, index) => {
			if ("columnWidgets" in targetLayout) return targetLayout.columnWidgets[index];
			if ("rowWidgets" in targetLayout) return targetLayout.rowWidgets[index];
			if ("tableWidgets" in targetLayout) return targetLayout.tableWidgets[index];
			if ("layout" in targetLayout) return targetLayout.layout[index];
			if (targetLayout instanceof Widget) {
				if (targetLayout.props.kind === "PopoverButton" && targetLayout.props instanceof PopoverButton && targetLayout.props.popoverLayout) {
					return targetLayout.props.popoverLayout[index];
				}
				// eslint-disable-next-line no-console
				console.error("Tried to index widget");
				return targetLayout;
			}
			// This is a path traversal so we can assume from the backend that it exists
			// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
			if ("action" in targetLayout) return targetLayout.children![index];
			return targetLayout[index];
		}, layout.layout as UIItem);

		// If this is a list with a length, then set the length to 0 to clear the list
		if ("length" in diffObject) {
			diffObject.length = 0;
		}
		// Remove all of the keys from the old object
		// eslint-disable-next-line @typescript-eslint/no-explicit-any
		Object.keys(diffObject).forEach((key) => delete (diffObject as any)[key]);

		// Assign keys to the new object
		// `Object.assign` works but `diffObject = update.newValue;` doesn't.
		// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
		Object.assign(diffObject, update.newValue);
	});
}

export type LayoutGroup = WidgetSpanRow | WidgetSpanColumn | WidgetTable | WidgetSection;

export type WidgetSpanColumn = { columnWidgets: Widget[] };
export function isWidgetSpanColumn(layoutColumn: LayoutGroup): layoutColumn is WidgetSpanColumn {
	return Boolean((layoutColumn as WidgetSpanColumn)?.columnWidgets);
}

export type WidgetSpanRow = { rowWidgets: Widget[] };
export function isWidgetSpanRow(layoutRow: LayoutGroup): layoutRow is WidgetSpanRow {
	return Boolean((layoutRow as WidgetSpanRow)?.rowWidgets);
}

export type WidgetTable = { tableWidgets: Widget[][] };
export function isWidgetTable(layoutTable: LayoutGroup): layoutTable is WidgetTable {
	return Boolean((layoutTable as WidgetTable)?.tableWidgets);
}

export type WidgetSection = { name: string; description: string; visible: boolean; pinned: boolean; id: bigint; layout: LayoutGroup[] };
export function isWidgetSection(layoutRow: LayoutGroup): layoutRow is WidgetSection {
	return Boolean((layoutRow as WidgetSection)?.layout);
}

// Unpacking rust types to more usable type in the frontend
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createWidgetDiff(diffs: any[]): WidgetDiff[] {
	return diffs.map((diff) => {
		const { widgetPath, newValue } = diff;
		if (newValue.subLayout) {
			return { widgetPath, newValue: newValue.subLayout.map(createLayoutGroup) };
		}
		if (newValue.layoutGroup) {
			return { widgetPath, newValue: createLayoutGroup(newValue.layoutGroup) };
		}
		if (newValue.widget) {
			return { widgetPath, newValue: hoistWidgetHolder(newValue.widget) };
		}
		// This code should be unreachable
		throw new Error("DiffUpdate invalid");
	});
}

// Unpacking a layout group
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createLayoutGroup(layoutGroup: any): LayoutGroup {
	if (layoutGroup.column) {
		const columnWidgets = hoistWidgetHolders(layoutGroup.column.columnWidgets);

		const result: WidgetSpanColumn = { columnWidgets };
		return result;
	}

	if (layoutGroup.row) {
		const result: WidgetSpanRow = { rowWidgets: hoistWidgetHolders(layoutGroup.row.rowWidgets) };
		return result;
	}

	if (layoutGroup.section) {
		const result: WidgetSection = {
			name: layoutGroup.section.name,
			description: layoutGroup.section.description,
			visible: layoutGroup.section.visible,
			pinned: layoutGroup.section.pinned,
			id: layoutGroup.section.id,
			layout: layoutGroup.section.layout.map(createLayoutGroup),
		};
		return result;
	}

	if (layoutGroup.table) {
		const result: WidgetTable = {
			tableWidgets: layoutGroup.table.tableWidgets.map(hoistWidgetHolders),
		};
		return result;
	}

	throw new Error("Layout row type does not exist");
}

// WIDGET LAYOUTS
export class UpdateDialogButtons extends WidgetDiffUpdate {}

export class UpdateDialogColumn1 extends WidgetDiffUpdate {}

export class UpdateDialogColumn2 extends WidgetDiffUpdate {}

export class UpdateDocumentBarLayout extends WidgetDiffUpdate {}

export class UpdateDocumentModeLayout extends WidgetDiffUpdate {}

export class UpdateLayersPanelControlBarLeftLayout extends WidgetDiffUpdate {}

export class UpdateLayersPanelControlBarRightLayout extends WidgetDiffUpdate {}

export class UpdateLayersPanelBottomBarLayout extends WidgetDiffUpdate {}

// Extends JsMessage instead of WidgetDiffUpdate because the menu bar isn't diffed
export class UpdateMenuBarLayout extends JsMessage {
	layoutTarget!: unknown;

	// TODO: Replace `any` with correct typing
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	@Transform(({ value }: { value: any }) => createMenuLayout(value))
	layout!: MenuBarEntry[];
}

export class UpdateNodeGraphControlBarLayout extends WidgetDiffUpdate {}

export class UpdatePropertyPanelSectionsLayout extends WidgetDiffUpdate {}

export class UpdateSpreadsheetLayout extends WidgetDiffUpdate {}

export class UpdateToolOptionsLayout extends WidgetDiffUpdate {}

export class UpdateToolShelfLayout extends WidgetDiffUpdate {}

export class UpdateWorkingColorsLayout extends WidgetDiffUpdate {}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createMenuLayout(menuBarEntry: any[]): MenuBarEntry[] {
	return menuBarEntry.map((entry) => ({
		...entry,
		children: createMenuLayoutRecursive(entry.children),
	}));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createMenuLayoutRecursive(children: any[][]): MenuBarEntry[][] {
	return children.map((groups) =>
		groups.map((entry) => ({
			...entry,
			action: hoistWidgetHolders([entry.action])[0],
			children: entry.children ? createMenuLayoutRecursive(entry.children) : undefined,
			disabled: entry.disabled ?? false,
		})),
	);
}

// `any` is used since the type of the object should be known from the Rust side
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type JSMessageFactory = (data: any, wasm: WebAssembly.Memory, handle: EditorHandle) => JsMessage;
type MessageMaker = typeof JsMessage | JSMessageFactory;

export const messageMakers: Record<string, MessageMaker> = {
	ClearAllNodeGraphWires,
	DisplayDialog,
	DisplayDialogDismiss,
	DisplayDialogPanic,
	DisplayEditableTextbox,
	DisplayEditableTextboxTransform,
	DisplayRemoveEditableTextbox,
	SendUIMetadata,
	TriggerAboutGraphiteLocalizedCommitDate,
	TriggerDelayedZoomCanvasToFitAll,
	TriggerDownloadImage,
	TriggerDownloadTextFile,
	TriggerFetchAndOpenDocument,
	TriggerFontLoad,
	TriggerImport,
	TriggerIndexedDbRemoveDocument,
	TriggerIndexedDbWriteDocument,
	TriggerLoadFirstAutoSaveDocument,
	TriggerLoadPreferences,
	TriggerLoadRestAutoSaveDocuments,
	TriggerOpenDocument,
	TriggerPaste,
	TriggerSaveActiveDocument,
	TriggerSavePreferences,
	TriggerTextCommit,
	TriggerTextCopy,
	TriggerVisitLink,
	UpdateActiveDocument,
	UpdateBox,
	UpdateClickTargets,
	UpdateContextMenuInformation,
	UpdateDialogButtons,
	UpdateDialogColumn1,
	UpdateDialogColumn2,
	UpdateDocumentArtwork,
	UpdateDocumentBarLayout,
	UpdateDocumentLayerDetails,
	UpdateDocumentLayerStructureJs,
	UpdateDocumentModeLayout,
	UpdateDocumentRulers,
	UpdateDocumentScrollbars,
	UpdateExportReorderIndex,
	UpdateEyedropperSamplingState,
	UpdateGraphFadeArtwork,
	UpdateGraphViewOverlay,
	UpdateSpreadsheetState,
	UpdateImportReorderIndex,
	UpdateImportsExports,
	UpdateInputHints,
	UpdateInSelectedNetwork,
	UpdateLayersPanelControlBarLeftLayout,
	UpdateLayersPanelControlBarRightLayout,
	UpdateLayersPanelBottomBarLayout,
	UpdateLayerWidths,
	UpdateMenuBarLayout,
	UpdateMouseCursor,
	UpdateNodeGraphNodes,
	UpdateVisibleNodes,
	UpdateNodeGraphWires,
	UpdateNodeGraphTransform,
	UpdateNodeGraphControlBarLayout,
	UpdateNodeGraphSelection,
	UpdateNodeThumbnail,
	UpdateOpenDocumentsList,
	UpdatePropertyPanelSectionsLayout,
	UpdateSpreadsheetLayout,
	UpdateToolOptionsLayout,
	UpdateToolShelfLayout,
	UpdateWirePathInProgress,
	UpdateWorkingColorsLayout,
} as const;
export type JsMessageType = keyof typeof messageMakers;