How to get tags around selected text in a contenteditable? - range

I'm trying to do an handler for applying certain formatting style (bold/cursive) at the click of respective button.
In particular, I want to handle selection of text: I want to toggle tags in a selection (tags are combinable).
I tried this way, but I think there should be better ideas. I found the nearest container to selected text, than I found all of its ancestors inside textarea.
var selection = document.getSelection();
var selectedText = selection.toString();
var range = selection.getRangeAt(0).cloneRange();
var firstTag = $("#textarea-ce *:contains("+selectedText+")");
var currNode = firstTag;
var newNode = $(document.createTextNode(selectedText))[0];
var currTagName;
var currTag;
var lastTag = false;
var found = false;
while (!lastTag) {
currTagName = $(currNode).prop('tagName').toLowerCase();
currTag = $("<"+currTagName+"><"+currTagName+"/>")[0];
if (currTagName != selectedTagName){
newNode = $(currTag).html(newNode);
}
else {
found = true;
}
if ($(currNode).parent().attr('id') == 'textarea-ce') {
lastTag = true;
}
else {
currNode = $(currNode).parent();
}
}
currNode = $(textarea).find(currNode)[0];
var newNodeContent = $(newNode).html();
if (!found) {
newNodeContent = "<"+selectedTagName+">"+newNodeContent+"<"+selectedTagName+"/>";
newNode = $(selectedTag).html($(newNode));
}
if (currTagName.startsWith("h")){
$(currNode).html(newNodeContent);
range.insertNode(currNode);
}
else {
$(currNode).replaceWith(newNode);
}
I used header (h1, h2,...) displayed as inline for sizing text.
In order to get surrounding tags I tried also with documentFragment (range.extractContents) but after a selection, sometimes it doesn't include tags, but only the text node.
The hardest challenge is to handle the case in which the user selects part of a formatted text and removes one of those tags.
Any suggestion is appreciated.

Related

How can I export AgGrid data in case of infinite row model (infinite scrolling) in react

How can I export AgGrid data in case of infinite row model (infinite scrolling) in react.
For the normal row models it is being done in this way:
this.gridOptions.api.exportDataAsCsv(params);
What about infinite row model case?
Here is the solution that I've implemented.
Grid footers, multiple headers is not considered here.
This code is for simple grid with headers and rows under it.
In case of infinite scrolling and dynamic columns (in some cases columns can be changed).
var LINE_SEPARATOR = '\r\n';
var COLUMN_SEPARATOR = ',';
var fileName = 'export.csv';
let csvString = '';
let columnsToExport = this.gridOptions.api.columnController.getAllDisplayedColumns();
// adding column headers.
columnsToExport.map((column) => {
csvString+= column.colDef.headerName;
csvString+= COLUMN_SEPARATOR;
});
csvString+= LINE_SEPARATOR;
// adding content of data currently loaded in the grid.
this.gridOptions.api.forEachNode( function(node) {
node.columnController.allDisplayedColumns.map((column) => {
let cellContent = node.valueService.getValue(column, node);
csvString+= (cellContent != null) ? cellContent : "";
csvString+= COLUMN_SEPARATOR;
});
csvString+= LINE_SEPARATOR;
});
// for Excel, we need \ufeff at the start
var blobObj = new Blob(["\ufeff", csvString], {
type: "text/csv;charset=utf-8;"
});
// Internet Explorer
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blobObj, fileName);
}
else {
// Chrome
var downloadLink = document.createElement("a");
downloadLink.href = window.URL.createObjectURL(blobObj);
downloadLink.download = fileName;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}

itextsharp: words are broken when splitting textchunk into words

