-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
296 lines (231 loc) · 7.68 KB
/
Copy pathscripts.js
File metadata and controls
296 lines (231 loc) · 7.68 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
document.addEventListener("DOMContentLoaded", () => {
/* ===========================
CONFIGURAÇÃO DA API
=========================== */
const API_BASE = "https://controle-acessos-api.vercel.app/api";
/* ===========================
GERAR OU RECUPERAR USER ID
=========================== */
function obterOuCriarUserId() {
let userId = localStorage.getItem("userId");
if (!userId) {
userId = crypto.randomUUID();
localStorage.setItem("userId", userId);
}
return userId;
}
const userId = obterOuCriarUserId();
/* ===========================
REGISTRAR VISITA (POST)
=========================== */
async function registrarVisita() {
try {
await fetch(`${API_BASE}/registrar-acesso`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId })
});
} catch (erro) {
console.error("Erro ao registrar visita:", erro);
}
}
/* ===========================
CARREGAR CONTADORES (GET)
=========================== */
async function carregarContadores() {
const totalEl = document.getElementById("contador-total");
const usuarioEl = document.getElementById("contador-usuario");
if (!totalEl || !usuarioEl) return;
try {
const resposta = await fetch(`${API_BASE}/visitas-usuario?uuid=${userId}`);
const dados = await resposta.json();
totalEl.textContent = dados.totalVisitas ?? "--";
usuarioEl.textContent = dados.visitasUsuario ?? "--";
} catch (erro) {
console.error("Erro ao carregar contadores:", erro);
}
}
/* ===========================
EXECUTAR AO CARREGAR
=========================== */
registrarVisita().then(carregarContadores);
/* ===========================
TABELA DE PROJETOS
===========================
async function carregarProjetos() {
const tabela = document.getElementById("tabelaProjetos");
if (!tabela) return;
try {
const response = await fetch("projetos.json");
if (!response.ok) throw new Error("Não foi possível carregar projetos.json");
const data = await response.json();
if (!Array.isArray(data) || data.length === 0) return;
const cabecalho = Object.keys(data[0]);
let thead = "<thead><tr>";
cabecalho.forEach(col => thead += `<th>${col}</th>`);
thead += "</tr></thead>";
let tbody = "<tbody>";
data.forEach(item => {
tbody += "<tr>";
cabecalho.forEach(col => {
tbody += `<td>${item[col] ?? ""}</td>`;
});
tbody += "</tr>";
});
tbody += "</tbody>";
tabela.innerHTML = thead + tbody;
} catch (error) {
console.error("Erro ao carregar projetos:", error);
}
}
carregarProjetos();
*/
/* ==================
TABELA DE PROJETOS
================== */
let projetos = []; // cache dos dados
/* =================
CARREGAR PROJETOS
================= */
async function carregarProjetos()
{
if (window.location.pathname.includes("projetos.html"))
{
return;
}
try {
const response = await fetch("projetos.json");
if (!response.ok) {
console.error("Erro ao carregar projetos.json:", response.status);
return;
}
const data = await response.json();
if (!Array.isArray(data) || data.length === 0) {
console.warn("projetos.json está vazio ou não é um array.");
return;
}
// Armazena no cache global
projetos = data;
// Monta a tabela inicial
montarTabela(projetos);
} catch (error) {
console.error("Erro inesperado ao carregar projetos:", error);
}
}
/* =============
MONTAR TABELA
============= */
function montarTabela(lista) {
const tabela = document.getElementById("tabelaProjetos");
if (!tabela) return;
// Se não houver resultados, limpa a tabela e mostra aviso
if (lista.length === 0) {
tabela.innerHTML = `
<thead>
<tr><th>Nenhum resultado encontrado</th></tr>
</thead>
<tbody></tbody>
`;
return;
}
const colunas = Object.keys(lista[0]).filter(col => col !== "Link");
const thead = `
<thead>
<tr>
${colunas.map(col => `<th>${col}</th>`).join("")}
</tr>
</thead>
`;
const tbody = `
<tbody>
${lista.map(item => `
<tr>
${colunas.map(col => {
let valor = item[col] ?? "";
if (col === "NomeDoProjeto" && item.Link) {
valor = `
<a href="${item.Link}" target="_blank" class="link-projeto">
${valor} 🔗
</a>
`;
}
return `<td>${valor}</td>`;
}).join("")}
</tr>
`).join("")}
</tbody>
`;
tabela.innerHTML = thead + tbody;
}
/* ===========================
FILTROS
=========================== */
function aplicarFiltros() {
const nomeFiltro = document.getElementById("filtroNome")?.value.trim().toLowerCase();
const linguagensFiltro = document.getElementById("filtroLinguagens")?.value.trim().toLowerCase();
const filtrados = projetos.filter(p => {
const nome = (p.NomeDoProjeto ?? "").toLowerCase();
const linguagens = (p.Linguagens ?? "").toLowerCase();
const nomeOK = nomeFiltro ? nome.includes(nomeFiltro) : true;
const linguagensOK = linguagensFiltro ? linguagens.includes(linguagensFiltro) : true;
return nomeOK && linguagensOK;
});
montarTabela(filtrados);
}
/* Eventos dos filtros */
const filtroNome = document.getElementById("filtroNome");
const filtroLinguagens = document.getElementById("filtroLinguagens");
const btnLimpar = document.getElementById("btnLimparFiltros");
if (filtroNome) filtroNome.addEventListener("input", aplicarFiltros);
if (filtroLinguagens) filtroLinguagens.addEventListener("input", aplicarFiltros);
if (btnLimpar)
{
btnLimpar.addEventListener("click", () =>
{
filtroNome.value = "";
filtroLinguagens.value = "";
aplicarFiltros();
});
}
/* Inicialização */
carregarProjetos();
/* ===========================
TEMA ESCURO/CLARO
=========================== */
const toggleBtn = document.getElementById("toggle-theme");
function aplicarTema(tema) {
document.body.classList.remove("dark-mode", "light-mode");
if (tema === "light") {
document.body.classList.add("light-mode");
toggleBtn.textContent = "🌙 Modo escuro";
} else {
document.body.classList.add("dark-mode");
toggleBtn.textContent = "☀️ Modo claro";
}
}
function detectarTemaInicial() {
const salvo = localStorage.getItem("tema-bercelli");
if (salvo === "light" || salvo === "dark") return salvo;
if (window.matchMedia("(prefers-color-scheme: light)").matches) return "light";
return "dark";
}
aplicarTema(detectarTemaInicial());
if (toggleBtn) {
toggleBtn.addEventListener("click", () => {
const temaAtual = document.body.classList.contains("light-mode") ? "light" : "dark";
const novoTema = temaAtual === "light" ? "dark" : "light";
aplicarTema(novoTema);
localStorage.setItem("tema-bercelli", novoTema);
});
}
/* ===========================
MENU ATIVO
=========================== */
const itensMenu = document.querySelectorAll(".menuItem");
itensMenu.forEach(item => {
item.addEventListener("click", () => {
itensMenu.forEach(i => i.classList.remove("active"));
item.classList.add("active");
});
});
});