Jelajahi Sumber

🐛 (api-v13): 术语 summary_text 取 note 的第一个自然段,不再只取第一行

没有 summary 时,原来把整篇 note 渲染成纯文本再取第一个非空行;纯文本里段落之间
与段内换行都只是一个换行,分不出段,开头是 {{ai}} 的术语就只得到「[AI 生成内容]」。
改为渲染前在源码上按空行取第一段(markdown / markdown-e2 相同),跳过标题、围栏、
分隔线与只有模板的段,段首只有模板的行(如 {{ai}})去掉。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 23 jam lalu
induk
melakukan
3dc6706742
2 mengubah file dengan 51 tambahan dan 10 penghapusan
  1. 37 10
      api-v13/app/Services/V3/TermService.php
  2. 14 0
      api-v13/tests/Feature/TermV3Test.php

+ 37 - 10
api-v13/app/Services/V3/TermService.php

@@ -517,7 +517,7 @@ class TermService
                 'contentType' => $term->effectiveContentType(),
                 'contentType' => $term->effectiveContentType(),
             ];
             ];
             $summary = trim((string) $term->summary);
             $summary = trim((string) $term->summary);
-            $items["{$term->guid}|summary"] = $base + ['source' => $summary !== '' ? $summary : (string) $term->note];
+            $items["{$term->guid}|summary"] = $base + ['source' => $summary !== '' ? $summary : $this->firstParagraph((string) $term->note)];
             if ($withBody) {
             if ($withBody) {
                 $bodyChannels = ! empty($render['channels']) ? $render['channels'] : $base['channels'];
                 $bodyChannels = ! empty($render['channels']) ? $render['channels'] : $base['channels'];
                 $items["{$term->guid}|body"] = ['channels' => $bodyChannels] + $base + ['source' => trim($summary."\n\n".(string) $term->note)];
                 $items["{$term->guid}|body"] = ['channels' => $bodyChannels] + $base + ['source' => trim($summary."\n\n".(string) $term->note)];
@@ -533,7 +533,7 @@ class TermService
         foreach ($terms as $term) {
         foreach ($terms as $term) {
             $term->abilities = $abilities[$term->guid];
             $term->abilities = $abilities[$term->guid];
             $text = (string) $rendered[Format::Text->value]["{$term->guid}|summary"];
             $text = (string) $rendered[Format::Text->value]["{$term->guid}|summary"];
-            $term->summary_text = trim((string) $term->summary) !== '' ? trim($text) : $this->firstParagraph($text);
+            $term->summary_text = trim($text);
             if ($withBody && $bodyFormat === Format::Html) {
             if ($withBody && $bodyFormat === Format::Html) {
                 $term->html = (string) $rendered[Format::Html->value]["{$term->guid}|body"];
                 $term->html = (string) $rendered[Format::Html->value]["{$term->guid}|body"];
             } elseif ($withBody) {
             } elseif ($withBody) {
@@ -543,18 +543,45 @@ class TermService
     }
     }
 
 
     /**
     /**
-     * 纯文本渲染({@see Format::Text})里段落之间只隔一个换行,第一个非空行就是第一段。
+     * 正文源码(markdown / markdown-e2)的第一个自然段,渲染前在源码上取。
+     *
+     * 不能渲染后再切:纯文本渲染里段落之间与段内换行都只是一个 `\n`,分不出段。
+     * 自然段以空行分隔(两种方言相同),围栏(```)内的空行不算;跳过标题、围栏、分隔线、
+     * 以及只由模板组成的段(`{{toc}}` 等);段首只由模板组成的行(如 `{{ai}}` 提示)去掉。
+     * 一段也没有时退回整篇。
      */
      */
-    private function firstParagraph(string $text): string
-    {
-        foreach (preg_split('/\n/u', $text) ?: [] as $paragraph) {
-            $paragraph = trim($paragraph);
-            if ($paragraph !== '') {
-                return $paragraph;
+    private function firstParagraph(string $source): string
+    {
+        $blocks = [];
+        $lines = [];
+        $fenced = false;
+        foreach (preg_split('/\R/u', $source) ?: [] as $line) {
+            if (preg_match('/^\s*(```|~~~)/u', $line) === 1) {
+                $fenced = ! $fenced;
             }
             }
+            if (! $fenced && trim($line) === '') {
+                $blocks[] = $lines;
+                $lines = [];
+
+                continue;
+            }
+            $lines[] = $line;
+        }
+        $blocks[] = $lines;
+
+        $templateOnly = '/^\s*(?:(?<t>\{\{(?:[^{}]++|(?&t))*\}\})\s*)+$/u';
+        foreach ($blocks as $lines) {
+            while ($lines !== [] && preg_match($templateOnly, $lines[0]) === 1) {
+                array_shift($lines);
+            }
+            if ($lines === [] || preg_match('/^\s*(#|```|~~~|([-*_])\s*\2\s*\2[\s\-*_]*$)/u', $lines[0]) === 1) {
+                continue;
+            }
+
+            return implode("\n", $lines);
         }
         }
 
 
-        return '';
+        return $source;
     }
     }
 
 
     /**
     /**

+ 14 - 0
api-v13/tests/Feature/TermV3Test.php

@@ -162,6 +162,20 @@ it('shows a term with ETag, and hides terms of private channels', function () {
     $this->getJson('/api/v3/terms/'.Str::uuid())->assertNotFound();
     $this->getJson('/api/v3/terms/'.Str::uuid())->assertNotFound();
 });
 });
 
 
+it('takes the first natural paragraph of the note as summary_text, in both dialects', function (string $contentType) {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $note = "## 标题\n\n{{toc}}\n\n{{ai}}\n第一段第一行,\n第一段第二行。\n\n```\n围栏\n\n里的空行\n```\n\n第二段。";
+    $term = newTerm($channel, $owner, ['note' => $note, 'content_type' => $contentType]);
+
+    $text = $this->getJson("/api/v3/terms/{$term['id']}")->assertOk()->json('data.summary_text');
+    expect($text)->toContain('第一段第一行')->toContain('第一段第二行')
+        ->not->toContain('AI')->not->toContain('标题')->not->toContain('第二段');
+
+    $listed = $this->getJson("/api/v3/terms?word={$term['word']}")->assertOk()->json('data.0.summary_text');
+    expect($listed)->toBe($text);
+})->with(['markdown', 'markdown-e2']);
+
 it('treats legacy studio-level terms with an empty-string channal like null ones', function () {
 it('treats legacy studio-level terms with an empty-string channal like null ones', function () {
     [$team, $users] = makeTeam();
     [$team, $users] = makeTeam();
     $created = $this->postJson("/api/v3/studios/{$team}/terms", ['word' => 'legacy', 'meaning' => '老', 'language' => 'zh-Hans'], authHeader($users['owner']))
     $created = $this->postJson("/api/v3/studios/{$team}/terms", ['word' => 'legacy', 'meaning' => '老', 'language' => 'zh-Hans'], authHeader($users['owner']))