Limit size of entered data in tinyMCE 5 - tinymce

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.

Related

Asynchronous function in SAPUI5

I'm using a function to open a dialog in SAPUI5. While this dialog is opening, some data should be set in the local storage of the browser. However, when I add the local storage function, it takes a few seconds to open the dialog.
Is there a way I can make the local storage async? I tried putting the function of the local storage after the opening of the dialog. But it doesn't change anything..
/* WHEN THE USER CLICKS ON AN ASSIGNMENT IN THE CALENDAR */
onClickAssignment: function(oEvent) {
var oAppointment = oEvent.getParameter("appointment");
this.lastAppointment = oAppointment;
if (oAppointment) {
var key = this.byId("PC1").getViewKey();
if (key === "Month") {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show assignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewAssignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
} else {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show subassignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewSubassignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
}
this.oAppBC = oAppointment.getBindingContext();
this._oDetailsDialog.setBindingContext(this.oAppBC);
this._oDetailsDialog.open();
this.lastClickedAssignment = oAppointment.getProperty("assignment");
this.lastClickedSubassignment = oAppointment.getProperty("subassignment");
//SET LOCAL STORAGE
// var stringifiedContext = CircularJSON.stringify(oAppointment.getBindingContext());
// var stringifiedAssignment = CircularJSON.stringify(oAppointment.getProperty("assignment"));
// var stringifiedSubassignment = CircularJSON.stringify(oAppointment.getProperty("subassignment"));
// this.setLocalStorage("context", stringifiedContext);
// this.setLocalStorage("assignment", stringifiedAssignment);
// this.setLocalStorage("subassignment", stringifiedSubassignment);
}
},
You can detach execution of that part of the code from the main execution thread by wrapping it into setTimeout:
/* WHEN THE USER CLICKS ON AN ASSIGNMENT IN THE CALENDAR */
onClickAssignment: function(oEvent) {
var oAppointment = oEvent.getParameter("appointment");
this.lastAppointment = oAppointment;
if (oAppointment) {
var key = this.byId("PC1").getViewKey();
if (key === "Month") {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show assignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewAssignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
} else {
if (!this._oDetailsDialog || this._oDetailsDialog === null) {
// show subassignment dialog
this._oDetailsDialog = sap.ui.xmlfragment(this.fragmentDetailsId, "be.xxxxxxxxxxx.fragment.viewSubassignment", this);
this.getView().addDependent(this._oDetailsDialog);
}
}
this.oAppBC = oAppointment.getBindingContext();
this._oDetailsDialog.setBindingContext(this.oAppBC);
this._oDetailsDialog.open();
this.lastClickedAssignment = oAppointment.getProperty("assignment");
this.lastClickedSubassignment = oAppointment.getProperty("subassignment");
setTimeout(function () {
//SET LOCAL STORAGE
var stringifiedContext = CircularJSON.stringify(oAppointment.getBindingContext());
var stringifiedAssignment = CircularJSON.stringify(oAppointment.getProperty("assignment"));
var stringifiedSubassignment = CircularJSON.stringify(oAppointment.getProperty("subassignment"));
this.setLocalStorage("context", stringifiedContext);
this.setLocalStorage("assignment", stringifiedAssignment);
this.setLocalStorage("subassignment", stringifiedSubassignment);
});
}
},
OR you can also do it after open:
this._oDetailsDialog.attachEventOnce('afterOpen', function () {
//SET LOCAL STORAGE
// ...
});

algolia/instantsearch: connectMenu refine() remove current refined value

