How to dynamic create custom controls - tinymce

I am trying to add a customized mymenubutton, the menu's items are based on another dropdown's selected value, which returns a json array with bunch items.
So I use the example http://fiddle.tinymce.com/gaaaab which could create mymenubutton for the first time, but when the drop down list changes, how should I re-init this control and rebind json array to mymenubutton?
function generateTokensList(result) {
tinymce.create('tinymce.plugins.ExamplePlugin', {
createControl: function (n, cm) {
switch (n) {
case 'mysplitbutton':
var c = cm.createSplitButton('mysplitbutton', {
title: 'My split button',
image: 'some.gif',
onclick: function () {
alert('Button was clicked.');
}
});
c.onRenderMenu.add(function (c, m) {
m.add({ title: 'Tokens', 'class': 'mceMenuItemTitle' }).setDisabled(1);
var insertVar = function (val) {
return function () { tinyMCE.activeEditor.execCommand('mceInsertContent', false, val); }
};
for (var i = 0; i < result.length; i++) {
var field = result[i].field;
var variable = insertVar(result[i].field);
m.add({ title: result[i].name, onclick: variable });
}
});
// Return the new splitbutton instance
return c;
}
return null;
}
});
tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin);
}

Solved this by myself. Bind the data to a variable and each time just call var.
c.onRenderMenu.add(function (c, m) {
m.add({ title: 'Tokens', 'class': 'mceMenuItemTitle' }).setDisabled(1);
var insertVar = function (val) {
return function () { tinyMCE.activeEditor.execCommand('mceInsertContent', false, val); }
};
for (var i = 0; i < tokens.length; i++) {
var field = tokens[i].field;
var variable = insertVar( '[['+tokens[i].name+']]');
m.add({ title: '[['+tokens[i].name+']]', onclick: variable });
}
});

Related

Updating data doesnt expand the data tree inside material-table

Im trying to build a table with nested tree folder inside.
When trying to add nested data into the datasource data the structure will not updated and will not toggle anymore.
Code below:
https://stackblitz.com/edit/angular-table-tree-example-k2zqmt?file=app%2Ftable-basic-example.ts&file=app%2Ftable-basic-example.html,app%2Ftable-basic-example.ts
Environment
Angular:
Material Table
Material tree system
These are the things that are happening when logNode method is called
The item is getting added but the treeControl.toggle method does not work anymore.
When you are assigning a new dataset to the dataSource all the nodes get reset and the tree closes, so this.treeControl.toggle is trying to toggle a node that does not exist.
You need to find the node to be toggled from the list you get from treeControl.dataNodes
I would suggest having the toggle code in a separate method and adding a node code in a separate method, and a separate button to add the node.
The below code should work for your scenario, also remove this line from your HTML, (click)="treeControl.toggle(data)"
interface ExampleFlatNode {
expandable: boolean;
RoleName: string;
Access: boolean;
level: number;
CatId: number;
}
private transformer = (node: FoodNode, level: number) => {
return {
expandable:
!!node.CategoryPermissions && node.CategoryPermissions.length > 0,
RoleName: node.RoleName,
Access: node.Access,
level: level,
CatId: node.CatId,
};
};
tempNodes = []
constructor() {
this.dataSource.data = TREE_DATA;
}
logNode(clickedNode) {
this.tempNodes = [];
this.treeControl.dataNodes.forEach((node) =>
this.tempNodes.push({
...node,
expanded: this.treeControl.isExpanded(node),
})
);
if (!this.treeControl.isExpanded(clickedNode)) {
const temp = {
Access: true,
RoleName: 'test 1 2',
CatId: 113,
};
const clickedNodeIdx = this.treeControl.dataNodes.findIndex(
(node: any) =>
node.CatId === clickedNode.CatId &&
node.RoleName === clickedNode.RoleName &&
node.level === clickedNode.level
);
const childIdx = 1;
let child;
if (clickedNode.level === 0) {
child =
this.dataSource.data[clickedNodeIdx].CategoryPermissions[childIdx];
} else {
this.dataSource.data.forEach(
(item) => (child = this.findDataSource(item, clickedNode))
);
}
child.CategoryPermissions.push(temp);
this.dataSource.data = this.dataSource.data;
const addedNode = this.treeControl.dataNodes.find(
(node: any) =>
node.CatId === temp.CatId && node.RoleName === temp.RoleName
);
this.expandParent(addedNode);
this.setPreviousState();
} else {
this.treeControl.collapse(clickedNode);
}
}
findDataSource(item, node) {
if (item.RoleName === node.RoleName) {
return item;
} else if (item.CategoryPermissions) {
let matchedItem;
item.CategoryPermissions.forEach((e) => {
const temp = this.findDataSource(e, node);
if (temp) {
matchedItem = temp;
}
});
return matchedItem;
}
}
setPreviousState() {
for (let i = 0, j = 0; i < this.treeControl.dataNodes.length; i++) {
if (
this.tempNodes[j] &&
this.treeControl.dataNodes[i].RoleName === this.tempNodes[j].RoleName &&
this.treeControl.dataNodes[i].CatId === this.tempNodes[j].CatId &&
this.treeControl.dataNodes[i].level === this.tempNodes[j].level
) {
if (this.tempNodes[j].expanded) {
this.treeControl.expand(this.treeControl.dataNodes[i]);
}
j++;
}
}
}
expandParent(node: ExampleFlatNode) {
const { treeControl } = this;
const currentLevel = treeControl.getLevel(node);
const index = treeControl.dataNodes.indexOf(node) - 1;
for (let i = index; i >= 0; i--) {
const currentNode = treeControl.dataNodes[i];
if (currentLevel === 0) {
this.treeControl.expand(currentNode);
return null;
}
if (treeControl.getLevel(currentNode) < currentLevel) {
this.treeControl.expand(currentNode);
this.expandParent(currentNode);
break;
}
}
}

