-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1581 lines (1345 loc) · 45.9 KB
/
Copy pathscript.js
File metadata and controls
1581 lines (1345 loc) · 45.9 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
// Global state
let state = {
zoom: 1,
panX: 0,
panY: 0,
notes: [],
isDragging: false,
dragStart: { x: 0, y: 0 },
lastPan: { x: 0, y: 0 },
maxZIndex: 1,
}
// Note interaction state
let currentNote = null
let isResizingNote = false
let isDraggingNote = false
let noteDragData = null
let noteResizeData = null
// Click handling state
let clickTimer = null
let clickPosition = { x: 0, y: 0 }
const CLICK_DELAY = 300 // ms to wait for potential double-click
// Touch handling state
let touches = []
let lastPinchDistance = 0
let isPinching = false
let isTouchPanning = false
let touchPanStart = { x: 0, y: 0 }
let touchLastPan = { x: 0, y: 0 }
let lastPinchCenter = { x: 0, y: 0 }
// Double-tap detection for mobile
let lastTapTime = 0
let lastTapX = 0
let lastTapY = 0
const DOUBLE_TAP_DELAY = 300 // ms
const DOUBLE_TAP_DISTANCE = 40 // px
// Tap-to-create-note detection for mobile
let tapStartTime = 0
let tapStartX = 0
let tapStartY = 0
const TAP_MAX_DURATION = 250 // ms
const TAP_MAX_MOVE = 10 // px
let tapMoved = false
let tapCreateNoteTimer = null
let tapCreateNotePosition = { x: 0, y: 0 }
// DOM elements
const viewport = document.getElementById('viewport')
const world = document.getElementById('world')
// Constants
const MIN_ZOOM = 0.1
const MAX_ZOOM = 5
const ZOOM_FACTOR = 0.05
const STORAGE_KEY = 'infinote-state'
let doubleTapDetected = false
// Initialize the app
async function init() {
// Disable transition during initialization to prevent animation
world.style.transition = 'none'
try {
await initStorage()
await loadState()
} catch (e) {
console.warn('Failed to initialize IndexedDB, falling back to localStorage:', e)
// The loadState function already has localStorage fallback
await loadState()
}
updateTransform()
updateUI()
attachEventListeners()
// Handle instructions visibility
handleInstructions()
// Check if backup reminder is needed
checkBackupReminder()
// Re-enable transition after all notes are loaded and positioned
// Wait two frames to ensure DOM is fully settled
requestAnimationFrame(() => {
requestAnimationFrame(() => {
world.style.transition = 'transform 0.1s ease-out'
})
})
}
// Handle instructions visibility
function handleInstructions() {
const instructions = document.querySelector('.instructions')
if (!instructions) return
const INSTRUCTIONS_SEEN_KEY = 'infinote-instructions-seen'
const hasSeenInstructions = localStorage.getItem(INSTRUCTIONS_SEEN_KEY)
if (!hasSeenInstructions) {
// Show instructions if they haven't been seen before
instructions.style.display = 'block'
// Hide instructions after 5 seconds and mark as seen
setTimeout(() => {
instructions.style.opacity = '0'
instructions.style.pointerEvents = 'none'
instructions.style.transition = 'opacity 0.5s ease'
// Mark instructions as seen
localStorage.setItem(INSTRUCTIONS_SEEN_KEY, 'true')
}, 5000)
}
}
// Event listeners
function attachEventListeners() {
// Mouse events for panning and note creation
viewport.addEventListener('mousedown', handleMouseDown)
viewport.addEventListener('mousemove', handleMouseMove)
viewport.addEventListener('mouseup', handleMouseUp)
viewport.addEventListener('mouseleave', handleMouseUp)
// Double-click for reset view
viewport.addEventListener('dblclick', handleDoubleClick)
// Wheel event for zooming
viewport.addEventListener('wheel', handleWheel, { passive: false })
// Touch events for mobile pinch-to-zoom
viewport.addEventListener('touchstart', handleTouchStart, { passive: false })
viewport.addEventListener('touchmove', handleTouchMove, { passive: false })
viewport.addEventListener('touchend', handleTouchEnd, { passive: false })
// Prevent context menu
viewport.addEventListener('contextmenu', e => e.preventDefault())
// Window resize
window.addEventListener('resize', updateTransform)
// Double-tap detection for mobile
viewport.addEventListener('touchend', handleTouchTap, { passive: false })
// Tap-to-create-note detection for mobile
viewport.addEventListener('touchstart', handleViewportTouchStart, {
passive: false,
})
viewport.addEventListener('touchmove', handleViewportTouchMove, {
passive: false,
})
viewport.addEventListener('touchend', handleViewportTouchEnd, {
passive: false,
})
// Global mouse handlers for note interactions
document.addEventListener('mousemove', handleGlobalMouseMove)
document.addEventListener('mouseup', handleGlobalMouseUp)
// Global touch handlers for note interactions
document.addEventListener('touchmove', handleGlobalTouchMove, {
passive: false,
})
document.addEventListener('touchend', handleGlobalTouchEnd, {
passive: false,
})
// Drag and drop backup import
viewport.addEventListener('dragover', handleDragOver, { passive: false })
viewport.addEventListener('drop', handleDrop, { passive: false })
viewport.addEventListener('dragenter', handleDragEnter, { passive: false })
viewport.addEventListener('dragleave', handleDragLeave, { passive: false })
}
// Drag and drop handlers for backup import
let dragCounter = 0
function handleDragEnter(e) {
e.preventDefault()
dragCounter++
if (dragCounter === 1) {
viewport.classList.add('drag-over')
showDropOverlay()
}
}
function handleDragLeave(e) {
e.preventDefault()
dragCounter--
if (dragCounter === 0) {
viewport.classList.remove('drag-over')
hideDropOverlay()
}
}
function handleDragOver(e) {
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
}
function handleDrop(e) {
e.preventDefault()
dragCounter = 0
viewport.classList.remove('drag-over')
hideDropOverlay()
const files = Array.from(e.dataTransfer.files)
const jsonFile = files.find(
file => file.type === 'application/json' || file.name.endsWith('.json'),
)
if (jsonFile) {
if (confirm('Import backup file? This will replace all current notes.')) {
importData(jsonFile)
.then(() => {
console.log('✅ Backup imported successfully')
})
.catch(error => {
console.error('❌ Failed to import backup:', error)
alert('Failed to import backup file. Please check the file format.')
})
}
} else {
alert('Please drop a JSON backup file.')
}
}
function showDropOverlay() {
let overlay = document.getElementById('drop-overlay')
if (!overlay) {
overlay = document.createElement('div')
overlay.id = 'drop-overlay'
overlay.innerHTML = `
<div class="drop-message">
<div class="drop-icon">📁</div>
<div>Drop backup file to import</div>
</div>
`
document.body.appendChild(overlay)
}
overlay.style.display = 'flex'
}
function hideDropOverlay() {
const overlay = document.getElementById('drop-overlay')
if (overlay) {
overlay.style.display = 'none'
}
}
// Mouse event handlers
function handleMouseDown(e) {
if (e.target !== viewport && e.target !== world) return
state.isDragging = true
state.dragStart = { x: e.clientX, y: e.clientY }
state.lastPan = { x: state.panX, y: state.panY }
viewport.classList.add('dragging')
e.preventDefault()
}
function handleMouseMove(e) {
if (!state.isDragging) return
const deltaX = e.clientX - state.dragStart.x
const deltaY = e.clientY - state.dragStart.y
state.panX = state.lastPan.x + deltaX
state.panY = state.lastPan.y + deltaY
updateTransform()
e.preventDefault()
}
function handleMouseUp(e) {
if (!state.isDragging) return
const deltaX = Math.abs(e.clientX - state.dragStart.x)
const deltaY = Math.abs(e.clientY - state.dragStart.y)
// Check if any color picker is currently open
const isColorPickerOpen = document.querySelector('.color-palette.show') !== null
// Check if a textarea is currently focused
const focusedTextarea = document.querySelector('textarea.note:focus')
// If mouse didn't move much and no color picker is open, handle click with delay
if (
deltaX < 5 &&
deltaY < 5 &&
(e.target === viewport || e.target === world) &&
!isColorPickerOpen
) {
if (focusedTextarea) {
// Just blur the focused textarea instead of creating a new note
focusedTextarea.blur()
} else {
// Store click position and start timer for delayed note creation
clickPosition.x = e.clientX
clickPosition.y = e.clientY
// Clear any existing timer
if (clickTimer) {
clearTimeout(clickTimer)
}
// Start timer for delayed note creation
clickTimer = setTimeout(() => {
createNoteAtPosition(clickPosition.x, clickPosition.y)
clickTimer = null
}, CLICK_DELAY)
}
}
state.isDragging = false
viewport.classList.remove('dragging')
saveState()
}
// Double-click event handler
function handleDoubleClick(e) {
// Only handle double-clicks on empty space
if (e.target === viewport || e.target === world) {
// Cancel any pending note creation
if (clickTimer) {
clearTimeout(clickTimer)
clickTimer = null
}
// Execute reset view
resetView()
e.preventDefault()
}
}
// Wheel event for zooming
function handleWheel(e) {
// Don't zoom if wheeling inside a focused textarea
if (e.target.tagName === 'TEXTAREA' && e.target.matches(':focus')) {
return
}
e.preventDefault()
const rect = viewport.getBoundingClientRect()
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
// Calculate world coordinates before zoom
const worldX = (mouseX - state.panX) / state.zoom
const worldY = (mouseY - state.panY) / state.zoom
// Update zoom
const zoomDelta = e.deltaY > 0 ? (-ZOOM_FACTOR * state.zoom) / 2 : (ZOOM_FACTOR * state.zoom) / 2
const newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, state.zoom + zoomDelta))
// Calculate new pan to keep mouse position constant in world space
state.panX = mouseX - worldX * newZoom
state.panY = mouseY - worldY * newZoom
state.zoom = newZoom
updateTransform()
updateUI()
saveState()
}
// Touch event handlers for pinch-to-zoom and panning
function handleTouchStart(e) {
touches = Array.from(e.touches)
if (touches.length === 2) {
// Start pinch gesture
isPinching = true
isTouchPanning = false // Stop panning when pinching starts
lastPinchDistance = getPinchDistance(touches[0], touches[1])
// Initialize pinch center tracking
const rect = viewport.getBoundingClientRect()
lastPinchCenter.x = (touches[0].clientX + touches[1].clientX) / 2 - rect.left
lastPinchCenter.y = (touches[0].clientY + touches[1].clientY) / 2 - rect.top
e.preventDefault()
} else if (touches.length === 1 && (e.target === viewport || e.target === world)) {
// Start single-finger panning
isTouchPanning = true
touchPanStart.x = touches[0].clientX
touchPanStart.y = touches[0].clientY
touchLastPan.x = state.panX
touchLastPan.y = state.panY
viewport.classList.add('dragging')
e.preventDefault()
}
}
function handleTouchMove(e) {
if (isPinching && e.touches.length === 2) {
e.preventDefault()
const touch1 = e.touches[0]
const touch2 = e.touches[1]
const pinchDistance = getPinchDistance(touch1, touch2)
if (lastPinchDistance > 0) {
// Calculate zoom change based on pinch distance change
const zoomRatio = pinchDistance / lastPinchDistance
const newZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, state.zoom * zoomRatio))
// Calculate center point of pinch
const rect = viewport.getBoundingClientRect()
const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left
const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top
// Calculate center point movement (panning while pinching)
const centerDeltaX = centerX - lastPinchCenter.x
const centerDeltaY = centerY - lastPinchCenter.y
// Calculate world coordinates before zoom
const worldX = (centerX - state.panX) / state.zoom
const worldY = (centerY - state.panY) / state.zoom
// Update zoom and pan to keep pinch center constant
state.panX = centerX - worldX * newZoom + centerDeltaX
state.panY = centerY - worldY * newZoom + centerDeltaY
state.zoom = newZoom
// Update last pinch center for next frame
lastPinchCenter.x = centerX
lastPinchCenter.y = centerY
updateTransform()
updateUI()
}
lastPinchDistance = pinchDistance
} else if (isTouchPanning && e.touches.length === 1) {
e.preventDefault()
const touch = e.touches[0]
const deltaX = touch.clientX - touchPanStart.x
const deltaY = touch.clientY - touchPanStart.y
state.panX = touchLastPan.x + deltaX
state.panY = touchLastPan.y + deltaY
updateTransform()
}
}
function handleTouchEnd(e) {
if (isPinching) {
isPinching = false
lastPinchDistance = 0
saveState()
}
if (isTouchPanning) {
isTouchPanning = false
viewport.classList.remove('dragging')
saveState()
}
touches = Array.from(e.touches)
// If there are still touches remaining, check if we should start a new gesture
if (touches.length === 1 && !isPinching) {
// Single touch remains, restart panning if on viewport/world
const remainingTouch = touches[0]
if (
document.elementFromPoint(remainingTouch.clientX, remainingTouch.clientY) === viewport ||
document.elementFromPoint(remainingTouch.clientX, remainingTouch.clientY) === world
) {
isTouchPanning = true
touchPanStart.x = remainingTouch.clientX
touchPanStart.y = remainingTouch.clientY
touchLastPan.x = state.panX
touchLastPan.y = state.panY
viewport.classList.add('dragging')
}
}
}
// Helper function to calculate distance between two touch points
function getPinchDistance(touch1, touch2) {
const dx = touch1.clientX - touch2.clientX
const dy = touch1.clientY - touch2.clientY
return Math.sqrt(dx * dx + dy * dy)
}
// Global mouse handlers for note interactions
function handleGlobalMouseMove(e) {
if (isResizingNote && noteResizeData && currentNote) {
// Calculate mouse delta from initial position
const deltaX = e.clientX - noteResizeData.startMouseX
const deltaY = e.clientY - noteResizeData.startMouseY
// Apply delta to initial size, accounting for zoom
const newWidth = Math.max(150, noteResizeData.startWidth + deltaX / state.zoom)
const newHeight = Math.max(150, noteResizeData.startHeight + deltaY / state.zoom)
// Update the container size (world coordinates)
noteResizeData.container.style.width = `${newWidth}px`
noteResizeData.container.style.height = `${newHeight}px`
// Update the note data
currentNote.width = newWidth
currentNote.height = newHeight
return
}
if (isDraggingNote && noteDragData && currentNote) {
noteDragData.hasMoved = true
noteDragData.noteElement.style.cursor = 'grabbing'
const rect = viewport.getBoundingClientRect()
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
// Convert to world coordinates and maintain the click offset
const worldX = (mouseX - noteDragData.dragOffset.x - state.panX) / state.zoom
const worldY = (mouseY - noteDragData.dragOffset.y - state.panY) / state.zoom
currentNote.x = worldX
currentNote.y = worldY
noteDragData.container.style.left = `${worldX}px`
noteDragData.container.style.top = `${worldY}px`
e.preventDefault()
}
}
function handleGlobalMouseUp() {
if (isResizingNote && noteResizeData && currentNote) {
isResizingNote = false
// Snap resize to 10x10 grid
const gridSize = 10
const snappedWidth = Math.round(currentNote.width / gridSize) * gridSize
const snappedHeight = Math.round(currentNote.height / gridSize) * gridSize
// Update note size to snapped coordinates
currentNote.width = Math.max(150, snappedWidth)
currentNote.height = Math.max(150, snappedHeight)
noteResizeData.container.style.width = `${currentNote.width}px`
noteResizeData.container.style.height = `${currentNote.height}px`
noteResizeData.noteElement.style.cursor = noteResizeData.noteElement.matches(':focus')
? 'text'
: 'grab'
noteResizeData = null
currentNote = null
saveState()
}
if (isDraggingNote && noteDragData && currentNote) {
isDraggingNote = false
noteDragData.noteElement.style.cursor = ''
noteDragData.noteElement.style.userSelect = ''
if (noteDragData.hasMoved) {
// Snap to 10x10 grid
const gridSize = 10
const snappedX = Math.round(currentNote.x / gridSize) * gridSize
const snappedY = Math.round(currentNote.y / gridSize) * gridSize
// Update note position to snapped coordinates
currentNote.x = snappedX
currentNote.y = snappedY
noteDragData.container.style.left = `${snappedX}px`
noteDragData.container.style.top = `${snappedY}px`
saveState()
} else {
// If didn't move, focus the textarea for editing
setTimeout(() => {
noteDragData.noteElement.focus()
}, 10)
}
noteDragData = null
currentNote = null
}
}
// Global touch handlers for note interactions
function handleGlobalTouchMove(e) {
if (isResizingNote && noteResizeData && currentNote && e.touches.length === 1) {
const touch = e.touches[0]
const deltaX = touch.clientX - noteResizeData.startTouchX
const deltaY = touch.clientY - noteResizeData.startTouchY
const newWidth = Math.max(150, noteResizeData.startWidth + deltaX / state.zoom)
const newHeight = Math.max(150, noteResizeData.startHeight + deltaY / state.zoom)
noteResizeData.container.style.width = `${newWidth}px`
noteResizeData.container.style.height = `${newHeight}px`
currentNote.width = newWidth
currentNote.height = newHeight
e.preventDefault()
return
}
if (isDraggingNote && noteDragData && currentNote && e.touches.length === 1) {
noteDragData.hasMoved = true
noteDragData.noteElement.style.cursor = 'grabbing'
const rect = viewport.getBoundingClientRect()
const touch = e.touches[0]
const mouseX = touch.clientX - rect.left
const mouseY = touch.clientY - rect.top
// Convert to world coordinates and maintain the click offset
const worldX = (mouseX - noteDragData.dragOffset.x - state.panX) / state.zoom
const worldY = (mouseY - noteDragData.dragOffset.y - state.panY) / state.zoom
currentNote.x = worldX
currentNote.y = worldY
noteDragData.container.style.left = `${worldX}px`
noteDragData.container.style.top = `${worldY}px`
e.preventDefault()
}
}
function handleGlobalTouchEnd(e) {
if (isResizingNote && noteResizeData && currentNote) {
isResizingNote = false
// Snap resize to 10x10 grid
const gridSize = 10
const snappedWidth = Math.round(currentNote.width / gridSize) * gridSize
const snappedHeight = Math.round(currentNote.height / gridSize) * gridSize
// Update note size to snapped coordinates
currentNote.width = Math.max(150, snappedWidth)
currentNote.height = Math.max(150, snappedHeight)
noteResizeData.container.style.width = `${currentNote.width}px`
noteResizeData.container.style.height = `${currentNote.height}px`
noteResizeData.noteElement.style.cursor = noteResizeData.noteElement.matches(':focus')
? 'text'
: 'grab'
noteResizeData = null
currentNote = null
saveState()
}
if (isDraggingNote && noteDragData && currentNote) {
isDraggingNote = false
noteDragData.noteElement.style.cursor = ''
noteDragData.noteElement.style.userSelect = ''
if (noteDragData.hasMoved) {
// Snap to 10x10 grid
const gridSize = 10
const snappedX = Math.round(currentNote.x / gridSize) * gridSize
const snappedY = Math.round(currentNote.y / gridSize) * gridSize
// Update note position to snapped coordinates
currentNote.x = snappedX
currentNote.y = snappedY
noteDragData.container.style.left = `${snappedX}px`
noteDragData.container.style.top = `${snappedY}px`
saveState()
} else {
// If didn't move, focus the textarea for editing
setTimeout(() => {
noteDragData.noteElement.focus()
}, 10)
}
noteDragData = null
currentNote = null
}
}
// Create a new note at screen position
function createNoteAtPosition(screenX, screenY) {
const rect = viewport.getBoundingClientRect()
const mouseX = screenX - rect.left
const mouseY = screenY - rect.top
// Convert screen coordinates to world coordinates
const worldX = (mouseX - state.panX) / state.zoom
const worldY = (mouseY - state.panY) / state.zoom
const note = {
id: Date.now() + Math.random(),
x: worldX,
y: worldY,
width: 150,
height: 150,
content: '',
color: 'rgba(255, 245, 157, 0.95)',
zIndex: ++state.maxZIndex,
}
state.notes.push(note)
renderNote(note)
updateUI()
saveState()
// Focus the new note
setTimeout(() => {
const container = document.querySelector(`[data-note-id="${note.id}"]`)
if (container) {
const textarea = container.querySelector('.note')
if (textarea) {
textarea.focus()
}
}
}, 100)
}
// Render a note element
function renderNote(note) {
// Create container div
const container = document.createElement('div')
container.className = 'note-container'
container.dataset.noteId = note.id
// Position and size container
container.style.left = `${note.x}px`
container.style.top = `${note.y}px`
container.style.width = `${note.width}px`
container.style.height = `${note.height}px`
container.style.zIndex = note.zIndex || 1
// Create textarea
const noteElement = document.createElement('textarea')
noteElement.className = 'note'
noteElement.value = note.content
noteElement.spellcheck = false
// Create color picker button
const colorBtn = document.createElement('div')
colorBtn.className = 'color-btn'
colorBtn.style.backgroundColor = note.color || 'rgba(255, 255, 255, 0.95)'
// Create color palette
const colorPalette = document.createElement('div')
colorPalette.className = 'color-palette'
// Define 10 saturated colors
const colors = [
'rgba(255, 255, 255, 0.95)', // White
'rgba(255, 200, 200, 0.95)', // Soft red
'rgba(255, 220, 170, 0.95)', // Soft orange
'rgba(255, 245, 157, 0.95)', // Soft yellow
'rgba(200, 255, 200, 0.95)', // Soft green
'rgba(173, 216, 230, 0.95)', // Soft blue
'rgba(221, 160, 221, 0.95)', // Soft purple
'rgba(255, 182, 193, 0.95)', // Soft pink
'rgba(255, 218, 185, 0.95)', // Soft peach
'rgba(211, 211, 211, 0.95)', // Light gray
]
colors.forEach(color => {
const colorOption = document.createElement('div')
colorOption.className = 'palette-color'
colorOption.style.backgroundColor = color
if (color === note.color) {
colorOption.classList.add('selected')
}
colorOption.addEventListener('mouseenter', e => {
// Update note color on hover
note.color = color
colorBtn.style.backgroundColor = color
noteElement.style.backgroundColor = color
// Remove selected class from all colors
colorPalette.querySelectorAll('.palette-color').forEach(c => c.classList.remove('selected'))
// Add selected class to hovered color
colorOption.classList.add('selected')
})
colorOption.addEventListener('click', e => {
e.stopPropagation()
// Commit the current color and hide palette
originalColor = note.color
colorPalette.classList.remove('show')
saveState()
})
colorPalette.appendChild(colorOption)
})
let originalColor = note.color
colorBtn.addEventListener('click', e => {
e.stopPropagation()
// Close other palettes first
document.querySelectorAll('.color-palette.show').forEach(p => {
if (p !== colorPalette) p.classList.remove('show')
})
// Store original color when opening
if (!colorPalette.classList.contains('show')) {
originalColor = note.color
}
colorPalette.classList.toggle('show')
})
// Reset to original color when mouse leaves palette
colorPalette.addEventListener('mouseleave', e => {
if (colorPalette.classList.contains('show')) {
// Reset to original color
note.color = originalColor
colorBtn.style.backgroundColor = originalColor
noteElement.style.backgroundColor = originalColor
// Update selected state to match original color
colorPalette.querySelectorAll('.palette-color').forEach(c => {
c.classList.remove('selected')
if (c.style.backgroundColor === originalColor) {
c.classList.add('selected')
}
})
}
})
// Hide palette when clicking elsewhere
document.addEventListener('click', e => {
if (!colorBtn.contains(e.target) && !colorPalette.contains(e.target)) {
// Reset to original color when closing without selection
note.color = originalColor
colorBtn.style.backgroundColor = originalColor
noteElement.style.backgroundColor = originalColor
colorPalette.classList.remove('show')
}
})
// Create delete button
const deleteBtn = document.createElement('button')
deleteBtn.className = 'delete-btn'
deleteBtn.innerHTML = `
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="#000" stroke-width="1.3" stroke-linecap="square" style="display: block; opacity: 0.2;">
<path d="M4 4L8 8"/>
<path d="M8 4L4 8"/>
</svg>
`
deleteBtn.addEventListener('click', e => {
e.stopPropagation()
deleteNote(note)
})
// Set note background color
if (note.color) {
noteElement.style.backgroundColor = note.color
}
// Append elements
container.appendChild(noteElement)
container.appendChild(colorBtn)
container.appendChild(colorPalette)
container.appendChild(deleteBtn)
// Bring to front on any interaction
function bringToFront() {
state.maxZIndex++
note.zIndex = state.maxZIndex
container.style.zIndex = state.maxZIndex
saveState()
}
// Event listeners for the note
noteElement.addEventListener('input', () => {
note.content = noteElement.value
saveState()
})
noteElement.addEventListener('focus', () => {
bringToFront()
noteElement.style.cursor = 'text'
})
// Mouse-based resize
container.addEventListener('mousedown', e => {
bringToFront()
const rect = container.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
// Don't handle clicks on color or delete buttons
if (e.target === colorBtn || e.target === deleteBtn || colorPalette.contains(e.target)) {
return
}
// Check if clicking in bottom-right resize handle area (40x40 px)
if (x > rect.width - 40 && y > rect.height - 40) {
isResizingNote = true
currentNote = note
noteResizeData = {
startWidth: note.width,
startHeight: note.height,
startMouseX: e.clientX,
startMouseY: e.clientY,
container: container,
noteElement: noteElement,
}
noteElement.style.cursor = 'nw-resize'
e.preventDefault()
e.stopPropagation()
return
}
e.stopPropagation()
})
// Touch-based resize
container.addEventListener(
'touchstart',
function (e) {
if (e.touches.length !== 1) return
bringToFront()
const rect = container.getBoundingClientRect()
const touch = e.touches[0]
const x = touch.clientX - rect.left
const y = touch.clientY - rect.top
if (x > rect.width - 40 && y > rect.height - 40) {
isResizingNote = true
currentNote = note
noteResizeData = {
startWidth: note.width,
startHeight: note.height,
startTouchX: touch.clientX,
startTouchY: touch.clientY,
container: container,
noteElement: noteElement,
}
noteElement.style.cursor = 'nw-resize'
e.preventDefault()
e.stopPropagation()
}
},
{ passive: false },
)
// Mouse-based interaction (tap to focus vs drag to move)
let noteMouseData = null
const NOTE_DRAG_THRESHOLD = 5 // pixels
noteElement.addEventListener('mousedown', e => {
if (isResizingNote) return
// If already focused, let textarea handle mouse normally
if (noteElement.matches(':focus')) return
// Don't start interaction if clicking buttons
if (e.target === colorBtn || e.target === deleteBtn || colorPalette.contains(e.target)) {
return
}
// Start tracking the interaction
const rect = container.getBoundingClientRect()
noteMouseData = {
startX: e.clientX,
startY: e.clientY,
startTime: Date.now(),
dragOffset: {
x: e.clientX - rect.left,
y: e.clientY - rect.top,
},
container: container,
noteElement: noteElement,
wasFocused: noteElement.matches(':focus'),
hasMoved: false,
isDragging: false,
}
noteElement.style.userSelect = 'none'
e.preventDefault()
})
noteElement.addEventListener('mousemove', e => {
if (!noteMouseData) return
const deltaX = Math.abs(e.clientX - noteMouseData.startX)
const deltaY = Math.abs(e.clientY - noteMouseData.startY)
// If movement exceeds threshold and not already dragging, start drag
if (
(deltaX > NOTE_DRAG_THRESHOLD || deltaY > NOTE_DRAG_THRESHOLD) &&
!noteMouseData.isDragging
) {
noteMouseData.isDragging = true
noteMouseData.hasMoved = true
isDraggingNote = true
currentNote = note
noteDragData = {
hasMoved: true,
dragOffset: noteMouseData.dragOffset,
container: noteMouseData.container,
noteElement: noteMouseData.noteElement,
}