about summary refs log tree commit diff stats
path: root/html
diff options
context:
space:
mode:
Diffstat (limited to 'html')
-rw-r--r--html/merfolk/app.js26
-rw-r--r--html/merfolk/index.html2
-rw-r--r--html/playground/index.html435
3 files changed, 233 insertions, 230 deletions
diff --git a/html/merfolk/app.js b/html/merfolk/app.js
index cb6eccf..963f22d 100644
--- a/html/merfolk/app.js
+++ b/html/merfolk/app.js
@@ -1,11 +1,11 @@
 /**
- * Mermaid diagram editor and viewer application
- * Features:
- * - Real-time preview of Mermaid diagrams
- * - Pan and zoom functionality
- * - Export as PNG with configurable scale
- * - Export as SVG
- * - Reset view to center
+ * Merfolk is a mermaid diagram editor and viewer.
+ * 
+ * Dependencies:
+ * - mermaid.js
+ * - html2canvas
+ * - panzoom
+ * 
  */
 
 // Configuration
@@ -15,7 +15,7 @@ mermaid.initialize({
     securityLevel: 'loose'
 });
 
-// DOM Elements
+// Known DOM Elements
 const input = document.getElementById('mermaid-input');
 const preview = document.getElementById('mermaid-preview');
 const errorMessage = document.getElementById('error-message');
@@ -45,7 +45,7 @@ const debounce = (func, wait) => {
 };
 
 /**
- * Renders a Mermaid diagram from the provided text
+ * Renders a Mermaid diagram from the provided markup
  * Handles initialization of panzoom functionality
  * @param {string} text - The Mermaid diagram syntax
  * @returns {Promise<void>}
@@ -96,7 +96,7 @@ const handleReset = () => {
 
 /**
  * Exports the current diagram as a PNG image
- * Prompts user to select scale factor before export
+ * Prompts user to select a desired scale before exporting
  * @returns {Promise<void>}
  */
 const handleExport = async () => {
@@ -202,7 +202,7 @@ const handleExport = async () => {
             document.body.appendChild(overlay);
         });
         