I want to highlight several keywords in a set of PDF files. Firstly, we have to identify the single words and match them with my keywords. I found an example:
class MyLocationTextExtractionStrategy : LocationTextExtractionStrategy
{
//Hold each coordinate
public List<RectAndText> myPoints = new List<RectAndText>();
List<string> topicTerms;
public MyLocationTextExtractionStrategy(List<string> topicTerms)
{
this.topicTerms = topicTerms;
}
//Automatically called for each chunk of text in the PDF
public override void RenderText(TextRenderInfo renderInfo)
{
base.RenderText(renderInfo);
//Get the bounding box for the chunk of text
var bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
var topRight = renderInfo.GetAscentLine().GetEndPoint();
//Create a rectangle from it
var rect = new iTextSharp.text.Rectangle(
bottomLeft[Vector.I1],
bottomLeft[Vector.I2],
topRight[Vector.I1],
topRight[Vector.I2]
);
//Add this to our main collection
//filter the meaingless words
string text = renderInfo.GetText();
this.myPoints.Add(new RectAndText(rect, renderInfo.GetText()));
However, I found so many words are broken. For example, "stop" will be "st" and "op". Are there any other method to identify a single word and its position?
When you want to collect single words and their coordination, the better way is to override the existing LocationTextExtractionStrategy. Here is my code:
public virtual String GetResultantText(ITextChunkFilter chunkFilter){
if (DUMP_STATE) {
DumpState();
}
List<TextChunk> filteredTextChunks = filterTextChunks(locationalResult, chunkFilter);
filteredTextChunks.Sort();
List<RectAndText> tmpList = new List<RectAndText>();
StringBuilder sb = new StringBuilder();
TextChunk lastChunk = null;
foreach (TextChunk chunk in filteredTextChunks) {
if (lastChunk == null){
sb.Append(chunk.Text);
var startLocation = chunk.StartLocation;
var endLocation = chunk.EndLocation;
var rect = new iTextSharp.text.Rectangle(startLocation[0], startLocation[1], endLocation[0], endLocation[1]);
tmpList.Add(new RectAndText(rect, chunk.Text));
} else {
if (chunk.SameLine(lastChunk)){
// we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
if (IsChunkAtWordBoundary(chunk, lastChunk) && !StartsWithSpace(chunk.Text) && !EndsWithSpace(lastChunk.Text))
{
sb.Append(' ');
if (tmpList.Count > 0)
{
mergeAndStoreChunk(tmpList);
tmpList.Clear();
}
}
sb.Append(chunk.Text);
var startLocation = chunk.StartLocation;
var endLocation = chunk.EndLocation;
var rect = new iTextSharp.text.Rectangle(startLocation[0], startLocation[1], endLocation[0], endLocation[1]);
////var topRight = renderInfo.GetAscentLine().GetEndPoint();
tmpList.Add(new RectAndText(rect,chunk.Text));
} else {
sb.Append('\n');
sb.Append(chunk.Text);
}
}
lastChunk = chunk;
}
return sb.ToString();
}
private void mergeAndStoreChunk(List<RectAndText> tmpList)
{
RectAndText mergedChunk = tmpList[0];
int tmpListCount = tmpList.Count();
for (int i = 1; i < tmpListCount; i++)
{
RectAndText nowChunk = tmpList[i];
mergedChunk.Rect.Right = nowChunk.Rect.Right;
mergedChunk.Text += nowChunk.Text;
}
this.myPoints.Add(mergedChunk);
}
myPoints is a list, which will return all we want.

Google apps script listbox event processing, undefined value

The idea of this apps script is to populate listbox LbxJobs based on the selected item in listbox LbxJobTypes.
I am getting an undefined value for e.parameter.LbxJobType which seems to be preventing conditional population of LbxJobs.
I successfully tested the handler(JobTypeValueHandler) by hard coding(I set JobType=T300_JOB_TYPE) JobTypeValueHandler function and the LbxJobs listbox populated as expected.
I do get "LbxJobType" when checking e.parameter.source. The listboxes were created in GUI builder.
var T200_JOB_TYPE = 1;
var T300_JOB_TYPE = 2;
function doGet() {
var app = UiApp.createApplication();
app.add(app.loadComponent("BasicCalculator"));
var Dischandler = app.createServerHandler('DiscClickHandler');
app.getElementById('chbxDiscl').addValueChangeHandler(Dischandler);
return app;
}
function DiscClickHandler(e) {
var app = UiApp.getActiveApplication();
var Discpanel = app.getElementById('FLpnlDisc');
BCalcSetup(app);
Discpanel.setVisible(false);
return app;
}
function BasicClickHandler(e) {
var app = UiApp.getActiveApplication();
return app;
}
function BCalcSetup(app){
var BCalcpanel = app.getElementById('APnlBCalc');
var lbxJobType = app.getElementById('LbxJobType');
var JobTpyehandler = app.createServerChangeHandler('JobTypeValueHandler');
var lbxJobs = app.getElementById('LbxJobs');
JobTpyehandler.addCallbackElement(lbxJobType);
lbxJobType.addChangeHandler(JobTpyehandler);
lbxJobType.addItem('Title 200');
lbxJobType.addItem('Title 300');
loadClassifications(lbxJobs,T200_JOB_TYPE);
BCalcpanel.setVisible(true);
}
function JobTypeValueHandler(e) {
var app = UiApp.getActiveApplication();
var JobType=T200_JOB_TYPE;
var lboxJobs=app.getElementById('LbxJobs');
if (e.parameter.LbxJobType=='Title 300'){JobType=T300_JOB_TYPE;}
loadClassifications(lboxJobs,JobType);
app.close();
return app;
}
function loadClassifications(lbox,JobType){
var spreadsheet = SpreadsheetApp.openById(SPREADSHEET_ID);
lbox.clear();
if (JobType==T300_JOB_TYPE){
var T3data =spreadsheet.getRangeByName('Title300Jobs').getValues();
for (var row1 = 1; row1 < T3data.length; row1++) {
lbox.addItem(T3data[row1]);
}
}else{
var T2data =spreadsheet.getRangeByName('Title200Jobs').getValues();
for (var row2 = 1; row2 < T2data.length; row2++) {
lbox.addItem(T2data[row2]);
}
}
}
I feel kind of silly but I figured this out. The problem I had was I did not fill in the Name property for these listboxes when I created the interface in GUI builder. I went back into GUI builder and filled in the name property for each box and and now it works like a champ. Live and learn

execCommand without a selection? (set font, size etc)

I can get my custom WYSIWYG editor to apply styling to selected text no problem:
pnlDocumentEditor_IFrame.document.execCommand(cmd, ui, opt)
.. but what I need to be able to do is allow the user to set a font, or font size, or bold etc so that text typed AFTER this command is issued will have that style applied.
Is this possible? All execCommands I've tried seem to only work on selected text.
Appling execCommand on certain element, WITHOUT selecting it with mouse, can be done with this function:
jsFiddle example
function execCommandOnElement(el, commandName, value) {
if (typeof value == "undefined") {
value = null;
}
if (typeof window.getSelection != "undefined") {
// Non-IE case
var sel = window.getSelection();
// Save the current selection
var savedRanges = [];
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
savedRanges[i] = sel.getRangeAt(i).cloneRange();
}
// Temporarily enable designMode so that
// document.execCommand() will work
document.designMode = "on";
// Select the element's content
sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
// Execute the command
document.execCommand(commandName, false, value);
// Disable designMode
document.designMode = "off";
// Restore the previous selection
sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedRanges.length; i < len; ++i) {
sel.addRange(savedRanges[i]);
}
} else if (typeof document.body.createTextRange != "undefined") {
// IE case
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.execCommand(commandName, false, value);
}
}
And example usage:
var testDiv = document.getElementById("test");
execCommandOnElement(testDiv, "Bold");
execCommandOnElement(testDiv, "ForeColor", "red");
Source: set execcommand just for a div

