forked from jlongster/tigma
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
2620 lines (2264 loc) · 82.3 KB
/
index.ts
File metadata and controls
2620 lines (2264 loc) · 82.3 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 {
createCliRenderer,
RGBA,
type CliRenderer,
type KeyEvent,
type MouseEvent,
type OptimizedBuffer,
TextAttributes,
BoxRenderable,
} from "@opentui/core"
import * as fs from "fs"
import * as path from "path"
// Color can be null for transparent
type EntityColor = RGBA | null
interface TextChar {
char: string
bold: boolean
color: EntityColor // text color (stroke)
}
interface TextBox {
id: number
x: number
y: number
chars: TextChar[]
zIndex: number
strokeColor: EntityColor
fillColor: EntityColor
}
interface Rectangle {
id: number
x1: number
y1: number
x2: number
y2: number
bold: boolean
zIndex: number
strokeColor: EntityColor
fillColor: EntityColor
}
interface Line {
id: number
x1: number
y1: number
x2: number
y2: number
bold: boolean
zIndex: number
strokeColor: EntityColor
fillColor: EntityColor // not used for lines, but keeping consistent
}
// Color palette for strokes (bright colors)
const STROKE_PALETTE: (RGBA | null)[] = [
null, // transparent
RGBA.fromInts(0, 0, 0, 255), // black
RGBA.fromInts(255, 255, 255, 255), // white
RGBA.fromInts(255, 100, 100, 255), // red
RGBA.fromInts(100, 255, 100, 255), // green
RGBA.fromInts(100, 100, 255, 255), // blue
RGBA.fromInts(255, 255, 100, 255), // yellow
]
// Color palette for fills (muted/darker versions for backgrounds)
const FILL_PALETTE: (RGBA | null)[] = [
null, // transparent
RGBA.fromInts(0, 0, 0, 255), // black
RGBA.fromInts(60, 60, 60, 255), // muted white/gray
RGBA.fromInts(80, 30, 30, 255), // muted red
RGBA.fromInts(30, 80, 30, 255), // muted green
RGBA.fromInts(30, 30, 80, 255), // muted blue
RGBA.fromInts(80, 80, 30, 255), // muted yellow
]
type Tool = "move" | "text" | "rectangle" | "line"
interface ToolInfo {
name: string
key: string
}
const TOOLS: Record<Tool, ToolInfo> = {
move: { name: "Move", key: "M" },
text: { name: "Text", key: "T" },
rectangle: { name: "Rectangle", key: "R" },
line: { name: "Line", key: "L" }
}
type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w" | null
interface HistorySnapshot {
textBoxes: TextBox[]
rectangles: Rectangle[]
lines: Line[]
nextTextBoxId: number
nextRectId: number
nextLineId: number
nextZIndex: number
}
// File format for saving/loading designs
interface TigmaFile {
version: 1
textBoxes: SerializedTextBox[]
rectangles: SerializedRectangle[]
lines: SerializedLine[]
nextTextBoxId: number
nextRectId: number
nextLineId: number
nextZIndex: number
}
// Serialized versions with colors as arrays instead of RGBA objects
interface SerializedColor {
r: number
g: number
b: number
a: number
}
interface SerializedTextChar {
char: string
bold: boolean
color: SerializedColor | null
}
interface SerializedTextBox {
id: number
x: number
y: number
chars: SerializedTextChar[]
zIndex: number
strokeColor: SerializedColor | null
fillColor: SerializedColor | null
}
interface SerializedRectangle {
id: number
x1: number
y1: number
x2: number
y2: number
bold: boolean
zIndex: number
strokeColor: SerializedColor | null
fillColor: SerializedColor | null
}
interface SerializedLine {
id: number
x1: number
y1: number
x2: number
y2: number
bold: boolean
zIndex: number
strokeColor: SerializedColor | null
fillColor: SerializedColor | null
}
class CanvasApp {
private renderer: CliRenderer
private boldMode = false
private canvas: BoxRenderable
private currentFilePath: string | null = null
private saveStatusMessage: string | null = null
private saveStatusTimeout: number = 0
private isSelecting = false
private isSelectionPending = false
// Save prompt state
private showSavePrompt: boolean = false
private savePromptInput: string = ""
// Canvas dimensions
private gridWidth = 0
private gridHeight = 0
// Text boxes layer
private textBoxes: TextBox[] = []
private nextTextBoxId = 1
// Rectangle layer
private rectangles: Rectangle[] = []
private nextRectId = 1
// Line layer
private lines: Line[] = []
private nextLineId = 1
// Z-index for layer ordering (higher = on top)
private nextZIndex = 1
// Tool state
private currentTool: Tool = "move"
private isDrawingRect = false
private isDrawingLine = false
private drawStartX = 0
private drawStartY = 0
private drawCursorX = 0
private drawCursorY = 0
private isDraggingMouse = false
// Active text box (currently being edited)
private activeTextBoxId: number | null = null
private textCursorPos = 0
private cursorBlinkVisible = true
private cursorBlinkInterval: ReturnType<typeof setInterval> | null = null
// Hover state
private hoveredTextBoxId: number | null = null
private hoveredRectId: number | null = null
private hoveredLineId: number | null = null
// Selection state (persists after clicking/dragging)
// Using Sets to support multi-selection
private selectedTextBoxIds: Set<number> = new Set()
private selectedRectIds: Set<number> = new Set()
private selectedLineIds: Set<number> = new Set()
// Dragging state (for moving objects)
private isDraggingSelection = false
private dragStartX = 0
private dragStartY = 0
private isResizingRect = false
private resizeHandle: ResizeHandle = null
private moveOffsetX = 0
private moveOffsetY = 0
private mouseDownX = 0
private mouseDownY = 0
private hasDragged = false
private clickedOnSelectedTextBox = false
// History for undo/redo
private historyStack: HistorySnapshot[] = []
private redoStack: HistorySnapshot[] = []
private readonly MAX_HISTORY = 100
// Current stroke and fill colors for new entities
private currentStrokeColor: EntityColor = RGBA.fromInts(255, 255, 255, 255) // white
private currentFillColor: EntityColor = null // transparent
private currentStrokeColorIndex = 2 // index in STROKE_PALETTE (white)
private currentFillColorIndex = 0 // index in FILL_PALETTE (0 = transparent)
private colorPickerMode: "stroke" | "fill" = "stroke"
private readonly textColor = RGBA.fromInts(255, 255, 255, 255)
private readonly bgColor = RGBA.fromInts(0, 0, 0, 255)
private readonly cursorBgColor = RGBA.fromInts(80, 80, 80, 255)
private readonly toolbarBgColor = RGBA.fromInts(30, 30, 30, 255)
private readonly toolbarTextColor = RGBA.fromInts(200, 200, 200, 255)
private readonly toolbarActiveColor = RGBA.fromInts(100, 150, 255, 255)
private readonly hoverColor = RGBA.fromInts(35, 40, 60, 255)
// Selection uses a subtle muted blue
private readonly selectedBgColor = RGBA.fromInts(25, 40, 80, 255) // muted blue tint
private readonly handleColor = RGBA.fromInts(50, 80, 160, 255) // slightly brighter blue for handles
private readonly textBoxBorderColor = RGBA.fromInts(100, 150, 255, 255)
private readonly TOOLBAR_HEIGHT = 1
constructor(renderer: CliRenderer) {
this.renderer = renderer
this.gridWidth = renderer.terminalWidth
this.gridHeight = renderer.terminalHeight - this.TOOLBAR_HEIGHT
const self = this
this.canvas = new BoxRenderable(renderer, {
id: "canvas",
width: "100%",
height: "100%",
backgroundColor: this.bgColor,
zIndex: 0,
onMouse(event: MouseEvent) {
self.handleMouse(event)
},
renderAfter(buffer: OptimizedBuffer) {
self.render(buffer)
},
})
renderer.root.add(this.canvas)
this.setupInput()
this.startCursorBlink()
renderer.on("resize", (width: number, height: number) => {
this.handleResize(width, height - this.TOOLBAR_HEIGHT)
})
// Clean up resources when the renderer is destroyed (e.g., on Ctrl+C)
renderer.on("destroy", () => {
this.cleanup()
})
}
private cleanup(): void {
if (this.cursorBlinkInterval) {
clearInterval(this.cursorBlinkInterval)
this.cursorBlinkInterval = null
}
}
// ==================== Cursor Blink ====================
private startCursorBlink(): void {
this.cursorBlinkInterval = setInterval(() => {
if (this.activeTextBoxId !== null) {
this.cursorBlinkVisible = !this.cursorBlinkVisible
this.renderer.requestRender()
}
}, 530)
}
private resetCursorBlink(): void {
this.cursorBlinkVisible = true
this.renderer.requestRender()
}
// ==================== Resize ====================
private handleResize(width: number, height: number): void {
this.gridWidth = width
this.gridHeight = height
}
// ==================== History (Undo/Redo) ====================
private saveSnapshot(): void {
const snapshot: HistorySnapshot = {
textBoxes: this.cloneTextBoxes(this.textBoxes),
rectangles: this.cloneRectangles(this.rectangles),
lines: this.cloneLines(this.lines),
nextTextBoxId: this.nextTextBoxId,
nextRectId: this.nextRectId,
nextLineId: this.nextLineId,
nextZIndex: this.nextZIndex,
}
this.historyStack.push(snapshot)
if (this.historyStack.length > this.MAX_HISTORY) {
this.historyStack.shift()
}
this.redoStack = []
}
private cloneTextBoxes(boxes: TextBox[]): TextBox[] {
return boxes.map(b => ({ ...b, chars: b.chars.map(c => ({ ...c })) }))
}
private cloneRectangles(rects: Rectangle[]): Rectangle[] {
return rects.map(r => ({ ...r }))
}
private cloneLines(lines: Line[]): Line[] {
return lines.map(l => ({ ...l }))
}
private undo(): void {
if (this.historyStack.length === 0) return
const currentSnapshot: HistorySnapshot = {
textBoxes: this.cloneTextBoxes(this.textBoxes),
rectangles: this.cloneRectangles(this.rectangles),
lines: this.cloneLines(this.lines),
nextTextBoxId: this.nextTextBoxId,
nextRectId: this.nextRectId,
nextLineId: this.nextLineId,
nextZIndex: this.nextZIndex,
}
this.redoStack.push(currentSnapshot)
const snapshot = this.historyStack.pop()!
this.textBoxes = snapshot.textBoxes
this.rectangles = snapshot.rectangles
this.lines = snapshot.lines
this.nextTextBoxId = snapshot.nextTextBoxId
this.nextRectId = snapshot.nextRectId
this.nextLineId = snapshot.nextLineId
this.nextZIndex = snapshot.nextZIndex
this.activeTextBoxId = null
this.hoveredTextBoxId = null
this.hoveredRectId = null
this.hoveredLineId = null
this.clearSelection()
this.renderer.requestRender()
}
private redo(): void {
if (this.redoStack.length === 0) return
const currentSnapshot: HistorySnapshot = {
textBoxes: this.cloneTextBoxes(this.textBoxes),
rectangles: this.cloneRectangles(this.rectangles),
lines: this.cloneLines(this.lines),
nextTextBoxId: this.nextTextBoxId,
nextRectId: this.nextRectId,
nextLineId: this.nextLineId,
nextZIndex: this.nextZIndex,
}
this.historyStack.push(currentSnapshot)
const snapshot = this.redoStack.pop()!
this.textBoxes = snapshot.textBoxes
this.rectangles = snapshot.rectangles
this.lines = snapshot.lines
this.nextTextBoxId = snapshot.nextTextBoxId
this.nextRectId = snapshot.nextRectId
this.nextLineId = snapshot.nextLineId
this.nextZIndex = snapshot.nextZIndex
this.activeTextBoxId = null
this.hoveredTextBoxId = null
this.hoveredRectId = null
this.hoveredLineId = null
this.clearSelection()
this.renderer.requestRender()
}
// ==================== File Save/Load ====================
private serializeColor(color: EntityColor): SerializedColor | null {
if (color === null) return null
return { r: color.r, g: color.g, b: color.b, a: color.a }
}
private deserializeColor(color: SerializedColor | null): EntityColor {
if (color === null) return null
return RGBA.fromValues(color.r, color.g, color.b, color.a)
}
private serializeTextBox(box: TextBox): SerializedTextBox {
return {
id: box.id,
x: box.x,
y: box.y,
chars: box.chars.map(c => ({
char: c.char,
bold: c.bold,
color: this.serializeColor(c.color),
})),
zIndex: box.zIndex,
strokeColor: this.serializeColor(box.strokeColor),
fillColor: this.serializeColor(box.fillColor),
}
}
private deserializeTextBox(box: SerializedTextBox): TextBox {
return {
id: box.id,
x: box.x,
y: box.y,
chars: box.chars.map(c => ({
char: c.char,
bold: c.bold,
color: this.deserializeColor(c.color),
})),
zIndex: box.zIndex,
strokeColor: this.deserializeColor(box.strokeColor),
fillColor: this.deserializeColor(box.fillColor),
}
}
private serializeRectangle(rect: Rectangle): SerializedRectangle {
return {
id: rect.id,
x1: rect.x1,
y1: rect.y1,
x2: rect.x2,
y2: rect.y2,
bold: rect.bold,
zIndex: rect.zIndex,
strokeColor: this.serializeColor(rect.strokeColor),
fillColor: this.serializeColor(rect.fillColor),
}
}
private deserializeRectangle(rect: SerializedRectangle): Rectangle {
return {
id: rect.id,
x1: rect.x1,
y1: rect.y1,
x2: rect.x2,
y2: rect.y2,
bold: rect.bold,
zIndex: rect.zIndex,
strokeColor: this.deserializeColor(rect.strokeColor),
fillColor: this.deserializeColor(rect.fillColor),
}
}
private serializeLine(line: Line): SerializedLine {
return {
id: line.id,
x1: line.x1,
y1: line.y1,
x2: line.x2,
y2: line.y2,
bold: line.bold,
zIndex: line.zIndex,
strokeColor: this.serializeColor(line.strokeColor),
fillColor: this.serializeColor(line.fillColor),
}
}
private deserializeLine(line: SerializedLine): Line {
return {
id: line.id,
x1: line.x1,
y1: line.y1,
x2: line.x2,
y2: line.y2,
bold: line.bold,
zIndex: line.zIndex,
strokeColor: this.deserializeColor(line.strokeColor),
fillColor: this.deserializeColor(line.fillColor),
}
}
private toFileData(): TigmaFile {
return {
version: 1,
textBoxes: this.textBoxes.map(b => this.serializeTextBox(b)),
rectangles: this.rectangles.map(r => this.serializeRectangle(r)),
lines: this.lines.map(l => this.serializeLine(l)),
nextTextBoxId: this.nextTextBoxId,
nextRectId: this.nextRectId,
nextLineId: this.nextLineId,
nextZIndex: this.nextZIndex,
}
}
private loadFromFileData(data: TigmaFile): void {
this.textBoxes = data.textBoxes.map(b => this.deserializeTextBox(b))
this.rectangles = data.rectangles.map(r => this.deserializeRectangle(r))
this.lines = data.lines.map(l => this.deserializeLine(l))
this.nextTextBoxId = data.nextTextBoxId
this.nextRectId = data.nextRectId
this.nextLineId = data.nextLineId
this.nextZIndex = data.nextZIndex
// Reset UI state
this.activeTextBoxId = null
this.hoveredTextBoxId = null
this.hoveredRectId = null
this.hoveredLineId = null
this.clearSelection()
this.historyStack = []
this.redoStack = []
this.renderer.requestRender()
}
public loadFile(filePath: string): boolean {
try {
const absolutePath = path.resolve(filePath)
const content = fs.readFileSync(absolutePath, "utf-8")
const data = JSON.parse(content) as TigmaFile
if (data.version !== 1) {
console.error(`Unsupported file version: ${data.version}`)
return false
}
this.loadFromFileData(data)
this.currentFilePath = absolutePath
return true
} catch (err) {
console.error(`Failed to load file: ${err}`)
return false
}
}
private saveFile(): void {
if (this.currentFilePath) {
// Save directly to the current file
this.doSaveFile(this.currentFilePath)
} else {
// Show prompt to ask for filename
this.showSavePrompt = true
this.savePromptInput = "design.tigma"
this.renderer.requestRender()
}
}
private doSaveFile(filename: string): void {
try {
const filePath = path.resolve(filename)
const data = this.toFileData()
fs.writeFileSync(filePath, JSON.stringify(data, null, 2))
this.currentFilePath = filePath
this.saveStatusMessage = `Saved to ${path.basename(filePath)}`
this.saveStatusTimeout = Date.now() + 2000 // Show for 2 seconds
this.renderer.requestRender()
} catch (err) {
this.saveStatusMessage = `Save failed: ${err}`
this.saveStatusTimeout = Date.now() + 3000
this.renderer.requestRender()
}
}
private closeSavePrompt(): void {
this.showSavePrompt = false
this.savePromptInput = ""
this.renderer.requestRender()
}
private handleSavePromptKey(key: KeyEvent): boolean {
if (!this.showSavePrompt) return false
// Let Ctrl+C pass through for exit handling
if (key.name === "c" && key.ctrl) {
return false
}
if (key.name === "escape") {
this.closeSavePrompt()
return true
}
if (key.name === "return") {
const filename = this.savePromptInput.trim() || "design.tigma"
this.closeSavePrompt()
this.doSaveFile(filename)
return true
}
if (key.name === "backspace") {
if (this.savePromptInput.length > 0) {
this.savePromptInput = this.savePromptInput.slice(0, -1)
this.renderer.requestRender()
}
return true
}
// Regular character input
if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {
this.savePromptInput += key.sequence
this.renderer.requestRender()
return true
}
return true // Consume all keys when prompt is open
}
// ==================== Selection Helpers ====================
private clearSelection(): void {
this.selectedTextBoxIds.clear()
this.selectedRectIds.clear()
this.selectedLineIds.clear()
}
private hasSelection(): boolean {
return this.selectedTextBoxIds.size > 0 || this.selectedRectIds.size > 0 || this.selectedLineIds.size > 0
}
private isMultiSelection(): boolean {
const total = this.selectedTextBoxIds.size + this.selectedRectIds.size + this.selectedLineIds.size
return total > 1
}
private getTotalSelectionCount(): number {
return this.selectedTextBoxIds.size + this.selectedRectIds.size + this.selectedLineIds.size
}
private isTextBoxSelected(id: number): boolean {
return this.selectedTextBoxIds.has(id)
}
private isRectSelected(id: number): boolean {
return this.selectedRectIds.has(id)
}
private isLineSelected(id: number): boolean {
return this.selectedLineIds.has(id)
}
private selectTextBox(id: number, addToSelection: boolean): void {
if (!addToSelection) {
this.clearSelection()
}
this.selectedTextBoxIds.add(id)
}
private selectRect(id: number, addToSelection: boolean): void {
if (!addToSelection) {
this.clearSelection()
}
this.selectedRectIds.add(id)
}
private selectLine(id: number, addToSelection: boolean): void {
if (!addToSelection) {
this.clearSelection()
}
this.selectedLineIds.add(id)
}
private moveSelection(dx: number, dy: number): void {
// Move all selected text boxes
for (const id of this.selectedTextBoxIds) {
const box = this.textBoxes.find(b => b.id === id)
if (box) {
box.x += dx
box.y += dy
}
}
// Move all selected rectangles
for (const id of this.selectedRectIds) {
const rect = this.rectangles.find(r => r.id === id)
if (rect) {
rect.x1 += dx
rect.y1 += dy
rect.x2 += dx
rect.y2 += dy
}
}
// Move all selected lines
for (const id of this.selectedLineIds) {
const line = this.lines.find(l => l.id === id)
if (line) {
line.x1 += dx
line.y1 += dy
line.x2 += dx
line.y2 += dy
}
}
this.renderer.requestRender()
}
// ==================== Mouse Handling ====================
private handleMouse(event: MouseEvent): void {
if (event.y >= this.gridHeight) {
return
}
// Check for color picker clicks first
if (event.type === "down") {
const colorPickerResult = this.handleColorPickerClick(event.x, event.y)
if (colorPickerResult) {
return
}
}
// Handle hover for all tools
if (event.type === "move") {
this.updateHover(event.x, event.y)
return
}
// Handle dragging (moving objects)
if (event.type === "drag") {
// Track if we've actually moved from the mouse down position
if (event.x !== this.mouseDownX || event.y !== this.mouseDownY) {
this.hasDragged = true
}
if (this.isSelectionPending && this.hasDragged && this.currentTool === "move") {
this.isSelectionPending = false
this.isSelecting = true
this.isDraggingMouse = true
}
if (this.isDraggingSelection) {
// Move all selected items
const dx = event.x - this.dragStartX
const dy = event.y - this.dragStartY
this.moveSelection(dx, dy)
this.dragStartX = event.x
this.dragStartY = event.y
} else if (this.isResizingRect) {
// Find the single selected rect for resizing
const rectId = this.selectedRectIds.values().next().value
if (rectId !== undefined) {
this.resizeRect(rectId, event.x, event.y)
}
} else if (this.isDrawingRect || this.isDrawingLine || this.isSelecting) {
this.drawCursorX = Math.max(0, Math.min(this.gridWidth - 1, event.x))
this.drawCursorY = Math.max(0, Math.min(this.gridHeight - 1, event.y))
this.renderer.requestRender()
}
return
}
// Handle drag end
if (event.type === "up" || event.type === "drag-end") {
if (this.isDrawingRect) {
this.drawCursorX = Math.max(0, Math.min(this.gridWidth - 1, event.x))
this.drawCursorY = Math.max(0, Math.min(this.gridHeight - 1, event.y))
this.commitRectangle()
}
if (this.isDrawingLine) {
this.drawCursorX = Math.max(0, Math.min(this.gridWidth - 1, event.x))
this.drawCursorY = Math.max(0, Math.min(this.gridHeight - 1, event.y))
this.commitLine()
}
if (this.isSelecting) {
this.drawCursorX = Math.max(0, Math.min(this.gridWidth - 1, event.x))
this.drawCursorY = Math.max(0, Math.min(this.gridHeight - 1, event.y))
this.commitSelection() // 后面会实现这个方法
}
// If we clicked on a selected text box and didn't drag, enter edit mode (only for single selection)
if (this.clickedOnSelectedTextBox && !this.hasDragged && this.selectedTextBoxIds.size === 1) {
const textBoxId = this.selectedTextBoxIds.values().next().value
const textBox = this.textBoxes.find(b => b.id === textBoxId)
if (textBox) {
this.activeTextBoxId = textBox.id
const relativeX = event.x - textBox.x
this.textCursorPos = Math.min(relativeX, this.getTextLength(textBox))
this.clearSelection()
this.resetCursorBlink()
this.renderer.requestRender()
}
}
this.isDraggingSelection = false
this.isResizingRect = false
this.resizeHandle = null
this.isDraggingMouse = false
this.clickedOnSelectedTextBox = false
this.hasDragged = false
this.isSelecting = false
this.isSelectionPending = false
return
}
// Handle mouse down
if (event.type === "down") {
// If editing text, check if clicking on same text box or elsewhere
if (this.activeTextBoxId !== null) {
const activeBox = this.textBoxes.find(b => b.id === this.activeTextBoxId)
if (activeBox) {
const boxWidth = Math.max(1, this.getTextLength(activeBox))
const clickedOnActiveBox = event.x >= activeBox.x && event.x < activeBox.x + boxWidth && event.y === activeBox.y
if (clickedOnActiveBox) {
// Move cursor within the text box
const relativeX = event.x - activeBox.x
this.textCursorPos = Math.min(relativeX, this.getTextLength(activeBox))
this.resetCursorBlink()
this.renderer.requestRender()
return
}
}
// Clicked outside - commit text and switch to Move tool
this.commitActiveTextBox()
this.setTool("move")
// Don't return - continue to handle the click in Move mode
}
// Move tool: select and move existing objects
if (this.currentTool === "move") {
// Track mouse down position for detecting clicks vs drags
this.mouseDownX = event.x
this.mouseDownY = event.y
this.hasDragged = false
this.clickedOnSelectedTextBox = false
const shiftHeld = event.modifiers?.shift ?? false
// First check if clicking on a SELECTED rectangle's resize handle (only for single selection)
if (this.selectedRectIds.size === 1 && !this.isMultiSelection()) {
const rectId = this.selectedRectIds.values().next().value
if (rectId !== undefined) {
const handle = this.getResizeHandleAt(rectId, event.x, event.y)
if (handle) {
this.saveSnapshot()
this.isResizingRect = true
this.resizeHandle = handle
this.isDraggingMouse = true
return
}
}
}
// Check if clicking on a text box
const clickedTextBox = this.getTextBoxAt(event.x, event.y)
if (clickedTextBox) {
const alreadySelected = this.isTextBoxSelected(clickedTextBox.id)
if (alreadySelected && !shiftHeld && !this.isMultiSelection()) {
// Single selected text box clicked again - prepare for edit mode
this.clickedOnSelectedTextBox = true
}
if (shiftHeld) {
// Toggle selection
if (alreadySelected) {
this.selectedTextBoxIds.delete(clickedTextBox.id)
} else {
this.selectedTextBoxIds.add(clickedTextBox.id)
}
} else if (!alreadySelected) {
// Regular click on unselected - select only this
this.selectTextBox(clickedTextBox.id, false)
}
// Prepare for dragging all selected items
this.saveSnapshot()
this.isDraggingSelection = true
this.dragStartX = event.x
this.dragStartY = event.y
this.isDraggingMouse = true
this.renderer.requestRender()
return
}
// Check if clicking on a rectangle
const clickedRect = this.getRectangleAt(event.x, event.y)
if (clickedRect) {
const alreadySelected = this.isRectSelected(clickedRect.id)
if (shiftHeld) {
// Toggle selection
if (alreadySelected) {
this.selectedRectIds.delete(clickedRect.id)
} else {
this.selectedRectIds.add(clickedRect.id)
}
} else if (!alreadySelected) {
// Regular click on unselected - select only this
this.selectRect(clickedRect.id, false)
}
// Prepare for dragging all selected items
this.saveSnapshot()
this.isDraggingSelection = true
this.dragStartX = event.x
this.dragStartY = event.y
this.isDraggingMouse = true
this.renderer.requestRender()
return
}
// Check if clicking on a line
const clickedLine = this.getLineAt(event.x, event.y)
if (clickedLine) {
const alreadySelected = this.isLineSelected(clickedLine.id)
if (shiftHeld) {
// Toggle selection
if (alreadySelected) {
this.selectedLineIds.delete(clickedLine.id)
} else {
this.selectedLineIds.add(clickedLine.id)
}
} else if (!alreadySelected) {
// Regular click on unselected - select only this
this.selectLine(clickedLine.id, false)
}
// Prepare for dragging all selected items
this.saveSnapshot()
this.isDraggingSelection = true
this.dragStartX = event.x
this.dragStartY = event.y
this.isDraggingMouse = true
this.renderer.requestRender()
return
}
// Clicking on empty space - clear selection (unless shift is held) and prep box selection
if (!shiftHeld) {
this.clearSelection()
}
this.isSelectionPending = true
this.drawStartX = event.x
this.drawStartY = event.y
this.drawCursorX = event.x
this.drawCursorY = event.y
this.renderer.requestRender()
return
}
// Drawing tools: create new objects (ignore existing objects)
// Clear selection when using drawing tools
this.clearSelection()
if (this.currentTool === "text") {
// Check if clicking on an existing text box to edit it
const clickedTextBox = this.getTextBoxAt(event.x, event.y)
if (clickedTextBox) {
// Start editing this text box
this.activeTextBoxId = clickedTextBox.id
const relativeX = event.x - clickedTextBox.x
this.textCursorPos = Math.min(relativeX, this.getTextLength(clickedTextBox))
this.resetCursorBlink()
} else {
// Create a new text box
this.saveSnapshot()
const newBox: TextBox = {