Type Alias: SimpleContextMenuItem
SimpleContextMenuItem =
BaseContextMenuItem&object
Стандартный элемент первого уровня контекстного меню.
Представляет собой простой пункт меню без подменю, который может быть добавлен непосредственно в контекстное меню редактора.
Наследует все свойства от BaseContextMenuItem и добавляет обязательный обработчик SimpleContextMenuItem.onClick.
Type declaration
onClick
readonlyonClick:Callback
Обработчик события (callback), вызываемый при клике пользователя на пункт меню.
Remarks
Как создать callback:
const callback = editorApi.createCallback(() => {
// Ваша логика здесь
});
Характеристики callback:
- Создаётся через
editorApi.createCallback() - Может быть синхронным или асинхронным (Promise)
- Вызывается в контексте редактора
- Имеет доступ к
editorApiчерез замыкание - Может выполнять любые операции с документом
Типичные операции в onClick:
- Получение выделенного текста:
editorApi.document.selection.getSelectionAsText() - Вставка содержимого:
editorApi.document.insertContent() - Операции с буфером обмена:
editorApi.document.clipboard.copy() - Показ уведомлений:
editorApi.ui.toasts.showToast() - Масштабирование:
editorApi.document.zoom.setZoomLevel()
Обработка ошибок:
- Используйте try-catch для асинхронных операций
- Показывайте ошибки пользователю через
editorApi.ui.toasts.showToast({ type: 'error' }) - Логируйте ошибки в console для отладки
Example
Синхронный callback
const menuItem: SimpleContextMenuItem = {
id: 'plugin:action',
title: 'Действие',
onClick: editorApi.createCallback(() => {
console.log('Пункт меню нажат');
editorApi.ui.toasts.showToast({ id, content: 'Действие выполнено' });
})
};
Асинхронный callback
const menuItem: SimpleContextMenuItem = {
id: 'plugin:async-action',
title: 'Асинхронное действие',
onClick: editorApi.createCallback(async () => {
const text = await editorApi.document.selection.getSelectionAsText();
// Асинхронная операция
await new Promise(resolve => setTimeout(resolve, 1000));
editorApi.ui.toasts.showToast({ id, content: 'Готово' });
})
};
Callback с обработкой ошибок
const menuItem: SimpleContextMenuItem = {
id: 'plugin:safe-action',
title: 'Безопасное действие',
onClick: editorApi.createCallback(async () => {
try {
const text = await editorApi.document.selection.getSelectionAsText();
if (!text) {
editorApi.ui.toasts.showToast({ id, content: 'Пожалуйста, выделите текст' });
return;
}
// Обработка текста
const processed = text.trim().toUpperCase();
await editorApi.document.insertContent(processed);
editorApi.ui.toasts.showToast({ id, content: 'Текст обработан' });
} catch (error) {
console.error('Ошибка:', error);
editorApi.ui.toasts.showToast({ id, type"error', content: 'Произошла ошибка при выполнении' });
}
})
};
Callback с доступом к контексту
const menuItem: SimpleContextMenuItem = {
id: 'plugin:context-aware',
title: 'Действие в зависимости от контекста',
onClick: editorApi.createCallback(async () => {
const docType = editorApi.document.type;
if (docType === 'text') {
editorApi.ui.toasts.showToast({ id, content: 'Это текстовый документ' });
} else if (docType === 'spreadsheet') {
editorApi.ui.toasts.showToast({ id, content: 'Это таблица' });
} else if (docType === 'presentation') {
editorApi.ui.toasts.showToast({ id, content: 'Это презентация' });
}
})
};
See
- Callback — полное описание интерфейса Callback
- EditorApi.createCallback — как создать callback
- ContextMenuApi — как использовать в контекстном меню
Remarks
Иерархия типов:
SimpleContextMenuItem (текущий тип)
└── extends BaseContextMenuItem
├── extends BaseControl
│ ├── id: string (обязательно)
│ ├── title: string (обязательно)
│ ├── onClick: Callback (обязательно)
│ └── ...
└── extends MayHaveIcon
└── icon?: string (опционально)
Ключевые отличия от других типов меню:
SimpleContextMenuItem— простой пункт без подменю (первый уровень)ContextMenuItemWithDropdown— пункт с подменю (каскадное меню)
Когда использовать SimpleContextMenuItem:
- Для прямых действий (копировать, вставить, удалить)
- Для операций, которые не требуют подвыбора
- Для простых надстроек с 1-2 пункт в меню
- Когда действие выполняется сразу без дополнительных опций
Обработчик onClick:
- Создаётся через
editorApi.createCallback() - Вызывается только при клике пользователя на пункт
- Должен содержать логику действия
- Может быть асинхронным (Promise)
Example
Простой пункт меню без условий
const menuItem: SimpleContextMenuItem = {
id: 'plugin:insert-date',
title: 'Вставить дату',
icon: 'Calendar',
onClick: editorApi.createCallback(async () => {
const today = new Date().toLocaleDateString('ru-RU');
await editorApi.document.insertContent(today);
editorApi.ui.toasts.showToast({ id, content: 'Дата вставлена' });
})
};
editorApi.ui.contextMenu.addItems([menuItem]);
Пункт с условной видимостью
const menuItem: SimpleContextMenuItem = {
id: 'plugin:uppercase',
title: 'ВЕРХНИЙ РЕГИСТР',
icon: 'TextUppercase',
shownInScopes: [
{ mode: 'selection' } // Видимо только при выделении
],
onClick: editorApi.createCallback(async () => {
const text = await editorApi.document.selection.getSelectionAsText();
if (text) {
await editorApi.document.insertContent(text.toUpperCase());
}
})
};
Несколько простых пунктов меню
const textTransformItems: SimpleContextMenuItem[] = [
{
id: 'plugin:uppercase',
title: 'ВЕРХНИЙ РЕГИСТР',
shownInScopes: [{ scope: 'selection' }],
onClick: editorApi.createCallback(async () => {
const text = await editorApi.document.selection.getSelectionAsText();
if (text) {
await editorApi.document.insertContent(text.toUpperCase());
}
})
},
{
id: 'plugin:lowercase',
title: 'нижний регистр',
shownInScopes: [{ scope: 'selection' }],
onClick: editorApi.createCallback(async () => {
const text = await editorApi.document.selection.getSelectionAsText();
if (text) {
await editorApi.document.insertContent(text.toLowerCase());
}
})
},
{
id: 'plugin:capitalize',
title: 'Первый Символ Заглавный',
shownInScopes: [{ scope: 'selection' }],
onClick: editorApi.createCallback(async () => {
const text = await editorApi.document.selection.getSelectionAsText();
if (text) {
const capitalized = text.charAt(0).toUpperCase() + text.slice(1);
await editorApi.document.insertContent(capitalized);
}
})
}
];
editorApi.ui.contextMenu.addItems(textTransformItems);
Пункт с асинхронной операцией
const asyncMenuItem: SimpleContextMenuItem = {
id: 'plugin:check-spelling',
title: 'Проверить орфографию',
icon: 'SpellCheck',
onClick: editorApi.createCallback(async () => {
try {
editorApi.ui.toasts.showToast({ id, content: 'Проверка орфографии...' });
// Вызываем асинхронную операцию
const result = await checkSpelling(editorApi.document);
if (result.errors.length > 0) {
editorApi.ui.toasts.showToast(
{ id, type: 'error', content: `Найдено ${result.errors.length} ошибок` }
);
} else {
editorApi.ui.toasts.showToast({ id, content: 'Ошибок не найдено' });
}
} catch (error) {
editorApi.ui.toasts.showToast({ id, type: 'error', content: 'Ошибка при проверке' });
}
})
};
See
- BaseContextMenuItem — наследуемые свойства (shownInScopes, disabledInScopes)
- Callback — описание типа callback функции
- ContextMenuApi.addItems — как регистрировать пункты меню
- ContextMenuItemWithDropdown — для пунктов с подменю