Browse Source

✨ discussions 正文切到新渲染服务:body 节点树 + content_type_v2(markdown-e2)

渲染:
- v3 discussions 响应的 html(v2 MdRender 的 MdTpl HTML 字符串)改成 body:
  App\Services\Markup 的节点树(text / el / tpl),summary 也由新服务生成;整页一起渲染、批量取数
- OpenAPI 生成器加命名 schema MarkupNode(递归),Resource 的 @return 可写 list<MarkupNode>,
  前端类型从生成结果取
- dashboard-v6 新增 components/markup:MarkupView 按节点树渲染,标签再过一道白名单、文本过 gfwClear;
  模板名对应到 components/template 里各模板的内部组件(导出 XxxCtl,原 MdTpl 路径不变);
  句子模板用只读的 SentenceView。DiscussionShow 从 MdView 换成 MarkupView
- 消费方:wikipali-mobile 只用 summary,wikipali-plugins 不读 html,dashboard-v4 不调 v3

方言:
- discussions.content_type 有 CHECK 约束(markdown / text / html),存不下 markdown-e2;
  加列 content_type_v2(nullable varchar(16))。v3 写入(新建、回复、评估、PATCH 改正文)
  content_type_v2 = markdown-e2、content_type 仍填 markdown(v2 / v4 照旧读);
  v3 读取与渲染用 Discussion::effectiveContentType()(v2 列优先)。响应形状不变
- v2 下线后 content_type 废弃,只认 content_type_v2(见 migration 与模型注释)

测试:DiscussionBodyV3Test;api-test 讨论用例断言 body / summary;dashboard-test 断言 body 渲染成组件、
页面上发的回复是 markdown-e2。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 8 hours ago
parent
commit
2a84acf19c
39 changed files with 3166 additions and 79 deletions
  1. 8 0
      api-test/cases/07_discussions.php
  2. 12 0
      api-test/client/.openapi-generator/FILES
  3. 17 17
      api-test/client/lib/Model/GetApiV3Discussions200ResponseDataInner.php
  4. 552 0
      api-test/client/lib/Model/MarkupElement.php
  5. 668 0
      api-test/client/lib/Model/MarkupNode.php
  6. 555 0
      api-test/client/lib/Model/MarkupTemplate.php
  7. 481 0
      api-test/client/lib/Model/MarkupText.php
  8. 1 1
      api-v13/app/Http/Requests/V3/StoreDiscussionRequest.php
  9. 13 3
      api-v13/app/Http/Resources/V3/DiscussionResource.php
  10. 28 1
      api-v13/app/Models/Discussion.php
  11. 29 8
      api-v13/app/Services/V3/DiscussionService.php
  12. 32 0
      api-v13/database/migrations/2026_11_17_070353_add_content_type_v2_to_discussions.php
  13. 129 0
      api-v13/tests/Feature/DiscussionBodyV3Test.php
  14. 2 1
      api-v13/tests/Feature/DiscussionV3Test.php
  15. 53 1
      dashboard-test/src/tests/discussion.spec.ts
  16. 4 3
      dashboard-v6/src/api/discussion.ts
  17. 41 10
      dashboard-v6/src/api/schema.d.ts
  18. 0 1
      dashboard-v6/src/components/discussion/DiscussionListCard.tsx
  19. 3 3
      dashboard-v6/src/components/discussion/DiscussionShow.tsx
  20. 87 0
      dashboard-v6/src/components/markup/MarkupTemplate.tsx
  21. 30 0
      dashboard-v6/src/components/markup/MarkupView.tsx
  22. 77 0
      dashboard-v6/src/components/markup/SentenceView.tsx
  23. 162 0
      dashboard-v6/src/components/markup/render.tsx
  24. 12 0
      dashboard-v6/src/components/markup/types.ts
  25. 1 1
      dashboard-v6/src/components/template/GrammarTermLookup.tsx
  26. 1 1
      dashboard-v6/src/components/template/Note.tsx
  27. 1 1
      dashboard-v6/src/components/template/Para.tsx
  28. 1 1
      dashboard-v6/src/components/template/Qa.tsx
  29. 1 1
      dashboard-v6/src/components/template/Quality.tsx
  30. 1 1
      dashboard-v6/src/components/template/Quote.tsx
  31. 1 1
      dashboard-v6/src/components/template/QuoteLink.tsx
  32. 1 1
      dashboard-v6/src/components/template/Reference.tsx
  33. 1 1
      dashboard-v6/src/components/template/Toggle.tsx
  34. 68 0
      openapi/public/assets/protocol/main.yaml
  35. 11 6
      openapi/public/assets/protocol/resources/auto/v3-discussions-discussion-replies.yaml
  36. 12 6
      openapi/public/assets/protocol/resources/auto/v3-discussions-discussion.yaml
  37. 11 6
      openapi/public/assets/protocol/resources/auto/v3-discussions.yaml
  38. 3 2
      openapi/public/assets/protocol/resources/auto/v3-tipitaka-discussions-channel.yaml
  39. 56 1
      openapi/scripts/generate.php

+ 8 - 0
api-test/cases/07_discussions.php

@@ -160,6 +160,14 @@ test('discussions 一轮:建话题 → 回复 → 关闭后回复 409 → 重
         assert_eq($id, $r['body']['data']['parent_id'] ?? null, '回复 parent_id');
         assert_eq('issue', $r['body']['data']['type'] ?? null, '回复类型跟话题');
 
+        // 正文渲染:挂在句子上的给节点树 body 与纯文本 summary(App\Services\Markup;不再有 html)
+        $rendered = raw('GET', "/v3/discussions/{$replyId}", null, null, $token);
+        assert_eq([['type' => 'text', 'value' => 'api-test 回复']], $rendered['body']['data']['body'] ?? null, '回复 body');
+        assert_eq('api-test 回复', $rendered['body']['data']['summary'] ?? null, '回复 summary');
+        if (array_key_exists('html', $rendered['body']['data'] ?? [])) {
+            fail('回复:不应再有 html 字段');
+        }
+
         // 回复上改话题专属字段(标题、状态、类型)→ 422
         $topicOnly = raw('PATCH', "/v3/discussions/{$replyId}", null, ['title' => 'x'], $token);
         assert_field_error('title', $topicOnly, 'PATCH 回复的 title');

+ 12 - 0
api-test/client/.openapi-generator/FILES

@@ -138,6 +138,10 @@ docs/Model/GetApiV3TipitakaRelatedParagraphsAggregate200Response.md
 docs/Model/GetApiV3TipitakaRelatedParagraphsAggregate200ResponseDataInner.md
 docs/Model/GetApiV3TipitakaRelatedParagraphsAggregateBookName200Response.md
 docs/Model/GetApiV3TipitakaRelatedParagraphsAggregateBookName200ResponseDataInner.md
+docs/Model/MarkupElement.md
+docs/Model/MarkupNode.md
+docs/Model/MarkupTemplate.md
+docs/Model/MarkupText.md
 docs/Model/PaginationMeta.md
 docs/Model/PatchApiV3ChannelsChannelLinksRequest.md
 docs/Model/PatchApiV3ChannelsChannelRequest.md
@@ -333,6 +337,10 @@ lib/Model/GetApiV3TipitakaRelatedParagraphsAggregate200Response.php
 lib/Model/GetApiV3TipitakaRelatedParagraphsAggregate200ResponseDataInner.php
 lib/Model/GetApiV3TipitakaRelatedParagraphsAggregateBookName200Response.php
 lib/Model/GetApiV3TipitakaRelatedParagraphsAggregateBookName200ResponseDataInner.php
+lib/Model/MarkupElement.php
+lib/Model/MarkupNode.php
+lib/Model/MarkupTemplate.php
+lib/Model/MarkupText.php
 lib/Model/ModelInterface.php
 lib/Model/PaginationMeta.php
 lib/Model/PatchApiV3ChannelsChannelLinksRequest.php
@@ -526,6 +534,10 @@ test/Model/GetApiV3TipitakaRelatedParagraphsAggregate200ResponseDataInnerTest.ph
 test/Model/GetApiV3TipitakaRelatedParagraphsAggregate200ResponseTest.php
 test/Model/GetApiV3TipitakaRelatedParagraphsAggregateBookName200ResponseDataInnerTest.php
 test/Model/GetApiV3TipitakaRelatedParagraphsAggregateBookName200ResponseTest.php
+test/Model/MarkupElementTest.php
+test/Model/MarkupNodeTest.php
+test/Model/MarkupTemplateTest.php
+test/Model/MarkupTextTest.php
 test/Model/PaginationMetaTest.php
 test/Model/PatchApiV3ChannelsChannelLinksRequestTest.php
 test/Model/PatchApiV3ChannelsChannelRequestTest.php

+ 17 - 17
api-test/client/lib/Model/GetApiV3Discussions200ResponseDataInner.php

@@ -68,7 +68,7 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
         'title' => 'string',
         'content' => 'string',
         'content_type' => 'string',
-        'html' => 'string',
+        'body' => '\WikipaliApi\Model\MarkupNode[]',
         'summary' => 'string',
         'tpl_id' => 'string',
         'pos_start' => 'int',
@@ -105,7 +105,7 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
         'title' => null,
         'content' => null,
         'content_type' => null,
-        'html' => null,
+        'body' => null,
         'summary' => null,
         'tpl_id' => null,
         'pos_start' => null,
@@ -140,7 +140,7 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
         'title' => true,
         'content' => true,
         'content_type' => false,
-        'html' => false,
+        'body' => false,
         'summary' => false,
         'tpl_id' => true,
         'pos_start' => true,
@@ -255,7 +255,7 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
         'title' => 'title',
         'content' => 'content',
         'content_type' => 'content_type',
-        'html' => 'html',
+        'body' => 'body',
         'summary' => 'summary',
         'tpl_id' => 'tpl_id',
         'pos_start' => 'pos_start',
@@ -290,7 +290,7 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
         'title' => 'setTitle',
         'content' => 'setContent',
         'content_type' => 'setContentType',
-        'html' => 'setHtml',
+        'body' => 'setBody',
         'summary' => 'setSummary',
         'tpl_id' => 'setTplId',
         'pos_start' => 'setPosStart',
@@ -325,7 +325,7 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
         'title' => 'getTitle',
         'content' => 'getContent',
         'content_type' => 'getContentType',
-        'html' => 'getHtml',
+        'body' => 'getBody',
         'summary' => 'getSummary',
         'tpl_id' => 'getTplId',
         'pos_start' => 'getPosStart',
@@ -411,7 +411,7 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
         $this->setIfExists('title', $data ?? [], null);
         $this->setIfExists('content', $data ?? [], null);
         $this->setIfExists('content_type', $data ?? [], null);
-        $this->setIfExists('html', $data ?? [], null);
+        $this->setIfExists('body', $data ?? [], null);
         $this->setIfExists('summary', $data ?? [], null);
         $this->setIfExists('tpl_id', $data ?? [], null);
         $this->setIfExists('pos_start', $data ?? [], null);
@@ -804,28 +804,28 @@ class GetApiV3Discussions200ResponseDataInner implements ModelInterface, ArrayAc
     }
 
     /**
-     * Gets html
+     * Gets body
      *
-     * @return string|null
+     * @return \WikipaliApi\Model\MarkupNode[]|null
      */
