#!/bin/sh
input=$(cat -)
input="${input#odin run src/}"
style="<style>$(cat styles.css)</style>"
doctype='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'
meta='<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'
start="$doctype<html><head><title>TypoML Preview</title>$meta$style</head><body>"
script='
<script>
(function () {
  var defs = {};
  var spans = document.querySelectorAll("[data-tlm-def]");
  for (var i = 0; i < spans.length; i++) {
    var el = spans[i];
    defs[el.dataset.tlmDef] = el.dataset.tlmValue;
  }
  var tlm = new Proxy({}, {
    get: function (_, name) {
      return defs[name];
    },
    set: function (_, name, value) {
      defs[name] = value;
      var refs = document.querySelectorAll("[data-tlm-var=\"" + name + "\"]");
      for (var i = 0; i < refs.length; i++) {
        refs[i].textContent = value;
      }
      return true;
    },
    ownKeys: function () {
      return Object.keys(defs);
    }
  });
  window.tlm = tlm;
})();
</script>'
end="$script</body></html>"
output="$start$input$end"
echo "$output" > preview.html
nohup xdg-open preview.html > /dev/null 2>&1 &
