-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathLayers.svelte
More file actions
975 lines (828 loc) · 31.1 KB
/
Layers.svelte
File metadata and controls
975 lines (828 loc) · 31.1 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
<script lang="ts">
import { getContext, onMount, onDestroy, tick } from "svelte";
import type { Editor } from "@graphite/editor";
import {
patchLayout,
UpdateDocumentLayerDetails,
UpdateDocumentLayerStructureJs,
UpdateLayersPanelControlBarLeftLayout,
UpdateLayersPanelControlBarRightLayout,
UpdateLayersPanelBottomBarLayout,
} from "@graphite/messages";
import type { DataBuffer, LayerPanelEntry, Layout } from "@graphite/messages";
import type { NodeGraphState } from "@graphite/state-providers/node-graph";
import type { TooltipState } from "@graphite/state-providers/tooltip";
import { operatingSystem } from "@graphite/utility-functions/platform";
import { extractPixelData } from "@graphite/utility-functions/rasterization";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import Separator from "@graphite/components/widgets/labels/Separator.svelte";
import WidgetLayout from "@graphite/components/widgets/WidgetLayout.svelte";
type LayerListingInfo = {
folderIndex: number;
bottomLayer: boolean;
editingName: boolean;
entry: LayerPanelEntry;
};
type DraggingData = {
select?: () => void;
insertParentId: bigint | undefined;
insertDepth: number;
insertIndex: number | undefined;
highlightFolder: boolean;
markerHeight: number;
};
type InternalDragState = {
active: boolean;
layerId: bigint;
listing: LayerListingInfo;
startX: number;
startY: number;
};
const editor = getContext<Editor>("editor");
const nodeGraph = getContext<NodeGraphState>("nodeGraph");
const tooltip = getContext<TooltipState>("tooltip");
let list: LayoutCol | undefined;
// Layer data
let layerCache = new Map<string, LayerPanelEntry>(); // TODO: replace with BigUint64Array as index
let layers: LayerListingInfo[] = [];
// Interactive dragging
let draggable = true;
let draggingData: undefined | DraggingData = undefined;
let internalDragState: InternalDragState | undefined = undefined;
let fakeHighlightOfNotYetSelectedLayerBeingDragged: undefined | bigint = undefined;
let justFinishedDrag = false; // Used to prevent click events after a drag
let dragInPanel = false;
// Interactive clipping
let layerToClipUponClick: LayerListingInfo | undefined = undefined;
let layerToClipAltKeyPressed = false;
// Layouts
let layersPanelControlBarLeftLayout: Layout = [];
let layersPanelControlBarRightLayout: Layout = [];
let layersPanelBottomBarLayout: Layout = [];
onMount(() => {
editor.subscriptions.subscribeJsMessage(UpdateLayersPanelControlBarLeftLayout, (data) => {
patchLayout(layersPanelControlBarLeftLayout, data);
layersPanelControlBarLeftLayout = layersPanelControlBarLeftLayout;
});
editor.subscriptions.subscribeJsMessage(UpdateLayersPanelControlBarRightLayout, (data) => {
patchLayout(layersPanelControlBarRightLayout, data);
layersPanelControlBarRightLayout = layersPanelControlBarRightLayout;
});
editor.subscriptions.subscribeJsMessage(UpdateLayersPanelBottomBarLayout, (data) => {
patchLayout(layersPanelBottomBarLayout, data);
layersPanelBottomBarLayout = layersPanelBottomBarLayout;
});
editor.subscriptions.subscribeJsMessage(UpdateDocumentLayerStructureJs, (data) => {
const structure = newUpdateDocumentLayerStructure(data.dataBuffer);
rebuildLayerHierarchy(structure);
});
editor.subscriptions.subscribeJsMessage(UpdateDocumentLayerDetails, (data) => {
const targetLayer = data.data;
const targetId = targetLayer.id;
updateLayerInTree(targetId, targetLayer);
});
addEventListener("pointerup", draggingPointerUp);
addEventListener("pointermove", draggingPointerMove);
addEventListener("mousedown", draggingMouseDown);
addEventListener("keydown", draggingKeyDown);
addEventListener("keydown", handleLayerPanelKeyDown);
addEventListener("pointermove", clippingHover);
addEventListener("keydown", clippingKeyPress);
addEventListener("keyup", clippingKeyPress);
});
onDestroy(() => {
editor.subscriptions.unsubscribeJsMessage(UpdateLayersPanelControlBarLeftLayout);
editor.subscriptions.unsubscribeJsMessage(UpdateLayersPanelControlBarRightLayout);
editor.subscriptions.unsubscribeJsMessage(UpdateLayersPanelBottomBarLayout);
editor.subscriptions.unsubscribeJsMessage(UpdateDocumentLayerStructureJs);
editor.subscriptions.unsubscribeJsMessage(UpdateDocumentLayerDetails);
removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointermove", draggingPointerMove);
removeEventListener("mousedown", draggingMouseDown);
removeEventListener("keydown", draggingKeyDown);
removeEventListener("keydown", handleLayerPanelKeyDown);
removeEventListener("pointermove", clippingHover);
removeEventListener("keydown", clippingKeyPress);
removeEventListener("keyup", clippingKeyPress);
});
type DocumentLayerStructure = {
layerId: bigint;
children: DocumentLayerStructure[];
};
function newUpdateDocumentLayerStructure(dataBuffer: DataBuffer): DocumentLayerStructure {
const pointerNum = Number(dataBuffer.pointer);
const lengthNum = Number(dataBuffer.length);
const wasmMemoryBuffer = editor.raw.buffer;
// Decode the folder structure encoding
const encoding = new DataView(wasmMemoryBuffer, pointerNum, lengthNum);
// The structure section indicates how to read through the upcoming layer list and assign depths to each layer
const structureSectionLength = Number(encoding.getBigUint64(0, true));
const structureSectionMsbSigned = new DataView(wasmMemoryBuffer, pointerNum + 8, structureSectionLength * 8);
// The layer IDs section lists each layer ID sequentially in the tree, as it will show up in the panel
const layerIdsSection = new DataView(wasmMemoryBuffer, pointerNum + 8 + structureSectionLength * 8);
let layersEncountered = 0;
let currentFolder: DocumentLayerStructure = { layerId: BigInt(-1), children: [] };
const currentFolderStack = [currentFolder];
for (let i = 0; i < structureSectionLength; i += 1) {
const msbSigned = structureSectionMsbSigned.getBigUint64(i * 8, true);
const msbMask = BigInt(1) << BigInt(64 - 1);
// Set the MSB to 0 to clear the sign and then read the number as usual
const numberOfLayersAtThisDepth = msbSigned & ~msbMask;
// Store child folders in the current folder (until we are interrupted by an indent)
for (let j = 0; j < numberOfLayersAtThisDepth; j += 1) {
const layerId = layerIdsSection.getBigUint64(layersEncountered * 8, true);
layersEncountered += 1;
const childLayer: DocumentLayerStructure = { layerId, children: [] };
currentFolder.children.push(childLayer);
}
// Check the sign of the MSB, where a 1 is a negative (outward) indent
const subsequentDirectionOfDepthChange = (msbSigned & msbMask) === BigInt(0);
// Inward
if (subsequentDirectionOfDepthChange) {
currentFolderStack.push(currentFolder);
currentFolder = currentFolder.children[currentFolder.children.length - 1];
}
// Outward
else {
const popped = currentFolderStack.pop();
if (!popped) throw Error("Too many negative indents in the folder structure");
if (popped) currentFolder = popped;
}
}
return currentFolder;
}
function toggleNodeVisibilityLayerPanel(id: bigint) {
editor.handle.toggleNodeVisibilityLayerPanel(id);
}
function toggleLayerLock(id: bigint) {
editor.handle.toggleLayerLock(id);
}
function handleExpandArrowClickWithModifiers(e: MouseEvent, id: bigint) {
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
const collapseRecursive = e.altKey || accel;
editor.handle.toggleLayerExpansion(id, collapseRecursive);
e.stopPropagation();
}
async function onEditLayerName(listing: LayerListingInfo) {
if (listing.editingName) return;
draggable = false;
listing.editingName = true;
layers = layers;
await tick();
const query = list?.div?.()?.querySelector("[data-text-input]:not([disabled])");
const textInput = (query instanceof HTMLInputElement && query) || undefined;
textInput?.select();
}
function onEditLayerNameChange(listing: LayerListingInfo, e: Event) {
// Eliminate duplicate events
if (!listing.editingName) return;
draggable = true;
listing.editingName = false;
layers = layers;
const name = (e.target instanceof HTMLInputElement && e.target.value) || "";
editor.handle.setLayerName(listing.entry.id, name);
listing.entry.alias = name;
}
async function onEditLayerNameDeselect(listing: LayerListingInfo) {
draggable = true;
listing.editingName = false;
layers = layers;
// Set it back to the original name if the user didn't enter a new name
if (document.activeElement instanceof HTMLInputElement) document.activeElement.value = listing.entry.alias;
// Deselect the text so it doesn't appear selected while the input field becomes disabled and styled to look like regular text
window.getSelection()?.removeAllRanges();
}
function selectLayerWithModifiers(e: MouseEvent, listing: LayerListingInfo) {
if (justFinishedDrag) {
justFinishedDrag = false;
// Prevent bubbling to deselectAllLayers
e.stopPropagation();
return;
}
// Get the pressed state of the modifier keys
const [ctrl, meta, shift, alt] = [e.ctrlKey, e.metaKey, e.shiftKey, e.altKey];
// Get the state of the platform's accel key and its opposite platform's accel key
const [accel, oppositeAccel] = operatingSystem() === "Mac" ? [meta, ctrl] : [ctrl, meta];
// Alt-clicking to make a clipping mask
if (layerToClipAltKeyPressed && layerToClipUponClick && layerToClipUponClick.entry.clippable) clipLayer(layerToClipUponClick);
// Select the layer only if the accel and/or shift keys are pressed
else if (!oppositeAccel && !alt) selectLayer(listing, accel, shift);
e.stopPropagation();
}
function clipLayer(listing: LayerListingInfo) {
editor.handle.clipLayer(listing.entry.id);
}
function clippingKeyPress(e: KeyboardEvent) {
layerToClipAltKeyPressed = e.altKey;
}
function clippingHover(e: PointerEvent) {
// Don't do anything if the user is dragging to rearrange layers
if (dragInPanel) return;
// Get the layer below the cursor
const target = (e.target instanceof HTMLElement && e.target.closest("[data-layer]")) || undefined;
if (!target) {
layerToClipUponClick = undefined;
return;
}
// Check if the cursor is near the border between two layers
const DISTANCE = 6;
const distanceFromTop = e.clientY - target.getBoundingClientRect().top;
const distanceFromBottom = target.getBoundingClientRect().bottom - e.clientY;
const nearTop = distanceFromTop < DISTANCE;
const nearBottom = distanceFromBottom < DISTANCE;
// If we are not near the border, we don't want to clip
if (!nearTop && !nearBottom) {
layerToClipUponClick = undefined;
return;
}
// If we are near the border, we want to clip the layer above the border
const indexAttribute = target?.getAttribute("data-index") ?? undefined;
const index = indexAttribute ? Number(indexAttribute) : undefined;
const layer = index !== undefined && layers[nearTop ? index - 1 : index];
if (!layer) return;
// Update the state used to show the clipping action
layerToClipUponClick = layer;
layerToClipAltKeyPressed = e.altKey;
}
function selectLayer(listing: LayerListingInfo, accel: boolean, shift: boolean) {
// Don't select while we are entering text to rename the layer
if (listing.editingName) return;
editor.handle.selectLayer(listing.entry.id, accel, shift);
}
async function deselectAllLayers() {
if (justFinishedDrag) {
justFinishedDrag = false;
return;
}
editor.handle.deselectAllLayers();
}
function calculateDragIndex(tree: LayoutCol, clientY: number, select?: () => void): DraggingData {
const treeChildren = tree.div()?.children;
const treeOffset = tree.div()?.getBoundingClientRect().top;
// Folder to insert into
let insertParentId: bigint | undefined = undefined;
let insertDepth = 0;
// Insert index (starts at the end, essentially infinity)
let insertIndex = undefined;
// Whether you are inserting into a folder and should show the folder outline
let highlightFolder = false;
let markerHeight = 0;
const layerPanel = document.querySelector("[data-layer-panel]"); // Selects the element with the data-layer-panel attribute
if (layerPanel !== null && treeChildren !== undefined && treeOffset !== undefined) {
let layerPanelTop = layerPanel.getBoundingClientRect().top;
Array.from(treeChildren).forEach((treeChild) => {
const indexAttribute = treeChild.getAttribute("data-index");
if (!indexAttribute) return;
const { folderIndex, entry: layer } = layers[parseInt(indexAttribute, 10)];
const rect = treeChild.getBoundingClientRect();
if (rect.top > clientY || rect.bottom < clientY) {
return;
}
const pointerPercentage = (clientY - rect.top) / rect.height;
if (layer.childrenAllowed) {
if (pointerPercentage < 0.25) {
insertParentId = layer.parentId;
insertDepth = layer.depth - 1;
insertIndex = folderIndex;
markerHeight = rect.top - layerPanelTop;
} else if (pointerPercentage < 0.75 || (layer.childrenPresent && layer.expanded)) {
insertParentId = layer.id;
insertDepth = layer.depth;
insertIndex = 0;
highlightFolder = true;
} else {
insertParentId = layer.parentId;
insertDepth = layer.depth - 1;
insertIndex = folderIndex + 1;
markerHeight = rect.bottom - layerPanelTop;
}
} else {
if (pointerPercentage < 0.5) {
insertParentId = layer.parentId;
insertDepth = layer.depth - 1;
insertIndex = folderIndex;
markerHeight = rect.top - layerPanelTop;
} else {
insertParentId = layer.parentId;
insertDepth = layer.depth - 1;
insertIndex = folderIndex + 1;
markerHeight = rect.bottom - layerPanelTop;
}
}
});
// Dragging to the empty space below all layers
let lastLayer = treeChildren[treeChildren.length - 1];
if (lastLayer.getBoundingClientRect().bottom < clientY) {
const numberRootLayers = layers.filter((layer) => layer.entry.depth === 1).length;
insertParentId = undefined;
insertDepth = 0;
insertIndex = numberRootLayers;
markerHeight = lastLayer.getBoundingClientRect().bottom - layerPanelTop;
}
}
return {
select,
insertParentId,
insertDepth,
insertIndex,
highlightFolder,
markerHeight,
};
}
function layerPointerDown(e: PointerEvent, listing: LayerListingInfo) {
// Only left click drags
if (e.button !== 0 || !draggable) return;
internalDragState = {
active: false,
layerId: listing.entry.id,
listing: listing,
startX: e.clientX,
startY: e.clientY,
};
}
function draggingPointerMove(e: PointerEvent) {
if (!internalDragState || !list) return;
// Calculate distance moved
if (!internalDragState.active) {
const distance = Math.hypot(e.clientX - internalDragState.startX, e.clientY - internalDragState.startY);
const DRAG_THRESHOLD = 5;
if (distance > DRAG_THRESHOLD) {
internalDragState.active = true;
dragInPanel = true;
const layer = internalDragState.listing.entry;
if (!$nodeGraph.selected.includes(layer.id)) {
fakeHighlightOfNotYetSelectedLayerBeingDragged = layer.id;
}
}
}
// Perform drag calculations if a drag is occurring
if (internalDragState.active) {
const select = () => {
if (internalDragState && !$nodeGraph.selected.includes(internalDragState.layerId)) {
selectLayer(internalDragState.listing, false, false);
}
};
draggingData = calculateDragIndex(list, e.clientY, select);
}
}
function draggingPointerUp() {
if (internalDragState?.active && draggingData) {
const { select, insertParentId, insertIndex } = draggingData;
// Commit the move
select?.();
editor.handle.moveLayerInTree(insertParentId, insertIndex);
// Prevent the subsequent click event from processing
justFinishedDrag = true;
} else if (justFinishedDrag) {
// Avoid right-click abort getting stuck with `justFinishedDrag` set and blocking the first subsequent click to select a layer
setTimeout(() => {
justFinishedDrag = false;
}, 0);
}
// Reset state
abortDrag();
}
function abortDrag() {
internalDragState = undefined;
draggingData = undefined;
fakeHighlightOfNotYetSelectedLayerBeingDragged = undefined;
dragInPanel = false;
}
function draggingMouseDown(e: MouseEvent) {
// Abort if a drag is active and the user presses the right mouse button (button 2)
if (e.button === 2 && internalDragState?.active) {
justFinishedDrag = true;
abortDrag();
}
}
function draggingKeyDown(e: KeyboardEvent) {
if (e.key === "Escape" && internalDragState?.active) {
justFinishedDrag = true;
abortDrag();
}
}
function handleLayerPanelKeyDown(e: KeyboardEvent) {
// Only handle F2 if not currently editing a layer name
if (e.key === "F2" && !layers.some((layer) => layer.editingName)) {
// Find the first selected layer
const selectedLayer = layers.find((layer) => layer.entry.selected);
if (selectedLayer) {
e.preventDefault();
onEditLayerName(selectedLayer);
}
}
}
async function navigateToLayer(currentListing: LayerListingInfo, direction: "Up" | "Down") {
// Save the current layer name
const inputElement = document.activeElement;
if (inputElement instanceof HTMLInputElement) {
const name = inputElement.value || "";
editor.handle.setLayerName(currentListing.entry.id, name);
currentListing.entry.alias = name;
}
// Find current layer index
const currentIndex = layers.findIndex((layer) => layer.entry.id === currentListing.entry.id);
if (currentIndex === -1) return;
// Calculate target index based on direction
const targetIndex = direction === "Down" ? currentIndex + 1 : currentIndex - 1;
if (targetIndex >= layers.length || targetIndex < 0) return;
const targetListing = layers[targetIndex];
if (!targetListing) return;
// Exit edit mode on current layer
currentListing.editingName = false;
draggable = true;
layers = layers;
// Start edit mode on target layer
await onEditLayerName(targetListing);
}
function fileDragOver(e: DragEvent) {
if (!draggable || !e.dataTransfer || !e.dataTransfer.types.includes("Files")) return;
// Stop the drag from being shown as cancelled
e.preventDefault();
dragInPanel = true;
if (list) draggingData = calculateDragIndex(list, e.clientY);
}
function fileDrop(e: DragEvent) {
if (!draggingData || !e.dataTransfer || !e.dataTransfer.types.includes("Files")) return;
const { insertParentId, insertIndex } = draggingData;
e.preventDefault();
Array.from(e.dataTransfer.items).forEach(async (item) => {
const file = item.getAsFile();
if (!file) return;
if (file.type.includes("svg")) {
const svgData = await file.text();
editor.handle.pasteSvg(file.name, svgData, undefined, undefined, insertParentId, insertIndex);
return;
}
if (file.type.startsWith("image")) {
const imageData = await extractPixelData(file);
editor.handle.pasteImage(file.name, new Uint8Array(imageData.data), imageData.width, imageData.height, undefined, undefined, insertParentId, insertIndex);
return;
}
// When we eventually have sub-documents, this should be changed to import the document instead of opening it in a separate tab
const graphiteFileSuffix = "." + editor.handle.fileExtension();
if (file.name.endsWith(graphiteFileSuffix)) {
const content = await file.text();
const documentName = file.name.slice(0, -graphiteFileSuffix.length);
editor.handle.openDocumentFile(documentName, content);
return;
}
});
draggingData = undefined;
fakeHighlightOfNotYetSelectedLayerBeingDragged = undefined;
dragInPanel = false;
}
function rebuildLayerHierarchy(updateDocumentLayerStructure: DocumentLayerStructure) {
const layerWithNameBeingEdited = layers.find((layer: LayerListingInfo) => layer.editingName);
const layerIdWithNameBeingEdited = layerWithNameBeingEdited?.entry.id;
// Clear the layer hierarchy before rebuilding it
layers = [];
// Build the new layer hierarchy
const recurse = (folder: DocumentLayerStructure) => {
folder.children.forEach((item, index) => {
const mapping = layerCache.get(String(item.layerId));
if (mapping) {
mapping.id = item.layerId;
layers.push({
folderIndex: index,
bottomLayer: index === folder.children.length - 1,
entry: mapping,
editingName: layerIdWithNameBeingEdited === item.layerId,
});
}
// Call self recursively if there are any children
if (item.children.length >= 1) recurse(item);
});
};
recurse(updateDocumentLayerStructure);
layers = layers;
}
function updateLayerInTree(targetId: bigint, targetLayer: LayerPanelEntry) {
layerCache.set(String(targetId), targetLayer);
const layer = layers.find((layer: LayerListingInfo) => layer.entry.id === targetId);
if (layer) {
layer.entry = targetLayer;
layers = layers;
}
}
</script>
<LayoutCol class="layers" on:dragleave={() => (dragInPanel = false)}>
<LayoutRow class="control-bar" scrollableX={true}>
<WidgetLayout layout={layersPanelControlBarLeftLayout} layoutTarget="LayersPanelControlLeftBar" />
{#if layersPanelControlBarLeftLayout?.length > 0 && layersPanelControlBarRightLayout?.length > 0}
<Separator />
{/if}
<WidgetLayout layout={layersPanelControlBarRightLayout} layoutTarget="LayersPanelControlRightBar" />
</LayoutRow>
<LayoutRow class="list-area" classes={{ "drag-ongoing": Boolean(internalDragState?.active && draggingData) }} scrollableY={true}>
<LayoutCol
class="list"
styles={{ cursor: layerToClipUponClick && layerToClipAltKeyPressed && layerToClipUponClick.entry.clippable ? "alias" : "auto" }}
data-layer-panel
bind:this={list}
on:click={() => deselectAllLayers()}
on:dragover={fileDragOver}
on:drop={fileDrop}
>
{#each layers as listing, index}
{@const selected = fakeHighlightOfNotYetSelectedLayerBeingDragged !== undefined ? fakeHighlightOfNotYetSelectedLayerBeingDragged === listing.entry.id : listing.entry.selected}
<LayoutRow
class="layer"
classes={{
selected,
"ancestor-of-selected": listing.entry.ancestorOfSelected,
"descendant-of-selected": listing.entry.descendantOfSelected,
"selected-but-not-in-selected-network": selected && !listing.entry.inSelectedNetwork,
"insert-folder": (draggingData?.highlightFolder || false) && draggingData?.insertParentId === listing.entry.id,
}}
styles={{ "--layer-indent-levels": `${listing.entry.depth - 1}` }}
data-layer
data-index={index}
on:pointerdown={(e) => layerPointerDown(e, listing)}
on:click={(e) => selectLayerWithModifiers(e, listing)}
>
{#if listing.entry.childrenAllowed}
<button
class="expand-arrow"
class:expanded={listing.entry.expanded}
disabled={!listing.entry.childrenPresent}
data-tooltip-label={listing.entry.expanded ? "Collapse (All)" : "Expand (All)"}
data-tooltip-description={(listing.entry.expanded
? "Hide the layers nested within. (To affect all open descendants, perform the shortcut shown.)"
: "Show the layers nested within. (To affect all closed descendants, perform the shortcut shown.)") +
(listing.entry.ancestorOfSelected && !listing.entry.expanded ? "\n\nA selected layer is currently contained within.\n" : "")}
data-tooltip-shortcut={$tooltip.altClickShortcut?.shortcut ? JSON.stringify($tooltip.altClickShortcut.shortcut) : undefined}
on:click={(e) => handleExpandArrowClickWithModifiers(e, listing.entry.id)}
tabindex="0"
></button>
{:else}
<div class="expand-arrow-none"></div>
{/if}
{#if listing.entry.clipped}
<IconLabel
icon="Clipped"
class="clipped-arrow"
tooltipLabel="Layer Clipped"
tooltipDescription="Clipping mask is active. To release it, target the bottom border of the layer and perform the shortcut shown."
tooltipShortcut={$tooltip.altClickShortcut}
/>
{/if}
<div class="thumbnail">
{#if $nodeGraph.thumbnails.has(listing.entry.id)}
{@html $nodeGraph.thumbnails.get(listing.entry.id)}
{/if}
</div>
{#if listing.entry.reference.type === "Network" && listing.entry.reference.data === "Artboard"}
<IconLabel icon="Artboard" class="layer-type-icon" tooltipLabel="Artboard" />
{/if}
<LayoutRow class="layer-name" on:dblclick={() => onEditLayerName(listing)}>
<input
data-text-input
type="text"
value={listing.entry.alias}
placeholder={listing.entry.reference.data}
disabled={!listing.editingName}
on:blur={() => onEditLayerNameDeselect(listing)}
on:keydown={(e) => {
if (e.key === "Escape") {
onEditLayerNameDeselect(listing);
} else if (e.key === "Enter") {
onEditLayerNameChange(listing, e);
} else if (e.key === "Tab") {
e.preventDefault();
navigateToLayer(listing, e.shiftKey ? "Up" : "Down");
} else if (e.key === "ArrowUp") {
e.preventDefault();
navigateToLayer(listing, "Up");
} else if (e.key === "ArrowDown") {
e.preventDefault();
navigateToLayer(listing, "Down");
}
}}
on:change={(e) => onEditLayerNameChange(listing, e)}
/>
</LayoutRow>
{#if !listing.entry.unlocked || !listing.entry.parentsUnlocked}
<IconButton
class="status-toggle"
classes={{ inherited: !listing.entry.parentsUnlocked }}
action={(e) => (toggleLayerLock(listing.entry.id), e?.stopPropagation())}
size={24}
icon={listing.entry.unlocked ? "PadlockUnlocked" : "PadlockLocked"}
hoverIcon={listing.entry.unlocked ? "PadlockLocked" : "PadlockUnlocked"}
tooltipLabel={listing.entry.unlocked ? "Lock" : "Unlock"}
tooltipDescription={!listing.entry.parentsUnlocked ? "A parent of this layer is locked and that status is being inherited." : ""}
/>
{/if}
<IconButton
class="status-toggle"
classes={{ inherited: !listing.entry.parentsVisible }}
action={(e) => (toggleNodeVisibilityLayerPanel(listing.entry.id), e?.stopPropagation())}
size={24}
icon={listing.entry.visible ? "EyeVisible" : "EyeHidden"}
hoverIcon={listing.entry.visible ? "EyeHide" : "EyeShow"}
tooltipLabel={listing.entry.visible ? "Hide" : "Show"}
tooltipDescription={!listing.entry.parentsVisible ? "A parent of this layer is hidden and that status is being inherited." : ""}
/>
</LayoutRow>
{/each}
</LayoutCol>
{#if draggingData && !draggingData.highlightFolder && dragInPanel}
<div class="insert-mark" style:left={`${4 + draggingData.insertDepth * 16}px`} style:top={`${draggingData.markerHeight}px`} />
{/if}
</LayoutRow>
<LayoutRow class="bottom-bar" scrollableX={true}>
<WidgetLayout layout={layersPanelBottomBarLayout} layoutTarget="LayersPanelBottomBar" />
</LayoutRow>
</LayoutCol>
<style lang="scss" global>
.layers {
// Control bar
.control-bar {
height: 32px;
flex: 0 0 auto;
margin: 0 4px;
border-bottom: 1px solid var(--color-2-mildblack);
justify-content: space-between;
.widget-span:first-child {
flex: 1 1 auto;
}
&:not(:has(*)) {
display: none;
}
}
// Bottom bar
.bottom-bar {
height: 24px;
padding-top: 4px;
flex: 0 0 auto;
margin: 0 4px;
justify-content: flex-end;
border-top: 1px solid var(--color-2-mildblack);
.widget-span > * {
margin: 0;
}
&:not(:has(*)) {
display: none;
}
}
// Layer hierarchy
.list-area {
position: relative;
padding-top: 4px;
// Combine with the bottom bar to avoid a double border
margin-bottom: -1px;
&.drag-ongoing .layer {
pointer-events: none;
}
.layer {
flex: 0 0 auto;
align-items: center;
position: relative;
border-bottom: 1px solid var(--color-2-mildblack);
border-radius: 2px;
height: 32px;
margin: 0 4px;
padding-left: calc(var(--layer-indent-levels) * 16px);
// Dimming
&.selected {
background: var(--color-4-dimgray);
}
&.ancestor-of-selected .expand-arrow:not(.expanded) {
background-image: var(--inheritance-dots-background-6-lowergray);
}
&.descendant-of-selected {
background-image: var(--inheritance-dots-background-4-dimgray);
}
&.selected-but-not-in-selected-network {
background: rgba(var(--color-4-dimgray-rgb), 0.5);
}
&.insert-folder {
outline: 3px solid var(--color-e-nearwhite);
outline-offset: -3px;
}
.expand-arrow {
padding: 0;
margin: 0;
margin-right: 4px;
width: 16px;
height: 100%;
border: none;
position: relative;
background: none;
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: center;
border-radius: 2px;
&::after {
content: "";
position: absolute;
width: 8px;
height: 8px;
background: var(--icon-expand-collapse-arrow);
}
&[disabled]::after {
background: var(--icon-expand-collapse-arrow-disabled);
}
&:hover:not([disabled]) {
background: var(--color-5-dullgray);
&::after {
background: var(--icon-expand-collapse-arrow-hover);
}
}
&.expanded::after {
transform: rotate(90deg);
}
}
.expand-arrow-none {
flex: 0 0 16px;
margin-right: 4px;
}
.clipped-arrow {
margin-left: 2px;
margin-right: 2px;
}
.thumbnail {
width: 36px;
height: 24px;
border-radius: 2px;
overflow: hidden;
flex: 0 0 auto;
background-image: var(--color-transparent-checkered-background);
background-size: var(--color-transparent-checkered-background-size-mini);
background-position: var(--color-transparent-checkered-background-position-mini);
background-repeat: var(--color-transparent-checkered-background-repeat);
svg {
width: 100%;
height: 100%;
}
}
.layer-type-icon {
margin-left: 8px;
margin-right: -4px;
}
.layer-name {
flex: 1 1 100%;
margin: 0 8px;
input {
color: inherit;
background: none;
border: none;
outline: none; // Ok for input element
margin: 0;
padding: 0;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
border-radius: 2px;
height: 24px;
width: 100%;
&:disabled {
-webkit-user-select: none; // Still required by Safari as of 2025
user-select: none;
// Workaround for `user-select: none` not working on <input> elements
pointer-events: none;
}
&:focus {
background: var(--color-1-nearblack);
padding: 0 4px;
&::placeholder {
opacity: 0.5;
}
}
&::placeholder {
opacity: 1;
color: inherit;
}
}
}
.status-toggle {
flex: 0 0 auto;
align-items: center;
height: 100%;
&.inherited {
background-image: var(--inheritance-stripes-background);
}
.icon-button {
height: 100%;
width: calc(24px + 2 * 4px);
}
}
}
.insert-mark {
position: absolute;
left: 4px;
right: 4px;
background: var(--color-e-nearwhite);
margin-top: 1px;
height: 5px;
z-index: 1;
pointer-events: none;
}
}
}
</style>