mystx.ext.live_preview
======================

.. py:module:: mystx.ext.live_preview

.. autoapi-nested-parse::

   live_preview — 在浏览器中实时预览 MyST 文档

   基于 Docutils 与 MyST-Parser，将输入的 MyST 文本转换为 HTML 或其它格式，
   并在 PyScript/Pyodide 环境中通过 DOM 事件实现即时刷新。

   - 覆盖简化的 HTML 翻译器与 Writer，仅输出 body 内容并禁用样式注入；
   - 解析 YAML 配置以设置 Docutils 转换参数，收集并显示警告信息；
   - 通过页面输入与选择器，实时触发转换并更新预览区域。



Attributes
----------

.. autoapisummary::

   mystx.ext.live_preview.HTML_FORMATS
   mystx.ext.live_preview.PARSER
   mystx.ext.live_preview.MIN_INTERVAL_MS
   mystx.ext.live_preview._last_run_ms
   mystx.ext.live_preview._last_config
   mystx.ext.live_preview._last_input
   mystx.ext.live_preview._last_format
   mystx.ext.live_preview.DOM


Classes
-------

.. autoapisummary::

   mystx.ext.live_preview.SimpleTranslator
   mystx.ext.live_preview.SimpleWriter
   mystx.ext.live_preview.LivePreviewDOM


Functions
---------

.. autoapisummary::

   mystx.ext.live_preview.is_html_format
   mystx.ext.live_preview.convert
   mystx.ext.live_preview.do_convert
   mystx.ext.live_preview.setup_dom


Package Contents
----------------

.. py:data:: HTML_FORMATS

.. py:function:: is_html_format(name: str) -> bool

.. py:data:: PARSER

.. py:data:: MIN_INTERVAL_MS
   :value: 250


.. py:data:: _last_run_ms
   :value: 0.0


.. py:data:: _last_config
   :value: ''


.. py:data:: _last_input
   :value: ''


.. py:data:: _last_format
   :value: ''


.. py:class:: SimpleTranslator(document)

   Bases: :py:obj:`docutils.writers.html5_polyglot.HTMLTranslator`


   简化的 HTML 翻译器。

   - 为代码块（literal_block）追加 ``highlight`` 类，便于外部样式统一高亮；
   - 禁用样式表插入，避免在页面中重复注入样式。


   .. py:method:: visit_literal_block(node)

      处理代码块节点，追加类名后交由父类渲染。



   .. py:method:: stylesheet_call(*args, **kwargs)

      覆盖样式表插入逻辑，返回空字符串以禁用样式输出。



.. py:class:: SimpleWriter

   Bases: :py:obj:`docutils.writers.html5_polyglot.Writer`


   简化的 HTML Writer，仅输出正文内容。

   - 通过 ``filter_settings_spec`` 精简可用设置；
   - 在 ``apply_template`` 中返回 ``{body}``，避免包裹多余模板结构。


   .. py:attribute:: settings_spec

      Runtime settings specification.  Override in subclasses.

      Defines runtime settings and associated command-line options, as used by
      `docutils.frontend.OptionParser`.  This is a tuple of:

      - Option group title (string or `None` which implies no group, just a list
        of single options).

      - Description (string or `None`).

      - A sequence of option tuples.  Each consists of:

        - Help text (string)

        - List of option strings (e.g. ``['-Q', '--quux']``).

        - Dictionary of keyword arguments sent to the OptionParser/OptionGroup
          ``add_option`` method.

          Runtime setting names are derived implicitly from long option names
          ('--a-setting' becomes ``settings.a_setting``) or explicitly from the
          'dest' keyword argument.

          Most settings will also have a 'validator' keyword & function.  The
          validator function validates setting values (from configuration files
          and command-line option arguments) and converts them to appropriate
          types.  For example, the ``docutils.frontend.validate_boolean``
          function, **required by all boolean settings**, converts true values
          ('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off',
          'no', 'false', and '') to 0.  Validators need only be set once per
          setting.  See the `docutils.frontend.validate_*` functions.

          See the optparse docs for more details.

      - More triples of group title, description, options, as many times as
        needed.  Thus, `settings_spec` tuples can be simply concatenated.



   .. py:method:: apply_template()

      使用插值字典仅渲染 `body` 段并返回字符串。



   .. py:attribute:: parts

      Mapping of document part names to fragments of `self.output`.

      See `Writer.assemble_parts()` below and
      <https://docutils.sourceforge.io/docs/api/publisher.html>.



   .. py:attribute:: translator_class


.. py:function:: convert(input_config: str, input_myst: str, writer_name: str) -> dict

   将 MyST 文本转换为指定输出格式。

   Args:
       input_config: YAML 字符串形式的 Docutils 设置（可为空）。
       input_myst: 待转换的 MyST 文本内容。
       writer_name: 输出目标；包含 ``html`` 时使用 ``SimpleWriter``，
           否则传递给 Docutils 的 ``writer_name``。

   Returns:
       dict: 包含 ``output``（转换结果字符串）与 ``warnings``（警告文本）。

   Notes:
       - 配置解析失败时会记录错误并回退到空设置；
       - 通过 ``publish_string`` 执行转换，异常会被捕获并返回堆栈信息。


.. py:class:: LivePreviewDOM

   .. py:attribute:: version_label
      :type:  object
      :value: None



   .. py:attribute:: config_textarea
      :type:  object
      :value: None



   .. py:attribute:: input_textarea
      :type:  object
      :value: None



   .. py:attribute:: output_iframe
      :type:  object
      :value: None



   .. py:attribute:: output_raw
      :type:  object
      :value: None



   .. py:attribute:: warnings_textarea
      :type:  object
      :value: None



   .. py:attribute:: oformat_select
      :type:  object
      :value: None



.. py:data:: DOM

.. py:function:: do_convert(event=None)

   读取页面输入并触发转换，更新预览与原始输出。

   - 当输出格式包含 `html` 时，将 HTML 注入到预览容器；
   - 否则提示切换到 HTML 以查看渲染结果；
   - 同步展示转换产生的警告信息。


.. py:function:: setup_dom()

   初始化浏览器端的 DOM 引用与事件绑定，并进行首轮转换。


