Skip to content

Commit

Permalink
Added Element relative Highlighter Range.
Browse files Browse the repository at this point in the history
Uses a DOM element as doc. This is more failsafe at HTML structure
changes.
  • Loading branch information
Cavva79 committed Jan 15, 2016
1 parent 1e55169 commit 23ca5e3
Show file tree
Hide file tree
Showing 8 changed files with 213 additions and 37 deletions.
156 changes: 156 additions & 0 deletions demos/highlighter_text_range.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<!DOCTYPE html>
<!--[if lte IE 6]><html class="ie6"><!--[if gt IE 8]><!--><html><!--<![endif]-->
<head>
<title>Rangy Highlighter Module Demo</title>
<link href="demo.css" rel="stylesheet" type="text/css">
<style type="text/css">
.highlight {
background-color: yellow;
}

.note {
background-color: limegreen;
}

#summary {
border: dotted orange 1px;
}
</style>
<script type="text/javascript" src="../lib/rangy-core.js"></script>
<script type="text/javascript" src="../lib/rangy-textrange.js"></script>
<script type="text/javascript" src="../lib/rangy-classapplier.js"></script>
<script type="text/javascript" src="../lib/rangy-highlighter.js"></script>
<script type="text/javascript">
function gEBI(id) {
return document.getElementById(id);
}
var serializedHighlights = decodeURIComponent(window.location.search.slice(window.location.search.indexOf("=") + 1));
var highlighter;

var initialDoc;

window.onload = function() {
rangy.init();

highlighter = rangy.createHighlighter(document.getElementById("content"), "TextRange");

highlighter.addClassApplier(rangy.createClassApplier("highlight", {
ignoreWhiteSpace: true,
tagNames: ["span", "a"]
}));

highlighter.addClassApplier(rangy.createClassApplier("note", {
ignoreWhiteSpace: true,
elementTagName: "a",
elementProperties: {
href: "#",
onclick: function() {
var highlight = highlighter.getHighlightForElement(this);
if (window.confirm("Delete this note (ID " + highlight.id + ")?")) {
highlighter.removeHighlights( [highlight] );
}
return false;
}
}
}));


if (serializedHighlights) {
highlighter.deserialize(serializedHighlights);
}
};


function highlightSelectedText() {
highlighter.highlightSelection("highlight");
}

function noteSelectedText() {
highlighter.highlightSelection("note");
}

function removeHighlightFromSelectedText() {
highlighter.unhighlightSelection();
}

function highlightScopedSelectedText() {
highlighter.highlightSelection("highlight", { containerElementId: "summary" });
}

function noteScopedSelectedText() {
highlighter.highlightSelection("note", { containerElementId: "summary" });
}

function reloadPage(button) {
button.form.elements["serializedHighlights"].value = highlighter.serialize();
button.form.submit();
}

</script>
</head>
<body>
<div id="buttons">
<h3>Highlighter</h3>
<p>Make a selection in the document and use the buttons below to highlight and unhighlight.</p>
<input type="button" ontouchstart="highlightSelectedText();" onclick="highlightSelectedText();" value="Highlight selection">
<input type="button" ontouchstart="noteSelectedText();" onclick="noteSelectedText();" value="Add note to selection">
<input type="button" ontouchstart="removeHighlightFromSelectedText();" onclick="removeHighlightFromSelectedText();" value="Remove highlights from selection">
<br>
<input type="button" ontouchstart="highlightScopedSelectedText();" onclick="highlightScopedSelectedText();" value="Highlight within outlined paragraph">
<input type="button" ontouchstart="noteScopedSelectedText();" onclick="noteScopedSelectedText();" value="Annotate selection within outlined paragraph">

<h3>Preserving highlights between page requests</h3>
<form action="highlighter_text_range.html" method="get">
Highlights can be preserved between page requests. Press the following button to reload the page with the
highlights preserved:
<br>
<input type="hidden" name="serializedHighlights" value="">
<input type="button" value="Reload" onclick="reloadPage(this)">
</form>
</div>