Why variable A is not being copied to variable B?

I'm using two variables with the same value. Variable A is an initial variable and variable B is the one that I use to apply changes, so when I want to reset variable B I just assign A to it, the problem is each time I do it, the changes of B then applied to both. I have look in many places and these are the solutions I tried:
List.toList()
_fields!.clear();
_fields = _initFields!.toList();
Spread operator (...)
_fields!.clear();
_fields = [...?_initFields];
Also tried the ones below from this post: Dart/Flutter – How to clone/copy a list
var newNumbers = List.from(numbers);
var newNumbers = List.generate(numbers.length, (index) => numbers[index]);
var newNumbers = List.of(numbers);
var newNumbers = List.unmodifiable(numbers);
Here the complete code:
import 'package:project/utilities/classes/filter_field.dart';
class FilterLogic {
List<FilterField>? _initFields = [];
List<FilterField>? _fields = [];
bool? listComplete = false;
void addField(FilterField? field) {
_fields!.add(field!);
}
void addInitField(FilterField? field) {
_initFields!.add(field!);
}
List<FilterField>? getFields() {
return _fields;
}
void resetFieldsToOriginal() {
_fields!.clear();
_fields = [...?_initFields!];
}
void showFields() {
print('_fields --------------------------------------------------------------------------------------');
_fields!.forEach((element) {
if(element.checked == true) {
print({ element.checked, element.field, element.filteredApplied, element.criteria, element.filteringOperators});
}
});
print('_initFields --------------------------------------------------------------------------------------');
_initFields!.forEach((element) {
if(element.checked == true) {
print({ element.checked, element.field, element.filteredApplied, element.criteria, element.filteringOperators});
}
});
}
}
Here is how I fill both variables:
filterCol.forEach((column) {
String? filteredApplied;
String? filteredCriteria = 'None';
bool checked = false;
filtersList.forEach((element) {
if (column.field == element.field) {
filteredApplied = element.operator;
filteredCriteria = element.criteria;
checked = true;
}
});
FilterField field = FilterField(
filteredApplied: filteredApplied,
field: column.field,
label: column.label,
filteringOperators: column.filteringOperators,
criteria: filteredCriteria,
checked: checked == true ? true : false,
);
FilterField initField = FilterField(
filteredApplied: filteredApplied,
field: column.field,
label: column.label,
filteringOperators: column.filteringOperators,
criteria: filteredCriteria,
checked: checked == true ? true : false,
);
setState(() {
filterLogic.addField(field);
filterLogic.addInitField(initField);
});
});
Here where I call the reset method:
DialogButton(
width: 106.25,
child: Text(
"CANCEL",
style: TextStyle(
color: Colors.white, fontSize: 14, fontFamily: 'Chivo'),
),
onPressed: () => {
Navigator.of(context).pop(),
setState(() {
filterLogic.resetFieldsToOriginal(); // <-------------
})
},
color: Color.fromRGBO(84, 84, 84, 1),
radius: BorderRadius.circular(0.0),
),
It's not enough just to copy the list cause your new list has references to the same FilterField instances. That means if you change any FilterField in the new list the same changes would be in the old one. So in your case, you need to make a so-called deep clone. You can create a method for that:
class FilterField {
// ... other code
FilterField CopyWith() {
return new FilterField(...);
}
}
and then you could something like that:
var newList = oldList.toList().map((item) => item.CopyWith()).toList();
and now you could change the lists separately.
But be aware that if FilterField has any other instances of classes that need to be changed you need to create new instances of those instances either. That's why it's called a deep clone.
Hope that's what you were looking for.

