Toggle the State of a CKEditor plugin button - javascript

What is the correct way to toggle the state of a ckeditor plugin menu button based on the selection?
For example, in a link/unlink plugin, I would only want to enable unlink if the cursor is in a link.
editor.addCommand("unlink", {
exec: function (editor) {
//do something here
},
refresh: function (editor, path) {
// never seems to get fired. Is this even the right hook?
}
});
editor.ui.addButton("Unlink", {
label: "Unlink",
command: "unlink"
});
Thanks for the help!

There is CKEDITOR.commandDefinition#contextSensitive property that makes it possible to control the state of a command in a particular context.
For example, the actual implementation of Unlink button looks like:
CKEDITOR.unlinkCommand.prototype = {
exec: function( editor ) {
...
},
refresh: function( editor, path ) {
var element = path.lastElement && path.lastElement.getAscendant( 'a', true );
if ( element && element.getName() == 'a' && element.getAttribute( 'href' ) && element.getChildCount() )
this.setState( CKEDITOR.TRISTATE_OFF );
else
this.setState( CKEDITOR.TRISTATE_DISABLED );
},
contextSensitive: 1,
...
};

Related

Error returning value when editing message

I've been thinking about how to do this for days and if you could help me.
I expose you, I have followed the CKEditor 5 tutorial to the point of including the mentions, this is where my problem begins.
Following the tutorial we come to the part of the output of the mention, this as they do in the tutorial I have transformed it from <span> to <a> together with its class, its URL and its data. Well the editor shows it fine until you want to edit the post.
That is, imagine this message:
Hello world I am the first code of #undercover
Well when I include it in the database everything is correct, but when we return that same message to the editor it becomes:
Hello world I am the first code of #undercover
Investigating and as my Javascript is quite low I have been trying things.
The conversion. I've tried but there is something I can't understand and it's like passing the values ​​to the function. Let me explain, when I pass that <a> that I save in the database, if I transform it into a <span> and then insert it if it tries to make the change to mention but the class attribute and the href attribute are "orphaned".
Well, I have 3 ideas and I can't do any of them at some point I get stuck, so I ask you for help.
My idea is to return the text I have in the database and the editor reads it fine.
Idea 1: Put the text in Javascript and identify and exchange the mentions that are in the database by the function of the mentions command, this is really complicated for me because it is very abstract, even so I am still looking for how to do it.
Idea 2: Save the value in the database in another way, this has been a last idea, how to search and put the of the mention but with the custom values. Even if {mention: {id: #undercover}} were saved in the database, I wouldn't care as long as it was later transformed correctly in the editor.
Idea 3: The use of conversions, I have managed to understand this and it has cost me that its function is to identify the mention within the editor and exchange it for the data you want. In this idea I can't understand how to pass the values ​​other than manually, that is, how to pass the class and href attributes.
Here I leave you the section of the code, I hope you can give me a hand and thank you very much.
function MentionCustomization( editor ) {
// The upcast converter will convert <a class="mention" href="" data-user-id="">
// elements to the model 'mention' attribute.
editor.conversion.for( 'upcast' ).elementToAttribute( {
view: {
name: 'a',
key: 'data-mention',
classes: 'mention',
attributes: {
href: true,
'data-user-id': true,
}
},
model: {
key: 'mention',
value: viewItem => {
// The mention feature expects that the mention attribute value
// in the model is a plain object with a set of additional attributes.
// In order to create a proper object, use the toMentionAttribute helper method:
const mentionAttribute = editor.plugins.get( 'Mention' ).toMentionAttribute( viewItem, {
// Add any other properties that you need.
link: viewItem.getAttribute( 'href' ),
userId: viewItem.getAttribute( 'data-user-id' )
} );
return mentionAttribute;
}
},
converterPriority: 'high'
} );
// Downcast the model 'mention' text attribute to a view <a> element.
editor.conversion.for( 'downcast' ).attributeToElement( {
model: 'mention',
view: ( modelAttributeValue, { writer } ) => {
// Do not convert empty attributes (lack of value means no mention).
if ( !modelAttributeValue ) {
return;
}
return writer.createAttributeElement( 'a', {
class: 'group-color-'+modelAttributeValue.group,
'data-mention': modelAttributeValue.id,
// 'data-user-id': modelAttributeValue.userId,
'href': '/member/profile/'+modelAttributeValue.user_id,
}, {
// Make mention attribute to be wrapped by other attribute elements.
priority: 20,
// Prevent merging mentions together.
id: modelAttributeValue.uid,
} );
},
converterPriority: 'high'
} );
}
$.ajax({
type: "POST",
dataType: "json",
url: "/members/list_json",
success: function(info){
ClassicEditor
.create( document.querySelector( '#comment' ), {
extraPlugins: [ MentionCustomization ],
updateSourceElementOnDestroy: true,
language: 'es',
toolbar: [ 'bold', 'italic', '|' , 'link', '|', 'bulletedList'],
mention: {
feeds: [
{
marker: '#',
feed: getFeedItems,
minimumCharacters: 2,
itemRenderer: customItemRenderer,
}
]
}
} )
.then( editor => {
window.editor = editor;
/*
*/
} )
.catch( err => {
console.error( err.stack );
} );
let list_members = [];
for(let i = 0; i < info.length; i++){
var member = info[i];
list_members.push(member);
}
function getFeedItems( queryText ) {
return new Promise( resolve => {
setTimeout( () => {
const itemsToDisplay = list_members
.filter( isItemMatching )
.slice( 0, 10 );
resolve( itemsToDisplay );
}, 100 );
} );
function isItemMatching( item ) {
const searchString = queryText.toLowerCase();
return (
item.username.toLowerCase().includes( searchString )
);
}
}
},
});
function customItemRenderer( item ) {
const itemElement = document.createElement( 'span' );
const avatar = document.createElement( 'img' );
const userNameElement = document.createElement( 'span' );
itemElement.classList.add( 'mention__item');
avatar.src = `${ item.avatar }`;
avatar.classList.add('image-fluid', 'img-thumbnail', 'rounded-circle');
userNameElement.classList.add( 'mention__item__user-name' );
userNameElement.style.cssText = 'color: '+ item.group_color +';';
userNameElement.textContent = item.id;
itemElement.appendChild( avatar );
itemElement.appendChild( userNameElement );
return itemElement;
}

CKEditor5 Custom Modal Plugin

I followed the initial plugin tutorial and got the Image Insert to work, but I would like to display a custom modal with two input fields instead of the prompt to set some more attributes.
How would I best implement this?
I know how to implement a normal modal in plain JS/CSS but I am a bit confused as to where to put the HTML for the modal to be displayed on the button click.
class Test extends Plugin {
init() {
editor = this.editor
editor.ui.componentFactory.add('SampleView', (locale) => {
const view = new ButtonView(locale)
view.set({
label: 'test',
icon: imageIcon,
tooltip: true
})
view.on('execute', () => {
//here I would like to open the modal instead of the prompt
})
})
}
}
For example, you can try to use SweetAlert2 which is zero-dependency pure javascript replacement for default popups.
import swal from 'sweetalert2';
...
view.on( 'execute', () => {
swal( {
input: 'text',
inputPlaceholder: 'Your image URL'
} )
.then ( result => {
editor.model.change( writer => {
const imageElement = writer.createElement( 'image', {
src: result.value
} );
editor.model.insertContent( imageElement, editor.model.document.selection );
} );
} )
} );

Need to pass argument to modal dlg from Datatable button action

I do use datatable where i've been declared some buttons to trigger action based which button user press:
var dpcroles = $('#example_roles').DataTable( {
dom: 'Bfrtip',
"columnDefs": [
{
"targets": [0],
"visible": false
}
],
buttons: [
{
text: 'Add',
id: 'btn_add',
"data-action":'add',
action: function ( e, dt, node, config ) {
$('#modal_action').modal();
}
},
{
id: 'btn_edit',
text: 'Edit',
action: function ( e, dt, node, config ) {
var id = $(e.relatedTarget).data('id');
console.log(id);
$('#model_action').modal(id);
},
enabled: true
},
],
However, how to pass arguments javascript which handles modal opening ?
$('#model_action').on('show.bs.modal', function(e) {
// if button 'edit', do something
.
.
// else if button 'add' do other thing
.
.
.
})
You can set data- attribute for a modal before calling modal() method. For example:
$('#modal_action').data('mode', 'edit');
$('#modal_action').modal();
Then in your event handler, you can retrieve the data. For example:
$('#modal_action').on('show.bs.modal', function(e) {
var $modal = $(this);
var mode = $modal.data('mode');
// if button 'edit', do something
if(mode === 'edit'){
// else if button 'add' do other thing
} else {
}
});
Another solution would be to use two different modals, one for each action.
Please note that you've probably misspelled the name of the modal in your example, it should be either modal_action or model_action.

Enabling custom button (disabled by default) when row is selected

I have a DataTable displaying data for Branches with two custom buttons defined: Add and Update. They are initialized at the top of the Javascript section
var buttons;
var tblBranch;
$.fn.dataTable.ext.buttons.add = {
className: 'button-add',
text: "Add Branch",
action: function (dt) {
onBtnAddClicked()
}
};
$.fn.dataTable.ext.buttons.update = {
className: 'button-update',
text: "Update",
action: function (dt) {
onBtnUpdateClicked()
}
};
I'd like to disable the Edit button on page load and only enable it to be clickable when a row has been selected. Problem is, I'm using custom buttons and I can't find anything on datatables.net about how to enable/disable them depending on conditions. So far what I've tried is this:
tblBranch = $("#tblBranches").DataTable({
dom: 'Blfrtip',
buttons: {
buttons :[
'add', 'update'
]
}
select: true;
})
$("#tblBranches tbody").on('click', 'tr', function () {
if (tblBranch.row(this).hasClass('selected')) {
$('button-update').removeClass("DTTT_disabled");
}
else {
table.$('tr.selected').removeClass('selected');
$('button-update').addClass("DTTT_disabled");
}
});
But I don't know what the code to disable the Edit button when the page loads should be like, and I've looked here, here, here and here.
Thanks for any guidance.
The last link you are referring to hold the solution you are looking for. But the documentation is a little bit vague, guess it need a solid example. It is not clear how you create the buttons (you show both methods) but below is an inline example, it would work with constructor as well. Simply give the button a class, like .edit and set it to disabled from start :
var table = $('#example').DataTable( {
dom: 'Bfrtip',
select: true,
buttons: [
{
text: 'Edit',
className: 'edit',
enabled: false,
action: function (e, dt, node, config) {
//do something
}
},
{
text: 'Add',
action: function (e, dt, node, config) {
//do something
}
}
]
})
Then use the Select plugins select and deselect events to update the enabled status of the .edit button :
$('#example').on('select.dt deselect.dt', function() {
table.buttons( ['.edit'] ).enable(
table.rows( { selected: true } ).indexes().length === 0 ? false : true
)
})
demo -> https://jsfiddle.net/pmee6w2L/

jstree open_node not working on child nodes

When my checkbox jstree has finished loading, I wish to pre open the last opened nodes (not select_node). The open_node function only seems to work on the top most parent level nodes. I even tried iterating through the node and calling open_node and it still doesn't work. I have the following:
// Create instance for checkbox jstree.
$(function () {
$('#myTree').jstree({
"core": {
"themes": {
'name': 'default',
"variant": "small",
"icons": false
},
},
"checkbox": {
"keep_selected_style": false,
"three_state": false,
},
"plugins": ["checkbox"]
});
});
$("#myTree").bind('ready.jstree', function (event, data) {
var $tree = $(this);
$($tree.jstree().get_json($tree, {
"flat": true
})).each(function (index, value) {
// lastOpenedNode.value contains the id of the last opened node
if ( nodeWasLastOpened(this.id) == true)
// ONLY OPENS TOP MOST PARENT NODES
$("#myTree").jstree().open_node(this.id);
})
});
Please help.
There is a private method you could use for that, _open_to, that will open all nodes down to the one you want to be shown. Check code below and demo - Fiddle.
$("#myTree").jstree()._open_to( lastOpenedNode.value );
or
if ( nodeWasLastOpened(this.id) )
$("#myTree").jstree()._open_to( this.id );
})

Categories

Resources