Skip to content

Instantly share code, notes, and snippets.

@MatthieuScarset
Last active March 22, 2022 13:41
Show Gist options
  • Save MatthieuScarset/3001844e75a5063b094eb70758b8066a to your computer and use it in GitHub Desktop.
Save MatthieuScarset/3001844e75a5063b094eb70758b8066a to your computer and use it in GitHub Desktop.
/**
* @file
* Tooltip plugin.
*/
(function (Drupal, CKEDITOR) {
CKEDITOR.plugins.add('tooltip', {
icons: 'tooltip',
init: function (editor) {
// Stop now if not allowed to use editor.
if (!editor.config.tooltip.modal_url) {
console.log(
Drupal.t('Tooltip button not visible because editor @editor is not accessible.', {
'@editor': editor.config.drupal.format
})
);
return;
}
editor.addCommand('tooltip', {
exec: function exec(editor) {
const saveCallback = function (values) {
console.log(values);
editor.fire('saveSnapshot');
const selection = editor.getSelection();
const selectedElement = selection.getSelectedElement();
if (selectedElement) {
// @todo Set tooltip attributes on existing selected <span>
console.log('set tooltip attributes', selectedElement);
} else {
// @todo Insert a span with tooltip attributes on selected text
const span = new CKEDITOR.dom.element.create('span');
span.dataset.tooltip = '';
span.dataset.tooltipContent = values.content || 'Tooltip content';
span.dataset.tooltipPlacement = values.placement || 'top';
span.innerHTML = selection.getSelectedText() || 'Tooltip text';
const range = selection.getRanges(true)[0];
range.shrink(CKEDITOR.SHRINK_TEXT);
range.insertNode(span);
}
editor.fire('saveSnapshot');
};
let dialogSettings = {
'dialogClass': 'tooltip-dialog',
'title': Drupal.t('Tooltip'),
'height': '75%',
'width': '75%',
};
let existingValues = {};
// @todo Parse focused element.
// existingValues = parseAttributes(editor, linkElement);
Drupal.ckeditor.openDialog(
editor,
editor.config.tooltip.modal_url,
existingValues,
saveCallback,
dialogSettings
);
}
});
if (editor.ui.addButton) {
editor.ui.addButton('tooltip', {
label: Drupal.t('Insert tooltip'),
command: 'tooltip'
});
}
// On "Ctrl+T" press.
editor.setKeystroke(CKEDITOR.CTRL + 116, 'tooltip');
}
});
})(Drupal, CKEDITOR);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment