System.register(["reactive-jsx", "src/client/strings.js", "src/external/lodash/lodash.js", "src/external/highlight.js"], function (_export, _context) {
  "use strict";

  var _childSpread, _addSourceLocation, _childText, _childElement, _attributeStringLiteral, _childExpression, _children, _attributeExpression, _attributes, _element, Strings, _, highlight, Markdown, __SystemJSRewritingHack;
  _export("default", void 0);
  return {
    setters: [function (_reactiveJsx) {
      _childSpread = _reactiveJsx.childSpread;
      _addSourceLocation = _reactiveJsx.addSourceLocation;
      _childText = _reactiveJsx.childText;
      _childElement = _reactiveJsx.childElement;
      _attributeStringLiteral = _reactiveJsx.attributeStringLiteral;
      _childExpression = _reactiveJsx.childExpression;
      _children = _reactiveJsx.children;
      _attributeExpression = _reactiveJsx.attributeExpression;
      _attributes = _reactiveJsx.attributes;
      _element = _reactiveJsx.element;
    }, function (_srcClientStringsJs) {
      Strings = _srcClientStringsJs.default;
    }, function (_srcExternalLodashLodashJs) {
      _ = _srcExternalLodashLodashJs.default;
    }, function (_srcExternalHighlightJs) {
      highlight = _srcExternalHighlightJs.default;
    }],
    execute: function () {
      __SystemJSRewritingHack = {};
      _recorder_._https__lively_kernel_org_lively4_lively4_ansgar_src_client_markdown_js = _recorder_._https__lively_kernel_org_lively4_lively4_ansgar_src_client_markdown_js || {};
      Object.defineProperty(_recorder_._https__lively_kernel_org_lively4_lively4_ansgar_src_client_markdown_js, "Strings", {
        get() {
          return Strings;
        },
        set(thisIsVererySecretVariableName) {
          Strings = thisIsVererySecretVariableName;
          return true;
        },
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(_recorder_._https__lively_kernel_org_lively4_lively4_ansgar_src_client_markdown_js, "_", {
        get() {
          return _;
        },
        set(thisIsVererySecretVariableName) {
          _ = thisIsVererySecretVariableName;
          return true;
        },
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(_recorder_._https__lively_kernel_org_lively4_lively4_ansgar_src_client_markdown_js, "highlight", {
        get() {
          return highlight;
        },
        set(thisIsVererySecretVariableName) {
          highlight = thisIsVererySecretVariableName;
          return true;
        },
        enumerable: true,
        configurable: true
      });
      _export("default", Markdown = class Markdown {
        // #helper 
        static parseAndReplaceTextNode(ea, eaChild, regex, func) {
          var s = eaChild.textContent;
          var m;
          regex = new RegExp(regex);
          var replace = () => {
            m = regex.exec(s);
            if (m) {
              var replacement = func(m, ea);
              if (replacement !== undefined) {
                if (_.isString(replacement)) {
                  replacement = new Text(replacement);
                }
                ea.insertBefore(new Text(s.slice(0, m.index)), eaChild);
                ea.insertBefore(replacement, eaChild);
                var rest = new Text(s.slice(m.index + m[0].length, s.length));
                ea.insertBefore(rest, eaChild);
                eaChild.remove();
                this.parseAndReplaceTextNode(ea, rest, regex, func); // go on with the rest...
              } else {
                if (regex.lastIndex) {
                  replace();
                }
              }
            }
          };
          replace();
        }

        // #helper 
        static parseAndReplace(element, regex, func) {
          var all = [element].concat(Array.from(element.querySelectorAll("*")));
          // lively.notify("parse " + all.length + " elements.")
          for (var ea of all) {
            // if (ea.localName == "code" || ea.localName == "pre") return; 
            try {
              // lively.showElement(ea)
              if (!ea.childNodes) continue;
              for (var eaChild of ea.childNodes) {
                if (eaChild instanceof Text) {
                  this.parseAndReplaceTextNode(ea, eaChild, regex, func);
                }
              }
            } catch (e) {
              console.error(e);
            }
          }
        }
        static parseAndReplaceBibrefs(element) {
          this.parseAndReplace(element, /\@([A-Za-z_]+[0-9]+[A-Za-z_]*)/g, m => {
            var link = _element("a", _attributes(_attributeExpression("click", evt => {
              evt.preventDefault();
              evt.stopPropagation();
              lively.openBrowser("bib://" + m[1]);
            })), _children(_childExpression(m[1])), {
              file: 'no_file_given',
              end: {
                column: 20,
                line: 96
              },
              start: {
                column: 17,
                line: 92
              }
            }); // href={"bib://" +m[1]}
            return link;
          });
        }
        static parseAndReplaceLabels(element) {
          this.parseAndReplace(element, /\\label({[^}]+})?/g, (m, contextElement) => {
            if (contextElement.localName !== "p") return;
            var id = "undefined"; // the id is allreay 
            var anchor = _element("a", _attributes(_attributeExpression("click", evt => {}), _attributeExpression("id", id)), _children(), {
              file: 'no_file_given',
              end: {
                column: 21,
                line: 108
              },
              start: {
                column: 19,
                line: 107
              }
            });
            return anchor;
          });
        }
        static parseAndReplaceMiscLatex(element) {
          this.parseAndReplace(element, /(\\[a-z]+({[^}]+})?(\[[^\]]+\])?)/g, (m, contextElement) => {
            if (contextElement.localName !== "p") return "";
            return _element("span", _attributes(_attributeStringLiteral("class", "stripped"), _attributeExpression("latex", m[1])), _children(), {
              file: 'no_file_given',
              end: {
                column: 56,
                line: 116
              },
              start: {
                column: 13,
                line: 116
              }
            });
          });
        }
        static parseAndReplaceFigures(element) {
          var container = lively.query(element, "lively-container");
          var baseDir = container ? container.getDir() : "";
          this.parseAndReplace(element, /\\includegraphics\[[^\]]*\]{([^}]+)\}/g, m => _element("div", _attributes(), _children(_childElement(_element("img", _attributes(_attributeExpression("src", baseDir + m[1])), _children(), {
            file: 'no_file_given',
            end: {
              column: 120,
              line: 123
            },
            start: {
              column: 88,
              line: 123
            }
          }))), {
            file: 'no_file_given',
            end: {
              column: 126,
              line: 123
            },
            start: {
              column: 83,
              line: 123
            }
          }));
          this.parseAndReplace(element, /\\caption\[[^\]]*\]{([^}]+)\}/g, m => _element("div", _attributes(), _children(_childText("Figure: "), _childExpression(m[1])), {
            file: 'no_file_given',
            end: {
              column: 100,
              line: 124
            },
            start: {
              column: 75,
              line: 124
            }
          }));
        }

        // #important
        static parseAndReplaceListings(element) {
          var container = lively.query(element, "lively-container");
          var baseDir = container ? container.getDir() : "";
          this.parseAndReplace(element, /(?:^|\n)\/([^ ]+) "([^"]*)"/g, m => {
            var pre = _element("pre", _attributes(), _children(_childText("LOADING...")), {
              file: 'no_file_given',
              end: {
                column: 37,
                line: 132
              },
              start: {
                column: 16,
                line: 132
              }
            });
            var url = baseDir + m[1];
            var description = m[2];
            fetch(url).then(async r => {
              if (r.status == 200) {
                let source = await r.text();
                pre.innerHTML = source;
                highlight.highlightBlock(pre);
              } else {
                pre.textContent = "Could not load " + url;
              }
            });
            return _element("div", _attributes(), _children(_childExpression(pre), _childElement(_element("p", _attributes(), _children(_childElement(_element("b", _attributes(), _children(_childText("Listing:")), {
              file: 'no_file_given',
              end: {
                column: 41,
                line: 145
              },
              start: {
                column: 26,
                line: 145
              }
            })), _childText(" "), _childExpression(description), _childText(" ")), {
              file: 'no_file_given',
              end: {
                column: 60,
                line: 145
              },
              start: {
                column: 23,
                line: 145
              }
            }))), {
              file: 'no_file_given',
              end: {
                column: 66,
                line: 145
              },
              start: {
                column: 13,
                line: 145
              }
            });
          });
        }
        static parseAndReplaceFigureRefs(element) {
          element.querySelectorAll("lively-drawio").forEach(ea => {
            var name = ea.getAttribute("alt");
            if (name && name !== null) {
              var titleString = ea.getAttribute("title");
              if (titleString == null) titleString = "";
              var title = _element("div", _attributes(_attributeStringLiteral("class", "figuretitle")), _children(_childElement(_element("a", _attributes(_attributeExpression("id", ea.getAttribute("alt"))), _children(), {
                file: 'no_file_given',
                end: {
                  column: 80,
                  line: 155
                },
                start: {
                  column: 45,
                  line: 155
                }
              })), _childElement(_element("b", _attributes(), _children(_childText("Figure "), _childExpression(ea.getAttribute("alt")), _childText(". ")), {
                file: 'no_file_given',
                end: {
                  column: 120,
                  line: 155
                },
                start: {
                  column: 80,
                  line: 155
                }
              })), _childExpression(titleString)), {
                file: 'no_file_given',
                end: {
                  column: 139,
                  line: 155
                },
                start: {
                  column: 20,
                  line: 155
                }
              });
              ea.parentElement.appendChild(title);
            }
          });

          // late parse and convert latex figure references
          this.parseAndReplace(element, /@fig:([A-Za-z0-9]+)/g, m => _element("a", _attributes(_attributeExpression("href", "#" + m[1])), _children(_childExpression(m[1])), {
            file: 'no_file_given',
            end: {
              column: 95,
              line: 161
            },
            start: {
              column: 65,
              line: 161
            }
          }));
          this.parseAndReplace(element, /\\(?:auto)?ref\{([^}]+)\}/g, m => _element("a", _attributes(_attributeExpression("href", "#" + m[1])), _children(_childExpression(m[1])), {
            file: 'no_file_given',
            end: {
              column: 101,
              line: 162
            },
            start: {
              column: 71,
              line: 162
            }
          }));
        }
        static parseAndReplaceHeadings(element) {
          this.parseAndReplace(element, /\\paragraph\{([^}]+)\}/g, m => _element("b", _attributes(), _children(_childExpression(m[1])), {
            file: 'no_file_given',
            end: {
              column: 81,
              line: 167
            },
            start: {
              column: 68,
              line: 167
            }
          }));
        }
        static allNodesBetween(startNode, endNode) {
          var nodes = [];
          var node = startNode;
          while (node && node != endNode) {
            if (node !== startNode) nodes.push(node);
            node = node.nextSibling;
          }
          return nodes;
        }
        static parseAndReplaceFootenotes(element) {
          var count = 1;
          var footnotes = [];
          // #TODO what about markup in that markup?: ^[*Exposé* shows an overview ]
          /*MD <browse://../Lively4DevelopmentExperience/content/Discussion.md> MD*/

          var stack = [];

          // hacky hacky hack hack hack!
          this.parseAndReplace(element, /((\^\[)|\])/g, m => {
            if (m[1] == "^[") {
              var footnote = {
                index: count++,
                content: "",
                id() {
                  return "footnote_" + this.index;
                }
              };
              footnotes.push(footnote);
              let link = _element("sup", _attributes(), _children(_childElement(_element("a", _attributes(_attributeExpression("href", "#" + footnote.id())), _children(_childExpression(footnote.index)), {
                file: 'no_file_given',
                end: {
                  column: 74,
                  line: 194
                },
                start: {
                  column: 24,
                  line: 194
                }
              }))), {
                file: 'no_file_given',
                end: {
                  column: 80,
                  line: 194
                },
                start: {
                  column: 19,
                  line: 194
                }
              });
              footnote.startNode = link;
              stack.push(footnote);
              return link;
            } else {
              let last = stack.pop();
              if (last) {
                var marker = _addSourceLocation(document.createElement("b"), {
                  file: 'no_file_given',
                  end: {
                    column: 50,
                    line: 201
                  },
                  start: {
                    column: 23,
                    line: 201
                  }
                });
                marker.textContent = "END" + last.index;
                last.endNode = marker;
                return marker;
              }
            }
          });
          footnotes.forEach(ea => {
            if (ea.startNode && ea.endNode) {
              var region = this.allNodesBetween(ea.startNode, ea.endNode);
              ea.content = _element("span", _attributes(), _children(_childSpread(region)), {
                file: 'no_file_given',
                end: {
                  column: 45,
                  line: 213
                },
                start: {
                  column: 21,
                  line: 213
                }
              }); // will get removed...
              ea.endNode.remove(); // ged rid of the marker
            }
          });

          if (footnotes.length > 0) {
            var footnotesDiv = _element("div", _attributes(), _children(_childElement(_element("h3", _attributes(), _children(_childText("Footnotes")), {
              file: 'no_file_given',
              end: {
                column: 48,
                line: 220
              },
              start: {
                column: 30,
                line: 220
              }
            })), _childElement(_element("ol", _attributes(), _children(_childSpread(footnotes.map(ea => _element("li", _attributes(), _children(_childElement(_element("a", _attributes(_attributeExpression("id", ea.id())), _children(), {
              file: 'no_file_given',
              end: {
                column: 100,
                line: 220
              },
              start: {
                column: 80,
                line: 220
              }
            })), _childExpression(ea.content)), {
              file: 'no_file_given',
              end: {
                column: 117,
                line: 220
              },
              start: {
                column: 76,
                line: 220
              }
            })))), {
              file: 'no_file_given',
              end: {
                column: 124,
                line: 220
              },
              start: {
                column: 48,
                line: 220
              }
            }))), {
              file: 'no_file_given',
              end: {
                column: 130,
                line: 220
              },
              start: {
                column: 25,
                line: 220
              }
            });
            element.appendChild(footnotesDiv);
          }
        }

        /*MD
        <style>* {background-color:lightgray}</style>
        ```javascript
        // we have to "quote" the @ because we are still in markdown... and replacing those references
        Markdown.extractReferences(`Hello @`+`Foo1981HHC World\nggg @`+`Bar2019X`)
        ```
        <script>
        import Markdown from 'src/client/markdown.js';
        <pre>Result:{eval(this.parentElement.querySelector("code").textContent)}</pre>
        </script>
        MD*/

        static extractReferences(source) {
          return Strings.matchAll(/@([A-Za-z0-9_]+)/g, source).map(ea => ea[1]);
        }
        static parseAndReplaceLatex(element) {
          // do it only once
          if (element._parsedLatex) {
            return;
          } else {
            element._parsedLatex = true;
          }
          this.parseAndReplaceBibrefs(element);
          this.parseAndReplaceFootenotes(element);
          this.parseAndReplaceListings(element);
          this.parseAndReplaceFigures(element);
          this.parseAndReplaceFigureRefs(element);
          this.parseAndReplaceLabels(element);
          this.parseAndReplaceHeadings(element);
          this.parseAndReplaceMiscLatex(element);
        }
      });
      Object.defineProperty(_recorder_._https__lively_kernel_org_lively4_lively4_ansgar_src_client_markdown_js, "Markdown", {
        get() {
          return Markdown;
        },
        set(thisIsVererySecretVariableName) {
          _export("default", Markdown = thisIsVererySecretVariableName);
          return true;
        },
        enumerable: true,
        configurable: true
      });
    }
  };
});