Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
598 lines (533 loc) · 22.8 KB
/
Copy pathapp.js
File metadata and controls
598 lines (533 loc) · 22.8 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
/**
* Scriptor - Aplicação Principal
*/
// Estado Global do Projeto do Utilizador
let projectState = {
title: "",
phase1: {},
phase2: {},
phase3: {
problemaExterno: {},
conflitosSecundarios: [],
pontosDeVirada: [],
personagensApoio: []
},
phase4: [], // Array de Cartões de Cena
phase5: [],
sceneDrafts: {}, // Guardador individual dos rascunhos por id de cena
currentWritingSceneId: null,
editorDraft: "",
wordTarget: 50000
};
document.addEventListener('DOMContentLoaded', () => {
initTheme();
initMenu();
initPWA();
initBrandClick();
loadLocalProject();
initScriptorAvatar();
});
/* ==========================================================================
1. Persistência Local Básica
========================================================================== */
function saveLocalProject() {
localStorage.setItem('scriptor_current_project', JSON.stringify(projectState));
}
function loadLocalProject() {
const saved = localStorage.getItem('scriptor_current_project');
if (saved) {
try {
projectState = JSON.parse(saved);
if (!Array.isArray(projectState.phase4)) {
projectState.phase4 = [];
}
if (!projectState.sceneDrafts) {
projectState.sceneDrafts = {};
}
if (!projectState.wordTarget) {
projectState.wordTarget = 50000;
}
} catch (e) {
console.error('Erro ao carregar projeto local:', e);
}
}
}
/* ==========================================================================
2. Alternância do Modo Claro/Escuro, Avatares & Ação do Logótipo
========================================================================== */
function initTheme() {
const themeToggleBtn = document.getElementById('theme-toggle');
const savedTheme = localStorage.getItem('scriptor-theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
if (themeToggleBtn) {
themeToggleBtn.addEventListener('click', () => {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('scriptor-theme', newTheme);
});
}
}
function setScriptorAvatar(gender) {
const imgElement = document.getElementById('welcome-illustration');
const btnM = document.getElementById('avatar-m-btn');
const btnF = document.getElementById('avatar-f-btn');
localStorage.setItem('scriptor-avatar', gender);
if (imgElement) {
imgElement.src = gender === 'f' ? 'ilustra-scriptor-f.svg' : 'ilustra-scriptor.svg';
}
if (btnM && btnF) {
if (gender === 'f') {
btnF.style.borderColor = 'var(--primary-color)';
btnF.style.color = 'var(--primary-color)';
btnM.style.borderColor = 'var(--border-color)';
btnM.style.color = 'var(--text-color)';
} else {
btnM.style.borderColor = 'var(--primary-color)';
btnM.style.color = 'var(--primary-color)';
btnF.style.borderColor = 'var(--border-color)';
btnF.style.color = 'var(--text-color)';
}
}
}
function initScriptorAvatar() {
const savedAvatar = localStorage.getItem('scriptor-avatar') || 'm';
setScriptorAvatar(savedAvatar);
}
function initBrandClick() {
const brandElem = document.querySelector('.brand');
if (!brandElem) return;
brandElem.style.cursor = 'pointer';
brandElem.addEventListener('click', () => {
navigateToRoute('home');
});
}
/* ==========================================================================
3. Renderização de Ecrãs "Home", "Novo / Configurar Projeto" e Reset de Cache
========================================================================== */
function renderWelcomeView() {
return `
<section id="app-view" class="welcome-container">
<div class="welcome-overlay">
<h2>Bem-vindo ao Scriptor</h2>
<p>Selecione uma opção no menu lateral para começar.</p>
<!-- Alternador de Ilustração -->
<div class="avatar-toggle-container" style="margin-top: 14px; display: flex; gap: 8px; justify-content: center;">
<button id="avatar-m-btn" class="card-ctrl-btn" title="Ilustração Escritor" onclick="setScriptorAvatar('m')">
👨💻 Escritor
</button>
<button id="avatar-f-btn" class="card-ctrl-btn" title="Ilustração Escritora" onclick="setScriptorAvatar('f')">
👩💻 Escritora
</button>
</div>
</div>
<img id="welcome-illustration" src="ilustra-scriptor.svg" alt="Ilustração de boas-vindas do Scriptor" class="welcome-illustration">
</section>
`;
}
function renderNewProjectView() {
return `
<article class="theory-article">
<h1>Configuração e Título do Projeto</h1>
<p>Defina ou atualize o título do seu livro. Os seus dados e progresso serão mantidos até que decida resetar a aplicação.</p>
<div class="project-form-card">
<label for="project-title-input" class="form-label">Título do Romance</label>
<input
type="text"
id="project-title-input"
class="form-input"
placeholder="Digite o título do seu livro..."
value="${projectState.title || ''}"
autocomplete="off"
/>
<div class="form-actions" style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 12px;">
<button id="start-project-btn" class="primary-btn">
${projectState.title ? 'Salvar Título e Continuar' : 'Iniciar Projeto'}
</button>
</div>
</div>
<!-- Card: Sobre o Scriptor -->
<div class="project-form-card about-scriptor-card" style="margin-top: 24px;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: var(--primary-color);">Sobre o Scriptor</h3>
<p class="field-hint" style="margin-bottom: 16px !important; color: var(--text-color); font-size: 0.95rem; line-height: 1.6;">
O Scriptor é uma aplicação focada no planejamento estruturado e na criação de livros literários. Desenvolvido para guiar escritores desde a fundação da ideia até a organização de cenas e rascunho, ele garante total privacidade mantendo seus dados salvos localmente.
</p>
<div>
<a
href="https://github.com/magpe-stack/Scriptor/blob/main/manual_do_usu_rio_scriptor.md"
target="_blank"
rel="noopener noreferrer"
class="card-ctrl-btn manual-btn"
style="display: inline-flex; align-items: center; gap: 8px; text-decoration: none;"
>
<svg viewBox="0 0 24 24" style="fill: currentColor; width: 18px; height: 18px;">
<path d="M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM6 4h5v8l-2.5-1.5L6 12V4z"/>
</svg>
Acessar Manual do Scriptor
</a>
</div>
</div>
<!-- Ação Crítica Exclusiva: Limpar Cache e Apagar Dados -->
<div class="project-form-card" style="border-color: rgba(255, 87, 34, 0.4); margin-top: 24px;">
<h3 style="margin: 0; font-size: 1.05rem; color: #ff5722;">Reset Completo da Aplicação</h3>
<p class="field-hint" style="margin-bottom: 12px !important;">
Para apagar definitivamente todos os dados do projeto atual salvos no navegador e restaurar o Scriptor do zero, utilize o botão abaixo.
</p>
<div>
<button id="clear-cache-btn" class="card-ctrl-btn" style="border-color: #ff5722; color: #ff5722; cursor: pointer;">
<svg viewBox="0 0 24 24" style="fill: currentColor; width: 18px; height: 18px;"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/></svg>
Limpar Cache e Resetar Aplicação
</button>
</div>
</div>
</article>
`;
}
function initNewProjectEvents() {
const titleInput = document.getElementById('project-title-input');
const startBtn = document.getElementById('start-project-btn');
const clearCacheBtn = document.getElementById('clear-cache-btn');
if (startBtn) {
startBtn.addEventListener('click', () => {
const inputVal = titleInput.value.trim();
if (!inputVal) {
alert('Por favor, digite o título do projeto.');
titleInput.focus();
return;
}
projectState.title = inputVal;
saveLocalProject();
navigateToRoute('phase1');
});
}
if (titleInput) {
titleInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
startBtn.click();
}
});
}
if (clearCacheBtn) {
clearCacheBtn.addEventListener('click', () => {
if (confirm('Tem a certeza de que deseja APAGAR TODOS OS DADOS do projeto e resetar a aplicação? Esta ação não pode ser desfeita.')) {
localStorage.removeItem('scriptor_current_project');
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
for (let registration of registrations) {
registration.unregister();
}
});
}
if ('caches' in window) {
caches.keys().then(names => {
for (let name of names) {
caches.delete(name);
}
});
}
alert('Aplicação e dados resetados com sucesso!');
window.location.reload(true);
}
});
}
}
/* ==========================================================================
4. Navegação Principal e Rotas
========================================================================== */
function navigateToRoute(route) {
const mainView = document.getElementById('app-view');
document.querySelectorAll('.icon-btn').forEach(b => b.classList.remove('active'));
const activeBtn = document.querySelector(`.icon-btn[data-route="${route}"]`);
if (activeBtn) activeBtn.classList.add('active');
if (route === 'home') {
mainView.outerHTML = renderWelcomeView();
initScriptorAvatar();
} else if (route === 'new') {
mainView.innerHTML = renderNewProjectView();
initNewProjectEvents();
} else if (route === 'dashboard') {
if (typeof renderDashboardView !== 'undefined') {
mainView.innerHTML = renderDashboardView();
initDashboardEvents();
}
} else if (route === 'phase1') {
if (typeof renderPhase1View !== 'undefined') {
mainView.innerHTML = renderPhase1View();
initPhase1Events();
}
} else if (route === 'phase2') {
if (typeof renderPhase2View !== 'undefined') {
mainView.innerHTML = renderPhase2View();
initPhase2Events();
}
} else if (route === 'phase3') {
if (typeof renderPhase3View !== 'undefined') {
mainView.innerHTML = renderPhase3View();
initPhase3Events();
}
} else if (route === 'phase4') {
if (typeof renderPhase4View !== 'undefined') {
mainView.innerHTML = renderPhase4View();
initPhase4Events();
}
} else if (route === 'phase5') {
if (typeof renderPhase5View !== 'undefined') {
mainView.innerHTML = renderPhase5View();
initPhase5Events();
}
} else if (route === 'editor') {
if (typeof renderEditorView !== 'undefined') {
mainView.innerHTML = renderEditorView();
initEditorEvents();
} else {
mainView.innerHTML = `
<article class="theory-article">
<h1>EDITOR DE RASCUNHO</h1>
<p>Certifique-se de que o ficheiro editor.js está incluído no index.html.</p>
</article>
`;
}
} else if (route === 'theory-pt') {
if (typeof theoryPtContent !== 'undefined') mainView.innerHTML = theoryPtContent;
} else if (route === 'theory-storygenius') {
if (typeof theoryStoryGeniusContent !== 'undefined') mainView.innerHTML = theoryStoryGeniusContent;
} else if (route === 'theory-steps') {
if (typeof theoryStepsContent !== 'undefined') mainView.innerHTML = theoryStepsContent;
} else if (route === 'theory-example') {
if (typeof theoryExampleContent !== 'undefined') mainView.innerHTML = theoryExampleContent;
} else if (route === 'theory-tips') {
if (typeof renderTipsView !== 'undefined') {
mainView.innerHTML = renderTipsView();
initTipsEvents();
}
} else {
mainView.innerHTML = `
<article class="theory-article">
<h1>${route.toUpperCase()}</h1>
<p>Página em desenvolvimento.</p>
</article>
`;
}
}
function initMenu() {
const hasSubmenuItems = document.querySelectorAll('.menu-item.has-submenu');
hasSubmenuItems.forEach(item => {
const toggleBtn = item.querySelector('.toggle-submenu');
toggleBtn.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = item.classList.contains('open');
hasSubmenuItems.forEach(otherItem => otherItem.classList.remove('open'));
if (!isOpen) item.classList.add('open');
});
});
document.querySelectorAll('.icon-btn[data-route], .icon-btn[data-action], .icon-btn[data-export], .icon-btn[data-import]').forEach(btn => {
btn.addEventListener('click', (e) => {
const target = e.currentTarget;
if (target.dataset.action === 'new') {
navigateToRoute('new');
return;
}
if (target.dataset.route) {
navigateToRoute(target.dataset.route);
return;
}
if (target.dataset.export) {
exportProject(target.dataset.export);
return;
}
if (target.dataset.import === 'json') {
importJsonProject();
return;
}
});
});
}
/* ==========================================================================
5. Carregar / Importar Projeto de Ficheiro JSON
========================================================================== */
function importJsonProject() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.json,application/json';
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const importedData = JSON.parse(event.target.result);
if (importedData && typeof importedData === 'object' && importedData.title) {
projectState = importedData;
if (!Array.isArray(projectState.phase4)) {
projectState.phase4 = [];
}
if (!projectState.sceneDrafts) {
projectState.sceneDrafts = {};
}
saveLocalProject();
alert(`Projeto "${projectState.title}" carregado com sucesso!`);
navigateToRoute('phase1');
} else {
alert('O ficheiro JSON selecionado é inválido ou não possui o formato de projeto do Scriptor.');
}
} catch (err) {
console.error('Erro ao ler ficheiro JSON:', err);
alert('Erro ao abrir o ficheiro. Certifique-se de que é um JSON válido.');
}
};
reader.readAsText(file);
});
fileInput.click();
}
/* ==========================================================================
6. Exportação Semântica Ordenada
========================================================================== */
function exportProject(format) {
if (!projectState.title) {
alert('Nenhum projeto foi iniciado ainda.');
return;
}
const filename = `${projectState.title.toLowerCase().replace(/[^a-z0-9]/g, '_')}_scriptor`;
const p1 = projectState.phase1 || {};
const p2 = projectState.phase2 || {};
const p3 = projectState.phase3 || {};
const pe = p3.problemaExterno || {};
if (format === 'json') {
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(projectState, null, 2));
downloadFile(dataStr, `${filename}.json`);
} else if (format === 'md' || format === 'txt') {
let content = `# ${projectState.title}\n\n`;
// Fase 1
content += `## Fase 1: Fundação e Conexão Autoral\n\n`;
content += `### 1. A Primeira Fagulha\n${p1.fagulha || '(Vazio)'}\n\n`;
content += `### 2. Por Que Você Se Importa?\n${p1.motivacao || '(Vazio)'}\n\n`;
content += `### 3. O Ponto Central\n${p1.pontoCentral || '(Vazio)'}\n\n`;
content += `### 4. A Premissa "E Se?"\n${p1.premissa || '(Vazio)'}\n\n`;
content += `### 5. Leitor Ideal\n${p1.leitorIdeal || '(Vazio)'}\n\n`;
content += `### 6. Sinopse de Contracapa\n${p1.sinopse || '(Vazio)'}\n\n`;
content += `### 7. Livros Comparáveis\n${p1.comps || '(Vazio)'}\n\n`;
content += `### 8. Promessa de Entretenimento e Gênero\n${p1.promessa || '(Vazio)'}\n\n`;
// Fase 2
content += `## Fase 2: Arquitetura Psicológica e Backstory Dramatizada\n\n`;
content += `### 5. Estado Inicial\n${p2.estadoInicial || '(Vazio)'}\n\n`;
content += `### 6. Desejo Superficial\n${p2.desejoSuperficial || '(Vazio)'}\n\n`;
content += `### 7. Motivação Interna do Desejo\n${p2.motivacaoInterna || '(Vazio)'}\n\n`;
content += `### 8. A Falsa Crença Central\n${p2.falsaCrenca || '(Vazio)'}\n\n`;
content += `### 9 e 10. A Cena de Origem (Planejamento)\n${p2.cenaOrigemPlanejamento || '(Vazio)'}\n\n`;
content += `### 9 e 10. A Cena de Origem (A Escrita)\n${p2.cenaOrigemEscrita || '(Vazio)'}\n\n`;
content += `### 11. Cenas de Encruzilhada\n`;
content += `* **Primeiro Momento:** ${p2.encruzilhada1 || '(Vazio)'}\n`;
content += `* **Segundo Momento:** ${p2.encruzilhada2 || '(Vazio)'}\n`;
content += `* **Terceiro Momento:** ${p2.encruzilhada3 || '(Vazio)'}\n\n`;
// Fase 3
content += `## Fase 3: Estruturação Causal do Enredo e Terceiro Trilho\n\n`;
content += `### 12. O Problema Externo Principal\n`;
content += `* **Descrição:** ${pe.descricao || '(Vazio)'}\n`;
content += `* **Consequências Reais:** ${pe.consequencias || '(Vazio)'}\n`;
content += `* **Prazo Limite:** ${pe.prazoLimite || '(Vazio)'}\n`;
content += `* **Alto Custo Emocional:** ${pe.custoEmocional || '(Vazio)'}\n\n`;
content += `### 13 & 14. Conflitos Secundários e Avaliação do Terceiro Trilho\n`;
if (p3.conflitosSecundarios && p3.conflitosSecundarios.length > 0) {
p3.conflitosSecundarios.forEach((c, i) => {
content += `#### Conflito #${i+1}\n`;
content += `* **Texto:** ${c.texto || '(Vazio)'}\n`;
content += `* **Estágio:** ${c.categoria}\n`;
content += `* **Força Dramática:** ${c.avaliacaoForca}\n`;
content += `* **Terceiro Trilho:** ${c.avaliacaoTerceiroTrilho}\n`;
content += `* **Notas:** ${c.notasQualitativas || '(Sem notas)'}\n\n`;
});
} else {
content += `(Nenhum conflito cadastrado)\n\n`;
}
content += `### 15. Pontos de Virada\n`;
if (p3.pontosDeVirada && p3.pontosDeVirada.length > 0) {
p3.pontosDeVirada.forEach((pv, i) => {
content += `#### Ponto de Virada #${i+1}: ${pv.titulo || '(Sem título)'}\n`;
content += `${pv.descricao || '(Sem descrição)'}\n`;
content += `* Causalidade ("Portanto"): ${pv.testeCausaEfeito ? 'Sim' : 'Não'}\n`;
content += `* Fere Falsa Crença: ${pv.testeImpactoFalsaCrenca ? 'Sim' : 'Não'}\n`;
content += `* Sem saída fácil: ${pv.testeAcaoVazia ? 'Sim' : 'Não'}\n\n`;
});
} else {
content += `(Nenhum ponto de virada cadastrado)\n\n`;
}
content += `### 16. Personagens de Apoio\n`;
if (p3.personagensApoio && p3.personagensApoio.length > 0) {
p3.personagensApoio.forEach((pers) => {
content += `* **${pers.nome || 'Sem nome'}** (${pers.funcao}): ${pers.conexaoEnredoCrenca || '(Sem conexão)'}\n`;
});
content += `\n`;
} else {
content += `(Nenhum personagem de apoio cadastrado)\n\n`;
}
// Fase 4
content += `## Fase 4: Cartões de Cena\n\n`;
if (Array.isArray(projectState.phase4) && projectState.phase4.length > 0) {
projectState.phase4.forEach((sc, i) => {
content += `### Cena #${i+1}: ${sc.titulo || '(Sem título)'}\n`;
content += `* **Ponto Alfa:** ${sc.pontoAlfa || '(Vazio)'}\n`;
content += `* **Causa (Ação):** ${sc.enredoCausa || '(Vazio)'}\n`;
content += `* **Efeito (Consequência):** ${sc.enredoEfeito || '(Vazio)'}\n`;
content += `* **Terceiro Trilho (Significado):** ${sc.terceiroTrilhoImporta || '(Vazio)'}\n`;
content += `* **Terceiro Trilho (Realização):** ${sc.terceiroTrilhoRealizacao || '(Vazio)'}\n`;
content += `* **E Por Isso? (Próxima decisão):** ${sc.ePorIsso || '(Vazio)'}\n\n`;
});
} else {
content += `(Nenhum cartão de cena cadastrado)\n\n`;
}
// Fase 5
content += `## Fase 5: Roteiro (Roadmap)\n\n`;
if (Array.isArray(projectState.phase4) && projectState.phase4.length > 0) {
projectState.phase4.forEach((sc, i) => {
const draftText = projectState.sceneDrafts ? projectState.sceneDrafts[sc.id] : '';
content += `### ${i+1}. ${sc.titulo || 'Cena sem título'}\n`;
content += `* **ALFA:** ${sc.pontoAlfa || '(Vazio)'}\n`;
content += `* **E POR ISSO?:** ${sc.ePorIsso || '(Vazio)'}\n`;
content += `* **RASCUNHO:**\n${draftText || '(Sem rascunho escrito)'}\n\n`;
});
} else {
content += `(Nenhuma cena no roteiro)\n\n`;
}
// Rascunho Geral e Cenas Escritas
content += `## Rascunho Geral e Cenas Escritas\n\n`;
if (projectState.sceneDrafts && Object.keys(projectState.sceneDrafts).length > 0) {
Object.keys(projectState.sceneDrafts).forEach((id) => {
const d = projectState.sceneDrafts[id];
const sceneInfo = (projectState.phase4 || []).find(s => s.id === id);
const title = d.title || (sceneInfo ? sceneInfo.titulo : 'Cena');
content += `### ${title}\n\n${d.content || '(Vazio)'}\n\n`;
});
} else {
content += `${projectState.editorDraft || '(Vazio)'}\n`;
}
const mime = format === 'md' ? 'text/markdown' : 'text/plain';
const dataStr = `data:${mime};charset=utf-8,` + encodeURIComponent(content);
downloadFile(dataStr, `${filename}.${format}`);
} else if (format === 'docx') {
if (typeof exportFullBookToDocx === 'function') {
exportFullBookToDocx();
} else {
alert('O ficheiro de suporte export.js não foi carregado corretamente.');
}
}
}
function downloadFile(dataStr, fileName) {
const downloadAnchor = document.createElement('a');
downloadAnchor.setAttribute("href", dataStr);
downloadAnchor.setAttribute("download", fileName);
document.body.appendChild(downloadAnchor);
downloadAnchor.click();
downloadAnchor.remove();
}
/* ==========================================================================
7. Registo do Service Worker (PWA)
========================================================================== */
function initPWA() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw.js')
.then(reg => console.log('Service Worker registado:', reg.scope))
.catch(err => console.error('Erro no Service Worker:', err));
});
}
}