|
| 1 | +from io import StringIO |
| 2 | + |
| 3 | +import yaml |
| 4 | +from docutils.core import publish_string |
| 5 | +from js import document |
| 6 | + |
| 7 | +from myst_parser import __version__ |
| 8 | +from myst_parser.parsers.docutils_ import Parser |
| 9 | + |
| 10 | + |
| 11 | +def convert(input_config: str, input_myst: str, writer_name: str) -> dict: |
| 12 | + warning_stream = StringIO() |
| 13 | + try: |
| 14 | + settings = yaml.safe_load(input_config) if input_config else {} |
| 15 | + assert isinstance(settings, dict), "not a dictionary" |
| 16 | + except Exception as exc: |
| 17 | + warning_stream.write(f"ERROR: config load: {exc}\n") |
| 18 | + settings = {} |
| 19 | + settings.update( |
| 20 | + { |
| 21 | + "output_encoding": "unicode", |
| 22 | + "warning_stream": warning_stream, |
| 23 | + } |
| 24 | + ) |
| 25 | + try: |
| 26 | + output = publish_string( |
| 27 | + input_myst, |
| 28 | + parser=Parser(), |
| 29 | + writer_name=writer_name, |
| 30 | + settings_overrides=settings, |
| 31 | + ) |
| 32 | + except Exception as exc: |
| 33 | + output = f"ERROR: conversion:\n{exc}" |
| 34 | + return {"output": output, "warnings": warning_stream.getvalue()} |
| 35 | + |
| 36 | + |
| 37 | +version_label = document.querySelector("span#myst-version") |
| 38 | +config_textarea = document.querySelector("textarea#input_config") |
| 39 | +input_textarea = document.querySelector("textarea#input_myst") |
| 40 | +output_iframe = document.querySelector("iframe#output_html") |
| 41 | +output_raw = document.querySelector("textarea#output_raw") |
| 42 | +warnings_textarea = document.querySelector("textarea#output_warnings") |
| 43 | +oformat_select = document.querySelector("select#output_format") |
| 44 | + |
| 45 | + |
| 46 | +def do_convert(event=None): |
| 47 | + result = convert(config_textarea.value, input_textarea.value, oformat_select.value) |
| 48 | + output_raw.value = result["output"] |
| 49 | + if "html" in oformat_select.value: |
| 50 | + output_iframe.contentDocument.body.innerHTML = result["output"] |
| 51 | + else: |
| 52 | + output_iframe.contentDocument.body.innerHTML = ( |
| 53 | + "Change output format to HTML to see output" |
| 54 | + ) |
| 55 | + warnings_textarea.value = result["warnings"] |
| 56 | + |
| 57 | + |
| 58 | +version_label.textContent = f"myst-parser v{__version__}" |
| 59 | +config_textarea.oninput = do_convert |
| 60 | +input_textarea.oninput = do_convert |
| 61 | +oformat_select.onchange = do_convert |
| 62 | + |
| 63 | +do_convert() |
0 commit comments