-        // If user cancelled, return early
+        // Return early on cancel
         if (scale === null) return;
         
         const canvas = await html2canvas(preview, { 
@@ -233,7 +233,6 @@ const handleExportSvg = async () => {
         // Reset view before capturing
         handleReset();
         
-        // Small delay to ensure the reset is complete
         await new Promise(resolve => setTimeout(resolve, 100));
         
         const svg = preview.querySelector('svg');
@@ -255,7 +254,6 @@ const handleExportSvg = async () => {
         link.href = svgUrl;
         link.click();
         
-        // Clean up
         URL.revokeObjectURL(svgUrl);
     } catch (err) {
         errorMessage.textContent = 'SVG export failed.';
@@ -263,7 +261,7 @@ const handleExportSvg = async () => {
     }
 };
 
-// Event Handlers
+
 const debouncedRender = debounce(renderMermaid, 300);
 input.addEventListener('input', (e) => {
     debouncedRender(e.target.value);
diff --git a/html/merfolk/index.html b/html/merfolk/index.html
index f184e07..4d30da7 100644
--- a/html/merfolk/index.html
+++ b/html/merfolk/index.html
@@ -3,7 +3,7 @@
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>Mermaid Preview</title>
+    <title>Merfolk Mermaid Diagram Viewer</title>
     <script src="mermaid.min.js"></script>
     <link rel="stylesheet" href="styles.css">
 </head>
diff --git a/html/playground/index.html b/html/playground/index.html
index 680f022..a236d2f 100644
--- a/html/playground/index.html
+++ b/html/playground/index.html
@@ -6,238 +6,243 @@
     <title>JavaScript Playground</title>
     <meta name="description" content="A JavaScript jungle-gym for doing experiments and sharing scrappy fiddles.">
     <style>
-        body {
-            display: flex;
-            flex-direction: column;
-            align-items: center;
-            background-color: #ddd;
-            padding: 10px;
-            height: 100vh;
-            margin: 0;
-        }
-
-        textarea {
-            width: 100%;
-            height: 64%;
-            font-family: monospace;
-            background-color: #FFFEEC;
-            border: 2px solid #000;
-            scrollbar-width: none;            
-            font-size: 1rem;
-            margin-bottom: 10px;
-            padding: 10px;
-            box-sizing: border-box;
-            resize: none;
-            border-bottom: 12px solid teal;
-            -webkit-user-modify: read-write-plaintext-only;
-        }
-
-        textarea::-webkit-scrollbar {
-            display: none;
-        }
-
-        textarea::selection {
-            background-color: #EFECA7;
-        }
-
-        textarea:focus {
-            outline: none;
-        }
-
-        #console {
-            width: 100%;
-            height: 22%;
-            background-color: #000;
-            color: #0fc;
-            font-family: monospace;
-            font-size: 1rem;
-            overflow-y: auto;
-            padding: 10px;
-            box-sizing: border-box;
-            white-space: pre-wrap;
-        }
-
-        .button-container {
-            width: 100%;
-            display: flex;
-            justify-content: flex-end;
-            margin-bottom: 10px;
-        }
-
-        button {
-            padding: 10px 20px;
-            font-size: 1rem;
-            margin-left: 10px;
-            cursor: pointer;
-            border: none;
-            transition: background-color 0.3s ease;
-        }
-
-        button:hover, button:focus {
-            outline: none; 
-        }
-
-        button.run {
-            background-color: teal;
-            color: #FFFFFF;
-        }
+        html, body { height: 100%; margin: 0; padding: 0; }
+        body { display: flex; flex-direction: column; background-color: #ddd; }
+        #app { display: flex; flex-direction: column; padding: 10px; height: 100%; box-sizing: border-box; }
+        .button-container { width: 100%; display: flex; justify-content: flex-end; margin-bottom: 10px; flex-shrink: 0; }
+        button { padding: 10px 20px; font-size: 1rem; margin-left: 10px; cursor: pointer; border: none; transition: background-color 0.3s ease; }
+        button:hover, button:focus { outline: none; }
+        button:disabled { background-color: #999; cursor: not-allowed; }
+        button.run { background-color: teal; color: #FFFFFF; }
+        textarea { width: 100%; height: 64%; font-family: monospace; background-color: #FFFEEC; border: 2px solid #000; scrollbar-width: none; font-size: 1rem; margin-bottom: 10px; padding: 10px; box-sizing: border-box; resize: none; border-bottom: 12px solid teal; -webkit-user-modify: read-write-plaintext-only; flex-shrink: 0; }
+        textarea::-webkit-scrollbar { display: none; }
+        textarea::selection { background-color: #EFECA7; }
+        textarea:focus { outline: none; }
+        #console { width: 100%; height: 22%; background-color: #000; color: #0fc; font-family: monospace; font-size: 1rem; overflow-y: auto; padding: 10px; box-sizing: border-box; white-space: pre-wrap; flex-grow: 1; }
+        #console .log-item { margin-bottom: 5px; border-bottom: 1px solid #333; }
+        #console details { cursor: pointer; }
+        #console summary { outline: none; }
     </style>
 </head>
 <body>
+    <div id="app"></div>
 
-    <div class="playground" id="playground">    
-        <div class="seesaw" id="seesaw"></div>
-        <div class="slide" id="slide"></div>
-    </div>
-
-    <div class="button-container">
-        <button onclick="clearEverything()">Clear</button>
-        <button onclick="downloadCodeAndEditor()">Download</button>
-        <button onclick="shareCode()">Share</button>
-        <button onclick="evaluateCode()" class="run">Run Code</button>
-    </div>
-    <textarea id="codeInput" placeholder="Enter JavaScript..." spellcheck="false"></textarea>
-    <div id="console"></div>
+    <iframe id="sandbox" style="display: none;" title="JavaScript Sandbox"></iframe>
 
     <script>
-        function evaluateCode() {
-            const code = document.getElementById('codeInput').value;
-            const consoleDiv = document.getElementById('console');
-            consoleDiv.innerHTML = '';
-
-            // Custom console.log function to output to the console div
-            const originalConsoleLog = console.log;
-            console.log = function(...args) {
-                args.forEach(arg => {
-                    const output = document.createElement('div');
-                    output.textContent = typeof arg === 'object' ? JSON.stringify(arg, null, 2) : arg;
-                    consoleDiv.appendChild(output);
-                });
-                originalConsoleLog.apply(console, args);
-            };
-
-            try {
-                eval(code);
-            } catch (error) {
-                const errorOutput = document.createElement('div');
-                errorOutput.textContent = error;
-                errorOutput.style.color = 'red';
-                consoleDiv.appendChild(errorOutput);
+        /**
+         * ----------------------------------------------------------------
+         * Functional Utilities
+         * ----------------------------------------------------------------
+         */
+
+        const pipe = (...fns) => (initialValue) => fns.reduce((acc, fn) => fn(acc), initialValue);
+        const compose = (...fns) => (initialValue) => fns.reduceRight((acc, fn) => fn(acc), initialValue);
+
+        /**
+         * ----------------------------------------------------------------
+         * The Elm Architecture (Model, View, Update) Implementation
+         * ----------------------------------------------------------------
+         */
+
+        const init = {
+            code: `
+            const add = (a, b) => a + b;
+            const multiply = (a, b) => a * b;
+
+            const addAndMultiply = pipe(add, multiply);
+
+            console.log(addAndMultiply(2, 3));
+`,
+            consoleOutput: [],
+            sandboxReady: false,
+        };
+
+        const view = (model) => `
+            <div class="button-container">
+                <button onclick="dispatch({ type: 'CLEAR' })">Clear</button>
+                <button onclick="dispatch({ type: 'DOWNLOAD' })">Download</button>
+                <button onclick="dispatch({ type: 'SHARE' })">Share</button>
+                <button onclick="dispatch({ type: 'RUN_CODE' })" class="run" ${!model.sandboxReady ? 'disabled title="Sandbox is loading..."' : ''}>Run Code</button>
+            </div>
+            <textarea id="codeInput" oninput="dispatch({ type: 'CODE_CHANGED', payload: this.value })" onkeydown="handleKeyDown(event)">${model.code}</textarea>
+            <div id="console">
+                ${model.consoleOutput.map(log => {
+                    if (typeof log === 'object' && log !== null) {
+                        return `<div class="log-item"><details><summary>${Object.prototype.toString.call(log)}</summary><pre>${JSON.stringify(log, null, 2)}</pre></details></div>`;
+                    }
+                    return `<div class="log-item">${log}</div>`;
+                }).join('')}
+            </div>
+        `;
+
+        const update = (msg, model) => {
+            switch (msg.type) {
+                case 'CODE_CHANGED':
+                    return { ...model, code: msg.payload };
+                
+                case 'RUN_CODE':
+                    return model;
+
+                case 'CONSOLE_LOG':
+                    return { ...model, consoleOutput: [...model.consoleOutput, ...msg.payload] };
+
+                case 'CLEAR':
+                    if (confirm('Are you sure you want to reset the playground?')) {
+                        window.location.hash = '';
+                        window.location.reload();
+                    }
+                    return model;
+
+                case 'CLEAR_CONSOLE':
+                     return { ...model, consoleOutput: [] };
+                
+                case 'SHARE':
+                case 'DOWNLOAD':
+                    return model;
+
+                case 'SANDBOX_READY':
+                    return { ...model, sandboxReady: true };
+
+                default:
+                    return model;
             }
-
-            // Restore browser's console.log
-            console.log = originalConsoleLog;
-        }
-
-        function downloadCodeAndEditor() {
-            const codeInput = document.getElementById('codeInput').value;
-            const htmlContent = document.documentElement.outerHTML.replace(
-                /<textarea id="codeInput"[^>]*>.*<\/textarea>/,
-                `<textarea id="codeInput">${codeInput}</textarea>`
-            );
-
-            const blob = new Blob([htmlContent], { type: 'text/html' });
-            const url = URL.createObjectURL(blob);
-            const a = document.createElement('a');
-            a.href = url;
-            a.download = 'code_editor.html';
-            document.body.appendChild(a);
-            a.click();
-            document.body.removeChild(a);
-            URL.revokeObjectURL(url);
-        }
-
-        function shareCode() {
-            const code = document.getElementById('codeInput').value;
-            const encodedCode = btoa(encodeURIComponent(code));
-            window.location.hash = encodedCode;
-            window.prompt("Copy the URL to share.\nBe warned! Very long URLs don't share wicked well, sometimes.", window.location.href);
-        }
-
-        function clearEverything() {
-            if (!confirm('Are you sure you want to reset the playground?')) {
-                return;
-            } else {               
-                window.location.hash = '';
-                window.location.reload();
+        };
+
+        /**
+         * ----------------------------------------------------------------
+         * Application Core & Side-Effect Handling
+         * ----------------------------------------------------------------
+         */
+
+        let model = null;
+        const appContainer = document.getElementById('app');
+        const sandbox = document.getElementById('sandbox');
+
+        const dispatch = (msg) => {
+            const newModel = update(msg, model);
+            handleSideEffects(msg, newModel);
+            model = newModel;
+            render(model);
+        };
+
+        const handleSideEffects = (msg, model) => {
+             if (msg.type === 'RUN_CODE') {
+                if (!model.sandboxReady) return;
+                dispatch({ type: 'CLEAR_CONSOLE' });
+                sandbox.contentWindow.postMessage({ code: model.code }, '*');
+            } else if (msg.type === 'SHARE') {
+                const encodedCode = btoa(encodeURIComponent(model.code));
+                window.location.hash = encodedCode;
+                window.prompt("Copy the URL to share.", window.location.href);
+            } else if (msg.type === 'DOWNLOAD') {
+                const htmlContent = document.documentElement.outerHTML.replace(
+                    /<textarea id="codeInput"[^>]*>.*<\/textarea>/,
+                    `<textarea id="codeInput">${model.code}</textarea>`
+                );
+                const blob = new Blob([htmlContent], { type: 'text/html' });
+                const url = URL.createObjectURL(blob);
+                const a = document.createElement('a');
+                a.href = url;
+                a.download = 'playground.html';
+                a.click();
+                URL.revokeObjectURL(url);
             }
-        }
-
-        function loadCodeFromHash() {
-            const hash = window.location.hash.substring(1);
-            if (hash) {
-                try {
-                    const decodedCode = decodeURIComponent(atob(hash));
-                    document.getElementById('codeInput').value = decodedCode;
-                } catch (error) {
-                    console.error('Failed to decode the URL hash:', error);
+        };
+
+        const render = (model) => {
+            const focusedElementId = document.activeElement?.id;
+            const selectionStart = document.activeElement?.selectionStart;
+            const selectionEnd = document.activeElement?.selectionEnd;
+
+            appContainer.innerHTML = view(model);
+
+            if (focusedElementId === 'codeInput') {
+                const focusedElement = document.getElementById(focusedElementId);
+                if (focusedElement) {
+                    focusedElement.focus();
+                    if (typeof selectionStart === 'number') {
+                       focusedElement.selectionStart = selectionStart;
+                       focusedElement.selectionEnd = selectionEnd;
+                    }
                 }
             }
-        }
+        };
 
-        function help() {
-            const helpText = `
-            Welcome to the JavaScript Playground! Here are some tips to get you started:
-
-            1. Enter your JavaScript code in the textarea.
-            2. Click the "Run Code" button to execute your code.
-            3. The console output will be displayed below the textarea.
-            4. Click the "Clear" button to reset the playground.
-            5. Click the "Download" button to save your code and editor as an HTML file.
-            6. Click the "Share" button to generate a URL to share your code with others.
-            7. You can also press "Cmd + Enter" to run your code.
-            8. There's an empty div above the buttons with the id "playground"
-            9. You can mount stuff to it using the "mount" function, for more info run "mountHelp()"
-            10. You can use the "clear()" function to clear the content's of the console.
-
-            Go nuts! Share scrappy fiddles!
-            `;
-            console.log(helpText);
-        }
-
-        function clear() {
-            document.getElementById('console').innerHTML = '';
-        }
-
-        function mountHelp() {
-            console.log(`
-            The mount function is used to mount stuff to the playground div.
-            It takes a function as an argument, which in turn receives the playground div as an argument.
-            Before mounting, it clears the playground div.
-            Here's an example of how to use the mount function:
-
-            mount(playground => {
-                const h1 = document.createElement('h1');
-                h1.textContent = 'Hell is empty and all the devils are here.';
-                playground.appendChild(h1);
-            });
-
-            This will add an h1 element to the playground div.
-            `);
-        }
-
-        function mount(mountFunction) {
-            const playground = document.getElementById('playground');
-            if (!playground) {
-                console.error("Couldn't find a div with the id 'playground'! You may need to reload the page.");
-                return;
+        const handleKeyDown = (event) => {
+            if (event.key === 'Tab') {
+                event.preventDefault();
+                const start = event.target.selectionStart;
+                const end = event.target.selectionEnd;
+                event.target.value = event.target.value.substring(0, start) + "  " + event.target.value.substring(end);
+                dispatch({ type: 'CODE_CHANGED', payload: event.target.value });
+                event.target.selectionStart = event.target.selectionEnd = start + 2;
             }
+            if (event.metaKey && event.key === 'Enter') {
+                event.preventDefault();
+                dispatch({ type: 'RUN_CODE' });
+            }
+        };
+        
+        /**
+         * ----------------------------------------------------------------
+         * Sandbox Initialization
+         * ----------------------------------------------------------------
+         */
+         
+        const sandboxSrc = `
+            <script>
+                const pipe = ${pipe.toString()};
+                const compose = ${compose.toString()};
+            
+                const originalConsoleLog = console.log;
+                console.log = (...args) => {
+                    parent.postMessage({ type: 'CONSOLE_LOG', payload: args }, '*');
+                };
+
+                window.addEventListener('message', (event) => {
+                    try {
+                        eval(event.data.code);
+                    } catch (e) {
+                        console.log(e.toString());
+                    }
+                });
+            <\/script>
+        `;
 
-            if (playground.innerHTML.trim() !== "") {
-                playground.innerHTML = "";
+        window.addEventListener('message', (event) => {
+            if (event.source === sandbox.contentWindow && event.data.type === 'CONSOLE_LOG') {
+                dispatch(event.data);
             }
-            mountFunction(playground);
+        });
+        
+        /**
+         * ----------------------------------------------------------------
+         * Application Entry Point
+         * ----------------------------------------------------------------
+         */
+        
+        const hash = window.location.hash.substring(1);
+        if (hash) {
+            try {
+                const decodedCode = decodeURIComponent(atob(hash));
+                model = { ...init, code: decodedCode };
+            } catch (error) {
+                console.error('Failed to decode the URL hash:', error);
+                model = init;
+            }
+        } else {
+            model = init;
         }
 
+        render(model);
 
-        document.getElementById('codeInput').addEventListener('keydown', function(event) {
-            if (event.metaKey && event.key === 'Enter') {
-                event.preventDefault();
-                evaluateCode();
-            }
-        });
+        sandbox.onload = () => {
+            dispatch({ type: 'SANDBOX_READY' });
+        };
+
+        sandbox.srcdoc = sandboxSrc;
 
-        window.onload = loadCodeFromHash;
     </script>
 </body>
-</html>
+</html>
\ No newline at end of file