diff --git a/packages/markdown/README.md b/packages/markdown/README.md index 147aa303..d2e1fabb 100644 --- a/packages/markdown/README.md +++ b/packages/markdown/README.md @@ -15,7 +15,7 @@ Markdown processing engine for Hyperbook. This package provides extensive markdo - Image processing with attributes **Supported Directives:** -`:alert`, `:video`, `:youtube`, `:audio`, `:archive`, `:download`, `:embed`, `:excalidraw`, `:mermaid`, `:plantuml`, `:collapsible`, `:tabs`, `:tiles`, `:slideshow`, `:term`, `:pagelist`, `:bookmarks`, `:qr`, `:protect`, `:textinput`, `:pyide`, `:sqlide`, `:webide`, `:onlineide`, `:scratchblock`, `:h5p`, `:geogebra`, `:jsxgraph`, `:abcmusic`, `:learningmap`, `:struktog`, `:typst`, and more. +`:alert`, `:video`, `:youtube`, `:audio`, `:archive`, `:download`, `:embed`, `:excalidraw`, `:mermaid`, `:plantuml`, `:collapsible`, `:tabs`, `:tiles`, `:slideshow`, `:term`, `:pagelist`, `:bookmarks`, `:qr`, `:protect`, `:textinput`, `:pyide`, `:sqlide`, `:webide`, `:onlineide`, `:scratchblock`, `:h5p`, `:geogebra`, `:jsxgraph`, `:abcmusic`, `:learningmap`, `:struktog`, `:typst`, `:openscad`, and more. ## Installation diff --git a/packages/markdown/assets/directive-openscad/client.js b/packages/markdown/assets/directive-openscad/client.js new file mode 100644 index 00000000..ffb6a104 --- /dev/null +++ b/packages/markdown/assets/directive-openscad/client.js @@ -0,0 +1,486 @@ +/// + +/** + * OpenSCAD IDE directive. + * @type {any} + * @memberof hyperbook + */ +hyperbook.openscad = (function () { + window.codeInput?.registerTemplate( + "openscad-highlighted", + codeInput.templates.prism(window.Prism, [ + new codeInput.plugins.AutoCloseBrackets(), + new codeInput.plugins.Indent(true, 2), + ]), + ); + + let openscadPromise = null; + let threePromise = null; + + const i18nGet = (key, fallback = key) => hyperbook.i18n?.get(key) || fallback; + + const getOpenScad = async () => { + if (!openscadPromise) { + openscadPromise = import("https://cdn.jsdelivr.net/npm/openscad-wasm@0.0.4/+esm") + .then((m) => m.createOpenSCAD()) + .then((instance) => { + const fs = instance.getInstance().FS; + try { + fs.mkdir("/tmp"); + } catch (_) {} + return instance; + }); + } + return openscadPromise; + }; + + const getThree = async () => { + if (!threePromise) { + threePromise = Promise.all([ + import("https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js/+esm"), + import("https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/loaders/STLLoader.js/+esm"), + import("https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/controls/OrbitControls.js/+esm"), + ]).then(([THREE, STLLoaderModule, OrbitControlsModule]) => ({ + THREE, + STLLoader: STLLoaderModule.STLLoader, + OrbitControls: OrbitControlsModule.OrbitControls, + })); + } + return threePromise; + }; + + const formatValue = (value) => { + if (typeof value === "string") return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; + if (Array.isArray(value)) return `[${value.map(formatValue).join(",")}]`; + if (typeof value === "boolean" || typeof value === "number") return `${value}`; + throw new Error("Only numbers, booleans, strings and arrays are supported in parameters"); + }; + + function setupSplitter(elem, previewContainer, editorContainer, splitter) { + if (!previewContainer || !editorContainer || !splitter) return; + + const minPanelSize = 120; + + const getIsHorizontal = () => + getComputedStyle(elem).flexDirection.startsWith("row"); + + const applySplitSize = (rawSize, isHorizontal) => { + const total = isHorizontal ? elem.clientWidth : elem.clientHeight; + const splitterSize = isHorizontal ? splitter.offsetWidth : splitter.offsetHeight; + const maxSize = Math.max(minPanelSize, total - splitterSize - minPanelSize); + const clamped = Math.max(minPanelSize, Math.min(rawSize, maxSize)); + previewContainer.style.flex = `0 0 ${clamped}px`; + return clamped; + }; + + const applyStoredSplitSize = () => { + const isHorizontal = getIsHorizontal(); + elem.classList.toggle("split-horizontal", isHorizontal); + elem.classList.toggle("split-vertical", !isHorizontal); + const key = isHorizontal ? "splitHorizontal" : "splitVertical"; + const rawStored = Number(elem.dataset[key]); + if (!Number.isFinite(rawStored) || rawStored <= 0) { + previewContainer.style.flex = ""; + return; + } + applySplitSize(rawStored, isHorizontal); + }; + + applyStoredSplitSize(); + + splitter.addEventListener("pointerdown", (event) => { + event.preventDefault(); + splitter.setPointerCapture(event.pointerId); + + const isHorizontal = getIsHorizontal(); + const key = isHorizontal ? "splitHorizontal" : "splitVertical"; + const startPointer = isHorizontal ? event.clientX : event.clientY; + const startSize = isHorizontal + ? previewContainer.getBoundingClientRect().width + : previewContainer.getBoundingClientRect().height; + + elem.classList.add("resizing"); + + const onPointerMove = (moveEvent) => { + const pointer = isHorizontal ? moveEvent.clientX : moveEvent.clientY; + const delta = pointer - startPointer; + const size = applySplitSize(startSize + delta, isHorizontal); + elem.dataset[key] = String(Math.round(size)); + }; + + const onPointerUp = () => { + elem.classList.remove("resizing"); + splitter.removeEventListener("pointermove", onPointerMove); + splitter.removeEventListener("pointerup", onPointerUp); + splitter.removeEventListener("pointercancel", onPointerUp); + }; + + splitter.addEventListener("pointermove", onPointerMove); + splitter.addEventListener("pointerup", onPointerUp); + splitter.addEventListener("pointercancel", onPointerUp); + }); + + window.addEventListener("resize", applyStoredSplitSize); + } + + const updateFullscreenButtonState = (elem, button) => { + if (!elem || !button) return; + const isFullscreen = document.fullscreenElement === elem; + const label = i18nGet("ide-fullscreen-enter", "Fullscreen"); + button.textContent = "⛶"; + button.title = label; + button.setAttribute("aria-label", label); + button.classList.toggle("active", isFullscreen); + }; + + const toggleFullscreen = async (elem) => { + if (!elem) return; + if (document.fullscreenElement === elem) { + await document.exitFullscreen(); + return; + } + await elem.requestFullscreen(); + }; + + const syncFullscreenButtons = () => { + const elems = document.querySelectorAll(".directive-openscad"); + elems.forEach((elem) => { + const fullscreen = elem.querySelector("button.fullscreen"); + updateFullscreenButtonState(elem, fullscreen); + }); + }; + + const toUint8Array = (data) => { + if (data instanceof Uint8Array) return data; + if (typeof data === "string") return new TextEncoder().encode(data); + return new Uint8Array(data || []); + }; + + function initElement(elem) { + if (elem.getAttribute("data-openscad-initialized") === "true") return; + elem.setAttribute("data-openscad-initialized", "true"); + + const id = elem.getAttribute("data-id"); + + const previewContainer = elem.querySelector(".preview-container"); + const editorContainer = elem.querySelector(".editor-container"); + const splitter = elem.querySelector(".splitter"); + const canvas = elem.querySelector(".preview-canvas"); + const output = elem.querySelector(".output"); + const editor = elem.querySelector("code-input.editor"); + const params = elem.querySelector("textarea.parameters"); + + const tabCode = elem.querySelector("button.tab-code"); + const tabParameters = elem.querySelector("button.tab-parameters"); + + const renderBtn = elem.querySelector("button.render"); + const copyBtn = elem.querySelector("button.copy"); + const downloadStlBtn = elem.querySelector("button.download-stl"); + const download3mfBtn = elem.querySelector("button.download-3mf"); + const resetBtn = elem.querySelector("button.reset"); + const fullscreenBtn = elem.querySelector("button.fullscreen"); + + setupSplitter(elem, previewContainer, editorContainer, splitter); + + const viewerState = { + renderer: null, + camera: null, + scene: null, + controls: null, + mesh: null, + raf: 0, + disposed: false, + }; + + const setOutput = (text) => { + if (output) output.textContent = text || ""; + }; + + const save = async () => { + if (!id) return; + await hyperbook.store.db.openscad.put({ + id, + code: editor?.value || "", + params: params?.value || "{}", + }); + }; + + const load = async () => { + if (!id) return; + const result = await hyperbook.store.db.openscad.get(id); + if (!result) return; + if (editor && typeof result.code === "string") { + editor.value = result.code; + } + if (params && typeof result.params === "string") { + params.value = result.params; + } + }; + + const getParamDefinitions = () => { + const parsed = JSON.parse(params?.value || "{}"); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error(i18nGet("openscad-params-object", "Parameters must be a JSON object")); + } + return Object.entries(parsed).map(([k, v]) => `-D${k}=${formatValue(v)}`); + }; + + const renderWithFormat = async (format) => { + renderBtn?.setAttribute("disabled", "true"); + setOutput(i18nGet("openscad-rendering", "Rendering ...")); + + try { + const paramDefinitions = getParamDefinitions(); + const openscad = await getOpenScad(); + const instance = openscad.getInstance(); + + const sourcePath = "/tmp/model.scad"; + const outPath = `/tmp/output.${format}`; + const exportFormat = format === "stl" ? "binstl" : format; + + try { + instance.FS.unlink(sourcePath); + } catch (_) {} + try { + instance.FS.unlink(outPath); + } catch (_) {} + + instance.FS.writeFile(sourcePath, editor?.value || ""); + + const args = [ + sourcePath, + "-o", + outPath, + "--backend=manifold", + `--export-format=${exportFormat}`, + ...paramDefinitions, + ]; + + const exitCode = instance.callMain(args); + if (exitCode !== 0) { + throw new Error(i18nGet("openscad-render-failed", "OpenSCAD render failed")); + } + + const content = toUint8Array(instance.FS.readFile(outPath, { encoding: "binary" })); + return content; + } finally { + renderBtn?.removeAttribute("disabled"); + } + }; + + const downloadBinary = (content, ext) => { + const blob = new Blob([content], { type: "application/octet-stream" }); + const a = document.createElement("a"); + a.href = URL.createObjectURL(blob); + a.download = `openscad-${id || "model"}.${ext}`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 1000); + }; + + const renderPreview = async () => { + try { + await save(); + const stl = await renderWithFormat("stl"); + await renderStl(stl); + setOutput(i18nGet("openscad-render-success", "Render complete")); + } catch (error) { + setOutput(error?.message || `${error}`); + } + }; + + const renderStl = async (stlData) => { + const { THREE, STLLoader, OrbitControls } = await getThree(); + if (!canvas) return; + + if (!viewerState.renderer) { + viewerState.renderer = new THREE.WebGLRenderer({ + canvas, + antialias: true, + alpha: true, + }); + viewerState.renderer.setPixelRatio(window.devicePixelRatio || 1); + + viewerState.scene = new THREE.Scene(); + viewerState.scene.background = new THREE.Color(0xf8fafc); + + const ambient = new THREE.AmbientLight(0xffffff, 0.75); + const key = new THREE.DirectionalLight(0xffffff, 1); + key.position.set(1, 1, 2); + const fill = new THREE.DirectionalLight(0xffffff, 0.5); + fill.position.set(-1, -1, 1); + + viewerState.scene.add(ambient); + viewerState.scene.add(key); + viewerState.scene.add(fill); + + viewerState.camera = new THREE.PerspectiveCamera(45, 1, 0.1, 5000); + viewerState.controls = new OrbitControls(viewerState.camera, canvas); + viewerState.controls.enableDamping = true; + + const tick = () => { + if (viewerState.disposed) return; + if (viewerState.controls) viewerState.controls.update(); + if (viewerState.renderer && viewerState.scene && viewerState.camera) { + viewerState.renderer.render(viewerState.scene, viewerState.camera); + } + viewerState.raf = requestAnimationFrame(tick); + }; + tick(); + } + + const bounds = previewContainer?.getBoundingClientRect(); + const width = Math.max(1, Math.floor(bounds?.width || canvas.clientWidth || 320)); + const height = Math.max(1, Math.floor(bounds?.height || canvas.clientHeight || 320)); + viewerState.renderer.setSize(width, height, false); + viewerState.camera.aspect = width / height; + viewerState.camera.updateProjectionMatrix(); + + if (viewerState.mesh) { + viewerState.scene.remove(viewerState.mesh); + viewerState.mesh.geometry?.dispose(); + } + + const loader = new STLLoader(); + const arrayBuffer = stlData.buffer.slice( + stlData.byteOffset, + stlData.byteOffset + stlData.byteLength, + ); + const geometry = loader.parse(arrayBuffer); + geometry.computeBoundingBox(); + geometry.computeVertexNormals(); + + const material = new THREE.MeshStandardMaterial({ + color: 0x3b82f6, + metalness: 0.1, + roughness: 0.6, + }); + const mesh = new THREE.Mesh(geometry, material); + viewerState.mesh = mesh; + viewerState.scene.add(mesh); + + const box = geometry.boundingBox; + const size = new THREE.Vector3(); + const center = new THREE.Vector3(); + box.getSize(size); + box.getCenter(center); + + mesh.position.x = -center.x; + mesh.position.y = -center.y; + mesh.position.z = -center.z; + + const maxDim = Math.max(size.x, size.y, size.z) || 1; + const distance = maxDim * 1.8; + viewerState.camera.position.set(distance, distance, distance); + viewerState.camera.near = Math.max(0.01, distance / 1000); + viewerState.camera.far = Math.max(1000, distance * 10); + viewerState.camera.lookAt(0, 0, 0); + viewerState.camera.updateProjectionMatrix(); + + viewerState.controls.target.set(0, 0, 0); + viewerState.controls.update(); + }; + + tabCode?.addEventListener("click", () => { + tabCode.classList.add("active"); + tabParameters?.classList.remove("active"); + editor?.classList.add("active"); + params?.classList.remove("active"); + }); + + tabParameters?.addEventListener("click", () => { + tabParameters.classList.add("active"); + tabCode?.classList.remove("active"); + params?.classList.add("active"); + editor?.classList.remove("active"); + }); + + copyBtn?.addEventListener("click", async () => { + await navigator.clipboard.writeText(editor?.value || ""); + setOutput(i18nGet("openscad-copy-done", "Code copied")); + }); + + resetBtn?.addEventListener("click", async () => { + if (!window.confirm(i18nGet("openscad-reset-prompt", "Are you sure you want to reset the code?"))) { + return; + } + await hyperbook.store.db.openscad.delete(id); + window.location.reload(); + }); + + renderBtn?.addEventListener("click", renderPreview); + + downloadStlBtn?.addEventListener("click", async () => { + try { + await save(); + const stl = await renderWithFormat("stl"); + downloadBinary(stl, "stl"); + await renderStl(stl); + setOutput(i18nGet("openscad-download-ready", "Download ready")); + } catch (error) { + setOutput(error?.message || `${error}`); + } + }); + + download3mfBtn?.addEventListener("click", async () => { + try { + await save(); + const threeMf = await renderWithFormat("3mf"); + downloadBinary(threeMf, "3mf"); + setOutput(i18nGet("openscad-download-ready", "Download ready")); + } catch (error) { + setOutput(error?.message || `${error}`); + } + }); + + fullscreenBtn?.addEventListener("click", async () => { + try { + await toggleFullscreen(elem); + } catch (error) { + console.error(error?.message || error); + } + }); + + updateFullscreenButtonState(elem, fullscreenBtn); + + editor?.addEventListener("code-input_load", async () => { + await load(); + editor.addEventListener("input", save); + params?.addEventListener("input", save); + if (!editor.value.trim()) { + editor.value = "// OpenSCAD\ncube([20,20,20], center=true);"; + } + if (!params?.value.trim()) { + params.value = "{}"; + } + await save(); + renderPreview(); + }); + } + + function init(root) { + const elems = root.querySelectorAll(".directive-openscad"); + elems.forEach(initElement); + } + + document.addEventListener("DOMContentLoaded", () => { + init(document); + }); + document.addEventListener("fullscreenchange", syncFullscreenButtons); + + const observer = new MutationObserver((mutations) => { + mutations.forEach((mutation) => { + mutation.addedNodes.forEach((node) => { + if ( + node.nodeType === 1 && + node.classList.contains("directive-openscad") + ) { + initElement(node); + } + }); + }); + }); + + observer.observe(document.body, { childList: true, subtree: true }); + + return { init }; +})(); diff --git a/packages/markdown/assets/directive-openscad/style.css b/packages/markdown/assets/directive-openscad/style.css new file mode 100644 index 00000000..3d4b00d7 --- /dev/null +++ b/packages/markdown/assets/directive-openscad/style.css @@ -0,0 +1,173 @@ +.directive-openscad { + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; + overflow: hidden; + gap: 8px; + height: var(--openscad-height, calc(100dvh - 80px)); +} + +.directive-openscad .preview-container { + width: 100%; + min-height: 120px; + min-width: 120px; + border: 1px solid var(--color-spacer); + border-radius: 8px; + overflow: hidden; + background-color: var(--color--background); + flex: 1 1 0; + display: flex; + flex-direction: column; +} + +.directive-openscad .preview-header { + border-bottom: 1px solid var(--color-spacer); + padding: 8px 16px; + font-weight: 600; +} + +.directive-openscad .preview-canvas { + width: 100%; + height: 100%; + min-height: 260px; + display: block; + background: linear-gradient(180deg, #f8fafc 0%, #e2e8f0 100%); +} + +.directive-openscad .output { + margin: 0; + border-top: 1px solid var(--color-spacer); + padding: 8px 12px; + min-height: 56px; + max-height: 120px; + overflow: auto; + white-space: pre-wrap; + font-family: hyperbook-monospace, monospace; +} + +.directive-openscad .editor-container { + width: 100%; + display: flex; + flex-direction: column; + min-height: 120px; + min-width: 120px; + flex: 1 1 0; +} + +.directive-openscad .splitter { + background: var(--color-spacer); + border-radius: 999px; + flex-shrink: 0; + touch-action: none; + opacity: 0.45; + transition: opacity 0.15s ease-in-out; +} + +.directive-openscad .splitter:hover { + opacity: 0.65; +} + +.directive-openscad.split-vertical .splitter { + width: 100%; + height: 4px; + cursor: row-resize; +} + +.directive-openscad.split-horizontal .splitter { + width: 4px; + height: 100%; + cursor: col-resize; +} + +.directive-openscad.resizing { + user-select: none; +} + +.directive-openscad .buttons { + display: flex; + border: 1px solid var(--color-spacer); + border-radius: 8px; + border-bottom: none; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; + overflow: hidden; +} + +.directive-openscad .buttons.bottom { + border: 1px solid var(--color-spacer); + border-radius: 8px; + border-top: none; + border-top-left-radius: 0; + border-top-right-radius: 0; +} + +.directive-openscad button { + flex: 1; + padding: 8px 16px; + border: none; + border-right: 1px solid var(--color-spacer); + background-color: var(--color--background); + color: var(--color-text); + cursor: pointer; +} + +.directive-openscad .buttons button:last-child { + border-right: none; +} + +.directive-openscad button.fullscreen { + flex: 0 0 auto; + min-width: 42px; + width: 42px; + padding: 8px 0; +} + +.directive-openscad button:hover, +.directive-openscad button.active { + background-color: var(--color-spacer); +} + +.directive-openscad .editor, +.directive-openscad .parameters { + width: 100%; + border: 1px solid var(--color-spacer); + flex: 1; +} + +.directive-openscad .parameters { + display: none; + box-sizing: border-box; + resize: none; + padding: 12px; + font-family: hyperbook-monospace, monospace; +} + +.directive-openscad .editor:not(.active), +.directive-openscad .parameters:not(.active) { + display: none; +} + +.directive-openscad:fullscreen { + width: 100vw; + height: 100dvh !important; + padding: 12px; + box-sizing: border-box; + background-color: var(--color-background, var(--color--background, #fff)); +} + +.directive-openscad:fullscreen::backdrop { + background-color: var(--color-background, var(--color--background, #fff)); +} + +@media screen and (min-width: 1024px) { + .directive-openscad { + flex-direction: row; + } + + .directive-openscad .preview-container, + .directive-openscad .editor-container { + flex: 1; + height: 100% !important; + } +} diff --git a/packages/markdown/assets/store.js b/packages/markdown/assets/store.js index b4807e34..5a761898 100644 --- a/packages/markdown/assets/store.js +++ b/packages/markdown/assets/store.js @@ -12,7 +12,7 @@ var hyperbook = window.hyperbook = window.hyperbook || {}; hyperbook.store = (function () { /** @type {import("dexie").Dexie} */ var db = new Dexie("Hyperbook"); - db.version(4).stores({ + db.version(5).stores({ consent: `id`, currentState: ` id, @@ -46,6 +46,7 @@ hyperbook.store = (function () { struktolab: `id,tree`, multievent: `id,state`, typst: `id,code`, + openscad: `id,code,params`, }); /** @returns {Promise} */ diff --git a/packages/markdown/locales/de.json b/packages/markdown/locales/de.json index b5d80dcb..14346c7d 100644 --- a/packages/markdown/locales/de.json +++ b/packages/markdown/locales/de.json @@ -88,6 +88,21 @@ "typst-file-replace": "Existierende Datei ersetzen?", "typst-binary-files": "Binärdateien", "typst-no-binary-files": "Keine Binärdateien", + "openscad-preview": "Vorschau", + "openscad-code": "Code", + "openscad-parameters": "Parameter", + "openscad-render": "Rendern", + "openscad-copy": "Kopieren", + "openscad-copy-done": "Code kopiert", + "openscad-download-stl": "STL herunterladen", + "openscad-download-3mf": "3MF herunterladen", + "openscad-download-ready": "Download bereit", + "openscad-reset": "Zurücksetzen", + "openscad-reset-prompt": "Sind Sie sicher, dass Sie den Code zurücksetzen möchten?", + "openscad-rendering": "Rendern ...", + "openscad-render-success": "Rendern abgeschlossen", + "openscad-render-failed": "OpenSCAD-Rendern fehlgeschlagen", + "openscad-params-object": "Parameter müssen ein JSON-Objekt sein", "user-login-title": "Anmelden", "user-username": "Benutzername", "user-password": "Passwort", diff --git a/packages/markdown/locales/en.json b/packages/markdown/locales/en.json index 1088e91d..39f688ee 100644 --- a/packages/markdown/locales/en.json +++ b/packages/markdown/locales/en.json @@ -88,6 +88,21 @@ "typst-file-replace": "Replace existing file?", "typst-binary-files": "Binary Files", "typst-no-binary-files": "No binary files", + "openscad-preview": "Preview", + "openscad-code": "Code", + "openscad-parameters": "Parameters", + "openscad-render": "Render", + "openscad-copy": "Copy", + "openscad-copy-done": "Code copied", + "openscad-download-stl": "Download STL", + "openscad-download-3mf": "Download 3MF", + "openscad-download-ready": "Download ready", + "openscad-reset": "Reset", + "openscad-reset-prompt": "Are you sure you want to reset the code?", + "openscad-rendering": "Rendering ...", + "openscad-render-success": "Render complete", + "openscad-render-failed": "OpenSCAD render failed", + "openscad-params-object": "Parameters must be a JSON object", "user-login-title": "Login", "user-username": "Username", "user-password": "Password", diff --git a/packages/markdown/src/process.ts b/packages/markdown/src/process.ts index 9e51f9eb..68086a01 100644 --- a/packages/markdown/src/process.ts +++ b/packages/markdown/src/process.ts @@ -65,6 +65,7 @@ import remarkImageAttrs from "./remarkImageAttrs"; import remarkDirectiveLearningmap from "./remarkDirectiveLearningmap"; import remarkDirectiveTextinput from "./remarkDirectiveTextinput"; import remarkDirectiveTypst from "./remarkDirectiveTypst"; +import remarkDirectiveOpenscad from "./remarkDirectiveOpenscad"; import remarkDirectiveStruktolab from "./remarkDirectiveStruktolab"; import remarkDirectiveBlockflowPlayer from "./remarkDirectiveBlockflowPlayer"; import remarkDirectiveBlockflowEditor from "./remarkDirectiveBlockflowEditor"; @@ -115,6 +116,7 @@ export const remark = (ctx: HyperbookContext) => { remarkDirectiveLearningmap(ctx), remarkDirectiveTextinput(ctx), remarkDirectiveTypst(ctx), + remarkDirectiveOpenscad(ctx), remarkCode(ctx), remarkMath, remarkGithubEmoji, diff --git a/packages/markdown/src/remarkDirectiveOpenscad.ts b/packages/markdown/src/remarkDirectiveOpenscad.ts new file mode 100644 index 00000000..19fdaba7 --- /dev/null +++ b/packages/markdown/src/remarkDirectiveOpenscad.ts @@ -0,0 +1,279 @@ +// Register directive nodes in mdast: +/// +// +import { HyperbookContext } from "@hyperbook/types"; +import { Code, Root } from "mdast"; +import { visit } from "unist-util-visit"; +import { VFile } from "vfile"; +import { + expectContainerDirective, + isDirective, + registerDirective, + requestCSS, + requestJS, +} from "./remarkHelper"; +import hash from "./objectHash"; +import { i18n } from "./i18n"; +import { readFile } from "./helper"; + +function htmlEntities(str: string) { + return String(str) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +export default (ctx: HyperbookContext) => () => { + const name = "openscad"; + + return (tree: Root, file: VFile) => { + visit(tree, function (node) { + if (isDirective(node) && node.name === name) { + const { src = "", id = hash(node), height } = node.attributes || {}; + const data = node.data || (node.data = {}); + + expectContainerDirective(node, file, name); + registerDirective(file, name, ["client.js"], ["style.css"], []); + requestJS(file, ["code-input", "code-input.min.js"]); + requestCSS(file, ["code-input", "code-input.min.css"]); + requestJS(file, ["code-input", "auto-close-brackets.min.js"]); + requestJS(file, ["code-input", "indent.min.js"]); + + let source = ""; + if (src) { + source = readFile(src, ctx) || ""; + } else { + source = + ( + node.children.find( + (c) => + c.type === "code" && + ((c as Code).lang === "scad" || (c as Code).lang === "openscad"), + ) as Code + )?.value || ""; + } + + data.hName = "div"; + data.hProperties = { + class: "directive-openscad", + "data-id": id, + ...(height ? { style: `--openscad-height: ${height}` } : {}), + }; + + data.hChildren = [ + { + type: "element", + tagName: "div", + properties: { + class: "preview-container", + }, + children: [ + { + type: "element", + tagName: "div", + properties: { + class: "preview-header", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-preview"), + }, + ], + }, + { + type: "element", + tagName: "canvas", + properties: { + class: "preview-canvas", + }, + children: [], + }, + { + type: "element", + tagName: "pre", + properties: { + class: "output", + }, + children: [], + }, + ], + }, + { + type: "element", + tagName: "div", + properties: { + class: "splitter", + role: "separator", + "aria-label": "Resize panels", + }, + children: [], + }, + { + type: "element", + tagName: "div", + properties: { + class: "editor-container", + }, + children: [ + { + type: "element", + tagName: "div", + properties: { + class: "buttons", + }, + children: [ + { + type: "element", + tagName: "button", + properties: { + class: "tab-code active", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-code"), + }, + ], + }, + { + type: "element", + tagName: "button", + properties: { + class: "tab-parameters", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-parameters"), + }, + ], + }, + ], + }, + { + type: "element", + tagName: "code-input", + properties: { + class: "editor active line-numbers", + language: "clike", + template: "openscad-highlighted", + }, + children: [ + { + type: "raw", + value: htmlEntities(source), + }, + ], + }, + { + type: "element", + tagName: "textarea", + properties: { + class: "parameters", + placeholder: '{"size": 20, "height": 10}', + }, + children: [ + { + type: "text", + value: "{}", + }, + ], + }, + { + type: "element", + tagName: "div", + properties: { + class: "buttons bottom", + }, + children: [ + { + type: "element", + tagName: "button", + properties: { + class: "render", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-render"), + }, + ], + }, + { + type: "element", + tagName: "button", + properties: { + class: "copy", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-copy"), + }, + ], + }, + { + type: "element", + tagName: "button", + properties: { + class: "download-stl", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-download-stl"), + }, + ], + }, + { + type: "element", + tagName: "button", + properties: { + class: "download-3mf", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-download-3mf"), + }, + ], + }, + { + type: "element", + tagName: "button", + properties: { + class: "reset", + }, + children: [ + { + type: "text", + value: i18n.get("openscad-reset"), + }, + ], + }, + { + type: "element", + tagName: "button", + properties: { + class: "fullscreen", + title: i18n.get("ide-fullscreen-enter"), + "aria-label": i18n.get("ide-fullscreen-enter"), + }, + children: [ + { + type: "text", + value: "⛶", + }, + ], + }, + ], + }, + ], + }, + ]; + } + }); + }; +}; diff --git a/packages/markdown/tests/__snapshots__/remarkDirectiveOpenscad.test.ts.snap b/packages/markdown/tests/__snapshots__/remarkDirectiveOpenscad.test.ts.snap new file mode 100644 index 00000000..63fd4dd4 --- /dev/null +++ b/packages/markdown/tests/__snapshots__/remarkDirectiveOpenscad.test.ts.snap @@ -0,0 +1,19 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`remarkDirectiveOpenscad > should transform basic openscad 1`] = ` +" + + + openscad-preview + + + + + + openscad-codeopenscad-parameters + cube([20,20,20], center=true);{} + openscad-renderopenscad-copyopenscad-download-stlopenscad-download-3mfopenscad-reset⛶ + + +" +`; diff --git a/packages/markdown/tests/remarkDirectiveOpenscad.test.ts b/packages/markdown/tests/remarkDirectiveOpenscad.test.ts new file mode 100644 index 00000000..2a94783c --- /dev/null +++ b/packages/markdown/tests/remarkDirectiveOpenscad.test.ts @@ -0,0 +1,49 @@ +import { HyperbookContext } from "@hyperbook/types"; +import { describe, expect, it } from "vitest"; +import rehypeStringify from "rehype-stringify"; +import remarkToRehype from "remark-rehype"; +import rehypeFormat from "rehype-format"; +import { unified, PluggableList } from "unified"; +import remarkDirective from "remark-directive"; +import remarkDirectiveRehype from "remark-directive-rehype"; +import remarkDirectiveOpenscad from "../src/remarkDirectiveOpenscad"; +import { ctx } from "./mock"; +import remarkParse from "../src/remarkParse"; + +export const toHtml = (md: string, ctx: HyperbookContext) => { + const remarkPlugins: PluggableList = [ + remarkDirective, + remarkDirectiveRehype, + remarkDirectiveOpenscad(ctx), + ]; + + return unified() + .use(remarkParse) + .use(remarkPlugins) + .use(remarkToRehype) + .use(rehypeFormat) + .use(rehypeStringify, { + allowDangerousCharacters: true, + allowDangerousHtml: true, + }) + .processSync(md); +}; + +describe("remarkDirectiveOpenscad", () => { + it("should transform basic openscad", async () => { + expect( + toHtml( + `:::openscad + +\`\`\`scad +cube([20,20,20], center=true); +\`\`\` + +::: + +`, + ctx, + ).value, + ).toMatchSnapshot(); + }); +}); diff --git a/website/de/book/elements/openscad.md b/website/de/book/elements/openscad.md new file mode 100644 index 00000000..8bd1e09a --- /dev/null +++ b/website/de/book/elements/openscad.md @@ -0,0 +1,124 @@ +--- +name: OpenSCAD +permaid: openscad +lang: de +--- + +# OpenSCAD + +Die `openscad`-Direktive bietet einen interaktiven OpenSCAD-Editor mit: + +- einer **Code-Ansicht**, +- einer **Parameter-Ansicht** (JSON-Objekt, das auf `-D`-Variablen gemappt wird), +- und einer **3D-Vorschau**. + +Sie können das Modell rendern, den Code kopieren und als **STL** oder **3MF** herunterladen. + +## Verwendung + +Packen Sie OpenSCAD-Code in einen `:::openscad`-Block und verwenden Sie einen `scad`- (oder `openscad`-) Codeblock. + +````md +:::openscad + +```scad +cube([20,20,20], center=true); +``` + +::: +```` + +:::openscad + +```scad +cube([20,20,20], center=true); +``` + +::: + +## Attribute + +| Attribut | Beschreibung | Standard | +|---|---|---| +| `id` | Eindeutige ID für Persistenz | automatisch generiert | +| `src` | Lädt Quellcode aus einem externen Dateipfad | eingebetteter Codeblock | +| `height` | Höhe des Editor-/Vorschau-Containers | `calc(100dvh - 80px)` | + +## Code aus Datei laden + +````md +:::openscad{src="openscad/example.scad"} +::: +```` + +## Parameter (JSON) + +Öffnen Sie den Tab **Parameters** und geben Sie ein JSON-Objekt an. Jedes Schlüssel/Wert-Paar wird als `-Dname=value` an OpenSCAD übergeben. + +Beispiel: + +```json +{ + "size": 24, + "height": 16, + "segments": 64, + "rounded": true, + "label": "A" +} +``` + +## Beispiel mit Variablen + +````md +:::openscad + +```scad +$fn = segments; + +module body(size, height, rounded) { + if (rounded) { + minkowski() { + cube([size, size, height], center=true); + sphere(r=1); + } + } else { + cube([size, size, height], center=true); + } +} + +difference() { + body(size, height, rounded); + translate([0, 0, height / 2 + 0.1]) + linear_extrude(height=1) + text(label, size=8, halign="center", valign="center"); +} +``` + +::: +```` + +:::openscad + +```scad +$fn = segments; + +module body(size, height, rounded) { + if (rounded) { + minkowski() { + cube([size, size, height], center=true); + sphere(r=1); + } + } else { + cube([size, size, height], center=true); + } +} + +difference() { + body(size, height, rounded); + translate([0, 0, height / 2 + 0.1]) + linear_extrude(height=1) + text(label, size=8, halign="center", valign="center"); +} +``` + +::: diff --git a/website/en/book/elements/openscad-docs-screenshot.png b/website/en/book/elements/openscad-docs-screenshot.png new file mode 100644 index 00000000..e7efb091 Binary files /dev/null and b/website/en/book/elements/openscad-docs-screenshot.png differ diff --git a/website/en/book/elements/openscad.md b/website/en/book/elements/openscad.md new file mode 100644 index 00000000..e7b9ef46 --- /dev/null +++ b/website/en/book/elements/openscad.md @@ -0,0 +1,123 @@ +--- +name: OpenSCAD +permaid: openscad +--- + +# OpenSCAD + +The `openscad` directive provides an interactive OpenSCAD editor with: + +- a **code view**, +- a **parameter view** (JSON object mapped to `-D` variables), +- and a **3D preview**. + +You can render the model, copy the code, and download exports as **STL** or **3MF**. + +## Usage + +Wrap OpenSCAD code in a `:::openscad` block and use a `scad` (or `openscad`) code fence. + +````md +:::openscad + +```scad +cube([20,20,20], center=true); +``` + +::: +```` + +:::openscad + +```scad +cube([20,20,20], center=true); +``` + +::: + +## Attributes + +| Attribute | Description | Default | +|---|---|---| +| `id` | Unique id for persistence | auto-generated | +| `src` | Load source from an external file path | inline code block | +| `height` | Height of the editor/preview container | `calc(100dvh - 80px)` | + +## Load code from file + +````md +:::openscad{src="openscad/example.scad"} +::: +```` + +## Parameters (JSON) + +Open the **Parameters** tab and provide a JSON object. Each key/value pair is passed to OpenSCAD as `-Dname=value`. + +Example: + +```json +{ + "size": 24, + "height": 16, + "segments": 64, + "rounded": true, + "label": "A" +} +``` + +## Example with variables + +````md +:::openscad + +```scad +$fn = segments; + +module body(size, height, rounded) { + if (rounded) { + minkowski() { + cube([size, size, height], center=true); + sphere(r=1); + } + } else { + cube([size, size, height], center=true); + } +} + +difference() { + body(size, height, rounded); + translate([0, 0, height / 2 + 0.1]) + linear_extrude(height=1) + text(label, size=8, halign="center", valign="center"); +} +``` + +::: +```` + +:::openscad + +```scad +$fn = segments; + +module body(size, height, rounded) { + if (rounded) { + minkowski() { + cube([size, size, height], center=true); + sphere(r=1); + } + } else { + cube([size, size, height], center=true); + } +} + +difference() { + body(size, height, rounded); + translate([0, 0, height / 2 + 0.1]) + linear_extrude(height=1) + text(label, size=8, halign="center", valign="center"); +} +``` + +:::