Is there any way to REMOVE a refined value with connectMenu’s connector?
These are the things I tried that did not work:
passing an empty string refine('')
passing a null value refine(null)
passing a false value refine(false)
passing no parameter refine()
The reason why I’d like to do this is because otherwise currentRefinedValues widget shows an attribute as refined even if it’s not.
var customMenuRenderFn = function (renderParams, isFirstRendering) {
var container = renderParams.widgetParams.containerNode;
var title = renderParams.widgetParams.title || 'dropdownMenu';
var templates = renderParams.widgetParams.templates;
var hideIfIsUnselected = renderParams.widgetParams.hideIfIsUnselected || false;
var cssClasses = renderParams.widgetParams.cssClasses || "";
if (isFirstRendering)
{
$(container).append(
(templates.header || '<h1>' + renderParams.widgetParams.attributeName + '</h1>') +
'<select class="' + cssClasses.select + '">' +
'<option value="__EMPTY__">Tutto</option>' +
'</select>'
).hide();
var refine = renderParams.refine;
if (! hideIfIsUnselected)
{
$(container).show();
}
else
{
$(hideIfIsUnselected).find('select').on('items:loaded', function () {
if (isFirstRendering) {
var valueToCheck = $(hideIfIsUnselected).find('select').val();
$(container).toggle(valueToCheck !== '__EMPTY__');
$(container).find('select').off('items:loaded');
}
});
$(hideIfIsUnselected).find('select').on('change', function (event) {
var value = event.target.value === '__EMPTY__' ? '' : event.target.value;
if (value === '') {
refine();
}
$(container).toggle(value !== '');
});
}
$(container).find('select').on('change', function (event) {
var value = event.target.value === '__EMPTY__' ? '' : event.target.value;
refine(value);
});
}
function updateHits (hits)
{
var items = renderParams.items;
optionsHtml = ['<option class="' + cssClasses.item + '" value="__EMPTY__" selected>Tutto</option>']
.concat(
items.map(function (item) {
return `<option class="${cssClasses.item}" value="${item.value}" ${item.isRefined ? 'selected' : ''}>
${item.label} (${item.count})
</option>`;
})
);
$(container).find('select').html(optionsHtml);
$(container).find('select').trigger('items:loaded');
}
if (hideIfIsUnselected && $(hideIfIsUnselected).val() !== '__EMPTY__') {
updateHits(renderParams.items);
} else if (! hideIfIsUnselected) {
updateHits(renderParams.items);
}
}
var dropdownMenu = instantsearch.connectors.connectMenu(customMenuRenderFn);
The refine function actually toggles the value (setting it if not set, or unsetting if set). If you want to unselect any item in the menu, you need to find the currently selected value and use refine on it.
connectMenu(function render(params, isFirstRendering) {
var items = params.items;
var currentlySelectedItem = items.find(function isSelected(i) {
return i.isRefined;
});
params.refine(currentlySelectedItem);
});
This example won't solve your code completely, but it shows how to find the currently selected item and unselect it.

Accordion Native Bootstrap

I have a problem with the accordion in Bootstrap Native. Everything works fine except for one thing. After expanding other .collapsed accordion, the class is not added to the former that was developed. I've tried several ways and still nothing. Adding the collapsed class is addClass (element, collapsed); just the other way removeClass ...
Below JS file:
// event targets and constants
var accordion = null, collapse = null, self = this,
isAnimating = false, // when true it will prevent click handlers
accordionData = element[getAttribute]('data-parent'),
// component strings
component = 'collapse',
collapsed = 'collapsed',
test = 'test'
// private methods
openAction = function(collapseElement) {
bootstrapCustomEvent.call(collapseElement, showEvent, component);
isAnimating = true;
addClass(collapseElement,collapsing);
addClass(collapseElement,showClass);
addClass(element,collapsed);
setTimeout(function() {
collapseElement[style][height] = getMaxHeight(collapseElement) + 'px';
(function(){
emulateTransitionEnd(collapseElement, function(){
isAnimating = false;
collapseElement[setAttribute](ariaExpanded,'true');
removeClass(collapseElement,collapsing);
collapseElement[style][height] = '';
bootstrapCustomEvent.call(collapseElement, shownEvent, component);
});
}());
}, 20);
},
closeAction = function(collapseElement) {
bootstrapCustomEvent.call(collapseElement, hideEvent, component);
isAnimating = true;
collapseElement[style][height] = getMaxHeight(collapseElement) + 'px';
setTimeout(function() {
addClass(collapseElement,collapsing);
collapseElement[style][height] = '0px';
(function() {
emulateTransitionEnd(collapseElement, function(){
isAnimating = false;
collapseElement[setAttribute](ariaExpanded,'false');
removeClass(collapseElement,collapsing);
removeClass(collapseElement,showClass);
collapseElement[style][height] = '';
bootstrapCustomEvent.call(collapseElement, hiddenEvent, component);
});
}());
},20);
},
getTarget = function() {
var href = element.href && element[getAttribute]('href'),
parent = element[getAttribute](dataTarget),
id = href || ( parent && targetsReg.test(parent) ) && parent;
return id && queryElement(id);
};
// public methods
this.toggle = function(e) {
e.preventDefault();
if (isAnimating) return;
if (!hasClass(collapse,showClass)) {
self.show();
} else {
self.hide();
}
};
this.hide = function() {
closeAction(collapse);
addClass(element,collapsed);
//jak się zwija dodaje klase
};
this.show = function() {
openAction(collapse);
removeClass(element,collapsed);
//jak się rozwija usuwa klase
if ( accordion !== null ) {
var activeCollapses = getElementsByClassName(accordion,component+' '+showClass);
for (var i=0, al=activeCollapses[length]; i<al; i++) {
if ( activeCollapses[i] !== collapse) closeAction(activeCollapses[i]);
}
}
};
// init
if ( !(stringCollapse in element ) ) { // prevent adding event handlers twice
on(element, clickEvent, this.toggle);
}
collapse = getTarget();
accordion = queryElement(options.parent) || accordionData && getClosest(element, accordionData);
element[stringCollapse] = this;
};
As you can see the code is not added to the previously developed(<a href...) .collapsed accordion.

