File size: 14,249 Bytes
28e7a2d
 
 
ad712b8
6878c32
97ec167
ad712b8
 
97ec167
 
 
 
28e7a2d
ad712b8
 
 
496c2ca
97ec167
fe025eb
 
496c2ca
 
 
 
fe025eb
496c2ca
cdad520
 
 
ad712b8
 
0ca929b
cfbdb4e
0ca929b
 
d24c82d
0ca929b
 
496c2ca
0ca929b
496c2ca
 
cdad520
ad712b8
 
 
0ca929b
59569e0
0ca929b
fe025eb
59569e0
 
 
cdad520
fe025eb
cdad520
 
496c2ca
cdad520
 
59569e0
6878c32
ad712b8
 
496c2ca
989ba3c
 
cfbdb4e
 
989ba3c
fe025eb
f0c8ad1
 
 
 
 
 
 
 
989ba3c
 
0ca929b
989ba3c
cfbdb4e
fe025eb
 
 
cfbdb4e
 
fe025eb
0ca929b
cfbdb4e
 
 
0ca929b
 
 
 
496c2ca
 
 
989ba3c
496c2ca
 
bafc7d2
496c2ca
cdad520
989ba3c
 
 
 
 
 
 
 
 
0ca929b
 
 
 
 
 
 
 
fe025eb
 
 
 
 
 
 
0ca929b
 
 
 
cfbdb4e
fe025eb
 
 
cfbdb4e
 
0ca929b
 
fe025eb
0ca929b
cfbdb4e
 
0ca929b
 
 
 
 
496c2ca
fe025eb
 
 
 
 
 
 
 
d6e6711
 
 
496c2ca
fe025eb
d6e6711
fe025eb
 
 
496c2ca
d6e6711
 
496c2ca
fe025eb
 
 
 
 
 
 
 
 
 
 
 
 
 
496c2ca
 
fe025eb
 
496c2ca
fe025eb
496c2ca
fe025eb
 
 
 
496c2ca
 
 
 
fe025eb
 
 
 
496c2ca
0ca929b
fe025eb
496c2ca
 
fe025eb
 
 
496c2ca
550f82a
 
 
 
 
 
 
fe025eb
 
550f82a
 
fe025eb
 
 
550f82a
 
fe025eb
 
 
 
 
550f82a
 
fe025eb
550f82a
 
fe025eb
550f82a
989ba3c
496c2ca
fe025eb
 
 
496c2ca
 
 
 
 
bafc7d2
fe025eb
 
 
 
 
 
 
496c2ca
 
 
fe025eb
496c2ca
 
 
 
fe025eb
 
 
bafc7d2
496c2ca
 
 
fe025eb
989ba3c
fe025eb
 
bafc7d2
496c2ca
 
 
fe025eb
496c2ca
 
fe025eb
 
 
0ca929b
fe025eb
 
 
 
