Dashboard Temp Share Shortlinks Frames API

HTMLify

app.js
Views: 46 | Author: devwajahat
  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
let db = JSON.parse(localStorage.getItem('docDB')) || [];
let editor;
let activeProject = null;
let activeDoc = null;

const UI = {
    sidebarNav: document.getElementById('sidebarNav'),
    editorContainer: document.getElementById('editorContainer'),
    editorHeader: document.getElementById('editorHeader'),
    emptyState: document.getElementById('emptyState'),
    tocSidebar: document.getElementById('tocSidebar'),
    tocList: document.getElementById('tocList'),
    currentDocTitle: document.getElementById('currentDocTitle'),
    currentProjectTitle: document.getElementById('currentProjectTitle'),
    modalNewProject: document.getElementById('modalNewProject'),
    inputProjectName: document.getElementById('inputProjectName'),
    modalNewDoc: document.getElementById('modalNewDoc'),
    inputDocName: document.getElementById('inputDocName'),
    hiddenProjectName: document.getElementById('hiddenProjectName'),
    imageZoomOverlay: document.getElementById('imageZoomOverlay'),
    zoomedImage: document.getElementById('zoomedImage')
};

function saveDB() {
    localStorage.setItem('docDB', JSON.stringify(db));
    renderSidebar();
}

function renderSidebar() {
    UI.sidebarNav.innerHTML = '';
    db.forEach(project => {
        const projDiv = document.createElement('div');
        projDiv.className = 'mb-8';
        
        const projHeader = document.createElement('div');
        projHeader.className = 'flex justify-between items-center mb-3';
        
        const projTitleContainer = document.createElement('div');
        projTitleContainer.className = 'flex items-center gap-2';

        const projTitle = document.createElement('h3');
        projTitle.className = 'text-xs font-bold text-purple-400 uppercase tracking-widest';
        projTitle.textContent = project.projectName;

        const exportBtn = document.createElement('button');
        exportBtn.innerHTML = '<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>';
        exportBtn.className = 'text-gray-400 hover:text-white transition';
        exportBtn.title = "Export Static Project";
        exportBtn.onclick = () => exportProjectStatic(project.projectName);

        projTitleContainer.appendChild(projTitle);
        projTitleContainer.appendChild(exportBtn);
        
        const addDocBtn = document.createElement('button');
        addDocBtn.className = 'text-gray-500 hover:text-white text-xl leading-none transition';
        addDocBtn.innerHTML = '+';
        addDocBtn.onclick = () => openDocModal(project.projectName);

        projHeader.appendChild(projTitleContainer);
        projHeader.appendChild(addDocBtn);
        projDiv.appendChild(projHeader);

        const docList = document.createElement('ul');
        docList.className = 'space-y-1';
        
        project.docs.forEach(doc => {
            const docItem = document.createElement('li');
            const docLink = document.createElement('button');
            docLink.className = `w-full text-left px-3 py-2 rounded-lg text-sm transition font-medium ${activeDoc === doc.docName && activeProject === project.projectName ? 'bg-[#b300ff] text-white shadow-[0_0_15px_rgba(179,0,255,0.4)]' : 'text-gray-300 hover:bg-white/5 hover:text-white'}`;
            docLink.textContent = doc.docName;
            docLink.onclick = () => loadDocument(project.projectName, doc.docName);
            
            const deleteDocBtn = document.createElement('button');
            deleteDocBtn.innerHTML = '×';
            deleteDocBtn.className = 'ml-2 text-gray-600 hover:text-red-400 text-lg font-bold px-2';
            deleteDocBtn.onclick = (e) => {
                e.stopPropagation();
                deleteDocument(project.projectName, doc.docName);
            };

            const flexContainer = document.createElement('div');
            flexContainer.className = 'flex items-center justify-between group';
            flexContainer.appendChild(docLink);
            flexContainer.appendChild(deleteDocBtn);
            
            docItem.appendChild(flexContainer);
            docList.appendChild(docItem);
        });
        
        projDiv.appendChild(docList);
        UI.sidebarNav.appendChild(projDiv);
    });
}

function openDocModal(projectName) {
    UI.hiddenProjectName.value = projectName;
    UI.inputDocName.value = '';
    UI.modalNewDoc.classList.remove('hidden');
}

