Kaynağa Gözat

✨ 新模板 {{ai}}:AI 生成内容提示

{{ai}} / {{ai|标题}} / {{ai|标题|说明}},参数 title、message(markdown)、
style=block|tag。block 是黄底引用块(警告图标 + 标题,下面是说明);
tag 行内只显示图标与「AI」,鼠标移入显示标题与说明。默认标题
labels.ai_generated(随内容语言)。

取代新渲染器里的旧 {{ai|model}}(AI 对话组件,库里无实际使用;
v2 TemplateRender 与 dashboard-v4 不动)。

- Template::block() 改为接收 Call(ai 只有 block 样式是块级)
- library 阅读页与 wiki 条目页共用 resources/css/modules/markup-ai.css
- dashboard-v6 新增 template/Ai.tsx(图标放进标题,避免 antd Alert
  有 description 时放大图标)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 5 saat önce
ebeveyn
işleme
d41c4d5e05

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

@@ -111,7 +111,7 @@ final class HtmlRenderer implements Renderer
             if ($node instanceof Text && trim($node->value) === '') {
             if ($node instanceof Text && trim($node->value) === '') {
                 continue;
                 continue;
             }
             }
-            if (! $node instanceof Call || ! $node->template->block()) {
+            if (! $node instanceof Call || ! $node->template->block($node)) {
                 return false;
                 return false;
             }
             }
             $found = true;
             $found = true;

+ 97 - 5
api-v13/app/Services/Markup/Templates/AiTemplate.php

@@ -4,18 +4,58 @@ namespace App\Services\Markup\Templates;
 
 
 use App\Services\Markup\Format;
 use App\Services\Markup\Format;
 use App\Services\Markup\Ir\Call;
 use App\Services\Markup\Ir\Call;
