Summernote custom button pass context and data - javascript

I am using summernote in angular I want to create a custom button.
I would like to pass the listHit in customButton as parameter like this 'testBtn': this.customButton(context, listHit) but I am not sure how to do this since the function looks like this 'testBtn': this.customButton any help would be appreciated thank you.
My custom button looks something like this.
customButton(context) {
var listHit = ['One', 'Two', 'Tree'];
const ui = ($ as any).summernote.ui;
var i;
var listHitHtml = "";
for (i = 0; i < listHit.length; i++) {
listHitHtml += "<li>" + listHit[i] + "</li>";
}
var button = ui.buttonGroup([
ui.button({
className: 'dropdown-toggle',
contents: '<i class="fa fa-comments"/><span class="caret"></span>',
tooltip: '#erp_colombia.Lang.Resource.conAvailableComments',
data: {
toggle: 'dropdown'
}
}),
ui.dropdown({
className: 'drop-default summernote-list',
contents: "<div id=\"container-comentario\"><div id=\"dialog\" title=\"Comentarios\" ><h1 class=\"header-comentario\">" + 'Comment' + "</h1><ul id=\"liste-comentarios\"><ul>" + listHitHtml + "</ul></div></div>",
callback: function ($dropdown) {
$dropdown.find('li').each(function () {
$(this).click(function () {
context.invoke("editor.insertText", $(this).html() + "\n");
});
});
}
})
]);
return button.render(); // return button as jquery object
}
Here is my pdfmaker config
this.config = {
placeholder: placeholder,
shortcuts: false,
disableDragAndDrop: true,
//tabsize: 2,
hint: {
mentions: this.quoteCommentsForSummerNote,
match: /\b(\w{1,})$/,
search: function (keyword, callback) {
callback($.grep(this.mentions, function (item: any) {
return item.indexOf(keyword) == 0;
}));
},
content: function (item) {
return item;
}
},
height: 200,
toolbar: [
['myotherbutton', ['testBtn']],
],
buttons: {
'testBtn': this.customButton
}
}
And this is my angular html
Here you can fiddle with a example I created a list that we will assume comes from a service I would like to pass this list to customButton
listStringFromDbService = ['one', 'two', 'three'];
https://stackblitz.com/edit/angular-summernote-demo-gdvvbn?file=src%2Fapp%2Fapp.component.ts

I believe I figured this out.
You can change your button declaration to a function that returns a button function. That way you can pass data to it before constructing the function that Evernote binds to testBtn.
Change the function declaration (expression or declaration will work, like you pointed out)
function customButtonGenerator(arr) {
return function (context) {
const ui = $.summernote.ui;
const button = ui.button({
contents: '<i class="note-icon-magic"></i> Hello',
tooltip: 'Custom button',
container: '.note-editor',
className: 'note-btn',
click: function () {
context.invoke('editor.insertText', 'Hello from test btn!!! ' + arr);
},
});
return button.render();
};
};
then when you create the ui config you can generate the button function instead:
buttons: {
testBtn: customButtonGenerator(this.listStringFromDbService),
},
Here's an updated stackblitz showing a working example.

I have modified the answer of MPawlak like this in it there is a dropdown where you can click the items you want to add. Also I have the passing of parameter to the custom button that still works. Thanks to MPawlak
https://stackblitz.com/edit/angular-summernote-demo-yq8t4t

Related

Generating TinyMCE drop-down menu dynamically

I am trying to create toolbar button in TinyMCE with options that are derived from the array. I've followed the examples on Tiny's website and the button is getting generated as expected. Here is the code:
var mergeFields = {one: "first", two: "second", three: "third"};
tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: 'mergefields',
setup: function (editor) {
editor.ui.registry.addMenuButton('mergefields', {
text: 'Merge Fields',
fetch: function (callback) {
var items = [];
for (var fieldName in mergeFields) {
var menuItem = {
type: 'menuitem',
text: mergeFields[fieldName],
onAction: function() {
// The problem: this function always inserts the last element of the array
// instead of the expected fieldName associated with this menuItem
editor.insertContent(fieldName);
},
};
items.push(menuItem);
}
callback(items);
},
});
}
});
<script src="https://cloud.tinymce.com/5/tinymce.min.js?apiKey=XXXXX"></script>
<textarea>Editor</textarea>
The problem happens when one of the options is selected and the anonymous function assigned to onAction property is executed -- it always inserts "three" into the document (presumably because after running through the whole array, fieldName is set to "three"). How can I make the onAction handler insert the right value into the document?
This needs to work in TinyMCE 5.
I've found a similar question here: Adding custom dropdown menu to tinyMCE and insert dynamic contents, but it was referring to TinyMCE 4 and unfortunately the provided answer does not work for TinyMCE 5.
Thanks for your help!
I had the same problem.
I solved it using value+onSetup
https://jsfiddle.net/stvakis/tjh7k20v/8/
var mergeFields = {
one: "first",
two: "second",
three: "third"
};
tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: 'mergefields',
setup: function(editor) {
editor.ui.registry.addMenuButton('mergefields', {
text: 'Merge Fields',
fetch: function(callback) {
var items = [];
for (var fieldName in mergeFields) {
var menuItem = {
type: 'menuitem',
text: mergeFields[fieldName],
value:fieldName,
onSetup: function(buttonApi) {
var $this = this;
this.onAction = function() {
editor.insertContent($this.data.value);
};
},
};
items.push(menuItem);
}
callback(items);
},
});
}
});

