Rangy
repository·master·Indexed 25 days ago
https://github.com/timdown/rangyA cross-browser JavaScript library for managing text ranges and selections. Version 1.3.2 provides a consistent API for complex selection tasks, including range manipulation, bookmarking, and selection wrapping. It supports NPM, Bower, and AMD, and includes a modular architecture for extending functionality.
What's inside rangy
- Rangy 1.3 and later versions include support for AMD (Asynchronous Module Definition).
Install Rangy via NPM
masterYou can install the official Rangy module using npm. This is the recommended way to include Rangy in modern JavaScript projects.Install Rangy via Bower
masterRangy is available via Bower. Versions 1.2 and 1.3 are supported.Access Rangy documentation
masterDetailed documentation for Rangy, including API references and usage guides, is maintained in the project's GitHub wiki.Understand the TextRange module features
masterThe
TextRangemodule is a Rangy plugin designed for text-based manipulation and searching of ranges and selections. Key capabilities include:- Boundary Manipulation: Move range boundaries using character or word offsets.
- Customizable Tokenization: Use a custom word tokenizer for different languages or rules.
- Smart Visibility Awareness: Automatically ignores text nodes inside
<script>or<style>elements, or those hidden by CSSdisplayandvisibilityproperties. - Text Searching: Use
range.findText()to search for text or regular expressions within the page or a specific range, with support for whole-word and case-sensitivity flags. - Persistence: Save and restore selections and ranges as text offsets within a node.
- Text Extraction: Retrieve visible text within a range or selection, and use
innerTextfor elements.
Use the SaveRestore module to save and restore selections
masterThe
SaveRestoremodule is a Rangy plugin that allows you to save a user's current selection (or multiple ranges) and restore them later. It works by inserting invisible marker elements (<span>tags with the classrangySelectionBoundary) into the DOM to act as anchors.To use it, you must first ensure the module is loaded via Rangy's
createModulemechanism. Once loaded, the API is attached to therangyobject.Workflow:
- Call
rangy.saveSelection(window)to capture the current selection. This returns asavedSelectionobject containing the necessary metadata and range information. - Perform other DOM manipulations.
- Call
rangy.restoreSelection(savedSelection)to re-apply the captured selection to the window.
- Call
How WrappedSelection and WrappedRange work together
masterIn Rangy, a
WrappedSelectionis a high-level wrapper around the browser's native selection mechanism. It manages one or moreWrappedRangeobjects.When you call
addRangeon aWrappedSelection, you are adding aWrappedRangeto the selection's internal list of ranges. TheWrappedSelectiontracks properties likeanchorNode,focusNode,anchorOffset,focusOffset,rangeCount,isCollapsed, andtype(e.g.,'Caret','Range', or'None').If the browser supports multiple ranges (like modern W3C compliant browsers), the
WrappedSelectionmanages a collection of ranges. In older IE environments, it may useControlRangeto simulate multiple selections by treating a group of elements as a singleControlselection.Initialize Rangy
masterRangy can be initialized manually using
api.init(). If you are loading Rangy after the document has already loaded, useapi.addInitListener(callback)to register a function that will execute as soon as Rangy is initialized.Additionally,
api.shim(window)can be used to initialize the library and notify shim listeners, which is useful for polyfilling missing native APIs in older browsers.Use the Rangy Serializer module to save and restore selections
masterThe
Serializermodule allows you to convert DOM Ranges and Selections into string formats. This is useful for persisting a user's selection (e.g., in a cookie or local storage) and restoring it later.Key features include:
- Checksums: By default, serialized ranges include a checksum of the root node to ensure the selection is only restored if the DOM structure hasn't changed significantly.
- Cookie Support: Built-in methods to save and restore selections directly from/to cookies.
To use these features, ensure the
Serializermodule is loaded as part of your Rangy installation.Configure TextRange findText options
masterThe
findTextmethod accepts an options object to control the search behavior:caseSensitive(boolean): Whether the search should be case-sensitive.withinRange(Range|null): If provided, the search is restricted to this specific range.wholeWordsOnly(boolean): If true, only matches that constitute whole words are returned.wrap(boolean): Whether to wrap the search (e.g., searching from the end of the document backwards).direction(string): The direction of the search ("forward"or"backward").wordOptions(Object|null): Custom word tokenization settings.characterOptions(Object|null): Custom character/whitespace handling settings.
Configure TextRange character options
masterWhen performing text-based operations, you can control how whitespace and collapsed characters are handled using
characterOptions.Available configuration keys:
includeBlockContentTrailingSpace(boolean): Whether to include trailing spaces inside block elements.includeSpaceBeforeBr(boolean): Whether to include spaces preceding a<br>element.includeSpaceBeforeBlock(boolean): Whether to include spaces preceding a block element.includePreLineTrailingSpace(boolean): Whether to include trailing spaces in elements withwhite-space: pre-line.ignoreCharacters(string): A string of characters to be ignored during text operations.
Configure Rangy options
masterRangy provides a global
configobject to control its behavior. Key configuration options include:alertOnFail: Boolean. If true, Rangy will trigger a browseralert()if it fails to initialize or encounters a critical error.alertOnWarn: Boolean. If true, Rangy will trigger a browseralert()for warnings.preferTextRange: Boolean. Determines whether to prefer the legacyTextRangeAPI over the standardRangeAPI where available.autoInitialize: Boolean. Determines if Rangy should automatically initialize. This can be controlled by setting a globalrangyAutoInitializevariable before Rangy loads.