@samuelbradshaw/highlight-helper-js 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/publish.yml +22 -0
- package/LICENSE +21 -0
- package/README.md +122 -0
- package/demo.html +365 -0
- package/highlight-helper.js +1449 -0
- package/package.json +26 -0
- package/test-load.html +224 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# From https://docs.github.com/en/actions/tutorials/publish-packages/publish-nodejs-packages#publishing-packages-to-the-npm-registry
|
|
2
|
+
|
|
3
|
+
name: Publish Package to npmjs
|
|
4
|
+
on:
|
|
5
|
+
release:
|
|
6
|
+
types: [published]
|
|
7
|
+
jobs:
|
|
8
|
+
build:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
id-token: write
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v5
|
|
15
|
+
- uses: actions/setup-node@v4
|
|
16
|
+
with:
|
|
17
|
+
node-version: '20.x'
|
|
18
|
+
registry-url: 'https://registry.npmjs.org'
|
|
19
|
+
- run: npm ci
|
|
20
|
+
- run: npm publish --provenance --access public
|
|
21
|
+
env:
|
|
22
|
+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Samuel Bradshaw
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Highlight Helper
|
|
2
|
+
|
|
3
|
+
**Highlight Helper** is a JavaScript tool that enables highlighting or underlining text in an HTML page (such as a digital book or article). Highlighting text in an HTML document can be difficult, especially in cases where a highlight starts in one element but ends in another.
|
|
4
|
+
|
|
5
|
+
Behind the scenes, Highlight Helper supports three different mechanisms for drawing highlights:
|
|
6
|
+
|
|
7
|
+
1. [SVG shapes](https://developer.mozilla.org/en-US/docs/Web/SVG) drawn behind text (default).
|
|
8
|
+
2. The [CSS Custom Highlight API](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API) (experimental*).
|
|
9
|
+
3. Inserted [HTML mark elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/mark).
|
|
10
|
+
|
|
11
|
+
An HTML demo page that shows basic functionality can be found here: [Highlight Helper Demo](https://samuelbradshaw.github.io/highlight-helper-js/demo.html). Source code for the demo is in **demo.html**. Highlight Helper itself is in **highlight-helper.js**.
|
|
12
|
+
|
|
13
|
+
*The Custom Highlight API requires Safari 17.2+ or Chrome 105+, and may hang when rendering a large number of highlights. Additionally, only a few CSS styles are supported (see [Styling Highlights](https://www.w3.org/TR/css-pseudo-4/#highlight-styling)). Browser support and loading speed will hopefully improve in the future. See also the [load test page](https://samuelbradshaw.github.io/highlight-helper-js/test-load.html) for Highlight Helper.
|
|
14
|
+
|
|
15
|
+
### Documentation:
|
|
16
|
+
- [Known issues](#known-issues)
|
|
17
|
+
- [Getting started](#getting-started)
|
|
18
|
+
- [Methods, options, and custom events](#methods-options-and-custom-events)
|
|
19
|
+
- [Methods](#methods)
|
|
20
|
+
- [Options](#options)
|
|
21
|
+
- [Custom events](#custom-events)
|
|
22
|
+
- [Highlight attributes](#highlight-attributes)
|
|
23
|
+
|
|
24
|
+
## <a name="known-issues"></a>Known issues
|
|
25
|
+
|
|
26
|
+
There are a few known issues:
|
|
27
|
+
|
|
28
|
+
- **Chrome on Android** doesn’t set focus (and therefore doesn’t show text selection handles) when text is programmatically selected (such as from a disambiguation panel), unless the selection is initiated directly by a user’s tap. However, if you’re working in a native app with a webview, you may be able to focus the webview from Android (see [StackOverflow](https://stackoverflow.com/a/6372903/1349044) and [GitHub](https://github.com/lawlsausage/save_gfy/pull/1)).
|
|
29
|
+
- **Safari on iOS** doesn’t respect the text selection color set via CSS, so when a highlight is active for editing it has a blue overlay. However, if you’re working in a native app with a webview, you may be able to set colors natively with [tintColor](https://stackoverflow.com/a/60510743/1349044), [highlightView](https://developer.apple.com/documentation/uikit/uitextselectiondisplayinteraction/4195471-highlightview), and/or [handleViews](https://developer.apple.com/documentation/uikit/uitextselectiondisplayinteraction/4195470-handleviews).
|
|
30
|
+
- **Safari on iOS** loses focus and doesn’t send a `visibilitychange` event if the device screen locks after a period of inactivity. This can cause selection handles to not show when unlocking your device and tapping on an existing highlight. Going to another app and back or manually triggering a `visibilitychange` event will allow Highlight Helper to set focus again. Focus will also be set again if the user long-presses to select text.
|
|
31
|
+
- **Safari on iOS and macOS** doesn’t allow setting underline thickness on a ::highlight() pseudo-element, so underline highlights drawn by the Custom Highlight API are thin and hard to see (see [StackOverflow](https://stackoverflow.com/q/79060854/1349044) and [WebKit Bugzilla](https://bugs.webkit.org/show_bug.cgi?id=282027)). This will hopefully be fixed in a future version of Safari.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## <a name="getting-started"></a>Getting started
|
|
35
|
+
|
|
36
|
+
The easiest way to get started is to download demo.html and highlight-helper.js, open demo.html in a text editor and browser, and make changes to adapt it for your needs.
|
|
37
|
+
|
|
38
|
+
In the source of demo.html, you’ll see CSS styles, followed by the HTML body, followed by JavaScript code. The JavaScript code does the following:
|
|
39
|
+
1. Links to highlight-helper.js,
|
|
40
|
+
2. Initializes a “Highlighter” instance with options,
|
|
41
|
+
3. Pre-loads and draws a few existing highlights,
|
|
42
|
+
3. Sets up logic to call Highlight Helper methods when buttons on the demo page are tapped, and
|
|
43
|
+
4. Sets up listeners to respond to custom event messages that come back from Highlight Helper.
|
|
44
|
+
|
|
45
|
+
All of the available methods, options, and custom events are documented below.
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
## <a name="methods-options-and-custom-events"></a>Methods, options, and custom events
|
|
49
|
+
|
|
50
|
+
### <a name="methods"></a>Methods
|
|
51
|
+
|
|
52
|
+
- **loadHighlights(highlights)** – Load an array of existing highlights into Highlight Helper. Each highlight should have one or more of the properties described under “Highlight attributes” below. Omitted or invalid properties will fall back to previous or default values. If highlights are already loaded, this method will replace the loaded highlights by diffing for changes, then adding, removing, or updating individual highlights as needed.
|
|
53
|
+
- **createOrUpdateHighlight(attributes, triggeredByUserAction)** – Create or update an individual highlight. `attributes` is an object with one or more of the properties described under “Highlight attributes” below. If a highlight ID isn’t passed in, the currently-active highlight will be updated, if there is one, otherwise a new highlight will be created. If it’s a new highlight and start and end bounds aren’t passed in, the highlight will be created based on selected text. `triggeredByUserAction` is an optional boolean (default: `true`). If this is set to false, the highlight won’t be activated after editing, and the color and style won’t be saved as the default for the next highlight.
|
|
54
|
+
- **drawHighlights(highlightIds)** – Draw or redraw highlights on the page, given an array of highlight IDs. If no highlight IDs are passed, all highlights will be drawn. This shouldn’t need to be called frequently (Highlight Helper will usually draw or redraw highlights automatically).
|
|
55
|
+
- **activateHighlight(highlightId)** – Activate a highlight for editing, given its `highlightId`. Only one highlight can be active at a time (because it’s tied to text selection, and there can only be one text selection on a page). Normally, a highlight activates automatically when the user taps it; however, if there are overlapping highlights or if `autoTapToActivate` is set to `false`, this will need to be called manually.
|
|
56
|
+
- **activateHyperlink(position)** – Activate the specified hyperlink (i.e. open the link). `position` is the 0-based position of the link in the annotatable area of the page, relative to other links. Normally, a link opens automatically when the user taps it; however, if a highlight overlaps the hyperlink or if `autoTapToActivate` is set to `false`, this will need to be called manually.
|
|
57
|
+
- **deactivateHighlights()** – Clear the text selection and deactivate any active highlights. Normally, highlights are deactivated automatically when the user taps away.
|
|
58
|
+
- **removeHighlights(highlightIds)** – Remove the specified highlights. If `highlightIds` isn’t provided, all highlights will be removed.
|
|
59
|
+
- **getActiveHighlightId()** – Get the ID of the currently-active highlight (if there is one).
|
|
60
|
+
- **getHighlightInfo(highlightIds, paragraphId)** – Get highlight information for an array of highlight IDs. If no highlight IDs are passed, information for all relevant highlights will be returned. If `paragraphId` is provided, only highlights that start in the specified paragraph will be returned. Highlights will be sorted based on their position on the page.
|
|
61
|
+
- **setOption(key, value)** – Change one of the initialized options. Available options are described below.
|
|
62
|
+
- **getOptions()** – Get the initialized options, including defaults for any options that weren’t explicitly set.
|
|
63
|
+
- **removeHighlighter()** – Removes the current Highlighter instance and all of its highlights from the page. If a new Highlighter instance is created with the same container (as defined by the `containerSelector` option), the previous instance for that container will be removed automatically (there can be multiple Highlighter instances on a page, but each one needs to have a different container).
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
### <a name="options"></a>Options
|
|
67
|
+
|
|
68
|
+
Options can be provided when Highlight Helper is initialized. They can also be set on demand using `setOption(key, value)` (described above). All of these settings are optional. If not specified, the default value for each option will be used.
|
|
69
|
+
|
|
70
|
+
- **containerSelector** – CSS selector for the section of the page that should be annotatable. Default: `body`.
|
|
71
|
+
- **paragraphSelector** – CSS selector for the paragraphs (or other block elements) on the page that should be annotatable. Each paragraph is expected to have an ID attribute in the HTML, which is used to keep track of where a highlight starts and ends. Default: `h1[id], h2[id], h3[id], h4[id], h5[id], h6[id], p[id], ol[id], ul[id], dl[id], tr[id]`.
|
|
72
|
+
- **colors** – Object that describes available highlight colors. Keys are color names, and values are [CSS color values](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). Default: red, orange, yellow, green, blue (see full default values at the bottom of highlight-helper.js).
|
|
73
|
+
- **styles** – Object that describes available highlight styles. Keys are style names, and there are four properties for each style: `css`, `svg`, `css-active` (optional), and `svg-active` (optional). `css` is a CSS string used for styling highlights in `highlight-api` and `mark-elements` drawing modes, as well as for read-only highlights. `svg` is an SVG string (one or more SVG shapes) to represent the highlight in `svg` drawing mode. `css-active` and `svg-active` are alternative styles to be used when a highlight is active. The CSS custom property `var(--hh-color)` can be used to reference the highlight color value. For SVG highlights, the following variables (if present) will be replaced with relevant values from the highlight’s DOMRect: `{x}`, `{y}`, `{width}`, `{height}`, `{top}`, `{bottom}`, `{left}`, `{right}`. Default: fill, single-underline, double-underline, colored-text, redacted (see full default values at the bottom of highlight-helper.js).
|
|
74
|
+
- **wrappers** – Object that describes available highlight wrappers. Keys are wrapper names, and values are objects with two optional properties: `start` (HTML string to be inserted at the beginning of the highlight), and `end` (HTML string to be inserted at the end of the highlight). Only read-only highlights support wrappers. To avoid problems when calculating ranges and offsets, all [text nodes](https://developer.mozilla.org/en-US/docs/Web/API/Text) in the start and end wrappers will be removed (if text is needed, it should be rendered with CSS). `var(--hh-color)` can be used to reference the highlight color value. Variables surrounded by curly brackets will be replaced with variables stored in the `wrapperVariables` attribute of the highlight, if applicable. See default values at the bottom of highlight-helper.js.
|
|
75
|
+
- **selectionHandles** – Object that describes custom selection handles that a user can drag to resize a selection or highlight. Because most touch devices have built-in selection handles, custom selection handles will only show when using a mouse or trackpad. There are two properties: `left` (HTML string to be used for the left selection handle) and `right` (HTML string to be used for the right selection handle). `var(--hh-color)` can be used to reference the highlight color value. See default values at the bottom of highlight-helper.js.
|
|
76
|
+
- **rememberStyle** – Whether the most recent color, style, and wrapper should be remembered and used by default the next time the user creates a highlight. Boolean. Default: `true`.
|
|
77
|
+
- **snapToWord** – Whether highlights should snap to the nearest word boundary. Spaces and dashes are considered word boundaries (this option may not work correctly in all languages). Boolean. Default: `false`.
|
|
78
|
+
- **autoTapToActivate** – Whether Highlight Helper should automatically activate highlights and hyperlinks when they’re tapped. If set to false, you’ll need to listen for the `hh:tap` event and call `activateHighlight()` or `activateHyperlink()` manually when needed. Boolean. Default: `true`.
|
|
79
|
+
- **longPressTimeout** – Duration in milliseconds before a tap turns into a long-press. On long-press, Highlight Helper will send an `hh:tap` event with `isLongPress: true`. If this option is set to 0, Highlight Helper will treat long-presses the same as regular taps, sending the `hh:tap` event after the user lifts their finger. If you have access to system APIs (such as in a mobile app), you may be able to get the system long-press duration to use for this value (which may vary based on accessibility settings). For example, Android has a [getLongPressTimeout()](https://developer.android.com/reference/kotlin/android/view/ViewConfiguration#getlongpresstimeout) method and iOS has a [minimumPressDuration](https://developer.apple.com/documentation/uikit/uilongpressgesturerecognizer/minimumpressduration) property. Default: `500`.
|
|
80
|
+
- **pointerMode** – Mode for responding to pointer events. Options are `simple` (create highlights by selecting text, then tapping a color or style); `live` (create highlights immediately when selecting text, without needing to tap a button); and `auto` (`simple` for touch and mouse input, but `live` when a stylus or Apple Pencil is detected). Default: `auto`.
|
|
81
|
+
- **drawingMode** – Mode for drawing highlights on the page. Options are `svg` (SVG shapes), `highlight-api` (Custom Highlight API), and `mark-elements` (inserted HTML mark elements). For faster performance, read-only highlights will always be drawn as mark elements, even if a different drawing mode is set. Default: `svg`.
|
|
82
|
+
- **defaultColor** – Key of the default highlight color. Default: `yellow`.
|
|
83
|
+
- **defaultStyle** – Key of the default highlight style. Default: `fill`.
|
|
84
|
+
- **defaultWrapper** – Key of the default highlight wrapper. Default: `none`.
|
|
85
|
+
- **highlightIdFunction** – Identifier of a function that provides unique IDs for new highlights. Default: `hhGetNewHighlightId`.
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
### <a name="custom-events"></a>Custom events
|
|
89
|
+
|
|
90
|
+
Highlight Helper sends [custom events](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events) to the container element (defined in the `containerSelector` option) that can be listened for and responded to:
|
|
91
|
+
|
|
92
|
+
- **hh:highlightsload** – Sent when an array of highlights loads. Includes the number of highlights added, removed, or updated, the total number of loaded highlights, and the time they took to load (in milliseconds).
|
|
93
|
+
- **hh:highlightcreate** – Sent when a new highlight is created. Includes information about the highlight.
|
|
94
|
+
- **hh:highlightupdate** – Sent when the highlight changes. Includes information about the highlight, and a list of the attributes that changed.
|
|
95
|
+
- **hh:highlightremove** – Sent when a highlight is removed. Includes the ID of the removed highlight.
|
|
96
|
+
- **hh:tap** – Sent when a user taps in the annotatable container (potentially trying to activate a highlight or link). This will only be sent if there isn’t currently an active highlight. Includes the location of the tap, the highlight(s) that were tapped, and the hyperlink(s) that were tapped, if any.
|
|
97
|
+
- **hh:selectionupdate** – Sent when the selection color or style changes. Can be used to update custom selection UI, such as the color of selection handles. Includes the key of the color and style.
|
|
98
|
+
- **hh:highlightactivate** – Sent when a highlight is activated. Includes information about the activated highlight.
|
|
99
|
+
- **hh:highlightdeactivate** – Sent when a highlight is deactivated. Includes the ID of the deactivated highlight.
|
|
100
|
+
- **hh:ambiguousaction** – Sent when a user taps on overlapping highlights or an overlapping highlight and link. Includes the location of the tap, the highlight(s) that were tapped, and the hyperlink(s) that were tapped. This event will not be sent if `autoTapToActivate` is set to `false`.
|
|
101
|
+
- **selectionchange** – This is a [standard JavaScript event](https://developer.mozilla.org/en-US/docs/Web/API/Document/selectionchange_event) (not specific to Highlight Helper), but it’s worth mentioning here because it can be useful for adding custom selection UI around the selected text (such as a floating annotation menu). When this sends, you can call `window.getSelection()` to get the current [Selection object](https://developer.mozilla.org/en-US/docs/Web/API/Selection).
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
## <a name="highlight-attributes"></a>Highlight attributes
|
|
105
|
+
|
|
106
|
+
These are the attributes that Highlight Helper stores for each highlight. You can update a highlight by calling `createOrUpdateHighlight(attributes)`, where `attributes` is an object that includes the keys to be updated.
|
|
107
|
+
|
|
108
|
+
- **highlightId** (read-only after creation) – The ID of the highlight.
|
|
109
|
+
- **color** – The color of the highlight (key from the `colors` object in the initialized options). Example: `red`.
|
|
110
|
+
- **style** – The style of the highlight (key from the `styles` object in the initialized options). Example: `single-underline`.
|
|
111
|
+
- **wrapper** – The wrapper of the highlight (key from the `wrappers` object in the initialized options). More information about wrappers can be found above. Example: `none`.
|
|
112
|
+
- **wrapperVariables** – Variables used in wrappers. Example: `{ marker: 'a', }`.
|
|
113
|
+
- **readOnly** – Whether the highlight should be read-only (prevents a user from changing its color, bounds, or other attributes). Boolean. Example: `true`.
|
|
114
|
+
- **startParagraphId** – ID of the paragraph where the highlight starts. Example: `p1`.
|
|
115
|
+
- **startParagraphOffset** – Character offset where the highlight starts, relative to the beginning of the paragraph. Example: 12.
|
|
116
|
+
- **endParagraphId** – ID of the paragraph where the highlight ends. Example: `p1`.
|
|
117
|
+
- **endParagraphOffset** – Character offset where the highlight ends, relative to the beginning of the paragraph. Example: 14.
|
|
118
|
+
- **escapedHighlightId** (read-only) – Escaped highlight ID used as a CSS identifier (this is used internally by Highlight Helper).
|
|
119
|
+
- **rangeText** (read-only) – Text content in the highlighted range.
|
|
120
|
+
- **rangeHtml** (read-only) – HTML content in the highlighted range.
|
|
121
|
+
- **rangeParagraphIds** (read-only) – IDs of paragraphs in the highlighted range.
|
|
122
|
+
- **rangeObj** (read-only) – The [Range](https://developer.mozilla.org/en-US/docs/Web/API/Range) object that represents where the highlight is drawn.
|
package/demo.html
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en" translate="no">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<title>Text Selection Demo</title>
|
|
6
|
+
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1.0">
|
|
7
|
+
<meta name="google" content="notranslate">
|
|
8
|
+
<style>
|
|
9
|
+
:root {
|
|
10
|
+
-webkit-text-size-adjust: 100%;
|
|
11
|
+
--page-bg: hsl(0, 0%, 100%);
|
|
12
|
+
--text-color: hsl(0, 0%, 0%);
|
|
13
|
+
--gray-90: hsl(0, 0%, 90%);
|
|
14
|
+
--gray-50: hsl(0, 0%, 50%);
|
|
15
|
+
}
|
|
16
|
+
@media (prefers-color-scheme: dark) { :root {
|
|
17
|
+
--page-bg: hsl(0, 0%, 17%);
|
|
18
|
+
--text-color: hsl(0, 0%, 95%);
|
|
19
|
+
--gray-90: hsl(0, 0%, 30%);
|
|
20
|
+
--gray-50: hsl(0, 0%, 70%);
|
|
21
|
+
}}
|
|
22
|
+
|
|
23
|
+
body {
|
|
24
|
+
background-color: var(--page-bg);
|
|
25
|
+
color: var(--text-color);
|
|
26
|
+
line-height: 1.4;
|
|
27
|
+
}
|
|
28
|
+
img { width: 120px; height: 120px; float: right; }
|
|
29
|
+
a { color: var(--gray-50); }
|
|
30
|
+
button {
|
|
31
|
+
cursor: pointer;
|
|
32
|
+
user-select: none;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
#annotation-menu {
|
|
36
|
+
font-family: "Helvetica", sans-serif;
|
|
37
|
+
font-size: 0.8em;
|
|
38
|
+
.buttons-area {
|
|
39
|
+
display: grid;
|
|
40
|
+
grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
|
|
41
|
+
gap: 0.6em;
|
|
42
|
+
overflow: scroll;
|
|
43
|
+
& > * {
|
|
44
|
+
background-color: var(--page-bg);
|
|
45
|
+
border: 0; border-radius: 0.4em;
|
|
46
|
+
padding: 0.6em 0.4em;
|
|
47
|
+
font-size: inherit;
|
|
48
|
+
white-space: nowrap;
|
|
49
|
+
}
|
|
50
|
+
input[type="text"] { width: 2em; padding: 0.1em 0.3em; border: 1px solid var(--gray-50); }
|
|
51
|
+
button[name="hh-color"] { color: var(--page-bg); }
|
|
52
|
+
button[name="hh-color"][value="red"] { background-color: hsl(352, 99%, 65%); }
|
|
53
|
+
button[name="hh-color"][value="orange"] { background-color: hsl(31, 99%, 58%); }
|
|
54
|
+
button[name="hh-color"][value="yellow"] { background-color: hsl(50, 98%, 61%); }
|
|
55
|
+
button[name="hh-color"][value="green"] { background-color: hsl(75, 70%, 49%); }
|
|
56
|
+
button[name="hh-color"][value="blue"] { background-color: hsl(182, 86%, 47%); }
|
|
57
|
+
button[name="hh-style"], button[name="hh-wrapper"] { color: inherit; border: 2px solid var(--gray-50); }
|
|
58
|
+
button[name="hh-remove"] { background-color: var(--gray-50); color: var(--page-bg); }
|
|
59
|
+
.highlight-placeholder {
|
|
60
|
+
background-color: var(--gray-90);
|
|
61
|
+
padding: 0 0.3em;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
.footnote-marker {
|
|
66
|
+
display: inline-block;
|
|
67
|
+
vertical-align: super;
|
|
68
|
+
font-size: smaller;
|
|
69
|
+
line-height: 0.5em;
|
|
70
|
+
&::before {
|
|
71
|
+
content: attr(data-marker) / attr(data-accessibility-label);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#disambiguation-panel {
|
|
76
|
+
color: inherit;
|
|
77
|
+
background-color: inherit;
|
|
78
|
+
width: 400px; max-width: 100%;
|
|
79
|
+
flex-direction: column;
|
|
80
|
+
gap: 0.5em;
|
|
81
|
+
box-sizing: border-box;
|
|
82
|
+
&[open] { display: flex; }
|
|
83
|
+
#disambiguation-buttons {
|
|
84
|
+
display: flex;
|
|
85
|
+
flex-direction: column;
|
|
86
|
+
& button {
|
|
87
|
+
display: inline-block;
|
|
88
|
+
border: none;
|
|
89
|
+
background-color: inherit;
|
|
90
|
+
color: inherit;
|
|
91
|
+
font-family: inherit;
|
|
92
|
+
font-size: inherit;
|
|
93
|
+
text-align: inherit;
|
|
94
|
+
margin-bottom: 1em;
|
|
95
|
+
& * {
|
|
96
|
+
display: inline;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
&::backdrop {
|
|
101
|
+
background-color: hsla(0, 0%, 0%, 0.5);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
</style>
|
|
105
|
+
</head>
|
|
106
|
+
<body>
|
|
107
|
+
<main>
|
|
108
|
+
<h1 id="title1">Highlight Helper Demo</h1>
|
|
109
|
+
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/41/CMYK_color_model.svg/180px-CMYK_color_model.svg.png">
|
|
110
|
+
<p id="p1"><b>Highlight Helper</b> enables highlighting or underlining text in an HTML page. Highlights are drawn via <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/SVG">SVG shapes</a>, the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API">Custom Highlight API</a>, or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/mark">HTML mark elements</a>. Highlights can be drawn across multiple paragraphs or <b>inline <i>style</i></b> elements—they can even overlap!</p>
|
|
111
|
+
<p id="p2">Select text, then choose a color and style. Tap away when you’re done. Tap to activate it again for editing. Secondary elements like images (right) and Japanese ruby/furigana (below) are highlighted around.</p>
|
|
112
|
+
<p id="p3">わたしニーファイは<ruby><rb>善</rb><rt>よ</rt></ruby>い<ruby><rb>両</rb><rt>りょう</rt></ruby><ruby><rb>親</rb><rt>しん</rt></ruby>から<ruby><rb>生</rb><rt>う</rt></ruby>まれたので,<ruby><rb>父</rb><rt>ちち</rt></ruby>が<ruby><rb>学</rb><rt>まな</rt></ruby>んだすべてのことの<ruby><rb>中</rb><rt>なか</rt></ruby>から<ruby><rb>幾</rb><rt>いく</rt></ruby>らかの<ruby><rb>教</rb><rt>おし</rt></ruby>えを<ruby><rb>受</rb><rt>う</rt></ruby>けた。</p>
|
|
113
|
+
<p id="p4" style="direction: rtl;">فِي الْبَدْءِ خَلَقَ اللهُ السَّمَاوَاتِ وَالأَرْضَ. وَكَانَتِ الأَرْضُ خَرِبَةً وَخَالِيَةً، وَعَلَى وَجْهِ الْغَمْرِ ظُلْمَةٌ، وَرُوحُ اللهِ يَرِفُّ عَلَى وَجْهِ الْمِيَاهِ. وَقَالَ اللهُ: «لِيَكُنْ نُورٌ»، فَكَانَ نُورٌ.</p>
|
|
114
|
+
</main>
|
|
115
|
+
|
|
116
|
+
<hr>
|
|
117
|
+
<aside id="annotation-menu">
|
|
118
|
+
<div class="buttons-area">
|
|
119
|
+
<button name="hh-color" value="red">Red</button>
|
|
120
|
+
<button name="hh-color" value="orange">Orange</button>
|
|
121
|
+
<button name="hh-color" value="yellow">Yellow</button>
|
|
122
|
+
<button name="hh-color" value="green">Green</button>
|
|
123
|
+
<button name="hh-color" value="blue">Blue</button>
|
|
124
|
+
<button name="hh-style" value="fill" checked> Fill</button>
|
|
125
|
+
<button name="hh-style" value="single-underline"> Underline</button>
|
|
126
|
+
<button name="hh-style" value="double-underline"> Double underline</button>
|
|
127
|
+
<button name="hh-style" value="colored-text"> Colored text</button>
|
|
128
|
+
<button name="hh-style" value="redacted"> Redacted</button>
|
|
129
|
+
<button name="hh-remove">Remove</button>
|
|
130
|
+
<div></div>
|
|
131
|
+
<!--button name="hh-wrapper" value="none" title="No wrapper"><span class="highlight-placeholder">…</span></button>
|
|
132
|
+
<button name="hh-wrapper" value="footnote" title="Footnote"><span class="footnote-marker" data-marker="a" data-accessibility-label="Footnote"></span><span class="highlight-placeholder">…</span></button-->
|
|
133
|
+
</div>
|
|
134
|
+
<p>
|
|
135
|
+
<label><input type="checkbox" id="hh-remember-style" checked> Remember most recent color and style</label><br>
|
|
136
|
+
<label><input type="checkbox" id="hh-snap-to-word"> Snap highlights to the nearest word</label><br>
|
|
137
|
+
</p>
|
|
138
|
+
<p>
|
|
139
|
+
Pointer mode:<br>
|
|
140
|
+
<label><input type="radio" name="hh-pointer-mode" value="auto" checked> Auto (based on input device)</label><br>
|
|
141
|
+
<label><input type="radio" name="hh-pointer-mode" value="simple"> Simple</label><br>
|
|
142
|
+
<label><input type="radio" name="hh-pointer-mode" value="live"> Live</label><br>
|
|
143
|
+
</p>
|
|
144
|
+
<p>
|
|
145
|
+
Drawing mode:<br>
|
|
146
|
+
<label><input type="radio" name="hh-drawing-mode" value="svg" checked> SVG shapes</label><br>
|
|
147
|
+
<label><input type="radio" name="hh-drawing-mode" value="highlight-api"> Custom Highlight API</label><br>
|
|
148
|
+
<label><input type="radio" name="hh-drawing-mode" value="mark-elements"> HTML mark elements</label><br>
|
|
149
|
+
</p>
|
|
150
|
+
<b>Active highlight:</b>
|
|
151
|
+
<div id="snippet-container">
|
|
152
|
+
<div id="snippet">N/A</div>
|
|
153
|
+
</div>
|
|
154
|
+
<p id="highlight-info"></p>
|
|
155
|
+
</aside>
|
|
156
|
+
<dialog id="disambiguation-panel">
|
|
157
|
+
<h1>Select One</h1>
|
|
158
|
+
<div id="disambiguation-buttons"></div>
|
|
159
|
+
<button id="disambiguation-cancel">Cancel</button>
|
|
160
|
+
</dialog>
|
|
161
|
+
|
|
162
|
+
<!-- Link to the Highlight Helper JavaScript file -->
|
|
163
|
+
<script src="highlight-helper.js"></script>
|
|
164
|
+
<script>
|
|
165
|
+
// Example highlights
|
|
166
|
+
let highlights = [
|
|
167
|
+
{
|
|
168
|
+
highlightId: 'hh-1729991847207',
|
|
169
|
+
color: 'green', style: 'fill',
|
|
170
|
+
startParagraphId: 'p1', startParagraphOffset: 25,
|
|
171
|
+
endParagraphId: 'p1', endParagraphOffset: 57,
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
highlightId: 'hh-1729991847300',
|
|
175
|
+
color: 'blue', style: 'fill',
|
|
176
|
+
startParagraphId: 'p2', startParagraphOffset: 27,
|
|
177
|
+
endParagraphId: 'p2', endParagraphOffset: 42,
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
highlightId: 'hh-1729991847468',
|
|
181
|
+
color: 'red', style: 'colored-text', wrapper: 'footnote',
|
|
182
|
+
wrapperVariables: { marker: 'a', accessibilityLabel: 'Footnote 1a', },
|
|
183
|
+
readOnly: true,
|
|
184
|
+
startParagraphId: 'p2', startParagraphOffset: 119,
|
|
185
|
+
endParagraphId: 'p2', endParagraphOffset: 127,
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
highlightId: 'hh-1729991847301',
|
|
189
|
+
color: 'orange', style: 'fill',
|
|
190
|
+
startParagraphId: 'p3', startParagraphOffset: 56,
|
|
191
|
+
endParagraphId: 'p3', endParagraphOffset: 65,
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
highlightId: 'hh-1735379727958',
|
|
195
|
+
color: 'yellow', style: 'fill',
|
|
196
|
+
startParagraphId: 'p1', startParagraphOffset: 246,
|
|
197
|
+
endParagraphId: 'p1', endParagraphOffset: 259,
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
highlightId: 'hh-1735379721523',
|
|
201
|
+
color: 'red', style: 'fill',
|
|
202
|
+
startParagraphId: 'p1', startParagraphOffset: 237,
|
|
203
|
+
endParagraphId: 'p1', endParagraphOffset: 250,
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
highlightId: 'hh-1735479727958',
|
|
207
|
+
color: 'yellow', style: 'fill',
|
|
208
|
+
startParagraphId: 'p4', startParagraphOffset: 191,
|
|
209
|
+
endParagraphId: 'p4', endParagraphOffset: 207,
|
|
210
|
+
},
|
|
211
|
+
];
|
|
212
|
+
|
|
213
|
+
// Initialize a Highlighter instance, then load highlights
|
|
214
|
+
const highlighter = new Highlighter({
|
|
215
|
+
containerSelector: 'main',
|
|
216
|
+
paragraphSelector: 'main [id]',
|
|
217
|
+
wrappers: {
|
|
218
|
+
'footnote': { start: '<span class="footnote-marker" data-marker="{marker}" data-accessibility-label="{accessibilityLabel}"></span>', end: '', },
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
highlighter.loadHighlights(highlights);
|
|
222
|
+
|
|
223
|
+
// Call Highlight Helper methods when color, style, wrapper, or remove buttons on this demo page are tapped
|
|
224
|
+
const colorButtons = document.getElementsByName('hh-color');
|
|
225
|
+
for (const colorButton of colorButtons) {
|
|
226
|
+
colorButton.addEventListener('click', () => { highlighter.createOrUpdateHighlight({ color: colorButton.value }); });
|
|
227
|
+
}
|
|
228
|
+
const styleButtons = document.getElementsByName('hh-style');
|
|
229
|
+
for (const styleButton of styleButtons) {
|
|
230
|
+
styleButton.addEventListener('click', () => { highlighter.createOrUpdateHighlight({ style: styleButton.value }); });
|
|
231
|
+
}
|
|
232
|
+
const wrapperButtons = document.getElementsByName('hh-wrapper');
|
|
233
|
+
for (const wrapperButton of wrapperButtons) {
|
|
234
|
+
wrapperButton.addEventListener('click', () => { highlighter.createOrUpdateHighlight({ wrapper: wrapperButton.value }); });
|
|
235
|
+
}
|
|
236
|
+
const removeButton = document.getElementsByName('hh-remove')[0];
|
|
237
|
+
removeButton.addEventListener('click', () => { highlighter.removeHighlights([highlighter.getActiveHighlightId()]); });
|
|
238
|
+
document.addEventListener('keydown', respondToKeyPress);
|
|
239
|
+
function respondToKeyPress(event) {
|
|
240
|
+
if (event.key === 'Backspace') highlighter.removeHighlights([highlighter.getActiveHighlightId()]);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Call Highlight Helper methods when options are changed
|
|
244
|
+
const rememberStyleCheckbox = document.getElementById('hh-remember-style');
|
|
245
|
+
const snapToWordCheckbox = document.getElementById('hh-snap-to-word');
|
|
246
|
+
const pointerModeRadioButtons = document.getElementsByName('hh-pointer-mode');
|
|
247
|
+
const drawingModeRadioButtons = document.getElementsByName('hh-drawing-mode');
|
|
248
|
+
rememberStyleCheckbox.addEventListener('change', (event) => { highlighter.setOption('rememberStyle', event.currentTarget.checked); });
|
|
249
|
+
snapToWordCheckbox.addEventListener('change', (event) => { highlighter.setOption('snapToWord', event.currentTarget.checked); });
|
|
250
|
+
for (const pointerModeRadioButton of pointerModeRadioButtons) {
|
|
251
|
+
pointerModeRadioButton.addEventListener('change', (event) => {
|
|
252
|
+
let pointerMode = document.querySelector('[name="hh-pointer-mode"]:checked').value;
|
|
253
|
+
highlighter.setOption('pointerMode', pointerMode);
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
for (const drawingModeRadioButton of drawingModeRadioButtons) {
|
|
257
|
+
drawingModeRadioButton.addEventListener('change', (event) => {
|
|
258
|
+
let drawingMode = document.querySelector('[name="hh-drawing-mode"]:checked').value;
|
|
259
|
+
if (drawingMode === 'highlight-api' && !CSS.highlights) {
|
|
260
|
+
alert('Your browser doesn’t support the Custom Highlight API.');
|
|
261
|
+
} else {
|
|
262
|
+
highlighter.setOption('drawingMode', drawingMode);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const container = document.querySelector(highlighter.getOptions().containerSelector);
|
|
268
|
+
const snippetDiv = document.getElementById('snippet');
|
|
269
|
+
const infoDiv = document.getElementById('highlight-info');
|
|
270
|
+
|
|
271
|
+
// Respond to highlight update and highlight activate event
|
|
272
|
+
container.addEventListener('hh:highlightupdate', updateHighlightInfo);
|
|
273
|
+
container.addEventListener('hh:highlightactivate', updateHighlightInfo);
|
|
274
|
+
function updateHighlightInfo(event) {
|
|
275
|
+
clearHighlightInfo();
|
|
276
|
+
infoDiv.innerHTML = `
|
|
277
|
+
<b>Highlight:</b> ${event.detail.highlight.highlightId}<br>
|
|
278
|
+
<b>Color and style:</b> ${event.detail.highlight.color}, ${event.detail.highlight.style}<br>
|
|
279
|
+
<b>Wrapper:</b> ${event.detail.highlight.wrapper}, ${JSON.stringify(event.detail.highlight.wrapperVariables)}<br>
|
|
280
|
+
<b>Read-only:</b> ${event.detail.highlight.readOnly}<br>
|
|
281
|
+
<b>Start:</b> #${event.detail.highlight.startParagraphId}, offset ${event.detail.highlight.startParagraphOffset}<br>
|
|
282
|
+
<b>End:</b> #${event.detail.highlight.endParagraphId}, offset ${event.detail.highlight.endParagraphOffset}
|
|
283
|
+
`;
|
|
284
|
+
const annotatedParagraphs = container.querySelectorAll(`#${event.detail.highlight.rangeParagraphIds.join(', #')}`);
|
|
285
|
+
for (const annotatedParagraph of annotatedParagraphs) {
|
|
286
|
+
const snippetParagraph = annotatedParagraph.cloneNode(true);
|
|
287
|
+
snippetParagraph.id = `${snippetParagraph.id}_${event.detail.highlight.highlightId}`;
|
|
288
|
+
snippetDiv.append(snippetParagraph);
|
|
289
|
+
}
|
|
290
|
+
const snippetHighlights = [
|
|
291
|
+
{
|
|
292
|
+
highlightId: event.detail.highlight.highlightId + '_snippet',
|
|
293
|
+
readOnly: true,
|
|
294
|
+
color: event.detail.highlight.color, style: event.detail.highlight.style,
|
|
295
|
+
startParagraphId: `${event.detail.highlight.startParagraphId}_${event.detail.highlight.highlightId}`, startParagraphOffset: event.detail.highlight.startParagraphOffset,
|
|
296
|
+
endParagraphId: `${event.detail.highlight.endParagraphId}_${event.detail.highlight.highlightId}`, endParagraphOffset: event.detail.highlight.endParagraphOffset,
|
|
297
|
+
},
|
|
298
|
+
];
|
|
299
|
+
const snippetHighlighter = new Highlighter({
|
|
300
|
+
containerSelector: '#snippet-container',
|
|
301
|
+
paragraphSelector: '#snippet [id]',
|
|
302
|
+
});
|
|
303
|
+
snippetHighlighter.loadHighlights(snippetHighlights);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Respond to highlight deactivate event
|
|
307
|
+
container.addEventListener('hh:highlightdeactivate', clearHighlightInfo);
|
|
308
|
+
function clearHighlightInfo(event) {
|
|
309
|
+
snippetDiv.innerHTML = '';
|
|
310
|
+
infoDiv.innerHTML = 'N/A';
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Respond to ambiguous action events (when a user taps on overlapping highlights, or an overlapping link and highlight)
|
|
314
|
+
const disambiguationPanel = document.getElementById('disambiguation-panel');
|
|
315
|
+
const disambiguationButtonsDiv = document.getElementById('disambiguation-buttons');
|
|
316
|
+
const disambiguationCancelButton = document.getElementById('disambiguation-cancel');
|
|
317
|
+
disambiguationCancelButton.addEventListener('click', (event) => disambiguationPanel.close());
|
|
318
|
+
container.addEventListener('hh:ambiguousaction', handleAmbiguousAction);
|
|
319
|
+
function handleAmbiguousAction(event) {
|
|
320
|
+
disambiguationButtonsDiv.innerHTML = '';
|
|
321
|
+
for (const highlight of event.detail.highlights) {
|
|
322
|
+
let buttonStyle = highlighter.getOptions().styles[highlight.style]['css']
|
|
323
|
+
let buttonHtml = `
|
|
324
|
+
<button data-color="${highlight.color}" onclick="disambiguationPanel.close();highlighter.activateHighlight('${highlight.highlightId}');">
|
|
325
|
+
<span style="${buttonStyle}">${highlight.rangeHtml}</span>
|
|
326
|
+
</button>
|
|
327
|
+
`;
|
|
328
|
+
disambiguationButtonsDiv.insertAdjacentHTML('beforeend', buttonHtml);
|
|
329
|
+
}
|
|
330
|
+
for (const hyperlink of event.detail.hyperlinks) {
|
|
331
|
+
let buttonStyle = 'color: var(--gray-50); text-decoration: underline;'
|
|
332
|
+
let buttonHtml = `
|
|
333
|
+
<button onclick="disambiguationPanel.close();highlighter.activateHyperlink(${hyperlink.position});">
|
|
334
|
+
<span style="${buttonStyle}">${hyperlink.text}</span>
|
|
335
|
+
</button>
|
|
336
|
+
`;
|
|
337
|
+
disambiguationButtonsDiv.insertAdjacentHTML('beforeend', buttonHtml);
|
|
338
|
+
}
|
|
339
|
+
// TODO: Waiting 10 milliseconds before showing the disambiguation panel is a workaround for an issue in Android Chrome where a click event fires right after the pointerup event that triggered hh:ambiguousaction. If the click event happens to be at the same position as a button in the panel, the button will receive the click, dismissing the panel before the user sees it.
|
|
340
|
+
setTimeout(function() { disambiguationPanel.showModal(); }, 10);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Log events for debugging
|
|
344
|
+
container.addEventListener('hh:highlightcreate', console.info)
|
|
345
|
+
container.addEventListener('hh:highlightupdate', console.info)
|
|
346
|
+
container.addEventListener('hh:highlightremove', console.info)
|
|
347
|
+
container.addEventListener('hh:highlightsload', console.info)
|
|
348
|
+
container.addEventListener('hh:highlightactivate', console.info)
|
|
349
|
+
container.addEventListener('hh:highlightdeactivate', console.info)
|
|
350
|
+
container.addEventListener('hh:selectionupdate', console.info)
|
|
351
|
+
container.addEventListener('hh:ambiguousaction', console.info)
|
|
352
|
+
container.addEventListener('hh:tap', console.info)
|
|
353
|
+
|
|
354
|
+
// snippetDiv.addEventListener('hh:highlightcreate', console.warn)
|
|
355
|
+
// snippetDiv.addEventListener('hh:highlightupdate', console.warn)
|
|
356
|
+
// snippetDiv.addEventListener('hh:highlightremove', console.warn)
|
|
357
|
+
// snippetDiv.addEventListener('hh:highlightsload', console.warn)
|
|
358
|
+
// snippetDiv.addEventListener('hh:highlightactivate', console.warn)
|
|
359
|
+
// snippetDiv.addEventListener('hh:highlightdeactivate', console.warn)
|
|
360
|
+
// snippetDiv.addEventListener('hh:selectionupdate', console.warn)
|
|
361
|
+
// snippetDiv.addEventListener('hh:ambiguousaction', console.warn)
|
|
362
|
+
// snippetDiv.addEventListener('hh:tap', console.warn)
|
|
363
|
+
</script>
|
|
364
|
+
</body>
|
|
365
|
+
</html>
|