1
📥 Structured Ingest
Selections save just the highlighted code. Splitter mode ingests the whole editor and extracts metadata automatically.
Workchat
Native local Workchat ready.
General
Local-first room
local
ʊai.com • MASTER CODEX • Physics-Informed Substrate + Genetic Codex
AetherWeave • Document Combiner
Codex Synthesis Status
Idle
Blueprint ID
DNA Length
Root Hash
Message
Deploy will generate a blueprint, encode DNA, and verify integrity.
DNA Preview
`; codexFrame.dataset.loaded = 'error'; } } function mountAetherWeaveIntoRoot() { if (!aetherRoot) return; const shadow = aetherRoot.shadowRoot || aetherRoot.attachShadow({ mode: 'open' }); if (shadow.childNodes.length) return; shadow.innerHTML = `
AETHERWEAVE
Document Combiner for sequencing files into one exportable mega document
Untitled Document
Imported Files • 0 drag or double-tap to sequence
Drop files anywhere in this card to import them
Selected Order • 0 files
Live Preview • Mega Markdown Document ordered export surface
`; const $ = (selector) => shadow.querySelector(selector); const $$ = (selector) => Array.from(shadow.querySelectorAll(selector)); const storageKey = 'aetherweave-state'; const fileInput = $('#file-input'); const libraryGrid = $('#library-grid'); const sequenceList = $('#sequence-list'); const previewFrame = $('#live-preview-frame'); const projectNameEl = $('#project-name'); const libraryCountEl = $('#library-count'); const sequenceCountEl = $('#sequence-count'); const trashZone = $('#trash-zone'); const modal = $('#modal'); const modalTitle = $('#modal-title'); const modalBody = $('#modal-body'); const toast = $('#toast'); const libraryDropzone = $('#library-dropzone'); let state = { files: [], sequence: [], projectName: 'Untitled Document' }; let currentModalFileId = null; let draggedId = null; let mobilePickedUpId = null; let toastTimer = 0; function generateId() { return `af-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; } function utf8ToB64(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_, p1) => String.fromCharCode(`0x${p1}`))); } function b64ToUtf8(str) { return decodeURIComponent(atob(str).split('').map((ch) => `%${(`00${ch.charCodeAt(0).toString(16)}`).slice(-2)}`).join('')); } function getSnippet(content, type) { if (String(type || '').includes('image')) return '[IMAGE]'; const text = String(content || ''); return `${text.slice(0, 220)}${text.length > 220 ? '…' : ''}`; } function normalizeFile(file) { return { id: file.id || generateId(), name: file.name || 'Unnamed file', type: file.type || 'text/plain', content: file.content || '', size: Number(file.size) || String(file.content || '').length, snippet: file.snippet || getSnippet(file.content, file.type), timestamp: Number(file.timestamp) || Date.now() }; } function orderedFiles() { return state.sequence.map((id) => state.files.find((file) => file.id === id)).filter(Boolean); } function downloadText(filename, text, mimeType) { const blob = new Blob([text], { type: mimeType }); const url = URL.createObjectURL(blob); const anchor = document.createElement('a'); anchor.href = url; anchor.download = filename; anchor.click(); URL.revokeObjectURL(url); } function showToast(message) { toast.textContent = message; toast.classList.add('visible'); clearTimeout(toastTimer); toastTimer = window.setTimeout(() => { toast.classList.remove('visible'); }, 2600); } function saveToLocalStorage() { localStorage.setItem(storageKey, JSON.stringify({ files: state.files, sequence: state.sequence, projectName: state.projectName })); } function loadFromLocalStorage() { const saved = localStorage.getItem(storageKey); if (!saved) return; try { const parsed = JSON.parse(saved); state.files = Array.isArray(parsed.files) ? parsed.files.map(normalizeFile) : []; state.sequence = Array.isArray(parsed.sequence) ? parsed.sequence.filter((id) => state.files.some((file) => file.id === id)) : []; state.projectName = parsed.projectName || 'Untitled Document'; } catch (error) { console.warn('AetherWeave state restore failed', error); } } function updateProjectName(name) { state.projectName = String(name || '').trim() || 'Untitled Document'; projectNameEl.textContent = state.projectName; saveToLocalStorage(); renderLivePreview(); } function updateFileName(id, nextName) { const file = state.files.find((entry) => entry.id === id); if (!file) return; file.name = String(nextName || '').trim() || 'Unnamed file'; saveToLocalStorage(); renderLibrary(); renderSequence(); renderLivePreview(); } function removeFromLibrary(id) { state.files = state.files.filter((file) => file.id !== id); state.sequence = state.sequence.filter((itemId) => itemId !== id); saveToLocalStorage(); renderLibrary(); renderSequence(); renderLivePreview(); } function removeFromSequence(id) { state.sequence = state.sequence.filter((itemId) => itemId !== id); saveToLocalStorage(); renderSequence(); renderLivePreview(); } function clearSequence() { state.sequence = []; saveToLocalStorage(); renderSequence(); renderLivePreview(); } function clearAll() { if (!window.confirm('Erase everything and start over?')) return; state = { files: [], sequence: [], projectName: 'Untitled Document' }; localStorage.removeItem(storageKey); projectNameEl.textContent = state.projectName; renderLibrary(); renderSequence(); renderLivePreview(); showToast('Reset complete'); } function openModal(id) { const file = state.files.find((entry) => entry.id === id); if (!file) return; currentModalFileId = id; modalTitle.textContent = `Editing ${file.name}`; modalBody.innerHTML = ''; if (String(file.type).includes('image')) { const img = document.createElement('img'); img.src = file.content; img.alt = file.name; img.style.maxWidth = '100%'; img.style.borderRadius = '12px'; modalBody.appendChild(img); } else { const textarea = document.createElement('textarea'); textarea.id = 'modal-textarea'; textarea.className = 'modal-textarea'; textarea.value = file.content; modalBody.appendChild(textarea); } modal.classList.add('open'); modal.setAttribute('aria-hidden', 'false'); } function closeModal() { modal.classList.remove('open'); modal.setAttribute('aria-hidden', 'true'); currentModalFileId = null; modalBody.innerHTML = ''; } function saveModalEdit() { if (!currentModalFileId) return; const file = state.files.find((entry) => entry.id === currentModalFileId); if (!file) return; if (!String(file.type).includes('image')) { const textarea = $('#modal-textarea'); if (textarea) { file.content = textarea.value; file.snippet = getSnippet(file.content, file.type); file.size = textarea.value.length; } } saveToLocalStorage(); closeModal(); renderLibrary(); renderSequence(); renderLivePreview(); } function createLibraryCard(file) { const card = document.createElement('div'); card.className = 'file-card'; card.draggable = true; card.dataset.id = file.id; card.dataset.origin = 'library'; const top = document.createElement('div'); top.className = 'file-card-top'; const name = document.createElement('div'); name.className = 'file-name'; name.contentEditable = 'true'; name.spellcheck = false; name.textContent = file.name; name.addEventListener('blur', () => updateFileName(file.id, name.textContent)); top.appendChild(name); const actions = document.createElement('div'); actions.className = 'card-actions'; const editBtn = document.createElement('button'); editBtn.type = 'button'; editBtn.className = 'card-icon-btn'; editBtn.title = 'Edit file'; editBtn.textContent = '✎'; editBtn.addEventListener('click', (event) => { event.stopPropagation(); openModal(file.id); }); const removeBtn = document.createElement('button'); removeBtn.type = 'button'; removeBtn.className = 'card-icon-btn danger'; removeBtn.title = 'Remove file'; removeBtn.textContent = '×'; removeBtn.addEventListener('click', (event) => { event.stopPropagation(); removeFromLibrary(file.id); }); actions.append(editBtn, removeBtn); top.appendChild(actions); const typeEl = document.createElement('div'); typeEl.className = 'file-type'; typeEl.textContent = file.type || 'text/plain'; const snippet = document.createElement('div'); snippet.className = 'snippet'; snippet.textContent = file.snippet || getSnippet(file.content, file.type); const meta = document.createElement('div'); meta.className = 'meta-row'; meta.innerHTML = `${(file.size / 1024).toFixed(1)} KB${new Date(file.timestamp).toLocaleDateString()}`; card.append(top, typeEl, snippet, meta); bindCardInteractions(card, file.id, 'library'); return card; } function createSequenceCard(file, index) { const card = document.createElement('div'); card.className = 'file-card'; card.draggable = true; card.dataset.id = file.id; card.dataset.origin = 'sequence'; const top = document.createElement('div'); top.className = 'file-card-top'; const indexBadge = document.createElement('span'); indexBadge.className = 'sequence-index'; indexBadge.textContent = String(index + 1); top.appendChild(indexBadge); const name = document.createElement('div'); name.className = 'file-name'; name.contentEditable = 'true'; name.spellcheck = false; name.textContent = file.name; name.addEventListener('blur', () => updateFileName(file.id, name.textContent)); top.appendChild(name); const actions = document.createElement('div'); actions.className = 'card-actions'; const removeBtn = document.createElement('button'); removeBtn.type = 'button'; removeBtn.className = 'card-icon-btn danger'; removeBtn.title = 'Remove from sequence'; removeBtn.textContent = '×'; removeBtn.addEventListener('click', (event) => { event.stopPropagation(); removeFromSequence(file.id); }); actions.appendChild(removeBtn); top.appendChild(actions); const snippet = document.createElement('div'); snippet.className = 'snippet'; snippet.textContent = file.snippet || getSnippet(file.content, file.type); card.append(top, snippet); bindCardInteractions(card, file.id, 'sequence'); return card; } function renderLibrary() { libraryGrid.innerHTML = ''; libraryCountEl.textContent = String(state.files.length); if (!state.files.length) { const empty = document.createElement('div'); empty.className = 'empty-state'; empty.textContent = 'Import files to build the library.'; libraryGrid.appendChild(empty); return; } state.files.forEach((file) => { libraryGrid.appendChild(createLibraryCard(file)); }); } function renderSequence() { sequenceList.innerHTML = ''; sequenceCountEl.textContent = String(state.sequence.length); const files = orderedFiles(); if (!files.length) { const empty = document.createElement('div'); empty.className = 'empty-state'; empty.textContent = 'Drop files here in the order you want them exported.'; sequenceList.appendChild(empty); return; } files.forEach((file, index) => { sequenceList.appendChild(createSequenceCard(file, index)); }); } function renderLivePreview() { previewFrame.innerHTML = ''; const files = orderedFiles(); if (!files.length) { const empty = document.createElement('div'); empty.className = 'preview-empty'; empty.textContent = 'Drag files from the library into the sequence to preview the final mega document.'; previewFrame.appendChild(empty); return; } const title = document.createElement('div'); title.className = 'preview-page'; const heading = document.createElement('h2'); heading.style.margin = '0 0 10px'; heading.style.fontSize = '1.25rem'; heading.textContent = state.projectName; const summary = document.createElement('div'); summary.style.fontSize = '0.85rem'; summary.style.color = '#50606e'; summary.textContent = `Generated by AetherWeave • ${new Date().toLocaleString()} • ${files.length} file${files.length === 1 ? '' : 's'}`; title.append(heading, summary); previewFrame.appendChild(title); files.forEach((file, index) => { const page = document.createElement('div'); page.className = 'preview-page'; const h3 = document.createElement('h3'); h3.style.margin = '0 0 10px'; h3.textContent = `${index + 1}. ${file.name}`; page.appendChild(h3); if (String(file.type).includes('image')) { const img = document.createElement('img'); img.src = file.content; img.alt = file.name; img.style.maxWidth = '100%'; img.style.borderRadius = '10px'; page.appendChild(img); } else { const pre = document.createElement('pre'); pre.style.margin = '0'; pre.style.padding = '14px'; pre.style.background = '#f5f8fb'; pre.style.borderRadius = '10px'; pre.style.whiteSpace = 'pre-wrap'; pre.style.wordBreak = 'break-word'; pre.style.maxHeight = '280px'; pre.style.overflow = 'auto'; pre.textContent = `${file.content.slice(0, 1200)}${file.content.length > 1200 ? '\n… (truncated for preview)' : ''}`; page.appendChild(pre); } previewFrame.appendChild(page); }); } function getDragAfterElement(container, y) { const cards = [...container.querySelectorAll('.file-card:not(.dragging)')]; return cards.reduce((closest, child) => { const box = child.getBoundingClientRect(); const offset = y - box.top - box.height / 2; if (offset < 0 && offset > closest.offset) { return { offset, element: child }; } return closest; }, { offset: Number.NEGATIVE_INFINITY, element: null }).element; } function placeInSequence(id, beforeId = null) { if (!state.files.some((file) => file.id === id)) return; state.sequence = state.sequence.filter((itemId) => itemId !== id); if (beforeId && state.sequence.includes(beforeId)) { const targetIndex = state.sequence.indexOf(beforeId); state.sequence.splice(targetIndex, 0, id); } else { state.sequence.push(id); } saveToLocalStorage(); renderSequence(); renderLivePreview(); } function bindCardInteractions(card, id, origin) { card.addEventListener('dragstart', () => { draggedId = id; card.classList.add('dragging'); trashZone.classList.add('active'); }); card.addEventListener('dragend', () => { draggedId = null; card.classList.remove('dragging'); trashZone.classList.remove('active'); }); let lastTap = 0; card.addEventListener('touchend', (event) => { if (event.target.closest('button')) return; const now = Date.now(); if (now - lastTap < 300) { event.preventDefault(); mobilePickedUpId = id; $$('.file-card').forEach((entry) => entry.classList.remove('picked-up-mobile')); card.classList.add('picked-up-mobile'); showToast(origin === 'sequence' ? 'Picked up from sequence.' : 'Picked up from library.'); } lastTap = now; }, { passive: false }); } async function handleFiles(fileList) { let files = Array.from(fileList || []); if (!files.length) return; if (files.length > 30) { showToast('Maximum 30 files at a time. Trimming the rest.'); files = files.slice(0, 30); } const imported = await Promise.all(files.map((file) => new Promise((resolve) => { const reader = new FileReader(); if (file.type.startsWith('image/')) { reader.onload = (event) => resolve(normalizeFile({ name: file.name, type: file.type, content: event.target.result, size: file.size, timestamp: Date.now() })); reader.readAsDataURL(file); return; } reader.onload = (event) => resolve(normalizeFile({ name: file.name, type: file.type || 'text/plain', content: event.target.result, size: file.size, timestamp: Date.now() })); reader.readAsText(file); }))); state.files = [...state.files, ...imported]; saveToLocalStorage(); renderLibrary(); showToast(`Imported ${imported.length} file${imported.length === 1 ? '' : 's'}.`); } function importProject() { const input = document.createElement('input'); input.type = 'file'; input.accept = '.json,.b64'; input.addEventListener('change', (event) => { const file = event.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = (loadEvent) => { let raw = String(loadEvent.target?.result || ''); if (file.name.endsWith('.b64') || (!raw.trim().startsWith('{') && raw.trim().length > 1000)) { try { raw = b64ToUtf8(raw.trim()); } catch (error) { console.warn('AetherWeave B64 decode failed', error); } } try { const imported = JSON.parse(raw); state.files = Array.isArray(imported.files) ? imported.files.map(normalizeFile) : []; state.sequence = Array.isArray(imported.sequence) ? imported.sequence.filter((id) => state.files.some((fileEntry) => fileEntry.id === id)) : []; state.projectName = imported.projectName || 'Imported Document'; projectNameEl.textContent = state.projectName; saveToLocalStorage(); renderLibrary(); renderSequence(); renderLivePreview(); showToast('Project loaded successfully.'); } catch (error) { showToast('Invalid project file.'); } }; reader.readAsText(file); }); input.click(); } function exportProjectJSON() { downloadText(`${state.projectName.replace(/\s+/g, '-')}-project.json`, JSON.stringify({ files: state.files, sequence: state.sequence, projectName: state.projectName }, null, 2), 'application/json'); showToast('Project JSON exported.'); } function exportProjectB64() { const encoded = utf8ToB64(JSON.stringify({ files: state.files, sequence: state.sequence, projectName: state.projectName })); downloadText(`${state.projectName.replace(/\s+/g, '-')}-project.b64`, encoded, 'text/plain'); showToast('Project B64 exported.'); } function exportMegaMarkdown() { const files = orderedFiles(); if (!files.length) { showToast('Add files to the sequence first.'); return; } let markdown = `# ${state.projectName}\n\n`; markdown += `Generated by AetherWeave • ${new Date().toLocaleString()}\n\n`; markdown += `Total files: ${files.length}\n\n---\n\n`; files.forEach((file, index) => { const ext = String(file.name.split('.').pop() || '').toLowerCase(); const lang = ({ js: 'javascript', md: 'markdown' })[ext] || ext || 'text'; markdown += `## ${index + 1}. ${file.name} (${(file.size / 1024).toFixed(1)} KB)\n\n`; if (String(file.type).includes('image')) { markdown += `![${file.name}](${file.content})\n\n`; } else { markdown += `\`\`\`${lang}\n${file.content}\n\`\`\`\n\n`; } markdown += `---\n\n`; }); downloadText(`${state.projectName.replace(/\s+/g, '-')}-MEGA.md`, markdown, 'text/markdown'); showToast('Mega Markdown exported.'); } function setupSequenceDnD() { sequenceList.addEventListener('dragover', (event) => { event.preventDefault(); }); sequenceList.addEventListener('drop', (event) => { event.preventDefault(); if (!draggedId) return; const afterElement = getDragAfterElement(sequenceList, event.clientY); placeInSequence(draggedId, afterElement?.dataset.id || null); }); sequenceList.addEventListener('touchend', () => { if (!mobilePickedUpId) return; placeInSequence(mobilePickedUpId); mobilePickedUpId = null; $$('.file-card').forEach((entry) => entry.classList.remove('picked-up-mobile')); showToast('Placed in sequence.'); }, { passive: true }); libraryGrid.addEventListener('touchend', () => { if (!mobilePickedUpId) return; if (state.sequence.includes(mobilePickedUpId)) { removeFromSequence(mobilePickedUpId); showToast('Returned to library.'); } mobilePickedUpId = null; $$('.file-card').forEach((entry) => entry.classList.remove('picked-up-mobile')); }, { passive: true }); trashZone.addEventListener('dragover', (event) => { event.preventDefault(); }); trashZone.addEventListener('drop', (event) => { event.preventDefault(); if (!draggedId) return; if (state.sequence.includes(draggedId)) removeFromSequence(draggedId); else removeFromLibrary(draggedId); draggedId = null; trashZone.classList.remove('active'); }); } function setupGlobalDrop() { const shell = $('.shell'); let dragDepth = 0; shell.addEventListener('dragenter', (event) => { event.preventDefault(); dragDepth += 1; libraryDropzone.classList.add('active'); }); shell.addEventListener('dragover', (event) => { event.preventDefault(); }); shell.addEventListener('dragleave', (event) => { event.preventDefault(); dragDepth = Math.max(0, dragDepth - 1); if (!dragDepth) libraryDropzone.classList.remove('active'); }); shell.addEventListener('drop', (event) => { event.preventDefault(); dragDepth = 0; libraryDropzone.classList.remove('active'); if (event.dataTransfer?.files?.length) handleFiles(event.dataTransfer.files); }); } function setupPanelMinimize() { $$('[data-panel] .panel-header').forEach((header) => { const toggleMinimize = (event) => { if (event.target.closest('button')) return; header.parentElement.classList.toggle('minimized'); }; header.addEventListener('dblclick', toggleMinimize); let lastTap = 0; header.addEventListener('touchend', (event) => { if (event.target.closest('button')) return; const now = Date.now(); if (now - lastTap < 300) { event.preventDefault(); toggleMinimize(event); } lastTap = now; }, { passive: false }); }); } $('#import-files-btn').addEventListener('click', () => fileInput.click()); fileInput.addEventListener('change', (event) => { if (event.target.files?.length) handleFiles(event.target.files); event.target.value = ''; }); $('#load-project-btn').addEventListener('click', importProject); $('#export-json-btn').addEventListener('click', exportProjectJSON); $('#export-b64-btn').addEventListener('click', exportProjectB64); $('#export-markdown-btn').addEventListener('click', exportMegaMarkdown); $('#reset-btn').addEventListener('click', clearAll); $('#clear-sequence-btn').addEventListener('click', (event) => { event.stopPropagation(); clearSequence(); }); projectNameEl.addEventListener('blur', () => updateProjectName(projectNameEl.textContent)); $('#close-modal-btn').addEventListener('click', closeModal); $('#cancel-modal-btn').addEventListener('click', closeModal); $('#save-modal-btn').addEventListener('click', saveModalEdit); modal.addEventListener('click', (event) => { if (event.target === modal) closeModal(); }); loadFromLocalStorage(); projectNameEl.textContent = state.projectName; renderLibrary(); renderSequence(); renderLivePreview(); setupSequenceDnD(); setupGlobalDrop(); setupPanelMinimize(); } function openCodexCard() { ensureCodexLoaded(); restoreCard(codexCard); codexCard.style.display = 'flex'; ensureCardPlacement(codexCard); bringCardToFront(codexCard); toggleCodexBtn.classList.add('active'); } function closeCodexCard() { closeCard(codexCard); } toggleCodexBtn.addEventListener('click', () => { if (isCardVisible(codexCard)) closeCodexCard(); else openCodexCard(); }); let aetherMounted = false; function ensureAetherMounted() { if (aetherMounted) return; mountAetherWeaveIntoRoot(); aetherMounted = true; } function openAetherCard() { ensureAetherMounted(); restoreCard(aetherCard); aetherCard.style.display = 'flex'; ensureCardPlacement(aetherCard); bringCardToFront(aetherCard); toggleAetherBtn.classList.add('active'); } function closeAetherCard() { closeCard(aetherCard); } toggleAetherBtn.addEventListener('click', () => { if (isCardVisible(aetherCard)) closeAetherCard(); else openAetherCard(); }); toggleWorkchatBtn.addEventListener('click', () => { const hidden = getComputedStyle(workchatWidget).display === 'none'; if (workchatWidget.classList.contains('is-minimized')) { restoreCard(workchatWidget); workchatWidget.style.display = 'flex'; ensureCardPlacement(workchatWidget); bringCardToFront(workchatWidget); ensureWorkchatLoaded(); return; } workchatWidget.style.display = hidden ? 'flex' : 'none'; if (!hidden) stopCardMotion(workchatWidget); if (hidden) { ensureCardPlacement(workchatWidget); bringCardToFront(workchatWidget); ensureWorkchatLoaded(); } syncCardToggleState(workchatWidget); }); workchatFrame?.addEventListener('load', () => { clearTimeout(workchatLoadTimer); setWorkchatStatus(`Mounted: ${WORKCHAT_URL}`); }); workchatFrame?.addEventListener('error', () => { clearTimeout(workchatLoadTimer); setWorkchatStatus('Mount failed. Open in tab to verify.'); }); openWorkchatTabBtn?.addEventListener('click', () => { window.open(WORKCHAT_URL, '_blank', 'noopener'); }); toggleCodeViewBtn.addEventListener('pointerdown', (e) => { if (e.button !== undefined && e.button !== 0) return; codeButtonHoldTriggered = false; clearCodeButtonHold(); codeButtonHoldTimer = window.setTimeout(() => { codeButtonHoldTriggered = true; openHybridViewCard(); }, 2000); }); ['pointerup', 'pointercancel', 'pointerleave'].forEach((eventName) => { toggleCodeViewBtn.addEventListener(eventName, clearCodeButtonHold); }); toggleCodeViewBtn.addEventListener('click', (e) => { if (codeButtonHoldTriggered) { e.preventDefault(); codeButtonHoldTriggered = false; return; } toggleMainSurfaceMode(); }); hybridLayoutMode.addEventListener('change', applyHybridLayout); hybridDivider.addEventListener('input', applyHybridLayout); document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { const fullscreenCard = document.querySelector('.floating-card.is-fullscreen'); if (fullscreenCard) { toggleCardFullscreen(fullscreenCard); return; } if (isCardVisible(aetherCard)) { closeAetherCard(); return; } if (isCardVisible(codexCard)) closeCodexCard(); } }); // ========================================== // GALLERY & LIGHTBOX UI LOGIC // ========================================== const galleryWidget = document.getElementById('gallery-widget'); const ingestWidget = document.getElementById('ingest-widget'); const galleryList = document.getElementById('gallery-list'); const searchInput = document.getElementById('search-input'); const toggleGalleryBtn = document.getElementById('toggle-gallery'); const toggleIngestBtn = document.getElementById('toggle-ingest'); const ingestModeInput = document.getElementById('ingest-mode'); const ingestModuleTypeInput = document.getElementById('ingest-module-type'); const ingestTitleInput = document.getElementById('ingest-title'); const ingestCategoryInput = document.getElementById('ingest-category'); const ingestSummaryInput = document.getElementById('ingest-summary'); const ingestExportsInput = document.getElementById('ingest-exports'); const ingestDependenciesInput = document.getElementById('ingest-dependencies'); const ingestTagsInput = document.getElementById('ingest-tags'); const lbOverlay = document.getElementById('lightbox-overlay'); const lbTitle = document.getElementById('lb-title'); const lbCat = document.getElementById('lb-cat'); const lbSummary = document.getElementById('lb-summary'); const lbMeta = document.getElementById('lb-meta'); const lbCodePreview = document.getElementById('lb-code-preview'); const lbInjectMode = document.getElementById('lb-inject-mode'); const lbInjectBtn = document.getElementById('lb-inject-btn'); const lbCloseBtn = document.getElementById('lb-close'); let activeModule = null; const toolbarPreviewBtn = document.getElementById('toolbar-preview'); const toolbarCopyBtn = document.getElementById('toolbar-copy'); const toolbarDownloadBtn = document.getElementById('toolbar-download'); function getSelectedCodeSnippet() { const start = codeInput.selectionStart ?? 0; const end = codeInput.selectionEnd ?? 0; return end > start ? codeInput.value.slice(start, end) : ''; } async function copyTextToClipboard(text) { const payload = String(text || ''); if (!payload) return; if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(payload); return; } const ghost = document.createElement('textarea'); ghost.value = payload; ghost.setAttribute('readonly', 'readonly'); ghost.style.position = 'fixed'; ghost.style.opacity = '0'; ghost.style.pointerEvents = 'none'; document.body.appendChild(ghost); ghost.select(); document.execCommand('copy'); ghost.remove(); } function bumpToolbarButton(button, label) { if (!button) return; const span = button.querySelector('span'); const originalTitle = button.dataset.originalTitle || button.title || ''; button.dataset.originalTitle = originalTitle; button.classList.add('active'); if (span) { const originalLabel = button.dataset.originalLabel || span.textContent; button.dataset.originalLabel = originalLabel; span.textContent = label; } else { button.title = label; button.setAttribute('aria-label', label); } clearTimeout(button._bumpTimer); button._bumpTimer = window.setTimeout(() => { button.classList.remove('active'); if (span) span.textContent = button.dataset.originalLabel || span.textContent; button.title = button.dataset.originalTitle || originalTitle; if (button.hasAttribute('aria-label')) button.setAttribute('aria-label', button.title); }, 1200); } function toggleGalleryWidget() { if (!galleryWidget) return; const isHidden = getComputedStyle(galleryWidget).display === 'none'; if (galleryWidget.classList.contains('is-minimized')) { restoreCard(galleryWidget); galleryWidget.style.display = 'flex'; ensureCardPlacement(galleryWidget); bringCardToFront(galleryWidget); renderGallery(searchInput.value || ''); searchInput.focus(); return; } if (isHidden) { galleryWidget.style.display = 'flex'; ensureCardPlacement(galleryWidget); bringCardToFront(galleryWidget); renderGallery(searchInput.value || ''); searchInput.focus(); syncCardToggleState(galleryWidget); return; } closeCard(galleryWidget); } function toggleIngestWidget() { if (!ingestWidget) return; const isHidden = getComputedStyle(ingestWidget).display === 'none'; if (ingestWidget.classList.contains('is-minimized')) { restoreCard(ingestWidget); ingestWidget.style.display = 'flex'; ensureCardPlacement(ingestWidget); bringCardToFront(ingestWidget); ingestTitleInput.focus(); return; } if (isHidden) { ingestWidget.style.display = 'flex'; ensureCardPlacement(ingestWidget); bringCardToFront(ingestWidget); updateIngestModeUI(); ingestTitleInput.focus(); syncCardToggleState(ingestWidget); return; } closeCard(ingestWidget); } function updateIngestModeUI() { const mode = ingestModeInput.value || 'module'; const isSplitter = mode === 'splitter'; const isSnippet = mode === 'snippet'; ingestModuleTypeInput.disabled = isSplitter; if (isSplitter) { ingestModuleTypeInput.value = 'manifest'; } else if (ingestModuleTypeInput.value === 'manifest') { ingestModuleTypeInput.value = ''; } ingestExportsInput.disabled = isSplitter; ingestDependenciesInput.disabled = false; ingestSummaryInput.placeholder = isSplitter ? 'Whole-editor ingest will auto derive metadata from the current source.' : isSnippet ? 'Brief description for the selected snippet...' : 'Brief description...'; } function splitCsvList(value) { return String(value || '') .split(',') .map(item => item.trim()) .filter(Boolean); } function uniqueList(items) { return Array.from(new Set((items || []).filter(Boolean))); } function humanizeModuleType(value) { const map = { snippet: 'Snippet', style: 'Style', component: 'Component', runtime: 'Runtime', feature: 'Feature', data: 'Data', manifest: 'Manifest' }; return map[value] || 'Module'; } function mapLanguageName(languageKey) { const map = { js: 'javascript', html: 'html', css: 'css' }; return map[languageKey] || 'javascript'; } function inferModuleType(category, code, explicitType = '') { if (explicitType) return explicitType; const loweredCategory = String(category || '').toLowerCase(); const languageKey = detectLanguage(code || ''); if (languageKey === 'css') return 'style'; if (languageKey === 'html') return 'component'; if (/ui|component|widget|layout/.test(loweredCategory)) return 'component'; if (/runtime|engine|simulation|system|parser|backend|physics/.test(loweredCategory)) return 'runtime'; if (/data|schema|json|store/.test(loweredCategory)) return 'data'; if (/feature|interaction|workflow|export/.test(loweredCategory)) return 'feature'; if (/manifest|project|page/.test(loweredCategory)) return 'manifest'; return 'snippet'; } function inferExportsFromCode(code, language) { if (language !== 'javascript') return []; const exports = []; const pushMatch = (regex) => { for (const match of code.matchAll(regex)) { if (match[1]) exports.push(match[1]); } }; pushMatch(/function\s+([A-Za-z_$][\w$]*)\s*\(/g); pushMatch(/class\s+([A-Za-z_$][\w$]*)\s*/g); pushMatch(/(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/g); pushMatch(/(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*\(/g); return uniqueList(exports).slice(0, 24); } function inferImportsFromCode(code) { const imports = []; for (const match of code.matchAll(/import\s+(?:[\s\S]*?)\s+from\s+["']([^"']+)["']/g)) { imports.push(match[1]); } return uniqueList(imports).slice(0, 24); } function inferSelectorsFromCode(code) { const selectors = []; for (const match of code.matchAll(/getElementById\(\s*["']([^"']+)["']\s*\)/g)) { selectors.push(`#${match[1]}`); } for (const match of code.matchAll(/querySelector(?:All)?\(\s*["']([^"']+)["']\s*\)/g)) { selectors.push(match[1]); } return uniqueList(selectors).slice(0, 24); } function inferEventsFromCode(code) { const events = []; for (const match of code.matchAll(/addEventListener\(\s*["']([^"']+)["']/g)) { events.push(match[1]); } return uniqueList(events).slice(0, 24); } function extractStyleBlocksFromCode(code, language) { const blocks = []; for (const match of code.matchAll(/]*>([\s\S]*?)<\/style>/gi)) { const value = match[1].trim(); if (value) blocks.push(value); } if (!blocks.length && language === 'css') { const value = code.trim(); if (value) blocks.push(value); } return blocks; } function extractTemplateBlocksFromCode(code, language) { const blocks = []; if (language === 'html') { const value = code.trim(); if (value) blocks.push(value); } for (const match of code.matchAll(/`([\s\S]*?<\w[\s\S]*?>[\s\S]*?)`/g)) { const value = match[1].trim(); if (value) blocks.push(value); } return uniqueList(blocks).slice(0, 12); } function normalizeModuleRecord(mod) { const codeSnippet = String(mod.codeSnippet || ''); const languageKey = detectLanguage(codeSnippet); const language = mod.language || mapLanguageName(languageKey); const moduleType = inferModuleType(mod.category || '', codeSnippet, mod.moduleType || ''); const tags = uniqueList(Array.isArray(mod.tags) ? mod.tags : splitCsvList(mod.tags)); const dependencies = uniqueList(Array.isArray(mod.dependencies) ? mod.dependencies : splitCsvList(mod.dependencies)); const exportsList = uniqueList(Array.isArray(mod.exports) ? mod.exports : splitCsvList(mod.exports)); const importsList = uniqueList(Array.isArray(mod.imports) ? mod.imports : inferImportsFromCode(codeSnippet)); const selectors = uniqueList(Array.isArray(mod.selectors) ? mod.selectors : inferSelectorsFromCode(codeSnippet)); const events = uniqueList(Array.isArray(mod.events) ? mod.events : inferEventsFromCode(codeSnippet)); const styleBlocks = Array.isArray(mod.styleBlocks) ? mod.styleBlocks : extractStyleBlocksFromCode(codeSnippet, languageKey); const templateBlocks = Array.isArray(mod.templateBlocks) ? mod.templateBlocks : extractTemplateBlocksFromCode(codeSnippet, languageKey); return { ...mod, category: mod.category || humanizeModuleType(moduleType), summary: mod.summary || 'No summary provided.', moduleType, language, tags, dependencies, exports: exportsList.length ? exportsList : inferExportsFromCode(codeSnippet, language), imports: importsList, selectors, events, styleBlocks, templateBlocks, codeSnippet, createdAt: mod.createdAt || new Date().toISOString(), updatedAt: mod.updatedAt || mod.createdAt || new Date().toISOString(), sourceMode: mod.sourceMode || 'snippet' }; } function refreshManifest() { MANIFEST = Backend.getTable('tools').map(normalizeModuleRecord); } function renderGallery(filterText = '') { galleryList.innerHTML = ''; const lowerFilter = filterText.toLowerCase().trim(); const modules = (MANIFEST || []).map(normalizeModuleRecord); const filtered = modules.filter(mod => { if (!lowerFilter) return true; const haystack = [ mod.title, mod.category, mod.summary, mod.moduleType, mod.language, ...(mod.tags || []), ...(mod.dependencies || []), ...(mod.exports || []) ].join(' ').toLowerCase(); return haystack.includes(lowerFilter); }); if (!filtered.length) { galleryList.innerHTML = ''; return; } filtered.forEach(mod => { const div = document.createElement('div'); div.className = 'gallery-item'; const pills = [ `${humanizeModuleType(mod.moduleType)}`, `${mod.language}` ]; (mod.tags || []).slice(0, 2).forEach(tag => pills.push(`${tag}`)); div.innerHTML = `

