TinyMCE strip_tags function like php? - tinymce

how can I accept just certain tags and strip_tags all others when paste text to editor? just like php's strip_tags function?
and how can I remove all styles from that tags?
input is a string.

i have a function to this
var strip_tags = function(str,tags,attrs){
var reg2 = /\s*(\w+)=\"[^\"]+\"/gm;
var reg = /<\s*(\w+).*?>/gm;
str = str.replace(reg,function(match, i) {
var r_ = match;
var reg_ = /<\s*(\w+).*?>/gm;
var m_ = reg_.exec(match);
if(m_!=null){
if(tags.indexOf(m_[1])>=0){
r_ = match.replace(reg2,function(match_, i) {
var reg2_ = /\s*(\w+)=\"[^\"]+\"/gm;
var m = reg2_.exec(match_);
if(m!=null){
if(attrs.indexOf(m[1])>=0){
return match_;
}
}
return '';
});
}else{
r_ = '';
}
}else{
r_ = '';
}
return r_;
});
var reg3 = /<\/\s*(\w+).*?>/gm;
str = str.replace(reg3,function(match, i) {
var r_ = match;
var reg_ = /<\/\s*(\w+).*?>/gm;
var m_ = reg_.exec(match);
if(m_!=null){
if(tags.indexOf(m_[1])>=0){
return match;
}
}
return '';
});
return str;
};
tinyMCE.init(
...
plugins: "paste...
paste_preprocess : function(pl, o) {
var allowed_tags = ['ul','li','b','p','table','tr','td'];
var allowed_attributes = ['href','colspan','rowspan'];
o.content = strip_tags(o.content,allowed_tags,allowed_attributes);
},
...
);

Related

How to implement find column values and replace with new value in ag grid(like find and replace)

I am new to ag-grid angular. I want to implement a functionality where i can find each column values and replace with new values in a single column.
As ag-grid does not provide a way to Find/Replace , you can use the below algorithm to do it.
foundCell = [];
foundIndex = 0;
message = '';
//Find text in ag-grid
find(findText: string) {
let found = false;
let rowNodes: any = [];
let focusedCell = this.gridApi.getFocusedCell();
if (focusedCell) {
let lastFoundObj: any;
if (this.foundCell.length > 0) {
lastFoundObj = this.foundCell[this.foundCell.length - 1];
if (!(lastFoundObj.rowIndex == focusedCell.rowIndex && lastFoundObj.field == focusedCell.column.colId)) {
this.foundCell = [];
this.foundIndex = focusedCell.rowIndex;
}
}
}
this.gridApi.forEachNode(function (node,rowIndex) {
rowNodes.push(node);
});
for(let i=this.foundIndex; i < rowColumnData.rowNodes.length ; i++) {
let node = rowColumnData.rowNodes[i];
var rowObj = node.data;
found = false;
for (var key in rowObj) {
if (rowObj[key].includes(findText) && !this.checkIfAlreadyFound(key, node.rowIndex)) {
found = true;
this.foundCell.push({ 'field': key, 'rowIndex': node.rowIndex});
break;
}
}
if (found) {
break;
}
}
if (found) {
let lastFoundCell = this.foundCell[this.foundCell.length-1];
this.gridApi.ensureIndexVisible(lastFoundCell.rowIndex, 'middle');
this.gridApi.ensureColumnVisible(lastFoundCell.field);
this.gridApi.setFocusedCell(lastFoundCell.rowIndex,lastFoundCell.field);
this.found = true;
} else {
this.foundIndex = 0;
this.foundCell = [];
this.found = false;
this.message = 'Not found';
}
}
//Replace text in ag-grid
replace(findText: string, replaceWith: string, isReplaceAll: boolean) {
if (this.found || isReplaceAll) {
let focusedCell: any;
var cell: any;
let rowNodes = [];
focusedCell = this.gridApi.getFocusedCell();
if (focusedCell) {
cell = { rowIndex: focusedCell.rowIndex, field: focusedCell.column.colId };
} else {
cell = this.foundCell[this.foundCell.length - 1];
}
this.gridApi.forEachNode(function (node,rowIndex) {
rowNodes.push(node);
});
var rowNode: any;
var newCellValue: any;
if (isReplaceAll) {
let allfoundCell = this.findAllCells(rowNodes,findText);
for (var i = 0; i < allfoundCell.length; i++) {
cell = allfoundCell[i];
rowNode = gridApi.getDisplayedRowAtIndex(cell.rowIndex);
newCellValue = this.gridApi.getValue(cell.field, rowNode).replace(findText,replaceWith);
rowNode.setDataValue(cell.field, newCellValue);
}
} else {
rowNode = this.gridApi.getDisplayedRowAtIndex(cell.rowIndex);
newCellValue = this.gridApi.getValue(cell.field, rowNode).replace(findText,replaceWith);
if (newCellValue != rowNode.data[cell.field]) {
rowNode.setDataValue(cell.field, newCellValue);
}
}
this.found = false;
}
}

