Is there an option to paste always from the clipboard as plain text?
I tried it that way, but that does not work:
$(document).ready(function () {
ClassicEditor.create(document.querySelector('#text'), {
toolbar: [
'heading',
'bold',
'italic',
'link',
'bulletedList',
'numberedList',
'blockQuote',
'undo',
'redo'
]
}).then(function (editor) {
this.listenTo(editor.editing.view, 'clipboardInput', function (event, data) {
// No log.
console.log('hello');
});
}).catch(function (error) {
});
});
https://docs.ckeditor.com/ckeditor5/latest/api/module_clipboard_clipboard-Clipboard.html
https://docs.ckeditor.com/ckeditor5/latest/api/clipboard.html
https://docs.ckeditor.com/ckeditor5/latest/api/module_engine_view_document-Document.html#event-event:paste
The clipboardInput event is fired on the Document, not the View. So the first thing will be to listen on the right object.
The second thing is ensuring that the content inserted into the editor is a plain text. This can be done in two ways:
HTML taken from the clipboard can be "plain-textified". But this is hard.
We can take plain-text from the clipboard and insert that into the editor. However, the editor expects HTML to be pasted, so you need to "HTMLize" this plain-text. CKEditor 5 offers a function for that – plainTextToHtml().
To override the editor's default behaviour we'll need to override this callback: https://github.com/ckeditor/ckeditor5-clipboard/blob/a7819b9e6e2bfd64cc27f65d8e56b0d26423d156/src/clipboard.js#L137-L158
To do that, we'll listen to the same event (with a higher priority), do all the same things, but ignore text/html flavour of the clipboard data. Finally, we 'll call evt.stop() to block the default listener from being executed and ruining our job:
import plainTextToHtml from '#ckeditor/ckeditor5-clipboard/src/utils/plaintexttohtml';
// ...
const clipboardPlugin = editor.plugins.get( 'Clipboard' );
const editingView = editor.editing.view;
editingView.document.on( 'clipboardInput', ( evt, data ) => {
if ( editor.isReadOnly ) {
return;
}
const dataTransfer = data.dataTransfer;
let content = plainTextToHtml( dataTransfer.getData( 'text/plain' ) );
content = clipboardPlugin._htmlDataProcessor.toView( content );
clipboardPlugin.fire( 'inputTransformation', { content, dataTransfer } );
editingView.scrollToTheSelection();
evt.stop();
} );
EDIT:
Starting from CKEditor 27.0.0 the code has changed (you can read more about it here https://ckeditor.com/docs/ckeditor5/latest/builds/guides/migration/migration-to-27.html#clipboard-input-pipeline-integration)
import plainTextToHtml from '#ckeditor/ckeditor5-clipboard/src/utils/plaintexttohtml';
//...
const clipboardPlugin = editor.plugins.get( 'ClipboardPipeline' );
const editingView = editor.editing.view;
editingView.document.on( 'clipboardInput', ( evt, data ) => {
if ( editor.isReadOnly ) {
return;
}
const dataTransfer = data.dataTransfer;
let content = plainTextToHtml( dataTransfer.getData( 'text/plain' ) );
data.content = editor.data.htmlProcessor.toView( content );
editingView.scrollToTheSelection();
}, { priority: 'high' } );
Without any imports:
.then(editor => {
editor.editing.view.document.on('clipboardInput', (evt, data) => {
data.content = editor.data.htmlProcessor.toView(data.dataTransfer.getData('text/plain'));
});
})
You have complete methods in documentation of ckeditor clipboard events
Related
I'm accessing an iframe thru fancybox 3 with multiple ckeditor. It's working well but I want to track if a user has inputted anything on the textboxes so that I can change the button of the fancybox and give them an alert once they hit close. This is my JS code on the iframe page:
window.editors = {};
document.querySelectorAll( '.editor' ).forEach( ( node, index ) => {
ClassicEditor
.create( node, {
removePlugins: ['Heading', 'BlockQuote', 'CKFinderUploadAdapter', 'CKFinder', 'EasyImage', 'Image', 'ImageCaption', 'ImageStyle', 'ImageToolbar', 'ImageUpload', 'MediaEmbed'],
} )
.then( newEditor => {
window.editors[ index ] = newEditor;
} );
editors[ index ].document.on( 'change', () => {
console.log( 'Alert: The document has changed!, are you sure you want to close without saving?' );
} );
} );
But it's giving me an error:
ifram.php:1070 Uncaught TypeError: Cannot read properties of undefined (reading 'document')
at ifram.php:1070
at NodeList.forEach (<anonymous>)
at ifram.php:1060
I also tried taking this out off document.querySelectorAll() function
editors.document.on( 'change', () => {
console.log( 'Alert: The document has changed!, are you sure you want to close without saving?' );
} );
But it gave me another error: Uncaught TypeError: Cannot read properties of undefined (reading 'on')
You could use newEditor.model.document.on('change:data') document
<script src="https://cdn.ckeditor.com/ckeditor5/30.0.0/classic/ckeditor.js"></script>
<textarea class="editor"></textarea>
<script>
window.editors = {};
document.querySelectorAll( '.editor' ).forEach( ( node, index ) => {
ClassicEditor
.create( node, {
removePlugins: ['Heading', 'BlockQuote', 'CKFinderUploadAdapter', 'CKFinder', 'EasyImage', 'Image', 'ImageCaption', 'ImageStyle', 'ImageToolbar', 'ImageUpload', 'MediaEmbed'],
} )
.then( newEditor => {
window.editors[ index ] = newEditor;
newEditor.model.document.on('change:data', ()=> {
console.log( 'Alert: The document has changed!, are you sure you want to close without saving?' );
});
} );
});
</script>
I'm building a Grapesjs plugin and have added a 'jscript' trait to a button component, which appears as a codemirror textarea. The idea is for users to be able to edit some javascript code associated with a button. I can't seem to intercept the codemirror area's change event, at least, not the proper codemirror specific version.
Happily, when I edit the codemirror area and change focus, a regular 'change' event triggers the Grapejs onEvent handler within my plugin's editor.TraitManager.addType('jcodemirror-editor', {} - good. I can then store the contents of the codemirror area into the trait.
onEvent({ elInput, component, event }) {
let code_to_run = elInput.querySelector(".CodeMirror").CodeMirror.getValue()
component.getTrait('jscript').set('value', code_to_run);
},
However if we paste or backspace or delete etc. in the codemirror area then the regular 'change' event is never issued!
So I'm trying to intercept the deeper codemirror specific 'change' event which is usually intercepted via cm.on("change", function (cm, changeObj) {} and which is triggered more reliably (unfortunately also on each keystroke). How do I wire this codemirror specific event to trigger the usual onEvent({ elInput, component, event }) {} code?
I have a workaround in place in my https://jsfiddle.net/tcab/1rh7mn5b/ but would like to know the proper way to do this.
My Plugin:
function customScriptPlugin(editor) {
const codemirrorEnabled = true // otherwise trait editor is just a plain textarea
const script = function (props) {
this.onclick = function () {
eval(props.jscript)
}
};
editor.DomComponents.addType("customScript", {
isComponent: el => el.tagName == 'BUTTON' && el.hasAttribute && el.hasAttribute("data-scriptable"),
model: {
defaults: {
traits: [
{
// type: 'text',
type: 'jcodemirror-editor', // defined below
name: 'jscript',
changeProp: true,
}
],
script,
jscript: `let res = 1 + 3; console.log('result is', res);`,
'script-props': ['jscript'],
},
},
});
editor.TraitManager.addType('jcodemirror-editor', {
createInput({ trait }) {
const el = document.createElement('div');
el.innerHTML = `
<form>
<textarea id="myjscript" name="myjscript" rows="14">
</textarea>
</form>
</div>
`
if (codemirrorEnabled) {
const textareaEl = el.querySelector('textarea');
var myCodeMirror = CodeMirror.fromTextArea(textareaEl, {
mode: "javascript",
lineWrapping: true,
});
// This is the 'more accurate' codemirror 'change' event
// which is triggered key by key. We need it cos if we paste
// or backspace or delete etc. in codemirror then the
// regular 'change' event is never issued! But how do we get
// this event to trigger the proper, usual 'onEvent' below?
// Currently cheating and doing the onEvent work here with
// this special handler.
myCodeMirror.on("change", function (cm, changeObj) { // HACK
const component = editor.getSelected()
const code_to_run = myCodeMirror.getValue()
component.getTrait('jscript').set('value', code_to_run);
console.log('onEvent hack - (myCodeMirror change event) updating jscript trait to be:', code_to_run)
})
}
return el;
},
// UI textarea & codemirror 'change' events trigger this function,
// so that we can update the component 'jscript' trait property.
onEvent({ elInput, component, event }) {
let code_to_run
if (codemirrorEnabled)
code_to_run = elInput.querySelector(".CodeMirror").CodeMirror.getValue()
else
code_to_run = elInput.querySelector('textarea').value
console.log('onEvent - updating jscript trait to be:', code_to_run)
component.getTrait('jscript').set('value', code_to_run);
}, // onEvent
// Updates the trait area UI based on what is in the component.
onUpdate({ elInput, component }) {
console.log('onUpdate - component trait jscript -> UI', component.get('jscript'))
if (codemirrorEnabled) {
const cm = elInput.querySelector(".CodeMirror").CodeMirror
cm.setValue(component.get('jscript'))
// codemirror content doesn't appear till you click on it - fix with this trick
setTimeout(function () {
cm.refresh();
}, 1);
}
else {
const textareaEl = elInput.querySelector('textarea');
textareaEl.value = component.get('jscript')
// actually is this even needed as things still update automatically without it?
// textareaEl.dispatchEvent(new CustomEvent('change'));
}
}, // onUpdate
}) // addType
editor.BlockManager.add(
'btnRegular',
{
category: 'Basic',
label: 'Regular Button',
attributes: { class: "fa fa-square-o" },
content: '<button type="button">Click Me</button>',
});
editor.BlockManager.add(
'btnScriptable',
{
category: 'Scriptable',
label: 'Scriptable Button',
attributes: { class: "fa fa-rocket" },
content: '<button type="button" data-scriptable="true">Run Script</button>',
});
}
const editor = grapesjs.init({
container: '#gjs',
fromElement: 1,
height: '100%',
storageManager: { type: 0 },
plugins: ['gjs-blocks-basic', 'customScriptPlugin']
});
According to official Grapesjs documentation on traits integrating external ui components you can trigger the onEvent event manually by calling this.onChange(ev).
So within createInput I continued to intercept the more reliable myCodeMirror.on("change", ... event and within that handler triggered the onEvent manually viz:
editor.TraitManager.addType('jcodemirror-editor', {
createInput({ trait }) {
const self = this // SOLUTION part 1
const el = document.createElement('div');
el.innerHTML = `
<form>
<textarea id="myjscript" name="myjscript" rows="14">
</textarea>
</form>
</div>
`
if (codemirrorEnabled) {
const textareaEl = el.querySelector('textarea');
var myCodeMirror = CodeMirror.fromTextArea(textareaEl, {
mode: "javascript",
lineWrapping: true,
});
myCodeMirror.on("change", function (cm, changeObj) {
self.onChange(changeObj) // SOLUTION part 2
})
}
return el;
},
I feel like what I want to accomplish is simple: create a custom WordPress Gutenberg Block that auto-populates with the author name and image and is not editable. Then render this block on the frontend post.
I've gone at this from a lot of different angles, and I think what I need is a Dynamic Block
https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/
First issue is the wp.data.select("core/editor").getCurrentPostId() doesn't load the post ID. But then I'll be honest, I don't know if the return would even have the author info I want anyway. Any guidance is most appreciated.
const post_id = wp.data.select("core/editor").getCurrentPostId();
var el = wp.element.createElement;
wp.blocks.registerBlockType('my-plugin/author-block', {
title: 'Author Footer',
icon: 'admin-users',
category: 'my-blocks',
attributes: {
// Nothing stored
},
edit: wp.data.withSelect( function(select){ // Get server stuff to pass to our block
return {
posts: select('core').getEntityRecords('postType', 'post', {per_page: 1, post_id})
};
}) (function(props) { // How our block renders in the editor
if ( ! props.posts ) {
return 'Loading...';
}
if ( props.posts.length === 0 ) {
return 'No posts';
}
var post = props.posts[0];
// Do stuff with the post like maybe get author name and image???
// ... Return elements to editor viewer
}), // End edit()
save: function(props) { // Save the block for rendering in frontend post
// ... Return saved elements
} // End save()
});
Finally figured something out so thought I'd share.
edit: function(props) { // How our block renders in the editor in edit mode
var postID = wp.data.select("core/editor").getCurrentPostId();
wp.apiFetch( { path: '/wp/v2/posts/'+postID } ).then( post => {
var authorID = post.author
wp.apiFetch( { path: '/wp/v2/users/'+authorID } ).then( author => {
authorName = author.name;
authorImage = author.avatar_urls['96'];
jQuery('.author-bottom').html('<img src="'+authorImage+'"><div><h6>Written by</h6><h6 class="author-name">'+authorName+'</h6></div>');
});
});
return el(
'div',
{
className: 'author-bottom'
},
el(
'img',
{
src: null
}
),
el(
'div',
null,
el(
'h6',
null,
'Written by'
),
el(
'h6',
{
className: 'author-name'
},
'Loading...'
)
)
); // End return
}, // End edit()
As soon as the block loads, it initiates a couple apiFetch calls (one to get the author ID, then another to get the author's name and image).
While that's happening, the author block loads with the temporary text "Loading..."
Once the apiFetch is complete I used jQuery to update the author block.
There is no save function because it's a dynamic block. I registered the block in my plugin php file like so:
function my_author_block_dynamic_render($attributes, $content) {
return '
<div class="author-bottom">
<img src="'.get_avatar_url(get_the_author_email(), ['size' => '200']).'">
<div>
<h6>Written by</h6>
<h6 class="author-name">'.get_the_author().'</h6>
</div>
</div>';
}
function my_dynamic_blocks() {
wp_register_script(
'my-blocks-script',
plugins_url( 'my-block.js', __FILE__ ),
array( 'wp-blocks', 'wp-element' ));
register_block_type( 'my-blocks/author-block', array(
'editor_script' => 'my-blocks-script',
'render_callback' => 'my_author_block_dynamic_render'));
}
add_action( 'init', 'my_dynamic_blocks' );
I couldn't find a good tutorial on creating a custom author block, so hopefully this example helps some poor soul down the road!
In CKEditor5 I am creating a plugin to insert a span element to show a tooltip. The idea is to show a tooltip with a (foot)note inside of it while the element itself will display an incremental number. In CKEditor4 I made something like this with:
CKEDITOR.dialog.add( 'footnoteDialog', function( editor ) {
return {
title: 'Footnote Properties',
minWidth: 400,
minHeight: 100,
contents: [
{
id: 'tab-basic',
label: 'Basic Settings',
elements: [
{
type: 'text',
id: 'content',
label: 'Content of footnote',
validate: CKEDITOR.dialog.validate.notEmpty( "Footnote field cannot be empty." )
}
]
}
],
onOk: function() {
var dialog = this;
var footnote = editor.document.createElement( 'span' );
footnote.setAttribute('class', 'footnote');
footnote.setAttribute('data-toggle', 'tooltip');
footnote.setAttribute( 'title', dialog.getValueOf( 'tab-basic', 'content' ) );
footnote.setText('[FN]');
editor.insertElement( footnote );
}
};
});
[FN] would be transformed in an incremental number.
Now I try to make this plugin with in CKEditor5, but with no success. There are two issues I run in to. Fist, I can't manage to insert the element inside the text. Second, when I want to use the attribute data-toggle this doesn't work because of the - syntax. This is my current code:
import Plugin from '#ckeditor/ckeditor5-core/src/plugin';
import pilcrowIcon from '#ckeditor/ckeditor5-core/theme/icons/pilcrow.svg';
import ButtonView from '#ckeditor/ckeditor5-ui/src/button/buttonview';
export default class Footnote extends Plugin {
init() {
const editor = this.editor;
editor.ui.componentFactory.add( 'footnote', locale => {
const view = new ButtonView( locale );
view.set( {
label: 'Insert footnote',
icon: pilcrowIcon,
tooltip: true
} );
view.on( 'execute', () => {
const source = prompt( 'Footnote' );
editor.model.schema.register( 'span', { allowAttributes: ['class', 'data-toggle', 'title'] } );
editor.model.change( writer => {
const footnoteElement = writer.createElement( 'span', {
class: 'footnote',
// data-toggle: 'tooltip',
title: source
});
editor.model.insertContent( footnoteElement, editor.model.document.selection );
} );
} );
return view;
} );
}
}
How can I make sure my span element is inserted and also contains data-toggle="tooltip"?
For anyone who comes across this, there is a good description of how to set up inline elements in the model and view and then map between them here - How to add "target" attribute to `a` tag in ckeditor5?
Based on my experience, you will also need to set up Javascript code for a command that is run when a button is pressed. The command will insert the new information into the model, then this mapping code will convert it to the view (HTML) for display.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm using CKEditor 5 to create a text-rich editor on each textarea that has the class .section-dynamique-fr.
The editor is indeed appended to my html page.
Now, when I try to access the editor via javascript using e.nextElementSibling, it does not return its nextElementSibling as seen in the node tree from the console inspector, instead it returns e.nextElementSibling.nextElementSibling.
Any idea why I can't access e.nextElementSibling? (the div with the class .ck-editor) ?
See attached image for html node structure
document.querySelectorAll('.section-dynamique-fr').forEach( (e) => {
ClassicEditor
.create( document.querySelector('#' + e.id), {
// toolbar: [ 'heading', '|', 'bold', 'italic', 'link' ]
} )
.then( editor => {
window.editor = editor;
thisEditor = editor;
} )
.catch( err => {
console.error( err.stack );
} );
console.log(e); //This gives me the textarea
console.log(e.nextElementSibling); //This should gives me the div with class ck-editor but instead gives me the div with class .textarea-saved-content-fr
This is because editor did not create after create execution. you need replace you code to thencallback. callback is a Promise and it will be resolve after editor fully created. See documentaion
document.querySelectorAll('.section-dynamique-fr').forEach( (e) => {
ClassicEditor
.create( document.querySelector('#' + e.id), {
// toolbar: [ 'heading', '|', 'bold', 'italic', 'link' ]
} )
.then( editor => {
window.editor = editor;
thisEditor = editor;
console.log(e.nextElementSibling);
} )
.catch( err => {
console.error( err.stack );
} );