${mod.title}

${mod.summary}

`; div.onclick = () => openLightbox(mod); galleryList.appendChild(div); }); } function renderLightboxMeta(mod) { const metaItems = [ ['Type', humanizeModuleType(mod.moduleType)], ['Language', mod.language], ['Exports', (mod.exports || []).slice(0, 3).join(', ') || '—'], ['Dependencies', (mod.dependencies || []).slice(0, 3).join(', ') || '—'] ]; lbMeta.innerHTML = metaItems.map(([label, value]) => `
${label} ${value}
`).join(''); } function openLightbox(mod) { activeModule = normalizeModuleRecord(mod); lbTitle.textContent = activeModule.title; lbCat.textContent = `${activeModule.category} • ${humanizeModuleType(activeModule.moduleType)}`; lbSummary.textContent = activeModule.summary; lbCodePreview.textContent = activeModule.codeSnippet.slice(0, 900); renderLightboxMeta(activeModule); lbOverlay.style.display = 'grid'; } function closeLightbox() { lbOverlay.style.display = 'none'; activeModule = null; } lbCloseBtn.onclick = closeLightbox; lbOverlay.onclick = (e) => { if (e.target === lbOverlay) closeLightbox(); }; function insertAtCursor(insertText) { const start = codeInput.selectionStart ?? 0; const end = codeInput.selectionEnd ?? 0; const before = codeInput.value.slice(0, start); const after = codeInput.value.slice(end); codeInput.value = `${before}${insertText}${after}`; const nextPos = start + insertText.length; codeInput.focus(); codeInput.selectionStart = codeInput.selectionEnd = nextPos; syncEditor(); codeInput.dispatchEvent(new Event('scroll')); } function resolveDependencyModules(mod, seen = new Set()) { const resolved = []; const deps = mod.dependencies || []; deps.forEach(depName => { const key = String(depName).trim().toLowerCase(); if (!key || seen.has(key)) return; const match = (MANIFEST || []) .map(normalizeModuleRecord) .find(candidate => [candidate.id, candidate.title, `${candidate.moduleType}.${candidate.title}`] .map(value => String(value || '').toLowerCase()) .includes(key)); if (!match) return; seen.add(key); resolved.push(...resolveDependencyModules(match, seen)); resolved.push(match); }); return resolved; } function formatModuleForInjection(mod, options = {}) { const normalized = normalizeModuleRecord(mod); const blocks = [`// --- Injected ${humanizeModuleType(normalized.moduleType)}: ${normalized.title} ---`]; const shouldWrapStyle = normalized.moduleType === 'style' && !/]/i.test(normalized.codeSnippet); const stylePayload = (normalized.styleBlocks || []).join('\n\n').trim(); if (options.includeStyles && stylePayload) { blocks.push(``); } if (shouldWrapStyle) { blocks.push(``); } else { blocks.push(normalized.codeSnippet.trim()); } return blocks.filter(Boolean).join('\n'); } function buildInjectionSnippet(mod, mode = 'raw') { const normalized = normalizeModuleRecord(mod); const includeDependencies = mode === 'with-dependencies' || mode === 'full'; const includeStyles = mode === 'with-styles' || mode === 'full'; const sections = []; if (includeDependencies) { resolveDependencyModules(normalized).forEach(dep => { sections.push(formatModuleForInjection(dep, { includeStyles })); }); } sections.push(formatModuleForInjection(normalized, { includeStyles })); return `${sections.join('\n\n')}\n\n`; } function buildStructuredModuleRecord() { const title = ingestTitleInput.value.trim(); const category = ingestCategoryInput.value.trim(); const summary = ingestSummaryInput.value.trim(); const mode = ingestModeInput.value || 'module'; let code = codeInput.value.substring(codeInput.selectionStart, codeInput.selectionEnd); if (!code || mode === 'splitter') code = codeInput.value; if (!title || !code.trim()) { alert('Title and code snippet required.'); return null; } const languageKey = detectLanguage(code); const language = mapLanguageName(languageKey); const moduleType = mode === 'splitter' ? 'manifest' : inferModuleType(category, code, ingestModuleTypeInput.value || ''); const manualExports = splitCsvList(ingestExportsInput.value); const manualDependencies = splitCsvList(ingestDependenciesInput.value); const manualTags = splitCsvList(ingestTagsInput.value); const autoExports = mode === 'snippet' ? [] : inferExportsFromCode(code, language); const autoDependencies = mode === 'snippet' ? [] : inferImportsFromCode(code); const styleBlocks = mode === 'snippet' ? [] : extractStyleBlocksFromCode(code, languageKey); const templateBlocks = mode === 'snippet' ? [] : extractTemplateBlocksFromCode(code, languageKey); return normalizeModuleRecord({ id: `mod_${Date.now().toString(36)}`, title, category: category || humanizeModuleType(moduleType), summary, moduleType, language, codeSnippet: code, exports: manualExports.length ? manualExports : autoExports, imports: autoDependencies, selectors: mode === 'snippet' ? [] : inferSelectorsFromCode(code), events: mode === 'snippet' ? [] : inferEventsFromCode(code), dependencies: uniqueList([...manualDependencies, ...autoDependencies]), styleBlocks, templateBlocks, tags: uniqueList([...manualTags, mode, moduleType, language]), sourceMode: mode, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }); } searchInput.addEventListener('input', (e) => { renderGallery(e.target.value || ''); }); toggleGalleryBtn.addEventListener('click', toggleGalleryWidget); toggleIngestBtn.addEventListener('click', toggleIngestWidget); ingestModeInput.addEventListener('change', updateIngestModeUI); lbInjectBtn.addEventListener('click', () => { if (!activeModule) return; setMainSurfaceMode('code'); const mode = lbInjectMode.value || 'raw'; insertAtCursor(buildInjectionSnippet(activeModule, mode)); closeLightbox(); }); toolbarPreviewBtn?.addEventListener('click', () => { setMainSurfaceMode('preview'); }); toolbarCopyBtn?.addEventListener('click', async () => { const selection = getSelectedCodeSnippet(); const payload = selection || codeInput.value; try { await copyTextToClipboard(payload); bumpToolbarButton(toolbarCopyBtn, 'Copied'); } catch (error) { console.error(error); alert('Copy failed.'); } }); toolbarDownloadBtn?.addEventListener('click', () => { const payload = codeInput.value || ''; downloadTextFile('system-core-workbench-export.html', payload); bumpToolbarButton(toolbarDownloadBtn, 'Saved'); }); document.getElementById('btn-save-module').addEventListener('click', () => { const newMod = buildStructuredModuleRecord(); if (!newMod) return; Backend.insert('tools', newMod); refreshManifest(); renderGallery(searchInput.value || ''); ingestTitleInput.value = ''; ingestCategoryInput.value = ''; ingestSummaryInput.value = ''; ingestExportsInput.value = ''; ingestDependenciesInput.value = ''; ingestTagsInput.value = ''; ingestModeInput.value = 'module'; ingestModuleTypeInput.value = ''; updateIngestModeUI(); closeCard(ingestWidget); }); // ========================================== // GLOBAL FLOATING CARD LOGIC // ========================================== const cardTray = document.getElementById('card-tray'); const cardMotion = new Map(); let cardTicker = false; let topCardZ = 220; const CARD_FRICTION = 0.92; const CARD_MIN_SPEED = 0.08; const CARD_BOUNCE = 0.42; const CARD_MIN_WIDTH = 280; const CARD_MIN_HEIGHT = 180; const CARD_MARGIN = 12; const CARD_TOP_SAFE = 60; const cardDefaults = { 'gallery-widget': { x: Math.max(CARD_MARGIN, window.innerWidth - 356), y: 72, w: 320, h: Math.min(560, window.innerHeight - 96), display: 'flex' }, 'ingest-widget': { x: Math.max(CARD_MARGIN, window.innerWidth - 416), y: 104, w: 380, h: 470, display: 'flex' }, 'codex-card': { x: 96, y: 72, w: Math.min(960, window.innerWidth - 180), h: Math.min(window.innerHeight - 96, 820), display: 'flex' }, 'aether-card': { x: 72, y: 84, w: Math.min(1320, window.innerWidth - 120), h: Math.min(window.innerHeight - 110, 860), display: 'flex' }, 'synthesis-widget': { x: 24, y: Math.max(72, window.innerHeight - 320), w: Math.min(420, window.innerWidth - 96), h: 286, display: 'block' }, 'workchat-widget': { x: 60, y: 88, w: Math.min(1120, window.innerWidth - 120), h: Math.min(window.innerHeight - 120, 760), display: 'flex' }, 'hybrid-view-card': { x: 60, y: 88, w: Math.min(1100, window.innerWidth - 120), h: Math.min(window.innerHeight - 120, 760), display: 'flex' } }; function getCardDefaultDisplay(card) { return cardDefaults[card.id]?.display || 'block'; } function getCardBounds(width, height) { return { minX: CARD_MARGIN, minY: CARD_TOP_SAFE, maxX: Math.max(CARD_MARGIN, window.innerWidth - width - CARD_MARGIN), maxY: Math.max(CARD_TOP_SAFE, window.innerHeight - height - CARD_MARGIN) }; } function clamp(value, min, max) { return Math.min(Math.max(value, min), max); } function measureCard(card) { const wasHidden = getComputedStyle(card).display === 'none'; const prevDisplay = card.style.display; const prevVisibility = card.style.visibility; if (wasHidden) { card.style.visibility = 'hidden'; card.style.display = getCardDefaultDisplay(card); } const rect = card.getBoundingClientRect(); if (wasHidden) { card.style.display = prevDisplay || 'none'; card.style.visibility = prevVisibility || ''; } return rect; } function fitCardSize(width, height) { const maxW = Math.max(CARD_MIN_WIDTH, window.innerWidth - CARD_MARGIN * 2); const maxH = Math.max(CARD_MIN_HEIGHT, window.innerHeight - CARD_TOP_SAFE - CARD_MARGIN); let w = clamp(width, CARD_MIN_WIDTH, maxW); let h = clamp(height, CARD_MIN_HEIGHT, maxH); if (Math.abs(maxW - w) < 20) w = maxW; if (Math.abs(maxH - h) < 20) h = maxH; return { w, h }; } function applyCardPlacement(card) { if (card.classList.contains('is-fullscreen')) return; const currentW = parseFloat(card.dataset.w) || card.offsetWidth || measureCard(card).width || 320; const currentH = parseFloat(card.dataset.h) || card.offsetHeight || measureCard(card).height || 220; const { w, h } = fitCardSize(currentW, currentH); const bounds = getCardBounds(w, h); const x = clamp(parseFloat(card.dataset.x) || 0, bounds.minX, bounds.maxX); const y = clamp(parseFloat(card.dataset.y) || 0, bounds.minY, bounds.maxY); card.dataset.x = String(x); card.dataset.y = String(y); card.dataset.w = String(w); card.dataset.h = String(h); card.style.left = '0px'; card.style.top = '0px'; card.style.right = 'auto'; card.style.bottom = 'auto'; card.style.width = `${w}px`; card.style.height = `${h}px`; card.style.transform = `translate3d(${x}px, ${y}px, 0)`; } function ensureCardPlacement(card, forceMeasure = false) { if (card.classList.contains('is-fullscreen')) return; const needsMeasure = forceMeasure || !card.dataset.placed; if (!needsMeasure) { applyCardPlacement(card); return; } const rect = measureCard(card); const fallback = cardDefaults[card.id] || { x: CARD_MARGIN, y: CARD_TOP_SAFE, w: rect.width || 320, h: rect.height || 220 }; const firstPlacement = !card.dataset.placed; card.dataset.x = String(firstPlacement ? fallback.x : (rect.left || fallback.x)); card.dataset.y = String(firstPlacement ? fallback.y : (rect.top || fallback.y)); card.dataset.w = String(rect.width || fallback.w); card.dataset.h = String(rect.height || fallback.h); card.dataset.placed = 'true'; applyCardPlacement(card); } function bringCardToFront(card) { topCardZ += 1; card.style.zIndex = String(topCardZ); } function stopCardMotion(card) { const key = card.dataset.cardKey || card.id; cardMotion.delete(key); } function startCardTicker() { if (cardTicker) return; cardTicker = true; requestAnimationFrame(tickCardMotion); } function tickCardMotion() { if (!cardTicker) return; if (!cardMotion.size) { cardTicker = false; return; } for (const [key, motion] of Array.from(cardMotion.entries())) { const card = document.querySelector(`.floating-card[data-card-key="${key}"]`); if (!card || !isCardVisible(card) || card.classList.contains('is-fullscreen')) { cardMotion.delete(key); continue; } const width = parseFloat(card.dataset.w) || card.offsetWidth; const height = parseFloat(card.dataset.h) || card.offsetHeight; const bounds = getCardBounds(width, height); let x = (parseFloat(card.dataset.x) || 0) + motion.vx; let y = (parseFloat(card.dataset.y) || 0) + motion.vy; if (x < bounds.minX) { x = bounds.minX; motion.vx = Math.abs(motion.vx) * CARD_BOUNCE; } else if (x > bounds.maxX) { x = bounds.maxX; motion.vx = -Math.abs(motion.vx) * CARD_BOUNCE; } if (y < bounds.minY) { y = bounds.minY; motion.vy = Math.abs(motion.vy) * CARD_BOUNCE; } else if (y > bounds.maxY) { y = bounds.maxY; motion.vy = -Math.abs(motion.vy) * CARD_BOUNCE; } motion.vx *= CARD_FRICTION; motion.vy *= CARD_FRICTION; card.dataset.x = String(x); card.dataset.y = String(y); applyCardPlacement(card); if (Math.abs(motion.vx) < CARD_MIN_SPEED && Math.abs(motion.vy) < CARD_MIN_SPEED) { cardMotion.delete(key); } } if (cardMotion.size) { requestAnimationFrame(tickCardMotion); } else { cardTicker = false; } } function isCardVisible(card) { return getComputedStyle(card).display !== 'none' && !card.classList.contains('is-minimized'); } function syncCardToggleState(card) { if (card.id === 'gallery-widget') toggleGalleryBtn.classList.toggle('active', isCardVisible(card)); if (card.id === 'ingest-widget') toggleIngestBtn.classList.toggle('active', isCardVisible(card)); if (card.id === 'codex-card') toggleCodexBtn.classList.toggle('active', isCardVisible(card)); if (card.id === 'aether-card') toggleAetherBtn.classList.toggle('active', isCardVisible(card)); if (card.id === 'workchat-widget') toggleWorkchatBtn.classList.toggle('active', isCardVisible(card)); } function ensureCardChip(card) { let chip = cardTray.querySelector(`[data-tray-for="${card.dataset.cardKey}"]`); if (!chip) { chip = document.createElement('button'); chip.type = 'button'; chip.className = 'tray-chip'; chip.dataset.trayFor = card.dataset.cardKey; chip.textContent = `Restore ${card.dataset.cardTitle || card.id}`; chip.addEventListener('click', () => restoreCard(card)); cardTray.appendChild(chip); } return chip; } function toggleCardFullscreen(card) { const buttons = card.querySelectorAll('[data-card-fullscreen]'); if (card.classList.contains('is-fullscreen')) { card.classList.remove('is-fullscreen'); card.dataset.x = card.dataset.prevX || card.dataset.x || '24'; card.dataset.y = card.dataset.prevY || card.dataset.y || '72'; card.dataset.w = card.dataset.prevW || card.dataset.w || String(card.offsetWidth || 320); card.dataset.h = card.dataset.prevH || card.dataset.h || String(card.offsetHeight || 220); buttons.forEach((btn) => btn.classList.remove('is-active')); applyCardPlacement(card); bringCardToFront(card); return; } ensureCardPlacement(card); card.dataset.prevX = card.dataset.x || '24'; card.dataset.prevY = card.dataset.y || '72'; card.dataset.prevW = card.dataset.w || String(card.offsetWidth || 320); card.dataset.prevH = card.dataset.h || String(card.offsetHeight || 220); stopCardMotion(card); card.classList.remove('is-minimized'); card.classList.add('is-fullscreen'); card.style.transform = 'none'; buttons.forEach((btn) => btn.classList.add('is-active')); bringCardToFront(card); } function minimizeCard(card) { if (card.classList.contains('is-fullscreen')) toggleCardFullscreen(card); stopCardMotion(card); card.classList.add('is-minimized'); ensureCardChip(card); syncCardToggleState(card); } function restoreCard(card) { card.classList.remove('is-minimized'); if (!card.style.display || card.style.display === 'none') { card.style.display = getCardDefaultDisplay(card); } const chip = cardTray.querySelector(`[data-tray-for="${card.dataset.cardKey}"]`); if (chip) chip.remove(); ensureCardPlacement(card, !card.dataset.placed); bringCardToFront(card); syncCardToggleState(card); } function closeCard(card) { if (card.classList.contains('is-fullscreen')) toggleCardFullscreen(card); stopCardMotion(card); card.classList.remove('is-minimized'); card.style.display = 'none'; const chip = cardTray.querySelector(`[data-tray-for="${card.dataset.cardKey}"]`); if (chip) chip.remove(); syncCardToggleState(card); } function attachFloatingCard(card) { const handle = card.querySelector('.card-header'); if (!handle) return; ensureCardPlacement(card, true); let dragState = null; let resizeState = null; function ensureResizeHandle() { let resizeHandle = card.querySelector('.card-resize-handle'); if (!resizeHandle) { resizeHandle = document.createElement('button'); resizeHandle.type = 'button'; resizeHandle.className = 'card-resize-handle'; resizeHandle.setAttribute('aria-label', `Resize ${card.dataset.cardTitle || card.id}`); resizeHandle.title = 'Resize'; card.appendChild(resizeHandle); } return resizeHandle; } const resizeHandle = ensureResizeHandle(); handle.addEventListener('pointerdown', (e) => { if (card.classList.contains('is-fullscreen')) return; if (e.target.closest('button, input, textarea, select, a')) return; ensureCardPlacement(card); bringCardToFront(card); stopCardMotion(card); dragState = { pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, baseX: parseFloat(card.dataset.x) || 0, baseY: parseFloat(card.dataset.y) || 0, vx: 0, vy: 0 }; card.classList.add('is-dragging'); handle.setPointerCapture?.(e.pointerId); document.body.style.userSelect = 'none'; e.preventDefault(); }); handle.addEventListener('pointermove', (e) => { if (!dragState || e.pointerId !== dragState.pointerId) return; const width = parseFloat(card.dataset.w) || card.offsetWidth; const height = parseFloat(card.dataset.h) || card.offsetHeight; const bounds = getCardBounds(width, height); const dx = e.clientX - dragState.startX; const dy = e.clientY - dragState.startY; const nextX = clamp(dragState.baseX + dx, bounds.minX, bounds.maxX); const nextY = clamp(dragState.baseY + dy, bounds.minY, bounds.maxY); dragState.vx = nextX - (parseFloat(card.dataset.x) || dragState.baseX); dragState.vy = nextY - (parseFloat(card.dataset.y) || dragState.baseY); card.dataset.x = String(nextX); card.dataset.y = String(nextY); applyCardPlacement(card); }); function endDrag(e) { if (!dragState || (e && e.pointerId !== dragState.pointerId)) return; handle.releasePointerCapture?.(dragState.pointerId); card.classList.remove('is-dragging'); document.body.style.userSelect = ''; const momentum = dragState; dragState = null; if (Math.abs(momentum.vx) > 0.2 || Math.abs(momentum.vy) > 0.2) { cardMotion.set(card.dataset.cardKey || card.id, { vx: momentum.vx, vy: momentum.vy }); startCardTicker(); } } handle.addEventListener('pointerup', endDrag); handle.addEventListener('pointercancel', endDrag); resizeHandle.addEventListener('pointerdown', (e) => { if (card.classList.contains('is-fullscreen')) return; ensureCardPlacement(card); bringCardToFront(card); stopCardMotion(card); resizeState = { pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, startW: parseFloat(card.dataset.w) || card.offsetWidth, startH: parseFloat(card.dataset.h) || card.offsetHeight }; card.classList.add('is-resizing'); resizeHandle.setPointerCapture?.(e.pointerId); document.body.style.userSelect = 'none'; e.preventDefault(); e.stopPropagation(); }); resizeHandle.addEventListener('pointermove', (e) => { if (!resizeState || e.pointerId !== resizeState.pointerId) return; const desiredW = resizeState.startW + (e.clientX - resizeState.startX); const desiredH = resizeState.startH + (e.clientY - resizeState.startY); const { w, h } = fitCardSize(desiredW, desiredH); card.dataset.w = String(w); card.dataset.h = String(h); applyCardPlacement(card); }); function endResize(e) { if (!resizeState || (e && e.pointerId !== resizeState.pointerId)) return; resizeHandle.releasePointerCapture?.(resizeState.pointerId); resizeState = null; card.classList.remove('is-resizing'); document.body.style.userSelect = ''; applyCardPlacement(card); } resizeHandle.addEventListener('pointerup', endResize); resizeHandle.addEventListener('pointercancel', endResize); card.addEventListener('pointerdown', (e) => { if (e.target.closest('.card-resize-handle')) return; bringCardToFront(card); }); card.querySelectorAll('[data-card-minimize]').forEach((btn) => { btn.addEventListener('click', () => minimizeCard(card)); }); card.querySelectorAll('[data-card-close]').forEach((btn) => { btn.addEventListener('click', () => closeCard(card)); }); card.querySelectorAll('[data-card-fullscreen]').forEach((btn) => { btn.addEventListener('click', () => toggleCardFullscreen(card)); }); } window.addEventListener('resize', () => { document.querySelectorAll('.floating-card').forEach((card) => { if (!card.classList.contains('is-fullscreen') && card.dataset.placed) { applyCardPlacement(card); } }); if (hybridViewCard && getComputedStyle(hybridViewCard).display !== 'none') { applyHybridLayout(); } syncEditorLayout(); syncScroll(); }); document.querySelectorAll('.floating-card').forEach(attachFloatingCard); // ========================================== // SYNTHESIS PANEL + CODEX CONTRACTS // ========================================== const synthStatus = document.getElementById('synthStatus'); const synthBlueprintId = document.getElementById('synthBlueprintId'); const synthDnaLength = document.getElementById('synthDnaLength'); const synthRootHash = document.getElementById('synthRootHash'); const synthMessage = document.getElementById('synthMessage'); const synthDnaPreview = document.getElementById('synthDnaPreview'); const copyDnaBtn = document.getElementById('copyDnaBtn'); const downloadBlueprintBtn = document.getElementById('downloadBlueprintBtn'); let lastBlueprint = ""; let lastDnaStrand = ""; let lastReconciliation = null; function setSynthesisStatus(kind, message, blueprintId = "—", dnaLength = "—", hash = "—", dnaPreview = "—") { synthStatus.className = kind === "pass" ? "synth-status-pass" : kind === "fail" ? "synth-status-fail" : "synth-status-wait"; synthStatus.textContent = kind === "pass" ? "PASS" : kind === "fail" ? "FAIL" : "Idle"; synthBlueprintId.textContent = blueprintId; synthDnaLength.textContent = dnaLength; synthRootHash.textContent = hash; synthMessage.textContent = message; synthDnaPreview.textContent = dnaPreview; } function downloadTextFile(filename, textContent) { const blob = new Blob([textContent], { type: "text/plain;charset=utf-8" }); const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = filename; link.click(); URL.revokeObjectURL(link.href); } const BlueprintCompiler = (() => { function generate(rawCode, intentMode = "build", seedId = "genesis-001") { return JSON.stringify({ blueprint_version: "1.0.0", id: `bp_${Date.now().toString(36)}`, created_at: new Date().toISOString(), seed: { source: "workbench_operator", deterministic_seed: seedId, mode: intentMode }, manifest: { type: "tool", status: "active", origin: "native", runtime: "uai-lab", capabilities: { deterministic: true, phaseReconciled: false } }, source: { js_payload: rawCode } }, null, 2); } return { generate }; })(); const GeneticCodec = (() => { const START_CODON = "ATGCGTACGATC"; const STOP_CODON = "TAATAGTAATAG"; const ENCODE_DICT = { "00": "A", "01": "C", "10": "G", "11": "T" }; const DECODE_DICT = { "A": "00", "C": "01", "G": "10", "T": "11" }; function textToBinary(text) { return Array.from(new TextEncoder().encode(text)).map((b) => b.toString(2).padStart(8, "0")).join(""); } function binaryToText(binary) { const bytes = new Uint8Array(binary.length / 8); for (let i = 0; i < binary.length; i += 8) bytes[i / 8] = parseInt(binary.slice(i, i + 8), 2); return new TextDecoder().decode(bytes); } function encodeToDNA(blueprintJson) { const base64Payload = btoa(encodeURIComponent(blueprintJson)); const binaryPayload = textToBinary(base64Payload); let dna = ""; for (let i = 0; i < binaryPayload.length; i += 2) dna += ENCODE_DICT[binaryPayload.slice(i, i + 2).padEnd(2, "0")]; return `${START_CODON}${dna}${STOP_CODON}`; } function decodeFromDNA(dnaStrand) { if (!dnaStrand.startsWith(START_CODON) || !dnaStrand.endsWith(STOP_CODON)) throw new Error("Invalid Codon Framing"); const payloadDna = dnaStrand.slice(START_CODON.length, -STOP_CODON.length); let binaryPayload = ""; for (const char of payloadDna) binaryPayload += DECODE_DICT[char]; const base64Payload = binaryToText(binaryPayload); return decodeURIComponent(atob(base64Payload)); } return { encodeToDNA, decodeFromDNA }; })(); const PhaseReconciler = (() => { async function computeSHA256(text) { const buffer = new TextEncoder().encode(text); const hashBuffer = await crypto.subtle.digest("SHA-256", buffer); const hashArray = Array.from(new Uint8Array(hashBuffer)); return hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); } async function verify(dnaStrand, originalBlueprint) { try { const decodedBlueprint = GeneticCodec.decodeFromDNA(dnaStrand); const originalHash = await computeSHA256(originalBlueprint); const decodedHash = await computeSHA256(decodedBlueprint); const isMatch = originalHash === decodedHash; return { ok: isMatch, originalHash, decodedHash, decodedBlueprint }; } catch (error) { return { ok: false, error: error.message }; } } return { verify, computeSHA256 }; })(); copyDnaBtn.addEventListener("click", async () => { if (!lastDnaStrand) { setSynthesisStatus("idle", "No DNA strand synthesized yet."); return; } await navigator.clipboard.writeText(lastDnaStrand); setSynthesisStatus( lastReconciliation?.ok ? "pass" : "idle", "DNA strand copied to clipboard.", JSON.parse(lastBlueprint || "{}").id || "—", `${lastDnaStrand.length} bases`, lastReconciliation?.originalHash || "—", `${lastDnaStrand.slice(0, 84)}…` ); }); downloadBlueprintBtn.addEventListener("click", () => { if (!lastBlueprint) { setSynthesisStatus("idle", "No blueprint has been generated yet."); return; } const safeId = (JSON.parse(lastBlueprint).id || "blueprint").replace(/[^\w.-]+/g, "_"); downloadTextFile(`${safeId}.blueprint.json`, lastBlueprint); }); document.querySelector(".btn-deploy").addEventListener("click", async () => { const rawCode = document.getElementById("code-input").value; console.log("Initiating Synthesis..."); try { const blueprint = BlueprintCompiler.generate(rawCode, "build"); const blueprintObj = JSON.parse(blueprint); console.log("Blueprint Generated."); const dnaStrand = GeneticCodec.encodeToDNA(blueprint); console.log(`DNA Synthesized (${dnaStrand.length} bases).`); const reconciliation = await PhaseReconciler.verify(dnaStrand, blueprint); lastBlueprint = blueprint; lastDnaStrand = dnaStrand; lastReconciliation = reconciliation; if (reconciliation.ok) { console.log("Phase Reconciliation PASS."); setSynthesisStatus( "pass", "Blueprint generated, DNA encoded, and integrity verified.", blueprintObj.id, `${dnaStrand.length} bases`, `sha256:${reconciliation.originalHash}`, `${dnaStrand.slice(0, 84)}…` ); } else { console.error("Morphological drift detected or frame invalid!"); setSynthesisStatus("fail", reconciliation.error || "Morphological drift detected or frame invalid.", blueprintObj.id, `${dnaStrand.length} bases`, "—", `${dnaStrand.slice(0, 84)}…`); } // NEW LOGIC: Insert the deploy request into the backend simulator Backend.insert('deploy_requests', { id: `req_${Date.now()}`, timestamp: new Date().toISOString(), blueprintId: blueprintObj.id, status: 'queued', dnaLength: dnaStrand.length }); console.log(`Deployed blueprint ${blueprintObj.id} to Backend queue.`); } catch (error) { console.error(error); setSynthesisStatus("fail", error.message || "Synthesis failed."); } }); // ========================================== // DISTROFLUX SYSTEM CORE BRIDGE // ========================================== const DistrofluxSystemCoreBridge = (() => { const params = new URLSearchParams(location.search); const panel = (params.get('panel') || 'dashboard').toLowerCase(); const pointKey = params.get('point') || localStorage.getItem('distroflux.systemCore.activePoint') || 'FIB-0000'; const PROFILE_KEY = 'distroflux.systemCore.profile.v1'; const NOTES_KEY = 'distroflux.systemCore.notifications.v1'; const CONNECTIONS_KEY = 'distroflux.systemCore.connections.v1'; function readJson(key, fallback) { try { return JSON.parse(localStorage.getItem(key) || 'null') || fallback; } catch { return fallback; } } function writeJson(key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch {} } function safeId(value) { return String(value || 'local-demo').replace(/[^a-zA-Z0-9_.-]+/g, '_').slice(0, 96) || 'local-demo'; } function profileFromBridge() { const p = readJson(PROFILE_KEY, {}); const username = p.username || params.get('user') || 'local-demo'; return { id: p.id || username, username, displayName: p.displayName || username, email: p.email || 'local-demo', role: p.role || 'local viewer', pfp: p.pfp || 'DS', site: p.site || '', socials: p.socials || '', updatedAt: new Date().toISOString(), source: 'distroflux-system-core-bridge' }; } function primeWorkchatProfile() { const profile = profileFromBridge(); const selfId = `distroflux_${safeId(profile.id || profile.username)}`; try { localStorage.setItem('system_core_workchat_self_id', selfId); } catch {} const stateKey = 'system_core_workchat_native_v1'; const state = readJson(stateKey, null) || { selfId, activeRoomId: 'room_general', profiles: {}, rooms: {}, messages: {}, seenFiles: {} }; state.selfId = selfId; state.profiles = state.profiles || {}; state.rooms = state.rooms || {}; state.messages = state.messages || {}; state.seenFiles = state.seenFiles || {}; state.profiles[selfId] = { ...(state.profiles[selfId] || {}), id: selfId, username: profile.username, displayName: profile.displayName, pfp: profile.pfp, site: profile.site, socials: profile.socials, updatedAt: new Date().toISOString(), distrofluxPoint: pointKey }; if (!state.rooms.room_general) { state.rooms.room_general = { id:'room_general', type:'group', title:'General', memberIds:[selfId], createdAt:new Date().toISOString(), updatedAt:new Date().toISOString() }; } if (!state.rooms.room_general.memberIds.includes(selfId)) state.rooms.room_general.memberIds.push(selfId); if (!state.activeRoomId || !state.rooms[state.activeRoomId]) state.activeRoomId = 'room_general'; writeJson(stateKey, state); writeJson(PROFILE_KEY, profile); } function addBridgeToolbar() { const right = document.querySelector('.toolbar .toolbar-group:last-child'); if (!right || document.getElementById('distroflux-bridge-home')) return; const mk = (id, text, title, click) => { const btn = document.createElement('button'); btn.className = 'icon-btn'; btn.id = id; btn.type = 'button'; btn.title = title; btn.textContent = text; btn.addEventListener('click', click); return btn; }; right.prepend(mk('distroflux-bridge-home', 'Distroflux', 'Back to Distroflux', () => { location.href = 'index.php'; })); right.prepend(mk('distroflux-bridge-profile', 'Profile', 'Open local profile/workchat profile tools', () => openBridgePanel('profile'))); } function addNotification(title, body, type = 'workbench') { const notes = readJson(NOTES_KEY, []); notes.unshift({ id:`core-${Date.now().toString(36)}`, title, body, type, status:'unread', createdAt:new Date().toISOString(), pointKey }); writeJson(NOTES_KEY, notes.slice(0, 80)); } function openCard(card) { if (!card) return; restoreCard(card); card.style.display = 'flex'; ensureCardPlacement(card); bringCardToFront(card); } function openBridgePanel(which = panel) { const selected = (which || 'dashboard').toLowerCase(); if (selected === 'workchat' || selected === 'messages' || selected === 'connections' || selected === 'profile') { openCard(workchatWidget); ensureWorkchatLoaded(true); } if (selected === 'library') { openCard(galleryWidget); renderGallery(); } if (selected === 'codex') openCard(codexCard); if (selected === 'aether') openCard(aetherCard); if (selected === 'notifications') { const notes = readJson(NOTES_KEY, []); codeInput.value = JSON.stringify({ type: 'distroflux-system-core-notifications', pointKey, count: notes.length, notifications: notes }, null, 2); setMainSurfaceMode('code'); syncEditor(); } if (selected === 'profile' || selected === 'dashboard') { const profile = profileFromBridge(); const notes = readJson(NOTES_KEY, []); const connections = readJson(CONNECTIONS_KEY, []); codeInput.value = JSON.stringify({ type: 'distroflux-system-core-bridge-state', pointKey, profile, panels: ['workchat','library','ingest','codex','aether','notifications','connections'], notifications: notes.slice(0, 12), connections }, null, 2); setMainSurfaceMode('code'); syncEditor(); } addNotification('System Core panel opened', `Panel ${selected} opened for ${pointKey}.`, 'navigation'); } function boot() { try { localStorage.setItem('distroflux.systemCore.activePoint', pointKey); } catch {} primeWorkchatProfile(); addBridgeToolbar(); setTimeout(() => openBridgePanel(panel), 120); } return { boot, openBridgePanel }; })(); DistrofluxSystemCoreBridge.boot(); // ========================================== // WORKCHAT NATIVE LOCAL-FIRST BOOT // ========================================== WorkchatApp.boot(); // ========================================== // BOOT SEQUENCE // ========================================== Backend.init(); refreshManifest(); updateIngestModeUI(); codeInput.value = "// System Core Initialized.\n// Toggle 'Library' to browse and inject reusable modules.\n"; setMainSurfaceMode('code'); applyHybridLayout(); syncEditor(); renderGallery(); syncEditorLayout(); syncScroll(); syncCardToggleState(galleryWidget); syncCardToggleState(ingestWidget); syncCardToggleState(codexCard); syncCardToggleState(aetherCard); syncCardToggleState(document.getElementById('synthesis-widget')); syncCardToggleState(workchatWidget);