Limit size of entered data in tinyMCE 5

I use tinyMCE 5 in my web site to enter data stored in a database. Therefore I need to limit the entered size, including format information, to the size of the data field. How can I prohibit the user to enter more then the allowed number of bytes, say 2000?
Best of all if I could add some information like "42/2000" on the status bar.
We had a similar requirement in our project (difference: the output should be <entered_chars>/<chars_left> instead of <entered_chars>/<max_chars>), and it ended up being a custom plugin, based on the wordcount plugin. There is some hacks in there, which could make it fail whenever tinyMCE changes, since there is no API for the statusbar in version 5 at this point of time.
But maybe you will still find it useful:
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var maxChars = function (editor) {
return editor.getParam('number_max_chars', 3600);
};
var applyMaxChars = function (editor) {
return editor.getParam('restrict_to_max_chars', true);
};
var Settings = {
maxChars: maxChars,
applyMaxChars: applyMaxChars
};
var global$1 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
var getText = function (node, schema) {
var blockElements = schema.getBlockElements();
var shortEndedElements = schema.getShortEndedElements();
var isNewline = function (node) {
return blockElements[node.nodeName] || shortEndedElements[node.nodeName];
};
var textBlocks = [];
var txt = '';
var treeWalker = new global$1(node, node);
while (node = treeWalker.next()) {
if (node.nodeType === 3) {
txt += node.data;
} else if (isNewline(node) && txt.length) {
textBlocks.push(txt);
txt = '';
}
}
if (txt.length) {
textBlocks.push(txt);
}
return textBlocks;
};
var strLen = function (str) {
return str.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '_').length;
};
var countCharacters = function (node, schema) {
var text = getText(node, schema).join('');
return strLen(text);
};
var createBodyCounter = function (editor, count) {
return function () {
return count(editor.getBody(), editor.schema);
};
};
var createMaxCount = function (editor) {
return function () {
return Settings.maxChars(editor);
}
}
var createRestrictToMaxCount = function (editor) {
return function () {
return Settings.applyMaxChars(editor);
}
}
var get = function (editor) {
return {
getCount: createBodyCounter(editor, countCharacters),
getMaxCount: createMaxCount(editor),
getRestrictToMaxCount: createRestrictToMaxCount(editor)
};
};
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
function isAllowedKeycode(event) {
// allow arrow keys, backspace and delete
const key = event.keyCode;
return key === 37 || key === 38 || key === 39 || key === 40 || key === 8
|| key === 46;
}
var updateCount = function (editor, api) {
editor.getContainer().getElementsByClassName(
'tox-statusbar__text-container')[0].textContent = String(
api.getCount()) + " / " + String(
Settings.maxChars(editor) - api.getCount());
};
var setup = function (editor, api, delay) {
var debouncedUpdate = global$2.debounce(function () {
return updateCount(editor, api);
}, delay);
editor.on('init', function () {
updateCount(editor, api);
global$2.setEditorTimeout(editor, function () {
editor.on('SetContent BeforeAddUndo Undo Redo keyup', debouncedUpdate);
editor.on('SetContent BeforeAddUndo Undo Redo keydown', function (e) {
if (!isAllowedKeycode(e) && Settings.applyMaxChars(editor) &&
api.getCount() >= Settings.maxChars(editor)) {
e.preventDefault();
e.stopPropagation();
}
});
}, 0);
});
};
function Plugin(delay) {
if (delay === void 0) {
delay = 300;
}
global.add('charactercount', function (editor) {
var api = get(editor);
setup(editor, api, delay);
return api;
});
}
Plugin();
}());
Currently I'm working on a preprocessor for the paste plugin, so that the max_length effects also pasted text. That's why you see the charactercount API in the code.

