I am using Drupal 10, CKEditor5, and a text format that has a good number of options in the toolbar including the source editing plugin. I have a custom module that defines a custom permission that I would like to use to show/hide (not disable completely) the source editing button.
What I've tried so far:
my_module.permissions.yml
'show source button':
title: 'Display Source button in CKEditor'
description: 'Display the Source button in CKEditor.'
my_module.module
// first try
function my_module_ckeditor5_plugin_info_alter(array &$plugin_definitions) : void {
$currentUser = \Drupal::currentUser();
if (!$currentUser->hasPermission('show source button')) {
if (array_key_exists('ckeditor5_sourceEditing', $plugin_definitions)) {
unset($plugin_definitions['ckeditor5_sourceEditing']);
}
}
}
// second try
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$currentUser = \Drupal::currentUser();
if (!$currentUser->hasPermission('show source button')) {
$form['#attached']['library'][] = 'ckeditor_source_button/ckeditor_source_button';
}
}
my_module.js
((Drupal) => {
Drupal.behaviors.ckeditorSourceButtonBehavior = {
attach: (context, settings) => {
context.querySelectorAll('.ck-source-editing-button').forEach((element) => {
element.classList.add('visually-hidden');
});
}
}
})(Drupal);
Problems I've encountered with my methods:
- When using the hook_ckeditor5_plugin_info_alter, one problem is that unsetting the sourceEditing plugin completely removes the functionality and causes issues with html tags
- When using the hook_ckeditor5_plugin_info_alter, the second problem is that the current user is being cached and users that should be able to see the source button are not able to.
- When using hook_form_alter, I'm still having the cache issue happening as I said above but also that the query for '.ck-source-editing-button' is null every time and so is a query for '.ck-editor'.
I've tried adding cache contexts (ex. $form['#cache']['contexts'][] = 'session';) of session, user, or user.permissions to the my_module_form_alter but none of them seem to make a difference. Just for clarity, I've added these individually, never tried a combo of any of them