function createProject() {
    const name = UI.inputProjectName.value.trim();
    if (!name || db.find(p => p.projectName === name)) {
        alert("Invalid or duplicate project name.");
        return;
    }
    db.push({ projectName: name, docs: [] });
    saveDB();
    UI.modalNewProject.classList.add('hidden');
}

function createDocument() {
    const projectName = UI.hiddenProjectName.value;
    const docName = UI.inputDocName.value.trim();
    const project = db.find(p => p.projectName === projectName);
    
    if (!docName || project.docs.find(d => d.docName === docName)) {
        alert("Invalid or duplicate document name in this project.");
        return;
    }
    
    project.docs.push({ docName: docName, data: {} });
    saveDB();
    UI.modalNewDoc.classList.add('hidden');
    loadDocument(projectName, docName);
}

function deleteDocument(projectName, docName) {
    if(!confirm('Delete this document?')) return;
    const project = db.find(p => p.projectName === projectName);
    project.docs = project.docs.filter(d => d.docName !== docName);
    if(activeProject === projectName && activeDoc === docName) {
        activeProject = null;
        activeDoc = null;
        UI.editorContainer.classList.add('hidden');
        UI.editorHeader.classList.add('hidden');
        UI.tocSidebar.classList.add('hidden');
        UI.emptyState.classList.remove('hidden');
        if(editor && typeof editor.destroy === 'function') {
            editor.destroy();
            editor = null;
        }
    }
    saveDB();
}

function initEditor(data) {
    if (editor && typeof editor.destroy === 'function') {
        editor.destroy();
    }
    editor = new EditorJS({
        holder: 'editorjs',
        data: data || {},
        tools: {
            header: {
                class: Header,
                config: {
                    levels: [1, 2, 3, 4, 5, 6],
                    defaultLevel: 2
                }
            },
            list: EditorjsList,
            code: CodeTool,
            image: {
                class: ImageTool,
                config: {
                    uploader: {
                        uploadByFile(file) {
                            return new Promise((resolve, reject) => {
                                const reader = new FileReader();
                                reader.readAsDataURL(file);
                                reader.onload = () => resolve({ success: 1, file: { url: reader.result } });
                                reader.onerror = error => reject(error);
                            });
                        }
                    }
                }
            }
        },
        onChange: () => {
            generateTOC();
        }
    });
}
function loadDocument(projectName, docName) {
    activeProject = projectName;
    activeDoc = docName;
    
    UI.emptyState.classList.add('hidden');
    UI.editorContainer.classList.remove('hidden');
    UI.editorHeader.classList.remove('hidden');
    UI.tocSidebar.classList.remove('hidden');
    
    UI.currentProjectTitle.textContent = projectName;
    UI.currentDocTitle.textContent = docName;

    const project = db.find(p => p.projectName === projectName);
    const doc = project.docs.find(d => d.docName === docName);
    
    initEditor(doc.data);
    renderSidebar();
    setTimeout(generateTOC, 500); 
}

async function saveDocument() {
    if (!editor || !activeProject || !activeDoc) return;
    const outputData = await editor.save();
    const project = db.find(p => p.projectName === activeProject);
    const doc = project.docs.find(d => d.docName === activeDoc);
    doc.data = outputData;
    saveDB();
    generateTOC();
    
    const btn = document.getElementById('btnSaveDoc');
    const originalText = btn.textContent;
    btn.textContent = 'Saved!';
    btn.classList.add('bg-green-600');
    setTimeout(() => {
        btn.textContent = originalText;
        btn.classList.remove('bg-green-600');
    }, 2000);
}