Xtext, transform ascii character to math symboles

How can a xtext editor translate (for example) -> to the latex symbol \rightarrow?
Have a look at the nice feature of autoedit
public class MyDslDefaultAutoEditStrategyProvider extends DefaultAutoEditStrategyProvider {
#Inject
protected Provider<ShortCutEditStrategy> shortCut;
#Override
protected void configureStringLiteral(IEditStrategyAcceptor acceptor) {
acceptor.accept(shortCut.get().configure("->", "\\rightarrow"), IDocument.DEFAULT_CONTENT_TYPE);
}
}
and dont forget the binding
override Class<? extends AbstractEditStrategyProvider> bindAbstractEditStrategyProvider() {
MyDslDefaultAutoEditStrategyProvider
}
It's quite easy using JavaScript. This simple script should help:
replaceText('->', '\rightarrow');
var replaceText = function (search, replaceWith) {
var area = document.getElementById("area");
var getCount = function (str, search) {
return str.split(search).length - 1;
};
if (area.value.indexOf(search) >= 0) {
var start = area.selectionStart;
var end = area.selectionEnd;
var textBefore = area.value.substr(0, end);
var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore, search);
area.value = area.value.replace(search, replaceWith);
area.selectionStart = start + lengthDiff;
area.selectionEnd = end + lengthDiff;
}
};
This full text can be easily adapted for your use- here's a full example.
<textarea id="area"></textarea>
<script>
function keyDownTextField() {
replaceText('->', '\u2192');
}
var replaceText = function (search, replaceWith) {
var area = document.getElementById("area");
var getCount = function (str, search) {
return str.split(search).length - 1;
};
if (area.value.indexOf(search) >= 0) {
var start = area.selectionStart;
var end = area.selectionEnd;
var textBefore = area.value.substr(0, end);
var lengthDiff = (replaceWith.length - search.length) * getCount(textBefore, search);
area.value = area.value.replace(search, replaceWith);
area.selectionStart = start + lengthDiff;
area.selectionEnd = end + lengthDiff;
}
};
document.addEventListener("keydown", keyDownTextField, false);
</script>

after effects - selecting render queue items via script

