Adds attributions to blockquotes in CKEditor 5
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

84 lines
2.6 KiB

(function (Drupal, CKEditor5) {
const pluginNamespace = 'blockquoteAttribution';
const toolbarItem = 'blockquote_attribution';
const icon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M4.6 5.1h4.8v4.8H6.9c.1 1.8.9 3.1 2.5 4.1l-.9 1.3c-2.7-1.5-4-3.7-3.9-6.7V5.1zm7 0h4.8v4.8h-2.5c.1 1.8.9 3.1 2.5 4.1l-.9 1.3c-2.7-1.5-4-3.7-3.9-6.7V5.1z"/></svg>';
function escapeHtml(value) {
return String(value || '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function getSelectedHtml(editor) {
const selection = editor.model.document.selection;
if (selection.isCollapsed) {
return '<p>' + Drupal.t('Quote text') + '</p>';
}
try {
const selectedContent = editor.model.getSelectedContent(selection);
const html = editor.data.stringify(selectedContent);
return html && html.trim() ? html : '<p>' + Drupal.t('Quote text') + '</p>';
}
catch (e) {
return '<p>' + Drupal.t('Quote text') + '</p>';
}
}
function insertHtml(editor, html) {
const viewFragment = editor.data.processor.toView(html);
const modelFragment = editor.data.toModel(viewFragment);
editor.model.change(() => {
editor.model.insertContent(modelFragment);
});
editor.editing.view.focus();
}
class BlockquoteAttribution extends CKEditor5.core.Plugin {
static get pluginName() {
return 'BlockquoteAttribution';
}
init() {
const editor = this.editor;
editor.ui.componentFactory.add(toolbarItem, (locale) => {
const button = new CKEditor5.ui.ButtonView(locale);
button.set({
label: Drupal.t('Blockquote with Attribution'),
icon,
tooltip: true,
});
button.on('execute', () => {
const source = window.prompt(Drupal.t('Source attribution:'), '');
if (source === null) {
return;
}
const selectedHtml = getSelectedHtml(editor);
const attribution = escapeHtml(source.trim());
const figcaption = attribution ? '<figcaption>' + attribution + '</figcaption>' : '';
const citeAttribute = attribution ? ' cite="' + attribution + '"' : '';
const html = '<figure class="quote"><blockquote' + citeAttribute + '>' + selectedHtml + '</blockquote>' + figcaption + '</figure>';
insertHtml(editor, html);
});
return button;
});
}
}
CKEditor5[pluginNamespace] = CKEditor5[pluginNamespace] || {};
CKEditor5[pluginNamespace].BlockquoteAttribution = BlockquoteAttribution;
})(Drupal, CKEditor5);