rotas no back
This commit is contained in:
74
web/app.js
74
web/app.js
@@ -99,6 +99,7 @@ const API_BASE = "api";
|
||||
let authUser = null;
|
||||
let syncTimer = null;
|
||||
let pendingCloudData = null;
|
||||
let applyingCloudData = false;
|
||||
|
||||
// Drag & Drop
|
||||
let draggedShortcutId = null;
|
||||
@@ -251,6 +252,9 @@ function saveState() {
|
||||
console.warn("Falha ao salvar dados locais:", err);
|
||||
}
|
||||
try { updateTasksBadge(); } catch (e) {}
|
||||
// Mantém localStorage como cópia offline, mas trata a nuvem como fonte
|
||||
// principal sempre que houver uma sessão autenticada.
|
||||
if (authUser && !applyingCloudData) scheduleSync();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------
|
||||
@@ -1452,16 +1456,17 @@ window.addEventListener("DOMContentLoaded", () => {
|
||||
});
|
||||
|
||||
// Widget de Calendário Integrado ao Relógio / Saudação
|
||||
const clockTrigger = document.getElementById("clock-calendar-trigger");
|
||||
clockTrigger.addEventListener("click", (e) => {
|
||||
if (e.target.id === "user-display-name") {
|
||||
document.querySelectorAll("#clock-calendar-trigger, #clock-calendar-sidebar-trigger").forEach(clockTrigger => {
|
||||
clockTrigger.addEventListener("click", (e) => {
|
||||
if (e.target.id === "user-display-name") {
|
||||
e.stopPropagation();
|
||||
openSettingsModal();
|
||||
document.getElementById("setting-user-name").focus();
|
||||
return;
|
||||
}
|
||||
e.stopPropagation();
|
||||
openSettingsModal();
|
||||
document.getElementById("setting-user-name").focus();
|
||||
return;
|
||||
}
|
||||
e.stopPropagation();
|
||||
toggleCalendarWidget();
|
||||
toggleCalendarWidget();
|
||||
});
|
||||
});
|
||||
|
||||
// Navegação do Calendário
|
||||
@@ -2176,7 +2181,7 @@ async function checkAuth() {
|
||||
if (data.logged) {
|
||||
authUser = data;
|
||||
updateSyncUI();
|
||||
pullSync();
|
||||
await pullSync();
|
||||
} else {
|
||||
authUser = null;
|
||||
updateSyncUI();
|
||||
@@ -2214,33 +2219,53 @@ function updateSyncUI() {
|
||||
}
|
||||
|
||||
async function pushSync() {
|
||||
if (!authUser) return;
|
||||
if (!authUser) return false;
|
||||
try {
|
||||
await fetch(API_BASE + "/sync", {
|
||||
const res = await fetch(API_BASE + "/sync", {
|
||||
method: "PUT",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ data: state, version: Date.now() })
|
||||
});
|
||||
if (!res.ok) throw new Error(`sync upload failed: ${res.status}`);
|
||||
const badge = document.getElementById("sync-badge");
|
||||
if (badge) {
|
||||
badge.innerText = "Sincronizado";
|
||||
badge.classList.remove("hidden");
|
||||
}
|
||||
} catch (e) {}
|
||||
return true;
|
||||
} catch (e) {
|
||||
const badge = document.getElementById("sync-badge");
|
||||
if (badge) {
|
||||
badge.innerText = "Pendente";
|
||||
badge.classList.remove("hidden");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pullSync() {
|
||||
if (!authUser) return;
|
||||
if (!authUser) return false;
|
||||
try {
|
||||
const res = await fetch(API_BASE + "/sync", { credentials: "include" });
|
||||
if (!res.ok) throw new Error(`sync download failed: ${res.status}`);
|
||||
const json = await res.json();
|
||||
if (json.data) {
|
||||
pendingCloudData = json.data;
|
||||
const m = document.getElementById("modal-sync-merge");
|
||||
if (m) m.classList.remove("hidden");
|
||||
// Para uma conta conectada, os dados online prevalecem sobre a cópia local.
|
||||
applyCloudData(json.data);
|
||||
} else {
|
||||
// Conta nova: preserva os dados locais existentes ao criar a cópia online.
|
||||
if (!await pushSync()) return false;
|
||||
}
|
||||
} catch (e) {}
|
||||
return true;
|
||||
} catch (e) {
|
||||
const badge = document.getElementById("sync-badge");
|
||||
if (badge) {
|
||||
badge.innerText = "Offline";
|
||||
badge.classList.remove("hidden");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function applyCloudData(data) {
|
||||
@@ -2249,7 +2274,9 @@ function applyCloudData(data) {
|
||||
if (!Array.isArray(state.categories) || state.categories.length === 0) {
|
||||
state.categories = [...DEFAULT_CONFIG.categories];
|
||||
}
|
||||
applyingCloudData = true;
|
||||
saveState();
|
||||
applyingCloudData = false;
|
||||
applyAllSettings();
|
||||
renderTabs();
|
||||
renderShortcuts();
|
||||
@@ -2257,6 +2284,7 @@ function applyCloudData(data) {
|
||||
if (document.getElementById("modal-sync-merge")) document.getElementById("modal-sync-merge").classList.add("hidden");
|
||||
showToast("Dados da nuvem aplicados!", "cloud");
|
||||
} catch (e) {
|
||||
applyingCloudData = false;
|
||||
showToast("Erro ao aplicar dados da nuvem", "alert-circle");
|
||||
}
|
||||
}
|
||||
@@ -2318,7 +2346,6 @@ function closeAuthModal() {
|
||||
closeAuthModal();
|
||||
await checkAuth();
|
||||
showToast("Logado com sucesso!", "log-in");
|
||||
pullSync();
|
||||
} catch (ex) {
|
||||
errEl.innerText = "Erro de conexão";
|
||||
errEl.classList.remove("hidden");
|
||||
@@ -2348,7 +2375,6 @@ function closeAuthModal() {
|
||||
closeAuthModal();
|
||||
await checkAuth();
|
||||
showToast("Conta criada e logada!", "user-plus");
|
||||
scheduleSync();
|
||||
} catch (ex) {
|
||||
errEl.innerText = "Erro de conexão";
|
||||
errEl.classList.remove("hidden");
|
||||
@@ -2367,8 +2393,8 @@ function closeAuthModal() {
|
||||
document.getElementById("btn-sync-now")?.addEventListener("click", async () => {
|
||||
if (!authUser) return;
|
||||
showToast("Sincronizando...", "refresh-cw");
|
||||
await pushSync();
|
||||
showToast("Sincronização enviada!", "cloud");
|
||||
const synced = await pullSync();
|
||||
showToast(synced ? "Sincronização concluída!" : "Não foi possível sincronizar", synced ? "cloud" : "alert-circle");
|
||||
});
|
||||
|
||||
document.getElementById("modal-sync-merge")?.addEventListener("click", (e) => {
|
||||
@@ -2385,8 +2411,8 @@ function closeAuthModal() {
|
||||
document.getElementById("btn-sync-upload")?.addEventListener("click", async () => {
|
||||
document.getElementById("modal-sync-merge").classList.add("hidden");
|
||||
showToast("Enviando dados locais...", "upload-cloud");
|
||||
await pushSync();
|
||||
showToast("Dados enviados para a nuvem!", "cloud");
|
||||
const synced = await pushSync();
|
||||
showToast(synced ? "Dados enviados para a nuvem!" : "Não foi possível sincronizar", synced ? "cloud" : "alert-circle");
|
||||
});
|
||||
|
||||
checkAuth();
|
||||
|
||||
@@ -80,8 +80,8 @@
|
||||
</div>
|
||||
|
||||
<!-- Sidebar Lateral Direita (desktop) e Barra Inferior (mobile) -->
|
||||
<aside id="app-sidebar" class="fixed right-0 top-auto bottom-0 w-full h-12 z-600 flex flex-row items-center justify-center px-2 gap-2 border-t border-white/10 sm:top-0 sm:bottom-0 sm:right-0 sm:left-auto sm:w-12 sm:h-auto sm:flex-col sm:justify-start sm:pt-4 sm:pb-4 sm:border-t-0 sm:border-l sm:border-white/10 sm:border-r-0">
|
||||
<button id="clock-calendar-trigger" title="Calendário" aria-label="Abrir Calendário" class="sidebar-btn relative group">
|
||||
<aside id="app-sidebar" class="fixed right-0 top-auto bottom-0 w-full h-12 z-50 flex flex-row items-center justify-center px-2 gap-2 border-t border-white/10 sm:top-0 sm:bottom-0 sm:right-0 sm:left-auto sm:w-12 sm:h-auto sm:flex-col sm:justify-start sm:pt-4 sm:pb-4 sm:border-t-0 sm:border-l sm:border-white/10 sm:border-r-0">
|
||||
<button id="clock-calendar-sidebar-trigger" title="Calendário" aria-label="Abrir Calendário" class="sidebar-btn relative group">
|
||||
<i data-lucide="calendar" class="w-6 h-6"></i>
|
||||
</button>
|
||||
<button id="btn-open-tasks" title="Tarefas" aria-label="Abrir Tarefas" class="sidebar-btn relative group">
|
||||
|
||||
25
web/sw.js
25
web/sw.js
@@ -1,4 +1,4 @@
|
||||
const CACHE = "initpage-v4";
|
||||
const CACHE = "initpage-v6";
|
||||
const ASSETS = [
|
||||
"./",
|
||||
"./index.html",
|
||||
@@ -20,12 +20,35 @@ self.addEventListener("install", (event) => {
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
||||
.then(() => caches.open(CACHE))
|
||||
.then((cache) => cache.keys())
|
||||
.then((requests) => Promise.all(requests.filter((request) => {
|
||||
const url = new URL(request.url);
|
||||
return /\/api(?:\/|$)/.test(url.pathname);
|
||||
}).map((request) => caches.open(CACHE).then((cache) => cache.delete(request))))
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener("fetch", (event) => {
|
||||
if (event.request.method !== "GET") return;
|
||||
const requestURL = new URL(event.request.url);
|
||||
// Respostas autenticadas da API nunca devem entrar no cache compartilhado do SW.
|
||||
if (requestURL.origin === self.location.origin && /\/api(?:\/|$)/.test(requestURL.pathname)) return;
|
||||
|
||||
// Consulte o backend em cada navegação para não reaproveitar a página inicial
|
||||
// que o servidor pode ter enviado como fallback para uma rota de site estático.
|
||||
if (event.request.mode === "navigate") {
|
||||
const appHome = new URL("./", self.registration.scope);
|
||||
event.respondWith(
|
||||
fetch(event.request).catch(async () => {
|
||||
const cachedHome = await caches.match(appHome.href);
|
||||
return cachedHome || Response.error();
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
caches.match(event.request).then((cached) => {
|
||||
const fetchPromise = fetch(event.request).then((response) => {
|
||||
|
||||
Reference in New Issue
Block a user