From d7d7254a7b6ed9a670aba6bacf2487523221374c Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Wed, 27 Dec 2023 23:30:16 -0800 Subject: [PATCH] Extract loading and closing bergamot into a helper script. Signed-off-by: Danila Fedorin --- layouts/shortcodes/bergamot_js_css.html | 41 ++++++++++++++++++++++++- layouts/shortcodes/bergamot_widget.html | 2 +- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/layouts/shortcodes/bergamot_js_css.html b/layouts/shortcodes/bergamot_js_css.html index 89f5c17..6ae8bc7 100644 --- a/layouts/shortcodes/bergamot_js_css.html +++ b/layouts/shortcodes/bergamot_js_css.html @@ -75,10 +75,49 @@ const renderRules = LatexSym @ latex(?s, ?l) <- sym(?s), tostring(?s, ?l_1), join(["\\\\text{", ?l_1,"}"], ?l); LatexCall @ latex(?c, ?l) <- call(?c, ?n, ?ts), nonempty(?ts), latexlist(?ts, ?lts_1), intercalate(", ", ?lts_1, ?lts_2), join(?lts_2, ?lts_3), join(["\\\\text{", ?n, "}", "(", ?lts_3, ")"], ?l); `; -function runBergamot(nodeId, inputPrompt, rules, renderRules, query) { + +const loadedWidgets = {}; +const getButtons = (inputGroup) => { + return { + play: inputGroup.querySelector(".bergamot-play"), + reset: inputGroup.querySelector(".bergamot-reset"), + close: inputGroup.querySelector(".bergamot-close"), + } +} +const setRunning = (inputGroup, running) => { + if (inputGroup !== null) { + const buttons = getButtons(inputGroup); + if (buttons.play) buttons.play.classList.toggle("bergamot-hidden", running); + if (buttons.reset) buttons.reset.classList.toggle("bergamot-hidden", !running); + if (buttons.close) buttons.close.classList.toggle("bergamot-hidden", !running); + } +} + +window.Bergamot = {}; +window.Bergamot.run = (inputGroup, nodeId, inputPrompt, rules, renderRules, query) => { var app = Elm.Main.init({ node: document.getElementById(nodeId), flags: { renderRules, inputRules: inputPrompt, rules , query } }); + loadedWidgets[nodeId] = { app, parentNode: inputGroup ? inputGroup.parentElement : null }; + setRunning(inputGroup, true); +}; +window.Bergamot.runPreset = (inputGroup, nodeId, presetName) => { + const preset = window.Bergamot.presets[presetName]; + window.Bergamot.run(inputGroup, nodeId, preset.inputPrompt, preset.rules, renderRules, preset.query || ""); +}; +window.Bergamot.close = (inputGroup, nodeId) => { + if (!(nodeId in loadedWidgets)) return; + + const placeholderDiv = document.createElement('div'); + placeholderDiv.id = nodeId; + + const widget = loadedWidgets[nodeId]; + const elmRoot = widget.parentNode.querySelector(".bergamot-root"); + elmRoot.replaceWith(placeholderDiv) + delete loadedWidgets[nodeId]; + setRunning(inputGroup, false); } +window.Bergamot.presets = {}; + diff --git a/layouts/shortcodes/bergamot_widget.html b/layouts/shortcodes/bergamot_widget.html index 72bc978..9359fd5 100644 --- a/layouts/shortcodes/bergamot_widget.html +++ b/layouts/shortcodes/bergamot_widget.html @@ -1,4 +1,4 @@