TinyMCE 用户查找 API 允许您检索和缓存用户详细信息(如姓名和头像),并在编辑器中识别当前用户。
这在构建依赖用户上下文的特性时非常有用,例如评论、协作编辑或显示特定于用户的信息。该 API 提供内置缓存以高效管理用户数据,并在未提供数据时提供回退用户数据。
属性和方法
用户查找 API 有两个用途:识别当前用户以及获取其他用户的详细信息。可以通过 user_id 和 fetch_users 选项分别配置以满足您的应用程序需求。
用户查找 API 通过 editor.userLookup 对象提供属性和方法,该对象在编辑器初始化后可用。
| API | 类型 | 返回类型 |
|---|---|---|
| 属性 |
|
| 方法 |
|
editor.userLookup.userId
返回当前用户的 ID,该 ID 通过 user_id 配置选项设置。这是一个字符串,用于在编辑器上下文中唯一标识用户,例如用户名或电子邮件地址。如果未设置 user_id 选项,则默认为 'Anonymous'。
editor.userLookup.fetchUsers
获取并缓存指定用户 ID 的用户信息。此方法接受一个用户 ID 数组,并返回一个对象,其中每个键是用户 ID,每个值是一个解析为 UserObject 的 Promise。如果找不到用户 ID,Promise 将拒绝并返回错误消息。
User 对象
用户是一个包含以下字段的 Object:
| 字段 | 类型 | 必需? | 描述 |
|---|---|---|---|
|
| 必需 | 用户的唯一字符串 ID。 |
|
| 可选 | 用户的显示名称。如果未提供,默认为 |
|
| 可选 | 用户头像图片的 URL 或 Data URI。如果未提供,将使用基于用户首字母自动生成的 SVG。 |
|
| 可选 | 用户的附加元数据。这可以包括任何与您应用程序相关的自定义字段,例如角色或权限。 |
{
id: 'user-1', // Required: User identifier
name: 'Jane Doe', // Optional: Display name (defaults to id)
avatar: 'https://...', // Optional: Avatar URL or data URI
custom: { // Optional: Additional metadata
role: 'admin',
department: 'engineering'
}
}选项
以下配置选项会影响用户查找 API 的行为。
user_id
此选项设置编辑器中当前用户的唯一标识符。它在 UserLookup API 中使用。
类型: String
默认值: 'Anonymous'
user_id 选项tinymce.init({
selector: 'textarea', // Change this value according to your HTML
user_id: 'james-wilson' // replace this with a unique string to identify the user
});fetch_users
一个必需的回调函数,用于获取用户数据。此函数接收一个用户 ID 数组,并应返回一个解析为用户对象数组的 Promise。UserLookup API 会使用此回调。如果返回的数组不包含所有请求的用户 ID,缺失用户的 Promise 将被拒绝并抛出 "User {id} not found" 错误。
类型: Function
参数:- ids (Array<string>):要获取的用户 ID 数组。
返回:- Promise<Array<Object>>:解析为用户对象数组的 Promise。
fetch_users 选项const API_URL = 'https://demouserdirectory.tiny.cloud/v1/users';
tinymce.init({
selector: 'textarea',
user_id: 'james-wilson',
fetch_users: (userIds) => Promise.all(userIds
.map((userId) =>
fetch(`${API_URL}/${userId}`)
.then((response) => response.json())
.catch(() => ({ id: userId })))),
});示例:返回带验证的用户数组const API_URL = 'https://demouserdirectory.tiny.cloud/v1/users';
tinymce.init({
selector: 'textarea',
user_id: 'james-wilson',
fetch_users: async (userIds) => {
const users = await Promise.all(userIds
.map((userId) =>
fetch(`${API_URL}/${userId}`)
.then((response) => response.json())
.catch(() => ({ id: userId }))));
return userIds.map(
(userId) =>
users.find((user) => user.id === userId)
|| ({ id: userId }) // Still returns a valid user even if it wasn't returned from the server
);
},
});用法示例
基本设置
对于基本设置,配置 user_id 选项即可识别当前用户。可以省略 fetch_users 选项,TinyMCE 将提供回退用户数据。
tinymce.init({
selector: '#editor',
user_id: 'alextaylor'
});带有 fetch_users 的完整设置
此示例演示如何在浏览器中模拟用户查找。在生产环境中,fetch_users 函数通常会向您的后端 API 发送网络请求。
const userDb = {
'janedoe': {
id: 'janedoe',
name: 'Jane Doe',
avatar: 'https://example.com/avatar/jane.png'
},
'johnsmith': {
id: 'johnsmith',
name: 'John Smith'
},
'alextaylor': {
id: 'alextaylor',
name: 'Alex Taylor',
avatar: 'https://example.com/avatar/alex.png'
}
};
tinymce.init({
selector: '#editor',
user_id: 'alextaylor',
fetch_users: (userIds) => {
return Promise.all(
userIds.map(
(userId) => new Promise(
(resolve) => resolve(userDb[userId] || { id: userId }) // Return user data or a fallback object if not found
)
)
)
},
});建议在 fetch_users 函数中处理(或捕获)Promise 拒绝,并提供回退数据。这将确保您的应用程序能够优雅地处理未找到用户数据或网络请求失败的情况。基本用法
一旦编辑器初始化完成,您就可以访问当前用户 ID 并获取用户信息:
editor.on('init', () => {
// Get the current user ID
const currentUserId = editor.userLookup.userId;
console.log('Current user:', currentUserId);
// Fetch user information
const users = editor.userLookup.fetchUsers([ currentUserId ]);
users[currentUserId].then((user) => {
console.log('Current user name:', user.name);
});
// Handle multiple users
Promise.all(Object.values(users)).then((allUsers) => {
allUsers.forEach((user) => {
console.log(`Fetched: ${user.name} (${user.id})`);
});
});
});带有 UI 的高级用法示例
此示例展示了如何创建一个工具栏按钮来显示当前用户的信息:
tinymce.init({
selector: '#editor',
user_id: 'alextaylor',
setup: (editor) => {
editor.ui.registry.addButton('show-user', {
text: 'Show User',
onAction: () => {
const currentUser = editor.userLookup.userId;
const users = editor.userLookup.fetchUsers([ currentUser ]);
users[currentUser].then((user) => {
editor.notificationManager.open({
text: `Logged in as: ${user.name}`,
type: 'info'
});
});
}
});
},
toolbar: 'show-user'
});回退行为
如果未配置 fetch_users 函数,TinyMCE 将返回带有自动生成数据的回退用户:
name默认为用户 IDavatar是使用名称首字母自动生成的 SVG
这对于简单的设置或原型设计非常有用:
tinymce.init({
selector: '#editor',
user_id: 'alextaylor'
});editor.on('init', () => { const users = editor.userLookup.fetchUsers(['alextaylor']); users['alextaylor'].then((user) => { console.log('Generated fallback user:', user); });});