Repository navigation
Expand file tree
/
Copy pathproject_context.txt
More file actions
1780 lines (1746 loc) · 54.2 KB
/
Copy pathproject_context.txt
File metadata and controls
1780 lines (1746 loc) · 54.2 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
==============================
PROJECT STRUCTURE
==============================
./.env.example
./.eslintrc.cjs
./.gitignore
./ARCHITECTURE.md
./demo.gif
./demo.mov
./index.html
./package.json
./public/vite.svg
./README.md
./src/App.jsx
./src/app/router.jsx
./src/appwrite/config.js
./src/appwrite/databases.js
./src/assets/colors.json
./src/assets/fakeData.js
./src/assets/react.svg
./src/components/AddButton.jsx
./src/components/Color.jsx
./src/components/Controls.jsx
./src/components/DeleteButton.jsx
./src/components/NoteCard.jsx
./src/components/NotesBoard.jsx
./src/context/NotesContext.jsx
./src/icons/Plus.jsx
./src/icons/Spinner.jsx
./src/icons/Trash.jsx
./src/index.css
./src/main.jsx
./src/pages/LoginPage.jsx
./src/pages/NotesPage.jsx
./src/pages/NotFoundPage.jsx
./src/pages/SettingsPage.jsx
./src/services/notesService.js
./src/utils.js
./vite.config.js
==============================
FILE CONTENTS
==============================
============================================================
FILE: ./.env.example
============================================================
1 VITE_ENDPOINT=https://cloud.appwrite.io/v1
2 VITE_PROJECT_ID=
3 VITE_DATABASE_ID=
4 VITE_COLLECTION_NOTES_ID=
============================================================
FILE: ./.eslintrc.cjs
============================================================
1 module.exports = {
2 root: true,
3 env: { browser: true, es2020: true },
4 extends: [
5 'eslint:recommended',
6 'plugin:react/recommended',
7 'plugin:react/jsx-runtime',
8 'plugin:react-hooks/recommended',
9 ],
10 ignorePatterns: ['dist', '.eslintrc.cjs'],
11 parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
12 settings: { react: { version: '18.2' } },
13 plugins: ['react-refresh'],
14 rules: {
15 'react-refresh/only-export-components': [
16 'warn',
17 { allowConstantExport: true },
18 ],
19 },
20 }
============================================================
FILE: ./.gitignore
============================================================
1 # Logs
2 .env/
3 .env
4 logs
5 *.log
6 npm-debug.log*
7 yarn-debug.log*
8 yarn-error.log*
9 pnpm-debug.log*
10 lerna-debug.log*
11
12 node_modules
13 dist
14 dist-ssr
15 *.local
16
17 # Editor directories and files
18 .vscode/*
19 !.vscode/extensions.json
20 .idea
21 .DS_Store
22 *.suo
23 *.ntvs*
24 *.njsproj
25 *.sln
26 *.sw?
27 .vercel
28 .env*.local
============================================================
FILE: ./ARCHITECTURE.md
============================================================
1 # Snappy Notes Architecture
2
3 ## Stack
4
5 - React 18
6 - Vite
7 - React Router
8 - Appwrite
9 - Plain CSS
10
11 ## Routes
12
13 - `/` redirects to `/notes`
14 - `/notes` renders the notes workspace
15 - `/login` is reserved for authentication
16 - `/settings` is reserved for settings
17 - Unknown URLs render the not-found page
18
19 ## Responsibility boundaries
20
21 ### Router
22
23 `src/app/router.jsx` defines application routes.
24
25 ### Pages
26
27 Page components represent complete screens. Only the notes
28 route mounts `NotesProvider`, so ordinary pages do not fetch notes.
29
30 ### Notes context
31
32 `NotesContext.jsx` owns:
33
34 - Loaded notes
35 - Selected note ID
36 - Initial loading state
37 - Initial load errors
38 - Create, update, and delete actions
39
40 ### Notes service
41
42 `notesService.js` is the boundary between React and Appwrite.
43 UI components do not import the Appwrite database directly.
44
45 ### Notes board
46
47 `NotesBoard.jsx` owns the board layout. The dark grid and scrolling
48 belong to `.notes-board`, not to the root application element.
============================================================
FILE: ./index.html
============================================================
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5
6 <meta
7 name="viewport"
8 content="width=device-width, initial-scale=1.0"
9 />
10
11 <meta
12 name="theme-color"
13 content="#212228"
14 />
15
16 <title>Snappy Notes</title>
17 </head>
18
19 <body>
20 <div id="root"></div>
21 <script type="module" src="/src/main.jsx"></script>
22 </body>
23 </html>
============================================================
FILE: ./package.json
============================================================
1 {
2 "name": "snappy-notes",
3 "private": true,
4 "version": "0.0.0",
5 "type": "module",
6 "scripts": {
7 "dev": "vite",
8 "build": "vite build",
9 "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
10 "preview": "vite preview"
11 },
12 "dependencies": {
13 "appwrite": "^15.0.0",
14 "react": "^18.2.0",
15 "react-dom": "^18.2.0",
16 "react-router-dom": "^6.30.4"
17 },
18 "devDependencies": {
19 "@types/react": "^18.2.15",
20 "@types/react-dom": "^18.2.7",
21 "@vitejs/plugin-react": "^4.0.3",
22 "eslint": "^8.45.0",
23 "eslint-plugin-react": "^7.32.2",
24 "eslint-plugin-react-hooks": "^4.6.0",
25 "eslint-plugin-react-refresh": "^0.4.3",
26 "vite": "^4.4.5"
27 }
28 }
============================================================
FILE: ./README.md
============================================================
1 # Sticky Notes React
2
3 A modern, sticky notes application built with React, Vite, and Appwrite. Features a dynamic drag-and-drop interface, auto-saving capability, and real-time backend synchronization.
4
5 
6
7 ## Features
8
9 - **📠Create & Edit Notes**: Easily add new sticky notes and edit their content seamlessly.
10 - **💾 Auto-Saving**: Content changes are automatically saved to the Appwrite backend safely and securely.
11 - **ðŸ–±ï¸ Drag & Drop**: Organize your workspace by dragging notes anywhere on the screen. The position is persisted.
12 - **🎨 Dynamic Colors**: Each note gets assigned coordinated header and body colors for a polished look.
13 - **ðŸ—‘ï¸ Delete Notes**: intuitive controls to remove notes you no longer need.
14 - **âš¡ Fast & Reactive**: Built with Vite for lightning-fast development and production performance.
15
16 ## Tech Stack
17
18 - **Frontend**: [React](https://react.dev/)
19 - **Build Tool**: [Vite](https://vitejs.dev/)
20 - **Backend**: [Appwrite](https://appwrite.io/) (Database & API)
21 - **Icons**: Custom SVG Icons
22
23 ## Getting Started
24
25 Follow these steps to get the application running on your local machine.
26
27 ### Prerequisites
28
29 - [Node.js](https://nodejs.org/) (v16 or higher)
30 - An [Appwrite](https://appwrite.io/) account and project
31
32 ### Installation
33
34 1. **Clone the repository**
35
36 ```bash
37 git clone <repository-url>
38 cd NotesWithBackend
39 ```
40
41 2. **Install dependencies**
42
43 ```bash
44 npm install
45 ```
46
47 3. **Environment Configuration**
48 Create a `.env.local` file in the root directory. You can use `.env.example` as a reference. Add your Appwrite configuration keys:
49
50 ```properties
51 VITE_ENDPOINT="https://cloud.appwrite.io/v1"
52 VITE_PROJECT_ID="your_project_id"
53 VITE_DATABASE_ID="your_database_id"
54 VITE_COLLECTION_NOTES_ID="your_collection_id"
55 ```
56
57 4. **Run the application**
58
59 ```bash
60 npm run dev
61 ```
62
63 Open `http://localhost:5173` in your browser to view the app.
64
65 ## Documentation
66
67 For a detailed look at the project's architecture, data models, and directory structure, please refer to [ARCHITECTURE.md](./ARCHITECTURE.md).
68
69 ## Project Structure
70
71 - `src/appwrite`: Appwrite configuration and service setup.
72 - `src/components`: Reusable UI components (NoteCard, Controls, etc.).
73 - `src/context`: React Context for state management.
74 - `src/pages`: Main application pages.
75 - `src/utils.js`: Utility functions for logic like auto-grow and positioning.
76
77 ## Contributing
78
79 Contributions are welcome! Please feel free to submit a Pull Request.
============================================================
FILE: ./src/App.jsx
============================================================
1 import { RouterProvider } from "react-router-dom";
2 import router from "./app/router";
3
4 function App() {
5 return <RouterProvider router={router} />;
6 }
7
8 export default App;
============================================================
FILE: ./src/app/router.jsx
============================================================
1 import {
2 createBrowserRouter,
3 Navigate,
4 } from "react-router-dom";
5
6 import NotesProvider from "../context/NotesContext";
7 import NotesPage from "../pages/NotesPage";
8 import LoginPage from "../pages/LoginPage";
9 import SettingsPage from "../pages/SettingsPage";
10 import NotFoundPage from "../pages/NotFoundPage";
11
12 const router = createBrowserRouter([
13 {
14 path: "/",
15 element: <Navigate to="/notes" replace />,
16 },
17 {
18 path: "/notes",
19 element: (
20 <NotesProvider>
21 <NotesPage />
22 </NotesProvider>
23 ),
24 },
25 {
26 path: "/login",
27 element: <LoginPage />,
28 },
29 {
30 path: "/settings",
31 element: <SettingsPage />,
32 },
33 {
34 path: "*",
35 element: <NotFoundPage />,
36 },
37 ]);
38
39 export default router;
============================================================
FILE: ./src/appwrite/config.js
============================================================
1 import { Client, Databases, Account } from "appwrite";
2
3 const client = new Client()
4 .setEndpoint(import.meta.env.VITE_ENDPOINT)
5 .setProject(import.meta.env.VITE_PROJECT_ID);
6
7 const databases = new Databases(client);
8 const account = new Account(client);
9
10 export { client, databases, account };
============================================================
FILE: ./src/appwrite/databases.js
============================================================
1 import { databases } from "./config";
2 import { ID } from "appwrite";
3
4 const collections = [
5 {
6 name: "notes",
7 id: import.meta.env.VITE_COLLECTION_NOTES_ID,
8 },
9 ];
10
11 const db = {};
12
13 collections.forEach((collection) => {
14 db[collection.name] = {
15 create: async (payload, id = ID.unique()) => {
16 return await databases.createDocument(
17 import.meta.env.VITE_DATABASE_ID,
18 collection.id,
19 id,
20 payload
21 );
22 },
23 update: async (id, payload) => {
24 console.log("Updating:", id);
25 return await databases.updateDocument(
26 import.meta.env.VITE_DATABASE_ID,
27 collection.id,
28 id,
29 payload
30 );
31 },
32 delete: async (id) => {
33 return await databases.deleteDocument(
34 import.meta.env.VITE_DATABASE_ID,
35 collection.id,
36 id
37 );
38 },
39 get: async (id) => {
40 return await databases.getDocument(
41 import.meta.env.VITE_DATABASE_ID,
42 collection.id,
43 id
44 );
45 },
46 list: async (queries) => {
47 return await databases.listDocuments(
48 import.meta.env.VITE_DATABASE_ID,
49 collection.id,
50 queries
51 );
52 },
53 };
54 });
55
56 export { db };
============================================================
FILE: ./src/assets/colors.json
============================================================
1 [
2 {
3 "id":"color-yellow",
4 "colorHeader":"#FFEFBE",
5 "colorBody":"#FFF5DF",
6 "colorText":"#18181A"
7 },
8 {
9 "id":"color-green",
10 "colorHeader":"#AFDA9F",
11 "colorBody":"#BCDEAF",
12 "colorText":"#18181A"
13 },
14 {
15 "id":"color-blue",
16 "colorHeader":"#9BD1DE",
17 "colorBody":"#A6DCE9",
18 "colorText":"#18181A"
19 },
20 {
21 "id":"color-purple",
22 "colorHeader":"#FED0FD",
23 "colorBody":"#FEE5FD",
24 "colorText":"#18181A"
25 }
26 ]
============================================================
FILE: ./src/assets/fakeData.js
============================================================
1 export const fakeData = [
2 {
3 $id: 1,
4 body: JSON.stringify(
5 'Resources:\n- Book: "You Don\'t Know JS: Scope & Closures" by Kyle Simpson.\n\n- Online Course: "JavaScript Patterns" on Udemy.\n\n- Articles:\n"Understanding JavaScript Closures" on Medium.\n\n"Mastering JavaScript Modules" on Dev.to.'
6 ),
7 colors: JSON.stringify({
8 id: "color-purple",
9 colorHeader: "#FED0FD",
10 colorBody: "#FEE5FD",
11 colorText: "#18181A",
12 }),
13 position: JSON.stringify({ x: 505, y: 10 }),
14 },
15 {
16 $id: 2,
17 body: JSON.stringify(
18 'Resources:\n- Book: "You Don\'t Know JS: Scope & Closures" by Kyle Simpson.\n\n- Online Course: "JavaScript Patterns" on Udemy.\n\n- Articles:\n"Understanding JavaScript Closures" on Medium.\n\n"Mastering JavaScript Modules" on Dev.to.'
19 ),
20 colors: JSON.stringify({
21 id: "color-blue",
22 colorHeader: "#9BD1DE",
23 colorBody: "#A6DCE9",
24 colorText: "#18181A",
25 }),
26 position: JSON.stringify({ x: 305, y: 110 }),
27 },
28 {
29 $id: 3,
30 body: JSON.stringify(
31 'Resources:\n- Book: "You Don\'t Know JS: Scope & Closures" by Kyle Simpson.\n\n- Online Course: "JavaScript Patterns" on Udemy.\n\n- Articles:\n"Understanding JavaScript Closures" on Medium.\n\n"Mastering JavaScript Modules" on Dev.to.'
32 ),
33 colors: JSON.stringify({
34 id: "color-yellow",
35 colorHeader: "#FFEFBE",
36 colorBody: "#FFF5DF",
37 colorText: "#18181A",
38 }),
39 position: JSON.stringify({ x: 605, y: 500 }),
40 },
41 ];
============================================================
FILE: ./src/components/AddButton.jsx
============================================================
1 import { useRef, useState } from "react";
2
3 import Plus from "../icons/Plus";
4 import colors from "../assets/colors.json";
5 import { useNotes } from "../context/NotesContext";
6
7 const AddButton = () => {
8 const { createNote } = useNotes();
9 const startingPosition = useRef(10);
10 const [creating, setCreating] = useState(false);
11
12 const addNote = async () => {
13 if (creating) {
14 return;
15 }
16
17 const payload = {
18 body: JSON.stringify(""),
19 position: JSON.stringify({
20 x: startingPosition.current,
21 y: startingPosition.current,
22 }),
23 colors: JSON.stringify(colors[0]),
24 };
25
26 setCreating(true);
27
28 try {
29 await createNote(payload);
30 startingPosition.current += 10;
31 } catch (error) {
32 console.error("Failed to create note:", error);
33 alert("The note could not be created.");
34 } finally {
35 setCreating(false);
36 }
37 };
38
39 return (
40 <button
41 id="add-btn"
42 type="button"
43 aria-label="Add note"
44 disabled={creating}
45 onClick={addNote}
46 >
47 <Plus />
48 </button>
49 );
50 };
51
52 export default AddButton;
============================================================
FILE: ./src/components/Color.jsx
============================================================
1 import { useState } from "react";
2
3 import { useNotes } from "../context/NotesContext";
4
5 const Color = ({ color }) => {
6 const { selectedNoteId, updateNote } = useNotes();
7 const [updating, setUpdating] = useState(false);
8
9 const changeColor = async () => {
10 if (!selectedNoteId) {
11 alert("Select a note before changing its colour.");
12 return;
13 }
14
15 if (updating) {
16 return;
17 }
18
19 setUpdating(true);
20
21 try {
22 await updateNote(selectedNoteId, {
23 colors: JSON.stringify(color),
24 });
25 } catch (error) {
26 console.error("Failed to update note colour:", error);
27 alert("The note colour could not be changed.");
28 } finally {
29 setUpdating(false);
30 }
31 };
32
33 return (
34 <button
35 type="button"
36 className="color"
37 aria-label={`Use ${color.id}`}
38 title={color.id}
39 disabled={updating}
40 onClick={changeColor}
41 style={{
42 backgroundColor: color.colorHeader,
43 }}
44 />
45 );
46 };
47
48 export default Color;
============================================================
FILE: ./src/components/Controls.jsx
============================================================
1 import AddButton from "./AddButton";
2 import Color from "./Color";
3 import colors from "../assets/colors.json";
4
5 const Controls = () => {
6 return (
7 <aside id="controls" aria-label="Note controls">
8 <AddButton />
9
10 {colors.map((color) => (
11 <Color key={color.id} color={color} />
12 ))}
13 </aside>
14 );
15 };
16
17 export default Controls;
============================================================
FILE: ./src/components/DeleteButton.jsx
============================================================
1 import { useState } from "react";
2
3 import Trash from "../icons/Trash";
4 import { useNotes } from "../context/NotesContext";
5
6 const DeleteButton = ({ noteId }) => {
7 const { deleteNote } = useNotes();
8 const [deleting, setDeleting] = useState(false);
9
10 const handleDelete = async (event) => {
11 event.stopPropagation();
12
13 if (deleting) {
14 return;
15 }
16
17 setDeleting(true);
18
19 try {
20 await deleteNote(noteId);
21 } catch (error) {
22 console.error("Failed to delete note:", error);
23 alert("The note could not be deleted.");
24 setDeleting(false);
25 }
26 };
27
28 return (
29 <button
30 type="button"
31 className="icon-button"
32 aria-label="Delete note"
33 disabled={deleting}
34 onMouseDown={(event) => event.stopPropagation()}
35 onClick={handleDelete}
36 >
37 <Trash />
38 </button>
39 );
40 };
41
42 export default DeleteButton;
============================================================
FILE: ./src/components/NoteCard.jsx
============================================================
1 import {
2 useEffect,
3 useRef,
4 useState,
5 } from "react";
6
7 import DeleteButton from "./DeleteButton";
8 import Spinner from "../icons/Spinner";
9 import {
10 autoGrow,
11 bodyParser,
12 parseStoredJson,
13 setNewOffset,
14 setZIndex,
15 } from "../utils";
16 import { useNotes } from "../context/NotesContext";
17
18 const DEFAULT_POSITION = {
19 x: 10,
20 y: 10,
21 };
22
23 const DEFAULT_COLORS = {
24 colorHeader: "#FFEFBE",
25 colorBody: "#FFF5DF",
26 colorText: "#18181A",
27 };
28
29 const NoteCard = ({ note }) => {
30 const { setSelectedNoteId, updateNote } = useNotes();
31
32 const cardRef = useRef(null);
33 const textAreaRef = useRef(null);
34 const saveTimerRef = useRef(null);
35 const mouseStartPosition = useRef({
36 x: 0,
37 y: 0,
38 });
39
40 const [saving, setSaving] = useState(false);
41
42 const [position, setPosition] = useState(() =>
43 parseStoredJson(note.position, DEFAULT_POSITION)
44 );
45
46 const colors = parseStoredJson(
47 note.colors,
48 DEFAULT_COLORS
49 );
50
51 const body = bodyParser(note.body);
52
53 useEffect(() => {
54 autoGrow(textAreaRef);
55 setZIndex(cardRef.current);
56
57 return () => {
58 if (saveTimerRef.current) {
59 clearTimeout(saveTimerRef.current);
60 }
61 };
62 }, []);
63
64 const saveData = async (key, value) => {
65 await updateNote(note.$id, {
66 [key]: JSON.stringify(value),
67 });
68 };
69
70 const handleMouseMove = (event) => {
71 event.preventDefault();
72
73 const mouseMovement = {
74 x: mouseStartPosition.current.x - event.clientX,
75 y: mouseStartPosition.current.y - event.clientY,
76 };
77
78 mouseStartPosition.current = {
79 x: event.clientX,
80 y: event.clientY,
81 };
82
83 const nextPosition = setNewOffset(
84 cardRef.current,
85 mouseMovement
86 );
87
88 setPosition(nextPosition);
89 };
90
91 const handleMouseUp = () => {
92 document.removeEventListener(
93 "mousemove",
94 handleMouseMove
95 );
96
97 document.removeEventListener(
98 "mouseup",
99 handleMouseUp
100 );
101
102 const nextPosition = setNewOffset(cardRef.current);
103
104 void saveData("position", nextPosition).catch((error) => {
105 console.error("Failed to save note position:", error);
106 });
107 };
108
109 const handleMouseDown = (event) => {
110 if (event.button !== 0) {
111 return;
112 }
113
114 mouseStartPosition.current = {
115 x: event.clientX,
116 y: event.clientY,
117 };
118
119 setSelectedNoteId(note.$id);
120 setZIndex(cardRef.current);
121
122 document.addEventListener(
123 "mousemove",
124 handleMouseMove
125 );
126
127 document.addEventListener(
128 "mouseup",
129 handleMouseUp
130 );
131 };
132
133 const handleInput = () => {
134 autoGrow(textAreaRef);
135 setSaving(true);
136
137 if (saveTimerRef.current) {
138 clearTimeout(saveTimerRef.current);
139 }
140
141 saveTimerRef.current = setTimeout(
142 async () => {
143 try {
144 await saveData(
145 "body",
146 textAreaRef.current.value
147 );
148 } catch (error) {
149 console.error(
150 "Failed to save note body:",
151 error
152 );
153 } finally {
154 setSaving(false);
155 }
156 },
157 1200
158 );
159 };
160
161 return (
162 <article
163 ref={cardRef}
164 className="card"
165 style={{
166 left: `${position.x}px`,
167 top: `${position.y}px`,
168 backgroundColor: colors.colorBody,
169 }}
170 >
171 <header
172 className="card-header"
173 onMouseDown={handleMouseDown}
174 style={{
175 backgroundColor: colors.colorHeader,
176 }}
177 >
178 <DeleteButton noteId={note.$id} />
179
180 {saving && (
181 <div className="card-saving">
182 <Spinner color={colors.colorText} />
183 <span style={{ color: colors.colorText }}>
184 Saving...
185 </span>
186 </div>
187 )}
188 </header>
189
190 <div className="card-body">
191 <textarea
192 ref={textAreaRef}
193 defaultValue={body}
194 aria-label="Note body"
195 onFocus={() => {
196 setZIndex(cardRef.current);
197 setSelectedNoteId(note.$id);
198 }}
199 onInput={handleInput}
200 style={{
201 color: colors.colorText,
202 }}
203 />
204 </div>
205 </article>
206 );
207 };
208
209 export default NoteCard;
============================================================
FILE: ./src/components/NotesBoard.jsx
============================================================
1 import { Link } from "react-router-dom";
2
3 import Controls from "./Controls";
4 import NoteCard from "./NoteCard";
5 import { useNotes } from "../context/NotesContext";
6
7 const NotesBoard = () => {
8 const { notes } = useNotes();
9
10 return (
11 <main className="notes-board">
12 <nav className="board-navigation">
13 <Link to="/notes">Notes</Link>
14 <Link to="/settings">Settings</Link>
15 </nav>
16
17 {notes.length === 0 && (
18 <div className="empty-board-message">
19 <strong>No notes yet</strong>
20 <span>Use the plus button to create one.</span>
21 </div>
22 )}
23
24 {notes.map((note) => (
25 <NoteCard key={note.$id} note={note} />
26 ))}
27
28 <Controls />
29 </main>
30 );
31 };
32
33 export default NotesBoard;
============================================================
FILE: ./src/context/NotesContext.jsx
============================================================
1 import {
2 createContext,
3 useCallback,
4 useContext,
5 useEffect,
6 useMemo,
7 useState,
8 } from "react";
9
10 import Spinner from "../icons/Spinner";
11 import { notesService } from "../services/notesService";
12
13 export const NotesContext = createContext(null);
14
15 export const useNotes = () => {
16 const context = useContext(NotesContext);
17
18 if (!context) {
19 throw new Error("useNotes must be used inside NotesProvider");
20 }
21
22 return context;
23 };
24
25 const NotesProvider = ({ children }) => {
26 const [notes, setNotes] = useState([]);
27 const [selectedNoteId, setSelectedNoteId] = useState(null);
28 const [loading, setLoading] = useState(true);
29 const [loadError, setLoadError] = useState(null);
30
31 const loadNotes = useCallback(async () => {
32 setLoading(true);
33 setLoadError(null);
34
35 try {
36 const loadedNotes = await notesService.list();
37 setNotes(loadedNotes);
38 } catch (error) {
39 console.error("Failed to load notes:", error);
40 setLoadError(error);
41 } finally {
42 setLoading(false);
43 }
44 }, []);
45
46 useEffect(() => {
47 void loadNotes();
48 }, [loadNotes]);
49
50 const createNote = useCallback(async (payload) => {
51 const createdNote = await notesService.create(payload);
52
53 setNotes((currentNotes) => [
54 createdNote,
55 ...currentNotes,
56 ]);
57
58 return createdNote;
59 }, []);
60
61 const updateNote = useCallback(async (id, payload) => {
62 const updatedNote = await notesService.update(id, payload);
63
64 setNotes((currentNotes) =>
65 currentNotes.map((note) =>