97ec167
496c2ca
28e7a2d
fb023d4
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
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover" />
  <title>NoteSync - Shared Tasks & Notes</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>

  <!-- PWA Manifest -->
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#3B82F6">
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 min-h-screen flex flex-col">

  <!-- Header -->
  <header class="p-4 bg-white dark:bg-gray-800 shadow-md flex flex-col gap-2 sticky top-0 z-10 safe-area-top">
    <h1 class="text-2xl font-bold bg-gradient-to-r from-blue-500 to-purple-600 bg-clip-text text-transparent">NoteSync</h1>
    
    <!-- Tabs -->
    <div class="flex gap-2">
      <button id="tab-tasks" class="flex-1 py-2 rounded-lg bg-blue-500 text-white font-semibold hover:opacity-90 transition">Tasks</button>
      <button id="tab-notes" class="flex-1 py-2 rounded-lg bg-gray-300 dark:bg-gray-700 text-gray-800 dark:text-gray-100 font-semibold hover:opacity-90 transition">Notes</button>
    </div>

    <span id="connection-status" class="flex items-center gap-2 text-sm px-3 py-1 rounded-full bg-gray-100 dark:bg-gray-700 w-max">
      <span class="w-2 h-2 rounded-full bg-gray-400"></span>
      <span>Connecting...</span>
    </span>
  </header>

  <!-- Login Form -->
  <div id="login-container" class="max-w-md mx-auto p-4 mt-4 bg-white dark:bg-gray-800 rounded-lg shadow-md invisible">
    <input id="email" type="email" placeholder="Email" class="w-full p-3 mb-2 rounded-lg bg-gray-100 dark:bg-gray-700 border-none outline-none" />
    <input id="password" type="password" placeholder="Password" class="w-full p-3 mb-2 rounded-lg bg-gray-100 dark:bg-gray-700 border-none outline-none" />
    <button id="login-btn" class="w-full py-3 bg-blue-500 text-white rounded-lg hover:opacity-90 transition">Login</button>
  </div>

  <!-- Content -->
  <main id="main-content" class="flex-1 p-4 max-w-2xl w-full mx-auto hidden">
    <ul id="items-list" class="space-y-3">
      <!-- Tasks or Notes will be loaded here -->
    </ul>
  </main>

  <!-- Input -->
  <footer id="footer-input" class="p-4 bg-white dark:bg-gray-800 shadow-md sticky bottom-0 safe-area-bottom hidden">
    <div class="max-w-2xl mx-auto">
      <div class="flex mb-2" id="name-input-container" style="display:none;">
        <input id="user-name" type="text" placeholder="Your name" 
               class="flex-1 p-3 rounded-lg bg-gray-100 dark:bg-gray-700 border-none outline-none focus:ring-2 focus:ring-blue-500 transition text-base"
               autocomplete="name" autocorrect="off" spellcheck="false" />
      </div>
      <div class="flex">
        <input id="item-input" type="text" placeholder="Write something..." 
               class="flex-1 p-3 rounded-l-lg bg-gray-100 dark:bg-gray-700 border-none outline-none focus:ring-2 focus:ring-blue-500 transition text-base"
               autocomplete="off" autocorrect="off" spellcheck="false" />
        <button id="add-item" class="px-6 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-r-lg hover:opacity-90 transition active:scale-95">
          <i data-feather="plus" class="w-5 h-5"></i>
        </button>
      </div>
    </div>
  </footer>

  <!-- Firebase & Script -->
  <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
    import { getFirestore, collection, addDoc, onSnapshot, serverTimestamp, orderBy, doc, deleteDoc, updateDoc, where, query, enableIndexedDbPersistence } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";
    import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, onAuthStateChanged, setPersistence, browserLocalPersistence } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";

    // Firebase config
    const firebaseConfig = {
      apiKey: "AIzaSyBB4nUHIYHAxzXbRBslGf9nAuqbTNBcslw",
      authDomain: "mynotes-3a0a3.firebaseapp.com",
      projectId: "mynotes-3a0a3",
      storageBucket: "mynotes-3a0a3.firebasestorage.app",
      messagingSenderId: "168872894321",
      appId: "1:168872894321:web:81be345db5143cf1f2a0d0"
    };
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);
    const auth = getAuth(app);

    // Enable offline persistence
    enableIndexedDbPersistence(db)
      .then(() => console.log("Firebase offline persistence enabled"))
      .catch(err => {
        if (err.code === 'failed-precondition') console.warn("Multiple tabs open, persistence only in one tab.");
        else if (err.code === 'unimplemented') console.warn("Persistence not available in this browser.");
      });

    // Ensure Auth persistence (remember me)
    setPersistence(auth, browserLocalPersistence).catch(err => console.error("Persistence error:", err));

    // DOM elements
    const loginContainer = document.getElementById('login-container');
    const mainContent = document.getElementById('main-content');
    const footerInput = document.getElementById('footer-input');
    const itemsList = document.getElementById('items-list');
    const itemInput = document.getElementById('item-input');
    const addItemBtn = document.getElementById('add-item');
    const connectionStatus = document.getElementById('connection-status');
    const tabTasks = document.getElementById('tab-tasks');
    const tabNotes = document.getElementById('tab-notes');
    let currentTab = 'tasks';

    // Connection status
    function setStatus(online) {
      connectionStatus.innerHTML = online
        ? `<span class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span><span>Connected</span>`
        : `<span class="w-2 h-2 rounded-full bg-red-500"></span><span>Offline</span>`;
    }
    window.addEventListener("online", () => setStatus(true));
    window.addEventListener("offline", () => setStatus(false));
    setStatus(navigator.onLine);

    // Login
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const loginBtn = document.getElementById('login-btn');

    loginBtn.addEventListener('click', async () => {
      const email = emailInput.value.trim();
      const password = passwordInput.value.trim();
      if (!email || !password) return;
      try {
        await signInWithEmailAndPassword(auth, email, password);
      } catch (err) {
        if (err.code === 'auth/user-not-found') {
          try { await createUserWithEmailAndPassword(auth, email, password); }
          catch (err2) { console.error(err2); alert(err2.message); }
        } else { console.error(err); alert(err.message); }
      }
    });

    // Auth state handling (no flashing)
    onAuthStateChanged(auth, user => {
      if (user) {
        console.log("Logged in as", user.email);
        loginContainer.classList.add('hidden');
        loginContainer.classList.remove('invisible');
        mainContent.classList.remove('hidden');
        footerInput.classList.remove('hidden');
        loadItems(currentTab);
      } else {
        loginContainer.classList.remove('hidden');
        loginContainer.classList.remove('invisible');
        mainContent.classList.add('hidden');
        footerInput.classList.add('hidden');
      }
    });

    // Add item
    async function addItem() {
      const text = itemInput.value.trim();
      const user = auth.currentUser;
      const userName = user ? user.email : 'Anonymous';
      if (!text) return;

      try {
        await addDoc(collection(db, "notes"), {
          text,
          userName,
          createdAt: serverTimestamp(),
          type: currentTab,
          done: currentTab === 'tasks' ? false : null
        });
        itemInput.value = '';
      } catch (err) {
        console.error("Error adding item:", err);
        alert("Failed to add item.");
      }
    }
    addItemBtn.addEventListener('click', addItem);
    itemInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') addItem(); });

    // Render item (tasks & notes)
    function renderItem(item) {
      const li = document.createElement("li");
      li.className = "note-item flex items-center justify-between p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm hover:shadow-md transition-all group";

      let dateText = "";
      if (item.createdAt && item.createdAt.toDate) {
        const d = item.createdAt.toDate();
        const day = String(d.getDate()).padStart(2, "0");
        const month = String(d.getMonth() + 1).padStart(2, "0");
        const year = d.getFullYear();
        dateText = `${day}-${month}-${year}`;
      }

      if (item.type === 'tasks') {
        li.innerHTML = `
          <div class="flex items-center flex-1">
            <input type="checkbox" class="done-checkbox w-5 h-5 mr-3 rounded border-gray-300 text-blue-600 focus:ring-blue-500" ${item.done ? "checked" : ""}>
            <div class="w-[calc(100%-2rem)]">
              <span class="note-text ${item.done ? "line-through text-gray-400 dark:text-gray-500" : ""}">${item.text}</span>
              <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                Added by ${item.userName || 'Anonymous'} on ${dateText || '...'}
              </div>
            </div>
          </div>
          <button class="delete-btn p-2 text-red-500 hover:bg-red-50 dark:hover:bg-gray-700 rounded-full opacity-100 md:opacity-0 md:group-hover:opacity-100 transition active:scale-95">
            <i data-feather="trash-2" class="w-4 h-4"></i>
          </button>`;
        li.querySelector(".done-checkbox").addEventListener("change", async (e) => {
          try { await updateDoc(doc(db, "notes", item.id), { done: e.target.checked }); }
          catch (err) { console.error("Error updating task:", err); }
        });
      } else {
        li.innerHTML = `
          <div class="flex-1">
            <span class="note-text">${item.text}</span>
            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
              Added by ${item.userName || 'Anonymous'} on ${dateText || '...'}
            </div>
          </div>
          <div class="flex gap-2">
            <button class="edit-btn p-2 text-blue-500 hover:bg-blue-50 dark:hover:bg-gray-700 rounded-full transition active:scale-95">
              <i data-feather="edit-3" class="w-4 h-4"></i>
            </button>
            <button class="delete-btn p-2 text-red-500 hover:bg-red-50 dark:hover:bg-gray-700 rounded-full transition active:scale-95">
              <i data-feather="trash-2" class="w-4 h-4"></i>
            </button>
          </div>`;
        li.querySelector(".edit-btn").addEventListener("click", () => {
          const textSpan = li.querySelector(".note-text");
          const input = document.createElement("input");
          input.type = "text";
          input.value = textSpan.textContent;
          input.className = "w-full p-1 rounded bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500";
          textSpan.replaceWith(input);
          input.focus();
          const saveEdit = async () => {
            const newText = input.value.trim();
            if (newText && newText !== item.text) {
              try { await updateDoc(doc(db, "notes", item.id), { text: newText }); }
              catch (err) { console.error("Error updating note:", err); }
            }
            input.replaceWith(textSpan);
            textSpan.textContent = newText || item.text;
          };
          input.addEventListener("blur", saveEdit);
          input.addEventListener("keypress", (e) => { if (e.key === "Enter") saveEdit(); });
        });
      }

      li.querySelector(".delete-btn").addEventListener("click", async () => {
        try { await deleteDoc(doc(db, "notes", item.id)); }
        catch (err) { console.error("Error deleting item:", err); }
      });

      itemsList.appendChild(li);
    }

    // Load items
    function loadItems(type) {
      itemsList.innerHTML = '<div class="text-center py-8"><div class="inline-block animate-spin h-8 w-8 border-t-2 border-b-2 border-blue-500 rounded-full"></div><p class="mt-2 text-gray-500">Loading...</p></div>';
      const q = query(collection(db, "notes"), where("type","==",type), orderBy("createdAt","asc"));
      onSnapshot(q, (snapshot) => {
        itemsList.innerHTML = "";
        if (snapshot.empty) {
          itemsList.innerHTML = `<div class="text-center py-8"><i data-feather="check-circle" class="w-12 h-12 mx-auto text-gray-400"></i><p class="mt-2 text-gray-500">No ${type} yet.</p></div>`;
          feather.replace();
          return;
        }
        snapshot.forEach(docSnap => renderItem({ id: docSnap.id, ...docSnap.data() }));
        feather.replace();
      });
    }

    // Tab switching
    tabTasks.addEventListener('click', () => {
      currentTab = 'tasks';
      tabTasks.classList.add('bg-blue-500','text-white');
      tabTasks.classList.remove('bg-gray-300','dark:bg-gray-700','text-gray-800','dark:text-gray-100');
      tabNotes.classList.add('bg-gray-300','dark:bg-gray-700','text-gray-800','dark:text-gray-100');
      tabNotes.classList.remove('bg-blue-500','text-white');
      loadItems(currentTab);
    });
    tabNotes.addEventListener('click', () => {
      currentTab = 'notes';
      tabNotes.classList.add('bg-blue-500','text-white');
      tabNotes.classList.remove('bg-gray-300','dark:bg-gray-700','text-gray-800','dark:text-gray-100');
      tabTasks.classList.add('bg-gray-300','dark:bg-gray-700','text-gray-800','dark:text-gray-100');
      tabTasks.classList.remove('bg-blue-500','text-white');
      loadItems(currentTab);
    });

    // Default tab
    loadItems(currentTab);

    // PWA service worker
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('sw.js')
        .then(() => console.log('Service Worker Registered'))
        .catch(err => console.error('Service Worker registration failed:', err));
    }
  </script>
</body>
</html>