Explorar o código

✨ (api-v13): 正文渲染服务 App\Services\Markup,取代 MdRender / TemplateRender

wikipali 的正文(article、term、sentence、discussion)是 markdown + 类维基模板。
旧实现先把模板转成 XML 再解析,嵌套难处理,且只能输出 HTML 字符串。新服务直接解析:

- 解析:预扫描把 {{模板}}、[[术语]]、脚注换成占位符,再交给 league/commonmark(CommonMark + GFM),
  模板可跨行、含空行、多层嵌套、放进表格;IR 构建时原始 HTML 过白名单
- 两种方言按 content_type:markdown(旧,反引号是脚注;跨行、双反引号按作者本意配对)、
  markdown-e2(标准代码;脚注用 {{note|…}} / {{n|…}} 或 ```note 围栏,紧挨上下文时角标在句中)
- 每个模板一个类(Templates/,TemplateRegistry 登记),取数批量(Resolver + Loader),
  不再逐个查库;术语 note 只展开一层
- 输出:tree(JSON 节点树,给 v3 API)/ html / text / simple / prompt / markdown
- mermaid 是普通 ```mermaid 围栏,不再 base64
- 中文标点旁的粗体:按 markdown-cjk-friendly 放宽 `*` 的贴合规则,两侧都不是 CJK 时与 CommonMark 一致
- 阅读页批注的结构化注入:AnnotationLayout 抽出输出策略 AnnotationMarkup,
  缺省 HtmlAnnotationMarkup 与旧 HTML 逐字节一致;AnnotationSet 写占位符,
  解析成 anno-issue / anno-issue-mark / anno-assessment / note 节点(内部模板,正文里写不出来)

v2 继续用 MdRender,不改。本提交只加服务,调用方在后续提交里切换。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda hai 8 horas
pai
achega
f7204eee29
Modificáronse 77 ficheiros con 6952 adicións e 47 borrados
  1. 13 47
      api-v13/app/Services/AnnotationLayout.php
  2. 40 0
      api-v13/app/Services/AnnotationMarkup.php
  3. 59 0
      api-v13/app/Services/HtmlAnnotationMarkup.php
  4. 96 0
      api-v13/app/Services/Markup/Annotation/AnnotationSet.php
  5. 32 0
      api-v13/app/Services/Markup/Annotation/AnnotationToken.php
  6. 16 0
      api-v13/app/Services/Markup/Annotation/AnnotationTokenNode.php
  7. 27 0
      api-v13/app/Services/Markup/Annotation/AnnotationTokenParser.php
  8. 33 0
      api-v13/app/Services/Markup/Annotation/Marker.php
  9. 154 0
      api-v13/app/Services/Markup/Annotation/RangeWrapper.php
  10. 27 0
      api-v13/app/Services/Markup/Dialect.php
  11. 28 0
      api-v13/app/Services/Markup/Format.php
  12. 137 0
      api-v13/app/Services/Markup/Html/HtmlFragment.php
  13. 115 0
      api-v13/app/Services/Markup/Html/HtmlPolicy.php
  14. 81 0
      api-v13/app/Services/Markup/Html/InlineHtmlAssembler.php
  15. 19 0
      api-v13/app/Services/Markup/Ir/Boundary.php
  16. 58 0
      api-v13/app/Services/Markup/Ir/Call.php
  17. 39 0
      api-v13/app/Services/Markup/Ir/Document.php
  18. 21 0
      api-v13/app/Services/Markup/Ir/Element.php
  19. 8 0
      api-v13/app/Services/Markup/Ir/Node.php
  20. 74 0
      api-v13/app/Services/Markup/Ir/Params.php
  21. 58 0
      api-v13/app/Services/Markup/Ir/Scope.php
  22. 11 0
      api-v13/app/Services/Markup/Ir/Text.php
  23. 145 0
      api-v13/app/Services/Markup/MarkupService.php
  24. 102 0
      api-v13/app/Services/Markup/Parsing/CjkFriendlyEmphasisParser.php
  25. 390 0
      api-v13/app/Services/Markup/Parsing/IrBuilder.php
  26. 299 0
      api-v13/app/Services/Markup/Parsing/MarkupParser.php
  27. 45 0
      api-v13/app/Services/Markup/Parsing/Placeholder.php
  28. 17 0
      api-v13/app/Services/Markup/Parsing/PlaceholderNode.php
  29. 28 0
      api-v13/app/Services/Markup/Parsing/PlaceholderParser.php
  30. 367 0
      api-v13/app/Services/Markup/Parsing/Preprocessor.php
  31. 64 0
      api-v13/app/Services/Markup/Parsing/TemplateSyntax.php
  32. 115 0
      api-v13/app/Services/Markup/Render/HtmlRenderer.php
  33. 79 0
      api-v13/app/Services/Markup/Render/MarkdownRenderer.php
  34. 99 0
      api-v13/app/Services/Markup/Render/RenderContext.php
  35. 13 0
      api-v13/app/Services/Markup/Render/Renderer.php
  36. 72 0
      api-v13/app/Services/Markup/Render/TextRenderer.php
  37. 103 0
      api-v13/app/Services/Markup/Render/TreeRenderer.php
  38. 46 0
      api-v13/app/Services/Markup/RenderOptions.php
  39. 58 0
      api-v13/app/Services/Markup/Resolve/ChannelDirectory.php
  40. 21 0
      api-v13/app/Services/Markup/Resolve/Loader.php
  41. 45 0
      api-v13/app/Services/Markup/Resolve/QaLoader.php
  42. 197 0
      api-v13/app/Services/Markup/Resolve/QuoteLinkLoader.php
  43. 64 0
      api-v13/app/Services/Markup/Resolve/QuoteLoader.php
  44. 92 0
      api-v13/app/Services/Markup/Resolve/Resolver.php
  45. 183 0
      api-v13/app/Services/Markup/Resolve/SentenceLoader.php
  46. 190 0
      api-v13/app/Services/Markup/Resolve/TermLoader.php
  47. 76 0
      api-v13/app/Services/Markup/Resolve/TplLoader.php
  48. 38 0
      api-v13/app/Services/Markup/Templates/AiTemplate.php
  49. 71 0
      api-v13/app/Services/Markup/Templates/ArticleTemplate.php
  50. 34 0
      api-v13/app/Services/Markup/Templates/CategoryTemplate.php
  51. 32 0
      api-v13/app/Services/Markup/Templates/DictPrefTemplate.php
  52. 42 0
      api-v13/app/Services/Markup/Templates/ExerciseTemplate.php
  53. 54 0
      api-v13/app/Services/Markup/Templates/GrammarTemplate.php
  54. 48 0
      api-v13/app/Services/Markup/Templates/Internal/AnnoAssessmentTemplate.php
  55. 36 0
      api-v13/app/Services/Markup/Templates/Internal/AnnoIssueMarkTemplate.php
  56. 82 0
      api-v13/app/Services/Markup/Templates/Internal/AnnoIssueTemplate.php
  57. 58 0
      api-v13/app/Services/Markup/Templates/MermaidTemplate.php
  58. 56 0
      api-v13/app/Services/Markup/Templates/NissayaTemplate.php
  59. 132 0
      api-v13/app/Services/Markup/Templates/NoteTemplate.php
  60. 41 0
      api-v13/app/Services/Markup/Templates/ParaTemplate.php
  61. 28 0
      api-v13/app/Services/Markup/Templates/ParamSpec.php
  62. 47 0
      api-v13/app/Services/Markup/Templates/QaTemplate.php
  63. 48 0
      api-v13/app/Services/Markup/Templates/QualityTemplate.php
  64. 72 0
      api-v13/app/Services/Markup/Templates/QuoteLinkTemplate.php
  65. 51 0
      api-v13/app/Services/Markup/Templates/QuoteTemplate.php
  66. 69 0
      api-v13/app/Services/Markup/Templates/ReferenceTemplate.php
  67. 216 0
      api-v13/app/Services/Markup/Templates/SentTemplate.php
  68. 117 0
      api-v13/app/Services/Markup/Templates/Template.php
  69. 80 0
      api-v13/app/Services/Markup/Templates/TemplateRegistry.php
  70. 154 0
      api-v13/app/Services/Markup/Templates/TermTemplate.php
  71. 44 0
      api-v13/app/Services/Markup/Templates/ToggleTemplate.php
  72. 85 0
      api-v13/app/Services/Markup/Templates/TplTemplate.php
  73. 32 0
      api-v13/app/Services/Markup/Templates/UnknownTemplate.php
  74. 37 0
      api-v13/app/Services/Markup/Templates/VideoTemplate.php
  75. 161 0
      api-v13/tests/Feature/MarkupAnnotationTest.php
  76. 605 0
      api-v13/tests/Feature/MarkupSyntaxTest.php
  77. 326 0
      api-v13/tests/Feature/MarkupTemplateDataTest.php

+ 13 - 47
api-v13/app/Services/AnnotationLayout.php

@@ -6,10 +6,12 @@ namespace App\Services;
  * 阅读页批注排版:把锚定在一句译文上的几种批注一次性排进句子的原始 content(markdown)。
  *
  * 纯计算,不查库、不渲染——输入 content 与已解析好的批注,输出改写后的 content。
- * 调用方是 {@see PaliContentService::injectAnnotationNotes()},改写后的 content 再交给 MdRender。
+ * 调用方是 {@see PaliContentService::injectAnnotationNotes()},改写后的 content 再交给 App\Services\Markup 渲染。
+ * 插入点写什么由 {@see AnnotationMarkup} 策略决定:阅读页写结构化标记({@see Markup\Annotation\AnnotationSet}),
+ * 能渲染成任意格式;缺省写 HTML。
  *
  * 三种东西,排法各不相同:
- * - glossary:区间 [start, end) 的原文换成 `[[title#原文]]`,MdRender 渲染成术语;
+ * - glossary:区间 [start, end) 的原文换成 `[[title#原文]]`,渲染成术语;
  * - issue:区间外包一层 `<span class="anno-issue …" data-discussion-ids="…">`(高亮,点击看内容);
  *   没有位置的 issue 合成一个三角叹号图标,放在句尾;
  * - note / commentary:在插入点插入调用方预先渲染好的 `{{note|…}}` 模板;
@@ -105,13 +107,15 @@ class AnnotationLayout
      * @param  list<array{id: string, at: int, order: array<int, int>, html: string}>  $notes  at 是插入点,order 是同一插入点上的先后
      * @param  bool  $withIssues  是否输出 issue 的高亮与图标、评估的对勾(只有 html 格式需要)
      * @param  array{id: string, score: int}|null  $assessment  这句的评估,没有为 null
+     * @param  AnnotationMarkup|null  $markup  插入点写什么,缺省写 HTML({@see HtmlAnnotationMarkup})
      * @return array{content: string, notes: list<string>, glossaries: list<string>, issues: list<array{ids: list<string>, severity: string|null, start: int|null, end: int|null}>}
      *
      * 返回值里 notes 是 note id 的阅读顺序,glossaries 是实际替换了的术语 id,
      * issues 是合并后的高亮(没有位置的合成一条,start / end 为 null)。
      */
-    public static function apply(string $content, array $glossaries, array $issues, array $notes, bool $withIssues = true, ?array $assessment = null): array
+    public static function apply(string $content, array $glossaries, array $issues, array $notes, bool $withIssues = true, ?array $assessment = null, ?AnnotationMarkup $markup = null): array
     {
+        $markup ??= new HtmlAnnotationMarkup;
         $len = mb_strlen($content, 'UTF-8');
         $protected = self::protectedRanges($content);
 
@@ -208,13 +212,13 @@ class AnnotationLayout
             $cursor = $x;
             // 合并后 issue 之间互不交叠,同一点上至多一个收尾、一个开头
             foreach ($closes[$x] ?? [] as $span) {
-                $out .= '</span>';
+                $out .= $markup->issueClose($span);
             }
             foreach ($notesAt[$x] ?? [] as $html) {
                 $out .= $html;
             }
             foreach ($opens[$x] ?? [] as $span) {
-                $out .= self::issueOpenTag($span['ids'], $span['severity']);
+                $out .= $markup->issueOpen($span);
             }
             if (isset($glossaryAt[$x])) {
                 $g = $glossaryAt[$x];
@@ -226,13 +230,13 @@ class AnnotationLayout
         $out .= mb_substr($content, $cursor, null, 'UTF-8');
 
         if ($withIssues && $unanchored !== []) {
-            $out .= self::issueMark(
+            $out .= $markup->issueMark(
                 array_column($unanchored, 'id'),
                 self::maxSeverity(array_column($unanchored, 'severity')),
             );
         }
         if ($withIssues && $assessment !== null) {
-            $out .= self::assessmentMark($assessment['id'], $assessment['score']);
+            $out .= $markup->assessmentMark($assessment['id'], $assessment['score']);
         }
 
         $report = array_map(fn ($s) => [
@@ -340,16 +344,6 @@ class AnnotationLayout
         return $max;
     }
 
-    /**
-     * @param  list<string>  $ids
-     */
-    private static function issueOpenTag(array $ids, ?string $severity): string
-    {
-        return '<span class="anno-issue anno-issue-'.($severity ?? 'none').'"'
-            .' data-discussion-ids="'.e(implode(',', $ids)).'"'
-            .' data-severity="'.e($severity ?? '').'">';
-    }
-
     /**
      * 评估分数的档位:high(≥80)/ medium(≥60)/ low。阅读器按档位着色(绿 / 橙 / 红)。
      */
@@ -365,38 +359,10 @@ class AnnotationLayout
     }
 
     /**
-     * 没有评估的句子:灰色对勾,不能点(没有 discussion id)。只在同段有别的句子评估过时由
-     * {@see PaliContentService::renderReadSentences()} 补上,标出句子的边界。
+     * 没有评估的句子的灰色对勾(HTML)。只在同段有别的句子评估过时补上,标出句子的边界。
      */
     public static function unassessedMark(): string
     {
-        return '<span class="anno-assessment-mark anno-assessment-none" data-level="none" aria-hidden="true">'
-            .'<i class="ti ti-circle-check"></i></span>';
-    }
-
-    /**
-     * 评估:句尾一个对勾图标,颜色按分数档位,点击看分数与理由。
-     */
-    private static function assessmentMark(string $id, int $score): string
-    {
-        $level = self::assessmentLevel($score);
-
-        return '<span class="anno-assessment-mark anno-assessment-'.$level.'"'
-            .' data-discussion-ids="'.e($id).'"'
-            .' data-score="'.$score.'" data-level="'.$level.'" role="button" tabindex="0">'
-            .'<i class="ti ti-circle-check"></i></span>';
-    }
-
-    /**
-     * 没有位置的 issue:句尾一个三角叹号图标,颜色取最重的 severity。
-     *
-     * @param  list<string>  $ids
-     */
-    private static function issueMark(array $ids, ?string $severity): string
-    {
-        return '<span class="anno-issue-mark anno-issue-'.($severity ?? 'none').'"'
-            .' data-discussion-ids="'.e(implode(',', $ids)).'"'
-            .' data-severity="'.e($severity ?? '').'" role="button" tabindex="0">'
-            .'<i class="ti ti-alert-triangle"></i></span>';
+        return HtmlAnnotationMarkup::unassessedMark();
     }
 }

+ 40 - 0
api-v13/app/Services/AnnotationMarkup.php

@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Services;
+
+/**
+ * {@see AnnotationLayout} 在插入点写什么。
+ *
+ * 布局算法只决定「在哪里」插;「插什么」由策略给:
+ * - {@see HtmlAnnotationMarkup}:直接写 HTML(默认,单元测试与旧口径)
+ * - {@see Markup\Annotation\AnnotationSet}:写结构化标记的占位符,交给 App\Services\Markup 解析成模板节点,
+ *   能渲染成任意格式
+ */
+interface AnnotationMarkup
+{
+    /**
+     * issue 高亮开头。
+     *
+     * @param  array{start: int, end: int, ids: list<string>, severity: string|null}  $span
+     */
+    public function issueOpen(array $span): string;
+
+    /**
+     * issue 高亮结尾(与同一个 $span 的 issueOpen 配对)。
+     *
+     * @param  array{start: int, end: int, ids: list<string>, severity: string|null}  $span
+     */
+    public function issueClose(array $span): string;
+
+    /**
+     * 没有位置的 issue:句尾的三角叹号。
+     *
+     * @param  list<string>  $ids
+     */
+    public function issueMark(array $ids, ?string $severity): string;
+
+    /**
+     * 评估:句尾的对勾。
+     */
+    public function assessmentMark(string $id, int $score): string;
+}

+ 59 - 0
api-v13/app/Services/HtmlAnnotationMarkup.php

@@ -0,0 +1,59 @@
+<?php
+
+namespace App\Services;
+
+/**
+ * 批注标记的 HTML 写法:阅读器(library、wikipali-mobile)的 CSS 与点击处理都认这套 class / data-*。
+ *
+ * {@see AnnotationLayout} 的默认策略;App\Services\Markup 的批注模板(anno-*)输出 html 时也用这里的方法,
+ * 两条路径的 HTML 逐字节一致。
+ */
+class HtmlAnnotationMarkup implements AnnotationMarkup
+{
+    public function issueOpen(array $span): string
+    {
+        return self::issueOpenTag($span['ids'], $span['severity']);
+    }
+
+    public function issueClose(array $span): string
+    {
+        return '</span>';
+    }
+
+    public function issueMark(array $ids, ?string $severity): string
+    {
+        return '<span class="anno-issue-mark anno-issue-'.($severity ?? 'none').'"'
+            .' data-discussion-ids="'.e(implode(',', $ids)).'"'
+            .' data-severity="'.e($severity ?? '').'" role="button" tabindex="0">'
+            .'<i class="ti ti-alert-triangle"></i></span>';
+    }
+
+    public function assessmentMark(string $id, int $score): string
+    {
+        $level = AnnotationLayout::assessmentLevel($score);
+
+        return '<span class="anno-assessment-mark anno-assessment-'.$level.'"'
+            .' data-discussion-ids="'.e($id).'"'
+            .' data-score="'.$score.'" data-level="'.$level.'" role="button" tabindex="0">'
+            .'<i class="ti ti-circle-check"></i></span>';
+    }
+
+    /**
+     * 没有评估的句子:灰色对勾,不能点(没有 discussion id)。
+     */
+    public static function unassessedMark(): string
+    {
+        return '<span class="anno-assessment-mark anno-assessment-none" data-level="none" aria-hidden="true">'
+            .'<i class="ti ti-circle-check"></i></span>';
+    }
+
+    /**
+     * @param  list<string>  $ids
+     */
+    public static function issueOpenTag(array $ids, ?string $severity): string
+    {
+        return '<span class="anno-issue anno-issue-'.($severity ?? 'none').'"'
+            .' data-discussion-ids="'.e(implode(',', $ids)).'"'
+            .' data-severity="'.e($severity ?? '').'">';
+    }
+}

+ 96 - 0
api-v13/app/Services/Markup/Annotation/AnnotationSet.php

@@ -0,0 +1,96 @@
+<?php
+
+namespace App\Services\Markup\Annotation;
+
+use App\Services\AnnotationLayout;
+use App\Services\AnnotationMarkup;
+
+/**
+ * 结构化的批注注入:作为 {@see AnnotationLayout} 的输出策略,在插入点写占位符而不是 HTML,
+ * 同时记下每个占位符的结构化内容({@see Marker})。解析时占位符变成模板节点
+ * (anno-issue、anno-issue-mark、anno-assessment、note),能渲染成任意格式。
+ *
+ * ```php
+ * $set = new AnnotationSet;
+ * $layout = AnnotationLayout::apply($content, $glossaries, $issues, $notes, true, $assessment, $set);
+ * $markup->renderMany([['source' => $layout['content'], 'annotations' => $set, …]], $options);
+ * ```
+ *
+ * 一个实例只对应一段内容(下标在这段内容里唯一)。
+ */
+final class AnnotationSet implements AnnotationMarkup
+{
+    /** @var list<Marker> */
+    private array $markers = [];
+
+    /** @var array<string, int> issue 区间 → pair 编号 */
+    private array $pairs = [];
+
+    public function issueOpen(array $span): string
+    {
+        $pair = count($this->pairs) + 1;
+        $this->pairs[self::spanKey($span)] = $pair;
+
+        return $this->add(new Marker(Marker::OPEN, $pair, 'anno-issue', [
+            'ids' => implode(',', $span['ids']),
+            'severity' => (string) ($span['severity'] ?? ''),
+        ]));
+    }
+
+    public function issueClose(array $span): string
+    {
+        return $this->add(new Marker(Marker::CLOSE, $this->pairs[self::spanKey($span)] ?? 0));
+    }
+
+    public function issueMark(array $ids, ?string $severity): string
+    {
+        return $this->add(new Marker(Marker::POINT, 0, 'anno-issue-mark', [
+            'ids' => implode(',', $ids),
+            'severity' => (string) ($severity ?? ''),
+        ]));
+    }
+
+    public function assessmentMark(string $id, int $score): string
+    {
+        return $this->add(new Marker(Marker::POINT, 0, 'anno-assessment', ['id' => $id, 'score' => (string) $score]));
+    }
+
+    /**
+     * 没有评估的句子的灰色对勾(同段有别的句子评估过时补上)。
+     */
+    public function unassessedMark(): string
+    {
+        return $this->add(new Marker(Marker::POINT, 0, 'anno-assessment'));
+    }
+
+    /**
+     * 边注 / 义注对应:一个 note 模板,正文是 markdown(解析成节点,格式与模板都保留)。
+     *
+     * @param  array<string, string>  $params  trigger / cite / citelink
+     * @param  string  $contentType  正文的方言(取自批注那一行)
+     */
+    public function note(string $body, array $params = [], string $contentType = 'markdown'): string
+    {
+        return $this->add(new Marker(Marker::POINT, 0, 'note', $params, $body, $contentType));
+    }
+
+    public function get(int $index): ?Marker
+    {
+        return $this->markers[$index] ?? null;
+    }
+
+    private function add(Marker $marker): string
+    {
+        $this->markers[] = $marker;
+
+        return AnnotationToken::make(count($this->markers) - 1);
+    }
+
+    /**
+     * @param  array{start: int, end: int}  $span
+     */
+    private static function spanKey(array $span): string
+    {
+        return $span['start'].'-'.$span['end'];
+    }
+}

+ 32 - 0
api-v13/app/Services/Markup/Annotation/AnnotationToken.php

@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Services\Markup\Annotation;
+
+use App\Services\Markup\Parsing\Placeholder;
+
+/**
+ * 批注标记在源码里的占位符:`\u{E002}n\u{E003}`,n 是 {@see AnnotationSet} 里的下标。
+ *
+ * 与模板占位符({@see Placeholder},E000 / E001)用不同的字符,互不干扰。
+ */
+final class AnnotationToken
+{
+    public const OPEN = "\u{E002}";
+
+    public const CLOSE = "\u{E003}";
+
+    public const PATTERN = '/'."\u{E002}".'(\d+)'."\u{E003}".'/u';
+
+    public static function make(int $index): string
+    {
+        return self::OPEN.$index.self::CLOSE;
+    }
+
+    /**
+     * 去掉占位符(代码里、属性里等不该出现批注的地方),以及源码里本来就有的这两个字符。
+     */
+    public static function strip(string $text): string
+    {
+        return str_replace([self::OPEN, self::CLOSE], '', (string) preg_replace(self::PATTERN, '', $text));
+    }
+}

+ 16 - 0
api-v13/app/Services/Markup/Annotation/AnnotationTokenNode.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace App\Services\Markup\Annotation;
+
+use League\CommonMark\Node\Inline\AbstractInline;
+
+/**
+ * CommonMark AST 里的批注占位节点,只记下标;IR 构建时换成模板调用或区间边界。
+ */
+final class AnnotationTokenNode extends AbstractInline
+{
+    public function __construct(public readonly int $index)
+    {
+        parent::__construct();
+    }
+}

+ 27 - 0
api-v13/app/Services/Markup/Annotation/AnnotationTokenParser.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace App\Services\Markup\Annotation;
+
+use League\CommonMark\Parser\Inline\InlineParserInterface;
+use League\CommonMark\Parser\Inline\InlineParserMatch;
+use League\CommonMark\Parser\InlineParserContext;
+
+/**
+ * 把批注占位符解析成 {@see AnnotationTokenNode}。
+ */
+final class AnnotationTokenParser implements InlineParserInterface
+{
+    public function getMatchDefinition(): InlineParserMatch
+    {
+        return InlineParserMatch::regex(AnnotationToken::OPEN.'(\d+)'.AnnotationToken::CLOSE);
+    }
+
+    public function parse(InlineParserContext $inlineContext): bool
+    {
+        [$index] = $inlineContext->getSubMatches();
+        $inlineContext->getCursor()->advanceBy($inlineContext->getFullMatchLength());
+        $inlineContext->getContainer()->appendChild(new AnnotationTokenNode((int) $index));
+
+        return true;
+    }
+}

+ 33 - 0
api-v13/app/Services/Markup/Annotation/Marker.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Services\Markup\Annotation;
+
+/**
+ * 一个批注标记:{@see AnnotationSet} 在源码里留下的占位符对应的结构化内容。
+ *
+ * - point:一个点,解析成一个模板调用(脚注、句尾图标)
+ * - open / close:一对区间边界(同一个 pair),解析后包住中间的内容(issue 高亮)
+ */
+final readonly class Marker
+{
+    public const OPEN = 'open';
+
+    public const CLOSE = 'close';
+
+    public const POINT = 'point';
+
+    /**
+     * @param  string  $template  模板名:point 与 open 用(close 跟随 open)
+     * @param  array<string, string>  $params  命名参数
+     * @param  string|null  $body  note 的正文(markdown),解析成 text slot
+     * @param  string  $bodyContentType  note 正文的方言(批注是 discussions 的一行,方言跟着它,不跟句子)
+     */
+    public function __construct(
+        public string $kind,
+        public int $pair = 0,
+        public string $template = '',
+        public array $params = [],
+        public ?string $body = null,
+        public string $bodyContentType = 'markdown',
+    ) {}
+}

+ 154 - 0
api-v13/app/Services/Markup/Annotation/RangeWrapper.php

@@ -0,0 +1,154 @@
+<?php
+
+namespace App\Services\Markup\Annotation;
+
+use App\Services\AnnotationLayout;
+use App\Services\Markup\Ir\Boundary;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Scope;
+
+/**
+ * 把配对的区间边界({@see Boundary})换成包住中间内容的模板调用(issue 高亮)。
+ *
+ * {@see AnnotationLayout} 保证边界不会切断模板、术语、`**粗体**`、HTML 标签,
+ * 但单星号斜体、链接这类没有保护,开、闭可能落在不同层级(一个在 `<em>` 里、一个在外面)。
+ * 这时把边界提升到两者最近的共同父层:开头挪到包含它的那个子节点之前,结尾挪到包含它的子节点之后——
+ * 相当于把高亮扩展到完整包住那个元素,与 AnnotationLayout「扩展到完整包住」的规则一致。
+ *
+ * 只在 Element 的 children 里找(模板参数里的内容是另一段 Document,批注不会落进去)。
+ */
+final class RangeWrapper
+{
+    /**
+     * @param  list<Node>  $nodes  根节点列表(就地修改)
+     * @return list<Node>
+     */
+    public static function apply(array $nodes, Scope $scope): array
+    {
+        $root = new Element('#root', [], $nodes);
+        while (($open = self::find($root, fn (Node $n) => $n instanceof Boundary && $n->open)) !== null) {
+            /** @var Boundary $boundary */
+            $boundary = self::at($root, $open);
+            $close = self::find($root, fn (Node $n) => $n instanceof Boundary && ! $n->open && $n->pair === $boundary->pair);
+            if ($close === null || $boundary->call === null || ! self::before($open, $close)) {
+                self::remove($root, $open);
+
+                continue;
+            }
+            self::wrap($root, $open, $close, $boundary, $scope);
+        }
+        // 剩下的都是配不上对的结尾
+        while (($orphan = self::find($root, fn (Node $n) => $n instanceof Boundary)) !== null) {
+            self::remove($root, $orphan);
+        }
+
+        return $root->children;
+    }
+
+    /**
+     * @param  list<int>  $open
+     * @param  list<int>  $close
+     */
+    private static function wrap(Element $root, array $open, array $close, Boundary $boundary, Scope $scope): void
+    {
+        // 最近的共同父层:两条路径在第 k 层分叉(或其中一条在第 k 层就是边界本身)
+        $k = 0;
+        while ($k < count($open) - 1 && $k < count($close) - 1 && $open[$k] === $close[$k]) {
+            $k++;
+        }
+        $container = $root;
+        for ($i = 0; $i < $k; $i++) {
+            /** @var Element $container */
+            $container = $container->children[$open[$i]];
+        }
+        $from = $open[$k];
+        $to = $close[$k];
+        $openIsDirect = count($open) === $k + 1;
+        $closeIsDirect = count($close) === $k + 1;
+
+        // 先删深处的边界(不影响第 k 层的下标),再处理第 k 层
+        if (! $closeIsDirect) {
+            self::remove($root, $close);
+        }
+        if (! $openIsDirect) {
+            self::remove($root, $open);
+        }
+        $start = $openIsDirect ? $from + 1 : $from;
+        $end = $closeIsDirect ? $to - 1 : $to;
+        $inner = array_slice($container->children, $start, max(0, $end - $start + 1));
+
+        $call = $boundary->call;
+        $call->slots['content'] = new Document($inner, true, '', [], $scope, fragment: true);
+        array_splice($container->children, $from, $to - $from + 1, [$call]);
+    }
+
+    /**
+     * 深度优先找第一个满足条件的节点,返回下标路径。
+     *
+     * @param  callable(Node): bool  $match
+     * @return list<int>|null
+     */
+    private static function find(Element $element, callable $match): ?array
+    {
+        foreach ($element->children as $i => $child) {
+            if ($match($child)) {
+                return [$i];
+            }
+            if ($child instanceof Element && ($path = self::find($child, $match)) !== null) {
+                return [$i, ...$path];
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * @param  list<int>  $path
+     */
+    private static function at(Element $root, array $path): Node
+    {
+        $node = $root;
+        foreach ($path as $i) {
+            /** @var Element $node */
+            $node = $node->children[$i];
+        }
+
+        return $node;
+    }
+
+    /**
+     * @param  list<int>  $path
+     */
+    private static function remove(Element $root, array $path): void
+    {
+        $parent = $root;
+        foreach (array_slice($path, 0, -1) as $i) {
+            /** @var Element $parent */
+            $parent = $parent->children[$i];
+        }
+        array_splice($parent->children, (int) end($path), 1);
+    }
+
+    /**
+     * 文档顺序上 a 在 b 之前。
+     *
+     * @param  list<int>  $a
+     * @param  list<int>  $b
+     */
+    private static function before(array $a, array $b): bool
+    {
+        // 逐层比下标(PHP 的数组 < 先比长度,不是字典序)
+        foreach ($a as $depth => $index) {
+            if (! isset($b[$depth])) {
+                return false;
+            }
+            if ($index !== $b[$depth]) {
+                return $index < $b[$depth];
+            }
+        }
+
+        return count($a) < count($b);
+    }
+}

+ 27 - 0
api-v13/app/Services/Markup/Dialect.php

@@ -0,0 +1,27 @@
+<?php
+
+namespace App\Services\Markup;
+
+/**
+ * 正文的标记方言,取自 sentences / articles / discussions 的 `content_type` 列。
+ *
+ * - Markdown(`markdown`):旧数据。`` `x` `` 与单独一行的 ``` 围栏是脚注(不是代码)。
+ * - MarkdownE2(`markdown-e2`):标准 CommonMark + GFM,代码照常是代码;脚注只用 `{{note|…}}` / `{{n|…}}`
+ *   或 ```note 围栏。
+ *
+ * 两种方言都认 `{{模板}}`、`[[术语]]`、`{{book-para-start-end}}` 句子简写、```note、```mermaid。
+ */
+enum Dialect: string
+{
+    case Markdown = 'markdown';
+    case MarkdownE2 = 'markdown-e2';
+
+    /**
+     * 从 content_type 推方言。`markdown-e2` 以外(markdown / html / json / null)一律按旧方言处理,
+     * 与 v2 的 MdRender 一致。
+     */
+    public static function fromContentType(?string $contentType): self
+    {
+        return $contentType === self::MarkdownE2->value ? self::MarkdownE2 : self::Markdown;
+    }
+}

+ 28 - 0
api-v13/app/Services/Markup/Format.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Services\Markup;
+
+/**
+ * 输出格式。
+ *
+ * - Tree:JSON 节点树,给 v3 API(dashboard-v6、wikipali-mobile)。节点形状见 {@see Render\TreeRenderer}
+ * - Html:静态 HTML,给 Laravel library 阅读器与导出
+ * - Text:纯文本;Simple:更省略的纯文本(标题等);Prompt:喂给 LLM 的纯文本
+ * - Markdown:模板展开后的 markdown,脚注转成 `[^n]`(导出用)
+ *
+ * v2 的 `react`(MdTpl + base64)、`unity`、`tex` 不在新服务里实现。
+ */
+enum Format: string
+{
+    case Tree = 'tree';
+    case Html = 'html';
+    case Text = 'text';
+    case Simple = 'simple';
+    case Prompt = 'prompt';
+    case Markdown = 'markdown';
+
+    public function isPlain(): bool
+    {
+        return in_array($this, [self::Text, self::Simple, self::Prompt], true);
+    }
+}

+ 137 - 0
api-v13/app/Services/Markup/Html/HtmlFragment.php

@@ -0,0 +1,137 @@
+<?php
+
+namespace App\Services\Markup\Html;
+
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Text;
+use Closure;
+use DOMDocument;
+use DOMElement;
+use DOMNode;
+use DOMText;
+
+/**
+ * 原始 HTML → IR 节点(过 {@see HtmlPolicy})。
+ *
+ * 两种来源:
+ * - HTML 块(CommonMark 的 HtmlBlock):整块交给 DOMDocument 解析
+ * - 行内 HTML(HtmlInline):CommonMark 把 `<u>a</u>` 拆成「开标签、文字、闭标签」三个兄弟节点,
+ *   由 {@see InlineHtmlAssembler} 按栈重新配对
+ */
+final class HtmlFragment
+{
+    /**
+     * @param  Closure(string): list<Node>  $expandText  文字 → 节点(展开其中的模板占位符)
+     * @return list<Node>
+     */
+    public static function parseBlock(string $html, Closure $expandText): array
+    {
+        $doc = new DOMDocument;
+        $previous = libxml_use_internal_errors(true);
+        $doc->loadHTML(
+            '<?xml encoding="UTF-8"><div>'.$html.'</div>',
+            LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_NOERROR | LIBXML_NOWARNING,
+        );
+        libxml_clear_errors();
+        libxml_use_internal_errors($previous);
+
+        $root = null;
+        foreach ($doc->childNodes as $child) {
+            if ($child instanceof DOMElement) {
+                $root = $child;
+                break;
+            }
+        }
+
+        return $root === null ? [] : self::children($root, $expandText);
+    }
+
+    /**
+     * @param  Closure(string): list<Node>  $expandText
+     * @return list<Node>
+     */
+    private static function children(DOMNode $parent, Closure $expandText): array
+    {
+        $nodes = [];
+        foreach ($parent->childNodes as $child) {
+            if ($child instanceof DOMText) {
+                array_push($nodes, ...$expandText($child->data));
+            } elseif ($child instanceof DOMElement) {
+                $element = self::element($child->tagName, self::domAttrs($child));
+                if ($element === false) {
+                    continue;
+                }
+                $element->children = self::children($child, $expandText);
+                $nodes[] = $element;
+            }
+        }
+
+        return $nodes;
+    }
+
+    /**
+     * 按白名单建元素;false 表示连同内容丢掉。
+     *
+     * @param  array<string, string>  $attrs
+     */
+    public static function element(string $tag, array $attrs): Element|false
+    {
+        $tag = strtolower($tag);
+        $decision = HtmlPolicy::tag($tag);
+        if ($decision === false) {
+            return false;
+        }
+        if ($decision === null) {
+            return new Element('span', ['data-tag' => $tag] + HtmlPolicy::attrs('span', $attrs));
+        }
+
+        return new Element($decision, HtmlPolicy::attrs($decision, $attrs));
+    }
+
+    /**
+     * @return array<string, string>
+     */
+    private static function domAttrs(DOMElement $element): array
+    {
+        $attrs = [];
+        foreach ($element->attributes as $attr) {
+            $attrs[strtolower($attr->nodeName)] = $attr->nodeValue ?? '';
+        }
+
+        return $attrs;
+    }
+
+    /**
+     * 解析一个标签字面量。
+     *
+     * @return array{kind: 'open'|'close'|'other', tag: string, attrs: array<string, string>, selfClosing: bool}
+     */
+    public static function tagLiteral(string $literal): array
+    {
+        if (preg_match('/^<\/([a-zA-Z][a-zA-Z0-9-]*)\s*>$/', $literal, $m) === 1) {
+            return ['kind' => 'close', 'tag' => strtolower($m[1]), 'attrs' => [], 'selfClosing' => false];
+        }
+        if (preg_match('/^<([a-zA-Z][a-zA-Z0-9-]*)(.*?)(\/?)>$/s', $literal, $m) !== 1) {
+            return ['kind' => 'other', 'tag' => '', 'attrs' => [], 'selfClosing' => false];
+        }
+        $attrs = [];
+        preg_match_all(
+            '/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'=<>`]+)))?/',
+            $m[2],
+            $pairs,
+            PREG_SET_ORDER,
+        );
+        foreach ($pairs as $pair) {
+            $value = ($pair[2] ?? '') !== '' ? $pair[2] : ((($pair[3] ?? '') !== '') ? $pair[3] : ($pair[4] ?? ''));
+            $attrs[strtolower($pair[1])] = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
+        }
+
+        return ['kind' => 'open', 'tag' => strtolower($m[1]), 'attrs' => $attrs, 'selfClosing' => $m[3] === '/'];
+    }
+
+    public static function text(string $value): Text
+    {
+        return new Text($value);
+    }
+}

+ 115 - 0
api-v13/app/Services/Markup/Html/HtmlPolicy.php

@@ -0,0 +1,115 @@
+<?php
+
+namespace App\Services\Markup\Html;
+
+/**
+ * 正文里原始 HTML 的白名单。
+ *
+ * v2 把原始 HTML 原样交给前端(XmlToReact 逐个 createElement),任何标签、任何属性都能进 DOM。
+ * 这里收紧:
+ * - 认识的标签保留;脚本、iframe、svg、表单等连同内容一起丢掉
+ * - 不认识的标签(库里有 `<nt>`、`<r>`、`<commentary>` 等自定义标签)改成 `span`,原名放 `data-tag`
+ * - 属性只留白名单,`style` 与 `on*` 一律去掉;链接与图片地址只允许 http(s)、mailto、站内相对路径
+ */
+final class HtmlPolicy
+{
+    /** 认识的标签:保留原名 */
+    private const ALLOWED = [
+        'a', 'abbr', 'b', 'bdi', 'bdo', 'blockquote', 'br', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
+        'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'font', 'h1', 'h2', 'h3',
+        'h4', 'h5', 'h6', 'hr', 'i', 'img', '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',
+    ];
+
+    /** 已废弃的展示类标签:换成等价的容器 */
+    private const RENAMED = ['center' => 'div', 'font' => 'span'];
+
+    /** 连同内容一起丢掉 */
+    private const DROPPED = [
+        'script', 'style', 'iframe', 'frame', 'frameset', 'object', 'embed', 'applet', 'svg', 'math', 'form',
+        'input', 'button', 'select', 'textarea', 'option', 'template', 'noscript', 'link', 'meta', 'base',
+        'title', 'head', 'html', 'body', 'canvas', 'dialog', 'portal',
+    ];
+
+    /** 自闭合标签 */
+    public const VOID = ['br', 'hr', 'img', 'wbr', 'col', 'source'];
+
+    /** role / tabindex / aria-*:阅读页注入的可点击图标(评估对勾、issue 叹号)要靠它们支持键盘与读屏 */
+    private const GLOBAL_ATTRS = ['class', 'title', 'lang', 'dir', 'role', 'tabindex'];
+
+    private const TAG_ATTRS = [
+        'a' => ['href'],
+        'img' => ['src', 'alt', 'width', 'height'],
+        'video' => ['src', 'controls', 'width', 'height', 'poster'],
+        'audio' => ['src', 'controls'],
+        'source' => ['src', 'type'],
+        'td' => ['colspan', 'rowspan', 'align'],
+        'th' => ['colspan', 'rowspan', 'align'],
+        'ol' => ['start'],
+        'details' => ['open'],
+    ];
+
+    private const URL_ATTRS = ['href', 'src', 'poster'];
+
+    /**
+     * 标签的去向。
+     *
+     * @return string|false|null string:保留并用这个名字;null:改成 span(原名放 data-tag);false:连同内容丢掉
+     */
+    public static function tag(string $tag): string|false|null
+    {
+        $tag = strtolower($tag);
+        if (in_array($tag, self::DROPPED, true)) {
+            return false;
+        }
+        if (in_array($tag, self::ALLOWED, true)) {
+            return self::RENAMED[$tag] ?? $tag;
+        }
+
+        return null;
+    }
+
+    /**
+     * 过滤属性。
+     *
+     * @param  array<string, string>  $attrs  原始属性(键已小写)
+     * @return array<string, string>
+     */
+    public static function attrs(string $tag, array $attrs): array
+    {
+        $allowed = array_merge(self::GLOBAL_ATTRS, self::TAG_ATTRS[$tag] ?? []);
+        $clean = [];
+        foreach ($attrs as $name => $value) {
+            $name = strtolower($name);
+            $isData = preg_match('/^(data|aria)-[a-z0-9][a-z0-9-]*$/', $name) === 1;
+            if (! $isData && ! in_array($name, $allowed, true)) {
+                continue;
+            }
+            if (in_array($name, self::URL_ATTRS, true)) {
+                $value = self::url($value);
+                if ($value === null) {
+                    continue;
+                }
+            }
+            $clean[$name] = $value;
+        }
+
+        return $clean;
+    }
+
+    /**
+     * 地址白名单:http(s)、mailto、站内绝对 / 相对路径、锚点。其余(javascript:、data: 等)返回 null。
+     */
+    public static function url(string $url): ?string
+    {
+        $url = trim($url);
+        // 去掉控制字符与空白后再判断协议,防 `java\tscript:` 之类绕过
+        $probe = strtolower((string) preg_replace('/[\x00-\x20]+/', '', $url));
+        if (preg_match('/^[a-z][a-z0-9+.-]*:/', $probe, $m) !== 1) {
+            return $url;
+        }
+
+        return in_array($m[0], ['http:', 'https:', 'mailto:'], true) ? $url : null;
+    }
+}

+ 81 - 0
api-v13/app/Services/Markup/Html/InlineHtmlAssembler.php

@@ -0,0 +1,81 @@
+<?php
+
+namespace App\Services\Markup\Html;
+
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+
+/**
+ * 把行内节点序列里散落的 HTML 开 / 闭标签重新配成嵌套元素。
+ *
+ * 闭标签找栈里最近的同名元素,中间没闭合的一并闭合;找不到的闭标签忽略;到结尾仍未闭合的就地闭合。
+ * 被 {@see HtmlPolicy} 丢掉的标签,直到它闭合为止的内容也一起丢掉。
+ */
+final class InlineHtmlAssembler
+{
+    /** @var list<Node> */
+    private array $root = [];
+
+    /** @var list<array{tag: string, element: Element|null}> element 为 null 表示被丢掉的标签 */
+    private array $stack = [];
+
+    public function add(Node $node): void
+    {
+        foreach ($this->stack as $frame) {
+            if ($frame['element'] === null) {
+                return;
+            }
+        }
+        $top = end($this->stack);
+        if ($top === false) {
+            $this->root[] = $node;
+        } else {
+            $top['element']->children[] = $node;
+        }
+    }
+
+    public function tag(string $literal): void
+    {
+        $tag = HtmlFragment::tagLiteral($literal);
+        if ($tag['kind'] === 'close') {
+            $this->close($tag['tag']);
+
+            return;
+        }
+        if ($tag['kind'] !== 'open') {
+            return;
+        }
+        $element = HtmlFragment::element($tag['tag'], $tag['attrs']);
+        $void = $tag['selfClosing'] || in_array($tag['tag'], HtmlPolicy::VOID, true);
+        if ($element === false) {
+            if (! $void) {
+                $this->stack[] = ['tag' => $tag['tag'], 'element' => null];
+            }
+
+            return;
+        }
+        $this->add($element);
+        if (! $void) {
+            $this->stack[] = ['tag' => $tag['tag'], 'element' => $element];
+        }
+    }
+
+    private function close(string $tag): void
+    {
+        for ($i = count($this->stack) - 1; $i >= 0; $i--) {
+            if ($this->stack[$i]['tag'] === $tag) {
+                $this->stack = array_slice($this->stack, 0, $i);
+
+                return;
+            }
+        }
+    }
+
+    /**
+     * @return list<Node>
+     */
+    public function nodes(): array
+    {
+        return $this->root;
+    }
+}

+ 19 - 0
api-v13/app/Services/Markup/Ir/Boundary.php

@@ -0,0 +1,19 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+use App\Services\Markup\Annotation\RangeWrapper;
+
+/**
+ * 批注区间的边界(开 / 闭),只在 IR 构建期间存在:
+ * {@see RangeWrapper} 把配对的边界换成包住中间内容的模板调用。
+ * 配不上对的边界被丢掉,渲染器不认识它。
+ */
+final class Boundary implements Node
+{
+    public function __construct(
+        public int $pair,
+        public bool $open,
+        public ?Call $call = null,
+    ) {}
+}

+ 58 - 0
api-v13/app/Services/Markup/Ir/Call.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+use App\Services\Markup\Resolve\Resolver;
+use App\Services\Markup\Templates\Template;
+
+/**
+ * 一次模板调用:`{{name|a|b=c}}`、`[[term]]`、`` `note` ``、```note、```mermaid 都落成它。
+ *
+ * 参数原样保存;声明为 markdown 的参数(如脚注正文)在解析时就递归解析成 slot。
+ * 取数阶段({@see Resolver})把查到的数据放进 $data。
+ */
+final class Call implements Node
+{
+    /** @var array<string, mixed> 取数结果,由模板自己约定键名 */
+    public array $data = [];
+
+    /**
+     * @param  string  $name  源码里写的名字(别名也原样保留,如 `n`、`ql`)
+     * @param  array<string, Document>  $slots  markdown 参数解析出的内容
+     * @param  string  $raw  源码原文(`{{…}}` 整段),未知模板与超深嵌套时原样输出
+     */
+    public function __construct(
+        public string $name,
+        public Template $template,
+        public Params $params,
+        public array $slots,
+        public Scope $scope,
+        public string $raw,
+    ) {}
+
+    /**
+     * 按「命名参数优先、其次位置参数、最后默认值」取参数,去首尾空白(v2 的 get_param)。
+     */
+    public function param(string $name, ?string $default = null): ?string
+    {
+        $spec = $this->template->params()[$name] ?? null;
+
+        return $this->params->get($name, $spec?->position, $default ?? $spec?->default ?? '');
+    }
+
+    public function slot(string $name): ?Document
+    {
+        return $this->slots[$name] ?? null;
+    }
+
+    /**
+     * 换掉一个命名参数,返回新的调用(逐段对读复制段落时用)。
+     */
+    public function withParam(string $name, string $value): self
+    {
+        $copy = clone $this;
+        $copy->params = $this->params->with($name, $value);
+
+        return $copy;
+    }
+}

+ 39 - 0
api-v13/app/Services/Markup/Ir/Document.php

@@ -0,0 +1,39 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+/**
+ * 一段内容的解析结果。
+ *
+ * - nodes:块级节点;inline 为真时整段只有一个段落,nodes 是该段落的行内节点(v2 的「单个 p 换成 span」)
+ * - source:预扫描后的源码,模板位置是占位符 `\u{E000}n\u{E001}`,n 是 calls 的下标(markdown 输出用)
+ * - calls:这段内容直接包含的全部模板调用(不含参数里嵌套的;那些在各自的 slot Document 里)
+ * - fragment:一段行内节点的切片(如 issue 高亮包住的内容),原样渲染:html 不包 span、纯文本不按块换行
+ */
+final class Document
+{
+    /**
+     * @param  list<Node>  $nodes
+     * @param  array<int, Call>  $calls
+     * @param  array<int, Call>  $annotationCalls  批注占位符下标 => 调用(只有点标记;markdown 输出替换源码里的占位符用)
+     */
+    public function __construct(
+        public array $nodes,
+        public bool $inline,
+        public string $source,
+        public array $calls,
+        public Scope $scope,
+        public bool $fragment = false,
+        public array $annotationCalls = [],
+    ) {}
+
+    public static function empty(Scope $scope): self
+    {
+        return new self([], true, '', [], $scope);
+    }
+
+    public function isEmpty(): bool
+    {
+        return $this->nodes === [];
+    }
+}

+ 21 - 0
api-v13/app/Services/Markup/Ir/Element.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+use App\Services\Markup\Html\HtmlPolicy;
+
+/**
+ * 普通 HTML 元素。tag 与属性都已经过 {@see HtmlPolicy} 白名单。
+ */
+final class Element implements Node
+{
+    /**
+     * @param  array<string, string>  $attrs
+     * @param  list<Node>  $children
+     */
+    public function __construct(
+        public string $tag,
+        public array $attrs = [],
+        public array $children = [],
+    ) {}
+}

+ 8 - 0
api-v13/app/Services/Markup/Ir/Node.php

@@ -0,0 +1,8 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+/**
+ * 中间表示(IR)节点:解析结果,未取数据、未定输出格式。三种:{@see Element}、{@see Text}、{@see Call}。
+ */
+interface Node {}

+ 74 - 0
api-v13/app/Services/Markup/Ir/Params.php

@@ -0,0 +1,74 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+/**
+ * 模板参数表。
+ *
+ * 命名参数 `name=value` 与位置参数并存;位置序号按全部参数的顺序计(命名参数也占位),
+ * 与 v2 一致:`{{note|text=a|①}}` 里 ① 是第 2 个参数。
+ */
+final class Params
+{
+    /**
+     * @param  array<string, string>  $named
+     * @param  array<int, string>  $positional  1 起
+     */
+    public function __construct(
+        public array $named = [],
+        public array $positional = [],
+    ) {}
+
+    public function get(string $name, ?int $position, ?string $default = ''): ?string
+    {
+        if (array_key_exists($name, $this->named)) {
+            return trim($this->named[$name]);
+        }
+        if ($position !== null && array_key_exists($position, $this->positional)) {
+            return trim($this->positional[$position]);
+        }
+
+        return $default;
+    }
+
+    /**
+     * 原值(不 trim),给 markdown 参数用。
+     */
+    public function raw(string $name, ?int $position): ?string
+    {
+        if (array_key_exists($name, $this->named)) {
+            return $this->named[$name];
+        }
+        if ($position !== null && array_key_exists($position, $this->positional)) {
+            return $this->positional[$position];
+        }
+
+        return null;
+    }
+
+    public function with(string $name, string $value): self
+    {
+        $copy = clone $this;
+        $copy->named[$name] = $value;
+
+        return $copy;
+    }
+
+    /**
+     * 全部参数,命名的用名字、位置的用序号字符串作键(Tpl 模板交给 Mustache 用)。
+     *
+     * @return array<string, string>
+     */
+    public function all(): array
+    {
+        $all = [];
+        foreach ($this->positional as $position => $value) {
+            $all[(string) $position] = trim($value);
+        }
+        foreach ($this->named as $name => $value) {
+            $all[$name] = trim($value);
+        }
+
+        return $all;
+    }
+}

+ 58 - 0
api-v13/app/Services/Markup/Ir/Scope.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+use App\Services\Markup\Dialect;
+
+/**
+ * 一段内容的上下文:属于哪些 channel、用哪种方言、在第几层内容里。
+ *
+ * 句子模板取回的译文、术语的 note、Tpl 模板的正文都是「另一段内容」,各自带新的 Scope(depth + 1)。
+ * 模板参数里的 markdown(如脚注正文)是同一段内容的一部分,沿用外层 Scope。
+ */
+final readonly class Scope
+{
+    /** 内容嵌套的最大层数:文章 → 句子译文 → 术语 note。再往下按纯文本输出(v2 是两层) */
+    public const MAX_DEPTH = 3;
+
+    /**
+     * @param  list<string>  $channels
+     * @param  bool  $inTermNote  这段内容是某个术语的 note:里面的术语不再取它们自己的 note(只展开一层,v2 口径)
+     */
+    public function __construct(
+        public array $channels = [],
+        public Dialect $dialect = Dialect::Markdown,
+        public int $depth = 1,
+        public string $channelType = 'translation',
+        public string $contentType = 'markdown',
+        public bool $inTermNote = false,
+    ) {}
+
+    public function firstChannel(): ?string
+    {
+        return $this->channels[0] ?? null;
+    }
+
+    /**
+     * 下一层内容的 Scope。
+     *
+     * @param  list<string>|null  $channels  null 表示沿用当前 channel
+     */
+    public function nested(?array $channels = null, ?string $contentType = null, string $channelType = 'translation'): self
+    {
+        $contentType ??= 'markdown';
+
+        return new self(
+            channels: $channels ?? $this->channels,
+            dialect: Dialect::fromContentType($contentType),
+            depth: $this->depth + 1,
+            channelType: $channelType,
+            contentType: $contentType,
+        );
+    }
+
+    public function canNest(): bool
+    {
+        return $this->depth < self::MAX_DEPTH;
+    }
+}

+ 11 - 0
api-v13/app/Services/Markup/Ir/Text.php

@@ -0,0 +1,11 @@
+<?php
+
+namespace App\Services\Markup\Ir;
+
+/**
+ * 纯文本(未转义)。
+ */
+final class Text implements Node
+{
+    public function __construct(public string $value) {}
+}

+ 145 - 0
api-v13/app/Services/Markup/MarkupService.php

@@ -0,0 +1,145 @@
+<?php
+
+namespace App\Services\Markup;
+
+use App\Services\Markup\Annotation\AnnotationSet;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Scope;
+use App\Services\Markup\Parsing\MarkupParser;
+use App\Services\Markup\Render\HtmlRenderer;
+use App\Services\Markup\Render\MarkdownRenderer;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Render\Renderer;
+use App\Services\Markup\Render\TextRenderer;
+use App\Services\Markup\Render\TreeRenderer;
+use App\Services\Markup\Resolve\Resolver;
+
+/**
+ * wikipali 正文(markdown + 类维基模板)的解析与渲染。取代 v2 的 `App\Http\Api\MdRender` + `TemplateRender`
+ * (v2 继续用旧代码,不改)。
+ *
+ * 三段式:解析成 IR({@see MarkupParser},纯函数)→ 批量取数({@see Resolver})→ 按格式输出({@see Renderer})。
+ * 一次渲染多段内容用 {@see renderMany()},所有段落里的术语、句子合在一起查。
+ *
+ * ```php
+ * $tree = $markup->render($sentence->content, new RenderOptions(
+ *     format: Format::Tree,
+ *     channels: [$sentence->channel_uid],
+ *     contentType: $sentence->content_type,
+ * ));
+ * ```
+ */
+final class MarkupService
+{
+    public function __construct(private readonly MarkupParser $parser) {}
+
+    /**
+     * 只解析不取数(测试、静态分析用)。
+     */
+    public function parse(string $source, RenderOptions $options): Document
+    {
+        return $this->parser->parse($source, $this->scope($options), $options->paragraph);
+    }
+
+    /**
+     * @return list<array<string, mixed>>|string tree 格式返回节点数组,其余返回字符串
+     */
+    public function render(?string $source, RenderOptions $options): array|string
+    {
+        return $this->renderMany(['content' => $source], $options)['content'];
+    }
+
+    /**
+     * 批量渲染。每项可以是源码字符串,或带自己 channel / content_type 的数组(如一章里各句来自不同 channel)。
+     *
+     * @template K of array-key
+     *
+     * @param  array<K, string|null|array{source: ?string, channels?: list<string>, contentType?: string, channelType?: string, annotations?: AnnotationSet, idPrefix?: string}>  $items
+     * @return array<K, list<array<string, mixed>>|string>
+     */
+    public function renderMany(array $items, RenderOptions $options): array
+    {
+        return $this->renderManyAs($items, $options, [$options->format])[$options->format->value];
+    }
+
+    /**
+     * 同一批内容按多种格式输出(如 discussions 同时要节点树与纯文本摘要):解析与取数只做一次。
+     *
+     * @template K of array-key
+     *
+     * @param  array<K, string|null|array{source: ?string, channels?: list<string>, contentType?: string, channelType?: string, annotations?: AnnotationSet, idPrefix?: string}>  $items
+     * @param  list<Format>  $formats
+     * @return array<string, array<K, list<array<string, mixed>>|string>> 格式名 => 各项结果
+     */
+    public function renderManyAs(array $items, RenderOptions $options, array $formats): array
+    {
+        $resolver = new Resolver($options, $this->parser);
+        $documents = [];
+        $idPrefixes = [];
+        foreach ($items as $key => $item) {
+            $itemOptions = is_array($item) ? $options->with(array_intersect_key($item, array_flip(['channels', 'contentType', 'channelType']))) : $options;
+            $source = is_array($item) ? $item['source'] : $item;
+            $annotations = is_array($item) ? ($item['annotations'] ?? null) : null;
+            $idPrefixes[$key] = is_array($item) && isset($item['idPrefix']) ? (string) $item['idPrefix'] : null;
+            $document = $this->parser->parse((string) $source, $this->scope($itemOptions), $options->paragraph, 0, $annotations);
+            $resolver->collect($document);
+            $documents[$key] = $document;
+        }
+        $resolver->run();
+
+        $output = [];
+        foreach ($formats as $format) {
+            $output[$format->value] = $this->output($documents, $options->with(['format' => $format]), $resolver, $idPrefixes);
+        }
+
+        return $output;
+    }
+
+    /**
+     * @template K of array-key
+     *
+     * @param  array<K, Document>  $documents
+     * @param  array<K, string|null>  $idPrefixes  各项 HTML id 的前缀;没给的取内容的短哈希
+     * @return array<K, list<array<string, mixed>>|string>
+     */
+    private function output(array $documents, RenderOptions $options, Resolver $resolver, array $idPrefixes): array
+    {
+        $renderer = $this->renderer($options->format);
+        $output = [];
+        foreach ($documents as $key => $document) {
+            $idPrefix = $idPrefixes[$key] ?? substr(md5($key.'|'.$document->source), 0, 8);
+            $ctx = new RenderContext($options, $resolver, $renderer, $idPrefix);
+            $rendered = $renderer->document($document, $ctx);
+            if (is_string($rendered) && $options->footnote) {
+                $rendered .= match (true) {
+                    $renderer instanceof HtmlRenderer => $renderer->footnotes($ctx),
+                    $renderer instanceof MarkdownRenderer => $renderer->footnotes($ctx),
+                    default => '',
+                };
+            }
+            $output[$key] = $rendered;
+        }
+
+        return $output;
+    }
+
+    private function scope(RenderOptions $options): Scope
+    {
+        return new Scope(
+            channels: array_values($options->channels),
+            dialect: $options->dialect(),
+            channelType: $options->channelType,
+            contentType: $options->contentType,
+        );
+    }
+
+    private function renderer(Format $format): Renderer
+    {
+        return match ($format) {
+            Format::Tree => new TreeRenderer,
+            Format::Html => new HtmlRenderer,
+            Format::Markdown => new MarkdownRenderer,
+            Format::Text, Format::Simple, Format::Prompt => new TextRenderer($format),
+        };
+    }
+}

+ 102 - 0
api-v13/app/Services/Markup/Parsing/CjkFriendlyEmphasisParser.php

@@ -0,0 +1,102 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+use League\CommonMark\Delimiter\Delimiter;
+use League\CommonMark\Environment\EnvironmentAwareInterface;
+use League\CommonMark\Environment\EnvironmentInterface;
+use League\CommonMark\Node\Inline\Text;
+use League\CommonMark\Parser\Inline\InlineParserInterface;
+use League\CommonMark\Parser\Inline\InlineParserMatch;
+use League\CommonMark\Parser\InlineParserContext;
+use League\CommonMark\Util\RegexHelper;
+
+/**
+ * `*` / `**` 强调的分隔符解析,按 markdown-cjk-friendly 提案放宽了「贴合」(flanking)规则。
+ *
+ * CommonMark 的规则为空格分词的语言设计:开头的 `**` 后面紧跟标点时,前面必须是空白或标点;
+ * 结尾的 `**` 前面紧挨标点时,后面必须是空白或标点。中文没有空格,粗体又常常把引号、括号包在里面,
+ * `从**“tuccha”**的角度` 两头都不成立,`**` 原样露出来。
+ *
+ * 放宽:在「紧挨着标点」的那一侧,中日韩字符(汉字、假名、谚文、注音)与空白同等对待。
+ * 两侧都不是 CJK 字符时,判断与 CommonMark 完全相同。
+ * 参考:https://github.com/tats-u/markdown-cjk-friendly
+ *
+ * 只接管 `*`:`_` 有词内不能强调的规则,中文正文也很少用;`~~` 删除线暂不处理。
+ * 逻辑照 league/commonmark 的 DelimiterParser(final、@internal,不能继承),只换了判断开闭的那一步;
+ * 配对与生成强调节点仍由原来的 EmphasisDelimiterProcessor 做。
+ */
+final class CjkFriendlyEmphasisParser implements EnvironmentAwareInterface, InlineParserInterface
+{
+    private const CJK = '/^[\p{Han}\p{Hiragana}\p{Katakana}\p{Hangul}\p{Bopomofo}]/u';
+
+    private EnvironmentInterface $environment;
+
+    public function setEnvironment(EnvironmentInterface $environment): void
+    {
+        $this->environment = $environment;
+    }
+
+    public function getMatchDefinition(): InlineParserMatch
+    {
+        return InlineParserMatch::string('*');
+    }
+
+    public function parse(InlineParserContext $inlineContext): bool
+    {
+        $processor = $this->environment->getDelimiterProcessors()->getDelimiterProcessor('*');
+        if ($processor === null) {
+            return false;
+        }
+        $cursor = $inlineContext->getCursor();
+        $charBefore = $cursor->peek(-1) ?? "\n";
+
+        $count = 0;
+        while ($cursor->peek($count) === '*') {
+            $count++;
+        }
+        if ($count < $processor->getMinLength()) {
+            return false;
+        }
+        $cursor->advanceBy($count);
+        $charAfter = $cursor->getCurrentCharacter() ?? "\n";
+
+        [$canOpen, $canClose] = self::flanking($charBefore, $charAfter);
+        $canOpen = $canOpen && $processor->getOpeningCharacter() === '*';
+        $canClose = $canClose && $processor->getClosingCharacter() === '*';
+
+        if (! $canOpen && ! $canClose) {
+            $inlineContext->getContainer()->appendChild(new Text(str_repeat('*', $count)));
+
+            return true;
+        }
+
+        $node = new Text(str_repeat('*', $count), ['delim' => true]);
+        $inlineContext->getContainer()->appendChild($node);
+        $inlineContext->getDelimiterStack()->push(
+            new Delimiter('*', $count, $node, $canOpen, $canClose, $cursor->getPosition())
+        );
+
+        return true;
+    }
+
+    /**
+     * 左贴合(能开)与右贴合(能闭)。与 CommonMark 的区别只在各自第二个条件里多了「或者另一侧是 CJK 字符」。
+     *
+     * @return array{0: bool, 1: bool}
+     */
+    public static function flanking(string $before, string $after): array
+    {
+        $afterSpace = preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $after) === 1;
+        $afterPunct = preg_match(RegexHelper::REGEX_PUNCTUATION, $after) === 1;
+        $beforeSpace = preg_match(RegexHelper::REGEX_UNICODE_WHITESPACE_CHAR, $before) === 1;
+        $beforePunct = preg_match(RegexHelper::REGEX_PUNCTUATION, $before) === 1;
+        $beforeCjk = preg_match(self::CJK, $before) === 1;
+        $afterCjk = preg_match(self::CJK, $after) === 1;
+
+        $left = ! $afterSpace && (! $afterPunct || $beforeSpace || $beforePunct || $beforeCjk);
+        $right = ! $beforeSpace && (! $beforePunct || $afterSpace || $afterPunct || $afterCjk);
+
+        return [$left, $right];
+    }
+}

+ 390 - 0
api-v13/app/Services/Markup/Parsing/IrBuilder.php

@@ -0,0 +1,390 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+use App\Services\Markup\Annotation\AnnotationSet;
+use App\Services\Markup\Annotation\AnnotationToken;
+use App\Services\Markup\Annotation\AnnotationTokenNode;
+use App\Services\Markup\Annotation\RangeWrapper;
+use App\Services\Markup\Html\HtmlFragment;
+use App\Services\Markup\Html\HtmlPolicy;
+use App\Services\Markup\Html\InlineHtmlAssembler;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Scope;
+use App\Services\Markup\Ir\Text;
+use App\Services\Markup\Templates\NoteTemplate;
+use Closure;
+use League\CommonMark\Extension\CommonMark\Node\Block\BlockQuote;
+use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
+use League\CommonMark\Extension\CommonMark\Node\Block\Heading;
+use League\CommonMark\Extension\CommonMark\Node\Block\HtmlBlock;
+use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode;
+use League\CommonMark\Extension\CommonMark\Node\Block\ListBlock;
+use League\CommonMark\Extension\CommonMark\Node\Block\ListItem;
+use League\CommonMark\Extension\CommonMark\Node\Block\ThematicBreak;
+use League\CommonMark\Extension\CommonMark\Node\Inline\Code;
+use League\CommonMark\Extension\CommonMark\Node\Inline\Emphasis;
+use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline;
+use League\CommonMark\Extension\CommonMark\Node\Inline\Image;
+use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
+use League\CommonMark\Extension\CommonMark\Node\Inline\Strong;
+use League\CommonMark\Extension\Strikethrough\Strikethrough;
+use League\CommonMark\Extension\Table\Table;
+use League\CommonMark\Extension\Table\TableCell;
+use League\CommonMark\Extension\Table\TableRow;
+use League\CommonMark\Extension\Table\TableSection;
+use League\CommonMark\Extension\TaskList\TaskListItemMarker;
+use League\CommonMark\Node\Block\Paragraph;
+use League\CommonMark\Node\Inline\Newline;
+use League\CommonMark\Node\Inline\Text as MdText;
+use League\CommonMark\Node\Node as MdNode;
+
+/**
+ * CommonMark AST → IR。
+ *
+ * 除了逐个节点对译,还做四件事:
+ * - 占位符换回模板调用;代码里的占位符换回源码原文
+ * - ```mermaid 变成 mermaid 模板;`<li><div>…</div></li>` 变成 toggle 模板(v2 的「可展开」)
+ * - 只有脚注的段落并到上一段末尾(```note 前后都是空行时)
+ * - 原始 HTML 过白名单
+ */
+final class IrBuilder
+{
+    private int $headingCount = 0;
+
+    /**
+     * @param  array<int, Call>  $calls  占位符下标 => 调用
+     * @param  array<int, string>  $raws  占位符下标 => 源码原文
+     * @param  Closure(string, list<string>, string): Call  $makeCall  建内部生成的调用(mermaid、toggle)
+     * @param  (Closure(int): ?Node)|null  $annotation  批注占位符下标 → 模板调用或区间边界({@see AnnotationSet})
+     */
+    public function __construct(
+        private readonly array $calls,
+        private readonly array $raws,
+        private readonly Closure $makeCall,
+        private readonly Scope $scope,
+        private readonly string $headingSeed,
+        private readonly ?Closure $annotation = null,
+    ) {}
+
+    /**
+     * @return array{0: list<Node>, 1: bool} [节点, 是否单段落(行内)]
+     */
+    public function build(MdNode $document): array
+    {
+        $blocks = $this->blocks($document);
+        if ($this->annotation !== null) {
+            $blocks = RangeWrapper::apply($blocks, $this->scope);
+        }
+        if (count($blocks) === 1 && $blocks[0] instanceof Element && $blocks[0]->tag === 'p') {
+            return [$blocks[0]->children, true];
+        }
+
+        return [$blocks, $blocks === []];
+    }
+
+    /**
+     * @return list<Node>
+     */
+    private function blocks(MdNode $container, bool $tight = false): array
+    {
+        $out = [];
+        foreach ($container->children() as $child) {
+            if ($child instanceof Paragraph) {
+                $inlines = $this->inlines($child);
+                if ($tight) {
+                    array_push($out, ...$inlines);
+
+                    continue;
+                }
+                $previous = end($out);
+                if ($this->onlyNotes($inlines) && $previous instanceof Element && $previous->tag === 'p') {
+                    array_push($previous->children, ...$this->trimWhitespace($inlines));
+
+                    continue;
+                }
+                if ($inlines !== []) {
+                    $out[] = new Element('p', [], $inlines);
+                }
+
+                continue;
+            }
+            array_push($out, ...$this->block($child));
+        }
+
+        return $out;
+    }
+
+    /**
+     * @return list<Node>
+     */
+    private function block(MdNode $node): array
+    {
+        return match (true) {
+            $node instanceof Heading => [$this->heading($node)],
+            $node instanceof BlockQuote => [new Element('blockquote', [], $this->blocks($node))],
+            $node instanceof ListBlock => [$this->listBlock($node)],
+            $node instanceof FencedCode => [$this->fencedCode($node)],
+            $node instanceof IndentedCode => [$this->code($node->getLiteral(), '')],
+            $node instanceof HtmlBlock => HtmlFragment::parseBlock($node->getLiteral(), $this->expandText(...)),
+            $node instanceof ThematicBreak => [new Element('hr')],
+            $node instanceof Table => [new Element('table', [], $this->tableChildren($node))],
+            default => $this->blocks($node),
+        };
+    }
+
+    private function heading(Heading $node): Element
+    {
+        $this->headingCount++;
+        $id = 'h-'.substr(md5($this->headingSeed), 0, 8).'-'.$this->headingCount;
+
+        return new Element('h'.$node->getLevel(), ['id' => $id], $this->inlines($node));
+    }
+
+    private function listBlock(ListBlock $node): Element
+    {
+        $data = $node->getListData();
+        $ordered = $data->type === ListBlock::TYPE_ORDERED;
+        $attrs = $ordered && $data->start !== null && $data->start !== 1 ? ['start' => (string) $data->start] : [];
+        $items = [];
+        foreach ($node->children() as $item) {
+            if ($item instanceof ListItem) {
+                $items[] = $this->listItem($this->blocks($item, $node->isTight()));
+            }
+        }
+
+        return new Element($ordered ? 'ol' : 'ul', $attrs, $items);
+    }
+
+    /**
+     * 列表项里只有一个 `<div>` 时变成 toggle(v2 react 格式的后处理,前端渲染成可展开的树)。
+     *
+     * @param  list<Node>  $children
+     */
+    private function listItem(array $children): Element
+    {
+        $significant = $this->trimWhitespace($children);
+        if (count($significant) === 1 && $significant[0] instanceof Element && $significant[0]->tag === 'div') {
+            $toggle = ($this->makeCall)('toggle', [], '');
+            $toggle->slots['content'] = new Document($significant, false, '', [], $this->scope);
+
+            return new Element('li', [], [$toggle]);
+        }
+
+        return new Element('li', [], $children);
+    }
+
+    private function fencedCode(FencedCode $node): Node
+    {
+        $words = $node->getInfoWords();
+        $language = strtolower($words[0] ?? '');
+        $literal = AnnotationToken::strip(Placeholder::restore($node->getLiteral(), $this->raws));
+        if ($language === 'mermaid') {
+            return ($this->makeCall)('mermaid', [rtrim($literal, "\n")], "```mermaid\n{$literal}```");
+        }
+
+        return $this->code($literal, $language);
+    }
+
+    private function code(string $literal, string $language): Element
+    {
+        $literal = AnnotationToken::strip(Placeholder::restore($literal, $this->raws));
+        $attrs = $language !== '' ? ['class' => 'language-'.$language] : [];
+
+        return new Element('pre', [], [new Element('code', $attrs, [new Text($literal)])]);
+    }
+
+    /**
+     * @return list<Node>
+     */
+    private function tableChildren(Table $table): array
+    {
+        $sections = [];
+        foreach ($table->children() as $section) {
+            if (! $section instanceof TableSection) {
+                continue;
+            }
+            $rows = [];
+            foreach ($section->children() as $row) {
+                if (! $row instanceof TableRow) {
+                    continue;
+                }
+                $cells = [];
+                foreach ($row->children() as $cell) {
+                    if ($cell instanceof TableCell) {
+                        $tag = $cell->getType() === TableCell::TYPE_HEADER ? 'th' : 'td';
+                        $attrs = $cell->getAlign() !== null ? ['align' => $cell->getAlign()] : [];
+                        $cells[] = new Element($tag, $attrs, $this->inlines($cell));
+                    }
+                }
+                $rows[] = new Element('tr', [], $cells);
+            }
+            $sections[] = new Element($section->isHead() ? 'thead' : 'tbody', [], $rows);
+        }
+
+        return $sections;
+    }
+
+    /**
+     * @return list<Node>
+     */
+    private function inlines(MdNode $container): array
+    {
+        $assembler = new InlineHtmlAssembler;
+        foreach ($container->children() as $child) {
+            if ($child instanceof HtmlInline) {
+                $assembler->tag($child->getLiteral());
+
+                continue;
+            }
+            foreach ($this->inline($child) as $node) {
+                $assembler->add($node);
+            }
+        }
+
+        return $assembler->nodes();
+    }
+
+    /**
+     * @return list<Node>
+     */
+    private function inline(MdNode $node): array
+    {
+        return match (true) {
+            $node instanceof PlaceholderNode => [$this->call($node->index)],
+            $node instanceof AnnotationTokenNode => $this->annotationNode($node->index),
+            $node instanceof MdText => [new Text($node->getLiteral())],
+            $node instanceof Newline => $node->getType() === Newline::HARDBREAK ? [new Element('br')] : [new Text("\n")],
+            $node instanceof Code => [new Element('code', [], [new Text(AnnotationToken::strip(Placeholder::restore($node->getLiteral(), $this->raws)))])],
+            $node instanceof Emphasis => [new Element('em', [], $this->inlines($node))],
+            $node instanceof Strong => [new Element('strong', [], $this->inlines($node))],
+            $node instanceof Strikethrough => [new Element('del', [], $this->inlines($node))],
+            $node instanceof Link => [$this->link($node)],
+            $node instanceof Image => [$this->image($node)],
+            $node instanceof TaskListItemMarker => [new Element('input', array_filter([
+                'type' => 'checkbox',
+                'disabled' => 'disabled',
+                'checked' => $node->isChecked() ? 'checked' : null,
+            ]))],
+            default => $this->inlines($node),
+        };
+    }
+
+    private function link(Link $node): Element
+    {
+        $attrs = [];
+        $url = HtmlPolicy::url(AnnotationToken::strip(Placeholder::restore($node->getUrl(), $this->raws)));
+        if ($url !== null) {
+            $attrs['href'] = $url;
+        }
+        if (($node->getTitle() ?? '') !== '') {
+            $attrs['title'] = (string) $node->getTitle();
+        }
+
+        return new Element('a', $attrs, $this->inlines($node));
+    }
+
+    private function image(Image $node): Element
+    {
+        $attrs = [];
+        $url = HtmlPolicy::url(AnnotationToken::strip(Placeholder::restore($node->getUrl(), $this->raws)));
+        if ($url !== null) {
+            $attrs['src'] = $url;
+        }
+        $attrs['alt'] = $this->plainText($node);
+        if (($node->getTitle() ?? '') !== '') {
+            $attrs['title'] = (string) $node->getTitle();
+        }
+
+        return new Element('img', $attrs);
+    }
+
+    private function plainText(MdNode $node): string
+    {
+        $text = '';
+        foreach ($node->iterator() as $child) {
+            if ($child instanceof MdText || $child instanceof Code) {
+                $text .= $child->getLiteral();
+            }
+        }
+
+        return AnnotationToken::strip(Placeholder::restore($text, $this->raws));
+    }
+
+    /**
+     * @return list<Node>
+     */
+    private function annotationNode(int $index): array
+    {
+        $node = $this->annotation === null ? null : ($this->annotation)($index);
+
+        return $node === null ? [] : [$node];
+    }
+
+    private function call(int $index): Node
+    {
+        return $this->calls[$index] ?? new Text('');
+    }
+
+    /**
+     * HTML 块里的文字:展开模板占位符(`<nt>{{65-464-2-27}}</nt>` 里的句子模板照常渲染)。
+     *
+     * @return list<Node>
+     */
+    private function expandText(string $text): array
+    {
+        $nodes = [];
+        $parts = preg_split(Placeholder::PATTERN, $text, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
+        foreach ($parts as $i => $part) {
+            if ($i % 2 === 1) {
+                $nodes[] = $this->call((int) $part);
+
+                continue;
+            }
+            // 批注占位符
+            $pieces = preg_split(AnnotationToken::PATTERN, $part, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
+            foreach ($pieces as $j => $piece) {
+                if ($j % 2 === 1) {
+                    array_push($nodes, ...$this->annotationNode((int) $piece));
+                } elseif ($piece !== '') {
+                    $nodes[] = new Text($piece);
+                }
+            }
+        }
+
+        return $nodes;
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     */
+    private function onlyNotes(array $nodes): bool
+    {
+        $significant = $this->trimWhitespace($nodes);
+        if ($significant === []) {
+            return false;
+        }
+        foreach ($significant as $node) {
+            if (! $node instanceof Call || ! $node->template instanceof NoteTemplate) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     * @return list<Node>
+     */
+    private function trimWhitespace(array $nodes): array
+    {
+        return array_values(array_filter(
+            $nodes,
+            fn (Node $node) => ! ($node instanceof Text && trim($node->value) === ''),
+        ));
+    }
+}

+ 299 - 0
api-v13/app/Services/Markup/Parsing/MarkupParser.php

@@ -0,0 +1,299 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+use App\Services\Markup\Annotation\AnnotationSet;
+use App\Services\Markup\Annotation\AnnotationToken;
+use App\Services\Markup\Annotation\AnnotationTokenParser;
+use App\Services\Markup\Annotation\Marker;
+use App\Services\Markup\Dialect;
+use App\Services\Markup\Ir\Boundary;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Params;
+use App\Services\Markup\Ir\Scope;
+use App\Services\Markup\Ir\Text;
+use App\Services\Markup\Templates\SentTemplate;
+use App\Services\Markup\Templates\TemplateRegistry;
+use Illuminate\Support\Facades\Log;
+use League\CommonMark\Environment\Environment;
+use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
+use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
+use League\CommonMark\Parser\MarkdownParser;
+
+/**
+ * 源码 → {@see Document}(IR)。纯解析,不查库。
+ *
+ * 流程:清洗编码 → nissaya 转换 → {@see Preprocessor}(模板换占位符)→ CommonMark + GFM → {@see IrBuilder}。
+ * 两种方言共用同一个 CommonMark 环境:旧方言的反引号脚注在预扫描时已经换掉了,剩下的反引号照 CommonMark 处理。
+ */
+final class MarkupParser
+{
+    /** 模板参数里再嵌模板的最大层数 */
+    private const MAX_NESTING = 8;
+
+    private ?Environment $environment = null;
+
+    public function __construct(private readonly TemplateRegistry $registry) {}
+
+    /**
+     * @param  bool  $paragraphMode  巴汉逐段对读,见 {@see self::duplicateSentenceParagraphs()}
+     * @param  AnnotationSet|null  $annotations  源码里批注占位符对应的结构化标记(阅读页注入,见 {@see AnnotationSet})
+     */
+    public function parse(string $source, Scope $scope, bool $paragraphMode = false, int $nesting = 0, ?AnnotationSet $annotations = null): Document
+    {
+        $source = $this->clean($source);
+        if ($annotations === null) {
+            // 没有批注时源码里不该有批注占位符;有批注时,下标对不上的占位符解析时自然丢掉
+            $source = AnnotationToken::strip($source);
+        }
+        // 只转换内容本身;模板参数(如 nissaya json 里 note 的正文)不是 nissaya 行
+        if ($scope->channelType === 'nissaya' && $nesting === 0) {
+            $source = $this->nissayaToTemplates($source, $scope->contentType);
+        }
+        if (trim($source) === '') {
+            return Document::empty($scope);
+        }
+
+        $calls = [];
+        $raws = [];
+        $register = function (string $kind, string $raw, string $inner, string $info) use (&$calls, &$raws, $scope, $nesting): int {
+            $index = count($calls);
+            $raws[$index] = $raw;
+            $calls[$index] = $this->callFromSyntax($kind, $raw, $inner, $info, $scope, $nesting);
+
+            return $index;
+        };
+        $prepared = (new Preprocessor)->run($source, $scope->dialect, $register);
+
+        $ast = (new MarkdownParser($this->environment()))->parse($prepared);
+        $annotationCalls = [];
+        $annotation = $annotations === null ? null : function (int $index) use ($annotations, $scope, $nesting, &$annotationCalls): ?Node {
+            $node = $this->annotationNode($annotations->get($index), $scope, $nesting);
+            if ($node instanceof Call) {
+                $annotationCalls[$index] = $node;
+            }
+
+            return $node;
+        };
+        $builder = new IrBuilder(
+            $calls,
+            $raws,
+            fn (string $name, array $segments, string $raw) => $this->makeCall($name, $segments, $raw, $scope, $nesting),
+            $scope,
+            $source,
+            $annotation,
+        );
+        [$nodes, $inline] = $builder->build($ast);
+
+        if ($paragraphMode) {
+            $blocks = $inline ? [new Element('p', [], $nodes)] : $nodes;
+            $duplicated = $this->duplicateSentenceParagraphs($blocks);
+            if (count($duplicated) !== count($blocks)) {
+                [$nodes, $inline] = [$duplicated, false];
+            }
+        }
+
+        return new Document($nodes, $inline, $prepared, $calls, $scope, annotationCalls: $annotationCalls);
+    }
+
+    /**
+     * 批注标记 → IR:点 → 模板调用;区间开 → 带着(待填内容的)调用的边界;区间闭 → 边界。
+     */
+    private function annotationNode(?Marker $marker, Scope $scope, int $nesting): ?Node
+    {
+        if ($marker === null) {
+            return null;
+        }
+        if ($marker->kind === Marker::CLOSE) {
+            return new Boundary($marker->pair, false);
+        }
+        if ($marker->template === 'note') {
+            $template = $this->registry->get('note');
+            // 批注正文的方言跟批注那一行(discussions),不跟句子
+            $bodyScope = new Scope($scope->channels, Dialect::fromContentType($marker->bodyContentType), $scope->depth, 'translation', $marker->bodyContentType);
+            $body = (string) $marker->body;
+
+            return new Call('note', $template, new Params($marker->params, [1 => $body]), [
+                'text' => $this->parse($body, $bodyScope, false, $nesting + 1),
+            ], $scope, '');
+        }
+        $call = new Call($marker->template, $this->registry->internal($marker->template), new Params($marker->params), [], $scope, '');
+
+        return $marker->kind === Marker::OPEN ? new Boundary($marker->pair, true, $call) : $call;
+    }
+
+    /**
+     * @param  list<string>|Params  $params  参数片段,或已经分好的参数表(```note 的正文不再切 `|`)
+     */
+    public function makeCall(string $name, array|Params $params, string $raw, Scope $scope, int $nesting): Call
+    {
+        $template = $this->registry->get($name);
+        if (is_array($params)) {
+            $params = $template->parseParams($params, $scope->dialect);
+        }
+        $slots = [];
+        foreach ($template->params() as $paramName => $spec) {
+            if (! $spec->markdown) {
+                continue;
+            }
+            $value = $params->raw($paramName, $spec->position);
+            if ($value === null) {
+                continue;
+            }
+            $slots[$paramName] = $nesting < self::MAX_NESTING
+                ? $this->parse($value, $scope, false, $nesting + 1)
+                : new Document([new Text($value)], true, $value, [], $scope);
+        }
+
+        return new Call($name, $template, $params, $slots, $scope, $raw);
+    }
+
+    private function callFromSyntax(string $kind, string $raw, string $inner, string $info, Scope $scope, int $nesting): Call
+    {
+        return match ($kind) {
+            'wikilink' => $this->makeCall('term', TemplateSyntax::split('term|'.$inner)[1], $raw, $scope, $nesting),
+            'note-backtick' => $this->makeCall('note', TemplateSyntax::split('note|'.$inner)[1], $raw, $scope, $nesting),
+            'note-fence' => $this->makeCall('note', $this->fenceParams($inner, $info), $raw, $scope, $nesting),
+            default => $this->templateCall($inner, $raw, $scope, $nesting),
+        };
+    }
+
+    private function templateCall(string $inner, string $raw, Scope $scope, int $nesting): Call
+    {
+        // 句子简写 {{book-para-start-end}}(可带 @channel)
+        if (preg_match('/^\s*[0-9]/', $inner) === 1) {
+            return $this->makeCall('sent', new Params(['id' => trim($inner)]), $raw, $scope, $nesting);
+        }
+        [$name, $segments] = TemplateSyntax::split($inner);
+
+        return $this->makeCall($name, $segments, $raw, $scope, $nesting);
+    }
+
+    /**
+     * ```note 的参数:正文整段是第 1 个参数,info string 里的 `name="value"` 是命名参数。
+     */
+    private function fenceParams(string $inner, string $info): Params
+    {
+        $named = [];
+        preg_match_all('/([a-z]+)=(?:"([^"]*)"|(\S+))/', $info, $pairs, PREG_SET_ORDER);
+        foreach ($pairs as $pair) {
+            $named[$pair[1]] = ($pair[2] ?? '') !== '' ? $pair[2] : ($pair[3] ?? '');
+        }
+
+        return new Params($named, [1 => $inner]);
+    }
+
+    /**
+     * 只由句子模板组成的段落复制成两段:一段只显示原文、一段只显示译文(v2 的 preprocessingForParagraph)。
+     *
+     * @param  list<Node>  $nodes
+     * @return list<Node>
+     */
+    private function duplicateSentenceParagraphs(array $nodes): array
+    {
+        $out = [];
+        foreach ($nodes as $node) {
+            if (! $node instanceof Element || $node->tag !== 'p' || ! $this->onlySentences($node->children)) {
+                $out[] = $node;
+
+                continue;
+            }
+            foreach (['origin', 'translation'] as $show) {
+                $out[] = new Element('p', [], array_map(
+                    fn (Node $child) => $child instanceof Call ? $child->withParam('text', $show) : $child,
+                    $node->children,
+                ));
+            }
+        }
+
+        return $out;
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     */
+    private function onlySentences(array $nodes): bool
+    {
+        $found = false;
+        foreach ($nodes as $node) {
+            if ($node instanceof Call && $node->template instanceof SentTemplate) {
+                $found = true;
+            } elseif (! ($node instanceof Text && trim($node->value, " \t\n>") === '')) {
+                return false;
+            }
+        }
+
+        return $found;
+    }
+
+    private function clean(string $source): string
+    {
+        $source = (string) iconv('UTF-8', 'UTF-8//IGNORE', $source);
+        $source = str_replace(["\r\n", "\r"], "\n", $source);
+
+        return Placeholder::strip($source);
+    }
+
+    /**
+     * nissaya channel 的内容转成 nissaya 模板(v2 markdown2wiki 的 nissaya 段,口径不变)。
+     *
+     * - json:对齐后的 `{original, translation, note}`(translation 用 `>` 分层)或逐词解析的 wbw json
+     * - markdown:每行 `巴利=意思`(`$` 也当 `=`)
+     */
+    private function nissayaToTemplates(string $source, string $contentType): string
+    {
+        if ($contentType === 'json') {
+            $words = json_decode($source);
+            if (! is_array($words)) {
+                Log::error('nissaya json data is not array', ['data' => $source]);
+
+                return '';
+            }
+            $out = [];
+            foreach ($words as $word) {
+                if (isset($word->original)) {
+                    $out[] = '{{nissaya|'.$word->original.'|'.str_replace('>', '=', $word->translation ?? '').'}}';
+                    if (! empty($word->note)) {
+                        $out[] = '{{note|'.$word->note.'|[nt]}}';
+                    }
+                } elseif (isset($word->sn) && count($word->sn) === 1) {
+                    $out[] = '{{nissaya|'.($word->word->value ?? '').'|'.($word->meaning->value ?? '').'}}';
+                }
+            }
+
+            return implode('', $out);
+        }
+
+        $lines = [];
+        foreach (explode("\n", $source) as $line) {
+            if (! str_contains($line, '=') && ! str_contains($line, '$')) {
+                $lines[] = $line;
+
+                continue;
+            }
+            $parts = explode('=', str_replace('$', '=', $line));
+            $lines[] = '{{nissaya|'.$parts[0].'|'.implode('=', array_slice($parts, 1)).'}}';
+        }
+
+        return implode("\n", $lines);
+    }
+
+    private function environment(): Environment
+    {
+        if ($this->environment === null) {
+            $environment = new Environment(['html_input' => 'allow']);
+            $environment->addExtension(new CommonMarkCoreExtension);
+            $environment->addExtension(new GithubFlavoredMarkdownExtension);
+            $environment->addInlineParser(new PlaceholderParser, 250);
+            $environment->addInlineParser(new AnnotationTokenParser, 250);
+            // 抢在 CommonMark 自带的分隔符解析(最低优先级)之前处理 `*`:中文标点旁的粗体
+            $environment->addInlineParser(new CjkFriendlyEmphasisParser, 0);
+            $this->environment = $environment;
+        }
+
+        return $this->environment;
+    }
+}

+ 45 - 0
api-v13/app/Services/Markup/Parsing/Placeholder.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+/**
+ * 预扫描用的占位符:私用区字符包住模板调用的下标,`\u{E000}12\u{E001}`。
+ *
+ * CommonMark 把它当普通文字,所以模板里的 `|`、空行、列表符号都不会打断段落或表格;
+ * 解析完再由 {@see PlaceholderParser} 换回模板节点。
+ */
+final class Placeholder
+{
+    public const OPEN = "\u{E000}";
+
+    public const CLOSE = "\u{E001}";
+
+    public const PATTERN = '/'."\u{E000}".'(\d+)'."\u{E001}".'/u';
+
+    public static function make(int $index): string
+    {
+        return self::OPEN.$index.self::CLOSE;
+    }
+
+    /**
+     * 去掉源码里本来就有的占位符字符,免得与真占位符混淆。
+     */
+    public static function strip(string $source): string
+    {
+        return str_replace([self::OPEN, self::CLOSE], '', $source);
+    }
+
+    /**
+     * 把文字里的占位符换回源码原文(代码块、原始 HTML 属性等不该展开模板的地方用)。
+     *
+     * @param  array<int, string>  $raws  下标 => 原文
+     */
+    public static function restore(string $text, array $raws): string
+    {
+        return (string) preg_replace_callback(
+            self::PATTERN,
+            fn (array $m) => $raws[(int) $m[1]] ?? '',
+            $text,
+        );
+    }
+}

+ 17 - 0
api-v13/app/Services/Markup/Parsing/PlaceholderNode.php

@@ -0,0 +1,17 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+use App\Services\Markup\Ir\Call;
+use League\CommonMark\Node\Inline\AbstractInline;
+
+/**
+ * CommonMark AST 里的模板占位节点,只记下标;IR 构建时换成 {@see Call}。
+ */
+final class PlaceholderNode extends AbstractInline
+{
+    public function __construct(public readonly int $index)
+    {
+        parent::__construct();
+    }
+}

+ 28 - 0
api-v13/app/Services/Markup/Parsing/PlaceholderParser.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+use League\CommonMark\Parser\Inline\InlineParserInterface;
+use League\CommonMark\Parser\Inline\InlineParserMatch;
+use League\CommonMark\Parser\InlineParserContext;
+
+/**
+ * 把预扫描留下的占位符解析成 {@see PlaceholderNode}。
+ */
+final class PlaceholderParser implements InlineParserInterface
+{
+    public function getMatchDefinition(): InlineParserMatch
+    {
+        return InlineParserMatch::regex(Placeholder::OPEN.'(\d+)'.Placeholder::CLOSE);
+    }
+
+    public function parse(InlineParserContext $inlineContext): bool
+    {
+        $cursor = $inlineContext->getCursor();
+        [$index] = $inlineContext->getSubMatches();
+        $cursor->advanceBy($inlineContext->getFullMatchLength());
+        $inlineContext->getContainer()->appendChild(new PlaceholderNode((int) $index));
+
+        return true;
+    }
+}

+ 367 - 0
api-v13/app/Services/Markup/Parsing/Preprocessor.php

@@ -0,0 +1,367 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+use App\Services\Markup\Dialect;
+use Closure;
+
+/**
+ * 预扫描:在交给 CommonMark 之前,把模板类语法整段换成占位符。
+ *
+ * 换掉的有:
+ * - `{{…}}`:按 `{{` / `}}` 深度配对,可跨行、可含空行、可嵌套
+ * - `[[x]]`:术语,单行
+ * - ```note 围栏(旧方言里没有 info 的 ``` 围栏也是):整块变成脚注,紧挨着的上下文合进同一段(见 {@see self::joinFence()})
+ * - 旧方言的 `` `x` ``:脚注,单行
+ *
+ * 跳过不扫的:代码围栏(含 ```mermaid,交给 CommonMark);E2 方言的行内代码 `` `…` ``。
+ * 反斜杠转义 `\{{`、`\[[`、`` \` `` 原样保留,由 CommonMark 去掉反斜杠。
+ *
+ * 为什么不写成 CommonMark 的 inline parser:inline parser 只看得到一个段落,模板里的空行、
+ * 行首的 `- ` / `#`、表格里的 `|` 都会先被块解析切开。
+ */
+final class Preprocessor
+{
+    /** `{{` 的最大嵌套深度,与 v2 的 STACK_DEEP 一致 */
+    private const MAX_BRACE_DEPTH = 8;
+
+    private const CJK = '/[\p{Han}\p{Hiragana}\p{Katakana}\p{Hangul}\x{3000}-\x{303F}\x{FF00}-\x{FFEF}]/u';
+
+    /** 下一行以这些开头时是新的块,不并进脚注所在段落 */
+    private const BLOCK_START = '/^ {0,3}(#{1,6}(\s|$)|>|[-*+]\s|\d{1,9}[.)]\s|`{3,}|~{3,}|\||<|([-*_=])[ \t]*(\3[ \t]*){2,}$)/';
+
+    private string $src = '';
+
+    private int $len = 0;
+
+    private string $out = '';
+
+    /**
+     * @param  Closure(string $kind, string $raw, string $inner, string $info): int  $register
+     *                                                                                          登记一次调用并返回下标。kind:template / wikilink / note-backtick / note-fence
+     */
+    public function run(string $source, Dialect $dialect, Closure $register): string
+    {
+        $this->src = $source;
+        $this->len = strlen($source);
+        $this->out = '';
+        $i = 0;
+        $lineStart = true;
+
+        while ($i < $this->len) {
+            if ($lineStart) {
+                $lineStart = false;
+                $fence = $this->fenceAt($i);
+                if ($fence !== null) {
+                    [$marker, $info] = $fence;
+                    [$contentStart, $contentEnd, $after] = $this->closingFence($i, $marker);
+                    if ($this->isNoteFence($marker, $info, $dialect)) {
+                        $inner = substr($this->src, $contentStart, max(0, $contentEnd - $contentStart));
+                        $raw = substr($this->src, $i, $after - $i);
+                        $index = $register('note-fence', rtrim($raw, "\n"), rtrim($inner, "\n"), $info);
+                        [$i, $lineStart] = $this->joinFence($index, $after);
+                    } else {
+                        $this->out .= substr($this->src, $i, $after - $i);
+                        $i = $after;
+                        $lineStart = true;
+                    }
+
+                    continue;
+                }
+            }
+
+            $char = $this->src[$i];
+
+            if ($char === '\\' && $i + 1 < $this->len && in_array($this->src[$i + 1], ['{', '[', '`'], true)) {
+                $this->out .= substr($this->src, $i, 2);
+                $i += 2;
+
+                continue;
+            }
+
+            if ($char === '{' && substr($this->src, $i, 2) === '{{') {
+                $end = $this->matchBraces($i);
+                if ($end !== null) {
+                    $raw = substr($this->src, $i, $end + 2 - $i);
+                    $this->out .= Placeholder::make($register('template', $raw, substr($raw, 2, -2), ''));
+                    $i = $end + 2;
+                } else {
+                    $this->out .= '{{';
+                    $i += 2;
+                }
+
+                continue;
+            }
+
+            if ($char === '[' && substr($this->src, $i, 2) === '[[') {
+                $close = $this->sameLine($i + 2, ']]');
+                if ($close !== null && $close > $i + 2) {
+                    $raw = substr($this->src, $i, $close + 2 - $i);
+                    $this->out .= Placeholder::make($register('wikilink', $raw, substr($raw, 2, -2), ''));
+                    $i = $close + 2;
+
+                    continue;
+                }
+            }
+
+            if ($char === '`') {
+                $i = $dialect === Dialect::MarkdownE2
+                    ? $this->skipCodeSpan($i)
+                    : $this->legacyBacktick($i, $register);
+
+                continue;
+            }
+
+            $this->out .= $char;
+            $i++;
+            if ($char === "\n") {
+                $lineStart = true;
+            }
+        }
+
+        return $this->out;
+    }
+
+    /**
+     * 行首是否是围栏开头。
+     *
+     * @return array{0: string, 1: string}|null [围栏符号串, info string]
+     */
+    private function fenceAt(int $i): ?array
+    {
+        $line = $this->lineAt($i);
+        if (preg_match('/^ {0,3}(`{3,}|~{3,})(.*)$/', rtrim($line, "\r"), $m) !== 1) {
+            return null;
+        }
+        // 反引号围栏的 info 里不能再有反引号(CommonMark 规则),否则这行只是行内代码
+        if ($m[1][0] === '`' && str_contains($m[2], '`')) {
+            return null;
+        }
+
+        return [$m[1], trim($m[2])];
+    }
+
+    /**
+     * 找围栏的结束行。没有结束行就到文末(与 CommonMark 一致;v2 旧方言也是补到文末)。
+     *
+     * @return array{0: int, 1: int, 2: int} [内容起点, 内容终点(不含), 结束行之后的位置]
+     */
+    private function closingFence(int $i, string $marker): array
+    {
+        $contentStart = $this->nextLine($i);
+        $pos = $contentStart;
+        $closing = '/^ {0,3}'.preg_quote($marker[0], '/').'{'.strlen($marker).',}[ \t]*\r?$/';
+        while ($pos < $this->len) {
+            $line = $this->lineAt($pos);
+            if (preg_match($closing, $line) === 1) {
+                return [$contentStart, $pos, $this->nextLine($pos)];
+            }
+            $pos = $this->nextLine($pos);
+        }
+
+        return [$contentStart, $this->len, $this->len];
+    }
+
+    private function isNoteFence(string $marker, string $info, Dialect $dialect): bool
+    {
+        $word = strtolower(explode(' ', $info, 2)[0]);
+        if ($word === 'note') {
+            return true;
+        }
+
+        // 旧方言:单独一行的 ``` 就是多行脚注
+        return $dialect === Dialect::Markdown && $info === '' && $marker === '```';
+    }
+
+    /**
+     * 脚注围栏的落点。
+     *
+     * 上一行有字:去掉换行,占位符直接贴在上一行末尾(角标贴着前面的字)。
+     * 下一行有字且不是新块:把下一行接到占位符后面;两侧都是 CJK 时不加空格,否则加一个空格。
+     * 这样「前半句 / ```note … ``` / 后半句」三段合成一个段落,脚注在句中(v2 旧方言就是这个效果)。
+     * 两侧都是空行时占位符独占一段,由 IR 构建时并到上一段末尾。
+     *
+     * @return array{0: int, 1: bool} [继续扫描的位置, 是否在行首]
+     */
+    private function joinFence(int $index, int $after): array
+    {
+        $left = null;
+        if (str_ends_with($this->out, "\n") && ! $this->previousLineBlank()) {
+            $this->out = rtrim($this->out, "\r\n");
+            $left = mb_substr($this->out, -1);
+        }
+        $this->out .= Placeholder::make($index);
+
+        if ($after >= $this->len) {
+            return [$after, false];
+        }
+        $next = $this->lineAt($after);
+        if (trim($next) === '' || preg_match(self::BLOCK_START, $next) === 1) {
+            $this->out .= "\n";
+
+            return [$after, true];
+        }
+
+        $indent = strspn($next, " \t");
+        $right = mb_substr(substr($next, $indent), 0, 1);
+        $bothCjk = ($left === null || $this->isCjk($left)) && $this->isCjk($right);
+        $this->out .= $bothCjk ? '' : ' ';
+
+        return [$after + $indent, false];
+    }
+
+    private function previousLineBlank(): bool
+    {
+        $body = substr($this->out, 0, -1);
+        $start = strrpos($body, "\n");
+        $line = $start === false ? $body : substr($body, $start + 1);
+
+        return trim($line) === '';
+    }
+
+    private function isCjk(string $char): bool
+    {
+        return $char !== '' && preg_match(self::CJK, $char) === 1;
+    }
+
+    /**
+     * 从 `{{` 起按深度配对,返回配对的 `}}` 的位置;不配对或超深返回 null。
+     */
+    private function matchBraces(int $i): ?int
+    {
+        $depth = 0;
+        $j = $i;
+        while ($j < $this->len - 1) {
+            $pair = substr($this->src, $j, 2);
+            if ($pair === '{{') {
+                $depth++;
+                if ($depth > self::MAX_BRACE_DEPTH) {
+                    return null;
+                }
+                $j += 2;
+
+                continue;
+            }
+            if ($pair === '}}') {
+                $depth--;
+                if ($depth === 0) {
+                    return $j;
+                }
+                $j += 2;
+
+                continue;
+            }
+            $j++;
+        }
+
+        return null;
+    }
+
+    /**
+     * E2:行内代码原样跳过(里面的 `{{`、`[[` 不是模板)。反引号串长度 n,找下一个恰好 n 个的串。
+     */
+    private function skipCodeSpan(int $i): int
+    {
+        $n = strspn($this->src, '`', $i);
+        $pos = $i + $n;
+        while (($found = strpos($this->src, str_repeat('`', $n), $pos)) !== false) {
+            $run = strspn($this->src, '`', $found);
+            if ($run === $n) {
+                $end = $found + $n;
+                $this->out .= substr($this->src, $i, $end - $i);
+
+                return $end;
+            }
+            $pos = $found + $run;
+        }
+        $this->out .= substr($this->src, $i, $n);
+
+        return $i + $n;
+    }
+
+    /**
+     * 旧方言:`` `x` `` 是脚注。配对口径同 v2 的正则 /`(.+?)`/:正文至少一个字符,且可以以反引号开头
+     * (``` ``x`` ``` 的正文是 `` `x ``,剩下一个反引号是普通字符)。
+     *
+     * 与 v2 不同的两点(都按作者本意,v2 在这些写法上配错了对):
+     * - 可以跨行(不跨空行),反引号后可以直接换行。库里有大量「词`多行注释`」的写法,v2 的正则不跨行,
+     *   配错了对,剩下的反引号又被 CommonMark 配成跨行的代码 span
+     * - ``` ``x`` ```(两个以上成对):整对是边界,正文是 x(v2 的正文是「`x」)
+     * 单行内写对的单反引号,配对结果与 v2 相同。
+     *
+     * @param  Closure(string, string, string, string): int  $register
+     */
+    private function legacyBacktick(int $i, Closure $register): int
+    {
+        // 两个以上的反引号成对(``x``):作者把整对当作脚注边界,正文是中间的部分
+        $n = strspn($this->src, '`', $i);
+        if ($n >= 2 && ($pair = $this->matchingRun($i + $n, $n)) !== null) {
+            $raw = substr($this->src, $i, $pair + $n - $i);
+            $this->out .= Placeholder::make($register('note-backtick', $raw, substr($raw, $n, -$n), ''));
+
+            return $pair + $n;
+        }
+
+        $close = $i + 2 <= $this->len ? strpos($this->src, '`', $i + 2) : false;
+        $spansParagraph = $close !== false
+            && preg_match('/\n[ \t]*\n/', substr($this->src, $i + 1, $close - $i - 1)) === 1;
+        if ($close === false || $spansParagraph) {
+            // 配不上对的反引号是普通字符:旧方言里反引号从来不是代码,转义掉免得 CommonMark 配成代码 span
+            $this->out .= '\\`';
+
+            return $i + 1;
+        }
+        $raw = substr($this->src, $i, $close + 1 - $i);
+        $this->out .= Placeholder::make($register('note-backtick', $raw, substr($raw, 1, -1), ''));
+
+        return $close + 1;
+    }
+
+    /**
+     * 从 $from 起找恰好 $n 个反引号的串(不跨空行),返回它的起点。
+     */
+    private function matchingRun(int $from, int $n): ?int
+    {
+        $pos = $from;
+        while (($found = strpos($this->src, str_repeat('`', $n), $pos)) !== false) {
+            if (preg_match('/\n[ \t]*\n/', substr($this->src, $from, $found - $from)) === 1) {
+                return null;
+            }
+            $run = strspn($this->src, '`', $found);
+            if ($run === $n) {
+                return $found;
+            }
+            $pos = $found + $run;
+        }
+
+        return null;
+    }
+
+    /**
+     * 在同一行内找 $needle,找不到返回 null。
+     */
+    private function sameLine(int $from, string $needle): ?int
+    {
+        $found = strpos($this->src, $needle, $from);
+        if ($found === false) {
+            return null;
+        }
+        $newline = strpos($this->src, "\n", $from);
+
+        return ($newline === false || $found < $newline) ? $found : null;
+    }
+
+    private function lineAt(int $i): string
+    {
+        $end = strpos($this->src, "\n", $i);
+
+        return substr($this->src, $i, ($end === false ? $this->len : $end) - $i);
+    }
+
+    private function nextLine(int $i): int
+    {
+        $end = strpos($this->src, "\n", $i);
+
+        return $end === false ? $this->len : $end + 1;
+    }
+}

+ 64 - 0
api-v13/app/Services/Markup/Parsing/TemplateSyntax.php

@@ -0,0 +1,64 @@
+<?php
+
+namespace App\Services\Markup\Parsing;
+
+/**
+ * `{{name|a|b=c}}` 的切分:模板名 + 参数片段。只在顶层(不在嵌套的 `{{ }}` / `[[ ]]` 里)切 `|`。
+ */
+final class TemplateSyntax
+{
+    /**
+     * @return array{0: string, 1: list<string>} [模板名, 参数片段]
+     */
+    public static function split(string $inner): array
+    {
+        $segments = self::splitTopLevel($inner);
+        $name = trim(array_shift($segments) ?? '');
+
+        // v2:`|` 后紧跟的换行去掉(`{{note|\n内容\n}}` 的内容不以换行开头)
+        $segments = array_map(
+            fn (string $segment) => (string) preg_replace('/^\r?\n/', '', $segment),
+            $segments,
+        );
+
+        return [$name, $segments];
+    }
+
+    /**
+     * @return list<string>
+     */
+    private static function splitTopLevel(string $text): array
+    {
+        $parts = [];
+        $current = '';
+        $braces = 0;
+        $brackets = 0;
+        $len = strlen($text);
+        for ($i = 0; $i < $len; $i++) {
+            $pair = substr($text, $i, 2);
+            if ($pair === '{{' || $pair === '}}' || $pair === '[[' || $pair === ']]') {
+                match ($pair) {
+                    '{{' => $braces++,
+                    '}}' => $braces = max(0, $braces - 1),
+                    '[[' => $brackets++,
+                    ']]' => $brackets = max(0, $brackets - 1),
+                };
+                $current .= $pair;
+                $i++;
+
+                continue;
+            }
+            $char = $text[$i];
+            if ($char === '|' && $braces === 0 && $brackets === 0) {
+                $parts[] = $current;
+                $current = '';
+
+                continue;
+            }
+            $current .= $char;
+        }
+        $parts[] = $current;
+
+        return $parts;
+    }
+}

+ 115 - 0
api-v13/app/Services/Markup/Render/HtmlRenderer.php

@@ -0,0 +1,115 @@
+<?php
+
+namespace App\Services\Markup\Render;
+
+use App\Services\Markup\Html\HtmlPolicy;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Text;
+
+/**
+ * IR → 静态 HTML(library 阅读器、导出)。
+ *
+ * 单段落内容包成 `<span>`(v2 的 replaceSinglePWithSpan);站内绝对路径的图片补上站点地址。
+ * 模板的 HTML 由各模板的 html() 给出。
+ */
+final class HtmlRenderer implements Renderer
+{
+    public function document(Document $document, RenderContext $ctx): string
+    {
+        $html = $this->nodes($document->nodes, $ctx);
+
+        return $document->inline && ! $document->fragment && $html !== '' ? "<span>{$html}</span>" : $html;
+    }
+
+    /** 行内安全渲染时要换成 span 的块级标签 */
+    private const BLOCK_TAGS = [
+        'p', 'div', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th',
+        'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'dl', 'dt', 'dd', 'figure', 'figcaption', 'details', 'summary',
+    ];
+
+    private bool $inlineOnly = false;
+
+    /**
+     * 渲染成只含行内元素的 HTML:块级标签换成 `<span class="md-{标签}">`,顶层块之间用 `<br />` 分隔。
+     *
+     * 用于嵌在句子中间的内容(脚注 sidenote):块级元素落进 `<p>` / `<span>` 里,浏览器会提前闭合外层,
+     * 把 sidenote 的结构切断、吞掉后面的正文。
+     */
+    public function inlineSafe(Document $document, RenderContext $ctx): string
+    {
+        $previous = $this->inlineOnly;
+        $this->inlineOnly = true;
+        try {
+            if ($document->inline) {
+                return $this->document($document, $ctx);
+            }
+            $blocks = array_map(fn (Node $node) => $this->nodes([$node], $ctx), $document->nodes);
+            $html = implode('<br />', array_filter($blocks, fn (string $html) => $html !== ''));
+
+            return $html === '' ? '' : "<span>{$html}</span>";
+        } finally {
+            $this->inlineOnly = $previous;
+        }
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     */
+    public function nodes(array $nodes, RenderContext $ctx): string
+    {
+        $html = '';
+        foreach ($nodes as $node) {
+            $html .= match (true) {
+                $node instanceof Text => e($node->value, false),
+                $node instanceof Element => $this->element($node, $ctx),
+                $node instanceof Call => $node->template->html($node, $ctx),
+                default => '',
+            };
+        }
+
+        return $html;
+    }
+
+    private function element(Element $element, RenderContext $ctx): string
+    {
+        $attrs = '';
+        foreach ($element->attrs as $name => $value) {
+            if ($name === 'src' && str_starts_with($value, '/') && ! str_starts_with($value, '//')) {
+                $value = rtrim((string) config('app.url'), '/').$value;
+            }
+            $attrs .= ' '.$name.'="'.e($value, false).'"';
+        }
+        if ($this->inlineOnly && in_array($element->tag, self::BLOCK_TAGS, true)) {
+            if ($element->tag === 'hr') {
+                return '<br />';
+            }
+            $class = 'md-'.$element->tag.(isset($element->attrs['class']) ? ' '.e($element->attrs['class'], false) : '');
+
+            return '<span class="'.$class.'">'.$this->nodes($element->children, $ctx).'</span>';
+        }
+        if (in_array($element->tag, [...HtmlPolicy::VOID, 'input'], true)) {
+            return "<{$element->tag}{$attrs} />";
+        }
+
+        return "<{$element->tag}{$attrs}>".$this->nodes($element->children, $ctx)."</{$element->tag}>";
+    }
+
+    /**
+     * 文末的脚注列表(footnote 选项打开时)。
+     */
+    public function footnotes(RenderContext $ctx): string
+    {
+        if ($ctx->footnotes === []) {
+            return '';
+        }
+        $html = '<div><h1>endnote</h1>';
+        foreach ($ctx->footnotes as $note) {
+            $html .= '<p><a name="footnote-'.$note['sn'].'">['.$note['sn'].']</a> '.$note['content'].'</p>';
+        }
+
+        return $html.'</div>';
+    }
+}

+ 79 - 0
api-v13/app/Services/Markup/Render/MarkdownRenderer.php

@@ -0,0 +1,79 @@
+<?php
+
+namespace App\Services\Markup\Render;
+
+use App\Services\Markup\Annotation\AnnotationToken;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Text;
+use App\Services\Markup\Parsing\Placeholder;
+
+/**
+ * 展开模板后的 markdown(导出用)。
+ *
+ * markdown 本身原样保留:拿预扫描后的源码,把每个占位符换成模板的 markdown() 输出;
+ * 脚注变成 `[^n]`,脚注正文在文末(footnote 选项打开时)。站内附件地址补上站点地址。
+ */
+final class MarkdownRenderer implements Renderer
+{
+    public function document(Document $document, RenderContext $ctx): string
+    {
+        if ($document->source === '') {
+            return $this->fromNodes($document->nodes, $ctx);
+        }
+        $markdown = (string) preg_replace_callback(
+            Placeholder::PATTERN,
+            function (array $m) use ($document, $ctx) {
+                $call = $document->calls[(int) $m[1]] ?? null;
+
+                return $call === null ? '' : $call->template->markdown($call, $ctx);
+            },
+            $document->source,
+        );
+
+        // 批注占位符:点标记换成模板的 markdown(脚注 → [^n]),区间边界去掉
+        $markdown = (string) preg_replace_callback(
+            AnnotationToken::PATTERN,
+            function (array $m) use ($document, $ctx) {
+                $call = $document->annotationCalls[(int) $m[1]] ?? null;
+
+                return $call === null ? '' : $call->template->markdown($call, $ctx);
+            },
+            $markdown,
+        );
+
+        return str_replace('](/attachments/', ']('.rtrim((string) config('app.url'), '/').'/attachments/', $markdown);
+    }
+
+    /**
+     * 没有源码的内容(IR 构建时生成的,如 toggle 的内容):只取文字与模板。
+     *
+     * @param  list<Node>  $nodes
+     */
+    private function fromNodes(array $nodes, RenderContext $ctx): string
+    {
+        $markdown = '';
+        foreach ($nodes as $node) {
+            $markdown .= match (true) {
+                $node instanceof Text => $node->value,
+                $node instanceof Call => $node->template->markdown($node, $ctx),
+                $node instanceof Element => $this->fromNodes($node->children, $ctx),
+                default => '',
+            };
+        }
+
+        return $markdown;
+    }
+
+    public function footnotes(RenderContext $ctx): string
+    {
+        if ($ctx->footnotes === []) {
+            return '';
+        }
+        $lines = array_map(fn (array $note) => '[^'.$note['sn'].']: '.$note['content'], $ctx->footnotes);
+
+        return "\n\n".implode("\n\n", $lines);
+    }
+}

+ 99 - 0
api-v13/app/Services/Markup/Render/RenderContext.php

@@ -0,0 +1,99 @@
+<?php
+
+namespace App\Services\Markup\Render;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Scope;
+use App\Services\Markup\RenderOptions;
+use App\Services\Markup\Resolve\Loader;
+use App\Services\Markup\Resolve\Resolver;
+
+/**
+ * 一段顶层内容渲染期间的状态:选项、取数结果、脚注编号与列表、引用到的经文段落、已出现过的术语。
+ *
+ * 取代 v2 的 `$GLOBALS['note_sn']` / `$GLOBALS['note']` / `$GLOBALS['ref_sent']` / `$GLOBALS['term-…']`。
+ */
+final class RenderContext
+{
+    public int $noteNumber = 0;
+
+    /** @var list<array{sn: int, trigger: string, content: string}> 脚注(html / markdown 输出末尾的列表) */
+    public array $footnotes = [];
+
+    /** @var array<int, array{0: int, 1: int}> 句子模板引用到的 [book, para](按调用去重),ref 模板据此列参考文献 */
+    public array $sentenceRefs = [];
+
+    /** @var array<string, int> 术语出现次数(markdown 输出只有第一次带巴利原词与脚注) */
+    public array $termSeen = [];
+
+    /**
+     * @param  string  $idPrefix  这段内容生成的 HTML id 的前缀(边注的 checkbox / label):同一页上多段内容
+     *                            各自从 1 编号,没有前缀 id 会重复,点角标会切换到别处的边注
+     */
+    public function __construct(
+        public readonly RenderOptions $options,
+        public readonly Resolver $resolver,
+        public readonly Renderer $renderer,
+        public readonly string $idPrefix = '',
+    ) {}
+
+    /**
+     * 本段内容里唯一、跨段也不重复的 HTML id。
+     */
+    public function htmlId(string $kind, int $number): string
+    {
+        return $this->idPrefix === '' ? "{$kind}-{$number}" : "{$kind}-{$this->idPrefix}-{$number}";
+    }
+
+    public function format(): Format
+    {
+        return $this->options->format;
+    }
+
+    /**
+     * @template T of Loader
+     *
+     * @param  class-string<T>  $class
+     * @return T
+     */
+    public function loader(string $class): Loader
+    {
+        return $this->resolver->loader($class);
+    }
+
+    /**
+     * 按当前格式渲染一段内容(模板 props 里的 Document、slot、句子正文都走这里)。
+     *
+     * @return list<array<string, mixed>>|string
+     */
+    public function render(Document $document): array|string
+    {
+        return $this->renderer->document($document, $this);
+    }
+
+    /**
+     * 按当前格式渲染,要求结果是字符串(html / 纯文本 / markdown 模板方法用)。
+     */
+    public function renderString(Document $document): string
+    {
+        $rendered = $this->render($document);
+
+        return is_string($rendered) ? $rendered : '';
+    }
+
+    /**
+     * 这段内容的语言:第一个 channel 的语言,没有 channel 用选项里的默认语言(v2 口径)。
+     */
+    public function lang(Scope $scope): string
+    {
+        $lang = $this->resolver->channels()->get($scope->firstChannel())?->lang;
+
+        return $lang !== null && $lang !== '' ? (string) $lang : $this->options->lang;
+    }
+
+    public function nextNoteNumber(): int
+    {
+        return ++$this->noteNumber;
+    }
+}

+ 13 - 0
api-v13/app/Services/Markup/Render/Renderer.php

@@ -0,0 +1,13 @@
+<?php
+
+namespace App\Services\Markup\Render;
+
+use App\Services\Markup\Ir\Document;
+
+interface Renderer
+{
+    /**
+     * @return list<array<string, mixed>>|string tree 返回节点数组,其余返回字符串
+     */
+    public function document(Document $document, RenderContext $ctx): array|string;
+}

+ 72 - 0
api-v13/app/Services/Markup/Render/TextRenderer.php

@@ -0,0 +1,72 @@
+<?php
+
+namespace App\Services\Markup\Render;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Text;
+
+/**
+ * IR → 纯文本(text / simple / prompt)。块与块之间换行,模板由各模板的 plain() 给出。
+ */
+final class TextRenderer implements Renderer
+{
+    private const BLOCKS = [
+        'p', 'div', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tr',
+        'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'dl', 'dt', 'dd', 'figure', 'details', 'summary',
+    ];
+
+    public function __construct(private readonly Format $format) {}
+
+    public function document(Document $document, RenderContext $ctx): string
+    {
+        if ($document->inline) {
+            return $this->nodes($document->nodes, $ctx);
+        }
+        // 块级内容逐块换行(块级模板如 mermaid 自己不带换行)
+        $text = '';
+        foreach ($document->nodes as $node) {
+            $text .= rtrim($this->nodes([$node], $ctx), "\n")."\n";
+        }
+
+        return rtrim($text, "\n");
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     */
+    private function nodes(array $nodes, RenderContext $ctx): string
+    {
+        $text = '';
+        foreach ($nodes as $node) {
+            if ($node instanceof Text) {
+                $text .= $node->value;
+            } elseif ($node instanceof Call) {
+                $text .= $node->template->plain($node, $ctx, $this->format);
+            } elseif ($node instanceof Element) {
+                $text .= $this->element($node, $ctx);
+            }
+        }
+
+        return $text;
+    }
+
+    private function element(Element $element, RenderContext $ctx): string
+    {
+        if ($element->tag === 'br') {
+            return "\n";
+        }
+        if ($element->tag === 'img') {
+            return $element->attrs['alt'] ?? '';
+        }
+        $inner = $this->nodes($element->children, $ctx);
+        if ($element->tag === 'td' || $element->tag === 'th') {
+            return $inner."\t";
+        }
+
+        return in_array($element->tag, self::BLOCKS, true) ? rtrim($inner, "\n")."\n" : $inner;
+    }
+}

+ 103 - 0
api-v13/app/Services/Markup/Render/TreeRenderer.php

@@ -0,0 +1,103 @@
+<?php
+
+namespace App\Services\Markup\Render;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Ir\Text;
+
+/**
+ * IR → JSON 节点树(v3 API 下发给 dashboard-v6 / wikipali-mobile)。
+ *
+ * 三种节点:
+ * - `{type: 'text', value}`:纯文本,前端直接作为 React 文本节点(自动转义)
+ * - `{type: 'el', tag, attrs?, children}`:HTML 元素,tag 与 attrs 已过白名单
+ * - `{type: 'tpl', name, props, children}`:模板,name 是前端组件名;props 里嵌套的内容(术语 note、句子正文)也是节点数组
+ *
+ * 单段落的内容(如一句译文)直接给出段落里的行内节点,不包 `p`。
+ */
+final class TreeRenderer implements Renderer
+{
+    /**
+     * @return list<array<string, mixed>>
+     */
+    public function document(Document $document, RenderContext $ctx): array
+    {
+        return $this->nodes($document->nodes, $ctx);
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     * @return list<array<string, mixed>>
+     */
+    private function nodes(array $nodes, RenderContext $ctx): array
+    {
+        $out = [];
+        foreach ($nodes as $node) {
+            if (! $node instanceof Text && ! $node instanceof Element && ! $node instanceof Call) {
+                continue;   // 构建期的辅助节点(如配不上对的批注边界)不输出
+            }
+            $rendered = $this->node($node, $ctx);
+            $last = array_key_last($out);
+            // 相邻文本并成一个节点
+            if ($rendered['type'] === 'text' && $last !== null && $out[$last]['type'] === 'text') {
+                $out[$last]['value'] .= $rendered['value'];
+
+                continue;
+            }
+            $out[] = $rendered;
+        }
+
+        return $out;
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    private function node(Node $node, RenderContext $ctx): array
+    {
+        if ($node instanceof Text) {
+            return ['type' => 'text', 'value' => $node->value];
+        }
+        if ($node instanceof Element) {
+            $element = ['type' => 'el', 'tag' => $node->tag];
+            if ($node->attrs !== []) {
+                $element['attrs'] = $node->attrs;
+            }
+            $element['children'] = $this->nodes($node->children, $ctx);
+
+            return $element;
+        }
+
+        /** @var Call $node */
+        $children = $node->template->children($node, $ctx);
+
+        return [
+            'type' => 'tpl',
+            'name' => $node->template->component($node, $ctx),
+            'props' => (object) $this->props($node->template->props($node, $ctx), $ctx),
+            'children' => $children === null ? [] : $this->document($children, $ctx),
+        ];
+    }
+
+    /**
+     * props 里的 Document 展开成节点数组(递归到数组里)。
+     *
+     * @param  array<array-key, mixed>  $props
+     * @return array<array-key, mixed>
+     */
+    private function props(array $props, RenderContext $ctx): array
+    {
+        foreach ($props as $key => $value) {
+            if ($value instanceof Document) {
+                $props[$key] = $this->document($value, $ctx);
+            } elseif (is_array($value)) {
+                $props[$key] = $this->props($value, $ctx);
+            }
+        }
+
+        return $props;
+    }
+}

+ 46 - 0
api-v13/app/Services/Markup/RenderOptions.php

@@ -0,0 +1,46 @@
+<?php
+
+namespace App\Services\Markup;
+
+/**
+ * 一次渲染的选项。字段与 v2 MdRender 的 $options 一一对应(去掉了 debug / studioId / unity)。
+ */
+final readonly class RenderOptions
+{
+    /**
+     * @param  list<string>  $channels  内容所属的 channel uid。句子模板默认读这些 channel 的译文,
+     *                                  术语按第一个 channel 查;第一个 channel 的语言也是默认语言
+     * @param  string  $mode  read | edit:句子模板据此输出 sentread / sentedit
+     * @param  string  $contentType  markdown | markdown-e2 | json | html(取自 content_type 列)
+     * @param  string  $channelType  translation | nissaya:nissaya 的 `a=b` 行会转成 nissaya 模板
+     * @param  bool  $footnote  html / markdown 输出是否在末尾附脚注列表
+     * @param  bool  $paragraph  巴汉逐段对读:只由句子模板组成的段落复制成原文段 + 译文段
+     * @param  bool  $origin  markdown 输出时句子模板是否带原文
+     * @param  bool  $translation  markdown 输出时句子模板是否带译文
+     */
+    public function __construct(
+        public Format $format = Format::Tree,
+        public array $channels = [],
+        public string $mode = 'read',
+        public string $contentType = 'markdown',
+        public string $channelType = 'translation',
+        public string $lang = 'zh-Hans',
+        public bool $footnote = false,
+        public bool $paragraph = false,
+        public bool $origin = true,
+        public bool $translation = true,
+    ) {}
+
+    public function dialect(): Dialect
+    {
+        return Dialect::fromContentType($this->contentType);
+    }
+
+    /**
+     * @param  array<string, mixed>  $changes
+     */
+    public function with(array $changes): self
+    {
+        return new self(...array_merge(get_object_vars($this), $changes));
+    }
+}

+ 58 - 0
api-v13/app/Services/Markup/Resolve/ChannelDirectory.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Models\Channel;
+use Illuminate\Support\Str;
+
+/**
+ * 渲染期间用到的 channel 的基本信息(uid、名字、类型、语言、拥有者),攒够一批再查。
+ */
+final class ChannelDirectory
+{
+    /** @var array<string, Channel|null> */
+    private array $channels = [];
+
+    /** @var array<string, true> */
+    private array $pending = [];
+
+    /**
+     * @param  list<string>  $uids
+     */
+    public function request(array $uids): void
+    {
+        foreach ($uids as $uid) {
+            if (Str::isUuid($uid) && ! array_key_exists($uid, $this->channels)) {
+                $this->pending[$uid] = true;
+            }
+        }
+    }
+
+    public function get(?string $uid): ?Channel
+    {
+        if ($uid === null || ! Str::isUuid($uid)) {
+            return null;
+        }
+        if (! array_key_exists($uid, $this->channels)) {
+            $this->pending[$uid] = true;
+        }
+        $this->flush();
+
+        return $this->channels[$uid] ?? null;
+    }
+
+    private function flush(): void
+    {
+        if ($this->pending === []) {
+            return;
+        }
+        $uids = array_keys($this->pending);
+        $this->pending = [];
+        $found = Channel::whereIn('uid', $uids)
+            ->get(['uid', 'name', 'type', 'lang', 'owner_uid'])
+            ->keyBy(fn (Channel $channel) => (string) $channel->uid);
+        foreach ($uids as $uid) {
+            $this->channels[$uid] = $found->get($uid);
+        }
+    }
+}

+ 21 - 0
api-v13/app/Services/Markup/Resolve/Loader.php

@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+/**
+ * 批量取数器。模板在 collect 阶段登记键,{@see Resolver::run()} 一轮一轮地调 {@see load()},
+ * 直到所有 loader 都没有待办(loader 取回的内容里又有模板,会登记下一轮)。
+ */
+abstract class Loader
+{
+    protected Resolver $resolver;
+
+    public function setResolver(Resolver $resolver): void
+    {
+        $this->resolver = $resolver;
+    }
+
+    abstract public function hasPending(): bool;
+
+    abstract public function load(): void;
+}

+ 45 - 0
api-v13/app/Services/Markup/Resolve/QaLoader.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Models\Discussion;
+
+/**
+ * qa 模板:按 id 取问答话题的标题与挂载对象,一次查完。
+ */
+final class QaLoader extends Loader
+{
+    /** @var array<string, true> */
+    private array $pending = [];
+
+    /** @var array<string, Discussion|null> */
+    private array $results = [];
+
+    public function request(string $id): void
+    {
+        if ($id !== '' && ! array_key_exists($id, $this->results)) {
+            $this->pending[$id] = true;
+        }
+    }
+
+    public function result(string $id): ?Discussion
+    {
+        return $this->results[$id] ?? null;
+    }
+
+    public function hasPending(): bool
+    {
+        return $this->pending !== [];
+    }
+
+    public function load(): void
+    {
+        $ids = array_keys($this->pending);
+        $this->pending = [];
+        $found = Discussion::whereIn('id', $ids)->get(['id', 'title', 'res_id', 'res_type'])
+            ->keyBy(fn (Discussion $row) => (string) $row->id);
+        foreach ($ids as $id) {
+            $this->results[$id] = $found->get($id);
+        }
+    }
+}

+ 197 - 0
api-v13/app/Services/Markup/Resolve/QuoteLinkLoader.php

@@ -0,0 +1,197 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Http\Api\BookTitle;
+use App\Models\PageNumber;
+use App\Models\PaliText;
+use App\Services\Markup\Ir\Call;
+
+/**
+ * ql(quote-link,引用某版本的页码)的取数。口径同 v2 TemplateRender::render_quote_link():
+ *
+ * - 给了书名 + 册 + 页:直接用
+ * - 给了 book + para:`type=c` 按章节路径取书名与章名,其余按 page_numbers 表取该版本的册页
+ * - 只给了缅文 title:按缅文书名缩写表拆出书名与页码
+ *
+ * 书名再按 `:quote:` tag 查一次术语,得到本地化书名(登记给 {@see TermLoader},下一轮一起查)。
+ * {@see BookTitle} 是 v2 的静态数据表,只读引用。
+ */
+final class QuoteLinkLoader extends Loader
+{
+    /** @var array<string, Call> */
+    private array $pending = [];
+
+    /** @var array<string, array{props: array<string, mixed>, text: string, termKey: ?string}> */
+    private array $results = [];
+
+    public function request(Call $call): string
+    {
+        $key = $call->raw."\x1F".implode(',', $call->scope->channels);
+        if (! isset($this->results[$key])) {
+            $this->pending[$key] = $call;
+        }
+
+        return $key;
+    }
+
+    /**
+     * @return array{props: array<string, mixed>, text: string, termKey: ?string}|null
+     */
+    public function result(string $key): ?array
+    {
+        return $this->results[$key] ?? null;
+    }
+
+    public function hasPending(): bool
+    {
+        return $this->pending !== [];
+    }
+
+    public function load(): void
+    {
+        $batch = $this->pending;
+        $this->pending = [];
+        foreach ($batch as $key => $call) {
+            $this->results[$key] = $this->resolve($call);
+        }
+    }
+
+    /**
+     * @return array{props: array<string, mixed>, text: string, termKey: ?string}
+     */
+    private function resolve(Call $call): array
+    {
+        $type = (string) $call->param('type');
+        $title = (string) $call->param('title');
+        $bookName = (string) $call->param('bookname');
+        $volume = (string) $call->param('volume');
+        $page = (string) $call->param('page');
+        $book = (string) $call->param('book');
+        $para = (string) $call->param('para');
+
+        $props = ['type' => $type, 'style' => (string) $call->param('style'), 'found' => true];
+
+        if ($bookName !== '' && $volume !== '' && $page !== '') {
+            $props += ['bookName' => $bookName, 'volume' => (int) $volume, 'page' => $page];
+        } elseif ($book !== '' && $para !== '') {
+            $props = array_merge($props, $type === 'c'
+                ? $this->chapterInfo((int) $book, (int) $para)
+                : $this->pageInfo($type, (int) $book, (int) $para));
+        } elseif ($title !== '') {
+            $props = array_merge($props, $this->myanmarTitle($title));
+        } else {
+            $props['found'] = false;
+        }
+
+        if ($book !== '' && $para !== '') {
+            $props['book'] = $book;
+            $props['para'] = $para;
+        }
+        if ($title !== '') {
+            $props['title'] = $title;
+        }
+
+        $text = '';
+        $termKey = null;
+        if (isset($props['bookName'])) {
+            $field = match ($type) {
+                'm' => 'm_title',
+                'p' => 'p_title',
+                default => null,
+            };
+            // v2 口径:只有 m / p 两个版本能在书名表里核对,其余版本一律记作未找到
+            if ($field === null || ! in_array($props['bookName'], array_column(BookTitle::get(), $field), true)) {
+                $props['found'] = false;
+            }
+            $termKey = $this->resolver->loader(TermLoader::class)
+                ->request((string) $props['bookName'], ':quote:', $call->scope->firstChannel(), $call->scope);
+        }
+        // v2 这里误用了 volume / page 参数本身:按 book+para 或缅文标题查到的册页从不显示(输出「 .」)。
+        // 这里改用查到的值;直接给参数时与 v2 相同
+        if (isset($props['volume'], $props['page'])) {
+            $text = " {$props['volume']}.{$props['page']}";
+        }
+
+        return ['props' => $props, 'text' => $text, 'termKey' => $termKey];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    private function chapterInfo(int $book, int $para): array
+    {
+        $path = json_decode((string) PaliText::where('book', $book)->where('paragraph', $para)->value('path'), true);
+        if (! is_array($path) || count($path) <= 2) {
+            return ['found' => false];
+        }
+
+        return [
+            'bookName' => strtolower((string) ($path[0]['title'] ?? '')),
+            'chapter' => strtolower((string) (end($path)['title'] ?? '')),
+            'found' => true,
+        ];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    private function pageInfo(string $type, int $book, int $para): array
+    {
+        $pageInfo = PageNumber::where('type', strtoupper($type))
+            ->where('book', $book)
+            ->where('paragraph', '<=', $para)
+            ->orderByDesc('paragraph')
+            ->first(['pcd_book_id', 'volume', 'page']);
+        if ($pageInfo === null) {
+            return ['found' => false];
+        }
+        $field = match (strtoupper($type)) {
+            'M' => 'm_title',
+            'P' => 'p_title',
+            'V' => 'v_title',
+            default => 'term',
+        };
+        $info = ['volume' => $pageInfo->volume, 'page' => $pageInfo->page, 'found' => true];
+        foreach (BookTitle::get() as $row) {
+            if ($row['id'] === $pageInfo->pcd_book_id) {
+                $info['bookName'] = $row[$field];
+                break;
+            }
+        }
+
+        return $info;
+    }
+
+    /**
+     * 缅文标题(书名缩写 + 页码,如「ဝိ၊၁၊၂၃」)→ 书名 / 册 / 页。
+     *
+     * @return array<string, mixed>
+     */
+    private function myanmarTitle(string $title): array
+    {
+        $titles = array_column(BookTitle::my(), 'title2');
+        for ($i = mb_strlen($title, 'UTF-8'); $i > 0; $i--) {
+            $prefix = mb_substr($title, 0, $i);
+            $found = array_search($prefix, $titles, true);
+            if ($found === false) {
+                continue;
+            }
+            $page = (int) str_replace(
+                ['၁', '၂', '၃', '၄', '၅', '၆', '၇', '၈', '၉', '၀'],
+                ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'],
+                (string) preg_replace('/^[၊။\s]+|[၊။\s]+$/u', '', mb_substr($title, $i)),
+            );
+            $row = BookTitle::my()[$found];
+
+            return [
+                'bookName' => $row['bookname'],
+                'volume' => $row['volume'],
+                'page' => $page,
+                'found' => $row['bookname'] !== '',
+            ];
+        }
+
+        return [];
+    }
+}

+ 64 - 0
api-v13/app/Services/Markup/Resolve/QuoteLoader.php

@@ -0,0 +1,64 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Models\PaliText;
+
+/**
+ * quote 模板:按 `book-para` 取段落的目录标题与路径,一次查完。
+ */
+final class QuoteLoader extends Loader
+{
+    /** @var array<string, array{0: int, 1: int}> */
+    private array $pending = [];
+
+    /** @var array<string, array{toc: string, path: mixed}|null> */
+    private array $results = [];
+
+    public function request(string $paraId): void
+    {
+        $parts = explode('-', $paraId);
+        if (count($parts) < 2 || ! ctype_digit($parts[0]) || ! ctype_digit($parts[1])) {
+            $this->results[$paraId] = null;
+
+            return;
+        }
+        if (! array_key_exists($paraId, $this->results)) {
+            $this->pending[$paraId] = [(int) $parts[0], (int) $parts[1]];
+        }
+    }
+
+    /**
+     * @return array{toc: string, path: mixed}|null
+     */
+    public function result(string $paraId): ?array
+    {
+        return $this->results[$paraId] ?? null;
+    }
+
+    public function hasPending(): bool
+    {
+        return $this->pending !== [];
+    }
+
+    public function load(): void
+    {
+        $batch = $this->pending;
+        $this->pending = [];
+        $rows = PaliText::query()
+            ->where(function ($query) use ($batch) {
+                foreach ($batch as [$book, $para]) {
+                    $query->orWhere(fn ($where) => $where->where('book', $book)->where('paragraph', $para));
+                }
+            })
+            ->get(['book', 'paragraph', 'toc', 'path'])
+            ->keyBy(fn (PaliText $row) => "{$row->book}-{$row->paragraph}");
+        foreach ($batch as $paraId => [$book, $para]) {
+            $row = $rows->get("{$book}-{$para}");
+            $this->results[$paraId] = $row === null ? null : [
+                'toc' => (string) $row->toc,
+                'path' => json_decode((string) $row->path, true),
+            ];
+        }
+    }
+}

+ 92 - 0
api-v13/app/Services/Markup/Resolve/Resolver.php

@@ -0,0 +1,92 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Element;
+use App\Services\Markup\Ir\Node;
+use App\Services\Markup\Parsing\MarkupParser;
+use App\Services\Markup\RenderOptions;
+
+/**
+ * 一次渲染的取数中心:遍历 IR 让每个模板登记要查的键,再按 loader 批量查。
+ *
+ * 一章几百个术语、几百个句子,各查一次(加上回退查询)而不是每个模板各查几次。
+ */
+final class Resolver
+{
+    /** 取数轮数上限:文章 → 句子 → 术语 note → … 每层一轮,正常两三轮就停 */
+    private const MAX_ROUNDS = 10;
+
+    /** @var array<class-string<Loader>, Loader> */
+    private array $loaders = [];
+
+    private ChannelDirectory $channels;
+
+    public function __construct(
+        public readonly RenderOptions $options,
+        public readonly MarkupParser $parser,
+    ) {
+        $this->channels = new ChannelDirectory;
+    }
+
+    /**
+     * @template T of Loader
+     *
+     * @param  class-string<T>  $class
+     * @return T
+     */
+    public function loader(string $class): Loader
+    {
+        if (! isset($this->loaders[$class])) {
+            $loader = app()->make($class);
+            $loader->setResolver($this);
+            $this->loaders[$class] = $loader;
+        }
+
+        /** @var T */
+        return $this->loaders[$class];
+    }
+
+    public function channels(): ChannelDirectory
+    {
+        return $this->channels;
+    }
+
+    public function collect(Document $document): void
+    {
+        $this->channels->request($document->scope->channels);
+        $this->collectNodes($document->nodes);
+    }
+
+    /**
+     * @param  list<Node>  $nodes
+     */
+    private function collectNodes(array $nodes): void
+    {
+        foreach ($nodes as $node) {
+            if ($node instanceof Element) {
+                $this->collectNodes($node->children);
+            } elseif ($node instanceof Call) {
+                $node->template->collect($node, $this);
+                foreach ($node->slots as $slot) {
+                    $this->collect($slot);
+                }
+            }
+        }
+    }
+
+    public function run(): void
+    {
+        for ($round = 0; $round < self::MAX_ROUNDS; $round++) {
+            $pending = array_filter($this->loaders, fn (Loader $loader) => $loader->hasPending());
+            if ($pending === []) {
+                return;
+            }
+            foreach ($pending as $loader) {
+                $loader->load();
+            }
+        }
+    }
+}

+ 183 - 0
api-v13/app/Services/Markup/Resolve/SentenceLoader.php

@@ -0,0 +1,183 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Models\CustomBook;
+use App\Models\Sentence;
+use App\Services\ChannelService;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Scope;
+
+/**
+ * 句子模板的取数:按坐标取若干 channel 的句子,正文解析成下一层内容。
+ *
+ * channel 口径同 v2 CorpusController::getSentTpl():调用方给的 channel,再加原文 channel——
+ * 三藏(book < 1000)阅读模式是 `_System_Pali_VRI_`、编辑模式是 `_System_Wbw_VRI_`;自定义书是该书的 channel。
+ * 所有句子一次查完(按段落分组 OR)。
+ *
+ * 只取渲染要用的字段。编辑器还要的 editor / studio / suggestionCount 等不在这里——
+ * 那是编辑接口的契约,迁编辑模式时在 v3 另做。
+ */
+final class SentenceLoader extends Loader
+{
+    /** @var array<string, array{id: string, channels: list<string>, mode: string, depth: int}> */
+    private array $pending = [];
+
+    /** @var array<string, array<string, mixed>|null> */
+    private array $results = [];
+
+    public function __construct(private readonly ChannelService $channelService) {}
+
+    /**
+     * @param  list<string>  $channels
+     */
+    public function request(string $id, array $channels, string $mode, Scope $scope): string
+    {
+        // 层数进 key:句子正文里再引用同一个句子时,每层各有自己的结果,到最大层数为止(否则渲染时无限递归)
+        $key = implode("\x1F", [$id, implode(',', $channels), $mode, $scope->depth]);
+        if (! array_key_exists($key, $this->results)) {
+            $this->pending[$key] = ['id' => $id, 'channels' => $channels, 'mode' => $mode, 'depth' => $scope->depth];
+        }
+
+        return $key;
+    }
+
+    /**
+     * @return array{book: int, para: int, wordStart: int, wordEnd: int, origin: list<array<string, mixed>>, translation: list<array<string, mixed>>, commentaries: list<array<string, mixed>>}|null
+     */
+    public function result(string $key): ?array
+    {
+        return $this->results[$key] ?? null;
+    }
+
+    public function hasPending(): bool
+    {
+        return $this->pending !== [];
+    }
+
+    public function load(): void
+    {
+        $batch = $this->pending;
+        $this->pending = [];
+
+        $requests = [];
+        foreach ($batch as $key => $request) {
+            $parts = explode('-', $request['id']);
+            if (count($parts) !== 4 || array_filter($parts, fn ($part) => ! ctype_digit(trim($part))) !== []) {
+                $this->results[$key] = null;
+
+                continue;
+            }
+            $requests[$key] = $request + ['coords' => array_map('intval', $parts)];
+        }
+        if ($requests === []) {
+            return;
+        }
+
+        $customBooks = $this->customBookChannels($requests);
+        $channelsByKey = [];
+        $allChannels = [];
+        $paragraphs = [];
+        foreach ($requests as $key => $request) {
+            [$book, $para] = $request['coords'];
+            $origin = $book < 1000
+                ? $this->channelService->systemUid($request['mode'] === 'read' ? '_System_Pali_VRI_' : '_System_Wbw_VRI_')
+                : ($customBooks[$book] ?? false);
+            $channels = $request['channels'];
+            if ($origin !== false && $origin !== null) {
+                $channels[] = (string) $origin;
+            }
+            $channels = array_values(array_unique($channels));
+            $channelsByKey[$key] = $channels;
+            array_push($allChannels, ...$channels);
+            $paragraphs["{$book}-{$para}"] = [$book, $para];
+        }
+        $this->resolver->channels()->request($allChannels);
+
+        $rows = Sentence::query()
+            ->where(function ($query) use ($paragraphs) {
+                foreach ($paragraphs as [$book, $para]) {
+                    $query->orWhere(fn ($where) => $where->where('book_id', $book)->where('paragraph', $para));
+                }
+            })
+            ->whereIn('channel_uid', array_values(array_unique($allChannels)))
+            ->get(['uid', 'book_id', 'paragraph', 'word_start', 'word_end', 'channel_uid', 'content', 'content_type'])
+            ->keyBy(fn (Sentence $row) => "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}@{$row->channel_uid}");
+
+        foreach ($requests as $key => $request) {
+            [$book, $para, $start, $end] = $request['coords'];
+            $result = [
+                'book' => $book, 'para' => $para, 'wordStart' => $start, 'wordEnd' => $end,
+                'origin' => [], 'translation' => [], 'commentaries' => [],
+            ];
+            foreach ($channelsByKey[$key] as $channelUid) {
+                $row = $rows->get("{$book}-{$para}-{$start}-{$end}@{$channelUid}");
+                $channel = $this->resolver->channels()->get($channelUid);
+                if ($row === null || $channel === null) {
+                    continue;
+                }
+                $entry = [
+                    'id' => (string) $row->uid,
+                    'channel' => [
+                        'id' => (string) $channel->uid,
+                        'name' => (string) $channel->name,
+                        'type' => (string) $channel->type,
+                        'lang' => (string) $channel->lang,
+                    ],
+                    'contentType' => (string) $row->content_type,
+                    'content' => (string) $row->content,
+                    'body' => $this->body($row, (string) $channel->type, $request),
+                ];
+                $area = match ((string) $channel->type) {
+                    'original', 'wbw' => 'origin',
+                    'commentary' => 'commentaries',
+                    default => 'translation',
+                };
+                $result[$area][] = $entry;
+            }
+            $this->results[$key] = $result;
+        }
+    }
+
+    /**
+     * 句子正文 → 下一层内容。逐词解析的 json(非 nissaya channel)不是标记文本,不解析。
+     *
+     * @param  array{channels: list<string>, depth: int}  $request
+     */
+    private function body(Sentence $row, string $channelType, array $request): ?Document
+    {
+        $parent = new Scope(channels: $request['channels'], depth: $request['depth']);
+        if (! $parent->canNest() || ($row->content_type === 'json' && $channelType !== 'nissaya')) {
+            return null;
+        }
+        // 义注 channel 的正文按全部 channel 渲染(v2 口径),其余按本句的 channel
+        $channels = $channelType === 'commentary' ? $request['channels'] : [(string) $row->channel_uid];
+        $document = $this->resolver->parser->parse(
+            (string) $row->content,
+            $parent->nested($channels, (string) $row->content_type, $channelType === 'nissaya' ? 'nissaya' : 'translation'),
+        );
+        $this->resolver->collect($document);
+
+        return $document;
+    }
+
+    /**
+     * 自定义书(book ≥ 1000)的原文 channel。
+     *
+     * @param  array<string, array{coords: list<int>}>  $requests
+     * @return array<int, string>
+     */
+    private function customBookChannels(array $requests): array
+    {
+        $books = array_values(array_unique(array_filter(
+            array_map(fn ($request) => $request['coords'][0], $requests),
+            fn (int $book) => $book >= 1000,
+        )));
+        if ($books === []) {
+            return [];
+        }
+
+        return CustomBook::whereIn('book_id', $books)->pluck('channel_id', 'book_id')
+            ->map(fn ($uid) => (string) $uid)->all();
+    }
+}

+ 190 - 0
api-v13/app/Services/Markup/Resolve/TermLoader.php

@@ -0,0 +1,190 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Models\DhammaTerm;
+use App\Services\ChannelService;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Scope;
+use Illuminate\Support\Collection;
+
+/**
+ * 术语查询,口径同 v2 TemplateRender::getTermProps():
+ *
+ * 1. 这个 channel 自己的术语(最新的一条)
+ * 2. channel 拥有者名下、不属于任何 channel 的术语:语言完全一致优先,其次同语族
+ * 3. 社区术语 channel `_community_term_zh-hans_`
+ *
+ * 没有 channel(或 channel 不存在)时不查,只回显词头。tag 为空表示不按 tag 过滤。
+ * 术语的 note 只展开一层:note 里出现的术语只查译名,不再取它们自己的 note。
+ * 每个 channel 三次查询,与术语个数无关。
+ */
+final class TermLoader extends Loader
+{
+    private const COMMUNITY_CHANNEL = '_community_term_zh-hans_';
+
+    /** @var array<string, array{word: string, tag: string, channel: ?string, depth: int, inTermNote: bool}> */
+    private array $pending = [];
+
+    /** @var array<string, array{term: ?DhammaTerm, community: bool, channel: ?string, studio: ?string, note: ?Document}> */
+    private array $results = [];
+
+    public function __construct(private readonly ChannelService $channelService) {}
+
+    public function request(string $word, string $tag, ?string $channel, Scope $scope): string
+    {
+        // 层数进 key:note 里再引用同一个术语时,每层各有自己的结果,到最大层数为止(否则渲染时无限递归)
+        $key = implode("\x1F", [$word, $tag, $channel ?? '', $scope->depth, (int) $scope->inTermNote]);
+        if (! isset($this->results[$key])) {
+            $this->pending[$key] = ['word' => $word, 'tag' => $tag, 'channel' => $channel, 'depth' => $scope->depth, 'inTermNote' => $scope->inTermNote];
+        }
+
+        return $key;
+    }
+
+    /**
+     * @return array{term: ?DhammaTerm, community: bool, channel: ?string, studio: ?string, note: ?Document}
+     */
+    public function result(string $key): array
+    {
+        return $this->results[$key] ?? ['term' => null, 'community' => false, 'channel' => null, 'studio' => null, 'note' => null];
+    }
+
+    public function hasPending(): bool
+    {
+        return $this->pending !== [];
+    }
+
+    public function load(): void
+    {
+        $batch = $this->pending;
+        $this->pending = [];
+
+        $byChannel = [];
+        foreach ($batch as $key => $request) {
+            $byChannel[$request['channel'] ?? ''][$key] = $request;
+        }
+
+        $community = null;
+        foreach ($byChannel as $channelUid => $requests) {
+            $channel = $this->resolver->channels()->get($channelUid === '' ? null : $channelUid);
+            if ($channel === null) {
+                // 没给 channel:不查。给了但 channel 已不存在(被删):只查社区术语(v2 口径)
+                $community = $channelUid === '' ? null : ($community ?? $this->communityTerms(array_column($batch, 'word')));
+                foreach ($requests as $key => $request) {
+                    $term = $community === null ? null : $this->first($community, $request);
+                    $this->results[$key] = [
+                        'term' => $term,
+                        'community' => $term !== null,
+                        'channel' => $request['channel'],
+                        'studio' => null,
+                        'note' => $request['inTermNote'] ? null : $this->note($term, $channelUid, $request['depth']),
+                    ];
+                }
+
+                continue;
+            }
+            $words = array_values(array_unique(array_column($requests, 'word')));
+            $own = DhammaTerm::whereIn('word', $words)->where('channal', $channelUid)
+                ->orderByDesc('updated_at')->get();
+            $studio = DhammaTerm::whereIn('word', $words)->where('owner', $channel->owner_uid)
+                ->where(fn ($query) => $query->whereNull('channal')->orWhere('channal', ''))
+                ->orderByDesc('updated_at')->get();
+            $community ??= $this->communityTerms(array_column($batch, 'word'));
+
+            foreach ($requests as $key => $request) {
+                $term = $this->first($own, $request);
+                $isCommunity = false;
+                if ($term === null) {
+                    $term = $this->bestByLanguage($studio, $request, (string) $channel->lang);
+                }
+                if ($term === null) {
+                    $term = $this->first($community, $request);
+                    $isCommunity = $term !== null;
+                }
+                $this->results[$key] = [
+                    'term' => $term,
+                    'community' => $isCommunity,
+                    'channel' => $channelUid,
+                    'studio' => (string) $channel->owner_uid,
+                    'note' => $request['inTermNote'] ? null : $this->note($term, $channelUid, $request['depth']),
+                ];
+            }
+        }
+    }
+
+    /**
+     * @param  list<string>  $words
+     * @return Collection<int, DhammaTerm>
+     */
+    private function communityTerms(array $words): Collection
+    {
+        $uid = $this->channelService->systemUid(self::COMMUNITY_CHANNEL);
+        if ($uid === false) {
+            return new Collection;
+        }
+
+        return DhammaTerm::whereIn('word', array_values(array_unique($words)))->where('channal', $uid)
+            ->orderByDesc('updated_at')->get();
+    }
+
+    /**
+     * @param  Collection<int, DhammaTerm>  $terms
+     * @param  array{word: string, tag: string}  $request
+     */
+    private function first(Collection $terms, array $request): ?DhammaTerm
+    {
+        return $terms->first(fn (DhammaTerm $term) => $this->matches($term, $request));
+    }
+
+    /**
+     * 语言完全一致记 2 分、同语族记 1 分,取分高的;同分取最新的。
+     *
+     * @param  Collection<int, DhammaTerm>  $terms
+     * @param  array{word: string, tag: string}  $request
+     */
+    private function bestByLanguage(Collection $terms, array $request, string $lang): ?DhammaTerm
+    {
+        $family = explode('-', $lang)[0];
+        $best = null;
+        $bestScore = 0;
+        foreach ($terms as $term) {
+            if (! $this->matches($term, $request)) {
+                continue;
+            }
+            $language = (string) $term->language;
+            $score = $language === $lang ? 2 : ($family !== '' && str_contains($language, $family) ? 1 : 0);
+            if ($score > $bestScore) {
+                [$best, $bestScore] = [$term, $score];
+            }
+        }
+
+        return $best;
+    }
+
+    /**
+     * @param  array{word: string, tag: string}  $request
+     */
+    private function matches(DhammaTerm $term, array $request): bool
+    {
+        return $term->word === $request['word'] && ($request['tag'] === '' || $term->tag === $request['tag']);
+    }
+
+    private function note(?DhammaTerm $term, string $channelUid, int $depth): ?Document
+    {
+        $note = (string) ($term?->note ?? '');
+        $scope = new Scope(channels: [$channelUid], depth: $depth);
+        if (trim($note) === '' || ! $scope->canNest()) {
+            return null;
+        }
+        $nested = $scope->nested(contentType: $term->getAttribute('content_type') ?? 'markdown');
+        // note 里的术语不再展开它们自己的 note:一层就够(v2 也只展开一层),否则词条正文互相引用会成倍膨胀
+        $document = $this->resolver->parser->parse(
+            $note,
+            new Scope($nested->channels, $nested->dialect, $nested->depth, $nested->channelType, $nested->contentType, inTermNote: true),
+        );
+        $this->resolver->collect($document);
+
+        return $document;
+    }
+}

+ 76 - 0
api-v13/app/Services/Markup/Resolve/TplLoader.php

@@ -0,0 +1,76 @@
+<?php
+
+namespace App\Services\Markup\Resolve;
+
+use App\Models\Article;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Scope;
+use Mustache\Engine as Mustache;
+
+/**
+ * `{{Tpl:名字|…}}`:取标题为「Tpl:名字」的文章,用 Mustache 代入参数,结果按 markdown 解析成下一层内容。
+ */
+final class TplLoader extends Loader
+{
+    /** @var array<string, array{title: string, params: array<string, string>, scope: Scope}> */
+    private array $pending = [];
+
+    /** @var array<string, array{content: string, document: ?Document}|null> */
+    private array $results = [];
+
+    /**
+     * @param  array<string, string>  $params
+     */
+    public function request(string $title, array $params, Scope $scope): string
+    {
+        // 层数进 key:模板正文里再用同一个模板时逐层展开,到最大层数为止
+        $key = $title."\x1F".json_encode($params)."\x1F".$scope->depth;
+        if (! array_key_exists($key, $this->results)) {
+            $this->pending[$key] = ['title' => $title, 'params' => $params, 'scope' => $scope];
+        }
+
+        return $key;
+    }
+
+    /**
+     * @return array{content: string, document: ?Document}|null
+     */
+    public function result(string $key): ?array
+    {
+        return $this->results[$key] ?? null;
+    }
+
+    public function hasPending(): bool
+    {
+        return $this->pending !== [];
+    }
+
+    public function load(): void
+    {
+        $batch = $this->pending;
+        $this->pending = [];
+        $articles = Article::whereIn('title', array_values(array_unique(array_column($batch, 'title'))))
+            ->get(['title', 'content'])
+            ->keyBy('title');
+        $mustache = new Mustache(['entity_flags' => ENT_QUOTES, 'escape' => fn ($value) => $value]);
+
+        foreach ($batch as $key => $request) {
+            $article = $articles->get($request['title']);
+            if ($article === null) {
+                $this->results[$key] = null;
+
+                continue;
+            }
+            $content = (string) $article->content;
+            if ($request['params'] !== []) {
+                $content = $mustache->render($content, $request['params']);
+            }
+            $document = null;
+            if ($request['scope']->canNest()) {
+                $document = $this->resolver->parser->parse($content, $request['scope']->nested(contentType: $request['scope']->contentType));
+                $this->resolver->collect($document);
+            }
+            $this->results[$key] = ['content' => $content, 'document' => $document];
+        }
+    }
+}

+ 38 - 0
api-v13/app/Services/Markup/Templates/AiTemplate.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * AI 对话组件:`{{ai|model}}`。prompt 输出里不出现。
+ */
+final class AiTemplate extends Template
+{
+    protected string $component = 'ai';
+
+    public function params(): array
+    {
+        return ['model' => ParamSpec::at(1, '1')];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['model' => (string) $call->param('model')];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return 'ai';
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $format === Format::Prompt ? '' : 'ai';
+    }
+}

+ 71 - 0
api-v13/app/Services/Markup/Templates/ArticleTemplate.php

@@ -0,0 +1,71 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 嵌入文章 / 章节:`{{article|type|id|title|channel|style|book|paragraphs|anthology}}`。
+ * `type=chapter` 且没给 id 时由 book + paragraphs 拼出 id。
+ */
+final class ArticleTemplate extends Template
+{
+    protected string $component = 'article';
+
+    public function params(): array
+    {
+        return [
+            'type' => ParamSpec::at(1),
+            'id' => ParamSpec::at(2),
+            'title' => ParamSpec::at(3),
+            'channel' => ParamSpec::at(4),
+            'style' => ParamSpec::at(5),
+            'book' => ParamSpec::at(6),
+            'paragraphs' => ParamSpec::at(7),
+            'anthology' => ParamSpec::at(8),
+        ];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        $type = (string) $call->param('type');
+        $id = (string) $call->param('id');
+        $book = (string) $call->param('book');
+        $paragraphs = (string) $call->param('paragraphs');
+        if ($type === 'chapter' && $id === '') {
+            $id = ((int) $book).'-'.((int) $paragraphs);
+        }
+        $props = ['type' => $type, 'id' => $id];
+        // style 为空时不给:前端组件用它自己的默认值(modal),传空串反而什么都不渲染
+        foreach (['style', 'channel', 'title', 'anthology'] as $name) {
+            $value = (string) $call->param($name);
+            if ($value !== '') {
+                $props[$name] = $value;
+            }
+        }
+        if ($book !== '') {
+            $props['book'] = $book;
+        }
+        if ($paragraphs !== '') {
+            $props['paragraphs'] = $paragraphs;
+        }
+        $props['parentChannels'] = $call->scope->channels;
+
+        return $props;
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $format === Format::Prompt ? '' : (string) $call->param('title');
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        return '';
+    }
+}

+ 34 - 0
api-v13/app/Services/Markup/Templates/CategoryTemplate.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 分类标签:`{{category|name}}`。
+ *
+ * v2 把它的组件名误写成 para;这里用 category,前端补对应组件。
+ */
+final class CategoryTemplate extends Template
+{
+    protected string $component = 'category';
+
+    public function params(): array
+    {
+        return ['name' => ParamSpec::at(1)];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['name' => (string) $call->param('name')];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return (string) $call->param('name');
+    }
+}

+ 32 - 0
api-v13/app/Services/Markup/Templates/DictPrefTemplate.php

@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 词典前缀列表组件:`{{dict-pref|page|size}}`(缺省第 1 页、每页 100)。
+ */
+final class DictPrefTemplate extends Template
+{
+    protected string $component = 'dict-pref';
+
+    public function params(): array
+    {
+        return ['page' => ParamSpec::at(1, '1'), 'size' => ParamSpec::at(2, '100')];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['currPage' => (int) $call->param('page'), 'pageSize' => (int) $call->param('size')];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return 'dict-pref';
+    }
+}

+ 42 - 0
api-v13/app/Services/Markup/Templates/ExerciseTemplate.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 练习题:`{{exercise|id}}`。title 与 id 共用第 1 个位置(v2 如此),通常写成 `title=`。
+ */
+final class ExerciseTemplate extends Template
+{
+    protected string $component = 'exercise';
+
+    public function params(): array
+    {
+        return ['id' => ParamSpec::at(1), 'title' => ParamSpec::at(1)];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return [
+            'id' => (string) $call->param('id'),
+            'title' => (string) $call->param('title'),
+            'channel' => $call->scope->firstChannel(),
+        ];
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $format === Format::Prompt ? '' : (string) $call->param('title');
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        return '';
+    }
+}

+ 54 - 0
api-v13/app/Services/Markup/Templates/GrammarTemplate.php

@@ -0,0 +1,54 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\ChannelService;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\Resolver;
+use App\Services\Markup\Resolve\TermLoader;
+
+/**
+ * 语法术语查询:`{{g|word}}`,在系统语法术语 channel(`_System_Grammar_Term_{lang}_`,缺省 en)里查。
+ */
+final class GrammarTemplate extends Template
+{
+    protected string $component = 'grammar';
+
+    public function __construct(private readonly ChannelService $channelService) {}
+
+    public function params(): array
+    {
+        return ['word' => ParamSpec::at(1)];
+    }
+
+    public function collect(Call $call, Resolver $resolver): void
+    {
+        $lang = $resolver->channels()->get($call->scope->firstChannel())?->lang ?: $resolver->options->lang;
+        $channel = $this->channelService->systemUid(
+            '_System_Grammar_Term_'.strtolower((string) $lang).'_',
+            '_System_Grammar_Term_en_',
+        );
+        $call->data['term'] = $resolver->loader(TermLoader::class)->request(
+            (string) $call->param('word'),
+            '',
+            $channel === false ? null : $channel,
+            $call->scope,
+        );
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        $word = (string) $call->param('word');
+
+        return ['word' => $word, 'term' => TermTemplate::termProps($ctx, $call->data['term'] ?? null, $word)];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return (string) $call->param('word');
+    }
+}

+ 48 - 0
api-v13/app/Services/Markup/Templates/Internal/AnnoAssessmentTemplate.php

@@ -0,0 +1,48 @@
+<?php
+
+namespace App\Services\Markup\Templates\Internal;
+
+use App\Services\AnnotationLayout;
+use App\Services\HtmlAnnotationMarkup;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Templates\ParamSpec;
+use App\Services\Markup\Templates\Template;
+
+/**
+ * 阅读页句尾的评估对勾:颜色按分数档位(high / medium / low),点击看分数与理由。
+ * 没有 id 的是「同段别的句子评估过、这句没有」的灰色对勾(level none,不能点)。由批注注入生成。
+ * 纯文本 / markdown 不输出。
+ */
+final class AnnoAssessmentTemplate extends Template
+{
+    protected string $component = 'anno-assessment';
+
+    public function params(): array
+    {
+        return ['id' => new ParamSpec, 'score' => new ParamSpec];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        $id = (string) $call->param('id');
+        if ($id === '') {
+            return ['level' => 'none'];
+        }
+        $score = (int) $call->param('score');
+
+        return ['id' => $id, 'score' => $score, 'level' => AnnotationLayout::assessmentLevel($score)];
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $id = (string) $call->param('id');
+
+        return $id === ''
+            ? HtmlAnnotationMarkup::unassessedMark()
+            : (new HtmlAnnotationMarkup)->assessmentMark($id, (int) $call->param('score'));
+    }
+}

+ 36 - 0
api-v13/app/Services/Markup/Templates/Internal/AnnoIssueMarkTemplate.php

@@ -0,0 +1,36 @@
+<?php
+
+namespace App\Services\Markup\Templates\Internal;
+
+use App\Services\HtmlAnnotationMarkup;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Templates\ParamSpec;
+use App\Services\Markup\Templates\Template;
+
+/**
+ * 阅读页句尾的三角叹号:没有位置的 issue 合成一个,点击看 issue。由批注注入生成。
+ * 纯文本 / markdown 不输出。
+ */
+final class AnnoIssueMarkTemplate extends Template
+{
+    protected string $component = 'anno-issue-mark';
+
+    public function params(): array
+    {
+        return ['ids' => new ParamSpec, 'severity' => new ParamSpec];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['ids' => AnnoIssueTemplate::ids($call), 'severity' => AnnoIssueTemplate::severity($call)];
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        return (new HtmlAnnotationMarkup)->issueMark(AnnoIssueTemplate::ids($call), AnnoIssueTemplate::severity($call));
+    }
+}

+ 82 - 0
api-v13/app/Services/Markup/Templates/Internal/AnnoIssueTemplate.php

@@ -0,0 +1,82 @@
+<?php
+
+namespace App\Services\Markup\Templates\Internal;
+
+use App\Services\HtmlAnnotationMarkup;
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Templates\ParamSpec;
+use App\Services\Markup\Templates\Template;
+
+/**
+ * 阅读页的 issue 高亮:包住锚定的那段正文,点击看 issue。由批注注入生成,正文里写不出来。
+ *
+ * tree:`{name: 'anno-issue', props: {ids, severity}, children}`;html 与阅读器 CSS 约定的 span 一致;
+ * 纯文本 / markdown 只输出被包住的正文。
+ */
+final class AnnoIssueTemplate extends Template
+{
+    protected string $component = 'anno-issue';
+
+    public function params(): array
+    {
+        return ['ids' => new ParamSpec, 'severity' => new ParamSpec];
+    }
+
+    /**
+     * @return list<string>
+     */
+    public static function ids(Call $call): array
+    {
+        return array_values(array_filter(explode(',', (string) $call->param('ids'))));
+    }
+
+    public static function severity(Call $call): ?string
+    {
+        $severity = (string) $call->param('severity');
+
+        return $severity === '' ? null : $severity;
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['ids' => self::ids($call), 'severity' => self::severity($call)];
+    }
+
+    public function children(Call $call, RenderContext $ctx): ?Document
+    {
+        return $call->slot('content');
+    }
+
+    private function inner(Call $call, RenderContext $ctx): string
+    {
+        $content = $call->slot('content');
+
+        return $content === null ? '' : $ctx->renderString($content);
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $this->inner($call, $ctx);
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $this->inner($call, $ctx);
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        return HtmlAnnotationMarkup::issueOpenTag(self::ids($call), self::severity($call)).$this->inner($call, $ctx).'</span>';
+    }
+
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        return $this->inner($call, $ctx);
+    }
+}

+ 58 - 0
api-v13/app/Services/Markup/Templates/MermaidTemplate.php

@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 图表:```mermaid 围栏(解析时转成本模板)。源码原样,不做 markdown 解析、不再 base64。
+ *
+ * html 输出 `<pre class="mermaid">`,由 library 页面按需加载 mermaid.js 渲染;没有 JS 时显示源码。
+ */
+final class MermaidTemplate extends Template
+{
+    protected string $component = 'mermaid';
+
+    public function params(): array
+    {
+        return ['text' => ParamSpec::at(1)];
+    }
+
+    private function source(Call $call): string
+    {
+        return (string) $call->params->raw('text', 1);
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['text' => $this->source($call)];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return 'mermaid';
+    }
+
+    /**
+     * prompt 给 LLM 原文:它读得懂 mermaid,只给「mermaid」一词会丢掉图里的信息。
+     */
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $format === Format::Prompt ? $this->markdown($call, $ctx) : 'mermaid';
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        return '<pre class="mermaid">'.e($this->source($call)).'</pre>';
+    }
+
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        return "```mermaid\n".$this->source($call)."\n```";
+    }
+}

+ 56 - 0
api-v13/app/Services/Markup/Templates/NissayaTemplate.php

@@ -0,0 +1,56 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+use App\Tools\Tools;
+
+/**
+ * 缅文逐词释义:`{{nissaya|巴利|意思=意思2}}`。nissaya channel 的 `巴利=意思` 行解析时自动转成它。
+ */
+final class NissayaTemplate extends Template
+{
+    protected string $component = 'nissaya';
+
+    public function params(): array
+    {
+        return ['pali' => ParamSpec::at(1), 'meaning' => ParamSpec::at(2)];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return [
+            'pali' => (string) $call->param('pali'),
+            'meaning' => explode('=', (string) $call->param('meaning')),
+        ];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $call->param('pali').'၊'.$call->param('meaning');
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        if ($format !== Format::Prompt) {
+            return $this->text($call, $ctx);
+        }
+        $meanings = explode('=', (string) $call->param('meaning'));
+
+        return Tools::MyToRm((string) $call->param('pali')).':'.end($meanings);
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $lang = $ctx->lang($call->scope);
+        $pali = e((string) $call->param('pali'));
+        $prefix = $lang === 'my' ? "<span lang=\"pi-Mymr\">{$pali}</span>၊ " : "<span lang=\"pi-Latn\">{$pali}</span> ";
+
+        return $prefix.'<span lang="'.e($lang).'">'.e((string) $call->param('meaning')).'</span>';
+    }
+}

+ 132 - 0
api-v13/app/Services/Markup/Templates/NoteTemplate.php

@@ -0,0 +1,132 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Dialect;
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Params;
+use App\Services\Markup\Render\HtmlRenderer;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 脚注:`{{note|正文}}`、`{{n|正文}}`、```note 围栏;旧方言还有 `` `正文` `` 与单独一行的 ``` 围栏。
+ *
+ * 正文是 markdown(可换行、可分段、可嵌模板)。角标总在行内:写在哪里就在哪里。
+ *
+ * 参数:text(正文)、trigger(角标文字)、cite(来源说明)、citelink(book-para-start-end 跳转坐标)。
+ * E2 方言只认第一个位置参数是正文,其余参数必须写名字;不是已声明参数名的片段连同 `|` 拼回正文,
+ * 所以正文里出现 `|`、`a=b` 都不会被拆开。
+ */
+final class NoteTemplate extends Template
+{
+    protected string $component = 'note';
+
+    public function params(): array
+    {
+        return [
+            'text' => ParamSpec::markdown(1),
+            'trigger' => ParamSpec::at(2),
+            'cite' => ParamSpec::at(3),
+            'citelink' => ParamSpec::at(4),
+        ];
+    }
+
+    public function parseParams(array $segments, Dialect $dialect): Params
+    {
+        if ($dialect === Dialect::Markdown) {
+            return parent::parseParams($segments, $dialect);
+        }
+        $named = [];
+        $body = [];
+        foreach ($segments as $segment) {
+            if (preg_match('/^(text|trigger|cite|citelink)=(.*)$/s', $segment, $m) === 1) {
+                $named[$m[1]] = $m[2];
+            } else {
+                $body[] = $segment;
+            }
+        }
+        $positional = $body === [] ? [] : [1 => implode('|', $body)];
+
+        return new Params($named, $positional);
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return array_filter([
+            'trigger' => (string) $call->param('trigger'),
+            'cite' => (string) $call->param('cite'),
+            'citelink' => (string) $call->param('citelink'),
+        ], fn (string $value) => $value !== '');
+    }
+
+    public function children(Call $call, RenderContext $ctx): ?Document
+    {
+        return $call->slot('text');
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return (string) $call->param('trigger');
+    }
+
+    /**
+     * 纯文本里只留角标文字;simple 与 prompt 连角标也不要(v2 口径)。
+     */
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $format === Format::Text ? $this->text($call, $ctx) : '';
+    }
+
+    /**
+     * 边注(sidenote)结构,与 library 阅读器的 CSS 配套;同时记进文末脚注列表。
+     */
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $sn = $ctx->nextNoteNumber();
+        $trigger = (string) $call->param('trigger');
+        // 角标嵌在句子中间:正文只能是行内元素,否则浏览器会切断 sidenote 的结构
+        $slot = $call->slot('text');
+        $content = $slot !== null && $ctx->renderer instanceof HtmlRenderer
+            ? $ctx->renderer->inlineSafe($slot, $ctx)
+            : $this->content($call, $ctx);
+        $ctx->footnotes[] = ['sn' => $sn, 'trigger' => $trigger, 'content' => $content];
+
+        $target = '';
+        $parts = explode('-', (string) $call->param('citelink'));
+        if (count($parts) === 4) {
+            $target = ' data-book="'.e($parts[0]).'" data-para="'.e($parts[1]).'" data-start="'.e($parts[2]).'" data-end="'.e($parts[3]).'"';
+        }
+        $cite = (string) $call->param('cite');
+        $citeHtml = $cite === '' ? '' : '<cite class="anno-jump"'.$target.'>'.e($cite).'</cite>';
+
+        $id = $ctx->htmlId('sn', $sn);
+
+        return '<label for="'.$id.'" class="margin-toggle sidenote-number"'.$target.'>'.e($trigger).'</label>'
+            .'<input type="checkbox" id="'.$id.'" class="margin-toggle"/>'
+            .'<span class="sidenote">'.$content.$citeHtml.'</span>';
+    }
+
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        $sn = $ctx->nextNoteNumber();
+        $ctx->footnotes[] = [
+            'sn' => $sn,
+            'trigger' => (string) $call->param('trigger'),
+            'content' => $this->content($call, $ctx),
+        ];
+
+        return "[^{$sn}]";
+    }
+
+    private function content(Call $call, RenderContext $ctx): string
+    {
+        $slot = $call->slot('text');
+
+        return $slot === null ? '' : $ctx->renderString($slot);
+    }
+}

+ 41 - 0
api-v13/app/Services/Markup/Templates/ParaTemplate.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 嵌入经文段落:`{{para|id=book-para|title|style}}`。
+ */
+final class ParaTemplate extends Template
+{
+    protected string $component = 'para';
+
+    public function params(): array
+    {
+        return ['id' => ParamSpec::at(1), 'title' => ParamSpec::at(2), 'style' => ParamSpec::at(3)];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        $props = [
+            'id' => (string) $call->param('id'),
+            'title' => (string) $call->param('title'),
+            'style' => (string) $call->param('style'),
+        ];
+        if ($call->scope->channels !== []) {
+            $props['channel'] = implode('_', $call->scope->channels);
+        }
+
+        return $props;
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return (string) $call->param('title');
+    }
+}

+ 28 - 0
api-v13/app/Services/Markup/Templates/ParamSpec.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+/**
+ * 模板参数声明。
+ *
+ * @param  int|null  $position  位置参数序号(1 起);null 表示只能用名字传
+ * @param  bool  $markdown  值是 markdown,解析时递归解析成 slot(如脚注正文)
+ */
+final readonly class ParamSpec
+{
+    public function __construct(
+        public ?int $position = null,
+        public string $default = '',
+        public bool $markdown = false,
+    ) {}
+
+    public static function at(int $position, string $default = ''): self
+    {
+        return new self($position, $default);
+    }
+
+    public static function markdown(int $position): self
+    {
+        return new self($position, '', true);
+    }
+}

+ 47 - 0
api-v13/app/Services/Markup/Templates/QaTemplate.php

@@ -0,0 +1,47 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\QaLoader;
+use App\Services\Markup\Resolve\Resolver;
+
+/**
+ * 嵌入问答话题:`{{qa|discussion id|style}}`。
+ */
+final class QaTemplate extends Template
+{
+    protected string $component = 'qa';
+
+    public function params(): array
+    {
+        return ['id' => ParamSpec::at(1), 'style' => ParamSpec::at(2)];
+    }
+
+    public function collect(Call $call, Resolver $resolver): void
+    {
+        $resolver->loader(QaLoader::class)->request((string) $call->param('id'));
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        $id = (string) $call->param('id');
+        $props = ['id' => $id, 'title' => ''];
+        $qa = $ctx->loader(QaLoader::class)->result($id);
+        if ($qa !== null) {
+            $props['title'] = (string) $qa->title;
+            $props['resType'] = $qa->res_type;
+        }
+
+        return $props;
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return (string) $this->props($call, $ctx)['title'];
+    }
+}

+ 48 - 0
api-v13/app/Services/Markup/Templates/QualityTemplate.php

@@ -0,0 +1,48 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 质量标签:`{{quality|featured}}`。只有 featured / standard / draft / pending 四个值,其余按 pending。
+ */
+final class QualityTemplate extends Template
+{
+    protected string $component = 'quality';
+
+    private const VALUES = ['featured', 'standard', 'draft', 'pending'];
+
+    public function params(): array
+    {
+        return ['value' => ParamSpec::at(1, 'pending')];
+    }
+
+    private function value(Call $call): string
+    {
+        $value = (string) $call->param('value');
+
+        return in_array($value, self::VALUES, true) ? $value : 'pending';
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['value' => $this->value($call)];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $this->value($call);
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $value = $this->value($call);
+
+        return "<span class=\"tag-quality {$value}\">{$value}</span>";
+    }
+}

+ 72 - 0
api-v13/app/Services/Markup/Templates/QuoteLinkTemplate.php

@@ -0,0 +1,72 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\QuoteLinkLoader;
+use App\Services\Markup\Resolve\Resolver;
+
+/**
+ * 引用某版本的册页:`{{ql|type|bookname|volume|page|style|title|book|para}}`,取数口径见 {@see QuoteLinkLoader}。
+ */
+final class QuoteLinkTemplate extends Template
+{
+    protected string $component = 'quote-link';
+
+    public function params(): array
+    {
+        return [
+            'type' => ParamSpec::at(1),
+            'bookname' => ParamSpec::at(2),
+            'volume' => ParamSpec::at(3),
+            'page' => ParamSpec::at(4),
+            'style' => ParamSpec::at(5, 'modal'),
+            'title' => ParamSpec::at(6),
+            'book' => ParamSpec::at(7),
+            'para' => ParamSpec::at(8),
+        ];
+    }
+
+    public function collect(Call $call, Resolver $resolver): void
+    {
+        $call->data['quoteLink'] = $resolver->loader(QuoteLinkLoader::class)->request($call);
+    }
+
+    /**
+     * @return array{props: array<string, mixed>, text: string}
+     */
+    private function resolved(Call $call, RenderContext $ctx): array
+    {
+        $result = $ctx->loader(QuoteLinkLoader::class)->result((string) ($call->data['quoteLink'] ?? ''));
+        if ($result === null) {
+            return ['props' => ['found' => false], 'text' => ''];
+        }
+        $props = $result['props'];
+        $text = '';
+        if ($result['termKey'] !== null) {
+            $term = TermTemplate::termProps($ctx, $result['termKey'], (string) $props['bookName']);
+            $props['term'] = $term;
+            if (isset($term['id'])) {
+                $text = (string) $term['meaning'];
+            } else {
+                $text = (string) $call->param('bookname');
+            }
+        }
+
+        return ['props' => $props, 'text' => $text.$result['text']];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return $this->resolved($call, $ctx)['props'];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $this->resolved($call, $ctx)['text'];
+    }
+}

+ 51 - 0
api-v13/app/Services/Markup/Templates/QuoteTemplate.php

@@ -0,0 +1,51 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\QuoteLoader;
+use App\Services\Markup\Resolve\Resolver;
+
+/**
+ * 引用经文段落:`{{quote|book-para}}`,显示该段的目录标题。
+ */
+final class QuoteTemplate extends Template
+{
+    protected string $component = 'quote';
+
+    public function params(): array
+    {
+        return ['para' => ParamSpec::at(1)];
+    }
+
+    public function collect(Call $call, Resolver $resolver): void
+    {
+        $resolver->loader(QuoteLoader::class)->request((string) $call->param('para'));
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        $paraId = (string) $call->param('para');
+        $props = ['paraId' => $paraId];
+        $found = $ctx->loader(QuoteLoader::class)->result($paraId);
+        if ($found !== null && $found['toc'] !== '') {
+            $props['pali'] = $found['toc'];
+        }
+
+        return $props;
+    }
+
+    /**
+     * 段落的目录标题,没有就是 book-para。
+     */
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        $props = $this->props($call, $ctx);
+
+        return (string) ($props['pali'] ?? $props['paraId']);
+    }
+}

+ 69 - 0
api-v13/app/Services/Markup/Templates/ReferenceTemplate.php

@@ -0,0 +1,69 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Models\BookTitle;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 参考文献:`{{ref}}`,列出本文前面句子模板引用到的巴利文献(按书名去重)。要放在文末。
+ */
+final class ReferenceTemplate extends Template
+{
+    protected string $component = 'reference';
+
+    private const COPYRIGHT = 'CSCD V4 VRI 2008';
+
+    /**
+     * @return list<array{sn: int, title: string, copyright: string}>
+     */
+    private function references(RenderContext $ctx): array
+    {
+        if ($ctx->sentenceRefs === []) {
+            return [];
+        }
+        $books = BookTitle::orderByDesc('sn')->get(['book', 'paragraph', 'title']);
+        $seen = [];
+        $references = [];
+        foreach ($ctx->sentenceRefs as [$book, $para]) {
+            foreach ($books as $title) {
+                if ((int) $title->book !== $book || (int) $title->paragraph >= $para || isset($seen[$title->title])) {
+                    continue;
+                }
+                $seen[$title->title] = true;
+                $references[] = ['sn' => count($references) + 1, 'title' => (string) $title->title, 'copyright' => self::COPYRIGHT];
+            }
+        }
+
+        return $references;
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['pali' => $this->references($ctx)];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        $text = '';
+        foreach ($this->references($ctx) as $reference) {
+            $text .= '['.$reference['sn'].'] '.ucfirst($reference['title']).' '.$reference['copyright']."\n";
+        }
+
+        return $text;
+    }
+
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        $markdown = '';
+        foreach ($this->references($ctx) as $reference) {
+            $markdown .= '['.$reference['sn'].'] **'.ucfirst($reference['title']).'** '.$reference['copyright']."\n\n";
+        }
+
+        return $markdown;
+    }
+}

+ 216 - 0
api-v13/app/Services/Markup/Templates/SentTemplate.php

@@ -0,0 +1,216 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\Resolver;
+use App\Services\Markup\Resolve\SentenceLoader;
+
+/**
+ * 句子:`{{sent|id=65-464-2-27}}`、简写 `{{65-464-2-27}}`、指定 channel `{{65-464-2-27@channel}}`。
+ *
+ * 参数:id、channel(逗号分隔,缺省用内容所属 channel)、text(both / origin / translation)、mode(read / edit)。
+ * channel 与 text 共用第 2 个位置(v2 如此)。
+ */
+final class SentTemplate extends Template
+{
+    public function params(): array
+    {
+        return [
+            'id' => ParamSpec::at(1),
+            'channel' => ParamSpec::at(2),
+            'text' => ParamSpec::at(2, 'both'),
+            'mode' => ParamSpec::at(3),
+        ];
+    }
+
+    /**
+     * @return array{0: string, 1: list<string>} [句子坐标, channel 列表]
+     */
+    private function target(Call $call): array
+    {
+        $id = (string) $call->param('id');
+        $channel = (string) $call->param('channel');
+        $channels = $channel !== '' && ! in_array($channel, ['both', 'origin', 'translation'], true)
+            ? array_values(array_filter(array_map('trim', explode(',', $channel))))
+            : $call->scope->channels;
+        if (str_contains($id, '@')) {
+            [$id, $only] = explode('@', $id, 2);
+            $channels = [trim($only)];
+        }
+
+        return [trim($id), $channels];
+    }
+
+    private function mode(Call $call, string $default): string
+    {
+        $mode = (string) $call->param('mode');
+
+        return $mode !== '' ? $mode : $default;
+    }
+
+    private function show(Call $call): string
+    {
+        $show = (string) $call->param('text', 'both');
+
+        return in_array($show, ['origin', 'translation'], true) ? $show : 'both';
+    }
+
+    public function collect(Call $call, Resolver $resolver): void
+    {
+        [$id, $channels] = $this->target($call);
+        $call->data['sentence'] = $resolver->loader(SentenceLoader::class)
+            ->request($id, $channels, $this->mode($call, $resolver->options->mode), $call->scope);
+    }
+
+    /**
+     * @return array<string, mixed>|null
+     */
+    private function sentence(Call $call, RenderContext $ctx): ?array
+    {
+        $sentence = $ctx->loader(SentenceLoader::class)->result((string) ($call->data['sentence'] ?? ''));
+        if ($sentence !== null) {
+            // 以调用为键:同一个调用在一次渲染里可能被取多次(props、纯文本…),只记一次
+            $ctx->sentenceRefs[spl_object_id($call)] = [$sentence['book'], $sentence['para']];
+        }
+
+        return $sentence;
+    }
+
+    public function component(Call $call, RenderContext $ctx): string
+    {
+        return $this->mode($call, $ctx->options->mode) === 'read' ? 'sentread' : 'sentedit';
+    }
+
+    /**
+     * `{id, show, origin, translation, commentaries?}`。id 是句子坐标 book-para-start-end;
+     * 每条:`{id, channel{id,name,lang}, body}`,body 是渲染后的正文;编辑模式另给 content(源码)与 contentType。
+     * 原文 / 译文 / 义注已经分组,所以不再给 channel.type;没有义注时不给 commentaries。
+     *
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        [$id] = $this->target($call);
+        $edit = $this->mode($call, $ctx->options->mode) !== 'read';
+        $sentence = $this->sentence($call, $ctx);
+        if ($sentence === null) {
+            return ['id' => $id, 'show' => $this->show($call), 'error' => 'invalid sentence id'];
+        }
+        $props = ['id' => $id, 'show' => $this->show($call)];
+        foreach (['origin', 'translation', 'commentaries'] as $area) {
+            if ($area === 'commentaries' && $sentence[$area] === []) {
+                continue;
+            }
+            $props[$area] = array_map(function (array $entry) use ($edit) {
+                $item = [
+                    'id' => $entry['id'],
+                    'channel' => [
+                        'id' => $entry['channel']['id'],
+                        'name' => $entry['channel']['name'],
+                        'lang' => $entry['channel']['lang'],
+                    ],
+                    'body' => $entry['body'],
+                ];
+                if ($edit) {
+                    $item['content'] = $entry['content'];
+                    $item['contentType'] = $entry['contentType'];
+                }
+
+                return $item;
+            }, $sentence[$area]);
+        }
+
+        return $props;
+    }
+
+    /**
+     * 各条正文按当前格式渲染后拼接。
+     *
+     * @param  list<array<string, mixed>>  $entries
+     */
+    private function join(array $entries, RenderContext $ctx, bool $trim = false, string $wrapClass = ''): string
+    {
+        $out = '';
+        foreach ($entries as $entry) {
+            $body = $entry['body'] ?? null;
+            $text = $body instanceof Document ? $ctx->renderString($body) : '';
+            if ($trim) {
+                $text = trim($text);
+            }
+            $out .= $wrapClass === '' ? $text : '<span class="'.$wrapClass.'">'.$text.'</span>';
+        }
+
+        return $out;
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $this->plain($call, $ctx, Format::Text);
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        $sentence = $this->sentence($call, $ctx);
+        if ($sentence === null) {
+            return '';
+        }
+        $show = $this->show($call);
+        $trim = $format === Format::Simple;
+        $out = '';
+        if ($show !== 'translation') {
+            $out .= $this->join($sentence['origin'], $ctx, $trim);
+        }
+        if ($show !== 'origin') {
+            $out .= $this->join($sentence['translation'], $ctx, $trim);
+        }
+
+        return $out;
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $sentence = $this->sentence($call, $ctx);
+        if ($sentence === null) {
+            return '';
+        }
+        $show = $this->show($call);
+        $html = '<span class="sentence">';
+        if ($show !== 'translation') {
+            $html .= $this->join($sentence['origin'], $ctx, false, 'origin');
+        }
+        if ($show !== 'origin') {
+            $html .= $this->join($sentence['translation'], $ctx, false, 'translation');
+        }
+
+        return $html.'</span>';
+    }
+
+    /**
+     * 导出:按 origin / translation 选项取原文、译文;只要译文却没有译文时用原文代替(v2 口径)。
+     */
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        $sentence = $this->sentence($call, $ctx);
+        if ($sentence === null) {
+            return '';
+        }
+        $show = $this->show($call);
+        $out = '';
+        if ($show !== 'translation' && $ctx->options->origin) {
+            $out .= $this->join($sentence['origin'], $ctx, true);
+        }
+        if ($show !== 'origin' && $ctx->options->translation) {
+            if ($sentence['translation'] !== []) {
+                $out .= $this->join($sentence['translation'], $ctx, true);
+            } elseif ($show === 'translation') {
+                $out .= $this->join($sentence['origin'], $ctx, true);
+            }
+        }
+
+        return $out;
+    }
+}

+ 117 - 0
api-v13/app/Services/Markup/Templates/Template.php

@@ -0,0 +1,117 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Dialect;
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Params;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\Resolver;
+
+/**
+ * 模板基类。一个模板一个子类,在 {@see TemplateRegistry} 登记名字。
+ *
+ * 生命周期:
+ * 1. 解析:{@see Params()} 声明参数(位置、默认值、是否 markdown);markdown 参数递归解析成 slot
+ * 2. 取数:{@see collect()} 把要查的键交给 Resolver,同类模板一次批量查完(不再逐个查库)
+ * 3. 输出:tree 用 {@see component()} + {@see props()} + {@see children()};html / 纯文本 / markdown
+ *    各有一个方法,默认都退回 {@see text()},只有真的不同才覆盖
+ *
+ * 模板实例无状态(单例),每次调用的数据都在 {@see Call} 上。
+ */
+abstract class Template
+{
+    /** tree 输出的组件名(前端按它分发) */
+    protected string $component = 'unknown';
+
+    /**
+     * @return array<string, ParamSpec>
+     */
+    public function params(): array
+    {
+        return [];
+    }
+
+    /**
+     * 参数片段 → 参数表。
+     *
+     * `name=value` 当命名参数的条件:名字全是小写字母(v2 口径);E2 方言下还要求名字是 {@see Params()}
+     * 声明过的,否则整段按位置参数处理——LLM 写的 `x=y` 不会被误认成参数。
+     *
+     * @param  list<string>  $segments
+     */
+    public function parseParams(array $segments, Dialect $dialect): Params
+    {
+        $declared = $this->params();
+        $named = [];
+        $positional = [];
+        foreach ($segments as $offset => $segment) {
+            if (preg_match('/^([a-z]+)=(.*)$/s', $segment, $m) === 1
+                && ($dialect === Dialect::Markdown || $this->acceptsAnyName() || isset($declared[$m[1]]))) {
+                $named[$m[1]] = $m[2];
+            } else {
+                $positional[$offset + 1] = $segment;
+            }
+        }
+
+        return new Params($named, $positional);
+    }
+
+    /**
+     * 是否接受任意名字的命名参数(Tpl 模板把参数原样交给 Mustache)。
+     */
+    protected function acceptsAnyName(): bool
+    {
+        return false;
+    }
+
+    public function collect(Call $call, Resolver $resolver): void {}
+
+    public function component(Call $call, RenderContext $ctx): string
+    {
+        return $this->component;
+    }
+
+    /**
+     * tree 输出的 props。值可以是 {@see Document},由渲染器按当前格式展开。
+     *
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return [];
+    }
+
+    /**
+     * tree 输出的 children。
+     */
+    public function children(Call $call, RenderContext $ctx): ?Document
+    {
+        return null;
+    }
+
+    /**
+     * 纯文本表示:text / simple / prompt / markdown / html 的默认输出都从它来。
+     */
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return '';
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $this->text($call, $ctx);
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        return e($this->text($call, $ctx));
+    }
+
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        return $this->text($call, $ctx);
+    }
+}

+ 80 - 0
api-v13/app/Services/Markup/Templates/TemplateRegistry.php

@@ -0,0 +1,80 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+/**
+ * 模板名 → 模板类。别名直接登记成另一个名字。
+ *
+ * 新增模板:写一个 {@see Template} 子类,在这里加一行。
+ */
+final class TemplateRegistry
+{
+    /** @var array<string, class-string<Template>> */
+    private const TEMPLATES = [
+        'term' => TermTemplate::class,
+        'note' => NoteTemplate::class,
+        'n' => NoteTemplate::class,
+        'sent' => SentTemplate::class,
+        'quote' => QuoteTemplate::class,
+        'ql' => QuoteLinkTemplate::class,
+        'exercise' => ExerciseTemplate::class,
+        'article' => ArticleTemplate::class,
+        'nissaya' => NissayaTemplate::class,
+        'mermaid' => MermaidTemplate::class,
+        'qa' => QaTemplate::class,
+        'v' => VideoTemplate::class,
+        'g' => GrammarTemplate::class,
+        'ref' => ReferenceTemplate::class,
+        'dict-pref' => DictPrefTemplate::class,
+        'ai' => AiTemplate::class,
+        'para' => ParaTemplate::class,
+        'category' => CategoryTemplate::class,
+        'quality' => QualityTemplate::class,
+        'toggle' => ToggleTemplate::class,
+    ];
+
+    /**
+     * 内部模板:只由程序生成(批注注入),不在源码语法里——正文里写 `{{anno-issue|…}}` 得到的是 unknown。
+     *
+     * @var array<string, class-string<Template>>
+     */
+    private const INTERNAL = [
+        'anno-issue' => Internal\AnnoIssueTemplate::class,
+        'anno-issue-mark' => Internal\AnnoIssueMarkTemplate::class,
+        'anno-assessment' => Internal\AnnoAssessmentTemplate::class,
+    ];
+
+    /** `{{Tpl:名字|…}}`:以文章为模板(标题就是模板名) */
+    public const TPL_PREFIX = 'Tpl:';
+
+    /** @var array<class-string<Template>, Template> */
+    private array $instances = [];
+
+    public function get(string $name): Template
+    {
+        $class = self::TEMPLATES[$name] ?? null;
+        if ($class === null) {
+            $class = str_starts_with($name, self::TPL_PREFIX) ? TplTemplate::class : UnknownTemplate::class;
+        }
+
+        return $this->instances[$class] ??= app($class);
+    }
+
+    /**
+     * 内部模板({@see self::INTERNAL});不是内部模板名时退回 {@see self::get()}。
+     */
+    public function internal(string $name): Template
+    {
+        $class = self::INTERNAL[$name] ?? null;
+
+        return $class === null ? $this->get($name) : ($this->instances[$class] ??= app($class));
+    }
+
+    /**
+     * @return list<string>
+     */
+    public function names(): array
+    {
+        return array_keys(self::TEMPLATES);
+    }
+}

+ 154 - 0
api-v13/app/Services/Markup/Templates/TermTemplate.php

@@ -0,0 +1,154 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Ir\Text;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\Resolver;
+use App\Services\Markup\Resolve\TermLoader;
+
+/**
+ * 术语:`{{term|word}}`、`[[word]]`。
+ *
+ * `word@tag` 按 tag 查;`word#显示文字` 用指定文字代替译名。查询口径见 {@see TermLoader}。
+ */
+final class TermTemplate extends Template
+{
+    protected string $component = 'term';
+
+    public function params(): array
+    {
+        return ['word' => ParamSpec::at(1)];
+    }
+
+    /**
+     * @return array{word: string, tag: string, display: ?string}
+     */
+    private function word(Call $call): array
+    {
+        $word = (string) $call->param('word');
+        $display = null;
+        if (str_contains($word, '#')) {
+            [$word, $display] = explode('#', $word, 2);
+        }
+        $tag = '';
+        if (str_contains($word, '@')) {
+            [$word, $tag] = explode('@', $word, 2);
+        }
+
+        return ['word' => $word, 'tag' => $tag, 'display' => $display];
+    }
+
+    public function collect(Call $call, Resolver $resolver): void
+    {
+        ['word' => $word, 'tag' => $tag] = $this->word($call);
+        $call->data['term'] = $resolver->loader(TermLoader::class)
+            ->request($word, $tag, $call->scope->firstChannel(), $call->scope);
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        ['word' => $word, 'display' => $display] = $this->word($call);
+        $props = self::termProps($ctx, $call->data['term'] ?? null, $word);
+        if ($display !== null) {
+            $props['meaning'] = $display;
+        }
+
+        return $props;
+    }
+
+    /**
+     * 术语查询结果 → props(ql、g 模板也用)。字段沿用 v2 的 getTermProps();note 是内容节点而不是 HTML。
+     *
+     * @return array<string, mixed>
+     */
+    public static function termProps(RenderContext $ctx, ?string $key, string $word): array
+    {
+        $result = $ctx->loader(TermLoader::class)->result((string) $key);
+        $props = [
+            'word' => $word,
+            'parentChannelId' => $result['channel'],
+            'parentStudioId' => $result['studio'],
+        ];
+        $term = $result['term'];
+        if ($term !== null) {
+            $props['id'] = (string) $term->guid;
+            $props['meaning'] = (string) $term->meaning;
+            $props['channel'] = $term->channal;
+            if (! empty($term->other_meaning)) {
+                $props['meaning2'] = (string) $term->other_meaning;
+            }
+            if ($result['community']) {
+                $props['isCommunity'] = true;
+            }
+            // tree 输出不带 note:前端的术语组件打开弹窗时自己取词条详情,note 全文随正文下发是浪费
+            // (一个词条的 note 动辄几十 KB)。markdown 导出用 note 做脚注(见 markdown())
+            if ($result['note'] !== null && $ctx->format() !== Format::Tree) {
+                $props['note'] = $result['note'];
+            }
+        }
+
+        return $props;
+    }
+
+    public function children(Call $call, RenderContext $ctx): Document
+    {
+        return new Document([new Text($this->label($call, $ctx))], true, '', [], $call->scope);
+    }
+
+    /**
+     * 正文里显示的文字:找到术语时「译名(原词)」,否则原词。
+     */
+    private function label(Call $call, RenderContext $ctx): string
+    {
+        $props = $this->props($call, $ctx);
+
+        return isset($props['meaning']) ? "{$props['meaning']}({$props['word']})" : $props['word'];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        $props = $this->props($call, $ctx);
+
+        return $props['meaning'] ?? $props['word'];
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $props = $this->props($call, $ctx);
+        $class = isset($props['id']) ? 'term-ref' : 'term-ref term_invalid';
+
+        return '<span class="'.$class.'" data-id="'.e($props['id'] ?? '').'" data-term="'.e($props['word']).'">'
+            .e($props['meaning'] ?? $props['word']).'</span>';
+    }
+
+    /**
+     * 第一次出现写「译名(原词)」并把术语 note 作为脚注,之后只写译名(v2 口径)。
+     */
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        $props = $this->props($call, $ctx);
+        if (! isset($props['meaning'])) {
+            return $props['word'];
+        }
+        $seen = $ctx->termSeen[$props['word']] ?? 0;
+        $ctx->termSeen[$props['word']] = $seen + 1;
+        if ($seen > 0) {
+            return $props['meaning'];
+        }
+        $output = "{$props['meaning']}({$props['word']})";
+        if (($props['note'] ?? null) instanceof Document) {
+            $sn = $ctx->nextNoteNumber();
+            $ctx->footnotes[] = ['sn' => $sn, 'trigger' => '', 'content' => $ctx->renderString($props['note'])];
+            $output .= "[^{$sn}]";
+        }
+
+        return $output;
+    }
+}

+ 44 - 0
api-v13/app/Services/Markup/Templates/ToggleTemplate.php

@@ -0,0 +1,44 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 可展开的列表项:源码里 `- <div>…</div>` 形式的列表项由解析器自动生成,不是手写模板。
+ * 前端把 children 渲染成可折叠的树(第一个子元素是标题)。
+ */
+final class ToggleTemplate extends Template
+{
+    protected string $component = 'toggle';
+
+    public function children(Call $call, RenderContext $ctx): ?Document
+    {
+        return $call->slot('content');
+    }
+
+    private function content(Call $call, RenderContext $ctx): string
+    {
+        $content = $call->slot('content');
+
+        return $content === null ? '' : $ctx->renderString($content);
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $this->content($call, $ctx);
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $this->content($call, $ctx);
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        return $this->content($call, $ctx);
+    }
+}

+ 85 - 0
api-v13/app/Services/Markup/Templates/TplTemplate.php

@@ -0,0 +1,85 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Format;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Render\RenderContext;
+use App\Services\Markup\Resolve\Resolver;
+use App\Services\Markup\Resolve\TplLoader;
+
+/**
+ * 用户自定义模板:`{{Tpl:名字|a|b=c}}`。正文是标题为「Tpl:名字」的文章,参数经 Mustache 代入
+ * (`{{1}}`、`{{b}}`),结果再按 markdown 渲染。
+ */
+final class TplTemplate extends Template
+{
+    protected string $component = 'tpl';
+
+    protected function acceptsAnyName(): bool
+    {
+        return true;
+    }
+
+    public function collect(Call $call, Resolver $resolver): void
+    {
+        $call->data['tpl'] = $resolver->loader(TplLoader::class)->request($call->name, $call->params->all(), $call->scope);
+    }
+
+    /**
+     * @return array{content: string, document: ?Document}|null
+     */
+    private function resolved(Call $call, RenderContext $ctx): ?array
+    {
+        return $ctx->loader(TplLoader::class)->result((string) ($call->data['tpl'] ?? ''));
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['name' => $call->name];
+    }
+
+    public function children(Call $call, RenderContext $ctx): ?Document
+    {
+        return $this->resolved($call, $ctx)['document'] ?? null;
+    }
+
+    private function rendered(Call $call, RenderContext $ctx): string
+    {
+        $resolved = $this->resolved($call, $ctx);
+        if ($resolved === null) {
+            return '';
+        }
+
+        return $resolved['document'] === null ? $resolved['content'] : $ctx->renderString($resolved['document']);
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $this->rendered($call, $ctx);
+    }
+
+    public function plain(Call $call, RenderContext $ctx, Format $format): string
+    {
+        return $this->rendered($call, $ctx);
+    }
+
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $resolved = $this->resolved($call, $ctx);
+        if ($resolved === null) {
+            return '';
+        }
+
+        return $resolved['document'] === null ? e($resolved['content']) : $ctx->renderString($resolved['document']);
+    }
+
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        return $this->rendered($call, $ctx);
+    }
+}

+ 32 - 0
api-v13/app/Services/Markup/Templates/UnknownTemplate.php

@@ -0,0 +1,32 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 没登记的模板名:tree 输出 `unknown` 组件(带名字),其余格式原样输出源码,不吞内容。
+ */
+final class UnknownTemplate extends Template
+{
+    protected string $component = 'unknown';
+
+    protected function acceptsAnyName(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return ['name' => $call->name, 'source' => $call->raw];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return $call->raw;
+    }
+}

+ 37 - 0
api-v13/app/Services/Markup/Templates/VideoTemplate.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace App\Services\Markup\Templates;
+
+use App\Services\Markup\Html\HtmlPolicy;
+use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Render\RenderContext;
+
+/**
+ * 视频:`{{v|url|style|title}}`。style 缺省 modal。地址只允许 http(s) 与站内路径。
+ */
+final class VideoTemplate extends Template
+{
+    protected string $component = 'video';
+
+    public function params(): array
+    {
+        return ['url' => ParamSpec::at(1), 'style' => ParamSpec::at(2, 'modal'), 'title' => ParamSpec::at(3)];
+    }
+
+    /**
+     * @return array<string, mixed>
+     */
+    public function props(Call $call, RenderContext $ctx): array
+    {
+        return [
+            'url' => HtmlPolicy::url((string) $call->param('url')) ?? '',
+            'title' => (string) $call->param('title'),
+            'style' => (string) $call->param('style'),
+        ];
+    }
+
+    public function text(Call $call, RenderContext $ctx): string
+    {
+        return (string) $call->param('title');
+    }
+}

+ 161 - 0
api-v13/tests/Feature/MarkupAnnotationTest.php

@@ -0,0 +1,161 @@
+<?php
+
+use App\Services\AnnotationLayout;
+use App\Services\HtmlAnnotationMarkup;
+use App\Services\Markup\Annotation\AnnotationSet;
+use App\Services\Markup\Annotation\AnnotationToken;
+use App\Services\Markup\Format;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\RenderOptions;
+
+/**
+ * 阅读页批注的结构化注入:AnnotationLayout 用 AnnotationSet 作输出策略,插入点写占位符,
+ * App\Services\Markup 解析成 anno-* / note 模板节点,各格式都能输出。
+ */
+
+/**
+ * 排版 + 渲染一句。
+ *
+ * @param  array<string, mixed>  $layout  AnnotationLayout::apply 的 glossaries / issues / notes / assessment
+ */
+function annotated(string $content, array $layout, Format $format = Format::Tree, ?callable $notes = null): array|string
+{
+    $set = new AnnotationSet;
+    $noteSpecs = $notes ? $notes($set) : [];
+    $result = AnnotationLayout::apply(
+        $content,
+        $layout['glossaries'] ?? [],
+        $layout['issues'] ?? [],
+        $noteSpecs,
+        true,
+        $layout['assessment'] ?? null,
+        $set,
+    );
+    $rendered = app(MarkupService::class)->renderMany(
+        [['source' => $result['content'], 'annotations' => $set]],
+        new RenderOptions(format: $format),
+    )[0];
+
+    return is_array($rendered) ? json_decode(json_encode($rendered), true) : $rendered;
+}
+
+it('wraps an issue range as an anno-issue node in the tree', function () {
+    $tree = annotated('first sentence', ['issues' => [['id' => 'i1', 'start' => 0, 'end' => 5, 'severity' => 'error']]]);
+
+    expect($tree[0])->toMatchArray(['type' => 'tpl', 'name' => 'anno-issue', 'props' => ['ids' => ['i1'], 'severity' => 'error']]);
+    expect($tree[0]['children'])->toBe([['type' => 'text', 'value' => 'first']]);
+    expect($tree[1])->toBe(['type' => 'text', 'value' => ' sentence']);
+});
+
+it('renders the same html as the legacy injection', function () {
+    $layout = [
+        'issues' => [
+            ['id' => 'i1', 'start' => 0, 'end' => 5, 'severity' => 'warning'],
+            ['id' => 'i2', 'start' => null, 'end' => null, 'severity' => 'error'],
+        ],
+        'assessment' => ['id' => 'a1', 'score' => 85],
+    ];
+    $html = annotated('first sentence', $layout, Format::Html);
+    $markup = new HtmlAnnotationMarkup;
+
+    expect($html)->toBe('<span>'
+        .HtmlAnnotationMarkup::issueOpenTag(['i1'], 'warning').'first</span> sentence'
+        .$markup->issueMark(['i2'], 'error')
+        .$markup->assessmentMark('a1', 85)
+        .'</span>');
+});
+
+it('keeps highlighted text and drops icons in plain formats', function () {
+    $layout = [
+        'issues' => [['id' => 'i1', 'start' => 0, 'end' => 5, 'severity' => null], ['id' => 'i2', 'start' => null, 'end' => null, 'severity' => null]],
+        'assessment' => ['id' => 'a1', 'score' => 30],
+    ];
+
+    expect(annotated('first sentence', $layout, Format::Text))->toBe('first sentence');
+    expect(annotated('first sentence', $layout, Format::Markdown))->toBe('first sentence');
+});
+
+it('exposes assessments and issue marks as props in the tree', function () {
+    $tree = annotated('句子', [
+        'issues' => [['id' => 'i2', 'start' => null, 'end' => null, 'severity' => 'suggestion']],
+        'assessment' => ['id' => 'a1', 'score' => 65],
+    ]);
+
+    expect($tree[1])->toMatchArray(['name' => 'anno-issue-mark', 'props' => ['ids' => ['i2'], 'severity' => 'suggestion']]);
+    expect($tree[2])->toMatchArray(['name' => 'anno-assessment', 'props' => ['id' => 'a1', 'score' => 65, 'level' => 'medium']]);
+});
+
+it('renders the unassessed mark as a level-none assessment', function () {
+    $set = new AnnotationSet;
+    $source = '句子'.$set->unassessedMark();
+    $render = fn (Format $f) => app(MarkupService::class)->renderMany([['source' => $source, 'annotations' => $set]], new RenderOptions(format: $f))[0];
+
+    expect(json_decode(json_encode($render(Format::Tree)), true)[1])->toMatchArray(['name' => 'anno-assessment', 'props' => ['level' => 'none']]);
+    expect($render(Format::Html))->toBe('<span>句子'.HtmlAnnotationMarkup::unassessedMark().'</span>');
+});
+
+it('lifts an issue that crosses an emphasis boundary to wrap the whole element', function () {
+    // 「*斜体*」不在 AnnotationLayout 的受保护区间里:区间 [3, 8) 从斜体中间开始
+    $content = 'ab *cdef* gh';
+    $tree = annotated($content, ['issues' => [['id' => 'i1', 'start' => 5, 'end' => 10, 'severity' => null]]]);
+
+    $issue = collect($tree)->firstWhere('name', 'anno-issue');
+    expect($issue)->not->toBeNull();
+    expect(collect($issue['children'])->pluck('tag')->filter()->values()->all())->toBe(['em']);
+    expect(json_encode($tree, JSON_UNESCAPED_UNICODE))->not->toContain("\u{E002}");
+});
+
+it('injects notes as structured note nodes with markdown and templates kept', function () {
+    $tree = annotated('first sentence', [], Format::Tree, fn (AnnotationSet $set) => [
+        ['id' => 'n1', 'at' => 5, 'order' => [0, 0, 0], 'html' => $set->note('见 **粗体** 与 [[dhamma]]', ['cite' => '义注', 'citelink' => '1-2-3-4'])],
+    ]);
+
+    expect($tree[1])->toMatchArray(['name' => 'note', 'props' => ['cite' => '义注', 'citelink' => '1-2-3-4']]);
+    expect(collect($tree[1]['children'])->pluck('tag')->filter()->values()->all())->toBe(['strong']);
+    expect(collect($tree[1]['children'])->firstWhere('name', 'term')['props']['word'])->toBe('dhamma');
+});
+
+it('renders note sidenotes with only inline html even for block content', function () {
+    $html = annotated('first sentence', [], Format::Html, fn (AnnotationSet $set) => [
+        ['id' => 'n1', 'at' => 5, 'order' => [0, 0, 0], 'html' => $set->note("1. 第一点\n2. 第二点\n\n另起一段")],
+    ]);
+
+    expect($html)->toContain('<span class="sidenote">')
+        ->not->toContain('<ol')->not->toContain('<p>')
+        ->toContain('<span class="md-ol"><span class="md-li">第一点</span>')
+        ->toContain('<br /><span class="md-p">另起一段</span>');
+});
+
+it('renders notes as markdown footnotes', function () {
+    $markdown = app(MarkupService::class)->renderMany(
+        [['source' => 'first'.($set = new AnnotationSet)->note('注释正文').' sentence', 'annotations' => $set]],
+        new RenderOptions(format: Format::Markdown, footnote: true),
+    )[0];
+
+    expect($markdown)->toBe("first[^1] sentence\n\n[^1]: 注释正文");
+});
+
+it('parses the note body in its own dialect', function () {
+    $tree = annotated('句子', [], Format::Tree, fn (AnnotationSet $set) => [
+        ['id' => 'n1', 'at' => 2, 'order' => [0, 0, 0], 'html' => $set->note('用 `code`', [], 'markdown-e2')],
+    ]);
+
+    expect($tree[1]['children'][1])->toMatchArray(['type' => 'el', 'tag' => 'code']);
+});
+
+it('gives sidenotes page-unique ids from the item id prefix', function () {
+    $html = app(MarkupService::class)->renderMany([
+        ['source' => 'a{{n|x}}', 'idPrefix' => '65-1-2-3'],
+        ['source' => 'b{{n|y}}', 'idPrefix' => '65-1-4-5'],
+    ], new RenderOptions(format: Format::Html));
+
+    expect($html[0])->toContain('id="sn-65-1-2-3-1"')->and($html[1])->toContain('id="sn-65-1-4-5-1"');
+});
+
+it('ignores annotation tokens and internal template names written in content', function () {
+    $stray = '正文'.AnnotationToken::make(0).'{{anno-issue|ids=x}}';
+    $tree = json_decode(json_encode(app(MarkupService::class)->render($stray, new RenderOptions)), true);
+
+    expect($tree[0])->toBe(['type' => 'text', 'value' => '正文']);
+    expect($tree[1])->toMatchArray(['name' => 'unknown']);
+});

+ 605 - 0
api-v13/tests/Feature/MarkupSyntaxTest.php

@@ -0,0 +1,605 @@
+<?php
+
+use App\Services\Markup\Format;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\Parsing\CjkFriendlyEmphasisParser;
+use App\Services\Markup\RenderOptions;
+
+/**
+ * App\Services\Markup 的语法测试:标准 markdown、原始 HTML 白名单、全部模板写法、两种方言、各输出格式。
+ * 这里的用例都不需要库里的数据(术语、句子等取数见 MarkupTemplateDataTest)。
+ */
+
+/**
+ * tree 输出,转成纯数组便于断言。
+ *
+ * @return list<array<string, mixed>>
+ */
+function markupTree(string $source, array $options = []): array
+{
+    $rendered = app(MarkupService::class)->render($source, new RenderOptions(...$options));
+
+    return json_decode(json_encode($rendered), true);
+}
+
+function markupRender(string $source, Format $format, array $options = []): string
+{
+    return app(MarkupService::class)->render($source, new RenderOptions(...array_merge($options, ['format' => $format])));
+}
+
+function markupE2(string $source): array
+{
+    return markupTree($source, ['contentType' => 'markdown-e2']);
+}
+
+/**
+ * 树里所有模板节点(深度优先,含 props 里嵌套的)。
+ *
+ * @return list<array<string, mixed>>
+ */
+function markupTemplates(array $nodes): array
+{
+    $found = [];
+    foreach ($nodes as $node) {
+        if (! is_array($node)) {
+            continue;
+        }
+        if (($node['type'] ?? null) === 'tpl') {
+            $found[] = $node;
+        }
+        foreach (['children', 'props'] as $key) {
+            if (isset($node[$key]) && is_array($node[$key])) {
+                array_push($found, ...markupTemplates(array_values($node[$key])));
+            }
+        }
+        if (! isset($node['type'])) {
+            array_push($found, ...markupTemplates(array_values($node)));
+        }
+    }
+
+    return $found;
+}
+
+function markupText(array $nodes): string
+{
+    $text = '';
+    foreach ($nodes as $node) {
+        if ($node['type'] === 'text') {
+            $text .= $node['value'];
+        } else {
+            $text .= markupText($node['children'] ?? []);
+        }
+    }
+
+    return $text;
+}
+
+describe('standard markdown', function () {
+    it('renders a single paragraph as inline nodes without a p wrapper', function () {
+        expect(markupTree('hello *world*'))->toBe([
+            ['type' => 'text', 'value' => 'hello '],
+            ['type' => 'el', 'tag' => 'em', 'children' => [['type' => 'text', 'value' => 'world']]],
+        ]);
+    });
+
+    it('renders headings h1 to h6 with stable ids', function () {
+        $tree = markupTree("# a\n\n## b\n\n### c\n\n#### d\n\n##### e\n\n###### f");
+        expect(array_column($tree, 'tag'))->toBe(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
+        expect($tree[0]['attrs']['id'])->toMatch('/^h-[0-9a-f]{8}-1$/');
+        expect(markupTree("# a\n\n## b")[0]['attrs']['id'])->not->toBe(markupTree("# x\n\n## b")[0]['attrs']['id']);
+        expect(markupTree("# a\n\n## b"))->toBe(markupTree("# a\n\n## b"));
+    });
+
+    it('renders emphasis, strong, strikethrough and nesting', function () {
+        $tree = markupTree('*em* **strong** ~~del~~ ***both***');
+        expect(array_values(array_filter(array_column($tree, 'tag'))))->toBe(['em', 'strong', 'del', 'em']);
+        expect($tree[6]['children'][0]['tag'])->toBe('strong');
+    });
+
+    it('renders links and images and drops unsafe urls', function () {
+        $tree = markupTree('[site](https://wikipali.org "t") [bad](javascript:alert(1)) ![pic](/attachments/a.png)');
+        expect($tree[0])->toMatchArray(['tag' => 'a', 'attrs' => ['href' => 'https://wikipali.org', 'title' => 't']]);
+        expect($tree[2]['tag'])->toBe('a')->and($tree[2])->not->toHaveKey('attrs');
+        expect($tree[4])->toMatchArray(['tag' => 'img', 'attrs' => ['src' => '/attachments/a.png', 'alt' => 'pic']]);
+    });
+
+    it('prefixes site images with the app url in html', function () {
+        config(['app.url' => 'https://example.test']);
+        expect(markupRender('![pic](/attachments/a.png)', Format::Html))
+            ->toBe('<span><img src="https://example.test/attachments/a.png" alt="pic" /></span>');
+    });
+
+    it('renders autolinks', function () {
+        expect(markupTree('see https://wikipali.org now')[1])
+            ->toMatchArray(['tag' => 'a', 'attrs' => ['href' => 'https://wikipali.org']]);
+    });
+
+    it('renders hard and soft line breaks', function () {
+        $tree = markupTree("a  \nb\nc");
+        expect($tree[1]['tag'])->toBe('br');
+        expect($tree[2])->toBe(['type' => 'text', 'value' => "b\nc"]);
+    });
+
+    it('renders block quotes', function () {
+        $tree = markupTree("> quoted\n>\n> two");
+        expect($tree[0]['tag'])->toBe('blockquote')
+            ->and(array_column($tree[0]['children'], 'tag'))->toBe(['p', 'p']);
+    });
+
+    it('renders tight, loose, ordered and nested lists', function () {
+        $tight = markupTree("- a\n- b\n  - c");
+        expect($tight[0]['tag'])->toBe('ul');
+        expect($tight[0]['children'][0]['children'][0])->toBe(['type' => 'text', 'value' => 'a']);
+        expect($tight[0]['children'][1]['children'][1]['tag'])->toBe('ul');
+
+        $loose = markupTree("- a\n\n- b");
+        expect($loose[0]['children'][0]['children'][0]['tag'])->toBe('p');
+
+        $ordered = markupTree("3. x\n4. y");
+        expect($ordered[0])->toMatchArray(['tag' => 'ol', 'attrs' => ['start' => '3']]);
+    });
+
+    it('renders task lists', function () {
+        $tree = markupTree("- [x] done\n- [ ] todo");
+        expect($tree[0]['children'][0]['children'][0])
+            ->toMatchArray(['tag' => 'input', 'attrs' => ['type' => 'checkbox', 'disabled' => 'disabled', 'checked' => 'checked']]);
+        expect($tree[0]['children'][1]['children'][0]['attrs'])->not->toHaveKey('checked');
+    });
+
+    it('renders tables with alignment', function () {
+        $tree = markupTree("| a | b |\n|:--|--:|\n| 1 | 2 |");
+        expect($tree[0]['tag'])->toBe('table');
+        [$head, $body] = $tree[0]['children'];
+        expect($head['tag'])->toBe('thead')->and($body['tag'])->toBe('tbody');
+        expect($head['children'][0]['children'][0])->toMatchArray(['tag' => 'th', 'attrs' => ['align' => 'left']]);
+        expect($body['children'][0]['children'][1])->toMatchArray(['tag' => 'td', 'attrs' => ['align' => 'right']]);
+    });
+
+    it('renders thematic breaks', function () {
+        expect(array_column(markupTree("a\n\n---\n\nb"), 'tag'))->toBe(['p', 'hr', 'p']);
+    });
+
+    it('renders indented code literally', function () {
+        $tree = markupTree("para\n\n    {{note|x}} *y*");
+        expect($tree[1]['tag'])->toBe('pre');
+        expect($tree[1]['children'][0]['children'][0]['value'])->toBe("{{note|x}} *y*\n");
+    });
+
+    it('escapes text in html output', function () {
+        expect(markupRender('a < b & "c"', Format::Html))->toBe('<span>a &lt; b &amp; &quot;c&quot;</span>');
+    });
+
+    it('returns empty output for empty content', function () {
+        expect(markupTree(''))->toBe([]);
+        expect(markupRender("  \n", Format::Html))->toBe('');
+    });
+});
+
+describe('raw html', function () {
+    it('keeps allowed inline tags and nests them', function () {
+        $tree = markupTree('a <u>under <b>bold</b></u> 10<sup>12</sup>');
+        expect($tree[1])->toMatchArray(['tag' => 'u']);
+        expect($tree[1]['children'][1]['tag'])->toBe('b');
+        expect($tree[3]['tag'])->toBe('sup');
+    });
+
+    it('keeps br as a void element', function () {
+        expect(markupTree('a<br>b')[1])->toBe(['type' => 'el', 'tag' => 'br', 'children' => []]);
+    });
+
+    it('turns unknown tags into spans with data-tag', function () {
+        $tree = markupTree('<r>(abhi-ṭṭha-1-291)</r>');
+        expect($tree[0])->toMatchArray(['tag' => 'span', 'attrs' => ['data-tag' => 'r']]);
+        expect($tree[0]['children'][0]['value'])->toBe('(abhi-ṭṭha-1-291)');
+    });
+
+    it('drops scripts, iframes and svg with their content', function () {
+        $tree = markupTree('a<script>alert(1)</script>b<iframe src="x"></iframe>c');
+        expect(markupText($tree))->toBe('abc');
+
+        $block = markupTree("<svg><text>x</text></svg>\n\nafter");
+        expect(markupText($block))->toBe('after');
+    });
+
+    it('drops event handlers and styles', function () {
+        $tree = markupTree('<span class="k" style="color:red" onclick="x()">t</span>');
+        expect($tree[0]['attrs'])->toBe(['class' => 'k']);
+    });
+
+    it('drops javascript links in raw html', function () {
+        $tree = markupTree('<a href="javascript:alert(1)">x</a> <a href="JaVa script:alert(1)">y</a>');
+        expect($tree[0])->not->toHaveKey('attrs');
+    });
+
+    it('parses html blocks through the dom', function () {
+        $tree = markupTree("<div class=\"box\">\n<p>inside</p>\n</div>");
+        expect($tree[0])->toMatchArray(['tag' => 'div', 'attrs' => ['class' => 'box']]);
+        expect($tree[0]['children'][1]['tag'])->toBe('p');
+    });
+
+    it('renders templates inside html blocks', function () {
+        $tree = markupTree("<nt>\n{{note|inner}}\n</nt>");
+        expect($tree[0]['attrs']['data-tag'])->toBe('nt');
+        expect(markupTemplates($tree)[0]['name'])->toBe('note');
+    });
+});
+
+describe('templates: syntax', function () {
+    it('parses named and positional params, counting named ones as positions', function () {
+        $tree = markupTree('{{note|text=body|②}}');
+        expect($tree[0])->toMatchArray(['type' => 'tpl', 'name' => 'note', 'props' => ['trigger' => '②']]);
+        expect($tree[0]['children'])->toBe([['type' => 'text', 'value' => 'body']]);
+    });
+
+    it('drops the newline right after a pipe', function () {
+        $tree = markupTree("{{note|\nbody}}");
+        expect($tree[0]['children'])->toBe([['type' => 'text', 'value' => 'body']]);
+    });
+
+    it('nests templates in params', function () {
+        $tree = markupTree('{{note|see {{note|deeper}} and [[dhamma]]}}');
+        $names = array_column(markupTemplates($tree), 'name');
+        expect($names)->toBe(['note', 'note', 'term']);
+    });
+
+    it('keeps an unclosed {{ as text', function () {
+        expect(markupText(markupTree('a {{note|b')))->toBe('a {{note|b');
+    });
+
+    it('keeps backslash-escaped braces as text', function () {
+        expect(markupTree('\{{note|x}}'))->toBe([['type' => 'text', 'value' => '{{note|x}}']]);
+    });
+
+    it('renders unknown templates as an unknown component and as source text', function () {
+        $tree = markupTree('{{nosuch|a}}');
+        expect($tree[0])->toMatchArray(['name' => 'unknown', 'props' => ['name' => 'nosuch', 'source' => '{{nosuch|a}}']]);
+        expect(markupRender('{{nosuch|a}}', Format::Text))->toBe('{{nosuch|a}}');
+    });
+
+    it('keeps template pipes from splitting table cells', function () {
+        $tree = markupTree("| a | b |\n|---|---|\n| {{note|x|y}} | 2 |");
+        $cells = $tree[0]['children'][1]['children'][0]['children'];
+        expect($cells)->toHaveCount(2);
+        expect($cells[0]['children'][0])->toMatchArray(['name' => 'note', 'props' => ['trigger' => 'y']]);
+    });
+
+    it('recognizes the sentence shorthand and the sent template', function () {
+        $short = markupTree('{{65-464-2-27}}');
+        $long = markupTree('{{sent|id=65-464-2-27}}');
+        expect($short[0])->toMatchArray(['type' => 'tpl', 'name' => 'sentread']);
+        expect($short[0]['props']['id'])->toBe('65-464-2-27');
+        expect($long[0]['props']['id'])->toBe('65-464-2-27');
+        expect(markupTree('{{65-464-2-27}}', ['mode' => 'edit'])[0]['name'])->toBe('sentedit');
+        expect(markupTree('{{sent|id=65-464-2-27|mode=edit}}')[0]['name'])->toBe('sentedit');
+    });
+
+    it('reports an invalid sentence id', function () {
+        expect(markupTree('{{1-2-3}}')[0]['props']['error'])->toBe('invalid sentence id');
+    });
+});
+
+describe('footnotes', function () {
+    it('accepts note and n', function () {
+        expect(markupTree('{{n|short}}')[0]['name'])->toBe('note');
+        expect(markupTree('{{note|short}}')[0]['name'])->toBe('note');
+    });
+
+    it('allows line breaks, blank lines and blocks inside an inline note', function () {
+        $tree = markupTree("正文{{n|第一段\n\n- 列表\n- 两项}}继续正文");
+        expect($tree[0]['type'])->toBe('text')->and($tree[2])->toBe(['type' => 'text', 'value' => '继续正文']);
+        $note = $tree[1];
+        expect($note['name'])->toBe('note');
+        expect(array_column($note['children'], 'tag'))->toBe(['p', 'ul']);
+    });
+
+    it('joins a note fence into the sentence around it (CJK: no space)', function () {
+        $tree = markupTree("前半句\n```note\ncontent\n```\n后半句");
+        expect($tree)->toHaveCount(3);
+        expect($tree[0])->toBe(['type' => 'text', 'value' => '前半句']);
+        expect($tree[1])->toMatchArray(['type' => 'tpl', 'name' => 'note']);
+        expect($tree[2])->toBe(['type' => 'text', 'value' => '后半句']);
+    });
+
+    it('joins a note fence with a space between latin words', function () {
+        $tree = markupTree("first half\n```note\ncontent\n```\nsecond half");
+        expect($tree[0]['value'])->toBe('first half');
+        expect($tree[2]['value'])->toBe(' second half');
+    });
+
+    it('keeps blank lines and pipes inside a note fence', function () {
+        $tree = markupTree("文\n```note\n第一段 a|b }}\n\n第二段\n```");
+        $note = $tree[1];
+        expect(array_column($note['children'], 'tag'))->toBe(['p', 'p']);
+        expect($note['children'][0]['children'][0]['value'])->toBe('第一段 a|b }}');
+    });
+
+    it('attaches a note fence surrounded by blank lines to the end of the previous paragraph', function () {
+        $tree = markupTree("一段话。\n\n```note\n整段注\n```\n\n下一段");
+        expect(array_column($tree, 'tag'))->toBe(['p', 'p']);
+        expect(end($tree[0]['children']))->toMatchArray(['type' => 'tpl', 'name' => 'note']);
+    });
+
+    it('reads trigger from the note fence info string', function () {
+        expect(markupTree("a\n```note trigger=\"①\"\nx\n```")[1]['props'])->toBe(['trigger' => '①']);
+    });
+
+    it('supports a longer fence so that the note can contain code', function () {
+        $tree = markupTree("文\n````note\n```\ncode\n```\n````", ['contentType' => 'markdown-e2']);
+        expect($tree[1]['children'][0]['tag'])->toBe('pre');
+    });
+});
+
+describe('legacy dialect (markdown)', function () {
+    it('treats `x` as a single-line note', function () {
+        $tree = markupTree('依法`这里是注释`,故为');
+        expect($tree[1])->toMatchArray(['name' => 'note']);
+        expect($tree[1]['children'][0]['value'])->toBe('这里是注释');
+    });
+
+    it('treats a bare ``` fence as a multi-line note joined into the sentence', function () {
+        $tree = markupTree("[[bodhisatta]]讲述。\n```\n或译为:亲依止缘。\n```");
+        expect(array_column(markupTemplates($tree), 'name'))->toBe(['term', 'note']);
+    });
+
+    it('also accepts ```note', function () {
+        expect(markupTree("a\n```note\nb\n```")[1]['name'])->toBe('note');
+    });
+
+    it('still treats ```lang fences as code', function () {
+        $tree = markupTree("```python\nx = 1\n```");
+        expect($tree[0]['tag'])->toBe('pre');
+        expect($tree[0]['children'][0])->toMatchArray(['tag' => 'code', 'attrs' => ['class' => 'language-python']]);
+    });
+
+    it('treats any lowercase name= segment as a named param', function () {
+        expect(markupTree('{{note|x=1}}')[0]['children'])->toBe([]);
+    });
+});
+
+describe('E2 dialect (markdown-e2)', function () {
+    it('renders backticks as code, not notes', function () {
+        $tree = markupE2('use `{{note|x}}` and `[[term]]`');
+        expect($tree[1])->toMatchArray(['tag' => 'code', 'children' => [['type' => 'text', 'value' => '{{note|x}}']]]);
+        expect($tree[3]['children'][0]['value'])->toBe('[[term]]');
+        expect(markupTemplates($tree))->toBe([]);
+    });
+
+    it('renders bare fences as code', function () {
+        $tree = markupE2("```\n{{note|x}}\n```");
+        expect($tree[0]['tag'])->toBe('pre');
+        expect($tree[0]['children'][0]['children'][0]['value'])->toBe("{{note|x}}\n");
+    });
+
+    it('keeps pipes and a=b inside note content', function () {
+        $tree = markupE2('{{n|含 | 竖线 a=b|trigger=①}}');
+        expect($tree[0]['props'])->toBe(['trigger' => '①']);
+        expect($tree[0]['children'][0]['value'])->toBe('含 | 竖线 a=b');
+    });
+
+    it('only treats declared names as named params', function () {
+        $tree = markupE2('{{quality|x=featured}}');
+        expect($tree[0]['props']['value'])->toBe('pending');
+        expect(markupE2('{{quality|value=featured}}')[0]['props']['value'])->toBe('featured');
+    });
+
+    it('still supports note fences', function () {
+        expect(markupE2("a\n```note\nb\n```\nc")[1]['name'])->toBe('note');
+    });
+});
+
+describe('templates without data', function () {
+    it('renders mermaid fences in both dialects', function () {
+        foreach (['markdown', 'markdown-e2'] as $type) {
+            $tree = markupTree("```mermaid\ngraph TD\nA-->B\n```", ['contentType' => $type]);
+            expect($tree[0])->toMatchArray(['type' => 'tpl', 'name' => 'mermaid', 'props' => ['text' => "graph TD\nA-->B"]]);
+        }
+    });
+
+    it('renders mermaid per format', function () {
+        $source = "```mermaid\ngraph TD\nA-->B\n```";
+        expect(markupRender($source, Format::Html))->toBe("<pre class=\"mermaid\">graph TD\nA--&gt;B</pre>");
+        expect(markupRender($source, Format::Text))->toBe('mermaid');
+        expect(markupRender($source, Format::Prompt))->toBe("```mermaid\ngraph TD\nA-->B\n```");
+        expect(markupRender($source, Format::Markdown))->toBe($source);
+    });
+
+    it('renders quality and falls back to pending', function () {
+        expect(markupTree('{{quality|featured}}')[0]['props'])->toBe(['value' => 'featured']);
+        expect(markupTree('{{quality|bogus}}')[0]['props'])->toBe(['value' => 'pending']);
+        expect(markupRender('{{quality|draft}}', Format::Html))->toBe('<span><span class="tag-quality draft">draft</span></span>');
+    });
+
+    it('renders category, para, dict-pref and ai', function () {
+        expect(markupTree('{{category|vinaya}}')[0])->toMatchArray(['name' => 'category', 'props' => ['name' => 'vinaya']]);
+        expect(markupTree('{{para|id=160-9|title=aa|style=card}}', ['channels' => ['c1', 'c2']])[0]['props'])
+            ->toBe(['id' => '160-9', 'title' => 'aa', 'style' => 'card', 'channel' => 'c1_c2']);
+        expect(markupTree('{{dict-pref|2}}')[0]['props'])->toBe(['currPage' => 2, 'pageSize' => 100]);
+        expect(markupTree('{{ai|gpt}}')[0]['props'])->toBe(['model' => 'gpt']);
+        expect(markupRender('x{{ai|gpt}}', Format::Prompt))->toBe('x');
+        expect(markupRender('x{{ai|gpt}}', Format::Text))->toBe('xai');
+    });
+
+    it('renders video and strips unsafe urls', function () {
+        expect(markupTree('{{v|https://v.example/a.mp4}}')[0]['props'])
+            ->toBe(['url' => 'https://v.example/a.mp4', 'title' => '', 'style' => 'modal']);
+        // 显式给空值时用空值(v2 口径:参数存在就不取默认值)
+        expect(markupTree('{{v|https://v.example/a.mp4||intro}}')[0]['props'])
+            ->toBe(['url' => 'https://v.example/a.mp4', 'title' => 'intro', 'style' => '']);
+        expect(markupTree('{{v|javascript:alert(1)}}')[0]['props']['url'])->toBe('');
+    });
+
+    it('renders exercise and article', function () {
+        expect(markupTree('{{exercise|id=e1|title=Q1}}', ['channels' => ['c1']])[0]['props'])
+            ->toBe(['id' => 'e1', 'title' => 'Q1', 'channel' => 'c1']);
+        $article = markupTree('{{article|type=chapter|book=168|paragraphs=915|title=T}}')[0]['props'];
+        expect($article)->toMatchArray(['type' => 'chapter', 'id' => '168-915', 'title' => 'T', 'book' => '168']);
+        expect(markupRender('{{article|type=article|id=x|title=T}}', Format::Text))->toBe('T');
+        expect(markupRender('{{article|type=article|id=x|title=T}}', Format::Prompt))->toBe('');
+    });
+
+    it('renders nissaya templates and nissaya channel lines', function () {
+        expect(markupTree('{{nissaya|evaṃ|ဤသို့=thus}}')[0]['props'])
+            ->toMatchArray(['pali' => 'evaṃ', 'meaning' => ['ဤသို့', 'thus']]);
+
+        $lines = markupTree("evaṃ=ဤသို့\nme\$ငါ", ['channelType' => 'nissaya']);
+        expect(array_column(markupTemplates($lines), 'name'))->toBe(['nissaya', 'nissaya']);
+        expect(markupTemplates($lines)[1]['props']['pali'])->toBe('me');
+    });
+
+    it('renders nissaya json content', function () {
+        $json = json_encode([
+            ['original' => 'evaṃ', 'translation' => 'ဤသို့>thus', 'note' => 'n1'],
+            ['sn' => [1], 'word' => ['value' => 'me'], 'meaning' => ['value' => 'ငါ']],
+        ]);
+        $tree = markupTree($json, ['channelType' => 'nissaya', 'contentType' => 'json']);
+        expect(array_column(markupTemplates($tree), 'name'))->toBe(['nissaya', 'note', 'nissaya']);
+        expect(markupTemplates($tree)[0]['props']['meaning'])->toBe(['ဤသို့', 'thus']);
+    });
+
+    it('turns a list item holding only a div into a toggle', function () {
+        $tree = markupTree("- <div>title</div>\n- plain");
+        $first = $tree[0]['children'][0]['children'][0];
+        expect($first)->toMatchArray(['type' => 'tpl', 'name' => 'toggle']);
+        expect($first['children'][0]['tag'])->toBe('div');
+        expect($tree[0]['children'][1]['children'][0]['type'])->toBe('text');
+    });
+
+    it('renders a term without a channel as the plain word', function () {
+        $tree = markupTree('[[dhamma]]');
+        expect($tree[0])->toMatchArray(['name' => 'term', 'props' => ['word' => 'dhamma', 'parentChannelId' => null, 'parentStudioId' => null]]);
+        expect($tree[0]['children'])->toBe([['type' => 'text', 'value' => 'dhamma']]);
+        expect(markupTree('[[dhamma#法]]')[0]['props']['meaning'])->toBe('法');
+    });
+});
+
+describe('output formats', function () {
+    $source = "# 标题\n\n正文[[dhamma]]{{n|注释 **粗**|trigger=①}}结束。\n\n- 一\n- 二";
+
+    it('renders html with sidenotes and an endnote list', function () use ($source) {
+        $html = markupRender($source, Format::Html, ['footnote' => true]);
+        expect($html)
+            ->toContain('<h1 id="')
+            ->toContain('<span class="term-ref term_invalid" data-id="" data-term="dhamma">dhamma</span>')
+            ->toMatch('/<label for="(sn-[0-9a-f]{8}-1)" class="margin-toggle sidenote-number">①<\/label><input type="checkbox" id="\1" class="margin-toggle"\/>/')
+            ->toContain('<span class="sidenote"><span>注释 <strong>粗</strong></span></span>')
+            ->toContain('<ul><li>一</li><li>二</li></ul>')
+            ->toContain('<div><h1>endnote</h1><p><a name="footnote-1">[1]</a> <span>注释 <strong>粗</strong></span></p></div>');
+    });
+
+    it('omits the endnote list without the footnote option', function () use ($source) {
+        expect(markupRender($source, Format::Html))->not->toContain('endnote');
+    });
+
+    it('renders text, simple and prompt', function () use ($source) {
+        expect(markupRender($source, Format::Text))->toBe("标题\n正文dhamma①结束。\n一\n二");
+        expect(markupRender($source, Format::Simple))->toBe("标题\n正文dhamma结束。\n一\n二");
+        expect(markupRender($source, Format::Prompt))->toBe("标题\n正文dhamma结束。\n一\n二");
+    });
+
+    it('renders markdown with footnote references', function () use ($source) {
+        expect(markupRender($source, Format::Markdown, ['footnote' => true]))
+            ->toBe("# 标题\n\n正文dhamma[^1]结束。\n\n- 一\n- 二\n\n[^1]: 注释 **粗**");
+    });
+
+    it('renders legacy backtick notes as markdown footnotes', function () {
+        expect(markupRender('a`b`c', Format::Markdown, ['footnote' => true]))->toBe("a[^1]c\n\n[^1]: b");
+    });
+
+    it('prefixes attachment links in markdown', function () {
+        config(['app.url' => 'https://example.test']);
+        expect(markupRender('![a](/attachments/x.png)', Format::Markdown))->toBe('![a](https://example.test/attachments/x.png)');
+    });
+
+    it('numbers footnotes per document in renderMany', function () {
+        $out = app(MarkupService::class)->renderMany(['a' => '{{n|x}}', 'b' => '{{n|y}}'], new RenderOptions(format: Format::Markdown, footnote: true));
+        expect($out)->toBe(['a' => "[^1]\n\n[^1]: x", 'b' => "[^1]\n\n[^1]: y"]);
+    });
+});
+
+describe('legacy backtick edge cases (from real data)', function () {
+    it('treats a pair of double backticks as the note boundary', function () {
+        // 库里的写法:``注释``。v2 的正则把正文算成「`注释」、剩一个反引号;作者本意是整对是边界
+        $tree = markupTree('婆罗门。``x y``后文');
+        expect($tree[1])->toMatchArray(['name' => 'note']);
+        expect($tree[1]['children'][0]['value'])->toBe('x y');
+        expect($tree[2])->toBe(['type' => 'text', 'value' => '后文']);
+    });
+
+    it('accepts a backtick note whose backticks sit on their own lines', function () {
+        $tree = markupTree("然后她们(宫女)\n`\n环绕(parikkhipiṃsu)一词用的是复数。\n`\n用屏风围上。");
+        expect(array_column(markupTemplates($tree), 'name'))->toBe(['note']);
+        expect(markupRender("她们\n`\n注释\n`\n用屏风", Format::Text))->toBe("她们\n\n用屏风");
+    });
+
+    it('pairs backtick notes across lines like the authors meant', function () {
+        // 库里的真实写法:两条多行注释。v2 只在单行内配对,配成了「奉为」一条 + 一个跨行代码 span
+        $tree = markupTree("炬口王`  炬口王 (Okkāka):……\n其音、义皆与巴利语不同。\n`奉为`  奉为 (dahanti):直译为放置。`祖父。");
+        expect(array_column(markupTemplates($tree), 'name'))->toBe(['note', 'note']);
+        expect(markupTemplates($tree)[1]['children'][0]['value'])->toBe('奉为 (dahanti):直译为放置。');
+        expect(markupRender("炬口王`注1\n续`奉为`注2`祖父", Format::Text))->toBe('炬口王奉为祖父');
+    });
+
+    it('does not pair backticks across a blank line', function () {
+        $tree = markupTree("王`  炬口王\n\n奉为`");
+        expect(markupTemplates($tree))->toBe([]);
+        expect(markupText($tree))->toBe('王`  炬口王奉为`');
+    });
+
+    it('does not join a note fence with a following thematic break', function () {
+        $tree = markupTree("瞿低迦經\n```\n莊春江 譯\n```\n***\n第三");
+        expect(array_column($tree, 'tag'))->toBe(['p', 'hr', 'p']);
+    });
+});
+
+/*
+ * 新服务不准回头依赖 v2 的渲染与帮手类(v2 继续用它们,新服务各自独立)。
+ * 一个类一条:pest-plugin-arch 的数组写法会空过。
+ */
+foreach (['App\Http\Api\MdRender', 'App\Http\Api\TemplateRender', 'App\Http\Api\ChannelApi', 'App\Http\Controllers\CorpusController'] as $legacy) {
+    arch("App\\Services\\Markup does not use {$legacy}")
+        ->expect('App\Services\Markup')
+        ->not->toUse($legacy);
+}
+
+describe('emphasis next to CJK punctuation (markdown-cjk-friendly)', function () {
+    it('renders bold that wraps CJK punctuation', function (string $source, string $html) {
+        expect(markupRender($source, Format::Html))->toBe("<span>{$html}</span>");
+    })->with([
+        '引号在粗体里' => ['从**“tuccha”**的角度', '从<strong>“tuccha”</strong>的角度'],
+        '括号在粗体里' => ['是**(括号)**吗', '是<strong>(括号)</strong>吗'],
+        '标点在粗体外' => ['“**粗**”', '“<strong>粗</strong>”'],
+        '句号紧跟' => ['**粗**。', '<strong>粗</strong>。'],
+        '斜体' => ['这是*“斜”*体', '这是<em>“斜”</em>体'],
+    ]);
+
+    it('keeps CommonMark behaviour when neither side is CJK', function (string $source, string $html) {
+        expect(markupRender($source, Format::Html))->toBe("<span>{$html}</span>");
+    })->with([
+        ['a **b** c', 'a <strong>b</strong> c'],
+        ['a**b**c', 'a<strong>b</strong>c'],
+        ['**ramu** + tano', '<strong>ramu</strong> + tano'],
+        ['**foo "*bar*" foo**', '<strong>foo &quot;<em>bar</em>&quot; foo</strong>'],
+        ['*(**foo**)*', '<em>(<strong>foo</strong>)</em>'],
+        ['a * b * c', 'a * b * c'],
+        ['a**"foo"**', 'a**&quot;foo&quot;**'],
+        ['**foo**bar', '<strong>foo</strong>bar'],
+    ]);
+
+    it('only differs from the CommonMark flanking rule when a CJK character is involved', function () {
+        $commonmark = function (string $before, string $after): array {
+            $as = preg_match('/^\pZ|\s/u', $after) === 1;
+            $ap = preg_match('/^[\p{P}\p{S}]/u', $after) === 1;
+            $bs = preg_match('/^\pZ|\s/u', $before) === 1;
+            $bp = preg_match('/^[\p{P}\p{S}]/u', $before) === 1;
+
+            return [! $as && (! $ap || $bs || $bp), ! $bs && (! $bp || $as || $ap)];
+        };
+        $chars = ['a', 'Z', '0', ' ', "\n", '"', '(', ')', '.', ',', '-', 'ā', 'ṃ', '“', '”', ',', '。', '(', ')', '€'];
+        foreach ($chars as $before) {
+            foreach ($chars as $after) {
+                expect(CjkFriendlyEmphasisParser::flanking($before, $after))
+                    ->toBe($commonmark($before, $after), "before={$before} after={$after}");
+            }
+        }
+    });
+});

+ 326 - 0
api-v13/tests/Feature/MarkupTemplateDataTest.php

@@ -0,0 +1,326 @@
+<?php
+
+use App\Models\Article;
+use App\Models\BookTitle;
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Models\Discussion;
+use App\Models\PaliText;
+use App\Services\Markup\Format;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\RenderOptions;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * App\Services\Markup 里要查库的模板:术语、句子、quote、ql、qa、Tpl、g、ref,以及批量取数、逐段对读、嵌套层数。
+ */
+function markupDataTree(string $source, array $options = []): array
+{
+    return json_decode(json_encode(app(MarkupService::class)->render($source, new RenderOptions(...$options))), true);
+}
+
+function markupDataRender(string $source, Format $format, array $options = []): string
+{
+    return app(MarkupService::class)->render($source, new RenderOptions(...array_merge($options, ['format' => $format])));
+}
+
+function makeMarkupTerm(array $attrs): DhammaTerm
+{
+    $term = new DhammaTerm;
+    $term->forceFill(array_merge([
+        'id' => random_int(1, PHP_INT_MAX),
+        'guid' => (string) Str::uuid(),
+        'word_en' => $attrs['word'],
+        'meaning' => '',
+        'language' => 'zh-Hans',
+        'editor_id' => 0,
+        'create_time' => time() * 1000,
+        'modify_time' => time() * 1000,
+    ], $attrs))->save();
+
+    return $term;
+}
+
+/**
+ * root 名下的系统 channel。
+ */
+function makeSystemChannel(string $name, string $type = 'translation', string $lang = 'en'): string
+{
+    $uid = makeChannel(config('mint.admin.root_uuid'), $name);
+    Channel::where('uid', $uid)->update(['type' => $type, 'lang' => $lang]);
+
+    return $uid;
+}
+
+beforeEach(function () {
+    $this->owner = makeStudio('markup-owner');
+    $this->channel = makeChannel($this->owner, 'markup channel');
+});
+
+describe('term', function () {
+    it('finds the channel own term', function () {
+        makeMarkupTerm(['word' => 'dhamma', 'meaning' => '法', 'other_meaning' => '正法', 'channal' => $this->channel, 'owner' => $this->owner]);
+
+        $tree = markupDataTree('[[dhamma]]', ['channels' => [$this->channel]]);
+        expect($tree[0]['props'])->toMatchArray([
+            'word' => 'dhamma',
+            'meaning' => '法',
+            'meaning2' => '正法',
+            'channel' => $this->channel,
+            'parentChannelId' => $this->channel,
+            'parentStudioId' => $this->owner,
+        ]);
+        expect($tree[0]['children'])->toBe([['type' => 'text', 'value' => '法(dhamma)']]);
+    });
+
+    it('falls back to the studio term in the same language before the language family', function () {
+        makeMarkupTerm(['word' => 'sati', 'meaning' => '念-繁', 'language' => 'zh-Hant', 'owner' => $this->owner]);
+        makeMarkupTerm(['word' => 'sati', 'meaning' => '念', 'language' => 'zh-Hans', 'owner' => $this->owner]);
+        makeMarkupTerm(['word' => 'sati', 'meaning' => 'mindfulness', 'language' => 'en', 'owner' => $this->owner]);
+
+        expect(markupDataTree('[[sati]]', ['channels' => [$this->channel]])[0]['props']['meaning'])->toBe('念');
+    });
+
+    it('falls back to the community term channel', function () {
+        $community = makeSystemChannel('_community_term_zh-hans_');
+        makeMarkupTerm(['word' => 'kusala', 'meaning' => '善', 'channal' => $community, 'owner' => config('mint.admin.root_uuid')]);
+
+        $props = markupDataTree('{{term|kusala}}', ['channels' => [$this->channel]])[0]['props'];
+        expect($props)->toMatchArray(['meaning' => '善', 'isCommunity' => true]);
+    });
+
+    it('filters by tag with word@tag and overrides the label with word#text', function () {
+        makeMarkupTerm(['word' => 'sutta', 'meaning' => '经', 'tag' => 'a', 'channal' => $this->channel, 'owner' => $this->owner]);
+        makeMarkupTerm(['word' => 'sutta', 'meaning' => '契经', 'tag' => 'b', 'channal' => $this->channel, 'owner' => $this->owner]);
+
+        expect(markupDataTree('[[sutta@b]]', ['channels' => [$this->channel]])[0]['props']['meaning'])->toBe('契经');
+        expect(markupDataTree('[[sutta@a#经文]]', ['channels' => [$this->channel]])[0]['props']['meaning'])->toBe('经文');
+    });
+
+    it('leaves the term note out of the tree but renders it, with its own templates, in markdown', function () {
+        makeMarkupTerm(['word' => 'magga', 'meaning' => '道', 'note' => '见 [[nibbāna]]', 'channal' => $this->channel, 'owner' => $this->owner]);
+        makeMarkupTerm(['word' => 'nibbāna', 'meaning' => '涅槃', 'channal' => $this->channel, 'owner' => $this->owner]);
+
+        // 前端术语组件自己取词条详情,note 不随正文下发
+        expect(markupDataTree('[[magga]]', ['channels' => [$this->channel]])[0]['props'])->not->toHaveKey('note');
+        expect(markupDataRender('[[magga]]', Format::Markdown, ['channels' => [$this->channel], 'footnote' => true]))
+            ->toBe("道(magga)[^1]\n\n[^1]: 见 涅槃(nibbāna)");
+    });
+
+    it('expands term notes only one level deep', function () {
+        makeMarkupTerm(['word' => 'a', 'meaning' => '甲', 'note' => '甲注 [[b]]', 'channal' => $this->channel, 'owner' => $this->owner]);
+        makeMarkupTerm(['word' => 'b', 'meaning' => '乙', 'note' => '乙注 [[c]]', 'channal' => $this->channel, 'owner' => $this->owner]);
+        makeMarkupTerm(['word' => 'c', 'meaning' => '丙', 'channal' => $this->channel, 'owner' => $this->owner]);
+
+        // 甲的 note 里的乙只出译名,不再展开乙注(否则词条互相引用会成倍膨胀)
+        expect(markupDataRender('[[a]]', Format::Markdown, ['channels' => [$this->channel], 'footnote' => true]))
+            ->toBe("甲(a)[^1]\n\n[^1]: 甲注 乙(b)");
+    });
+
+    it('renders terms per format', function () {
+        makeMarkupTerm(['word' => 'dhamma', 'meaning' => '法', 'note' => '注', 'channal' => $this->channel, 'owner' => $this->owner]);
+        $options = ['channels' => [$this->channel]];
+
+        expect(markupDataRender('[[dhamma]]', Format::Text, $options))->toBe('法');
+        expect(markupDataRender('[[dhamma]]', Format::Html, $options))
+            ->toMatch('/^<span><span class="term-ref" data-id="[0-9a-f-]{36}" data-term="dhamma">法<\/span><\/span>$/');
+        expect(markupDataRender('[[dhamma]]与[[dhamma]]', Format::Markdown, $options + ['footnote' => true]))
+            ->toBe("法(dhamma)[^1]与法\n\n[^1]: 注");
+    });
+
+    it('looks up all terms of a document with a constant number of queries', function () {
+        $words = [];
+        foreach (range(1, 30) as $i) {
+            makeMarkupTerm(['word' => "w{$i}", 'meaning' => "义{$i}", 'channal' => $this->channel, 'owner' => $this->owner]);
+            $words[] = "[[w{$i}]]";
+        }
+        makeSystemChannel('_community_term_zh-hans_');
+
+        DB::enableQueryLog();
+        $tree = markupDataTree(implode(' ', $words), ['channels' => [$this->channel]]);
+        $queries = count(DB::getQueryLog());
+        DB::disableQueryLog();
+
+        expect(collect($tree)->where('type', 'tpl')->pluck('props.meaning')->all())->toHaveCount(30)->toContain('义30');
+        // channel、本 channel 术语、studio 术语、社区 channel、社区术语
+        expect($queries)->toBeLessThanOrEqual(6);
+    });
+});
+
+describe('sent', function () {
+    beforeEach(function () {
+        $this->pali = makeSystemChannel('_System_Pali_VRI_', 'original', 'pi');
+        makeSentence($this->pali, 999, 1, 1, '<span>Evaṃ me sutaṃ</span>');
+        makeSentence($this->channel, 999, 1, 1, '如是我闻[[dhamma]]');
+        makeMarkupTerm(['word' => 'dhamma', 'meaning' => '法', 'channal' => $this->channel, 'owner' => $this->owner]);
+    });
+
+    it('renders origin and translation bodies with the row channel', function () {
+        $props = markupDataTree('{{999-1-1-1}}', ['channels' => [$this->channel]])[0]['props'];
+
+        // 只给渲染要用的:坐标在 id 里,原文 / 译文已分组(不给 channel.type),没有义注就不给 commentaries
+        expect(array_keys($props))->toBe(['id', 'show', 'origin', 'translation']);
+        expect($props)->toMatchArray(['id' => '999-1-1-1', 'show' => 'both']);
+        expect($props['origin'][0]['channel'])->toBe(['id' => $this->pali, 'name' => '_System_Pali_VRI_', 'lang' => 'pi']);
+        expect(array_keys($props['origin'][0]))->toBe(['id', 'channel', 'body']);
+        expect($props['origin'][0]['body'][0])->toMatchArray(['type' => 'el', 'tag' => 'span']);
+        expect($props['translation'][0]['body'][1]['name'])->toBe('term');
+        expect($props['translation'][0]['body'][1]['props']['meaning'])->toBe('法');
+        expect($props['translation'][0])->not->toHaveKey('content');
+    });
+
+    it('includes the source content in edit mode', function () {
+        $wbw = makeSystemChannel('_System_Wbw_VRI_', 'wbw', 'pi');
+        makeSentence($wbw, 999, 1, 1, 'wbw text');
+        $tree = markupDataTree('{{999-1-1-1}}', ['channels' => [$this->channel], 'mode' => 'edit']);
+
+        expect($tree[0]['name'])->toBe('sentedit');
+        expect($tree[0]['props']['translation'][0]['content'])->toBe('如是我闻[[dhamma]]');
+        expect($tree[0]['props']['translation'][0]['contentType'])->toBe('markdown');
+        expect($tree[0]['props']['origin'][0]['channel']['id'])->toBe($wbw);
+    });
+
+    it('reads a single channel with id@channel', function () {
+        $other = makeChannel($this->owner, 'other');
+        makeSentence($other, 999, 1, 1, '另一译');
+
+        $props = markupDataTree("{{999-1-1-1@{$other}}}", ['channels' => [$this->channel]])[0]['props'];
+        expect(array_column(array_column($props['translation'], 'channel'), 'id'))->toBe([$other]);
+    });
+
+    it('renders sentences per format and honours text=', function () {
+        $options = ['channels' => [$this->channel]];
+        expect(markupDataRender('{{999-1-1-1}}', Format::Html, $options))
+            ->toBe('<span><span class="sentence"><span class="origin"><span><span>Evaṃ me sutaṃ</span></span></span>'
+                .'<span class="translation"><span>如是我闻<span class="term-ref" data-id="'
+                .DhammaTerm::where('word', 'dhamma')->value('guid').'" data-term="dhamma">法</span></span></span></span></span>');
+        expect(markupDataRender('{{sent|id=999-1-1-1|text=translation}}', Format::Text, $options))->toBe('如是我闻法');
+        expect(markupDataRender('{{999-1-1-1}}', Format::Simple, $options))->toBe('Evaṃ me sutaṃ如是我闻法');
+        expect(markupDataRender('{{999-1-1-1}}', Format::Markdown, $options + ['origin' => false]))->toBe('如是我闻法(dhamma)');
+    });
+
+    it('renders a markdown-e2 sentence with code instead of notes', function () {
+        DB::table('sentences')->where('channel_uid', $this->channel)->update(['content' => '用 `code`', 'content_type' => 'markdown-e2']);
+
+        $body = markupDataTree('{{999-1-1-1}}', ['channels' => [$this->channel]])[0]['props']['translation'][0]['body'];
+        expect($body[1])->toMatchArray(['type' => 'el', 'tag' => 'code']);
+    });
+
+    it('renders sentences inside raw html blocks', function () {
+        $tree = markupDataTree("<nt>\n{{999-1-1-1}}\n</nt>", ['channels' => [$this->channel]]);
+        expect($tree[0]['attrs']['data-tag'])->toBe('nt');
+        $sent = collect($tree[0]['children'])->firstWhere('type', 'tpl');
+        expect($sent['props']['translation'][0]['body'][0]['value'])->toBe('如是我闻');
+    });
+
+    it('duplicates sentence-only paragraphs in paragraph mode', function () {
+        $tree = markupDataTree("{{999-1-1-1}}\n\n正文", ['channels' => [$this->channel], 'paragraph' => true]);
+        expect(array_column($tree, 'tag'))->toBe(['p', 'p', 'p']);
+        expect($tree[0]['children'][0]['props']['show'])->toBe('origin');
+        expect($tree[1]['children'][0]['props']['show'])->toBe('translation');
+    });
+
+    it('loads all sentences of a document in one query', function () {
+        foreach (range(2, 20) as $start) {
+            makeSentence($this->channel, 999, 1, $start, "句{$start}");
+        }
+        $source = implode('', array_map(fn ($start) => "{{999-1-{$start}-{$start}}}", range(1, 20)));
+
+        DB::enableQueryLog();
+        markupDataTree($source, ['channels' => [$this->channel]]);
+        $sentenceQueries = collect(DB::getQueryLog())->filter(fn ($q) => str_contains($q['query'], 'from "sentences"'))->count();
+        DB::disableQueryLog();
+
+        expect($sentenceQueries)->toBe(1);
+    });
+
+    it('stops nesting content that refers to itself', function () {
+        DB::table('sentences')->where('channel_uid', $this->channel)->update(['content' => '自引{{999-1-1-1}}']);
+
+        $tree = markupDataTree('{{999-1-1-1}}', ['channels' => [$this->channel]]);
+        $json = json_encode($tree, JSON_UNESCAPED_UNICODE);
+        // 文章 → 句子正文 → 句子正文,第 3 层不再展开
+        expect(substr_count($json, '自引'))->toBe(2);
+        expect($json)->toContain('"body":null');
+    });
+
+    it('lists referenced books with ref', function () {
+        BookTitle::forceCreate(['book' => 999, 'paragraph' => 0, 'title' => 'dīghanikāya', 'sn' => 1]);
+
+        $props = markupDataTree("{{999-1-1-1}}\n\n{{ref}}", ['channels' => [$this->channel]])[1]['children'][0]['props'];
+        expect($props['pali'])->toBe([['sn' => 1, 'title' => 'dīghanikāya', 'copyright' => 'CSCD V4 VRI 2008']]);
+        expect(markupDataRender("{{999-1-1-1}}\n\n{{ref}}", Format::Markdown, ['channels' => [$this->channel]]))
+            ->toEndWith("[1] **Dīghanikāya** CSCD V4 VRI 2008\n\n");
+    });
+});
+
+describe('templates reading other tables', function () {
+    it('renders quote with the paragraph toc', function () {
+        (new PaliText)->forceFill([
+            'book' => 9001, 'paragraph' => 3, 'level' => 2, 'class' => '', 'toc' => 'Brahmajālasutta',
+            'text' => '', 'html' => '', 'path' => json_encode([['title' => 'dīgha']]), 'uid' => (string) Str::uuid(),
+        ])->save();
+
+        expect(markupDataTree('{{quote|9001-3}}', ['channels' => [$this->channel]])[0]['props'])
+            ->toBe(['paraId' => '9001-3', 'pali' => 'Brahmajālasutta']);
+        expect(markupDataRender('{{quote|9001-3}}', Format::Text))->toBe('Brahmajālasutta');
+        expect(markupDataRender('{{quote|9001-404}}', Format::Text))->toBe('9001-404');
+    });
+
+    it('renders qa with the discussion title', function () {
+        $qa = Discussion::forceCreate([
+            'res_type' => 'sentence', 'res_id' => (string) Str::uuid(), 'type' => 'qa',
+            'title' => '为什么?', 'content' => 'body', 'editor_uid' => $this->owner,
+        ]);
+
+        $props = markupDataTree("{{qa|{$qa->id}}}")[0]['props'];
+        expect($props)->toBe(['id' => $qa->id, 'title' => '为什么?', 'resType' => 'sentence']);
+    });
+
+    it('renders Tpl articles with mustache params', function () {
+        (new Article)->forceFill([
+            'id' => random_int(1, PHP_INT_MAX), 'uid' => (string) Str::uuid(), 'title' => 'Tpl:greet',
+            'content' => 'Hello **{{1}}** from {{place}}', 'owner' => $this->owner, 'owner_id' => 0, 'editor_id' => 0,
+            'create_time' => time() * 1000, 'modify_time' => time() * 1000,
+        ])->save();
+
+        $tree = markupDataTree('{{Tpl:greet|Ānanda|place=Sāvatthī}}');
+        expect($tree[0])->toMatchArray(['name' => 'tpl', 'props' => ['name' => 'Tpl:greet']]);
+        expect($tree[0]['children'][1])->toMatchArray(['tag' => 'strong']);
+        expect(markupDataRender('{{Tpl:greet|Ānanda|place=Sāvatthī}}', Format::Text))->toBe('Hello Ānanda from Sāvatthī');
+        expect(markupDataTree('{{Tpl:missing}}')[0]['children'])->toBe([]);
+    });
+
+    it('renders grammar lookups from the system grammar channel', function () {
+        $grammar = makeSystemChannel('_System_Grammar_Term_en_');
+        makeMarkupTerm(['word' => 'nom', 'meaning' => 'nominative', 'channal' => $grammar, 'owner' => config('mint.admin.root_uuid')]);
+
+        $props = markupDataTree('{{g|nom}}', ['channels' => [$this->channel]])[0]['props'];
+        expect($props['word'])->toBe('nom');
+        expect($props['term'])->toMatchArray(['meaning' => 'nominative', 'channel' => $grammar]);
+    });
+
+    it('renders quote-link with a localized book name', function () {
+        makeMarkupTerm(['word' => 'dīghanikāya', 'meaning' => '长部', 'tag' => ':quote:', 'channal' => $this->channel, 'owner' => $this->owner]);
+
+        $tree = markupDataTree('{{ql|type=m|bookname=dīghanikāya|volume=1|page=23}}', ['channels' => [$this->channel]]);
+        expect($tree[0]['name'])->toBe('quote-link');
+        expect($tree[0]['props'])->toMatchArray(['type' => 'm', 'bookName' => 'dīghanikāya', 'volume' => 1, 'page' => '23']);
+        expect($tree[0]['props'])->not->toHaveKey('bookNameLocal');
+        expect($tree[0]['props']['term']['meaning'])->toBe('长部');
+        expect(markupDataRender('{{ql|type=m|bookname=dīghanikāya|volume=1|page=23}}', Format::Text, ['channels' => [$this->channel]]))
+            ->toBe('长部 1.23');
+    });
+
+    it('renders nissaya with the channel language', function () {
+        Channel::where('uid', $this->channel)->update(['lang' => 'my']);
+
+        expect(markupDataTree('{{nissaya|evaṃ|ဤသို့}}', ['channels' => [$this->channel]])[0]['props'])->toBe(['pali' => 'evaṃ', 'meaning' => ['ဤသို့']]);
+        expect(markupDataRender('{{nissaya|evaṃ|ဤသို့}}', Format::Html, ['channels' => [$this->channel]]))
+            ->toBe('<span><span lang="pi-Mymr">evaṃ</span>၊ <span lang="my">ဤသို့</span></span>');
+    });
+});