chrome.serial receiveTimeout Not working.

Below code is a copy with minor edits from https://github.com/GoogleChrome/chrome-app-samples/tree/master/serial/ledtoggle. I am able to send a byte and receive a reply. I am not able to get an TimeoutError event in case of reply is not sent by the client. I have set timeout to 50 ms.
this.receiveTimeout = 50;
Entire code follows.
const DEVICE_PATH = 'COM1';
const serial = chrome.serial;
var ab2str = function(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
var str2ab = function(str) {
var encodedString = unescape((str));
var bytes = new Uint8Array(1);
bytes[0] = parseInt(encodedString);
}
return bytes.buffer;
};
var SerialConnection = function() {
this.connectionId = -1;
this.lineBuffer = "";
this.receiveTimeout =50;
this.boundOnReceive = this.onReceive.bind(this);
this.boundOnReceiveError = this.onReceiveError.bind(this);
this.onConnect = new chrome.Event();
this.onReadLine = new chrome.Event();
this.onError = new chrome.Event();
};
SerialConnection.prototype.onConnectComplete = function(connectionInfo) {
if (!connectionInfo) {
log("Connection failed.");
return;
}
this.connectionId = connectionInfo.connectionId;
chrome.serial.onReceive.addListener(this.boundOnReceive);
chrome.serial.onReceiveError.addListener(this.boundOnReceiveError);
this.onConnect.dispatch();
};
SerialConnection.prototype.onReceive = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.lineBuffer += ab2str(receiveInfo.data);
var index;
while ((index = this.lineBuffer.indexOf('$')) >= 0) {
var line = this.lineBuffer.substr(0, index + 1);
this.onReadLine.dispatch(line);
this.lineBuffer = this.lineBuffer.substr(index + 1);
}
};
SerialConnection.prototype.onReceiveError = function(errorInfo) {
log('Error');
if (errorInfo.connectionId === this.connectionId) {
log('Error');
this.onError.dispatch(errorInfo.error);
log('Error');
}
log('Error');
};
SerialConnection.prototype.connect = function(path) {
serial.connect(path, this.onConnectComplete.bind(this))
};
SerialConnection.prototype.send = function(msg) {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.send(this.connectionId, str2ab(msg), function() {});
};
SerialConnection.prototype.disconnect = function() {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.disconnect(this.connectionId, function() {});
};
var connection = new SerialConnection();
connection.onConnect.addListener(function() {
log('connected to: ' + DEVICE_PATH);
);
connection.onReadLine.addListener(function(line) {
log('read line: ' + line);
});
connection.onError.addListener(function() {
log('Error: ');
});
connection.connect(DEVICE_PATH);
function log(msg) {
var buffer = document.querySelector('#buffer');
buffer.innerHTML += msg + '<br/>';
}
document.querySelector('button').addEventListener('click', function() {
connection.send(2);
});
Maybe I'm reading the code incorrectly, but at no point do you pass receiveTimeout into chrome.serial. The method signature is chrome.serial.connect(string path, ConnectionOptions options, function callback), where options is an optional parameter. You never pass anything into options. Fix that and let us know what happens.

TypeError: 'undefined' is not a function (evaluating 'ime.registIMEKey()')

Despite of setting and defining everything in Samsung smart TV SDK 4.0 I am getting this error:
TypeError: 'undefined' is not a function (evaluating 'ime.registIMEKey()')
Please help!
CODE:
var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();
var wapal_magic =
{
elementIds: new Array(),
inputs: new Array(),
ready: new Array()
};
/////////////////////////
var Input = function (id, previousId, nextId) {
var previousElement = document.getElementById(previousId),
nextElement = document.getElementById(nextId);
var installFocusKeyCallbacks = function () {
ime.setKeyFunc(tvKey.KEY_UP, function (keyCode) {
previousElement.focus();
return false;
});
ime.setKeyFunc(tvKey.KEY_DOWN, function (keyCode) {
nextElement.focus();
return false;
});
ime.setKeyFunc(tvKey.KEY_RETURN, function (keyCode) {
widgetAPI.blockNavigation();
return false;
});
ime.setKeyFunc(tvKey.KEY_EXIT, function (keyCode) {
widgetAPI.blockNavigation();
return false;
});
}
var imeReady = function (imeObject) {
installFocusKeyCallbacks();
wapal_magic.ready(id);
},
ime = new IMEShell(id, imeReady, 'en'),
element = document.getElementById(id);
}
wapal_magic.createInputObjects = function () {
var index,
previousIndex,
nextIndex;
for (index in this.elementIds) {
previousIndex = index - 1;
if (previousIndex < 0) {
previousIndex = wapal_magic.inputs.length - 1;
}
nextIndex = (index + 1) % wapal_magic.inputs.length;
wapal_magic.inputs[index] = new Input(this.elementIds[index],
this.elementIds[previousIndex], this.elementIds[nextIndex]);
}
};
wapal_magic.ready = function (id) {
var ready = true,
i;
for (i in wapal_magic.elementIds) {
if (wapal_magic.elementIds[i] == id) {
wapal_magic.ready[i] = true;
}
if (wapal_magic.ready[i] == false) {
ready = false;
}
}
if (ready) {
document.getElementById("txtInp1").focus();
}
};
////////////////////////
wapal_magic.onLoad = function()
{
// Enable key event processing
//this.enableKeys();
// widgetAPI.sendReadyEvent();
this.initTextBoxes(new Array("txtInp1", "txtInp2"));
};
wapal_magic.initTextBoxes = function(textboxes){
this.elementIds = textboxes;
for(i=0;i<this.elementIds.length;i++){
this.inputs[i]=false;
this.ready[i]=null;
}
this.createInputObjects();
widgetAPI.registIMEKey();
};
wapal_magic.onUnload = function()
{
};
wapal_magic.enableKeys = function()
{
document.getElementById("anchor").focus();
};
wapal_magic.keyDown = function()
{
var keyCode = event.keyCode;
alert("Key pressed: " + keyCode);
switch(keyCode)
{
case tvKey.KEY_RETURN:
case tvKey.KEY_PANEL_RETURN:
alert("RETURN");
widgetAPI.sendReturnEvent();
break;
case tvKey.KEY_LEFT:
alert("LEFT");
break;
case tvKey.KEY_RIGHT:
alert("RIGHT");
break;
case tvKey.KEY_UP:
alert("UP");
break;
case tvKey.KEY_DOWN:
alert("DOWN");
break;
case tvKey.KEY_ENTER:
case tvKey.KEY_PANEL_ENTER:
alert("ENTER");
break;
default:
alert("Unhandled key");
break;
}
};
The registIMEKey method is part of the Plugin API.
var pluginAPI = new Common.API.Plugin();
pluginAPI.registIMEKey();
See: http://www.samsungdforum.com/Guide/ref00006/common_module_plugin_object.html#ref00006-common-module-plugin-object-registimekey
Edit: Updated to add code solution.
widgetAPI no contains method registIMEKey();, it contains in IMEShell.