Openui5: wrong sort order with sap.ui.model.Sorter

It appears sap.ui.model.Sorter doesn't sort ISO-8859-1 characters correctly.
Below is an example where we create a list with one item pr character in the Norwegian alfabet. The output of this is not in the correct order, instead the order is "AÅÆBCDEFGHIJKLMNOØPQRSTUVWXYZ".
The expected results is the same order as when the alfabet variable is declared: "ABCDEFGHIJKLMOPQRSTUVWXYZÆØÅ"
How can we sort the model correctly?
JSBIN: https://jsbin.com/xuyafu/
var alfabet = "ABCDEFGHIJKLMOPQRSTUVWXYZÆØÅ"
var data = [];
for(var i=0; i< alfabet.length; i++){
data.push ({value:alfabet.charAt(i)});
}
var modelList = new sap.ui.model.json.JSONModel(data);
sap.ui.getCore().setModel(modelList);
var oSorter = new sap.ui.model.Sorter("value", null, null);
// Simple List in a Page
new sap.m.App({
pages: [
new sap.m.Page({
title: "Sorting with norwegian characters",
content: [
new sap.m.List("list", {
items: {
path: '/',
template: new sap.m.StandardListItem({
title: '{value}'
}),
sorter: oSorter
}
})
]
})
]
}).placeAt("content");
Based on the input from the comments on the question, it is straight forward to override the sorting function fnCompare to get the right order
var oSorter = new sap.ui.model.Sorter("value", null, null);
oSorter.fnCompare = function (a, b) {
if (a == b) {
return 0;
}
if (b == null) {
return -1;
}
if (a == null) {
return 1;
}
if (typeof a == "string" && typeof b == "string") {
return a.localeCompare(b, "nb");
}
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
Here "nb" is the locale the sort is done with

Getting ListData from a SharePoint list and then binding the results to a dropdown field, but how can I remove duplicates?

I have got list data from a SharePoint list and have binded one column of data into a dropdown using knockoutJS. I am now trying to remove duplicates from the binded results, but am struggling.
Here's my code so far:
var Info = ko.observable();
var AppModel = {
Acts: ko.observableArray([]),
sel: ko.observable()
}
$(function () {
$.ajax({
dataType: "json",
url: "MYLIST/_vti_bin/listdata.svc/LISTNAME?$select=Title",
data: {},
success: dataCallBack
});
ko.applyBindings();
});
function dataCallBack(data) {
var newData = [];
for(var idx=0; idx < data.d.results.length; idx++) {
function dataCallBack(data) {
var newData = [];
for(var idx=0; idx < data.d.results.length; idx++) {
var e = data.d.results[idx];
var foundItem = return ko.utils.arrayFirst(newData, function(item) {
return item == e;
});
if (!foundItem){
newData.push(e);
}
}
AppModel.Acts(newData);
}
HTML Here
<select id="location-input" data-bind="options: AppModel.Acts,
optionsText: 'Title
optionsCaption: 'Choose...',
value: AppModel.sel">
</select>
Can anyone advise as to where I'm going wrong? I think the for loop is breaking at the if statement.
Your attempt for checking duplicates is wrong.
Try something like this:
var foundItem = ko.utils.arrayFirst(newData, function(item) {
return item == e;
});
if (!foundItem)
{
newData.push(e);
}