TinyMce add multi elements to activeEditor.dom

I am using TinyMce4 i have pluging that add div to my editor
My code:
tinymce.create('tinymce.plugins.AddContent', {
init: function (ed, url) {
ed.addCommand('mceAddContent', function () {
var editor = tinymce.activeEditor;
var ed_body = $(editor.getBody());
tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'div', { 'class': 'draggableTemplate' }, 'Add you element here...');
}),
// Register example button
ed.addButton('addcontent', {
title: 'Add content at the end',
cmd: 'mceAddContent',
image: url + '/img/addcontent.png',
onclick: function () {
}
});
}
});
tinymce.PluginManager.add('addcontent', tinymce.plugins.AddContent);
Now what i need is to add not only div
i need element Link(a) inside of this div with href and class
Example:
<div class='draggableTemplate'>
Link to element
</div>
How can i use tinyMCE.activeEditor.dom.add or some think else to add div with link(a) like you see it in example
I found the solution it is very simple:
you just need to change
tinyMCE.activeEditor.getBody()
in
tinyMCE.activeEditor.dom.add(...)
to your element that you need,and this will insert Link(a) to your element
var yourElement= tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'div', { 'class': 'draggableTemplate' }, ' ');
tinyMCE.activeEditor.dom.add(yourElement, 'a', { 'href': '#scroll1'), 'class': ' scrollto ' }, 'Insert your anchor image or text first before you remove this...');
Full code:
tinymce.create('tinymce.plugins.AddContent', {
init: function (ed, url) {
ed.addCommand('mceAddContent', function () {
var editor = tinymce.activeEditor;
var ed_body = $(editor.getBody());
var yourElement= tinyMCE.activeEditor.dom.add(tinyMCE.activeEditor.getBody(), 'div', { 'class': 'draggableTemplate' }, ' ');
tinyMCE.activeEditor.dom.add(yourElement, 'a', { 'href': '#scroll1'), 'class': ' scrollto ' }, 'Link to element');
}),
// Register example button
ed.addButton('addcontent', {
title: 'Add content at the end',
cmd: 'mceAddContent',
image: url + '/img/addcontent.png',
onclick: function () {
}
});
}
});
tinymce.PluginManager.add('addcontent', tinymce.plugins.AddContent);
Result:
<div class='draggableTemplate'>
Link to element
</div>

How to add render and create methods to Selectize element

I have a HTML 'select' element that I want to use as 'AutoSuggest' by using Selectize.js and this is how I initialize the selectize
jQuery(ele).selectize({
//options: initData,
addPrecedence: false,
persist: false,
maxItems: 1,
create: function (input) {
return {
value: input,
text: input
};
},
render: {
option_create: function (data, escape) {
return '<div class="create"><strong>' + escape(data.input) + '</strong></div>';
}
}
});
Now, the issue is if the 'ele' is already initialized as a 'Selectize' control without the 'render' and 'create' options, how can I add these options?
I figured it out. Here is how you do this
if (ele.selectize) {
var selectizeCtrl = jQuery(ele)[0].selectize;
selectizeCtrl.settings.create = function (input) {
return {
value: input,
text: input
};
};
selectizeCtrl.settings.render.option_create = function (data, escape) {
return '<div class="create"><strong>' + escape(data.input) + '</strong></div>';
};
}

Unable to create a delete button in Meteor using reactive-table

