CKEditor 4 Mentions 插件全解析:三种数据源与自动补全机制的实战指南

原创2026-10-15 19:01:241,766 阅读
文章标签:前端UI组件

CKEditor 4 Mentions 插件全解析:三种数据源与自动补全机制的实战指南

导读

Mentions 是 CKEditor 4 内置的智能自动补全插件(自 4.10.0 起引入,见 CHANGES.md 中 #1703 的说明),允许用户输入一个标记字符(marker,默认为 @)后获得候选文本提示,广泛应用于 @ 提及用户、# 话题标签等场景。本文基于仓库中该功能的手动测试用例与源码实现,系统讲解 Mentions 插件支持的三种数据源(同步数组、异步 URL、异步回调函数)、全部配置参数及其默认值、与 autocomplete / textmatch 底层插件协作的原理,并给出可直接复制运行的配置示例与测试验证方法。

从一份手动测试用例说起

仓库中的 tests/plugins/mentions/manual/mentions.md 是一份 Bender 手动测试描述,它用三条要点概括了 Mentions 插件的三种数据源触发方式:

  • 输入 @:同步数组数据源(synchronous array feed);
  • 输入 $:异步 URL 字符串数据源(asynchronous URL string feed);
  • 输入 #:异步回调函数数据源(asynchronous callback feed)。

对应的 mentions.html 展示了这三个配置实例如何并存于同一个编辑器中:同一个编辑器可以同时挂载多个 Mentions 实例,每个实例拥有独立的 marker、feed 和 minChars,互不干扰。这正是 Mentions 插件最核心的设计——一个编辑器,多个数据源,多种触发字符。

插件架构:Mentions 如何工作

Mentions 不是从零实现的自动补全引擎,而是建立在三个底层插件之上的"业务层"封装。从 plugins/mentions/plugin.js 可见其依赖声明:

CKEDITOR.plugins.add( 'mentions', {
    requires: 'autocomplete,textmatch,ajax',
    instances: [],
    init: function( editor ) {
        var self = this;
        editor.on( 'instanceReady', function() {
            CKEDITOR.tools.array.forEach( editor.config.mentions || [], function( config ) {
                self.instances.push( new Mentions( editor, config ) );
            } );
        } );
    },
    isSupportedEnvironment: function( editor ) {
        return editor.plugins.autocomplete.isSupportedEnvironment( editor );
    }
} );

各层职责如下:

插件 职责
autocomplete 提供下拉面板的显示、定位、键盘交互(方向键、回车确认)与选中项插入逻辑;环境要求为 IE9+(见 plugins/autocomplete/plugin.js 中 isSupportedEnvironment 的实现:`!CKEDITOR.env.ie
textmatch 在 DOM 文本中定位光标左侧的匹配片段,返回匹配的起止位置
ajax 为 URL 数据源提供 CKEDITOR.ajax.load 请求能力

每次 instanceReady 事件触发时,插件会遍历 editor.config.mentions 数组,为每个配置对象创建一个独立的 Mentions 实例(类 CKEDITOR.plugins.mentions),实例内部再实例化一个 CKEDITOR.plugins.autocomplete 控制器,并把 textTestCallback 与 dataCallback 两个回调注入进去(见 plugins/mentions/plugin.js):

this._autocomplete = new CKEDITOR.plugins.autocomplete( editor, {
    textTestCallback: getTextTestCallback( this.marker, this.minChars, this.pattern ),
    dataCallback: getDataCallback( feed, this ),
    itemTemplate: config.itemTemplate,
    outputTemplate: config.outputTemplate,
    throttle: this.throttle,
    itemsLimit: config.itemsLimit,
    followingSpace: this.followingSpace
} );

也就是说,Mentions 的职责是"定义数据源 + 生成匹配规则",而交互层完全复用 autocomplete 的能力。

触发与匹配原理

默认匹配正则的生成

当用户未显式指定 pattern 时,Mentions 会调用 createPattern( marker, minChars ) 动态生成匹配正则(见 plugins/mentions/plugin.js):

function createPattern( marker, minChars ) {
    // Match also diacritic characters (#2491).
    var pattern = '\\' + marker + '[_a-zA-Z0-9À-ž]';

    if ( minChars ) {
        pattern += '{' + minChars + ',}';
    } else {
        pattern += '*';
    }

    pattern += '$';

    return new RegExp( pattern );
}

默认正则形态为 \@<a href="https://link.gitcode.com/i/1e357634af4954e3d8d930d0ee9f852a" target="_blank">_a-zA-Z0-9À-ž]{minChars,}$,注意字符集 [_a-zA-Z0-9À-ž] 显式包含了下划线以及 À-ž 区间的变音字符,这是为修复 #2491(Mentions 无法匹配波兰语等变音字符的问题)而加入的。仓库中的 [diacritic 手动测试 要求输入 @trąba_ 时能弹出包含 @trąba_bomba 的下拉框,mentions.js 中的 test matching diacritic characters、test matching underscore character 与 test not matching special characters 三条单元测试分别验证了变音字符、下划线可匹配,而 ~!@#$%^&*()-+= 等特殊字符不会误触发下拉框。

文本匹配回调

匹配流程由 getTextTestCallback 完成(见 plugins/mentions/plugin.js):

  1. 若光标选区非折叠(存在选中文本),直接返回 null,不做补全;
  2. 调用 CKEDITOR.plugins.textMatch.match( range, matchCallback ) 在光标左侧文本中查找匹配;
  3. matchCallback 用生成的正则对光标前的文本切片做匹配,若未命中返回 null;
  4. 关键约束:检查匹配片段前一个字符,若存在且不是空白字符(/\s+/),说明查询是一个单词的一部分,直接放弃——这正是测试用例 test feed with a marker as a part of word(输入 a@An)验证的行为。

匹配成功后会返回 { start: match.index, end: offset },交由 autocomplete 显示下拉面板。

三种数据源(feed)详解

feed 是每个 Mentions 配置实例的必选项,支持三种形态(见 plugins/mentions/plugin.js 对 feed 属性的文档说明)。数据获取逻辑统一收敛在 getDataCallback 中(plugins/mentions/plugin.js),它会先剥离开头部分的 marker,再把干净查询传给数据源。

1. 同步数组数据源(array feed)

最简单的方式,直接传入字符串数组:

var definition = { feed: [ 'Anna', 'Thomas', 'John' ], minChars: 0 };

底层处理逻辑(见 plugins/mentions/plugin.js)会先把数组通过 indexArrayFeed 索引化为 { name: 'Anna', id: 1 } 形式(id 自动递增),再用 item.name.indexOf( query ) === 0 做前缀匹配。默认匹配不区分大小写——比较前会把 itemName 和 query 都转成小写。若需区分大小写,设置 caseSensitive: true 即可,此时会跳过小写化直接前缀比较。

单元测试 tests/plugins/mentions/mentions.js 覆盖了数组数据源的匹配与大小写行为:@An 在默认配置下同时命中 Anna 与 Annabelle;开启 caseSensitive 后 @An 仍然命中,但 @an(小写查询)和 anna(小写数据)都无法命中。

2. 异步 URL 字符串数据源(URL feed)

把 feed 写成 URL 字符串,Mentions 会通过 CKEDITOR.ajax.load 发起异步请求。URL 支持 {encodedQuery} 占位符,会被替换为经过 encodeURIComponent 编码的查询词。例如查询 @anna、feed 为 /users?name={encodedQuery} 时,实际请求 /users?name=anna;非标准字符会被编码,测试 test URL gets encoded 验证了查询 F&/oo 会请求 F%26%2Foo(tests/plugins/mentions/mentions.js)。

var definition = { feed: '/users?query={encodedQuery}' };

后端需返回 JSON 格式数组,每项建议结构为 { id: 1, name: 'anna87', firstName: 'Anna', lastName: 'Doe' }(firstName、lastName 为可选的附加字段,可被模板引用)。响应数据会被 JSON.parse 解析后进入下拉列表(plugins/mentions/plugin.js)。

默认开启响应缓存(cache: true):缓存以编码后的完整 URL 为键,存放在 CKEDITOR._.mentions.cache 中,且在所有编辑器实例间全局共享。缓存逻辑:

  • 命中缓存直接返回,不再发请求;
  • 只有响应非 null 时才写入缓存(无效响应不缓存,见 test URL feed invalid responses are not cached)。

单元测试 test URL feed responses are cached 与 test URL feed cache can be disabled 形成对照:同样连续触发三次查询,开启缓存时 CKEDITOR.ajax.load 只被调用 2 次(第二次与第三次查询 An 命中同一缓存键),cache: false 时则调用 3 次(tests/plugins/mentions/mentions.js)。手动测试 cache.md 则是通过页面上方的请求历史日志,肉眼确认重复输入 @anna 不会产生重复请求。

另外,tests/plugins/mentions/mentions.js 中的 test URL has no race condition 验证了异步请求无竞态:较早发出的慢请求不会覆盖较晚发出的快请求结果。

3. 异步回调函数数据源(callback feed)

适合需要完全掌控数据来源的高级场景。feed 传入一个函数,签名固定为 function( opts, callback ):

  • opts:当前查询信息对象,形如 { query: 'anna', marker: '@' };
  • callback:把候选数组回传给 Mentions 实例。
var definition = {
    feed: function( opts, callback ) {
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function() {
            if ( xhr.readyState == 4 ) {
                if ( xhr.status == 200 ) {
                    callback( JSON.parse( this.responseText ) );
                } else {
                    callback( [] );
                }
            }
        }

        xhr.open( 'GET', '/users?name=' + opts.query );
        xhr.send();
    }
};

从源码 plugins/mentions/plugin.js 看,函数被调用时传入 { query, marker },其中 query 同样已去除 marker 前缀。回调函数既可以是异步的(如上面的 XHR),也可以是同步执行的。单元测试用 successFeed / failureFeed 两个辅助函数断言了 opts.query 与 opts.marker 的正确性,并验证了 # 等自定义 marker 会原样传递(tests/plugins/mentions/mentions.js)。

注意:当使用 URL 或回调这类异步数据源时,返回项必须携带唯一的 id 与 name 字段;而数组数据源会自动生成 id。

完整配置参数参考

一个 mentions 配置定义支持以下属性(默认值依据 plugins/mentions/plugin.js 与 configDefinition 文档,plugins/mentions/plugin.js):

配置项 类型 默认值 说明
feed String[] / String / Function 必填 数据源,三种形态见上文
marker String '@' 触发补全的标记字符,可设多字符(如 '##')
minChars Number 2 标记后至少输入几个字符才触发;设 0 时输入 marker 即弹窗
caseSensitive Boolean false 仅对数组数据源生效;URL/回调数据源由服务端自行过滤
pattern RegExp 由 marker+minChars 生成 自定义查询匹配正则,如 /^a+\w*$/
cache Boolean true 是否缓存 URL 数据源响应(全局共享缓存)
itemTemplate String 默认 <li data-id="{id}">{name}</li> 下拉面板中每条候选的渲染模板,可用 {id}、{name} 等字段
outputTemplate String 默认 <span>{name}</span> 选中后插入编辑器内容的模板
throttle Number 200(毫秒) 文本检查节流阈值,降低触发频率
itemsLimit Number 0(不限) 下拉列表最多显示的候选数量
followingSpace Boolean 无默认值 自 4.20.0 起(#2008),接受补全后自动追加一个空格

其中 throttle、itemsLimit、followingSpace、itemTemplate、outputTemplate 会原样透传给底层 autocomplete 实例(测试 test config options are passed to autocomplete 用 spy 验证了这一点,tests/plugins/mentions/mentions.js)。注意 autocomplete 自身的 throttle 默认值是 20ms,而 mentions 层默认提升到 200ms(plugins/autocomplete/plugin.js)。

配置示例:三数据源并存

参照 mentions.html 的演示配置,将三种数据源挂载到同一编辑器:

var data = [
    { id: 1, name: 'john', fullName: 'John Doe' },
    { id: 2, name: 'thomas', fullName: 'Thomas Doe' },
    { id: 3, name: 'anna', fullName: 'Anna Doe' },
    { id: 4, name: 'annabelle', fullName: 'Annabelle Doe' }
];

CKEDITOR.replace( 'editor', {
    height: 240,
    extraPlugins: 'mentions',
    mentions: [
        // @ —— 同步数组数据源,输入即弹窗
        {
            feed: CKEDITOR.tools.array.map( data, function( item ) {
                return item.name;
            } ),
            minChars: 0
        },
        // $ —— 异步 URL 数据源(示例中用 stub 模拟请求)
        {
            feed: '{encodedQuery}',
            marker: '$',
            minChars: 1,
            template: '<li data-id="{id}">{fullName}</li>'
        },
        // # —— 异步回调数据源
        {
            feed: dataCallback,
            marker: '#',
            template: '<li data-id="{id}">{name} ({fullName})</li>'
        }
    ]
} );

function dataCallback( opts, callback ) {
    setTimeout( function() {
        callback(
            data.filter( function( item ) {
                return item.name.indexOf( opts.query ) === 0;
            } )
        );
    }, Math.random() * 500 );
}

几点实操提示:

  • 该示例中 URL 数据源请求的目标就是 {encodedQuery} 本身(查询词),由于浏览器无法直接请求裸查询词,示例在 instanceReady 时用 stub 替换了 CKEDITOR.ajax.load 模拟后端响应——真实项目中应替换为你的后端地址,如 '/users?query={encodedQuery}';
  • 三个实例的 marker 互不相同(@、$、#),输入对应字符即触发各自的补全,互不干扰;
  • template(即 itemTemplate)可引用后端返回项的任意字段,如 {fullName}。

模板定制与输出格式化

itemTemplate:定制下拉项

默认下拉项模板渲染为 <li data-id="{id}">{name}</li>。数组数据源经 indexArrayFeed 索引化后只有 name 和 id 两个字段可用;URL/回调数据源则可引用返回对象的所有属性。手动测试 viewTemplate.md 要求下拉中的名字加粗并带 "item: " 前缀,单元测试 test feed with custom view template 用 <li data-id="{id}">{name} is the best!</li> 验证了自定义效果(tests/plugins/mentions/mentions.js)。

outputTemplate:定制插入内容

选中候选后,Mentions 会把结果插入编辑器。默认输出模板为 <span>{name}</span>,并且 resolveCallbackData 会为每个候选项动态生成一个以 marker 开头的 name(如 @Anna),因此插入的是 @Anna(plugins/mentions/plugin.js)。

通过 outputTemplate 可以完全控制插入的 HTML,例如把提及内容加粗:

mentions: [ {
    feed: [ 'Anna' ],
    outputTemplate: '<strong>{name}</strong>'
} ]

单元测试 test custom output template with default item 与 test custom output template with custom item 验证:插入后编辑器数据分别为 <p><strong>@Anna</strong></p> 和 <p><strong>@Anna Doe</strong></p>(后者引用了回调返回的 surname 字段,tests/plugins/mentions/mentions.js)。对应的手动测试 outputTemplate.md 同样要求选中后插入的名称保持加粗。

如何运行与验证

运行插件示例

打开仓库中的示例页面 plugins/mentions/samples/mentions.html(需通过 HTTP 服务访问,页面加载 ../../../ckeditor.js),输入 @、$、# 即可体验三种数据源的真实效果。

运行手动测试

仓库使用 Bender 测试框架。所有 mentions 手动测试位于 tests/plugins/mentions/manual/,包括:

手动测试 验证点
mentions.md 三种数据源(@ / $ / #)均可打开正确的补全面板
diacritic.md 变音字符匹配(#2491),如 @trąba_ → @trąba_bomba
casesensitive.md 大小写敏感行为:@a 不弹窗、@A 弹窗(#1934)
cache.md URL 响应缓存,重复查询不产生重复请求(#1969)
viewTemplate.md 自定义下拉项模板(#1987)
outputTemplate.md 自定义输出模板,插入内容带格式(#1987)

每个手动测试的 .md 文件头部包含 Bender 元数据(@bender-tags、@bender-ui、@bender-ckeditor-plugins),指明所属版本、功能标签与所需加载的插件集合,配套同名 .html 文件提供可运行的编辑器实例与配置。

自动化单元测试

Tests/plugins/mentions/mentions.js 是 mentions 的完整单元测试套件,覆盖了:三种数据源的匹配与不匹配、自定义 marker($、.、/、## 多字符)、自定义 pattern(/^a+\w*$/ 的命中与失败)、变音字符、大小写敏感、URL 编码、缓存开关与无效响应不缓存、异步竞态、模板定制、配置透传等。测试通过 bender.tools.ignoreUnsupportedEnvironment( 'mentions', editor ) 在 IE8 及以下环境跳过执行(与 autocomplete 的环境要求一致)。

底层原理小结

从源码结构看,Mentions 的完整数据流可归纳为:

  1. 用户在编辑器中输入文本,textwatcher(autocomplete 内部依赖)以 throttle 节流频率监听输入;
  2. getTextTestCallback 借助 textMatch 在光标左侧按正则定位 marker + 查询片段,并排除"单词中间"的误触发;
  3. 命中后 getDataCallback 根据 feed 形态分发:数组就地前缀过滤、URL 发 CKEDITOR.ajax.load 请求(可全局缓存)、函数回调由开发者自行取数;
  4. autocomplete 的 model 按 itemsLimit 截断数据,view 用 itemTemplate 渲染下拉面板;
  5. 用户回车确认后,用 outputTemplate 生成插入内容(默认含 marker 前缀),若开启 followingSpace 则自动补一个空格;
  6. 选中内容随编辑器数据处理流程(如 ACF)保存,正如 outputTemplate.md 中测试编辑器配置 allowedContent: 'strong' 以允许加粗输出所示。

这套"业务层封装 + 底层复用"的设计,使开发者可以极低成本为编辑器接入任意形态的用户提及功能,同时保持数据源的完全可控性。

参考文档与源码入口

登录后查看全文
ckeditor4