multi page apps
Browse files379 unmodified lines380381382383384385784 unmodified lines1170117111721173117411751953 unmodified lines312931303131313231333134313563 unmodified lines3199320032013202320332043205222 unmodified lines342834293430343134323433343459 unmodified lines349434953496349734983499350012 unmodified lines3513351435153516351735183519169 unmodified lines368936903691369236933694369510 unmodified lines37063707370837093710371137126 unmodified lines3719372037213722372337243725109 unmodified lines383538363837383838393840384122 unmodified lines38643865386638673868386938701452 unmodified lines532353245325532653275328379 unmodified linesAlways output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text. Do NOT add the language name at the top of the code output."""GENERIC_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert {language} developer. You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific technologies for {language}.Write clean, idiomatic, and runnable {language} code for the user's request. If possible, include comments and best practices. Output ONLY the code inside a ``` code block, and do not include any explanations or extra text. If the user provides a file or other context, use it as a reference. If the code is for a script or app, make it as self-contained as possible. Do NOT add the language name at the top of the code output."""784 unmodified linesmerged_html = build_transformers_inline_html(files)return send_to_sandbox(merged_html)def parse_svelte_output(text):"""Parse Svelte output to extract individual files"""files = {1953 unmodified lineselse:# Use language-specific promptif language == "html":system_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPTelif language == "transformers.js":system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH if enable_search else TRANSFORMERS_JS_SYSTEM_PROMPTelif language == "svelte":63 unmodified lines# Live streaming previewpreview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {222 unmodified linespreview_val = Noneif language == "html":preview_val = send_to_sandbox(final_content)elif language == "python" and is_streamlit_code(final_content):preview_val = send_streamlit_to_stlite(final_content)yield {59 unmodified linesclean_code = clean_code.replace("\\t", "\t")preview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {12 unmodified lines_history.append([query, clean_code])preview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {169 unmodified lines# Model returned a complete HTML filepreview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)elif language == "gradio" or (language == "python" and is_gradio_code(clean_code)):10 unmodified linesclean_content = remove_code_block(modified_content)preview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_content)elif language == "python" and is_streamlit_code(clean_content):preview_val = send_streamlit_to_stlite(clean_content)elif language == "gradio" or (language == "python" and is_gradio_code(clean_content)):6 unmodified lineselse:preview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)elif language == "gradio" or (language == "python" and is_gradio_code(clean_code)):109 unmodified linesyield {code_output: clean_content,history: _history,sandbox: (send_to_sandbox(clean_content) if language == "html" else (send_streamlit_to_stlite(clean_content) if (language == "python" and is_streamlit_code(clean_content)) else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>")),history_output: history_to_chatbot_messages(_history),}else:22 unmodified lines_history.append([query, final_content])preview_val = Noneif language == "html":preview_val = send_to_sandbox(final_content)elif language == "python" and is_streamlit_code(final_content):preview_val = send_streamlit_to_stlite(final_content)elif language == "gradio" or (language == "python" and is_gradio_code(final_content)):1452 unmodified linesdef preview_logic(code, language, html_part=None, js_part=None, css_part=None):if language == "html":return send_to_sandbox(code)if language == "streamlit":return send_streamlit_to_stlite(code) if is_streamlit_code(code) else "<div style='padding:1em;color:#888;text-align:center;'>Add `import streamlit as st` to enable Streamlit preview.</div>"379 unmodified lines380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433784 unmodified lines121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271953 unmodified lines3281328232833284328532863287328863 unmodified lines33523353335433553356335733583359222 unmodified lines3582358335843585358635873588358959 unmodified lines3649365036513652365336543655365612 unmodified lines36693670367136723673367436753676169 unmodified lines3846384738483849385038513852385310 unmodified lines386438653866386738683869387038716 unmodified lines38783879388038813882388338843885109 unmodified lines399539963997399839994000400122 unmodified lines402440254026402740284029403040311452 unmodified lines54845485548654875488548954905491549254935494379 unmodified linesAlways output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text. Do NOT add the language name at the top of the code output."""# Multi-page static HTML project prompt (generic, production-style structure)MULTIPAGE_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.Create a production-ready MULTI-PAGE website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.Output MUST be a multi-file project with at least:- index.html (home)- about.html (secondary page)- contact.html (secondary page)- assets/css/styles.css (global styles)- assets/js/main.js (site-wide JS)Navigation requirements:- A consistent header with a nav bar on every page- Highlight current nav item- Responsive layout and accessibility best practicesOutput format requirements (CRITICAL):- Return ONLY a series of file sections, each starting with a filename line:=== index.html ===...file content...=== about.html ===...file content...(repeat for all files)- Do NOT wrap files in Markdown code fences- Use relative paths between files (e.g., assets/css/styles.css)General requirements:- Use modern, semantic HTML- Mobile-first responsive design- Include basic SEO meta tags in <head>- Include a footer on all pages- Avoid external CSS/JS frameworks (optional: CDN fonts/icons allowed)"""# Multi-page with search augmentationMULTIPAGE_HTML_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert front-end developer. You have access to real-time web search.Create a production-ready MULTI-PAGE website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.Follow the same file output format and project structure as specified:=== filename === blocks for each file (no Markdown fences)Use search results to apply current best practices in accessibility, semantics, responsive meta tags, and performance (preconnect, responsive images)."""GENERIC_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert {language} developer. You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific technologies for {language}.Write clean, idiomatic, and runnable {language} code for the user's request. If possible, include comments and best practices. Output ONLY the code inside a ``` code block, and do not include any explanations or extra text. If the user provides a file or other context, use it as a reference. If the code is for a script or app, make it as self-contained as possible. Do NOT add the language name at the top of the code output."""784 unmodified linesmerged_html = build_transformers_inline_html(files)return send_to_sandbox(merged_html)def parse_multipage_html_output(text: str) -> Dict[str, str]:"""Parse multi-page HTML output formatted as repeated "=== filename ===" sections.Returns a mapping of filename → file content. Supports nested paths like assets/css/styles.css."""if not text:return {}# First, strip any markdown fencescleaned = remove_code_block(text)files: Dict[str, str] = {}import re as _repattern = _re.compile(r"^===\s*([^=\n]+?)\s*===\s*\n([\s\S]*?)(?=\n===\s*[^=\n]+?\s*===|\Z)", _re.MULTILINE)for m in pattern.finditer(cleaned):name = m.group(1).strip()content = m.group(2).strip()# Remove accidental trailing fences if presentcontent = _re.sub(r"^```\w*\s*\n|\n```\s*$", "", content)files[name] = contentreturn filesdef inline_multipage_into_single_preview(files: Dict[str, str]) -> str:"""Inline local CSS/JS referenced by index.html for preview inside a data: iframe.- Uses index.html as the base document- Inlines <link href="..."> if the target exists in files- Inlines <script src="..."> if the target exists in files- Leaves other links (e.g., about.html) untouched; preview covers the home page"""import re as _rehtml = files.get('index.html', '')if not html:return ""doc = html# Inline CSS links that point to known filesdef _inline_css(match):href = match.group(1)if href in files:return f"<style>\n{files[href]}\n</style>"return match.group(0)doc = _re.sub(r"<link[^>]+href=\"([^\"]+)\"[^>]*/?>", _inline_css, doc, flags=_re.IGNORECASE)# Inline JS scripts that point to known filesdef _inline_js(match):src = match.group(1)if src in files:return f"<script>\n{files[src]}\n</script>"return match.group(0)doc = _re.sub(r"<script[^>]+src=\"([^\"]+)\"[^>]*>\s*</script>", _inline_js, doc, flags=_re.IGNORECASE)# Inject a lightweight in-iframe client-side navigator to load other HTML filestry:import json as _jsonimport base64 as _b64import re as _rehtml_pages = {k: v for k, v in files.items() if k.lower().endswith('.html')}# Ensure index.html entry restores the current body's HTML_m_body = _re.search(r"<body[^>]*>([\s\S]*?)</body>", doc, flags=_re.IGNORECASE)_index_body = _m_body.group(1) if _m_body else dochtml_pages['index.html'] = _index_bodyencoded = _b64.b64encode(_json.dumps(html_pages).encode('utf-8')).decode('ascii')nav_script = ("<script>\n" # Simple client-side loader for internal links"(function(){\n"f" const MP_FILES = JSON.parse(atob('{encoded}'));\n"" function extractBody(html){\n"" try {\n"" const doc = new DOMParser().parseFromString(html, 'text/html');\n"" const title = doc.querySelector('title'); if (title) document.title = title.textContent || document.title;\n"" return doc.body ? doc.body.innerHTML : html;\n"" } catch(e){ return html; }\n"" }\n"" function loadPage(path){\n"" if (!MP_FILES[path]) return false;\n"" const bodyHTML = extractBody(MP_FILES[path]);\n"" document.body.innerHTML = bodyHTML;\n"" attach();\n"" try { history.replaceState({}, '', '#'+path); } catch(e){}\n"" return true;\n"" }\n"" function clickHandler(e){\n"" const a = e.target && e.target.closest ? e.target.closest('a') : null;\n"" if (!a) return;\n"" const href = a.getAttribute('href') || '';\n"" if (!href || href.startsWith('#') || /^https?:/i.test(href) || href.startsWith('mailto:') || href.startsWith('tel:')) return;\n"" const clean = href.split('#')[0].split('?')[0];\n"" if (MP_FILES[clean]) { e.preventDefault(); loadPage(clean); }\n"" }\n"" function attach(){ document.removeEventListener('click', clickHandler, true); document.addEventListener('click', clickHandler, true); }\n"" document.addEventListener('DOMContentLoaded', function(){ attach(); const initial = (location.hash||'').slice(1); if (initial && MP_FILES[initial]) loadPage(initial); }, { once:true });\n""})();\n""</script>")m = _re.search(r"</body>", doc, flags=_re.IGNORECASE)if m:i = m.start()doc = doc[:i] + nav_script + doc[i:]else:doc = doc + nav_scriptexcept Exception:# Non-fatal in previewpassreturn docdef parse_svelte_output(text):"""Parse Svelte output to extract individual files"""files = {1953 unmodified lineselse:# Use language-specific promptif language == "html":# Use multi-page format prompt to encourage production multi-file outputsystem_prompt = MULTIPAGE_HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else MULTIPAGE_HTML_SYSTEM_PROMPTelif language == "transformers.js":system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH if enable_search else TRANSFORMERS_JS_SYSTEM_PROMPTelif language == "svelte":63 unmodified lines# Live streaming previewpreview_val = Noneif language == "html":_mp = parse_multipage_html_output(clean_code)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mp)) if _mp.get('index.html') else send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {222 unmodified linespreview_val = Noneif language == "html":_mpf2 = parse_multipage_html_output(final_content)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpf2)) if _mpf2.get('index.html') else send_to_sandbox(final_content)elif language == "python" and is_streamlit_code(final_content):preview_val = send_streamlit_to_stlite(final_content)yield {59 unmodified linesclean_code = clean_code.replace("\\t", "\t")preview_val = Noneif language == "html":_mpc = parse_multipage_html_output(clean_code)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc)) if _mpc.get('index.html') else send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {12 unmodified lines_history.append([query, clean_code])preview_val = Noneif language == "html":_mpc2 = parse_multipage_html_output(clean_code)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc2)) if _mpc2.get('index.html') else send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {169 unmodified lines# Model returned a complete HTML filepreview_val = Noneif language == "html":_mpc3 = parse_multipage_html_output(clean_code)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc3)) if _mpc3.get('index.html') else send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)elif language == "gradio" or (language == "python" and is_gradio_code(clean_code)):10 unmodified linesclean_content = remove_code_block(modified_content)preview_val = Noneif language == "html":_mpc4 = parse_multipage_html_output(clean_content)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc4)) if _mpc4.get('index.html') else send_to_sandbox(clean_content)elif language == "python" and is_streamlit_code(clean_content):preview_val = send_streamlit_to_stlite(clean_content)elif language == "gradio" or (language == "python" and is_gradio_code(clean_content)):6 unmodified lineselse:preview_val = Noneif language == "html":_mpc5 = parse_multipage_html_output(clean_code)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc5)) if _mpc5.get('index.html') else send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)elif language == "gradio" or (language == "python" and is_gradio_code(clean_code)):109 unmodified linesyield {code_output: clean_content,history: _history,sandbox: ((send_to_sandbox(inline_multipage_into_single_preview(parse_multipage_html_output(clean_content))) if parse_multipage_html_output(clean_content).get('index.html') else send_to_sandbox(clean_content)) if language == "html" else (send_streamlit_to_stlite(clean_content) if (language == "python" and is_streamlit_code(clean_content)) else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>")),history_output: history_to_chatbot_messages(_history),}else:22 unmodified lines_history.append([query, final_content])preview_val = Noneif language == "html":_mpf = parse_multipage_html_output(final_content)preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpf)) if _mpf.get('index.html') else send_to_sandbox(final_content)elif language == "python" and is_streamlit_code(final_content):preview_val = send_streamlit_to_stlite(final_content)elif language == "gradio" or (language == "python" and is_gradio_code(final_content)):1452 unmodified linesdef preview_logic(code, language, html_part=None, js_part=None, css_part=None):if language == "html":# If the content is a multi-page block, inline for preview; else render directlyfiles = parse_multipage_html_output(code)if files and files.get('index.html'):merged = inline_multipage_into_single_preview(files)return send_to_sandbox(merged)return send_to_sandbox(code)if language == "streamlit":return send_streamlit_to_stlite(code) if is_streamlit_code(code) else "<div style='padding:1em;color:#888;text-align:center;'>Add `import streamlit as st` to enable Streamlit preview.</div>"
app.py+176-10