How to find if user has selectedwhole text or a part of text in tiny mce - tinymce

I want to check the node of the selected text. If it is span, another function will edit the classes applied to it. If it is same as the parent node, then the code will wrap the selection in span and set its styles. The problem here I'm facing is, how to determine, if user has selected the whole text inside the editor or only some text. If user selects the whole text, I want to apply the styles to the parent node instead of adding a new span and styles to it. Below is my code -
var ed=tinyMCE.getInstanceById('textAreaId');
var sel = ed.selection.getContent();
if(trim(sel)!="") {
//get the node of the selection
var thisNode=tinyMCE.activeEditor.selection.getStart().nodeName;
ed_Property=propertyName;
ed_PropertyVal=propertyValue;
//get the root node inside editor
var parentNode=tinyMCE.activeEditor.getBody().firstChild.nodeName;
if(thisNode=="SPAN") {
nodeclass=$(tinyMCE.activeEditor.selection.getNode()).attr('class');
//edit span properties
editSpanProperties(nodeclass,propertyName,propertyValue);
}
else if(thisNode==parentNode) {
var elmType="span";
var Spanid1=createSpanId(targetToStyle,elmType);
Spanid=targetToStyle+"_"+elmType+"_"+Spanid1;
var strStyle=ed_Property+":"+ed_PropertyVal;
//wrap selection in a span
sel = "<span id='"+Spanid+"' style='"+strStyle+"'>" + sel + "</span>";
//set content
ed.selection.setContent(sel);
//retain the selection
ed.selection.select(ed.dom.select('#'+Spanid)[0],false);
}
else {
//here I need to check if user has selected whole text and set properties
setStylesOnEditor(templateSection,propertyName,propertyValue);
}//if ends
}
else if(trim(sel)=="") {
alert('No text selected');
}

how to determine, if user has selected
the whole text inside the editor or
only some text.
You need to compare the selected text with the editors content:
var content_editor = $(ed.getBody()).text();
var content_selection = ed.selection.getContent({format : 'text'});
// now compare both either characterwise or as whole string,
// you might need to strip whitespace characters from the strings!
// and do what you want to do in each case

Related

Text style in google script TextItem title

