Rangy: Creating a new highlight is remembering the old highlight - javascript

I am using the highlighter module in Rangy.
I have a div element, which has some html. The html is actually loaded from a file using ajax, I have a button which does this loading.
Once the text is loaded, I can select a portion of the displayed html and press my "Highlight" button. This calls some Rangy code and highlights the text as desired...
//called on document load
rangy.init();
cssApplier = rangy.createCssClassApplier(highlightClassName, { normalize: true });
highlighter = rangy.createHighlighter(document, "TextRange");
highlighter.addClassApplier(cssApplier);
//called on "Highlight" button click
highlighter.highlightSelection(highlightClassName, selection);
For the purpose of replicating, please select a large portion for first highlight.
Next, I click my load html button to reload the html. The highlight is gone, as expected. But now I select another bit of text, which happens to overlap the first highlight that I did. Now when I press the "Highlight" button, for some reason the highlight is the one from the previous highlight. Why is this happening?
I know there must be something to do with the merging, but I can't understand why. When I debug the JS I can see that the selection (from rangy.getSelection()) is what I expect it to be.
Here is a JSFiddle replication of the problem

The reason this is happening is because each highlight exists as a pair of character offsets rather than having references to actual ranges in the DOM, meaning that when some part of the DOM is replaced, existing highlights remain blissfully unaware and continue to assume they are applied to the original character range.
Your workaround is fine. Another way would be to call the highlighter's removeHighlights() method:
highlighter.removeHighlights(highlighter.highlights);
Demo: http://jsfiddle.net/8pMEt/1/
I'm going to add a removeAllHighlights() method that will do the same thing.
One thing that the documentation doesn't make clear is that highlighting is designed to work on static DOMs, or at least DOMs with text content that doesn't change. Changing the DOM after highlights have been created could obviously throw character offsets off and the whole thing falls down.

I solved this problem by re-creating the highlighter prior to each highlightSelection call. I don't know why this works, but the highlighter must store some data regarding previous highlights that is uses for highlight merging or something.
The code in my question can be changed as follows to solve the problem:
//called on document load
rangy.init();
cssApplier = rangy.createCssClassApplier(highlightClassName, { normalize: true });
//called on "Highlight" button click
highlighter = rangy.createHighlighter(document, "TextRange");
highlighter.addClassApplier(cssApplier);
highlighter.highlightSelection(highlightClassName, selection);

Related

Using a Chrome extension to replace characters spanning more than one line in a Facebook status update

I have created a Google Chrome extension to allow users to select text in a component. This works great for most sites. However, Facebook handles its status updates differently. It seems that even though you are filling in what seems to be a single text box, it is actually using a div > div > span > span construct for every single line in this text box. I have no idea why they chose to do this but it makes replacing multiple lines of text much more complex.
Is there a way to select multiple lines (or even contiguous portions of multiple lines) of text in a Facebook status update and replace the data?
The relevant portion of my code looks like this:
function replace_text(language){
let selection = window.getSelection();
string = selection.toString();
/* This section contains code that uses string.replace to replace characters in the string. */
document.execCommand("insertText", false, string);
}
Based on the way my code works now, if I replace text on a single line I have no problems. But, if I replace text that spans multiple lines I end up with a blank unusable input box. Undoubtedly it is because it is removing portions of the html code. How can I fix my code so that the replacement process works properly not only for other sites but also for Facebook?
As of this moment, the one common theme among all status updates (and comments) are that their texts reside within a single or set of span elements with the attribute data-text set to true. So let's target those:
document.querySelectorAll("span[data-text='true']");
For me, I've typed into the status field 3 lines and comment field 1 line of dummy text. So when I execute the above code into the console it returns an array of those four cumulative lines:
>>> (4) [span, span, span, span]
With that array, I can use the Array.prototype.forEach() method to iterate through the spans and replace the innerText:
document.querySelectorAll("span[data-text='true']").forEach(function(element) {
element.innerText = element.innerText.replace('Lorem ipsum','Hello world');
});
However, it is important to note that these changes are being made in the HTML itself and Facebook doesn't store all of its data directly in the HTML. Therefore it can cause undesirable events to occur when you type text into a field, unfocus, change the text in the field, and refocus that field. When you refocus I believe it grabs data of what the text was, before you unfocused that field, from an ulterior source like React's Virtual DOM. To deter it from doing that, the changes either need to be made after clicking the field (real or simulate) or as the user is typing using some sort of MutationObserver (src).

