Référence
Le pont tient en quatre fichiers du dépôt, à copier dans votre projet :
| Fichier | Côté | Rôle |
|---|---|---|
slide_bridge.hpp, slide_bridge.cpp |
votre programme | les paramètres, déclarés une fois ; bibliothèque standard seulement |
slide-frame.html |
la page de la démo | sous le nom index.html à côté de project.js ; adaptez son CONFIG |
slide-controls.js |
la slide | des boutons et des valeurs dans le texte de la slide |
C++ : slide_bridge.hpp
| Fonction | Effet |
|---|---|
slide::parse(argc, argv) |
Garde les paires --clé valeur (un --clé seul vaut 1) et donne leurs valeurs aux paramètres déjà déclarés |
slide::arg(key, fallback), slide::has_arg(key) |
Un argument, déclaré ou non (une taille de fenêtre, avant que rien n'existe) |
slide::param(key, float& v, min, max, step) |
Un nombre, un curseur dans le panneau |
slide::param(key, int& v, min, max) |
Un entier |
slide::param(key, bool& v) |
Un interrupteur |
slide::param(key, std::string& v, {"a", "b"}) |
Un choix ; {{"a", "Label A"}, ...} donne les libellés des boutons |
slide::param(key, getter, setter, min, max, step) |
Un nombre dans d'autres unités que la variable (un float) |
slide::param(key, getter, setter) |
La même chose pour une bascule (un bool) |
slide::action(key, callback) |
Un bouton sans valeur |
slide::readout(key, getter) |
Une valeur calculée par le programme, affichée par la page et la slide, en lecture seule |
.with_label(label, short_label) |
Le libellé du contrôle (HTML permis), et celui du panneau compact |
.with_class(css) |
Une classe sur la ligne du contrôle dans le panneau |
.on_change(callback) |
Du code lancé après un changement venu de la slide |
slide::set(key, value) |
Change un paramètre comme le fait la slide (convertit le texte, lance les callbacks) ; false si refusé |
slide::describe() |
Les paramètres, leurs valeurs, intervalles et choix, en JSON |
slide::notify() |
Prévient la page que le programme a changé des valeurs de lui-même (un glisser, une valeur calculée) ; sans effet en natif |
slide::on_any_change(callback) |
Appelée avec la clé après chaque changement venu de la slide |
Un paramètre déclaré après parse() prend la valeur de l'adresse, sans appeler on_change. La compilation
web exporte slide_set(key, value) et slide_describe() ; éditez les liens avec
-sEXPORTED_FUNCTIONS=_main,_slide_set,_slide_describe -sEXPORTED_RUNTIME_METHODS=ccall.
L'adresse de la démo : slide-frame.html
| Dans l'adresse | Effet |
|---|---|
?clé=valeur&... |
Arguments du programme : --clé valeur |
controls=a,b,c |
Les contrôles du panneau, dans cet ordre ; mode:x:y ne garde que les boutons x et y du choix mode |
compact=1 |
Libellés courts, petit panneau |
panel=tl, tr, bl, br |
Le coin du panneau (tr par défaut) |
build=nom |
Charge nom/project.js : plusieurs compilations dans un même dossier |
Dans CONFIG, en tête du fichier : script (project.js par défaut), defaults (arguments quand l'adresse
n'en donne pas, {gui: '0'}), readyFrames (images dessinées avant que la démo soit montrée), capture
(garder l'image du canvas, true par défaut), navigationKeys.
La page définit aussi window.__lhtmlReady (un objet dont ready() donne une promesse résolue une fois la démo dessinée,
pour un export PDF), et affiche une erreur dans le cadre si le programme ne se charge pas ou s'arrête.
Messages
La slide et la démo communiquent par postMessage, ce qui marche aussi quand la démo est sur un autre site.
| De | Message | Sens |
|---|---|---|
| slide | {slide: {set: {ampl: 0.2, shape: 'waves'}}} |
Régler des paramètres (appliqués une fois la démo prête s'ils arrivent avant) |
| slide | {slide: {describe: true}} |
Demander les paramètres |
| démo | {slide: {ready: true, params: [...]}} |
La démo a démarré |
| démo | {slide: {changed: {key, value, accepted}, params: [...]}} |
Après chaque réglage |
| démo | {slide: {notified: true, params: [...]}} |
Le programme a changé des valeurs lui-même (au plus une fois par image) |
| démo | {slide: {described: true, params: [...]}} |
La réponse à describe |
| démo | {slide: {key: 'ArrowRight'}} |
Une touche de navigation, quand la slide est sur un autre site |
Chaque paramètre de params : {key, type, label, short, class, value, min, max, step, choices}, avec type
parmi number, integer, toggle, choice, action, readout.
La slide : slide-controls.js
| Attribut | Effet |
|---|---|
data-demo-set="a=1&b=2" |
Sur un bouton : règle les paramètres ; data-demo-set="drop" lance une action |
data-demo-value="clé" |
Affiche la valeur courante ; data-digits="2" pour un nombre |
data-demo-input="key" |
Sur un <input type="range"> de la slide : règle le paramètre pendant qu'il bouge, et suit sa valeur |
data-demo="#id" |
La démo d'un bouton, d'un curseur ou d'une valeur (par défaut : le premier iframe.demo, sinon le premier iframe) ; un sélecteur CSS comme "#left, #right" pilote plusieurs démos à la fois, et les valeurs affichées viennent de la première |
classe on |
Donnée à un bouton tant que ses réglages sont les valeurs courantes de la démo |
Depuis un script : slideDemo.set({ampl: 0.2}, frame), slideDemo.params(frame). Le script rejoue aussi les
touches de navigation postées par une démo d'un autre site, comme des appuis de touche dans la slide.
Le code du pont
Les quatre fichiers, tels qu'ils sont dans le dépôt.
bridge/slide_bridge.hpp (télécharger)
#pragma once // slide_bridge: the parameters of a demo, declared once, set from the slide. // // A demo shown in a slide (an iframe) receives its settings in two ways: // - at start, from the address of the iframe: slide-frame.html turns // index.html?freq=2&model=bunny into the arguments --freq 2 --model bunny; // - while it runs, from the controls of the page or of the slide, through // the exported function slide_set(key, value). // Each parameter is declared once, with its range or its choices: the page // builds its sliders and buttons from slide_describe() (JSON). // // slide::parse(argc, argv); // keep the --key value pairs // slide::param("freq", scene.freq, 0.3f, 5.0f); // a float in [0.3, 5] // slide::param("model", scene.model, {"spot", "bunny"}) // .on_change([&] { scene.load(scene.model); }); // called when the slide changes it // // A parameter declared after parse() takes the value given at start (without // calling on_change: the program reads its variables when it initializes). // slide::arg() reads an argument before anything is declared (a window size). // // No dependency but the standard library. Native builds compile it too: the // same arguments then come from the command line. #include <functional> #include <initializer_list> #include <string> #include <utility> #include <vector> namespace slide { enum class kind { number, integer, toggle, choice, action, readout }; // One choice of a parameter: a value, and the label of its button (the value by default). // {"spot", "bunny"} two choices, labelled by their values // {{"spot", "Cow"}, {"bunny", "Bunny"}} two choices with their labels struct choice { std::string value, label; choice(char const* v) : value(v), label(v) {} choice(std::string v) : value(v), label(std::move(v)) {} choice(std::string v, std::string l) : value(std::move(v)), label(std::move(l)) {} }; struct parameter { std::string key; kind type = kind::number; std::string label; // shown in the panel (may hold HTML, such as <i>f</i>) std::string short_label; // shown in the compact panel (compact=1) std::string css; // class of the row in the panel (to color a group of controls) float min = 0, max = 1, step = 0; std::vector<choice> choices; std::function<std::string()> get; // current value, as text std::function<bool(std::string const&)> set; // false: value refused std::vector<std::function<void()>> callbacks; // after a change from the slide // Chained settings: slide::param(...).label("frequency (Hz)").on_change(...) parameter& with_label(std::string text, std::string short_text = ""); parameter& with_class(std::string css_class); parameter& on_change(std::function<void()> callback); }; // Keep the "--key value" pairs of the command line (a lone "--key" counts as "1"), // and give their values to the parameters already declared. void parse(int argc, char* argv[]); // Value of an argument of the command line, declared or not bool has_arg(std::string const& key); std::string arg(std::string const& key, std::string const& fallback = ""); // Declarations, bound to a variable of the program parameter& param(std::string const& key, float& value, float min, float max, float step = 0); parameter& param(std::string const& key, int& value, int min, int max); parameter& param(std::string const& key, bool& value); parameter& param(std::string const& key, std::string& value, std::vector<choice> choices); // Declarations through a getter and a setter, when the variable has other units // (a frequency in Hz shown, 2 pi f stored) or is not a plain variable parameter& param(std::string const& key, std::function<float()> get, std::function<void(float)> set, float min, float max, float step = 0); parameter& param(std::string const& key, std::function<bool()> get, std::function<void(bool)> set); // A button without a value (reset, next step...) parameter& action(std::string const& key, std::function<void()> callback); // A value computed by the program, shown by the page or the slide, not set by them // (the length of a curve, the number of vertices...) parameter& readout(std::string const& key, std::function<float()> get); // Tell the page that the program changed values by itself (a drag with the mouse, a // readout that changed): the page and the slide show them again. Cheap; at most once a // frame is useful. Does nothing in a native build. void notify(); // Change a parameter as the slide does: converts the text, then calls its // callbacks. Returns false for an unknown key or a value that cannot be read. bool set(std::string const& key, std::string const& value); // The declared parameters, their current values, ranges and choices, as JSON std::string describe(); // Called after every change from the slide, with its key (a redraw, a log...) void on_any_change(std::function<void(std::string const&)> callback); // Forget everything (tests) void reset(); } // namespace slide
bridge/slide_bridge.cpp (télécharger)
#include "slide_bridge.hpp" #include <cerrno> #include <cstdio> #include <cstdlib> #include <map> #include <memory> #ifdef __EMSCRIPTEN__ #include <emscripten/emscripten.h> #endif namespace slide { namespace { struct registry_structure { std::vector<std::unique_ptr<parameter>> parameters; // in the order of declaration std::map<std::string, std::string> arguments; // --key value of the command line std::vector<std::function<void(std::string const&)>> any_change; }; registry_structure& registry() { static registry_structure r; return r; } parameter* find(std::string const& key) { for (auto& p : registry().parameters) if (p->key == key) return p.get(); return nullptr; } std::string number_text(float value) { char buffer[32]; std::snprintf(buffer, sizeof(buffer), "%.6g", double(value)); return buffer; } bool read_number(std::string const& text, float& value) { if (text.empty()) return false; char* end = nullptr; errno = 0; float const v = std::strtof(text.c_str(), &end); if (errno != 0 || end == text.c_str() || *end != '\0') return false; value = v; return true; } bool read_toggle(std::string const& text, bool& value) { if (text == "1" || text == "true" || text == "on" || text == "yes") { value = true; return true; } if (text == "0" || text == "false" || text == "off" || text == "no") { value = false; return true; } return false; } // Declares a parameter (a second declaration of the same key replaces the first) // and gives it the value of the command line, if any, without the callbacks parameter& declare(std::unique_ptr<parameter> p) { auto& list = registry().parameters; parameter* result = p.get(); bool replaced = false; for (auto& existing : list) if (existing->key == p->key) { existing = std::move(p); replaced = true; break; } if (!replaced) list.push_back(std::move(p)); if (result->label.empty()) result->label = result->key; auto const it = registry().arguments.find(result->key); if (it != registry().arguments.end() && result->type != kind::action) { if (!result->set(it->second)) std::fprintf(stderr, "slide_bridge: --%s %s: value not accepted\n", result->key.c_str(), it->second.c_str()); } return *result; } std::unique_ptr<parameter> make(std::string const& key, kind type) { auto p = std::make_unique<parameter>(); p->key = key; p->type = type; return p; } std::string json_string(std::string const& text) { std::string out = "\""; for (unsigned char c : text) { switch (c) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (c < 0x20) { char buffer[8]; std::snprintf(buffer, sizeof(buffer), "\\u%04x", c); out += buffer; } else out += char(c); } } return out + "\""; } char const* type_name(kind type) { switch (type) { case kind::number: return "number"; case kind::integer: return "integer"; case kind::toggle: return "toggle"; case kind::choice: return "choice"; case kind::action: return "action"; case kind::readout: return "readout"; } return "number"; } } // namespace parameter& parameter::with_label(std::string text, std::string short_text) { label = std::move(text); short_label = std::move(short_text); return *this; } parameter& parameter::with_class(std::string css_class) { css = std::move(css_class); return *this; } parameter& parameter::on_change(std::function<void()> callback) { callbacks.push_back(std::move(callback)); return *this; } void parse(int argc, char* argv[]) { auto& arguments = registry().arguments; for (int k = 1; k < argc; ++k) { std::string const word = argv[k]; if (word.rfind("--", 0) != 0 || word.size() <= 2) continue; std::string const key = word.substr(2); bool const has_value = k + 1 < argc && std::string(argv[k + 1]).rfind("--", 0) != 0; std::string const value = has_value ? argv[k + 1] : "1"; if (has_value) ++k; arguments[key] = value; if (parameter* p = find(key)) if (p->type != kind::action && !p->set(value)) std::fprintf(stderr, "slide_bridge: --%s %s: value not accepted\n", key.c_str(), value.c_str()); } } bool has_arg(std::string const& key) { return registry().arguments.count(key) > 0; } std::string arg(std::string const& key, std::string const& fallback) { auto const it = registry().arguments.find(key); return it == registry().arguments.end() ? fallback : it->second; } parameter& param(std::string const& key, float& value, float min, float max, float step) { float* v = &value; return param(key, std::function<float()>([v] { return *v; }), std::function<void(float)>([v](float x) { *v = x; }), min, max, step); } parameter& param(std::string const& key, std::function<float()> get, std::function<void(float)> set_value, float min, float max, float step) { auto p = make(key, kind::number); p->min = min; p->max = max; p->step = step; p->get = [get] { return number_text(get()); }; p->set = [set_value](std::string const& text) { float x; if (!read_number(text, x)) return false; set_value(x); return true; }; return declare(std::move(p)); } parameter& param(std::string const& key, int& value, int min, int max) { int* v = &value; auto p = make(key, kind::integer); p->min = float(min); p->max = float(max); p->step = 1; p->get = [v] { return std::to_string(*v); }; p->set = [v](std::string const& text) { float x; if (!read_number(text, x)) return false; *v = int(x < 0 ? x - 0.5f : x + 0.5f); return true; }; return declare(std::move(p)); } parameter& param(std::string const& key, bool& value) { bool* v = &value; return param(key, std::function<bool()>([v] { return *v; }), std::function<void(bool)>([v](bool x) { *v = x; })); } parameter& param(std::string const& key, std::function<bool()> get, std::function<void(bool)> set_value) { auto p = make(key, kind::toggle); p->get = [get] { return std::string(get() ? "1" : "0"); }; p->set = [set_value](std::string const& text) { bool x; if (!read_toggle(text, x)) return false; set_value(x); return true; }; return declare(std::move(p)); } parameter& param(std::string const& key, std::string& value, std::vector<choice> choices) { std::string* v = &value; auto p = make(key, kind::choice); p->choices = std::move(choices); parameter* raw = p.get(); p->get = [v] { return *v; }; p->set = [v, raw](std::string const& text) { if (!raw->choices.empty()) { bool known = false; for (auto const& c : raw->choices) known = known || c.value == text; if (!known) return false; } *v = text; return true; }; return declare(std::move(p)); } parameter& action(std::string const& key, std::function<void()> callback) { auto p = make(key, kind::action); p->get = [] { return std::string(); }; p->set = [](std::string const&) { return true; }; p->callbacks.push_back(std::move(callback)); return declare(std::move(p)); } parameter& readout(std::string const& key, std::function<float()> get) { auto p = make(key, kind::readout); p->get = [get] { return number_text(get()); }; p->set = [](std::string const&) { return false; }; // read only return declare(std::move(p)); } void notify() { #ifdef __EMSCRIPTEN__ EM_ASM({ if (Module.slideNotify) Module.slideNotify(); }); #endif } bool set(std::string const& key, std::string const& value) { parameter* p = find(key); if (p == nullptr) { std::fprintf(stderr, "slide_bridge: unknown parameter %s\n", key.c_str()); return false; } if (!p->set(value)) { std::fprintf(stderr, "slide_bridge: %s = %s: value not accepted\n", key.c_str(), value.c_str()); return false; } for (auto& callback : p->callbacks) callback(); for (auto& callback : registry().any_change) callback(key); return true; } std::string describe() { std::string out = "{\"version\":1,\"params\":["; bool first = true; for (auto const& p : registry().parameters) { if (!first) out += ","; first = false; out += "{\"key\":" + json_string(p->key); out += ",\"type\":\"" + std::string(type_name(p->type)) + "\""; out += ",\"label\":" + json_string(p->label); if (!p->short_label.empty()) out += ",\"short\":" + json_string(p->short_label); if (!p->css.empty()) out += ",\"class\":" + json_string(p->css); std::string const value = p->get(); switch (p->type) { case kind::readout: out += ",\"value\":" + value; break; case kind::number: case kind::integer: out += ",\"value\":" + value; out += ",\"min\":" + number_text(p->min) + ",\"max\":" + number_text(p->max); out += ",\"step\":" + number_text(p->step); break; case kind::toggle: out += std::string(",\"value\":") + (value == "1" ? "true" : "false"); break; case kind::choice: out += ",\"value\":" + json_string(value) + ",\"choices\":["; for (size_t k = 0; k < p->choices.size(); ++k) { if (k > 0) out += ","; out += "[" + json_string(p->choices[k].value) + "," + json_string(p->choices[k].label) + "]"; } out += "]"; break; case kind::action: break; } out += "}"; } return out + "]}"; } void on_any_change(std::function<void(std::string const&)> callback) { registry().any_change.push_back(std::move(callback)); } void reset() { registry() = registry_structure(); } } // namespace slide #ifdef __EMSCRIPTEN__ // Called by slide-frame.html: Module.ccall('slide_set', 'number', ['string', 'string'], [key, value]) extern "C" EMSCRIPTEN_KEEPALIVE int slide_set(char const* key, char const* value) { return slide::set(key, value) ? 1 : 0; } // Called by slide-frame.html: JSON.parse(Module.ccall('slide_describe', 'string', [], [])) extern "C" EMSCRIPTEN_KEEPALIVE char const* slide_describe() { static std::string text; text = slide::describe(); return text.c_str(); } #endif
bridge/slide-frame.html (télécharger)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Demo</title> <!-- slide-frame.html: the page of a demo compiled with Emscripten, made to be shown in a slide (an iframe). Copy it next to project.js / project.wasm / project.data as index.html, and adapt CONFIG below. The address of the iframe gives the settings: index.html?freq=2&model=bunny arguments of the program: --freq 2 --model bunny &controls=freq,model,mode:lbs:drag controls shown in the panel, in this order; mode:lbs:drag keeps only the buttons lbs and drag of the parameter mode &compact=1 short labels, small panel &panel=tl|tr|bl|br corner of the panel (default tr) &build=name load name/project.js (several builds in one folder) The panel is built from the parameters the program declares (slide_bridge.hpp): their ranges, choices and labels come from slide_describe(). The slide can drive the demo with postMessage (also from another origin): frame.contentWindow.postMessage({slide: {set: {freq: 3, mode: 'ds'}}}, '*') frame.contentWindow.postMessage({slide: {describe: true}}, '*') and the demo answers each change, and its start, with {slide: {ready|changed: ..., params: [...]}}. When the program changes values by itself (slide::notify(), a drag with the mouse, a readout), the page sends {slide: {notified: true, params: [...]}}, at most once a frame. The arrow keys and Page Up/Down go to the deck even when the demo has the focus, and the PDF export of lhtml-site waits for the first frames (window.__lhtmlReady). --> <script> var CONFIG = { script: 'project.js', // the file produced by Emscripten defaults: {}, // arguments given when the address does not, e.g. {gui: '0'} readyFrames: 10, // frames drawn before the demo is shown and counted as ready capture: true, // keep the image of the canvas (PDF export, tests); a little slower navigationKeys: ['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp', 'PageDown', 'PageUp'] }; </script> <style> html, body { margin: 0; height: 100%; overflow: hidden; background: white; } #canvas { display: block; position: fixed; left: 0; top: 0; outline: none; opacity: 0; transition: opacity 0.35s; } #canvas.ready { opacity: 1; } #status { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); color: #888; font: 22px system-ui, sans-serif; } #status.error { color: #b00020; max-width: 80%; text-align: center; } #controls { position: fixed; right: 12px; top: 12px; padding: 10px 16px; display: none; font-family: Palatino, "Palatino Linotype", Georgia, serif; font-size: 28px; background: rgba(255, 255, 255, 0.85); border: 1px solid #ddd; border-radius: 10px; } #controls.tl { right: auto; left: 12px; } #controls.bl { right: auto; left: 12px; top: auto; bottom: 12px; } #controls.br { top: auto; bottom: 12px; } #controls .row { display: flex; align-items: center; gap: 10px; margin: 4px 0; } #controls label { min-width: 200px; } #controls input[type=range] { width: 240px; } #controls .value { min-width: 60px; text-align: right; font-variant-numeric: tabular-nums; } #controls button { font: inherit; font-size: 0.93em; padding: 2px 12px; cursor: pointer; border: 1px solid #aaa; border-radius: 6px; background: white; } #controls button.on { background: #333; color: white; border-color: #333; } #controls.compact { font-size: 20px; padding: 4px 10px; } #controls.compact .row { gap: 8px; margin: 1px 0; } #controls.compact label { min-width: 0; width: 62px; } #controls.compact input[type=range] { width: 130px; } #controls.compact .value { min-width: 42px; } @media (max-width: 1100px) { #controls:not(.compact) { font-size: 24px; padding: 6px 10px; } #controls:not(.compact) label { min-width: 150px; } #controls:not(.compact) input[type=range] { width: 150px; } } /* colors of a group of controls (the class given in C++ by .with_class("time")): add yours here */ </style> <script> // The navigation keys go to the deck when the demo has the focus. A deck of lhtml-site // (from its version with window.__lhtmlNavigation) listens to the keys of its demos itself: // nothing to do then. Other decks: the key is sent to the slide, or posted to another origin. window.addEventListener('keydown', function (e) { if (window.parent === window || e.defaultPrevented || CONFIG.navigationKeys.indexOf(e.key) < 0) return; var parentListens = false; try { parentListens = !!window.parent.__lhtmlNavigation; } catch (err) {} if (parentListens) return; e.stopImmediatePropagation(); e.preventDefault(); try { // the event of the slide carries keyCode and which too: some slide tools (reveal.js) read them var copy = new KeyboardEvent('keydown', {key: e.key, code: e.code, bubbles: true, cancelable: true}); var code = {ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, PageUp: 33, PageDown: 34}[e.key] || 0; Object.defineProperty(copy, 'keyCode', {get: function () { return code; }}); Object.defineProperty(copy, 'which', {get: function () { return code; }}); window.parent.document.dispatchEvent(copy); } catch (err) { window.parent.postMessage({slide: {key: e.key}}, '*'); } // another origin }, true); </script> </head> <body> <canvas id="canvas" tabindex="-1" oncontextmenu="event.preventDefault()"></canvas> <div id="status">Loading...</div> <div id="controls"></div> <script> (function () { var RESERVED = ['controls', 'compact', 'panel', 'build']; var canvas = document.getElementById('canvas'); var statusBox = document.getElementById('status'); var panel = document.getElementById('controls'); var query = new URLSearchParams(window.location.search); // The canvas keeps its image after each frame, so that it can be captured (PDF export, tests). // The GLFW of Emscripten builds the attributes of its WebGL context from its hints only, and // ignores Module.webglContextAttributes: they are added here, for this canvas. if (CONFIG.capture) { var getContext = HTMLCanvasElement.prototype.getContext; HTMLCanvasElement.prototype.getContext = function (type, attributes) { if (this === canvas && /webgl/.test(type)) attributes = Object.assign({}, attributes, {preserveDrawingBuffer: true}); return getContext.call(this, type, attributes); }; } function resize() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; } resize(); window.addEventListener('resize', resize); // Arguments of the program: the defaults, then the address var options = {}; Object.keys(CONFIG.defaults).forEach(function (key) { options[key] = String(CONFIG.defaults[key]); }); query.forEach(function (value, key) { if (RESERVED.indexOf(key) < 0) options[key] = value; }); var args = []; Object.keys(options).forEach(function (key) { args.push('--' + key, options[key]); }); // Ready: the runtime started and a few frames are drawn (the PDF export of lhtml-site waits for it) var started = false, params = [], pending = []; var markReady; var ready = new Promise(function (done) { markReady = done; }); window.__lhtmlReady = {version: 1, ready: function () { return ready; }}; var build = (query.get('build') || '').replace(/[^A-Za-z0-9_-]/g, ''); var prefix = build ? build + '/' : ''; window.Module = { canvas: canvas, arguments: args, locateFile: function (path) { return prefix + path; }, print: function (text) { console.log(text); }, printErr: function (text) { console.warn(text); }, // Called before main(): the parameters are declared by main, so they are read a few frames later onRuntimeInitialized: function () { var frames = 0; (function count() { if (++frames < CONFIG.readyFrames) { requestAnimationFrame(count); return; } started = true; resize(); // a program may have created its window at a fixed size (glfwCreateWindow resizes the canvas) refresh(); buildPanel(); pending.forEach(function (m) { receive(m); }); pending = []; canvas.classList.add('ready'); statusBox.style.display = 'none'; markReady(); tellParent({ready: true}); })(); }, onAbort: function (what) { fail('The demo stopped: ' + what); }, // slide::notify() of the program: values changed by the program itself (a drag, a readout); // shown again at most once a frame slideNotify: function () { if (!started || notifyPending) return; notifyPending = true; requestAnimationFrame(function () { notifyPending = false; refresh(); updatePanel(); tellParent({notified: true}); }); } }; var notifyPending = false; function fail(message) { statusBox.textContent = message; statusBox.className = 'error'; statusBox.style.display = 'block'; markReady(); // the export prints the slide anyway, with the message } function refresh() { try { params = JSON.parse(Module.ccall('slide_describe', 'string', [], [])).params; } catch (e) { params = []; console.warn('slide_describe: ' + e); } } function find(key) { for (var k = 0; k < params.length; ++k) if (params[k].key === key) return params[k]; return null; } function setValue(key, value) { var ok = Module.ccall('slide_set', 'number', ['string', 'string'], [key, String(value)]); refresh(); // a change may change other parameters (a preset): show them all again updatePanel(); tellParent({changed: {key: key, value: value, accepted: !!ok}}); return ok; } function tellParent(message) { if (window.parent === window) return; message.params = params; window.parent.postMessage({slide: message}, '*'); } // Messages of the slide: {slide: {set: {key: value, ...}}} or {slide: {describe: true}} function receive(m) { if (m.set) Object.keys(m.set).forEach(function (key) { setValue(key, m.set[key]); }); if (m.describe) tellParent({described: true}); } window.addEventListener('message', function (event) { var m = event.data && event.data.slide; if (!m || typeof m !== 'object') return; if (started) receive(m); else pending.push(m); }); // The panel: controls=key1,key2,choice:value1:value2 var widgets = []; function buildPanel() { var list = (query.get('controls') || '').split(',').filter(function (s) { return s; }); if (list.length === 0) return; var compact = query.get('compact') === '1'; if (compact) panel.classList.add('compact'); var corner = query.get('panel'); if (['tl', 'bl', 'br'].indexOf(corner) >= 0) panel.classList.add(corner); list.forEach(function (entry) { var parts = entry.split(':'); var p = find(parts[0]); if (!p) { console.warn('controls: no parameter ' + parts[0]); return; } var row = document.createElement('div'); row.className = 'row' + (p.class ? ' ' + p.class : ''); var label = (compact && p.short) ? p.short : p.label; if (p.type === 'number' || p.type === 'integer') { row.innerHTML = '<label></label><input type="range"><span class="value"></span>'; row.querySelector('label').innerHTML = label; var input = row.querySelector('input'); input.min = p.min; input.max = p.max; input.step = p.step > 0 ? p.step : (p.max - p.min) / 100; input.addEventListener('input', function () { setValue(p.key, input.value); }); widgets.push({key: p.key, update: function (q) { if (document.activeElement !== input) input.value = q.value; row.querySelector('.value').textContent = formatNumber(q.value, input.step); }}); } else if (p.type === 'choice') { var keep = parts.slice(1); var buttons = []; p.choices.forEach(function (c) { if (keep.length > 0 && keep.indexOf(c[0]) < 0) return; var b = document.createElement('button'); b.innerHTML = c[1]; b.addEventListener('click', function () { setValue(p.key, c[0]); }); row.appendChild(b); buttons.push([c[0], b]); }); widgets.push({key: p.key, update: function (q) { buttons.forEach(function (x) { x[1].classList.toggle('on', x[0] === q.value); }); }}); } else if (p.type === 'toggle') { var t = document.createElement('button'); t.innerHTML = label; t.addEventListener('click', function () { setValue(p.key, find(p.key).value ? '0' : '1'); }); row.appendChild(t); widgets.push({key: p.key, update: function (q) { t.classList.toggle('on', !!q.value); }}); } else if (p.type === 'readout') { row.innerHTML = '<label></label><span class="value"></span>'; row.querySelector('label').innerHTML = label; widgets.push({key: p.key, update: function (q) { row.querySelector('.value').textContent = formatNumber(q.value, 0.01); }}); } else if (p.type === 'action') { var a = document.createElement('button'); a.innerHTML = label; a.addEventListener('click', function () { setValue(p.key, ''); }); row.appendChild(a); } panel.appendChild(row); }); panel.style.display = 'block'; updatePanel(); } function updatePanel() { widgets.forEach(function (w) { var q = find(w.key); if (q) w.update(q); }); } function formatNumber(value, step) { var decimals = Math.max(0, Math.min(4, Math.ceil(-Math.log10(Number(step) || 1)))); return Number(value).toFixed(decimals); } // The program itself var script = document.createElement('script'); script.src = prefix + CONFIG.script; script.async = true; script.onerror = function () { fail('Cannot load ' + script.src + ' (open this page with a web server, not as a file)'); }; document.body.appendChild(script); })(); </script> </body> </html>
bridge/slide-controls.js (télécharger)
// slide-controls.js: controls in the slide itself, outside the demo, with HTML attributes only. // // Load it in the slide (<script src=".../slide-controls.js"></script>), then: // <button data-demo-set="shape=ripple">Ripple</button> sets a parameter of the demo // <button data-demo-set="ampl=0.2&speed=6">Strong</button> sets several at once // <button data-demo-set="drop">Drop</button> runs an action (a parameter without value) // <span data-demo-value="ampl" data-digits="2"></span> shows the current value of a parameter // <input type="range" data-demo-input="ampl" min="0" max="0.3" step="0.01"> // a slider of the slide, which sets the parameter // A button whose settings are the current values of the demo gets the class "on". // The demo is the first iframe.demo of the page (or the first iframe); data-demo="#id" names another, and // data-demo="#left, #right" (any CSS selector) drives several demos at once: the buttons and the sliders // set all of them, the values shown are those of the first one. // // The demo is a page made from slide-frame.html: the messages go through postMessage, so the demo // may come from another origin. From a script: slideDemo.set({ampl: 0.2}), slideDemo.params(). (function () { 'use strict'; var params = new Map(); // demo window -> {key: parameter} function framesOf(element) { var selector = element && element.getAttribute('data-demo'); if (selector) return Array.prototype.slice.call(document.querySelectorAll(selector)); var frame = document.querySelector('iframe.demo') || document.querySelector('iframe'); return frame ? [frame] : []; } function frameOf(element) { return framesOf(element)[0] || null; } function parse(text) { var settings = {}; text.split('&').forEach(function (pair) { if (!pair) return; var k = pair.indexOf('='); if (k < 0) settings[decodeURIComponent(pair)] = ''; else settings[decodeURIComponent(pair.slice(0, k))] = decodeURIComponent(pair.slice(k + 1)); }); return settings; } function set(settings, frames) { frames = frames ? (Array.isArray(frames) ? frames : [frames]) : framesOf(null); frames.forEach(function (frame) { if (frame && frame.contentWindow) frame.contentWindow.postMessage({slide: {set: settings}}, '*'); }); } function same(value, text) { if (typeof value === 'boolean') return value === (text === '1' || text === 'true' || text === 'on'); if (typeof value === 'number') return Math.abs(value - Number(text)) < 1e-6; return String(value) === text; } function update() { document.querySelectorAll('[data-demo-set]').forEach(function (button) { var frame = frameOf(button); var current = frame && params.get(frame.contentWindow); if (!current) return; var settings = parse(button.getAttribute('data-demo-set')); var keys = Object.keys(settings); var on = keys.length > 0 && keys.every(function (key) { var p = current[key]; return p && p.type !== 'action' && same(p.value, settings[key]); }); button.classList.toggle('on', on); }); document.querySelectorAll('[data-demo-input]').forEach(function (input) { if (input === document.activeElement) return; // not while it is moved var frame = frameOf(input); var current = frame && params.get(frame.contentWindow); var p = current && current[input.getAttribute('data-demo-input')]; if (p && typeof p.value === 'number') input.value = p.value; }); document.querySelectorAll('[data-demo-value]').forEach(function (span) { var frame = frameOf(span); var current = frame && params.get(frame.contentWindow); var p = current && current[span.getAttribute('data-demo-value')]; if (!p) return; var digits = span.getAttribute('data-digits'); span.textContent = (typeof p.value === 'number' && digits !== null) ? p.value.toFixed(Number(digits)) : String(p.value); }); } document.addEventListener('click', function (event) { var button = event.target.closest && event.target.closest('[data-demo-set]'); if (!button) return; event.preventDefault(); set(parse(button.getAttribute('data-demo-set')), framesOf(button)); }); document.addEventListener('input', function (event) { var input = event.target.closest && event.target.closest('[data-demo-input]'); if (!input) return; var settings = {}; settings[input.getAttribute('data-demo-input')] = input.value; set(settings, framesOf(input)); }); // a slider released keeps the focus, and the slide tools ignore the arrow keys while an input has it: // give the focus back to the page, so that the arrow keys change the slide again document.addEventListener('change', function (event) { var input = event.target.closest && event.target.closest('[data-demo-input]'); if (input) input.blur(); }); window.addEventListener('message', function (event) { var m = event.data && event.data.slide; if (!m || typeof m !== 'object') return; if (m.key) { // a navigation key from a demo of another origin // a deck of lhtml-site handles these messages itself (window.__lhtmlNavigation) if (!window.__lhtmlNavigation) { // with keyCode and which: some slide tools (reveal.js) read them var copy = new KeyboardEvent('keydown', {key: m.key, bubbles: true, cancelable: true}); var code = {ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, PageUp: 33, PageDown: 34}[m.key] || 0; Object.defineProperty(copy, 'keyCode', {get: function () { return code; }}); Object.defineProperty(copy, 'which', {get: function () { return code; }}); document.dispatchEvent(copy); } return; } if (m.params) { var current = {}; m.params.forEach(function (p) { current[p.key] = p; }); params.set(event.source, current); update(); } }); window.slideDemo = { set: set, params: function (frame) { frame = frame || frameOf(null); return frame ? params.get(frame.contentWindow) : undefined; } }; })();