i'm looking for a way to select items in the render queue via script.
i'm creating a listBox that contains all the RQ items ( i need to list them in a simpler way then the RQ window, and i'm keeping the index number of each item), and i want to select from that list items and select them in the RQ.
ideas?
thanks
Dror
try{
function createUserInterface (thisObj,userInterfaceString,scriptName){
var pal = (thisObj instanceof Panel) ? thisObj : new Window("palette", scriptName,
undefined,{resizeable: true});
if (pal == null) return pal;
var UI=pal.add(userInterfaceString);
pal.layout.layout(true);
pal.layout.resize();
pal.onResizing = pal.onResize = function () {
this.layout.resize();
}
if ((pal != null) && (pal instanceof Window)) {
pal.show();
}
return UI;
};
{var res ="group {orientation:'column',\
alignment:['fill','fill'],\
alignChildren:['fill','top'],\
folderPathListbox:ListBox{\
alignment:['fill','fill'],\
properties:{\
multiline:true,\
multiselect:true,\
numberOfColumns:6,\
showHeaders:true,\
columnTitles: ['#','OM','Date','Time', 'Comp Name', 'Render Path']}\
},\
buttonGroup:Group{orientation:'row',\
alignment:['fill','bottom']\
alignChildren:['fill','bottom'],\
buttonPanel: Panel{\
text:'Actions',\
orientation: 'row',\
alignment:['fill','bottom']\
refButton: Button{text:'Refresh'}\
dupButton: Button{text:'Duplicate'}\
selButton: Button{text:'Select in RQ'}\
expButton: Button{text:'Export'}\
}\
searchPanel: Panel{\
text:'Search',\
orientation: 'row',\
searchBox: EditText{text:'search by fileName'},\
searchButton: Button{text:'Search'}, \
}\
}\
}";
}
function listRQ (rqList){
try{
var folderPathListbox = rqList;
var proj = app.project;
var totalRenderQ = proj.renderQueue.numItems;
for(var i= 1; i<=totalRenderQ; i++){
var totalOM= proj.renderQueue.item(i).numOutputModules;
for (var om= 1; om<=totalOM; om++){
var dateList, timeList, curItem;
if (proj.renderQueue.item(i).startTime != null){
var min = proj.renderQueue.item(i).startTime.getMinutes() <10 ? "0"+ proj.renderQueue.item(i).startTime.getMinutes() : proj.renderQueue.item(i).startTime.getMinutes();
var year = proj.renderQueue.item(i).startTime.getFullYear().toString().substr (-2,2);
timeList = (proj.renderQueue.item(i).startTime.getHours()-1)+":" + min;
dateList =proj.renderQueue.item(i).startTime.getDate()+"/"+(proj.renderQueue.item(i).startTime.getMonth()+1)+"/"+year ;
}else{
dateList = "not ";
timeList = "rendered";
}
curItem = folderPathListbox.add ('item', i ); // Column 1
curItem.subItems[0].text = om; // Column 2
curItem.subItems[1].text = dateList.toString(); // Column 3
curItem.subItems[2].text = timeList.toString(); // Column 4
curItem.subItems[3].text = proj.renderQueue.item(i).comp.name; // Column 5
curItem.subItems[4].text = proj.renderQueue.item(i).outputModule(om).file.toString().replace(new RegExp(",","g"), "\r").replace(new RegExp("%20","g"), " ").replace(new RegExp("%5B","g"), "[").replace(new RegExp("%5D","g"), "]"); // Column 6
}
}
}catch(err){alert(err)}
return folderPathListbox;
}
var UI = createUserInterface(this,res,"Better RQ");
var myList = UI.folderPathListbox;
var lsRq = listRQ(myList);
//~ alert(lsRq.toString());
{ // buttons action
UI.buttonGroup.buttonPanel.refButton.onClick = function () {
lsRq.removeAll();
listRQ(myList);
writeLn("all done");
}
UI.buttonGroup.buttonPanel.dupButton.onClick = function () {
var lstSlct = new Array ;
lstSlct = myList.selection;
if ( lstSlct != null){
var totalDup = lstSlct.length;
for (var i= 0; i<totalDup; i++){
var lsId = lstSlct[i].toString();
var dup = parseInt(lsId);
app.project.renderQueue.item(dup).duplicate();
writeLn("duplicated #"+dup);
}
}else{
alert ("select Something");
}
}
UI.buttonGroup.buttonPanel.selButton.onClick = function () {
app.project.renderQueue.showWindow(true) ; //shows the RQ
alert ("selButton");
}
UI.buttonGroup.buttonPanel.expButton.onClick = function () {
// var compName = myList.
alert ("expButton");
}
}
}
catch(err){
alert ("Error at line # " + err.line.toString() + "\r" + err.toString());
}

File Uploader - Upload excel file and convert it into JSON and bind to the table