Custom action links in .PDF...write Javascript to alter the appearance of links when clicked?

I have a .pdf document that contains custom links which run Javascript code.
There is no issue with the actual functionality of the working portion of the JS, but I do have one formatting/display problem that I havent been able to solve:
Is it possible to write JS that will alter the appearance of individual links as they are clicked?
I know I can programmatically change the appearance of all links on a page by looping through the doc.getLinks result and applying formatting changes to each element of the getLinks array. But I don't know how to refer to a specific link, as/after it's clicked, either by referencing that link's index location within the getLinks array, or by referring to it by any other name, handle, etc.
I would think that this is probably possible to do, but I'm at a loss.
Thanks in advance for any pointers!
EDIT: One thing to clarify...I can do everything I need to do for a single button. That is, I can manually find the button name, and manually enter the JS code to change the appearance of that particular button. To do this, I need to physically look up the name of the button using a few mouse clicks, and then hard code that button's name in my JS getField command. This requires different code for each and every button.
Is it possible to accomplish the same function using the same code for each and every button?
My ultimate objective is to be able to reproduce this function on a series of .pdf files that will, jointly, have thousands of individual buttons. So any manual component of this process will make implementation impractical.
I should have originally phrased the question in terms of, is it possible to write JS code that can automatically detect the name of the button which is calling the code? (ie, how would I implement a self-referential feature for a generic button?)
As wished by the OP…
When a script should refer to the field on which it is running, the field object to use is event.target.
An example:
You have a button which, when clicked, should change the width of the border between 1 and 3. The mouseUp event would containt this piece of code:
if (event.target.lineWidth == 1) {
event.target.lineWidth = 3 ;
} else {
event.target.lineWidth = 1 ;
}
Or another example: when the number in the calculated text field is negative, it should be in red, otherwise in black:
In the Format event of that field, you would add:
if (event.value*1 < 0) {
event.target.textColor = color.red ;
} else {
event.target.textColor = color.black ;
}
And that should give an idea on how to use event.target.

Updating a text box with javascript