+use App\Services\Markup\Ir\Document;
+use App\Services\Markup\Render\HtmlRenderer;
 use App\Services\Markup\Render\RenderContext;
 use App\Services\Markup\Render\RenderContext;
 
 
 /**
 /**
- * AI 对话组件:`{{ai|model}}`。prompt 输出里不出现。
+ * AI 生成内容提示:`{{ai}}`、`{{ai|标题}}`、`{{ai|标题|说明}}`、`{{ai|title=…|message=…|style=tag}}`。
+ *
+ * - title:标题,缺省(或为空)是「AI 生成内容」(labels.ai_generated,随内容语言)
+ * - message:说明文字,markdown(可嵌模板)
+ * - style:`block`(默认)黄底引用块,左上角警告图标 + 标题,下面是说明;
+ *   `tag` 行内只显示图标与「AI」,鼠标移入才显示标题与说明
+ *
+ * tree:`{name: 'ai', props: {title, style}, children: message}`。
+ *
+ * 取代旧的 AI 对话组件 `{{ai|model}}`(只有 v2 TemplateRender / dashboard-v4 在用,那边不动)。
  */
  */
 final class AiTemplate extends Template
 final class AiTemplate extends Template
 {
 {
     protected string $component = 'ai';
     protected string $component = 'ai';
 
 
+    private const STYLES = ['block', 'tag'];
+
+    private const ICON = '<svg class="markup-ai-icon" viewBox="0 0 16 16" width="1em" height="1em" aria-hidden="true">'
+        .'<path fill="currentColor" d="M8.87 1.5a1 1 0 0 0-1.74 0L.63 13a1 1 0 0 0 .87 1.5h13a1 1 0 0 0 .87-1.5L8.87 1.5ZM8 5a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 5Zm0 7.25a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"/>'
+        .'</svg>';
+
     public function params(): array
     public function params(): array
     {
     {
-        return ['model' => ParamSpec::at(1, '1')];
+        return [
+            'title' => ParamSpec::at(1),
+            'message' => ParamSpec::markdown(2),
+            'style' => ParamSpec::at(3, 'block'),
+        ];
+    }
+
+    public function block(Call $call): bool
+    {
+        return $this->style($call) === 'block';
+    }
+
+    private function style(Call $call): string
+    {
+        $style = trim((string) $call->param('style'));
+
+        return in_array($style, self::STYLES, true) ? $style : 'block';
+    }
+
+    private function title(Call $call, RenderContext $ctx): string
+    {
+        $title = trim((string) $call->param('title'));
+
+        return $title !== '' ? $title : (string) __('labels.ai_generated', [], $ctx->lang($call->scope));
     }
     }
 
 
     /**
     /**
@@ -23,16 +63,68 @@ final class AiTemplate extends Template
      */
      */
     public function props(Call $call, RenderContext $ctx): array
     public function props(Call $call, RenderContext $ctx): array
     {
     {
-        return ['model' => (string) $call->param('model')];
+        return ['title' => $this->title($call, $ctx), 'style' => $this->style($call)];
+    }
+
+    public function children(Call $call, RenderContext $ctx): ?Document
+    {
+        return $call->slot('message');
+    }
+
+    private function message(Call $call, RenderContext $ctx): string
+    {
+        $slot = $call->slot('message');
+
+        return $slot === null ? '' : trim($ctx->renderString($slot));
     }
     }
 
 
     public function text(Call $call, RenderContext $ctx): string
     public function text(Call $call, RenderContext $ctx): string
     {
     {
-        return 'ai';
+        $message = $this->message($call, $ctx);
+        $title = $this->title($call, $ctx);
+
+        return $message === '' ? "[{$title}]" : "[{$title}] {$message}";
     }
     }
 
 
+    /**
+     * 是界面提示而不是正文:prompt 里不出现。
+     */
     public function plain(Call $call, RenderContext $ctx, Format $format): string
     public function plain(Call $call, RenderContext $ctx, Format $format): string
     {
     {
-        return $format === Format::Prompt ? '' : 'ai';
+        return $format === Format::Prompt ? '' : $this->text($call, $ctx);
+    }
+
+    /**
+     * 只用 span(block 样式靠 CSS 显示成块),写在句子中间、脚注里都不会切断外层结构。
+     */
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $slot = $call->slot('message');
+        $message = $slot !== null && $ctx->renderer instanceof HtmlRenderer
+            ? $ctx->renderer->inlineSafe($slot, $ctx)
+            : e($this->message($call, $ctx));
+        $title = e($this->title($call, $ctx));
+        $messageHtml = $message === '' ? '' : '<span class="markup-ai-message">'.$message.'</span>';
+
+        if ($this->style($call) === 'tag') {
+            return '<span class="markup-ai markup-ai-tag" tabindex="0">'.self::ICON.'AI'
+                .'<span class="markup-ai-popup" role="tooltip"><span class="markup-ai-title">'.$title.'</span>'.$messageHtml.'</span>'
+                .'</span>';
+        }
+
+        return '<span class="markup-ai markup-ai-block" role="note">'
+            .'<span class="markup-ai-title">'.self::ICON.$title.'</span>'.$messageHtml
+            .'</span>';
+    }
+
+    public function markdown(Call $call, RenderContext $ctx): string
+    {
+        $title = $this->title($call, $ctx);
+        $message = $this->message($call, $ctx);
+        if ($this->style($call) === 'tag') {
+            return '⚠ AI';
+        }
+
+        return "\n\n> ⚠ **{$title}**".($message === '' ? '' : "\n>\n> ".str_replace("\n", "\n> ", $message))."\n\n";
     }
     }
 }
 }

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