After uploading the excel file on file uploader control in sapui5, excel file is converted in to JSON using following code.
handleExcelUpload : function(e) {
this._import(e.getParameter("files")
&& e.getParameter("files")[0]);
},
_import : function(file) {
if (file && window.FileReader) {
var reader = new FileReader();
that = this;
result = {};
var data;
reader.onload = function(e) {
var data = e.target.result;
var wb = XLSX.read(data, {
type : 'binary'
});
wb.SheetNames
.forEach(function(sheetName) {
var roa = XLSX.utils
.sheet_to_row_object_array(wb.Sheets[sheetName]);
if (roa.length > 0) {
result[sheetName] = roa;
}
});
};
reader.readAsBinaryString(file);
};
},
Note : I have used jszip.js and xlsx.js library to convert excel to JSON
Now in result variable I am getting JSON format data, and this data I have bind to the table.
The issue is, JSON binding with table is working fine with the Chrome, Firefox latest browser but, its not working on in IE 11 browser or it's showing only No data in table
Is there any other file reader method which supports IE11?
Yes I got answer.. I found readAsArrayBuffer method in Javascript which is compatible for all latest browser even in IE11
Here is my working code.
XML code:
<FileUploader id="fileUploader" name="myFileUpload"
class="sapUiSmallMarginEnd" uploadUrl="upload/" width="400px"
tooltip="Upload your file to the local server" uploadComplete="handleUploadComplete"
change="handleExcelUpload" placeholder="Please Select File" />
JS code:
handleExcelUpload : function(e) {
this._import(e.getParameter("files")
&& e.getParameter("files")[0]);
},
_import : function(file) {
debugger;
if (file && window.FileReader) {
var reader = new FileReader();
that = this;
//result = {};
//var data;
reader.onload = function(evt) {
var data = evt.target.result;
//var xlsx = XLSX.read(data, {type: 'binary'});
var arr = String.fromCharCode.apply(null, new Uint8Array(data));
var xlsx = XLSX.read(btoa(arr), {type: 'base64'});
result = xlsx.Strings;
result = {};
xlsx.SheetNames.forEach(function(sheetName) {
var rObjArr = XLSX.utils.sheet_to_row_object_array(xlsx.Sheets[sheetName]);
if(rObjArr.length > 0){
result[sheetName] = rObjArr;
}
});
return result;
that.b64toBlob(xlsx, "binary");
};
reader.readAsArrayBuffer(file);
};
},
b64toBlob : function(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
b64Data = b64Data.replace(/^[^,]+,/, '');
b64Data = b64Data.replace(/\s/g, '');
var byteCharacters = Base64.decode(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length;offset += sliceSize){
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {
type : contentType
});
}
After this add the base64 util
var Base64 = {}; // Base64 namespace
Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
Base64.encode = function(str, utf8encode) {
utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? Utf8.encode(str) : str;
c = plain.length % 3;
if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } }
for (c=0; c<plain.length; c+=3) {
o1 = plain.charCodeAt(c);
o2 = plain.charCodeAt(c+1);
o3 = plain.charCodeAt(c+2);
bits = o1<<16 | o2<<8 | o3;
h1 = bits>>18 & 0x3f;
h2 = bits>>12 & 0x3f;
h3 = bits>>6 & 0x3f;
h4 = bits & 0x3f;
e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
}
coded = e.join('');
coded = coded.slice(0, coded.length-pad.length) + pad;
return coded;
}
Base64.decode = function(str, utf8decode) {
utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? Utf8.decode(str) : str;
for (var c=0; c<coded.length; c+=4) {
h1 = b64.indexOf(coded.charAt(c));
h2 = b64.indexOf(coded.charAt(c+1));
h3 = b64.indexOf(coded.charAt(c+2));
h4 = b64.indexOf(coded.charAt(c+3));
bits = h1<<18 | h2<<12 | h3<<6 | h4;
o1 = bits>>>16 & 0xff;
o2 = bits>>>8 & 0xff;
o3 = bits & 0xff;
d[c/4] = String.fromCharCode(o1, o2, o3);
// check for padding
if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
}
plain = d.join(''); // join() is far faster than repeated string concatenation in IE
return utf8decode ? Utf8.decode(plain) : plain;
}
Try this, without external library:
/*In the function "Press" */
var file = oFileUploader.getFocusDomRef().files[0];
if (file && window.FileReader) {
var reader = new FileReader();
var that = this;
reader.onload = function(e) {
var strCSV = e.target.result;
var arrCSV = strCSV.replace(/['",]/g, '').split(/[↵\n]+/).join(';').split(';');
var noOfCols = 11; // 11 Columns
var hdrRow = arrCSV.splice(0, noOfCols);
var oData = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols)
if (row.length > 1) {
for (var i = 0; i < row.length; i++) obj[hdrRow[i].replace(/\r/g, "")] = row[i].trim();
oData.push(obj) // Data Json
}
}
oTable.setModel(new sap.ui.model.json.JSONModel(oData)); // Binding model
};
reader.readAsText(file, 'ISO-8859-1');
}
Regards.
Check the code in my gist
Upload_CSV.js
Place this in the controller to parse the file using JS client side
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "ItemsJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 3;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
data.reverse();
var json = JSON.stringify(data); // send to the backend
if I did not answer you please tell me

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.