diff --git a/src/download.js b/src/download.js index 3b15a68..d7e0a9f 100644 --- a/src/download.js +++ b/src/download.js @@ -31,16 +31,7 @@ async function createZipWithSingleFile ({ htmlContent, cssContent, jsContent }) async function createZipWithMultipleFiles ({ htmlContent, cssContent, jsContent }) { const zip = await getZip() - const indexHtml = ` - - - - - - ${htmlContent} - - -` + const indexHtml = buildIndexHtml(htmlContent) return await zip([ { name: 'style.css', input: cssContent }, @@ -49,6 +40,77 @@ async function createZipWithMultipleFiles ({ htmlContent, cssContent, jsContent ]).blob() } +function buildIndexHtml (html) { + const hasDoctype = /]*>/i.test(html) + const hasHtml = /]/i.test(html) + const hasHead = /]/i.test(html) + const hasBody = /]/i.test(html) + const hasStyleLink = /]*href=["']style\.css["'][^>]*>/i.test(html) + const hasScript = /]*src=["']script\.js["'][^>]*>/i.test(html) + + let result = html + + // Add script before or at the end + if (!hasScript) { + if (hasBody) { + result = result.replace(/<\/body>/i, ' \n ') + } else { + result = result + '\n ' + } + } + + // Add stylesheet link inside or store for later + if (!hasStyleLink) { + if (hasHead) { + result = result.replace(/]*)>/i, '\n ') + } + // If no , it will be added below with the link included + } + + // Add if missing + if (!hasHead) { + const headBlock = ' \n \n ' + if (hasBody) { + result = result.replace(/]*)>/i, '\n' + headBlock) + } else { + result = headBlock + '\n' + result + } + } + + // Wrap in if missing + if (!hasBody) { + if (hasHtml) { + // Find content after and before , wrap it in + result = result.replace(/(<\/head>)([\s\S]*?)(<\/html>)/i, '$1\n \n $2\n \n$3') + } else { + // Find content after and wrap the rest in + const headEnd = result.indexOf('') + if (headEnd !== -1) { + const afterHead = headEnd + ''.length + const before = result.slice(0, afterHead) + const after = result.slice(afterHead) + result = before + '\n ' + after + '\n ' + } else { + result = ' \n' + result + '\n ' + } + } + } + + // Wrap in if missing + if (!hasHtml) { + result = '\n' + result + '\n' + } + + // Add DOCTYPE if missing + if (!hasDoctype) { + result = '\n' + result + } + + return result +} + function generateZip ({ zipBlob, zipFileName }) { console.log({ zipBlob, zipFileName }) const element = window.document.createElement('a')