<div id="content">
<h1>Rangy Highlighter Module Demo</h1>
<p id="intro">
Please use your mouse and/or keyboard to make selections from the sample content below and use the buttons
on the left hand size to create and remove highlights.
</p>
<p id="summary">
<b>Association football</b> is a sport played between two teams. It is usually called <b>football</b>, but in
some countries, such as the United States, it is called <b>soccer</b>. In
<a href="http://simple.wikipedia.org/wiki/Japan">Japan</a>, New Zealand, South Africa, Australia, Canada and
Republic of Ireland, both words are commonly used.
</p>
<p>
Each team has 11 players on the field. One of these players is the <i>goalkeeper</i>, and the other ten are
known as <i>"outfield players."</i> The game is played by <b>kicking a ball into the opponent's goal</b>. A
match has 90 minutes of play, with a break of 15 minutes in the middle. The break in the middle is called
half-time.
</p>
<h2>Competitions</h2>
<p>
There are many competitions for football, for both football clubs and countries. Football clubs usually play
other teams in their own country, with a few exceptions. <b>Cardiff City F.C.</b> from Wales for example, play
in the English leagues and in the English FA Cup.
</p>
<h2>Who plays football <span class="smaller">(this section is in pre-formatted text)</span></h2>
<pre>
Football is the world's most popular sport. It is played in more
countries than any other game. In fact, FIFA (the Federation
Internationale de Football Association) has more members than the
United Nations.

It is played by both males and females.


</pre>
</div>