I building a sortable table in Meteor with Reactive-Table and having trouble getting my delete button to work for removing entries from the table.
Please see my javascript code below:
Movies = new Meteor.Collection("movies");
if (Meteor.isClient) {
Template.body.events({
"submit .new-movie": function (event) {
var title = event.target.title.value;
var year = event.target.year.value;
var genre = event.target.genre.value;
Movies.insert({
title: title,
year: year,
genre: genre
});
event.target.title.value = "";
event.target.year.value = "";
event.target.genre.value = "0";
return false;
}
});
Template.moviestable.events({
"click .deletebtn": function (event) {
Movies.remove(this._id);
}
});
Template.moviestable.helpers({
movies : function () {
return Movies.find();
},
tableSettings : function () {
return {
showFilter: false,
fields: [
{ key: 'title', label: 'Movie Title' },
{ key: 'year', label: 'Release Year' },
{ key: 'genre', label: 'Genre' },
{ key: 'edit', label: 'Edit', fn: function () { return new Spacebars.SafeString('<button type="button" class="editbtn">Edit</button>') } },
{ key: 'delete', label: 'Delete', fn: function () { return new Spacebars.SafeString('<button type="button" class="deletebtn">Delete</button>') } }
]
}
}
});
}
Can anyone tell me what I'm doing wrong?
In the reactive tables docs, there's an example of how to delete rows from the table. Adapting the example in the docs for your needs, your event should look like this:
Template.moviestable.events({
'click .reactive-table tbody tr': function (event) {
event.preventDefault();
var objToDelete = this;
// checks if the actual clicked element has the class `deletebtn `
if (event.target.className == "deletebtn") {
Movies.remove(objToDelete._id)
}
}
});
The problem you are having is that you are trying to find the _id property on the button click instead of the row click.
If you do console.log(this) on your button click event (as you have it in your question above) you will get something like this Object {key: "delete", label: "", fieldId: "2", sortOrder: ReactiveVar, sortDirection: ReactiveVar} which does not contain the property _id
It is easier to register the row click, where the row object is the actual document you are trying to delete, and then check if the event's target has the delete class you added.

How to dynamically generate options for RichCombo in CKEDITOR?

There is a form on my page with textarea (CKEDITOR) and select field <select id="_photogalleries" multiple="multiple"></select>. I'd like options in RichCombo to depend on the options that are selected in select with id #_photogalleries. Is there any way to regenerate RichCombo dynamically?
Thanks in advance.
CKEDITOR.plugins.add('style_plugin', {
requires: ['richcombo'],
init: function(editor) {
var pluginName = 'style_plugin';
var config = editor.config,
lang = editor.lang.format;
editor.ui.addRichCombo('photogalleries', {
label: "Фоторепортаж",
title: "Фоторепортаж",
voiceLabel: "Фоторепортаж",
className: 'cke_format',
multiSelect: false,
icon: CKEDITOR.plugins.getPath('style_plugin') + 'photo-list-horizontal.png',
panel: {
css: [config.contentsCss, CKEDITOR.getUrl(editor.skinPath + 'editor.css')],
voiceLabel: lang.panelVoiceLabel
},
init: function () {
this.startGroup("Фоторепортаж");
var list=this;
$("#_photogalleries option:selected").each(function(index, value){
console.log(index, value);
list.add("#HORIZONTAL_GALLERY_"+ $(value).val()+"#", "(Г) " + $(value).text(), "(Г) " + $(value).text());
list.add("#VERTICAL_GALLERY_"+ $(value).val()+"#", "(В) " + $(value).text(), "(В) " + $(value).text());
});
},
onClick: function (value) {
editor.focus();
editor.fire('saveSnapshot');
editor.insertHtml(value);
editor.fire('saveSnapshot');
}
});
}
});
This works for me and you dont have to keep a global variable.
CKEDITOR.plugins.add('systemdata', {
init: function (editor) {
var fnData = editor.config.fnData;
if (!fnData || typeof (fnData) != 'function')
throw "You must provide a function to retrieve the list data.";
editor.ui.addRichCombo('systemDataCmb',
{
allowedContent: 'abbr[title]',
label: "System Data",
title: "System Data",
multiSelect: false,
init: function () {
var self = this;
var content = fnData();
$.each(content, function(index, value) {
// value, html, text
self.add(value.name, value.name, value.name)
});
}
}
Then to set the function to get the data put this somewhere where you setup the ckeditor
CKEDITOR.replaceAll(function(element, config) {
config.startupFocus = true;
config.fnData = function() {
var returnData = null;
$.ajax({
url: "/GetData",
async: false,
data: { id: 1 },
}).done(function(result) { returnData= result; });
return returnData;
};
});
It assumes you bring back a json response that has an array of items that have a value property, that can be easily changed though.
I guess I found a solution that worked for me. It was to keep a list object in a global variable and then modify it when onchange event fires in the external select.
I solved this trouble with a single line:
YOURCOMBO.createPanel(editor);
For example:
var comboTeam = editor.ui.get("team");
comboTeam.createPanel(editor);//This is important, if not, doesnt works
Now you can add items to the combo
comboTeam.add("name","name","name");
comboTeam.add("name2","name2","name2");
comboTeam.add("name3","name3","name3");

Categories

Resources