I am having some trouble with some javascript and how it can control the html "text box".
First, here's what I have;
javascript:
function UpdateOrder()
{
// enable/disable appropriate buttons
document.getElementById("reset").disabled=false;
document.getElementById("add").disabled=false;
document.getElementById("submit").disabled=false;
document.getElementById("edit").disabled=false;
document.getElementById("update").disabled=true;
// Show display box, 'DispCurOrder'
document.getElementById('all_labels').disabled=true;
}
function EditOrder()
{
// enable/disable appropriate buttons
document.getElementById("reset").disabled=true;
document.getElementById("add").disabled=true;
document.getElementById("submit").disabled=true;
document.getElementById("edit").disabled=true;
document.getElementById("update").disabled=false;
document.getElementById('all_labels').disabled=false;
}
The Idea is simple... I have some buttons and inputs to generate a 'line' of text that get's dumped to the disabled text box. If the operator notices that they made a type-o or want to change something, they click on 'edit order' and it disables all the regular buttons, and enables the text box and 'update' button. The 'update order' button reverses this.
Now, when I just use the add lines to the text box, all works well. You can see each line get appended to the text box (there's another java function that does a bunch of error checking and such, but the crux is that it takes the contents of the text box, parses it on the "\n" to an array, then appends the new line of text. It then takes the array and puts it all together as a new string and puts it back into the text box. Here is that portion without all the error checking stuff;
function AppendOrder()
{
// let's set up an error flag.
var AppendError="";
var str1=document.forms["MyForm"].DataEntry1.value;
var str2=document.forms["MyForm"].DataEntry2.value;
if( /* checking variable str1 for errors */)
{
AppendError="Error in str 1 here";
}
if( /* checking variable str1 for errors */)
{
AppendError=AppendError+"Error in str 2 here";
}
// Display the error message, if there are no errors, it will clear what was there.
$('#AppendStatus').html(AppendError);
if(AppendError=="")
{
// it's all good, update the display
// create line of text
curEntry=str1 + " -- " + str2;
// let's get the current order into a list
str=document.getElementById('all_data').innerHTML;
if(str1=="Empty")
{
// make curOrder = to 1 element array of curEntry
var curOrder=[curEntry];
}
else
{
// parse str1 into an array and parse it to curOrder.
// Then push curEntry on the end.
var curOrder=str1.split("\n");
curOrder.push(curEntry);
}
// now we should have an array called 'curOrder[]'. Let's show it
// on the web page.
$('#all_labels').html(curOrder);
}
}
Now, the problem that I'm having is that after I add a line or two (or more) to the display using the 'add' button and then go into the 'edit' mode (where the text box is enabled) and I make all my changes, the 'add' button doesn't work.
Oddly enough, when I press the 'reset' button (which is just a reset button) it then shows all the adds I did after the edit, and the edited stuff is gone.
Now... to the question... is there something I'm not understanding about the text box? Is there some trick I need to do to get it to work? Am I going about this all wrong? Should I be using a different tool for this other than the 'textbox'?
Any help is greatly appreciated!!
Greg
Found the typo in your jsFiddle.
The first thing that I did was to add:
alert('hi there');
to the very top of the script, inside the $(document).ready() wrapper. Note that on jsFiddle you cannot see the document.ready wrapper, it is invisibly included, so just put the alert at top of javascript block as I did (link to my new jsFiddle is at bottom of answer)
Next, I noticed that you are enabling/disabling several controls by referencing them individually by ID. You can reference several controls at one time if they share the same class, so I invented the class="orderentry" and added that attribute to each of those controls. This removed 8 lines of code, which made troubleshooting easier.
Then, I began deleting/undeleting. First, I deleted everything in the javascript panel except alert('hi there');, and ran the jsFiddle. The alert popped up. Great. So I used Ctrl+z to undelete everything. Next, I selected everything EXCEPT the next block of code, and deleted the selection. I ran the jsFiddle, and again the alert popped up.
I continued deleting/undeleting until I found out where the alert no longer worked -- and that revealed the offending code block. Just had to carefully study the syntax in that specific area and found the error:
$('#txtOrder').attr({'disabled':'disabled')}; <== ERROR: note final parentheses
instead of
$('#txtOrder').attr({'disabled':'disabled'}); <== CORRECT: note final parentheses
Hope this helped, good luck on the rest of your project.
Here is the corrected jsFiddle
You didn't share your HTML, so I made assumptions about what your markup looks like.
Working jsFiddle here
The above jsFiddle is a much simplified version of what you are creating. Obviously, it is very different from what you have done so that I could create it quickly.
Observe how I made certain things happen with jQuery; take what is useful and ignore the rest.
Specifically, you can see how I initially disabled the textarea control:
$('#txtArea').attr({'disabled':'disabled'});
Re-enabled the textarea control for editing, while also hiding the Edit button and displaying the Save button:
$('#txtArea').removeAttr('disabled');
$('#btnSave').show();
$(this).hide();
Importantly, this is how I ensure each addition adds to (rather than overwriting) existing content:
var ord = 'Requested By: ' + $('#txtReq').val() + '\r\n';
Very likely you already know many (most?) of the things I am pointing out, but I have no idea what you know so, again, keep the one or two things you find useful and ignore the rest. I only hope I've managed to hit on the bit that has you stumped at the moment.
I very rarely recommend W3Schools for anything, but look here for their excellent summary / reference of jQuery selectors, events, methods. (Keep hitting Next Chapter to cycle through all pages of this reference).

How to prevent multiple html selection box displayed on screen?

I have been working on the last bit of my php + ajax based datagrid project.Everything works as I designed except one thing : I cannot stop user opening multiple selection boxes...
Go my research page and use username "ChenxiMao" and password "accedo" to login(without double quotes).
Note that perhaps the images used in this datagrid would not be displayed when page is loaded for the first time(weird, I am trying to fix this, browser incompatibilities, perhaps).
If you double click on one cell in the "CONSULTANT" column, a html select box would be displayed, you can select one consultant to assign him to this task or unassign the consultant from this task. No problem for this.
The problem is : when user leaves this selection box OPEN, he/she can still open another selection box... My jquery code cannot stop people from opening multiple selection boxes.
You can ctrl-U to see the source code on this page, and check the content inside the "gridview-helper.js" for what I have been done.
I want to let user only open a single selection box. When he/she leaves the cell, the selection box should be closed, without changing the html inside...
Puzzled, screwed up for this afternoon...
Thanks for any suggestons in advance!
JavaScript is single-threaded, so you can add a mutex variable and check its value before opening a new select box.
At the top of gridview-helper.js:
var is_choice_visible = false;
In your double-click handler:
$(this).dblclick(function()
{
if (is_choice_visible)
return;
is_choice_visible = true;
...
For your select box, add an onblur handler which sets is_choice_visible back to false and deletes itself.
Unrelated tip: Growing a string in a loop is slow on older versions of Internet Explorer. It's more efficient to append to an array and join the array, e.g.:
var html = ["<select>..."];
for (var i in consultantnames)
{
html.push("<option>...</option>");
}
html.push("</select>");
return html.join("");
Have you tried using the onmouseout event on the cell, and removing the child dropdown box element if mouse out is triggered? Seems that should work.

Problem getting selected text when using a sprited button and selection.createRange() in Internet Explorer

I'm working on implementing sprited buttons in Stackoverflow's beloved WMD markdown editor and I've run into an odd bug. On all versions of IE, the selected text is lost upon button clicks, so, say, highlighting a block of text and clicking the code button acts like you placed the cursor at the end of the selection and clicked the button.
e.g. highlighting this:
This
Is
Code
and clicking the code button give you:
This
Is
Code`enter code here`
What's really weird is that I left the original non-sprited button bar in and that works just fine. In fact ALL buttons and keyboard shortcuts code use the same doClick(button) function!
Old-style non-sprited buttons: OK
Keyboard shortcuts: OK
Sprited buttons in non-IE browsers: OK
Sprited buttons in IE: WTF
I've isolated the problem down to a call to selection.createRange() which finds nothing only when the sprited button is clicked. I've tried screwing around with focus()ing and making sure as little as possible happens before the doClick() but no joy. The keyboard shortcuts seem to work because the focus is never lost from the input textarea. Can anyone think of a hack that will let me somehow collect the selected text in IE?
The onclick handler looks like this:
button.onmouseout = function(){
this.style.backgroundPosition = this.XShift + " " + normalYShift;
};
button.onclick = function() {
if (this.onmouseout) {
this.onmouseout();
}
doClick(this);
}
I've tried moving the onmouseout call to after the doClick in case that was causing a loss of focus but that's not the problem.
EDIT:
The only thing that seems to be different is that, in the original button code, you are clicking on an image. In the sprited code, you are clicking on a list item <li> with a background image set. Perhaps it's trying to select the non-existent text in my list item?
/EDIT
Actual code is located in my wmd repository on git in the button-cleanup branch.
If you revert to the 0d6d1b32bb42a6bd1d4ac4e409a19fdfe8f1ffcc commit you can see both button bars. The top one is sprited and exhibits the weird behavior. The bottom one contains the remnants of the original button bar and works fine. The suspect code is in the setInputAreaSelectionStartEnd() function in the TextareaState object.
One last thing I should mention is that, for the time being, I'm trying to keep the control in pure Javascript so I'd like to avoid fixing this with an external library like jQuery if that's possible.
Thanks for your help!
I know what the answer to my own question is.
The sprited buttons are implemented using an HTML list and CSS, where all the list items have a background image. The background image is moved around using CSS to show different buttons and states (like mouseover highlights). Standard CSS button spriting stuff.
This works fine in IE with one exception: IE tries to select the empty list text when you click on the background image "button". The selection in the input textarea goes away and the current selection (which will be returned by document.selection.createRange()) is moved to the empty text in the list item.
The fix for this is simple - I created a variable to cache the selection and a flag. In IE I cache the selection and set the flag in a mousedown event handler. In the text processing, I check for the presence of the flag - if it's set I use the cached range instead of querying document.selection.createRange().
Here are some code snippets:
wmd.ieCachedRange = null;
wmd.ieRetardedClick = false;
if(global.isIE) {
button.onmousedown = function() {
wmd.ieRetardedClick = true;
wmd.ieCachedRange = document.selection.createRange();
};
}
var range;
if(wmd.ieRetardedClick && wmd.ieCachedRange) {
range = wmd.ieCachedRange;
wmd.ieRetardedClick = false;
}
else {
range = doc.selection.createRange();
}
The solution is only a few lines of code and avoids messing around with the DOM and potentially creating layout engine issues.
Thanks for your help, Cristoph. I came up with the answer while thinking and googling about your answer.
You have to blur() a button before IE can select anything else on a page.
Can you provide a minimal example (only containing relevant code) which reproduces the bug?

Categories