<p class="small">
Text adapted from <a href="http://simple.wikipedia.org/wiki/Association_football">Simple Wikipedia page on
Association Football</a>, licensed under the
<a href="http://simple.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License">Creative
Commons Attribution/Share-Alike License</a>.
</p>
</body>
</html>
11 changes: 4 additions & 7 deletions lib/rangy-classapplier.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
*
* Depends on Rangy core.
*
* Copyright 2015, Tim Down
* Copyright 2016, Tim Down
* Licensed under the MIT license.
* Version: 1.3.1-dev
* Build date: 20 May 2015
* Build date: 15 January 2016
*/
(function(factory, root) {
if (typeof define == "function" && define.amd) {
Expand Down Expand Up @@ -698,13 +698,10 @@
// Normalizes nodes after applying a class to a Range.
postApply: function(textNodes, range, positionsToPreserve, isUndo) {
var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1];

var merges = [], currentMerge;

var rangeStartNode = firstNode, rangeEndNode = lastNode;
var rangeStartOffset = 0, rangeEndOffset = lastNode.length;

var textNode, precedingTextNode;
var precedingTextNode;

// Check for every required merge and create a Merge object for each
forEach(textNodes, function(textNode) {
Expand Down Expand Up @@ -741,7 +738,7 @@

// Apply the merges
if (merges.length) {
for (i = 0, len = merges.length; i < len; ++i) {
for (var i = 0, len = merges.length; i < len; ++i) {
merges[i].doMerge(positionsToPreserve);
}

Expand Down
29 changes: 18 additions & 11 deletions lib/rangy-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
* Rangy, a cross-browser JavaScript range and selection library
* https://github.com/timdown/rangy
*
* Copyright 2015, Tim Down
* Copyright 2016, Tim Down
* Licensed under the MIT license.
* Version: 1.3.1-dev
* Build date: 20 May 2015
* Build date: 15 January 2016
*/

(function(factory, root) {
Expand Down Expand Up @@ -222,7 +222,7 @@
})();

// Very simple event handler wrapper function that doesn't attempt to solve issues such as "this" handling or
// normalization of event properties
// normalization of event properties because we don't need this.
var addListener;
if (isBrowser) {
if (isHostMethod(document, "addEventListener")) {
Expand Down Expand Up @@ -1303,6 +1303,7 @@
var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );
var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);
var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );
var getElementAncestor = createAncestorFinder( [1] );

function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {
if (getDocTypeNotationEntityAncestor(node, allowSelf)) {
Expand Down Expand Up @@ -1365,7 +1366,7 @@
var htmlParsingConforms = false;
try {
styleEl.innerHTML = "<b>x</b>";
htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node
htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Pre-Blink Opera incorrectly creates an element node
} catch (e) {
// IE 6 and 7 throw
}
Expand Down Expand Up @@ -1966,6 +1967,12 @@
break;
}

assertNoDocTypeNotationEntityAncestor(sc, true);
assertValidOffset(sc, so);

assertNoDocTypeNotationEntityAncestor(ec, true);
assertValidOffset(ec, eo);

boundaryUpdater(this, sc, so, ec, eo);
},

Expand Down Expand Up @@ -2128,6 +2135,12 @@
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
this.setStartAndEnd(node, offset);
},

parentElement: function() {
assertRangeValid(this);
var parentNode = this.commonAncestorContainer;
return parentNode ? getElementAncestor(this.commonAncestorContainer, true) : null;
}
});

Expand All @@ -2149,17 +2162,11 @@
range.endContainer = endContainer;
range.endOffset = endOffset;
range.document = dom.getDocument(startContainer);

updateCollapsedAndCommonAncestor(range);
}

function Range(doc) {
this.startContainer = doc;
this.startOffset = 0;
this.endContainer = doc;
this.endOffset = 0;
this.document = doc;
updateCollapsedAndCommonAncestor(this);
updateBoundaries(this, doc, 0, doc, 0);
}

createPrototypeRange(Range, updateBoundaries);
Expand Down
22 changes: 15 additions & 7 deletions lib/rangy-highlighter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
*
* Depends on Rangy core, ClassApplier and optionally TextRange modules.
*
* Copyright 2015, Tim Down
* Copyright 2016, Tim Down
* Licensed under the MIT license.
* Version: 1.3.1-dev
* Build date: 20 May 2015
* Build date: 15 January 2016
*/
(function(factory, root) {
if (typeof define == "function" && define.amd) {
Expand All @@ -34,8 +34,16 @@
return h1.characterRange.start - h2.characterRange.start;
}

function getDocumentFromUnknownElement(doc){
return Object.prototype.toString.call(doc) == "[object HTMLDocument]" ? doc : doc.ownerDocument;
}

function getContainerElementId(doc){
return Object.prototype.toString.call(doc) != "[object HTMLDocument]" ? doc.getAttribute('id') : null;
}

function getContainerElement(doc, id) {
return id ? doc.getElementById(id) : getBody(doc);
return id ? getDocumentFromUnknownElement(doc).getElementById(id) : getBody(doc);
}

/*----------------------------------------------------------------------------------------------------------------*/
Expand Down Expand Up @@ -330,7 +338,7 @@
var classApplier = className ? this.classAppliers[className] : null;

options = createOptions(options, {
containerElementId: null,
containerElementId: getContainerElementId(this.doc),
exclusive: true
});

Expand All @@ -339,7 +347,7 @@

var containerElement, containerElementRange, containerElementCharRange;
if (containerElementId) {
containerElement = this.doc.getElementById(containerElementId);
containerElement = getDocumentFromUnknownElement(this.doc).getElementById(containerElementId);
if (containerElement) {
containerElementRange = api.createRange(this.doc);
containerElementRange.selectNodeContents(containerElement);
Expand Down Expand Up @@ -431,7 +439,7 @@
var converter = this.converter;

options = createOptions(options, {
containerElement: null,
containerElement: this.doc,
exclusive: true
});

Expand Down Expand Up @@ -459,7 +467,7 @@
var classApplier = className ? this.classAppliers[className] : false;

options = createOptions(options, {
containerElementId: null,
containerElementId: getContainerElementId(this.doc),
exclusive: true
});

Expand Down
6 changes: 3 additions & 3 deletions lib/rangy-selectionsaverestore.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
*
* Depends on Rangy core.
*
* Copyright 2015, Tim Down
* Copyright 2016, Tim Down
* Licensed under the MIT license.
* Version: 1.3.1-dev
* Build date: 20 May 2015
* Build date: 15 January 2016
*/
(function(factory, root) {
if (typeof define == "function" && define.amd) {
Expand All @@ -24,7 +24,7 @@
factory(root.rangy);
}
})(function(rangy) {
rangy.createModule("SaveRestore", ["WrappedRange"], function(api, module) {
rangy.createModule("SaveRestore", ["WrappedSelection"], function(api, module) {
var dom = api.dom;
var removeNode = dom.removeNode;
var isDirectionBackward = api.Selection.isDirectionBackward;
Expand Down
4 changes: 2 additions & 2 deletions lib/rangy-serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
*
* Depends on Rangy core.
*
* Copyright 2015, Tim Down
* Copyright 2016, Tim Down
* Licensed under the MIT license.
* Version: 1.3.1-dev
* Build date: 20 May 2015
* Build date: 15 January 2016
*/
(function(factory, root) {
if (typeof define == "function" && define.amd) {
Expand Down
4 changes: 2 additions & 2 deletions lib/rangy-textrange.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
*
* Depends on Rangy core.
*
* Copyright 2015, Tim Down
* Copyright 2016, Tim Down
* Licensed under the MIT license.
* Version: 1.3.1-dev
* Build date: 20 May 2015
* Build date: 15 January 2016
*/

/**
Expand Down
Loading

0 comments on commit 23ca5e3

Please sign in to comment.