SuperBoxSelect: Using Shift+Click to Select Multiple Items at Once

When implementing SuperBoxSelect (http://www.sencha.com/forum/showthread.php?69307-3.x-Ext.ux.form.SuperBoxSelect), I've realized that it currently does not support shift + click selection of multiple items. Has anyone been able to implement this functionality or found a similar plugin that offers this functionality?
beforeadditem:function(self, recordValue) {
var start = 0;
var end = 0;
var record = this.findRecord(this.valueField, recordValue);
var recordIndex = this.store.indexOf(record);
if(window.event.shiftKey) {
this.multiSelectMode = true;
if(this.firstChoiceIndex == undefined) {
this.firstChoiceIndex = recordIndex;
this.view.all.item(recordIndex).addClass('x-combo-selected-shift');
return false;
} else {
this.secondChoiceIndex = recordIndex;
if(this.firstChoiceIndex > this.secondChoiceIndex) {
start = this.secondChoiceIndex;
end = this.firstChoiceIndex;
} else if(this.secondChoiceIndex > this.firstChoiceIndex) {
start = this.firstChoiceIndex;
end = this.secondChoiceIndex;
}
var selectedRecords = this.store.getRange(start, end);
Ext.each(selectedRecords, function(item, index, allitems) {
self.addRecord(item)
});
this.firstChoiceIndex = undefined;
this.secondChoiceIndex = undefined;
return false;
}
} else {
this.firstChoiceIndex = undefined;
this.secondChoiceIndex = undefined;
return true;
}
}
Add that listener and it works. The x-combo-selected-shift class is identical to the x-combo-selected class. It's just named different so the highlighting sticks to the item you shift+clicked on after you mouse out.