@@ -15,7 +15,7 @@ final class MermaidTemplate extends Template
 {
 {
     protected string $component = 'mermaid';
     protected string $component = 'mermaid';
 
 
-    public function block(): bool
+    public function block(Call $call): bool
     {
     {
         return true;
         return true;
     }
     }

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

@@ -70,9 +70,9 @@ abstract class Template
     public function collect(Call $call, Resolver $resolver): void {}
     public function collect(Call $call, Resolver $resolver): void {}
 
 
     /**
     /**
-     * html 输出是块级元素(目录的 nav、mermaid 的 pre):段落里只有它时不包 `<p>`。
+     * html 输出是块级元素(目录的 nav、mermaid 的 pre、`{{ai}}` 的 block 样式):段落里只有它时不包 `<p>`。
      */
      */
-    public function block(): bool
+    public function block(Call $call): bool
     {
     {
         return false;
         return false;
     }
     }

+ 1 - 1
api-v13/app/Services/Markup/Templates/TocTemplate.php

@@ -28,7 +28,7 @@ final class TocTemplate extends Template
 
 
     protected string $component = 'toc';
     protected string $component = 'toc';
 
 
-    public function block(): bool
+    public function block(Call $call): bool
     {
     {
         return true;
         return true;
     }
     }

+ 78 - 0
api-v13/resources/css/modules/markup-ai.css

@@ -0,0 +1,78 @@
+/* resources/css/modules/markup-ai.css
+   {{ai}} AI 生成内容提示(App\Services\Markup\Templates\AiTemplate 的 html 输出)。
+   不限定容器:阅读页(reader.css)与 wiki 条目页(wiki.css)共用。
+   全是 span,block 样式靠 display 显示成块。
+   wikipali-mobile 的阅读页(ReaderLayerPane.tsx)有一份同样的规则,改这里记得同步。
+*/
+
+.markup-ai {
+    --markup-ai-bg: #fffbe6;
+    --markup-ai-border: #ffe58f;
+    --markup-ai-icon: #faad14;
+}
+.dark-mode .markup-ai {
+    --markup-ai-bg: #2b2111;
+    --markup-ai-border: #594214;
+    --markup-ai-icon: #d89614;
+}
+.markup-ai-icon {
+    color: var(--markup-ai-icon);
+    flex: none;
+}
+.markup-ai-title {
+    display: flex;
+    align-items: center;
+    gap: 0.4em;
+    font-weight: 600;
+}
+.markup-ai-message {
+    display: block;
+}
+.markup-ai-block {
+    display: block;
+    margin: 1rem 0;
+    padding: 0.6rem 1rem;
+    background: var(--markup-ai-bg);
+    border-left: 3px solid var(--markup-ai-border);
+    border-radius: 4px;
+}
+.markup-ai-block .markup-ai-message {
+    margin-top: 0.25rem;
+}
+.markup-ai-tag {
+    position: relative;
+    display: inline-flex;
+    align-items: center;
+    gap: 0.2em;
+    padding: 0 0.35em;
+    font-size: 0.8em;
+    line-height: 1.5;
+    background: var(--markup-ai-bg);
+    border: 1px solid var(--markup-ai-border);
+    border-radius: 4px;
+    cursor: help;
+    vertical-align: 0.1em;
+}
+.markup-ai-popup {
+    display: none;
+    position: absolute;
+    z-index: 10;
+    left: 0;
+    top: 100%;
+    margin-top: 4px;
+    width: max-content;
+    max-width: 20rem;
+    padding: 0.5rem 0.75rem;
+    font-size: 0.9rem;
+    font-weight: normal;
+    background: var(--markup-ai-bg);
+    border: 1px solid var(--markup-ai-border);
+    border-radius: 4px;
+    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
+    cursor: auto;
+}
+.markup-ai-tag:hover .markup-ai-popup,
+.markup-ai-tag:focus .markup-ai-popup,
+.markup-ai-tag:focus-within .markup-ai-popup {
+    display: block;
+}

+ 2 - 0
api-v13/resources/css/modules/wiki.css

@@ -9,6 +9,8 @@
    本文件只保留 wiki 专属内容。
    本文件只保留 wiki 专属内容。
 */
 */
 
 
+@import './markup-ai.css';
+
 /* ══════════════════════════════════════════
 /* ══════════════════════════════════════════
    一、语言版本切换
    一、语言版本切换
    ══════════════════════════════════════════ */
    ══════════════════════════════════════════ */

+ 1 - 0
api-v13/resources/css/reader.css

@@ -5,3 +5,4 @@
 
 
 @import './modules/reader.css';
 @import './modules/reader.css';
 @import './modules/reader-content.css';
 @import './modules/reader-content.css';
+@import './modules/markup-ai.css';

+ 1 - 0
api-v13/resources/lang/en/labels.php

@@ -9,6 +9,7 @@ return [
     'similar' => 'Parallels',
     'similar' => 'Parallels',
     'toc' => 'Contents',
     'toc' => 'Contents',
     'references' => 'References',
     'references' => 'References',
+    'ai_generated' => 'AI-generated content',
 
 
     'script_convertor' => 'Pāli Script Converter',
     'script_convertor' => 'Pāli Script Converter',
     'input_script' => 'Input Script',
     'input_script' => 'Input Script',

+ 1 - 0
api-v13/resources/lang/zh-Hans/labels.php

@@ -9,6 +9,7 @@ return [
     'similar' => '相似段落',
     'similar' => '相似段落',
     'toc' => '目录',
     'toc' => '目录',
     'references' => '参考文献',
     'references' => '参考文献',
+    'ai_generated' => 'AI 生成内容',
 
 
     'script_convertor' => '巴利文字转换器',
     'script_convertor' => '巴利文字转换器',
     'input_script' => '输入文字',
     'input_script' => '输入文字',

+ 2 - 0
api-v13/resources/lang/zh-Hant/labels.php

@@ -1,7 +1,9 @@
 <?php
 <?php
+
 return [
 return [
     'toc' => '目錄',
     'toc' => '目錄',
     'references' => '參考文獻',
     'references' => '參考文獻',
+    'ai_generated' => 'AI 生成內容',
     'home' => '首页',
     'home' => '首页',
     'translation' => '譯文',
     'translation' => '譯文',
     'original' => '原文',
     'original' => '原文',

+ 33 - 4
api-v13/tests/Feature/MarkupSyntaxTest.php

@@ -409,14 +409,43 @@ describe('templates without data', function () {
         expect(markupRender('{{quality|draft}}', Format::Html))->toBe('<span><span class="tag-quality draft">draft</span></span>');
         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 () {
+    it('renders category, para and dict-pref', function () {
         expect(markupTree('{{category|vinaya}}')[0])->toMatchArray(['name' => 'category', 'props' => ['name' => 'vinaya']]);
         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'])
         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']);
             ->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('{{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 the ai notice with default title, positional title and markdown message', function () {
+        $default = markupTemplates(markupTree('{{ai}}', ['lang' => 'zh-Hans']))[0];
+        expect($default['name'])->toBe('ai');
+        expect($default['props'])->toBe(['title' => 'AI 生成内容', 'style' => 'block']);
+
+        expect(markupTemplates(markupTree('{{ai|机器翻译}}'))[0]['props'])->toBe(['title' => '机器翻译', 'style' => 'block']);
+
+        $full = markupTemplates(markupTree('{{ai|title=草稿|message=未经**校对**|style=tag}}'))[0];
+        expect($full['props'])->toBe(['title' => '草稿', 'style' => 'tag']);
+        expect(json_encode($full['children'], JSON_UNESCAPED_UNICODE))->toContain('校对');
+
+        // 未知 style 按 block
+        expect(markupTemplates(markupTree('{{ai|style=bogus}}', ['lang' => 'en']))[0]['props'])
+            ->toBe(['title' => 'AI-generated content', 'style' => 'block']);
+    });
+
+    it('renders the ai notice in html, text and prompt', function () {
+        // 单段文档整体按行内输出(外层 span);多段时块级模板独占一段不包 <p>
+        $block = markupRender("前文\n\n{{ai|草稿|未经校对}}", Format::Html);
+        expect($block)->toContain('<p>前文</p><span class="markup-ai markup-ai-block"')
+            ->toContain('<span class="markup-ai-title"><svg')
+            ->toContain('草稿')
+            ->toContain('<span class="markup-ai-message"><span>未经校对</span></span>');
+
+        $tag = markupRender('文字{{ai|草稿|未经校对|style=tag}}', Format::Html);
+        expect($tag)->toContain('文字<span class="markup-ai markup-ai-tag"')
+            ->toContain('AI<span class="markup-ai-popup" role="tooltip">');
+
+        expect(markupRender('x{{ai|草稿|未经校对}}', Format::Text))->toBe('x[草稿] 未经校对');
+        expect(markupRender('x{{ai|草稿}}', Format::Prompt))->toBe('x');
     });
     });
 
 
     it('renders video and strips unsafe urls', function () {
     it('renders video and strips unsafe urls', function () {

+ 11 - 1
dashboard-v6/src/components/markup/MarkupTemplate.tsx

@@ -2,6 +2,7 @@ import { Tag, Typography } from "antd";
 import type { ReactNode } from "react";
 import type { ReactNode } from "react";
 
 
 import Mermaid from "../general/Mermaid";
 import Mermaid from "../general/Mermaid";
+import { AiCtl } from "../template/Ai";
 import { ArticleCtl } from "../template/Article";
 import { ArticleCtl } from "../template/Article";
 import { GrammarTermLookupCtl } from "../template/GrammarTermLookup";
 import { GrammarTermLookupCtl } from "../template/GrammarTermLookup";
 import { NissayaCtl } from "../template/Nissaya";
 import { NissayaCtl } from "../template/Nissaya";
@@ -74,6 +75,15 @@ const TEMPLATES: Record<string, TemplateRenderer> = {
       {children}
       {children}
     </nav>
     </nav>
   ),
   ),
+  // AI 生成内容提示:block 黄底引用块 / tag 行内小标签;children 是说明文字
+  ai: (p, children) => (
+    <AiCtl
+      title={p.title as string | undefined}
+      style={p.style === "tag" ? "tag" : "block"}
+    >
+      {children}
+    </AiCtl>
+  ),
   // 用户自定义模板:正文已由后端渲染成 children
   // 用户自定义模板:正文已由后端渲染成 children
   tpl: (_, children) => <>{children}</>,
   tpl: (_, children) => <>{children}</>,
 };
 };
@@ -85,7 +95,7 @@ interface IWidget {
 }
 }
 
 
 /**
 /**
- * 一个模板节点。没有对应组件的(exercise、dict-pref、ai 等 v6 还没有界面的,或后端不认识的)
+ * 一个模板节点。没有对应组件的(exercise、dict-pref 等 v6 还没有界面的,或后端不认识的)
  * 显示后端给的源码 / 子节点,不吞内容。
  * 显示后端给的源码 / 子节点,不吞内容。
  */
  */
 const MarkupTemplate = ({ node, children }: IWidget) => {
 const MarkupTemplate = ({ node, children }: IWidget) => {

+ 62 - 0
dashboard-v6/src/components/template/Ai.tsx

@@ -0,0 +1,62 @@
+import { Alert, Popover, Tag } from "antd";
+import { WarningFilled } from "@ant-design/icons";
+import type { ReactNode } from "react";
+
+interface IAiCtl {
+  /** 标题;后端已按内容语言给了默认值「AI 生成内容」 */
+  title?: string;
+  /** block:黄底引用块;tag:行内只显示图标与「AI」,鼠标移入显示标题与说明 */
+  style?: "block" | "tag";
+  /** 说明文字(后端 message 参数,已渲染) */
+  children?: ReactNode;
+}
+
+const hasContent = (children: ReactNode) =>
+  Array.isArray(children) ? children.length > 0 : children != null;
+
+/**
+ * AI 生成内容提示:`{{ai}}`、`{{ai|标题|说明|style=tag}}`(后端 AiTemplate)。
+ */
+export const AiCtl = ({ title, style = "block", children }: IAiCtl) => {
+  const message = hasContent(children) ? children : undefined;
+
+  if (style === "tag") {
+    return (
+      <Popover
+        title={
+          <span>
+            <WarningFilled style={{ color: "#faad14", marginRight: 6 }} />
+            {title}
+          </span>
+        }
+        content={
+          message ? <div style={{ maxWidth: 320 }}>{message}</div> : undefined
+        }
+      >
+        <Tag
+          color="warning"
+          icon={<WarningFilled />}
+          style={{ cursor: "help", marginInline: 2 }}
+        >
+          AI
+        </Tag>
+      </Popover>
+    );
+  }
+
+  // 图标放进标题而不用 Alert 的 showIcon:antd 在有 description 时会把图标放大到标题字号,
+  // 有无说明文字图标大小不一
+  return (
+    <Alert
+      type="warning"
+      title={
+        <span>
+          <WarningFilled style={{ color: "#faad14", marginRight: 6 }} />
+          {title}
+        </span>
+      }
+      description={message}
+      style={{ margin: "12px 0" }}
+    />
+  );
+};