-    public function getHtml()
+    public function getBody()
     {
-        return $this->container['html'];
+        return $this->container['body'];
     }
 
     /**
-     * Sets html
+     * Sets body
      *
-     * @param string|null $html 仅在部分查询口径下返回。
+     * @param \WikipaliApi\Model\MarkupNode[]|null $body 仅在部分查询口径下返回。
      *
      * @return self
      */
-    public function setHtml($html)
+    public function setBody($body)
     {
-        if (is_null($html)) {
-            throw new \InvalidArgumentException('non-nullable html cannot be null');
+        if (is_null($body)) {
+            throw new \InvalidArgumentException('non-nullable body cannot be null');
         }
-        $this->container['html'] = $html;
+        $this->container['body'] = $body;
 
         return $this;
     }

+ 552 - 0
api-test/client/lib/Model/MarkupElement.php

@@ -0,0 +1,552 @@
+<?php
+/**
+ * MarkupElement
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * MarkupElement Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class MarkupElement implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'MarkupElement';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'type' => 'string',
+        'tag' => 'string',
+        'attrs' => 'array<string,string>',
+        'children' => '\WikipaliApi\Model\MarkupNode[]'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'type' => null,
+        'tag' => null,
+        'attrs' => null,
+        'children' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'type' => false,
+        'tag' => false,
+        'attrs' => false,
+        'children' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'type' => 'type',
+        'tag' => 'tag',
+        'attrs' => 'attrs',
+        'children' => 'children'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'type' => 'setType',
+        'tag' => 'setTag',
+        'attrs' => 'setAttrs',
+        'children' => 'setChildren'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'type' => 'getType',
+        'tag' => 'getTag',
+        'attrs' => 'getAttrs',
+        'children' => 'getChildren'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const TYPE_EL = 'el';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getTypeAllowableValues()
+    {
+        return [
+            self::TYPE_EL,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('type', $data ?? [], null);
+        $this->setIfExists('tag', $data ?? [], null);
+        $this->setIfExists('attrs', $data ?? [], null);
+        $this->setIfExists('children', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['type'] === null) {
+            $invalidProperties[] = "'type' can't be null";
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!is_null($this->container['type']) && !in_array($this->container['type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'type', must be one of '%s'",
+                $this->container['type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        if ($this->container['tag'] === null) {
+            $invalidProperties[] = "'tag' can't be null";
+        }
+        if ($this->container['children'] === null) {
+            $invalidProperties[] = "'children' can't be null";
+        }
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets type
+     *
+     * @return string
+     */
+    public function getType()
+    {
+        return $this->container['type'];
+    }
+
+    /**
+     * Sets type
+     *
+     * @param string $type type
+     *
+     * @return self
+     */
+    public function setType($type)
+    {
+        if (is_null($type)) {
+            throw new \InvalidArgumentException('non-nullable type cannot be null');
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!in_array($type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'type', must be one of '%s'",
+                    $type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['type'] = $type;
+
+        return $this;
+    }
+
+    /**
+     * Gets tag
+     *
+     * @return string
+     */
+    public function getTag()
+    {
+        return $this->container['tag'];
+    }
+
+    /**
+     * Sets tag
+     *
+     * @param string $tag 白名单内的 HTML 标签名(小写)
+     *
+     * @return self
+     */
+    public function setTag($tag)
+    {
+        if (is_null($tag)) {
+            throw new \InvalidArgumentException('non-nullable tag cannot be null');
+        }
+        $this->container['tag'] = $tag;
+
+        return $this;
+    }
+
+    /**
+     * Gets attrs
+     *
+     * @return array<string,string>|null
+     */
+    public function getAttrs()
+    {
+        return $this->container['attrs'];
+    }
+
+    /**
+     * Sets attrs
+     *
+     * @param array<string,string>|null $attrs attrs
+     *
+     * @return self
+     */
+    public function setAttrs($attrs)
+    {
+        if (is_null($attrs)) {
+            throw new \InvalidArgumentException('non-nullable attrs cannot be null');
+        }
+        $this->container['attrs'] = $attrs;
+
+        return $this;
+    }
+
+    /**
+     * Gets children
+     *
+     * @return \WikipaliApi\Model\MarkupNode[]
+     */
+    public function getChildren()
+    {
+        return $this->container['children'];
+    }
+
+    /**
+     * Sets children
+     *
+     * @param \WikipaliApi\Model\MarkupNode[] $children children
+     *
+     * @return self
+     */
+    public function setChildren($children)
+    {
+        if (is_null($children)) {
+            throw new \InvalidArgumentException('non-nullable children cannot be null');
+        }
+        $this->container['children'] = $children;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 668 - 0
api-test/client/lib/Model/MarkupNode.php

@@ -0,0 +1,668 @@
+<?php
+/**
+ * MarkupNode
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * MarkupNode Class Doc Comment
+ *
+ * @category Class
+ * @description 正文(markdown + 模板)渲染后的节点树,由 App\\Services\\Markup 生成。 三种节点:text 纯文本(前端作为 React 文本节点,自动转义);el HTML 元素(tag 与 attrs 已过白名单); tpl 模板(name 是前端组件名,props 随模板而定,props 里嵌套的内容也是节点数组)。
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class MarkupNode implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'MarkupNode';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'type' => 'string',
+        'value' => 'string',
+        'tag' => 'string',
+        'attrs' => 'array<string,string>',
+        'children' => '\WikipaliApi\Model\MarkupNode[]',
+        'name' => 'string',
+        'props' => 'array<string,mixed>'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'type' => null,
+        'value' => null,
+        'tag' => null,
+        'attrs' => null,
+        'children' => null,
+        'name' => null,
+        'props' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'type' => false,
+        'value' => false,
+        'tag' => false,
+        'attrs' => false,
+        'children' => false,
+        'name' => false,
+        'props' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'type' => 'type',
+        'value' => 'value',
+        'tag' => 'tag',
+        'attrs' => 'attrs',
+        'children' => 'children',
+        'name' => 'name',
+        'props' => 'props'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'type' => 'setType',
+        'value' => 'setValue',
+        'tag' => 'setTag',
+        'attrs' => 'setAttrs',
+        'children' => 'setChildren',
+        'name' => 'setName',
+        'props' => 'setProps'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'type' => 'getType',
+        'value' => 'getValue',
+        'tag' => 'getTag',
+        'attrs' => 'getAttrs',
+        'children' => 'getChildren',
+        'name' => 'getName',
+        'props' => 'getProps'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const TYPE_TEXT = 'text';
+    public const TYPE_EL = 'el';
+    public const TYPE_TPL = 'tpl';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getTypeAllowableValues()
+    {
+        return [
+            self::TYPE_TEXT,
+            self::TYPE_EL,
+            self::TYPE_TPL,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('type', $data ?? [], null);
+        $this->setIfExists('value', $data ?? [], null);
+        $this->setIfExists('tag', $data ?? [], null);
+        $this->setIfExists('attrs', $data ?? [], null);
+        $this->setIfExists('children', $data ?? [], null);
+        $this->setIfExists('name', $data ?? [], null);
+        $this->setIfExists('props', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['type'] === null) {
+            $invalidProperties[] = "'type' can't be null";
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!is_null($this->container['type']) && !in_array($this->container['type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'type', must be one of '%s'",
+                $this->container['type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        if ($this->container['value'] === null) {
+            $invalidProperties[] = "'value' can't be null";
+        }
+        if ($this->container['tag'] === null) {
+            $invalidProperties[] = "'tag' can't be null";
+        }
+        if ($this->container['children'] === null) {
+            $invalidProperties[] = "'children' can't be null";
+        }
+        if ($this->container['name'] === null) {
+            $invalidProperties[] = "'name' can't be null";
+        }
+        if ($this->container['props'] === null) {
+            $invalidProperties[] = "'props' can't be null";
+        }
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets type
+     *
+     * @return string
+     */
+    public function getType()
+    {
+        return $this->container['type'];
+    }
+
+    /**
+     * Sets type
+     *
+     * @param string $type type
+     *
+     * @return self
+     */
+    public function setType($type)
+    {
+        if (is_null($type)) {
+            throw new \InvalidArgumentException('non-nullable type cannot be null');
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!in_array($type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'type', must be one of '%s'",
+                    $type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['type'] = $type;
+
+        return $this;
+    }
+
+    /**
+     * Gets value
+     *
+     * @return string
+     */
+    public function getValue()
+    {
+        return $this->container['value'];
+    }
+
+    /**
+     * Sets value
+     *
+     * @param string $value value
+     *
+     * @return self
+     */
+    public function setValue($value)
+    {
+        if (is_null($value)) {
+            throw new \InvalidArgumentException('non-nullable value cannot be null');
+        }
+        $this->container['value'] = $value;
+
+        return $this;
+    }
+
+    /**
+     * Gets tag
+     *
+     * @return string
+     */
+    public function getTag()
+    {
+        return $this->container['tag'];
+    }
+
+    /**
+     * Sets tag
+     *
+     * @param string $tag 白名单内的 HTML 标签名(小写)
+     *
+     * @return self
+     */
+    public function setTag($tag)
+    {
+        if (is_null($tag)) {
+            throw new \InvalidArgumentException('non-nullable tag cannot be null');
+        }
+        $this->container['tag'] = $tag;
+
+        return $this;
+    }
+
+    /**
+     * Gets attrs
+     *
+     * @return array<string,string>|null
+     */
+    public function getAttrs()
+    {
+        return $this->container['attrs'];
+    }
+
+    /**
+     * Sets attrs
+     *
+     * @param array<string,string>|null $attrs attrs
+     *
+     * @return self
+     */
+    public function setAttrs($attrs)
+    {
+        if (is_null($attrs)) {
+            throw new \InvalidArgumentException('non-nullable attrs cannot be null');
+        }
+        $this->container['attrs'] = $attrs;
+
+        return $this;
+    }
+
+    /**
+     * Gets children
+     *
+     * @return \WikipaliApi\Model\MarkupNode[]
+     */
+    public function getChildren()
+    {
+        return $this->container['children'];
+    }
+
+    /**
+     * Sets children
+     *
+     * @param \WikipaliApi\Model\MarkupNode[] $children children
+     *
+     * @return self
+     */
+    public function setChildren($children)
+    {
+        if (is_null($children)) {
+            throw new \InvalidArgumentException('non-nullable children cannot be null');
+        }
+        $this->container['children'] = $children;
+
+        return $this;
+    }
+
+    /**
+     * Gets name
+     *
+     * @return string
+     */
+    public function getName()
+    {
+        return $this->container['name'];
+    }
+
+    /**
+     * Sets name
+     *
+     * @param string $name 前端组件名:term、note、sentread、sentedit、quote、quote-link、mermaid…
+     *
+     * @return self
+     */
+    public function setName($name)
+    {
+        if (is_null($name)) {
+            throw new \InvalidArgumentException('non-nullable name cannot be null');
+        }
+        $this->container['name'] = $name;
+
+        return $this;
+    }
+
+    /**
+     * Gets props
+     *
+     * @return array<string,mixed>
+     */
+    public function getProps()
+    {
+        return $this->container['props'];
+    }
+
+    /**
+     * Sets props
+     *
+     * @param array<string,mixed> $props props
+     *
+     * @return self
+     */
+    public function setProps($props)
+    {
+        if (is_null($props)) {
+            throw new \InvalidArgumentException('non-nullable props cannot be null');
+        }
+        $this->container['props'] = $props;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 555 - 0
api-test/client/lib/Model/MarkupTemplate.php

@@ -0,0 +1,555 @@
+<?php
+/**
+ * MarkupTemplate
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * MarkupTemplate Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class MarkupTemplate implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'MarkupTemplate';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'type' => 'string',
+        'name' => 'string',
+        'props' => 'array<string,mixed>',
+        'children' => '\WikipaliApi\Model\MarkupNode[]'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'type' => null,
+        'name' => null,
+        'props' => null,
+        'children' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'type' => false,
+        'name' => false,
+        'props' => false,
+        'children' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'type' => 'type',
+        'name' => 'name',
+        'props' => 'props',
+        'children' => 'children'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'type' => 'setType',
+        'name' => 'setName',
+        'props' => 'setProps',
+        'children' => 'setChildren'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'type' => 'getType',
+        'name' => 'getName',
+        'props' => 'getProps',
+        'children' => 'getChildren'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const TYPE_TPL = 'tpl';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getTypeAllowableValues()
+    {
+        return [
+            self::TYPE_TPL,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('type', $data ?? [], null);
+        $this->setIfExists('name', $data ?? [], null);
+        $this->setIfExists('props', $data ?? [], null);
+        $this->setIfExists('children', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['type'] === null) {
+            $invalidProperties[] = "'type' can't be null";
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!is_null($this->container['type']) && !in_array($this->container['type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'type', must be one of '%s'",
+                $this->container['type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        if ($this->container['name'] === null) {
+            $invalidProperties[] = "'name' can't be null";
+        }
+        if ($this->container['props'] === null) {
+            $invalidProperties[] = "'props' can't be null";
+        }
+        if ($this->container['children'] === null) {
+            $invalidProperties[] = "'children' can't be null";
+        }
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets type
+     *
+     * @return string
+     */
+    public function getType()
+    {
+        return $this->container['type'];
+    }
+
+    /**
+     * Sets type
+     *
+     * @param string $type type
+     *
+     * @return self
+     */
+    public function setType($type)
+    {
+        if (is_null($type)) {
+            throw new \InvalidArgumentException('non-nullable type cannot be null');
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!in_array($type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'type', must be one of '%s'",
+                    $type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['type'] = $type;
+
+        return $this;
+    }
+
+    /**
+     * Gets name
+     *
+     * @return string
+     */
+    public function getName()
+    {
+        return $this->container['name'];
+    }
+
+    /**
+     * Sets name
+     *
+     * @param string $name 前端组件名:term、note、sentread、sentedit、quote、quote-link、mermaid…
+     *
+     * @return self
+     */
+    public function setName($name)
+    {
+        if (is_null($name)) {
+            throw new \InvalidArgumentException('non-nullable name cannot be null');
+        }
+        $this->container['name'] = $name;
+
+        return $this;
+    }
+
+    /**
+     * Gets props
+     *
+     * @return array<string,mixed>
+     */
+    public function getProps()
+    {
+        return $this->container['props'];
+    }
+
+    /**
+     * Sets props
+     *
+     * @param array<string,mixed> $props props
+     *
+     * @return self
+     */
+    public function setProps($props)
+    {
+        if (is_null($props)) {
+            throw new \InvalidArgumentException('non-nullable props cannot be null');
+        }
+        $this->container['props'] = $props;
+
+        return $this;
+    }
+
+    /**
+     * Gets children
+     *
+     * @return \WikipaliApi\Model\MarkupNode[]
+     */
+    public function getChildren()
+    {
+        return $this->container['children'];
+    }
+
+    /**
+     * Sets children
+     *
+     * @param \WikipaliApi\Model\MarkupNode[] $children children
+     *
+     * @return self
+     */
+    public function setChildren($children)
+    {
+        if (is_null($children)) {
+            throw new \InvalidArgumentException('non-nullable children cannot be null');
+        }
+        $this->container['children'] = $children;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 481 - 0
api-test/client/lib/Model/MarkupText.php

@@ -0,0 +1,481 @@
+<?php
+/**
+ * MarkupText
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * MarkupText Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class MarkupText implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'MarkupText';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'type' => 'string',
+        'value' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'type' => null,
+        'value' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'type' => false,
+        'value' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'type' => 'type',
+        'value' => 'value'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'type' => 'setType',
+        'value' => 'setValue'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'type' => 'getType',
+        'value' => 'getValue'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const TYPE_TEXT = 'text';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getTypeAllowableValues()
+    {
+        return [
+            self::TYPE_TEXT,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('type', $data ?? [], null);
+        $this->setIfExists('value', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['type'] === null) {
+            $invalidProperties[] = "'type' can't be null";
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!is_null($this->container['type']) && !in_array($this->container['type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'type', must be one of '%s'",
+                $this->container['type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        if ($this->container['value'] === null) {
+            $invalidProperties[] = "'value' can't be null";
+        }
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets type
+     *
+     * @return string
+     */
+    public function getType()
+    {
+        return $this->container['type'];
+    }
+
+    /**
+     * Sets type
+     *
+     * @param string $type type
+     *
+     * @return self
+     */
+    public function setType($type)
+    {
+        if (is_null($type)) {
+            throw new \InvalidArgumentException('non-nullable type cannot be null');
+        }
+        $allowedValues = $this->getTypeAllowableValues();
+        if (!in_array($type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'type', must be one of '%s'",
+                    $type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['type'] = $type;
+
+        return $this;
+    }
+
+    /**
+     * Gets value
+     *
+     * @return string
+     */
+    public function getValue()
+    {
+        return $this->container['value'];
+    }
+
+    /**
+     * Sets value
+     *
+     * @param string $value value
+     *
+     * @return self
+     */
+    public function setValue($value)
+    {
+        if (is_null($value)) {
+            throw new \InvalidArgumentException('non-nullable value cannot be null');
+        }
+        $this->container['value'] = $value;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 1 - 1
api-v13/app/Http/Requests/V3/StoreDiscussionRequest.php

@@ -9,7 +9,7 @@ use Illuminate\Validation\Rule;
 /**
  * `POST /v3/discussions` 的入参:发起话题,或新建一条批注。
  *
- * 不收 content_type:v3 只写 markdown(v6 已没有 html 编辑器)。
+ * 不收 content_type:v3 一律按 markdown-e2 写(存 content_type_v2,见 Discussion::markWrittenByV3())。
  * severity 的取值随 type 而定,见 {@see Discussion::SEVERITIES};不收 severity 的类型传了就 422。
  *
  * 批注(note / commentary)与评论线程的规则不同:只能挂在句子上、标题可省、正文必填,

+ 13 - 3
api-v13/app/Http/Resources/V3/DiscussionResource.php

@@ -4,6 +4,8 @@ namespace App\Http\Resources\V3;
 
 use App\Http\Resources\Concerns\ResolvesActor;
 use App\Models\Discussion;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\Render\TreeRenderer;
 use App\Services\V3\DiscussionService;
 use Illuminate\Http\Request;
 
@@ -26,6 +28,14 @@ use Illuminate\Http\Request;
  * `sentence` 只在按经文范围列出时有(`GET /v3/tipitaka-discussions/{channel}`):所在句子的坐标,
  * 由查询顺带取出(`sentence_*` 属性),本类不另查。
  *
+ * `body` 是渲染后的正文({@see MarkupService} 的节点树,节点形状见
+ * {@see TreeRenderer}),`summary` 是纯文本摘要;两者只在挂在句子上、
+ * 未删除、有正文时给(正文里的模板要用句子所在的 channel 解析)。取代了 v3 早期的 `html`
+ * (v2 MdRender 的 MdTpl HTML 字符串)。
+ *
+ * `content_type` 是正文实际的方言:v3 写入的是 `markdown-e2`(存在 content_type_v2 列),
+ * v2 写入的是原 content_type(markdown / text / html),见 {@see Discussion::effectiveContentType()}。
+ *
  * 字段名改了两处(v2 → v3):res_type / res_id → target_type / target_id,
  * parent → parent_id;children_count → reply_count(只有话题有)。
  *
@@ -49,7 +59,7 @@ class DiscussionResource extends BaseResource
      *     title: string|null,
      *     content: string|null,
      *     content_type: string,
-     *     html?: string,
+     *     body?: list<MarkupNode>,
      *     summary?: string,
      *     tpl_id: string|null,
      *     pos_start: int|null,
@@ -82,8 +92,8 @@ class DiscussionResource extends BaseResource
             'status' => $this->status,
             'title' => $tombstone ? null : $this->title,
             'content' => $tombstone ? null : $this->content,
-            'content_type' => $this->content_type,
-            'html' => $this->when($this->rendered !== null, fn () => $this->rendered['html']),
+            'content_type' => $this->effectiveContentType(),
+            'body' => $this->when($this->rendered !== null, fn () => $this->rendered['body']),
             'summary' => $this->when($this->rendered !== null, fn () => $this->rendered['summary']),
             'tpl_id' => $this->tpl_id,
             'pos_start' => $this->pos_start,

+ 28 - 1
api-v13/app/Models/Discussion.php

@@ -2,6 +2,7 @@
 
 namespace App\Models;
 
+use App\Services\Markup\MarkupService;
 use App\Services\PaliContentService;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
@@ -49,6 +50,7 @@ class Discussion extends Model
         'title',
         'content',
         'content_type',
+        'content_type_v2',
         'parent',
         'editor_uid',
         'pos_start',
@@ -145,10 +147,35 @@ class Discussion extends Model
      * 正文渲染结果(只有挂在句子上的才有,需要句子所在的 channel 才能渲染模板),
      * 同样由 Service 算好后挂上。
      *
-     * @var array{html: string, summary: string}|null
+     * body 是 {@see MarkupService} 的节点树,summary 是纯文本。
+     *
+     * @var array{body: list<array<string, mixed>>, summary: string}|null
      */
     public ?array $rendered = null;
 
+    /** v3 写入的正文方言,存在 content_type_v2(content_type 的 CHECK 约束存不下它) */
+    public const CONTENT_TYPE_V3 = 'markdown-e2';
+
+    /**
+     * 正文实际的方言:content_type_v2 优先(v3 写入的),为空取 content_type(v2 写入的)。
+     * v3 读取、渲染都用它;v2 只认 content_type。
+     *
+     * TODO v2 下线后:content_type 废弃,存量空的 content_type_v2 回填为 markdown,这里只读 content_type_v2。
+     */
+    public function effectiveContentType(): string
+    {
+        return $this->content_type_v2 ?: ($this->content_type ?: 'markdown');
+    }
+
+    /**
+     * 标记这条正文是 v3 写的:content_type_v2 = markdown-e2,content_type 仍填 markdown 给 v2 / v4 读。
+     */
+    public function markWrittenByV3(): void
+    {
+        $this->content_type = 'markdown';
+        $this->content_type_v2 = self::CONTENT_TYPE_V3;
+    }
+
     /**
      * 编辑者(人类用户)。editor_uid 对 user_infos.userid。
      */

+ 29 - 8
api-v13/app/Services/V3/DiscussionService.php

@@ -3,7 +3,6 @@
 namespace App\Services\V3;
 
 use App\Exceptions\BusinessException;
-use App\Http\Api\MdRender;
 use App\Http\Api\Mq;
 use App\Http\Api\ShareApi;
 use App\Http\Resources\DiscussionResource as MqDiscussionPayload;
@@ -16,6 +15,9 @@ use App\Models\Sentence;
 use App\Models\Task;
 use App\Models\Wbw;
 use App\Models\WbwBlock;
+use App\Services\Markup\Format;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\RenderOptions;
 use App\Services\UserService;
 use Illuminate\Contracts\Pagination\LengthAwarePaginator;
 use Illuminate\Database\Eloquent\Builder;
@@ -89,6 +91,7 @@ class DiscussionService
         private readonly AgentGrantService $grants,
         private readonly TipitakaReadingService $reading,
         private readonly ChannelAbilityService $channels,
+        private readonly MarkupService $markup,
     ) {}
 
     /**
@@ -366,7 +369,7 @@ class DiscussionService
         $topic->type = $type;
         $topic->title = $data['title'] ?? null;
         $topic->content = $data['content'] ?? null;
-        $topic->content_type = 'markdown';
+        $topic->markWrittenByV3();
         $topic->severity = $data['severity'] ?? null;
         $topic->tpl_id = $data['tpl_id'] ?? null;
         $topic->fill(array_intersect_key($data, array_flip(self::ANCHOR_FIELDS)));
@@ -403,7 +406,7 @@ class DiscussionService
             $assessment->type = Discussion::TYPE_ASSESSMENT;
             $assessment->title = $data['title'] ?? null;
             $assessment->content = $data['content'] ?? null;
-            $assessment->content_type = 'markdown';
+            $assessment->markWrittenByV3();
             $assessment->severity = $data['severity'];
             $assessment->score = (int) $data['score'];
             $assessment->tpl_id = $data['tpl_id'] ?? null;
@@ -445,7 +448,7 @@ class DiscussionService
             $reply->type = $topic->type;
             $reply->parent = $topic->id;
             $reply->content = $data['content'];
-            $reply->content_type = 'markdown';
+            $reply->markWrittenByV3();
             $reply->editor_uid = $userUid;
             $reply->co_editor_uid = $actor['co_editor'];
             $reply->save();
@@ -527,6 +530,10 @@ class DiscussionService
             if ($authored !== []) {
                 $discussion->co_editor_uid = $actor['co_editor'];
             }
+            // 经 v3 改过正文,就按 v3 的方言存(旧正文里的反引号从此按代码解析,渲染差异不考虑)
+            if (array_key_exists('content', $authored)) {
+                $discussion->markWrittenByV3();
+            }
             foreach (['status', 'type', 'severity'] as $field) {
                 if (array_key_exists($field, $data)) {
                     $discussion->{$field} = $data[$field];
@@ -954,16 +961,30 @@ class DiscussionService
             ? collect()
             : Sentence::whereIn('uid', $sentenceIds)->pluck('channel_uid', 'uid');
 
-        foreach ($items as $item) {
+        $sources = [];
+        foreach ($items as $key => $item) {
             $item->abilities = $this->abilities($item, $viewerUid);
             $channel = $item->res_type === 'sentence' ? ($channels[$item->res_id] ?? null) : null;
             if ($channel && ! $item->trashed() && $item->content) {
-                $item->rendered = [
-                    'html' => MdRender::render($item->content, [$channel], null, 'read'),
-                    'summary' => MdRender::render($item->content, [$channel], null, 'read', 'translation', 'markdown', 'text'),
+                $sources[$key] = [
+                    'source' => $item->content,
+                    'channels' => [$channel],
+                    'contentType' => $item->effectiveContentType(),
                 ];
             }
         }
+        if ($sources === []) {
+            return;
+        }
+
+        // 整页一起渲染:正文里的术语、句子模板合在一起批量查
+        $rendered = $this->markup->renderManyAs($sources, new RenderOptions, [Format::Tree, Format::Text]);
+        foreach (array_keys($sources) as $key) {
+            $items[$key]->rendered = [
+                'body' => $rendered[Format::Tree->value][$key],
+                'summary' => $rendered[Format::Text->value][$key],
+            ];
+        }
     }
 
     /**

+ 32 - 0
api-v13/database/migrations/2026_11_17_070353_add_content_type_v2_to_discussions.php

@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * discussions 加 content_type_v2:v3 写入的正文方言(`markdown-e2`)。
+ *
+ * 原 content_type 是带 CHECK 约束的枚举(markdown / text / html),存不下 markdown-e2;
+ * 改约束等于改列类型(铁律 4),所以另加一列。v3 写入时这一列存 markdown-e2、content_type 仍填 markdown
+ * (v2 / v4 照旧读 content_type);v3 读取时这一列优先,为空取 content_type。
+ *
+ * v2 下线后 content_type 废弃,只认这一列(届时把存量的空值回填为 markdown,再删 content_type)。
+ */
+return new class extends Migration
+{
+    public function up(): void
+    {
+        Schema::table('discussions', function (Blueprint $table) {
+            $table->string('content_type_v2', 16)->nullable()
+                ->comment('v3 写入的正文方言(markdown-e2);为空时以 content_type 为准。v2 不读这一列');
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::table('discussions', function (Blueprint $table) {
+            $table->dropColumn('content_type_v2');
+        });
+    }
+};

+ 129 - 0
api-v13/tests/Feature/DiscussionBodyV3Test.php

@@ -0,0 +1,129 @@
+<?php
+
+use App\Models\DhammaTerm;
+use App\Models\Discussion;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * discussions 的正文渲染:`body` 是 App\Services\Markup 的节点树,`summary` 是纯文本。
+ * 只有挂在句子上的才渲染(模板要用句子所在 channel 解析)。
+ */
+function makeBodyTopic(string $owner, string $channel, string $content, array $attrs = []): Discussion
+{
+    $sentence = makeSentence($channel, 1, 1, random_int(1, 100000), 'sentence text');
+
+    return Discussion::forceCreate(array_merge([
+        'res_type' => 'sentence',
+        'res_id' => $sentence->uid,
+        'type' => 'discussion',
+        'title' => 'topic',
+        'content' => $content,
+        'editor_uid' => $owner,
+    ], $attrs));
+}
+
+function makeBodyTerm(string $channel, string $owner, string $word, string $meaning): void
+{
+    (new DhammaTerm)->forceFill([
+        'id' => random_int(1, PHP_INT_MAX), 'guid' => (string) Str::uuid(), 'word' => $word, 'word_en' => $word,
+        'meaning' => $meaning, 'channal' => $channel, 'owner' => $owner, 'language' => 'zh-Hans',
+        'editor_id' => 0, 'create_time' => time() * 1000, 'modify_time' => time() * 1000,
+    ])->save();
+}
+
+it('renders the body as a node tree and the summary as text', function () {
+    $owner = makeStudio('body-owner');
+    $channel = makeChannel($owner);
+    makeBodyTerm($channel, $owner, 'dhamma', '法');
+    $topic = makeBodyTopic($owner, $channel, '关于[[dhamma]]{{n|脚注}}的讨论');
+
+    $data = $this->getJson("/api/v3/discussions/{$topic->id}", authHeader($owner))->assertOk()->json('data');
+
+    expect($data)->not->toHaveKey('html');
+    expect($data['body'][0])->toBe(['type' => 'text', 'value' => '关于']);
+    expect($data['body'][1])->toMatchArray(['type' => 'tpl', 'name' => 'term']);
+    expect($data['body'][1]['props'])->toMatchArray(['word' => 'dhamma', 'meaning' => '法', 'parentChannelId' => $channel]);
+    expect($data['body'][2])->toMatchArray(['type' => 'tpl', 'name' => 'note', 'children' => [['type' => 'text', 'value' => '脚注']]]);
+    expect($data['summary'])->toBe('关于法的讨论');
+});
+
+it('does not render discussions that are not on a sentence', function () {
+    $owner = makeStudio('body-owner2');
+    $topic = Discussion::forceCreate([
+        'res_type' => 'article', 'res_id' => (string) Str::uuid(), 'type' => 'discussion',
+        'title' => 't', 'content' => '[[dhamma]]', 'editor_uid' => $owner,
+    ]);
+
+    $data = $this->getJson("/api/v3/discussions/{$topic->id}", authHeader($owner))->assertOk()->json('data');
+    expect($data)->not->toHaveKey('body')->not->toHaveKey('summary');
+});
+
+it('writes v3 content as markdown-e2 and renders backticks as code', function () {
+    $owner = makeStudio('body-owner-e2');
+    $channel = makeChannel($owner);
+    $sentence = makeSentence($channel, 1, 1, 7, 'sentence text');
+
+    $data = $this->postJson('/api/v3/discussions', [
+        'target_type' => 'sentence', 'target_id' => $sentence->uid, 'type' => 'discussion',
+        'title' => 't', 'content' => '用 `{{n|x}}` 写脚注', 'notify' => false,
+    ], authHeader($owner))->assertCreated()->json('data');
+
+    expect($data['content_type'])->toBe('markdown-e2');
+    expect($data['body'][1])->toMatchArray(['type' => 'el', 'tag' => 'code', 'children' => [['type' => 'text', 'value' => '{{n|x}}']]]);
+    // v2 / v4 照旧读 content_type
+    $row = Discussion::find($data['id']);
+    expect($row->content_type)->toBe('markdown')->and($row->content_type_v2)->toBe('markdown-e2');
+
+    $reply = $this->postJson("/api/v3/discussions/{$data['id']}/replies", ['content' => '`code`', 'notify' => false], authHeader($owner))
+        ->assertCreated()->json('data');
+    expect($reply['content_type'])->toBe('markdown-e2');
+    expect($reply['body'][0]['tag'])->toBe('code');
+});
+
+it('keeps v2 rows in the legacy dialect until their content is edited through v3', function () {
+    $owner = makeStudio('body-owner-legacy');
+    $channel = makeChannel($owner);
+    $topic = makeBodyTopic($owner, $channel, '旧`脚注`写法');
+
+    $data = $this->getJson("/api/v3/discussions/{$topic->id}", authHeader($owner))->assertOk()->json('data');
+    expect($data['content_type'])->toBe('markdown');
+    expect($data['body'][1])->toMatchArray(['type' => 'tpl', 'name' => 'note']);
+
+    // 只改状态不动正文:方言不变
+    $this->patchJson("/api/v3/discussions/{$topic->id}", ['status' => 'close'], authHeader($owner))->assertOk()
+        ->assertJsonPath('data.content_type', 'markdown');
+
+    // 经 v3 改了正文:按 E2 存
+    $patched = $this->patchJson("/api/v3/discussions/{$topic->id}", ['content' => '新`代码`'], authHeader($owner))
+        ->assertOk()->json('data');
+    expect($patched['content_type'])->toBe('markdown-e2');
+    expect($patched['body'][1]['tag'])->toBe('code');
+    expect($topic->fresh()->content_type)->toBe('markdown');
+});
+
+it('looks up the terms of a whole page of discussions together', function () {
+    $owner = makeStudio('body-owner4');
+    $channel = makeChannel($owner);
+    $sentence = makeSentence($channel, 1, 1, 1, 'sentence text');
+    foreach (range(1, 10) as $i) {
+        makeBodyTerm($channel, $owner, "w{$i}", "义{$i}");
+        Discussion::forceCreate([
+            'res_type' => 'sentence', 'res_id' => $sentence->uid, 'type' => 'discussion',
+            'title' => "t{$i}", 'content' => "[[w{$i}]]", 'editor_uid' => $owner,
+        ]);
+    }
+
+    DB::enableQueryLog();
+    $data = $this->getJson("/api/v3/discussions?target_type=sentence&target_id={$sentence->uid}", authHeader($owner))
+        ->assertOk()->json('data');
+    $termQueries = collect(DB::getQueryLog())->filter(fn ($q) => str_contains($q['query'], 'from "dhamma_terms"'))->count();
+    DB::disableQueryLog();
+
+    expect(collect($data)->pluck('summary')->sort()->values()->all())->toContain('义1', '义10');
+    // 本 channel 的术语、studio 术语各一次(没有社区术语 channel 时不查社区)
+    expect($termQueries)->toBeLessThanOrEqual(3);
+});

+ 2 - 1
api-v13/tests/Feature/DiscussionV3Test.php

@@ -233,7 +233,8 @@ it('creates a topic', function () {
         ->assertJsonPath('data.severity', 'error')
         ->assertJsonPath('data.parent_id', null)
         ->assertJsonPath('data.reply_count', 0)
-        ->assertJsonPath('data.content_type', 'markdown');
+        // v3 写入一律是 markdown-e2(存 content_type_v2;content_type 列仍是 markdown)
+        ->assertJsonPath('data.content_type', 'markdown-e2');
 
     expect(Discussion::where('editor_uid', $user)->value('res_id'))->toBe($target);
 });

+ 53 - 1
dashboard-test/src/tests/discussion.spec.ts

@@ -126,7 +126,10 @@ test.describe('话题页 /workspace/discussion/topic/:id', () => {
       await page.getByRole('button', { name: /提 *交/ }).click();
       const res = await posted;
       expect(res.status()).toBe(201);
-      uiReplyId = (await res.json()).data.id;
+      const replied = (await res.json()).data;
+      uiReplyId = replied.id;
+      // v6 经 v3 写入,正文一律是 markdown-e2(反引号是代码,与编辑器预览一致)
+      expect(replied.content_type).toBe('markdown-e2');
       await expect(page.locator(`#answer-${uiReplyId}`)).toContainText('页面上发的回复');
       await shot(page, '02-replied');
       log.dump('2. 发一条回复');
@@ -259,3 +262,52 @@ test.describe('v4 漏搬的讨论入口', () => {
     expect(loaded).toBe('function');
   });
 });
+
+test.describe('话题正文:后端节点树(body)渲染成组件', () => {
+  const stamp = `e2e-tmp-${Date.now()}-body`;
+  let topicId = '';
+
+  test.beforeAll(async ({ request }) => {
+    const topic = await call(request, 'POST', '/discussions', {
+      target_type: 'sentence',
+      target_id: SENTENCE,
+      type: 'discussion',
+      title: stamp,
+      content: '正文有 **粗体**、[[dhamma]] 与脚注{{n|脚注正文 *斜体*|trigger=①}}。\n\n- 列表一\n- 列表二',
+      notify: false,
+    });
+    expect(topic.status, JSON.stringify(topic.body)).toBe(201);
+    topicId = topic.body.data.id;
+    expect(topic.body.data.body, '挂在句子上的话题应带 body').toBeTruthy();
+    expect(topic.body.data).not.toHaveProperty('html');
+  });
+
+  test.afterAll(async ({ request }) => {
+    if (topicId) await call(request, 'DELETE', `/discussions/${topicId}`);
+  });
+
+  test('markdown、术语、脚注都渲染成元素 / 组件,没有「未定义模版」', async ({ page }) => {
+    const log = collect(page);
+    await page.goto(`workspace/discussion/topic/${topicId}`, { waitUntil: 'networkidle' });
+    const topic = page.locator(`#answer-${topicId}`);
+
+    await expect(topic.locator('strong', { hasText: '粗体' })).toBeVisible();
+    await expect(topic.locator('ul > li')).toHaveCount(2);
+    await expect(topic).toContainText('dhamma');
+    await expect(topic).not.toContainText('未定义模版');
+    await expect(topic).not.toContainText('{{');
+
+    // 脚注:角标 ①,悬停弹出正文(正文里的 markdown 也渲染了)
+    const trigger = topic.getByText('①', { exact: true });
+    await expect(trigger).toBeVisible();
+    await trigger.hover();
+    const popover = page.locator('.ant-popover:not(.ant-popover-hidden)');
+    await expect(popover).toContainText('脚注正文');
+    await expect(popover.locator('em', { hasText: '斜体' })).toBeVisible();
+    await shot(page, '10-body-rendered');
+
+    const problems = discussionProblems(log.all);
+    log.dump('正文节点树');
+    expect(problems).toEqual([]);
+  });
+});

+ 4 - 3
dashboard-v6/src/api/discussion.ts

@@ -6,7 +6,7 @@
 import type { IUser } from "./Auth";
 import { api, unwrap, unwrapQuiet } from "./client";
 import { ApiError } from "./error";
-import type { paths } from "./schema";
+import type { components, paths } from "./schema";
 
 /**
  * 通用的资源类型:transfer、webhook、右侧面板等也在用,比讨论能挂的对象多。
@@ -129,7 +129,8 @@ export interface IComment {
   parent?: string | null;
   title?: string | null;
   content?: string | null;
-  html?: string;
+  /** 渲染后的正文节点树(只有挂在句子上的有);没有时按 content 渲染 markdown */
+  body?: components["schemas"]["MarkupNode"][];
   summary?: string;
   status?: TDiscussionStatus;
   childrenCount?: number;
@@ -169,7 +170,7 @@ export const toIComment = (value: DiscussionData): IComment => ({
   parent: value.parent_id,
   title: value.title,
   content: value.content,
-  html: value.html,
+  body: value.body,
   summary: value.summary,
   status: value.status as TDiscussionStatus,
   childrenCount: value.reply_count,

+ 41 - 10
dashboard-v6/src/api/schema.d.ts

@@ -9343,6 +9343,37 @@ export interface paths {
 export type webhooks = Record<string, never>;
 export interface components {
     schemas: {
+        /**
+         * @description 正文(markdown + 模板)渲染后的节点树,由 App\Services\Markup 生成。
+         *     三种节点:text 纯文本(前端作为 React 文本节点,自动转义);el HTML 元素(tag 与 attrs 已过白名单);
+         *     tpl 模板(name 是前端组件名,props 随模板而定,props 里嵌套的内容也是节点数组)。
+         */
+        MarkupNode: components["schemas"]["MarkupText"] | components["schemas"]["MarkupElement"] | components["schemas"]["MarkupTemplate"];
+        MarkupText: {
+            /** @enum {string} */
+            type: "text";
+            value: string;
+        };
+        MarkupElement: {
+            /** @enum {string} */
+            type: "el";
+            /** @description 白名单内的 HTML 标签名(小写) */
+            tag: string;
+            attrs?: {
+                [key: string]: string;
+            };
+            children: components["schemas"]["MarkupNode"][];
+        };
+        MarkupTemplate: {
+            /** @enum {string} */
+            type: "tpl";
+            /** @description 前端组件名:term、note、sentread、sentedit、quote、quote-link、mermaid… */
+            name: string;
+            props: {
+                [key: string]: unknown;
+            };
+            children: components["schemas"]["MarkupNode"][];
+        };
         /**
          * @description RFC 9457 Problem Details,v3 端点的错误响应体。
          *     由 bootstrap/app.php 的异常处理器统一渲染,控制器不自己拼。
@@ -36939,7 +36970,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37070,7 +37101,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37139,7 +37170,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37313,7 +37344,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37397,7 +37428,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37530,7 +37561,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37629,7 +37660,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37726,7 +37757,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -37795,7 +37826,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;
@@ -40313,7 +40344,7 @@ export interface operations {
                             content?: string | null;
                             content_type?: string;
                             /** @description 仅在部分查询口径下返回。 */
-                            html?: string;
+                            body?: components["schemas"]["MarkupNode"][];
                             /** @description 仅在部分查询口径下返回。 */
                             summary?: string;
                             tpl_id?: string | null;

+ 0 - 1
dashboard-v6/src/components/discussion/DiscussionListCard.tsx

@@ -234,7 +234,6 @@ const DiscussionListCardWidget = ({
                     title: item.title,
                     parent: null,
                     content: item.content,
-                    html: item.html,
                     summary: item.summary ? item.summary : item._summary,
                     status: "active",
                     childrenCount: 0,

+ 3 - 3
dashboard-v6/src/components/discussion/DiscussionShow.tsx

@@ -32,7 +32,7 @@ import {
   type TDiscussionType,
 } from "../../api/discussion";
 import { refreshDiscussionBadge } from "./utils";
-import MdView from "../general/MdView";
+import MarkupView from "../markup/MarkupView";
 import { SeverityTag } from "./SeverityTag";
 
 const { Text } = Typography;
@@ -340,8 +340,8 @@ const DiscussionShowWidget = ({
       style={{ width: "100%" }}
     >
       <div>
-        {data.html ? (
-          <MdView html={data.html} />
+        {data.body ? (
+          <MarkupView nodes={data.body} />
         ) : (
           <Marked text={data.content ?? undefined} />
         )}

+ 87 - 0
dashboard-v6/src/components/markup/MarkupTemplate.tsx

@@ -0,0 +1,87 @@
+import { Tag, Typography } from "antd";
+import type { ReactNode } from "react";
+
+import Mermaid from "../general/Mermaid";
+import { ArticleCtl } from "../template/Article";
+import { GrammarTermLookupCtl } from "../template/GrammarTermLookup";
+import { NissayaCtl } from "../template/Nissaya";
+import { NoteCtl } from "../template/Note";
+import { ParaCtl } from "../template/Para";
+import { QaCtl } from "../template/Qa";
+import { QualityCtl } from "../template/Quality";
+import { QuoteCtl } from "../template/Quote";
+import { QuoteLinkCtl } from "../template/QuoteLink";
+import { ReferenceCtl } from "../template/Reference";
+import { ToggleCtl } from "../template/Toggle";
+import { VideoCtl } from "../template/Video";
+import { TermCtl } from "../term/TermCtl";
+import SentenceView, { type ISentenceViewProps } from "./SentenceView";
+import type { MarkupProps, MarkupTemplateNode } from "./types";
+
+const { Text } = Typography;
+
+/** 模板的 props 由各组件自己约定,这里按组件的入参类型取 */
+type PropsOf<C> = C extends (props: infer P) => ReactNode ? P : never;
+const as = <C,>(props: MarkupProps) => props as unknown as PropsOf<C>;
+
+type TemplateRenderer = (
+  props: MarkupProps,
+  children: ReactNode[]
+) => ReactNode;
+
+/**
+ * 模板名(后端 Template 的 component)→ 组件。复用 components/template 里各模板的内部组件;
+ * 它们原来经 MdTpl(base64 props)调用,这里直接传对象。
+ */
+const TEMPLATES: Record<string, TemplateRenderer> = {
+  term: (p) => <TermCtl {...as<typeof TermCtl>(p)} />,
+  note: (p, children) => (
+    <NoteCtl trigger={p.trigger as string | undefined}>{children}</NoteCtl>
+  ),
+  sentread: (p) => <SentenceView {...(p as unknown as ISentenceViewProps)} />,
+  // 编辑模式的句子编辑器要另一套数据(editor / studio / suggestionCount…),尚未迁到新渲染;先只读显示
+  sentedit: (p) => <SentenceView {...(p as unknown as ISentenceViewProps)} />,
+  quote: (p) => <QuoteCtl {...as<typeof QuoteCtl>(p)} />,
+  "quote-link": (p) => <QuoteLinkCtl {...as<typeof QuoteLinkCtl>(p)} />,
+  nissaya: (p) => <NissayaCtl {...as<typeof NissayaCtl>(p)} />,
+  mermaid: (p) => <Mermaid text={p.text as string | undefined} />,
+  qa: (p) => <QaCtl {...as<typeof QaCtl>(p)} />,
+  video: (p) => <VideoCtl {...as<typeof VideoCtl>(p)} />,
+  grammar: (p) => (
+    <GrammarTermLookupCtl {...as<typeof GrammarTermLookupCtl>(p)} />
+  ),
+  reference: (p) => <ReferenceCtl {...as<typeof ReferenceCtl>(p)} />,
+  para: (p) => <ParaCtl {...as<typeof ParaCtl>(p)} />,
+  quality: (p) => <QualityCtl {...as<typeof QualityCtl>(p)} />,
+  article: (p) => <ArticleCtl {...as<typeof ArticleCtl>(p)} />,
+  category: (p) => <Tag>{p.name as string}</Tag>,
+  toggle: (_, children) => <ToggleCtl>{children}</ToggleCtl>,
+  // 用户自定义模板:正文已由后端渲染成 children
+  tpl: (_, children) => <>{children}</>,
+};
+
+interface IWidget {
+  node: MarkupTemplateNode;
+  /** 已渲染的 children 节点 */
+  children: ReactNode[];
+}
+
+/**
+ * 一个模板节点。没有对应组件的(exercise、dict-pref、ai 等 v6 还没有界面的,或后端不认识的)
+ * 显示后端给的源码 / 子节点,不吞内容。
+ */
+const MarkupTemplate = ({ node, children }: IWidget) => {
+  const render = TEMPLATES[node.name];
+  if (render) {
+    return <>{render(node.props, children)}</>;
+  }
+  if (children.length > 0) {
+    return <>{children}</>;
+  }
+  const source = node.props.source;
+  return typeof source === "string" ? (
+    <Text type="secondary">{source}</Text>
+  ) : null;
+};
+
+export default MarkupTemplate;

+ 30 - 0
dashboard-v6/src/components/markup/MarkupView.tsx

@@ -0,0 +1,30 @@
+import { Typography } from "antd";
+import type { CSSProperties } from "react";
+
+import { renderNodes } from "./render";
+import type { MarkupNode } from "./types";
+
+const { Text } = Typography;
+
+interface IWidget {
+  nodes?: MarkupNode[] | null;
+  className?: string;
+  placeholder?: string;
+  style?: CSSProperties;
+}
+
+/**
+ * 显示后端渲染好的正文节点树(v3 接口的 `body` 字段)。取代 general/MdView(解析 MdTpl HTML 字符串)。
+ */
+const MarkupView = ({ nodes, className, placeholder, style }: IWidget) => {
+  if (!nodes || nodes.length === 0) {
+    return <Text type="secondary">{placeholder}</Text>;
+  }
+  return (
+    <Text className={className} style={style}>
+      {renderNodes(nodes)}
+    </Text>
+  );
+};
+
+export default MarkupView;

+ 77 - 0
dashboard-v6/src/components/markup/SentenceView.tsx

@@ -0,0 +1,77 @@
+import { Flex } from "antd";
+
+import { useSetting } from "../../hooks/useSetting";
+import { renderNodes } from "./render";
+import type { MarkupNode } from "./types";
+
+/** 一条译文 / 原文(后端 SentTemplate 的 props) */
+interface ISentenceEntry {
+  id: string;
+  channel: { id: string; name: string; lang: string };
+  body: MarkupNode[] | null;
+  /** 只在编辑模式给 */
+  content?: string;
+  contentType?: string;
+}
+
+export interface ISentenceViewProps {
+  /** 句子坐标 book-para-start-end */
+  id: string;
+  show?: "origin" | "translation" | "both";
+  origin?: ISentenceEntry[];
+  translation?: ISentenceEntry[];
+  commentaries?: ISentenceEntry[];
+  error?: string;
+}
+
+/**
+ * 句子模板的只读显示:原文(棕色)+ 各译文。
+ *
+ * 与 components/sentence/SentRead 的区别:那边的每条译文是 MdTpl HTML 字符串、带编辑菜单;
+ * 这里是节点树,只读。
+ */
+const SentenceView = ({
+  id,
+  show = "both",
+  origin = [],
+  translation = [],
+  error,
+}: ISentenceViewProps) => {
+  const layoutDirection = useSetting("setting.layout.direction");
+  const displayOriginal = useSetting("setting.display.original");
+  if (error) {
+    return <span className="sent_read_error">{id}</span>;
+  }
+  const showOrigin =
+    show !== "translation" &&
+    !(displayOriginal === false && translation.length > 0);
+  return (
+    <Flex
+      className="sent_read_shell"
+      gap="middle"
+      vertical={layoutDirection === "column"}
+      id={`sent_${id}`}
+    >
+      {showOrigin && (
+        <span style={{ flex: 5, color: "#9f3a01" }}>
+          {origin.map((item) => (
+            <span key={item.id} lang={item.channel.lang}>
+              {renderNodes(item.body)}
+            </span>
+          ))}
+        </span>
+      )}
+      {show !== "origin" && (
+        <span style={{ flex: 5 }}>
+          {translation.map((item) => (
+            <div key={item.id} lang={item.channel.lang}>
+              {renderNodes(item.body)}
+            </div>
+          ))}
+        </span>
+      )}
+    </Flex>
+  );
+};
+
+export default SentenceView;

+ 162 - 0
dashboard-v6/src/components/markup/render.tsx

@@ -0,0 +1,162 @@
+import { createElement, Fragment, type ReactNode } from "react";
+
+import { gfwClear } from "../../gfwlist";
+import MarkupTemplate from "./MarkupTemplate";
+import type { MarkupElementNode, MarkupNode } from "./types";
+
+/**
+ * 后端已经过白名单(App\Services\Markup\Html\HtmlPolicy),这里再兜一层:
+ * 不认识的标签只渲染子节点,不进 DOM。
+ */
+const ALLOWED_TAGS = new Set([
+  "a",
+  "abbr",
+  "b",
+  "bdi",
+  "bdo",
+  "blockquote",
+  "br",
+  "caption",
+  "cite",
+  "code",
+  "col",
+  "colgroup",
+  "dd",
+  "del",
+  "details",
+  "dfn",
+  "div",
+  "dl",
+  "dt",
+  "em",
+  "figcaption",
+  "figure",
+  "h1",
+  "h2",
+  "h3",
+  "h4",
+  "h5",
+  "h6",
+  "hr",
+  "i",
+  "img",
+  "input",
+  "ins",
+  "kbd",
+  "li",
+  "mark",
+  "ol",
+  "p",
+  "pre",
+  "q",
+  "rp",
+  "rt",
+  "ruby",
+  "s",
+  "samp",
+  "small",
+  "span",
+  "strong",
+  "sub",
+  "summary",
+  "sup",
+  "table",
+  "tbody",
+  "td",
+  "tfoot",
+  "th",
+  "thead",
+  "tr",
+  "u",
+  "ul",
+  "var",
+  "wbr",
+  "video",
+  "audio",
+  "source",
+]);
+
+const VOID_TAGS = new Set(["br", "hr", "img", "wbr", "col", "source", "input"]);
+
+/** HTML 属性名 → React 属性名 */
+const ATTR_NAMES: Record<string, string> = {
+  class: "className",
+  colspan: "colSpan",
+  rowspan: "rowSpan",
+};
+
+/** 布尔属性:有就是 true */
+const BOOLEAN_ATTRS = new Set(["checked", "disabled", "controls", "open"]);
+
+const toProps = (node: MarkupElementNode, key: number) => {
+  const props: Record<string, unknown> = { key };
+  for (const [name, value] of Object.entries(node.attrs ?? {})) {
+    if (BOOLEAN_ATTRS.has(name)) {
+      props[name] = true;
+    } else if (name === "href" || name === "src") {
+      props[name] = gfwClear(value);
+    } else {
+      props[ATTR_NAMES[name] ?? name] = value;
+    }
+  }
+  if (node.tag === "input") {
+    // 任务列表的勾选框只读
+    props.readOnly = true;
+  }
+  return props;
+};
+
+/**
+ * 渲染成块级元素的模板。markdown 段落里出现它们时,段落改用 div 渲染——`<p>` 里不能放 `<div>`,
+ * 浏览器会提前闭合段落、React 也会报嵌套错误。
+ */
+const BLOCK_TEMPLATES = new Set([
+  "sentread",
+  "sentedit",
+  "para",
+  "article",
+  "qa",
+  "toggle",
+  "mermaid",
+  "reference",
+  // VideoCtl 外层是 antd Space(div)
+  "video",
+]);
+
+const hasBlockTemplate = (node: MarkupElementNode) =>
+  node.children.some(
+    (child) => child.type === "tpl" && BLOCK_TEMPLATES.has(child.name)
+  );
+
+const renderNode = (node: MarkupNode, key: number): ReactNode => {
+  switch (node.type) {
+    case "text":
+      return gfwClear(node.value);
+    case "el": {
+      const children = renderNodes(node.children);
+      if (!ALLOWED_TAGS.has(node.tag)) {
+        return <Fragment key={key}>{children}</Fragment>;
+      }
+      if (node.tag === "p" && hasBlockTemplate(node)) {
+        return createElement(
+          "div",
+          { ...toProps(node, key), style: { marginBottom: "1em" } },
+          ...children
+        );
+      }
+      return VOID_TAGS.has(node.tag)
+        ? createElement(node.tag, toProps(node, key))
+        : createElement(node.tag, toProps(node, key), ...children);
+    }
+    case "tpl":
+      return (
+        <MarkupTemplate key={key} node={node}>
+          {renderNodes(node.children)}
+        </MarkupTemplate>
+      );
+  }
+};
+
+/** 节点数组 → React 节点 */
+export const renderNodes = (nodes?: MarkupNode[] | null): ReactNode[] =>
+  (nodes ?? []).map((node, index) => renderNode(node, index));

+ 12 - 0
dashboard-v6/src/components/markup/types.ts

@@ -0,0 +1,12 @@
+import type { components } from "../../api/schema";
+
+/**
+ * 正文渲染后的节点树(后端 App\Services\Markup 的 tree 输出)。
+ * 类型从 OpenAPI 生成,不手写。
+ */
+export type MarkupNode = components["schemas"]["MarkupNode"];
+export type MarkupElementNode = components["schemas"]["MarkupElement"];
+export type MarkupTemplateNode = components["schemas"]["MarkupTemplate"];
+
+/** 模板的 props:形状随模板而定,由各模板的组件自己约定 */
+export type MarkupProps = MarkupTemplateNode["props"];

+ 1 - 1
dashboard-v6/src/components/template/GrammarTermLookup.tsx

@@ -5,7 +5,7 @@ interface IGrammarTermLookupCtl {
   word?: string;
   term?: IWidgetTermCtl;
 }
-const GrammarTermLookupCtl = ({ word, term }: IGrammarTermLookupCtl) => {
+export const GrammarTermLookupCtl = ({ word, term }: IGrammarTermLookupCtl) => {
   return (
     <GrammarLookup word={word}>
       <TermCtl {...term} compact={true} />

+ 1 - 1
dashboard-v6/src/components/template/Note.tsx

@@ -13,7 +13,7 @@ interface IWidgetNoteCtl {
   note?: string;
   children?: React.ReactNode;
 }
-const NoteCtl = ({ trigger, note, children }: IWidgetNoteCtl) => {
+export const NoteCtl = ({ trigger, note, children }: IWidgetNoteCtl) => {
   const show = trigger ? trigger : <InfoCircleOutlined />;
   return (
     <>

+ 1 - 1
dashboard-v6/src/components/template/Para.tsx

@@ -8,7 +8,7 @@ interface IWidget extends IDisplayWrapperProps {
   id?: string;
   channel?: string;
 }
-const ParaCtl = (props: IWidget) => {
+export const ParaCtl = (props: IWidget) => {
   return (
     <DisplayWrapper {...props}>
       <TypePali

+ 1 - 1
dashboard-v6/src/components/template/Qa.tsx

@@ -9,7 +9,7 @@ interface IQaCtl {
   resId?: string;
   resType?: TResType;
 }
-const QaCtl = ({ id, title, resType }: IQaCtl) => {
+export const QaCtl = ({ id, title, resType }: IQaCtl) => {
   return (
     <Collapse bordered={false}>
       <Collapse.Panel header={title} key="1">

+ 1 - 1
dashboard-v6/src/components/template/Quality.tsx

@@ -22,7 +22,7 @@ interface IQualityCtl {
  * 渲染单个质量标签
  * 非法取值回退为默认的 pending,保证样式始终可预期
  */
-const QualityCtl = ({ value = "pending" }: IQualityCtl) => {
+export const QualityCtl = ({ value = "pending" }: IQualityCtl) => {
   const color = QUALITY_COLORS[value] ?? QUALITY_COLORS.pending;
   return <Tag color={color}>{value}</Tag>;
 };

+ 1 - 1
dashboard-v6/src/components/template/Quote.tsx

@@ -14,7 +14,7 @@ interface IWidgetQuoteCtl {
   error?: boolean;
   message?: string;
 }
-const QuoteCtl = ({ paraId, pali, error, message }: IWidgetQuoteCtl) => {
+export const QuoteCtl = ({ paraId, pali, error, message }: IWidgetQuoteCtl) => {
   const intl = useIntl();
   const show = pali ? pali : paraId;
   let textShow = <></>;

+ 1 - 1
dashboard-v6/src/components/template/QuoteLink.tsx

@@ -19,7 +19,7 @@ interface IWidgetQuoteLinkCtl {
   chapter?: string;
   found: boolean;
 }
-const QuoteLinkCtl = ({
+export const QuoteLinkCtl = ({
   type,
   bookName,
   volume,

+ 1 - 1
dashboard-v6/src/components/template/Reference.tsx

@@ -18,7 +18,7 @@ interface IReference {
 interface IReferenceCtl {
   pali?: IReference[];
 }
-const ReferenceCtl = ({ pali }: IReferenceCtl) => {
+export const ReferenceCtl = ({ pali }: IReferenceCtl) => {
   const Reference = (ref: IReference) => {
     return (
       <Paragraph>{`[${ref.sn}] ${ucFirst(ref.title)} ${

+ 1 - 1
dashboard-v6/src/components/template/Toggle.tsx

@@ -4,7 +4,7 @@ import { Children } from "react";
 interface IToggleCtlWidget {
   children?: React.ReactNode | React.ReactNode[];
 }
-const ToggleCtl = ({ children }: IToggleCtlWidget) => {
+export const ToggleCtl = ({ children }: IToggleCtlWidget) => {
   const arrayChildren = Children.toArray(children);
   if (arrayChildren.length === 0) {
     return <></>;

+ 68 - 0
openapi/public/assets/protocol/main.yaml

@@ -65,6 +65,74 @@ components:
               message: { type: string }
               errors: { type: object, additionalProperties: { type: array, items: { type: string } } }
   schemas:
+    MarkupNode:
+      description: |-
+        正文(markdown + 模板)渲染后的节点树,由 App\Services\Markup 生成。
+        三种节点:text 纯文本(前端作为 React 文本节点,自动转义);el HTML 元素(tag 与 attrs 已过白名单);
+        tpl 模板(name 是前端组件名,props 随模板而定,props 里嵌套的内容也是节点数组)。
+      oneOf:
+        -
+          $ref: '#/components/schemas/MarkupText'
+        -
+          $ref: '#/components/schemas/MarkupElement'
+        -
+          $ref: '#/components/schemas/MarkupTemplate'
+    MarkupText:
+      type: object
+      properties:
+        type:
+          type: string
+          enum:
+            - text
+        value:
+          type: string
+      required:
+        - type
+        - value
+    MarkupElement:
+      type: object
+      properties:
+        type:
+          type: string
+          enum:
+            - el
+        tag:
+          type: string
+          description: '白名单内的 HTML 标签名(小写)'
+        attrs:
+          type: object
+          additionalProperties:
+            type: string
+        children:
+          type: array
+          items:
+            $ref: '#/components/schemas/MarkupNode'
+      required:
+        - type
+        - tag
+        - children
+    MarkupTemplate:
+      type: object
+      properties:
+        type:
+          type: string
+          enum:
+            - tpl
+        name:
+          type: string
+          description: 前端组件名:term、note、sentread、sentedit、quote、quote-link、mermaid…
+        props:
+          type: object
+          additionalProperties: true
+        children:
+          type: array
+          items:
+            $ref: '#/components/schemas/MarkupNode'
+      required:
+        - type
+        - name
+        - props
+        - children
     ProblemDetails:
       type: object
       description: |-

+ 11 - 6
openapi/public/assets/protocol/resources/auto/v3-discussions-discussion-replies.yaml

@@ -74,8 +74,9 @@ get:
                       nullable: true
                     content_type:
                       type: string
-                    html:
-                      type: string
+                    body:
+                      type: array
+                      items: { $ref: '../../main.yaml#/components/schemas/MarkupNode' }
                       description: 仅在部分查询口径下返回。
                     summary:
                       type: string
@@ -203,8 +204,10 @@ post:
                     nullable: true
                   content_type:
                     type: string
-                  html:
-                    type: string
+                  body:
+                    type: array
+                    items:
+                      $ref: '../../main.yaml#/components/schemas/MarkupNode'
                     description: 仅在部分查询口径下返回。
                   summary:
                     type: string
@@ -311,8 +314,10 @@ post:
                     nullable: true
                   content_type:
                     type: string
-                  html:
-                    type: string
+                  body:
+                    type: array
+                    items:
+                      $ref: '../../main.yaml#/components/schemas/MarkupNode'
                     description: 仅在部分查询口径下返回。
                   summary:
                     type: string

+ 12 - 6
openapi/public/assets/protocol/resources/auto/v3-discussions-discussion.yaml

@@ -59,8 +59,10 @@ get:
                     nullable: true
                   content_type:
                     type: string
-                  html:
-                    type: string
+                  body:
+                    type: array
+                    items:
+                      $ref: '../../main.yaml#/components/schemas/MarkupNode'
                     description: 仅在部分查询口径下返回。
                   summary:
                     type: string
@@ -192,8 +194,10 @@ delete:
                     nullable: true
                   content_type:
                     type: string
-                  html:
-                    type: string
+                  body:
+                    type: array
+                    items:
+                      $ref: '../../main.yaml#/components/schemas/MarkupNode'
                     description: 仅在部分查询口径下返回。
                   summary:
                     type: string
@@ -393,8 +397,10 @@ patch:
                     nullable: true
                   content_type:
                     type: string
-                  html:
-                    type: string
+                  body:
+                    type: array
+                    items:
+                      $ref: '../../main.yaml#/components/schemas/MarkupNode'
                     description: 仅在部分查询口径下返回。
                   summary:
                     type: string

+ 11 - 6
openapi/public/assets/protocol/resources/auto/v3-discussions.yaml

@@ -135,8 +135,9 @@ get:
                       nullable: true
                     content_type:
                       type: string
-                    html:
-                      type: string
+                    body:
+                      type: array
+                      items: { $ref: '../../main.yaml#/components/schemas/MarkupNode' }
                       description: 仅在部分查询口径下返回。
                     summary:
                       type: string
@@ -321,8 +322,10 @@ post:
                     nullable: true
                   content_type:
                     type: string
-                  html:
-                    type: string
+                  body:
+                    type: array
+                    items:
+                      $ref: '../../main.yaml#/components/schemas/MarkupNode'
                     description: 仅在部分查询口径下返回。
                   summary:
                     type: string
@@ -429,8 +432,10 @@ post:
                     nullable: true
                   content_type:
                     type: string
-                  html:
-                    type: string
+                  body:
+                    type: array
+                    items:
+                      $ref: '../../main.yaml#/components/schemas/MarkupNode'
                     description: 仅在部分查询口径下返回。
                   summary:
                     type: string

+ 3 - 2
openapi/public/assets/protocol/resources/auto/v3-tipitaka-discussions-channel.yaml

@@ -130,8 +130,9 @@ get:
                       nullable: true
                     content_type:
                       type: string
-                    html:
-                      type: string
+                    body:
+                      type: array
+                      items: { $ref: '../../main.yaml#/components/schemas/MarkupNode' }
                       description: 仅在部分查询口径下返回。
                     summary:
                       type: string

+ 56 - 1
openapi/scripts/generate.php

@@ -592,6 +592,54 @@ function shapeToProperties(string $inner): array
 }
 
 /** PHPDoc 类型 → OpenAPI schema */
+/**
+ * Resource 的 `@return array{...}` 里可以直接写的命名类型 → components.schemas 里的定义。
+ *
+ * 用于写不成 array{...} 的形状(递归的节点树)。名字就是 schema 名,前端从
+ * `components["schemas"]["名字"]` 取类型。
+ */
+const NAMED_SCHEMAS = [
+    // App\Services\Markup\Render\TreeRenderer 的输出:正文渲染后的节点树
+    'MarkupNode' => [
+        'description' => "正文(markdown + 模板)渲染后的节点树,由 App\\Services\\Markup 生成。\n" .
+            "三种节点:text 纯文本(前端作为 React 文本节点,自动转义);el HTML 元素(tag 与 attrs 已过白名单);\n" .
+            'tpl 模板(name 是前端组件名,props 随模板而定,props 里嵌套的内容也是节点数组)。',
+        'oneOf' => [
+            ['$ref' => '#/components/schemas/MarkupText'],
+            ['$ref' => '#/components/schemas/MarkupElement'],
+            ['$ref' => '#/components/schemas/MarkupTemplate'],
+        ],
+    ],
+    'MarkupText' => [
+        'type' => 'object',
+        'properties' => [
+            'type' => ['type' => 'string', 'enum' => ['text']],
+            'value' => ['type' => 'string'],
+        ],
+        'required' => ['type', 'value'],
+    ],
+    'MarkupElement' => [
+        'type' => 'object',
+        'properties' => [
+            'type' => ['type' => 'string', 'enum' => ['el']],
+            'tag' => ['type' => 'string', 'description' => '白名单内的 HTML 标签名(小写)'],
+            'attrs' => ['type' => 'object', 'additionalProperties' => ['type' => 'string']],
+            'children' => ['type' => 'array', 'items' => ['$ref' => '#/components/schemas/MarkupNode']],
+        ],
+        'required' => ['type', 'tag', 'children'],
+    ],
+    'MarkupTemplate' => [
+        'type' => 'object',
+        'properties' => [
+            'type' => ['type' => 'string', 'enum' => ['tpl']],
+            'name' => ['type' => 'string', 'description' => '前端组件名:term、note、sentread、sentedit、quote、quote-link、mermaid…'],
+            'props' => ['type' => 'object', 'additionalProperties' => true],
+            'children' => ['type' => 'array', 'items' => ['$ref' => '#/components/schemas/MarkupNode']],
+        ],
+        'required' => ['type', 'name', 'props', 'children'],
+    ],
+];
+
 function phpTypeToSchema(string $type): array
 {
     $type = trim($type);
@@ -627,6 +675,13 @@ function phpTypeToSchema(string $type): array
     }
     $type = trim($type);
 
+    // 在 main.yaml components.schemas 里定义的命名 schema(如递归的 MarkupNode)
+    if (isset(NAMED_SCHEMAS[$type])) {
+        $schema = ['$ref' => '../../main.yaml#/components/schemas/' . $type];
+
+        return $nullable ? ['allOf' => [$schema], 'nullable' => true] : $schema;
+    }
+
     // 嵌套 array{...}
     if (preg_match('/^array\s*\{(.*)$/s', $type, $m)) {
         $innerText = extractBraced($m[1]);
@@ -1166,7 +1221,7 @@ $main = [
                 ]]],
             ],
         ],
-        'schemas' => [
+        'schemas' => NAMED_SCHEMAS + [
             'ProblemDetails' => [
                 'type' => 'object',
                 'description' => "RFC 9457 Problem Details,v3 端点的错误响应体。\n" .