I have written an app to automatically update an order form everytime an order is passed. Currently, the form consists in N Textitems, which titles are like:
Product (remains : [number of remaining products])
Product description
This is performed by the following lines :
var Products= wsStocks.getRange(1,1,wsStocks.getLastRow(),1).getValues();
var Description = wsStocks.getRange(1,2,wsStocks.getLastRow(),2).getValues();
var Qtys = wsStocks.getRange(1,3,wsStocks.getLastRow(),3).getValues();
for(j=0;j<Products.length;j++){
Items[j].setTitle( `${Products[j][0]} (remains: ${Qtys[j][0]})`+ "\n" +`${Description[j][0]}`;
};
I would like to set a text style for this title : I want the information on the number of remaining products to be in italic, and the description to be in small size. But while I have found how to set the style for a Text variable, I can't find how to do this for a string used in the setTitle method ?
You should get the Range of each item from the Items array first and then you should be able to change the TextStyle according to your needs by using the setTextStyle() method.
For customizing the text styles, you can create your own, something similar to this.
// italic text style
var style1 = SpreadsheetApp.newTextStyle()
.setFontSize(14)
.setItalic(true)
.build();
// small size text style
var style2 = var style = SpreadsheetApp.newTextStyle();
.setFontSize(11)
.build();
Afterwards, for each element of the Items array, you should do this
for(j = 0; j < Products.length; j++)
sheet.getRange("RANGE_OF_Items[j]_ELEMENT").setTextStyle(style1); //or style2
Reference
Apps Script Class TextStyle;
Apps Script Range Class - setTextStyle(style).

Kendo Editor Text Click(select event)

I am using a kendo editor and I have a select event
function onselect(e) {
var editor = e.sender;
var selection = editor.getSelection();
var selectedNode = selection.anchorNode;
var targetelement = $(selectedNode).closest("[contenteditable='false']");
}
Problem is when I click a single character then I am not getting the correct selected node and when I click any text(more than one character) I am getting proper selected node.

How to remove selection after replace in vscode API

while creating an extension for vscode I got stuck in selection, now the problem is when I replace some range of textEditor through an api it replaces that range as well as make that range selected. For snippets this is a good idea but my extension requirement is not to select replaced text, I searched in api but did't find anything related to remove text selection (Selection occurs when the document is empty)
editor.edit((editBuilder)=>{ //editor is an object of active text editor
editBuilder.replace(textRange,text) // text = 'dummydummydummy'
}) //after this I got the following output
editor.edit(builder => {
builder.replace(selection, newStr);
})
// The edit call returns a promise. When that resolves you can set
// the selection otherwise you interfere with the edit itself.
// So use "then" to sure edit call is done;
.then(success => {
console.log("success:", success);
// Change the selection: start and end position of the new
// selection is same, so it is not to select replaced text;
var postion = editor.selection.end;
editor.selection = new vscode.Selection(postion, postion);
});
I believe that this is happening because the edit is being applied within the current selection. edit returns a promise that is resolved when the edit is applied, and you can use this to set the selection after the edit is successful:
editor.edit((editBuilder) => {
editBuilder.replace(textRange, text)
}).then(success => {
if (success) {
// make selection empty
editor.selection.active = editor.selection.anchor
}
})
let editor = vscode.window.activeTextEditor;
let selection = editor.selection;
editor.edit(builder => {
builder.replace(selection, newStr);
});
see: TextEditorEdit API Doc

How to remove ContentEdit.Static element in ContentTools

I created a new tool in ContentTools that adds a static table (I don't want you to edit).
But being a static element doesn't maintain focus and I can not remove it when I click remove button.
I can do so that the table is not editable but can be removed if you click on it?
That's how I created the element:
new ContentEdit.Static('div', {'data-ce-moveable': true}, '<table><thead><tr><th>Foo head</th></tr></thead><tbody><tr><td>Foo body</td></tr></tbody></table>')
Thank you!
Static elements can't be interacted with for the most part (other elements can be dragged around them but that's about it). ContentEdit/Tools does allow you to restrict the some behaviour for elements but not being able to modify the content of a text element isn't one right now (though I think this might be a worthy addition).
However whilst there's no set way to do this at the moment here's an approach you can use that should provide the behaviour you describe (do let me know how you get on):
ContentEdit.Root.get().bind('mount', function(element) {
// We only care about `TableCell` elements
if (element.type() != 'TableCell') {
return;
}
// We only want to make the element read-only if the parent table has
// the `data-read-only` attribute.
var table = element.closest(function(node) {
return node.type() == 'Table';
});
if (table.attr('data-read-only') !== undefined) {
// Disable text editing for the table cell
element.tableCellText()._onKeyDown = function(ev) {
ev.preventDefault();
}
}
// Disable dragging of the table rows
var tableRow = element.closest(function(node) {
return node.type() == 'TableRow';
});
tableRow.can('drag', false);
tableRow.can('drop', false);
});

Inserting a new text at given cursor position

I am working on customizing the codemirror for my new language mode. As part of this new mode implementation, I am writing a new tool bar where user can select some text and say insert. This command should insert the text where user was typing just before clicking on tool bar.
I could not find any API level support to do so. If there is any other way can someone help me out on this?
Basically get the current cursor positio- line number and position at which cursor is currently present. May be a Position object
API for inserting a text, something like insertText("Text", PositionObject)
Here's how I did it:
function insertTextAtCursor(editor, text) {
var doc = editor.getDoc();
var cursor = doc.getCursor();
doc.replaceRange(text, cursor);
}
How about replaceSelection (http://codemirror.net/doc/manual.html#replaceSelection)?
doc.replaceSelection(replacement: string, ?select: string)
Replace the selection(s) with the given string. By default, the new selection ends up after the inserted text. The optional select argument can be used to change this—passing "around" will cause the new text to be selected, passing "start" will collapse the selection to the start of the inserted text.
To add the new line at the end -
function updateCodeMirror(data){
var cm = $('.CodeMirror')[0].CodeMirror;
var doc = cm.getDoc();
var cursor = doc.getCursor(); // gets the line number in the cursor position
var line = doc.getLine(cursor.line); // get the line contents
var pos = { // create a new object to avoid mutation of the original selection
line: cursor.line,
ch: line.length - 1 // set the character position to the end of the line
}
doc.replaceRange('\n'+data+'\n', pos); // adds a new line
}
Call function
updateCodeMirror("This is new line");
Improved function that, if selection present, replaces the text, if not, inserts in current cursor position
function insertString(editor,str){
var selection = editor.getSelection();
if(selection.length>0){
editor.replaceSelection(str);
}
else{
var doc = editor.getDoc();
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}
}
You want to use the replaceRange function. Even though the name says "replace", it also serves as "insert" depending on the arguments. From the documentation at the time I write this:
Replace the part of the document between from and to with the given
string. from and to must be {line, ch} objects. to can be left off to
simply insert the string at position from. When origin is given, it
will be passed on to "change" events, and its first letter will be
used to determine whether this change can be merged with previous
history events, in the way described for selection origins.
Final function to insert text at current cursor position in a performant way.
Hope it helps.
function insertStringInTemplate(str)
{
var doc = editor_template.getDoc();
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}
This function is used to insert to the specified position and move the cursor to the end of the inserted text.
function insertToCodeMirror(text) {
const doc = codeMirrorInstance.getDoc();
const cursor = codeMirrorInstance.getCursor();
doc.replaceRange(text, cursor);
codeMirrorInstance.focus();
setTimeout(() => {
cursor.ch += text.length;
codeMirrorInstance.setCursor(cursor);
}, 0);
}