async function generateTOC() {
    if (!editor) return;
    const outputData = await editor.save();
    UI.tocList.innerHTML = '';
    
    if(!outputData.blocks) return;

    const headers = outputData.blocks.filter(block => block.type === 'header');
    
    headers.forEach((header, index) => {
        const li = document.createElement('li');
        const a = document.createElement('a');
        
        a.href = '#';
        a.textContent = header.data.text.replace(/&nbsp;/g, ' ');
        
        const paddingLeft = `${(header.data.level - 1) * 0.75}rem`;
        a.style.paddingLeft = paddingLeft;
        a.className = 'block hover:text-[#b300ff] transition cursor-pointer font-medium';
        
        a.onclick = (e) => {
            e.preventDefault();
            const headerElements = document.querySelectorAll('.ce-header');
            if(headerElements[index]) {
                headerElements[index].scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        };
        
        li.appendChild(a);
        UI.tocList.appendChild(li);
    });
}

function parseBlockToHTML(block, index) {
    switch (block.type) {
        case 'paragraph':
            return `<p class="text-lg leading-relaxed text-gray-300 mb-6 font-['Inter'] tracking-tight">${block.data.text}</p>`;
        case 'header':
            let sizeClass = '';
            switch(block.data.level) {
                case 1: sizeClass = 'text-4xl mt-12 mb-6'; break;
                case 2: sizeClass = 'text-3xl mt-10 mb-5'; break;
                case 3: sizeClass = 'text-2xl mt-8 mb-4'; break;
                case 4: sizeClass = 'text-xl mt-6 mb-3'; break;
                case 5: sizeClass = 'text-lg mt-5 mb-2'; break;
                case 6: sizeClass = 'text-base mt-4 mb-2 uppercase tracking-wider text-gray-400'; break;
                default: sizeClass = 'text-2xl mt-8 mb-4';
            }
            const id = `heading-${index}`;
            return `<h${block.data.level} id="${id}" class="font-bold text-white font-['Poppins'] ${sizeClass} scroll-mt-10">${block.data.text}</h${block.data.level}>`;
        case 'list':
            const tag = block.data.style === 'ordered' ? 'ol' : 'ul';
            const listClass = block.data.style === 'ordered' ? 'list-decimal' : 'list-disc';
            
            // FIX: Recursive function to handle both plain strings and new nested object formats
            const renderItems = (items) => {
                return items.map(item => {
                    let text = '';
                    let nestedList = '';
                    
                    if (typeof item === 'string') {
                        text = item;
                    } else if (typeof item === 'object' && item !== null) {
                        text = item.content || '';
                        if (item.items && item.items.length > 0) {
                            nestedList = `<${tag} class="${listClass} pl-6 mt-2">${renderItems(item.items)}</${tag}>`;
                        }
                    }
                    return `<li class="mb-2">${text}${nestedList}</li>`;
                }).join('');
            };

            const itemsHTML = renderItems(block.data.items);
            return `<${tag} class="${listClass} pl-6 mb-8 text-lg text-gray-300 leading-relaxed font-['Inter']">${itemsHTML}</${tag}>`;
        case 'code':
            return `<pre class="bg-[#020617] text-indigo-200 p-6 rounded-xl mb-8 overflow-x-auto text-sm font-mono shadow-lg border border-gray-800"><code>${block.data.code.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code></pre>`;
        case 'image':
            return `<div class="mb-8"><img src="${block.data.file.url}" class="rounded-xl shadow-md max-w-full h-auto border border-gray-800" alt="Document image"><p class="text-center text-sm text-gray-500 mt-3">${block.data.caption || ''}</p></div>`;
        default:
            return '';
    }
}

function generateStaticHTML(project, currentDoc) {
    let navLinks = '';
    project.docs.forEach(doc => {
        const safeName = doc.docName.replace(/[^a-z0-9]/gi, '_').toLowerCase();
        const isActive = doc.docName === currentDoc.docName;
        const activeClass = isActive 
            ? 'bg-[#b300ff] text-white shadow-[0_0_15px_rgba(179,0,255,0.4)]' 
            : 'text-gray-400 hover:bg-white/5 hover:text-white';
        navLinks += `<a href="${safeName}.html" class="block w-full text-left px-3 py-2 rounded-lg text-sm transition font-medium mb-1 ${activeClass}">${doc.docName}</a>`;
    });

    let contentHTML = '';
    let tocHTML = '';
    
    if (currentDoc.data && currentDoc.data.blocks) {
        currentDoc.data.blocks.forEach((block, index) => {
            contentHTML += parseBlockToHTML(block, index);
            
            if (block.type === 'header') {
                const paddingLeft = `${(block.data.level - 1) * 0.75}rem`;
                tocHTML += `<li style="padding-left: ${paddingLeft}"><a href="#heading-${index}" class="block hover:text-[#b300ff] transition text-gray-400 font-medium">${block.data.text.replace(/&nbsp;/g, ' ')}</a></li>`;
            }
        });
    }

    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${currentDoc.docName} - ${project.projectName}</title>
    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Poppins:wght@600;700;800&display=swap" rel="stylesheet">
    <style>
        html { scroll-behavior: smooth; }
        body { background-color: #0f172a; }
        ::selection { background-color: #b300ff; color: white; }
    </style>
</head>
<body class="h-screen flex overflow-hidden bg-gradient-to-br from-black to-[#b300ff]/20 text-white font-['Inter']">

    <aside class="w-72 bg-black/70 backdrop-blur-md border-r border-[#b300ff]/30 flex flex-col h-full shadow-[4px_0_24px_rgba(0,0,0,0.5)] z-10 shrink-0">
        <div class="p-6 border-b border-[#b300ff]/30">
            <h1 class="text-2xl font-bold text-white tracking-wide font-['Poppins']">DocGenius</h1>
        </div>
        <div class="p-4 flex-1 overflow-y-auto">
            <div class="mb-8">
                <div class="flex items-center gap-2 mb-3">
                    <h3 class="text-xs font-bold text-purple-400 uppercase tracking-widest">${project.projectName}</h3>
                </div>
                <div class="space-y-1">
                    ${navLinks}
                </div>
            </div>
        </div>
    </aside>

    <main class="flex-1 flex flex-col h-full bg-transparent overflow-y-auto relative">
        <div class="px-12 py-6 border-b border-gray-800/50 backdrop-blur-sm sticky top-0 z-20">
            <p class="text-purple-300 uppercase tracking-widest text-sm font-bold mb-1">${project.projectName}</p>
            <h2 class="text-4xl font-extrabold text-white drop-shadow-lg font-['Poppins']">${currentDoc.docName}</h2>
        </div>

        <div class="p-12 pb-24">
            <article class="max-w-4xl mx-auto bg-gray-900/60 p-10 rounded-2xl border border-gray-800 shadow-2xl backdrop-blur-md">
                ${contentHTML}
            </article>
        </div>
    </main>

    <aside class="w-64 bg-black/70 backdrop-blur-md border-l border-[#b300ff]/30 p-6 h-full overflow-y-auto shadow-[-4px_0_24px_rgba(0,0,0,0.5)] z-10 shrink-0">
        <h3 class="text-xs uppercase tracking-widest text-purple-400 font-bold mb-6">On this page</h3>
        <ul class="space-y-3 text-sm">
            ${tocHTML}
        </ul>
    </aside>

</body>
</html>`;
}


function exportProjectStatic(projectName) {
    const project = db.find(p => p.projectName === projectName);
    if (!project || project.docs.length === 0) {
        alert('This project has no documents to export.');
        return;
    }

    const zip = new JSZip();
    const pagesFolder = zip.folder("pages");

    project.docs.forEach(doc => {
        const safeName = doc.docName.replace(/[^a-z0-9]/gi, '_').toLowerCase();
        const html = generateStaticHTML(project, doc);
        pagesFolder.file(`${safeName}.html`, html);
    });

    zip.generateAsync({ type: "blob" }).then(function(content) {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(content);
        link.download = `${projectName.replace(/[^a-z0-9]/gi, '_')}_static_export.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

// Event Listeners
document.getElementById('btnNewProject').onclick = () => {
    UI.inputProjectName.value = '';
    UI.modalNewProject.classList.remove('hidden');
};
document.getElementById('btnCancelProject').onclick = () => UI.modalNewProject.classList.add('hidden');
document.getElementById('btnConfirmProject').onclick = createProject;

document.getElementById('btnCancelDoc').onclick = () => UI.modalNewDoc.classList.add('hidden');
document.getElementById('btnConfirmDoc').onclick = createDocument;

document.getElementById('btnSaveDoc').onclick = saveDocument;

document.addEventListener('click', (e) => {
    if (e.target.tagName === 'IMG' && e.target.closest('.image-tool__image-picture')) {
        UI.zoomedImage.src = e.target.src;
        UI.imageZoomOverlay.style.display = 'flex';
    } else if (e.target.tagName === 'IMG' && !e.target.closest('.image-tool__image-picture')) {
        // Allow zooming in exported static pages as well
        UI.zoomedImage.src = e.target.src;
        UI.imageZoomOverlay.style.display = 'flex';
    }
});

UI.imageZoomOverlay.onclick = () => {
    UI.imageZoomOverlay.style.display = 'none';
};

renderSidebar();