@riebeckite/plugin-text-fragment 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Rerurate_514
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # @riebeckite/plugin-text-fragment
2
+
3
+ Copy a Text Fragment deep link (`#:~:text=`) or a Markdown quote for the text
4
+ you select in an article.
5
+
6
+ [日本語](./README_ja.md)
7
+
8
+ ## Overview
9
+
10
+ Client-only plugin. On page load it installs one selection popover with two
11
+ actions:
12
+
13
+ - **リンクをコピー** — builds a URL with a
14
+ [Text Fragment directive](https://wicg.github.io/scroll-to-text-fragment/)
15
+ that highlights the selected text.
16
+ - **引用をコピー** — builds a Markdown block quote with a link back to the page.
17
+
18
+ ## Usage
19
+
20
+ ```ts
21
+ import { defineConfig } from "@riebeckite/core";
22
+ import { textFragmentPlugin } from "@riebeckite/plugin-text-fragment";
23
+
24
+ export default defineConfig({
25
+ // ...
26
+ plugins: [textFragmentPlugin()],
27
+ });
28
+ ```
29
+
30
+ `textFragmentPlugin()` registers `style.css` and the `initTextFragmentShare`
31
+ client entry, which the app calls during page initialization.
32
+
33
+ ## Behavior
34
+
35
+ - A non-empty selection inside the article body shows the popover near the
36
+ selection. Selections inside `pre`, `code`, `a[href]`, or `[data-no-share]`
37
+ are ignored.
38
+ - Both actions write to the clipboard through `navigator.clipboard.writeText`
39
+ and fall back to a hidden textarea with `document.execCommand("copy")`.
40
+ - Failures are announced in a visible `aria-live="polite"` status region.
41
+ - `Escape` or a click outside closes the popover. The buttons are real
42
+ `<button>` elements, so they are reachable with the keyboard.
43
+ - The popover is installed once per page and does nothing when there is no
44
+ `document` (SSR-safe).
45
+
46
+ ### URL rules
47
+
48
+ The fragment follows `#:~:text=[prefix-,]start[,end][,-suffix]`:
49
+
50
+ - `,`, `-` and `&` are percent-encoded (`%2C`, `%2D`, `%26`).
51
+ - Other characters are encoded per UTF-8 (newlines become `%0A`).
52
+ - An existing hash on the page URL is dropped before the directive is appended.
53
+ - Selections longer than ~200 characters or containing a newline are reduced to
54
+ a `start,end` range built from the first and last token.
55
+ - An empty or whitespace-only selection produces `""`.
56
+
57
+ ## API
58
+
59
+ - `textFragmentPlugin()` — plugin factory
60
+ - `initTextFragmentShare()` — client initializer (also via
61
+ `@riebeckite/plugin-text-fragment/client`)
62
+ - `encodeTextFragment(text)` — percent-encodes one text fragment term
63
+ - `buildTextFragmentUrl(pageUrl, selection, options?)` — builds the deep link;
64
+ `options` is `{ prefix?, suffix? }`
65
+ - `buildQuoteMarkdown({ url, title, selection })` — builds the Markdown quote
66
+ - Type: `TextFragmentOptions`
67
+
68
+ ## See also
69
+
70
+ - [Plugin guide](../../docs/plugins_en.md)
package/README_ja.md ADDED
@@ -0,0 +1,57 @@
1
+ # @riebeckite/plugin-text-fragment
2
+
3
+ 記事内で選択したテキストから、Text Fragment のディープリンク(`#:~:text=`)と Markdown の引用を作るプラグインです。
4
+
5
+ [English](./README_en.md)
6
+
7
+ ## できること
8
+
9
+ クライアント専用のプラグインです。ページ表示時に、選択範囲のそばへ小さなポップオーバーを出し、次の二つをコピーできます。
10
+
11
+ - **リンクをコピー**: 選択したテキストをハイライトする [Text Fragment](https://wicg.github.io/scroll-to-text-fragment/) 付き URL を作ります。
12
+ - **引用をコピー**: ページへのリンク付きで Markdown の引用ブロックを作ります。
13
+
14
+ ## 設定する
15
+
16
+ ```ts
17
+ import { defineConfig } from "@riebeckite/core";
18
+ import { textFragmentPlugin } from "@riebeckite/plugin-text-fragment";
19
+
20
+ export default defineConfig({
21
+ // ...
22
+ plugins: [textFragmentPlugin()],
23
+ });
24
+ ```
25
+
26
+ `textFragmentPlugin()` はスタイルと `initTextFragmentShare` を登録します。初期化処理はアプリのページ初期化時に呼ばれます。
27
+
28
+ ## 挙動
29
+
30
+ - 記事本文内でテキストを選択すると、そのそばにポップオーバーが出ます。`pre`、`code`、`a[href]`、`[data-no-share]` の中の選択は対象外です。
31
+ - コピーは `navigator.clipboard.writeText` を使い、失敗時は隠し textarea と `document.execCommand("copy")` に切り替えます。
32
+ - コピーに失敗したときは `aria-live="polite"` の領域にメッセージを表示します。
33
+ - `Escape` またはポップオーバーの外側をクリックすると閉じます。ボタンは実体の `<button>` なのでキーボードでも操作できます。
34
+ - 初期化はページごとに一度だけで、`document` が無い環境では何もしません。
35
+
36
+ ### URL の規則
37
+
38
+ フラグメントは `#:~:text=[prefix-,]start[,end][,-suffix]` に従います。
39
+
40
+ - `,`、`-`、`&` はパーセントエンコードします(`%2C`、`%2D`、`%26`)。
41
+ - それ以外は UTF-8 単位でエンコードします(改行は `%0A`)。
42
+ - ページ URL に既存のハッシュがあるときは、それを外してからディレクティブを付けます。
43
+ - 200 文字前後より長い選択、または改行を含む選択は、先頭と末尾のトークンによる `start,end` に短縮します。
44
+ - 空または空白だけの選択は `""` を返します。
45
+
46
+ ## 公開 API
47
+
48
+ - `textFragmentPlugin()` — プラグインファクトリ
49
+ - `initTextFragmentShare()` — ブラウザ初期化関数(`@riebeckite/plugin-text-fragment/client` からも読み込める)
50
+ - `encodeTextFragment(text)` — テキスト片をパーセントエンコードする
51
+ - `buildTextFragmentUrl(pageUrl, selection, options?)` — ディープリンクを作る。`options` は `{ prefix?, suffix? }`
52
+ - `buildQuoteMarkdown({ url, title, selection })` — 引用ブロックを作る
53
+ - `TextFragmentOptions` — オプションの型
54
+
55
+ ## 関連資料
56
+
57
+ - [プラグインシステム](../../../docs/ja/plugin-system.md)
@@ -0,0 +1 @@
1
+ export { initTextFragmentShare } from "./src/text-fragment.client.js";
package/dist/client.js ADDED
@@ -0,0 +1,234 @@
1
+ // src/text-fragment.ts
2
+ var TEXT_FRAGMENT_PREFIX = "#:~:text=";
3
+ var MAX_TEXT_FRAGMENT_LENGTH = 200;
4
+ var NEWLINE_PATTERN = /\r\n|\r|\n/g;
5
+ var NEWLINE_TEST = /[\r\n]/;
6
+ function encodeTextFragment(text) {
7
+ let encoded;
8
+ try {
9
+ encoded = encodeURIComponent(text);
10
+ } catch {
11
+ encoded = encodeURIComponent(text.replace(/[\uD800-\uDFFF]/g, "�"));
12
+ }
13
+ return encoded.replace(/&/g, "%26").replace(/,/g, "%2C").replace(/-/g, "%2D");
14
+ }
15
+ function buildTextFragmentUrl(pageUrl, selection, options = {}) {
16
+ const directive = buildTextDirective(selection, options);
17
+ if (directive.length === 0) return "";
18
+ return `${stripUrlFragment(pageUrl)}${TEXT_FRAGMENT_PREFIX}${directive}`;
19
+ }
20
+ function buildQuoteMarkdown(args) {
21
+ const quoted = normalizeNewlines(args.selection).split("\n").map((line) => line.length > 0 ? `> ${line}` : ">").join("\n");
22
+ return `${quoted}
23
+ > — [${args.title}](${args.url})`;
24
+ }
25
+ function buildTextDirective(selection, options) {
26
+ const normalized = normalizeNewlines(selection).trim();
27
+ if (normalized.length === 0) return "";
28
+ const prefix = normalizeNewlines(options.prefix ?? "").trim();
29
+ const suffix = normalizeNewlines(options.suffix ?? "").trim();
30
+ const useRange = normalized.length > MAX_TEXT_FRAGMENT_LENGTH || NEWLINE_TEST.test(selection);
31
+ let match;
32
+ if (useRange) {
33
+ const tokens = normalized.split(/\s+/).filter(Boolean);
34
+ const start = tokens[0] ?? normalized;
35
+ const end = tokens.length > 1 ? tokens[tokens.length - 1] : "";
36
+ match = end.length > 0 ? `${encodeTextFragment(start)},${encodeTextFragment(end)}` : encodeTextFragment(start);
37
+ } else {
38
+ match = encodeTextFragment(normalized);
39
+ }
40
+ const prefixPart = prefix.length > 0 ? `${encodeTextFragment(prefix)}-,` : "";
41
+ const suffixPart = suffix.length > 0 ? `,-${encodeTextFragment(suffix)}` : "";
42
+ return `${prefixPart}${match}${suffixPart}`;
43
+ }
44
+ function normalizeNewlines(value) {
45
+ return value.replace(NEWLINE_PATTERN, "\n");
46
+ }
47
+ function stripUrlFragment(url) {
48
+ const index = url.indexOf("#");
49
+ return index === -1 ? url : url.slice(0, index);
50
+ }
51
+
52
+ // src/text-fragment.client.ts
53
+ var ARTICLE_SELECTOR = "[data-slot='article-body'], .rb-article-body, .prose, article";
54
+ var EXCLUDED_SELECTOR = "pre, code, a[href], [data-no-share]";
55
+ var POPOVER_GAP = 8;
56
+ var initialized = false;
57
+ function initTextFragmentShare() {
58
+ if (typeof document === "undefined") return;
59
+ if (initialized) return;
60
+ initialized = true;
61
+ const popover = document.createElement("div");
62
+ popover.className = "rr-text-fragment";
63
+ popover.hidden = true;
64
+ popover.setAttribute("role", "group");
65
+ popover.setAttribute("aria-label", "選択したテキストを共有");
66
+ const actions = document.createElement("div");
67
+ actions.className = "rr-text-fragment__actions";
68
+ const linkButton = createButton("リンクをコピー");
69
+ const quoteButton = createButton("引用をコピー");
70
+ const status = document.createElement("p");
71
+ status.className = "rr-text-fragment__status";
72
+ status.setAttribute("role", "status");
73
+ status.setAttribute("aria-live", "polite");
74
+ actions.append(linkButton, quoteButton);
75
+ popover.append(actions, status);
76
+ document.body.appendChild(popover);
77
+ let active = null;
78
+ let isCopying = false;
79
+ const hide = () => {
80
+ active = null;
81
+ popover.hidden = true;
82
+ status.textContent = "";
83
+ };
84
+ const show = (selection, resetStatus) => {
85
+ active = selection;
86
+ if (resetStatus) status.textContent = "";
87
+ popover.hidden = false;
88
+ positionPopover(popover, selection.rect);
89
+ };
90
+ const refresh = () => {
91
+ if (isCopying) return;
92
+ const selection = readShareableSelection();
93
+ if (!selection) {
94
+ hide();
95
+ return;
96
+ }
97
+ show(selection, active?.text !== selection.text);
98
+ };
99
+ const copy = async (buildValue, successMessage) => {
100
+ const selection = active;
101
+ if (!selection) return;
102
+ isCopying = true;
103
+ try {
104
+ const copied = await copyToClipboard(buildValue(selection.text));
105
+ status.textContent = copied ? successMessage : "コピーできませんでした。テキストを選び直してください。";
106
+ active = selection;
107
+ popover.hidden = false;
108
+ positionPopover(popover, selection.rect);
109
+ } finally {
110
+ window.setTimeout(() => {
111
+ isCopying = false;
112
+ }, 0);
113
+ }
114
+ };
115
+ linkButton.addEventListener("click", () => {
116
+ void copy(
117
+ (selection) => buildTextFragmentUrl(resolvePageUrl(), selection),
118
+ "リンクをコピーしました"
119
+ );
120
+ });
121
+ quoteButton.addEventListener("click", () => {
122
+ void copy(
123
+ (selection) => buildQuoteMarkdown({
124
+ url: resolvePageUrl(),
125
+ title: document.title,
126
+ selection
127
+ }),
128
+ "引用をコピーしました"
129
+ );
130
+ });
131
+ popover.addEventListener("mousedown", (event) => event.preventDefault());
132
+ document.addEventListener("selectionchange", refresh);
133
+ document.addEventListener("mouseup", refresh);
134
+ document.addEventListener("keyup", refresh);
135
+ document.addEventListener("keydown", (event) => {
136
+ if (event.key === "Escape" && !popover.hidden) {
137
+ event.preventDefault();
138
+ hide();
139
+ }
140
+ });
141
+ document.addEventListener("mousedown", (event) => {
142
+ if (popover.hidden) return;
143
+ if (event.target instanceof Node && popover.contains(event.target)) return;
144
+ hide();
145
+ });
146
+ window.addEventListener("scroll", hide, { passive: true });
147
+ }
148
+ function createButton(label) {
149
+ const button = document.createElement("button");
150
+ button.type = "button";
151
+ button.className = "rr-text-fragment__button";
152
+ button.textContent = label;
153
+ return button;
154
+ }
155
+ function readShareableSelection() {
156
+ const selection = window.getSelection();
157
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
158
+ return null;
159
+ }
160
+ const text = selection.toString().trim();
161
+ if (text.length === 0) return null;
162
+ const range = selection.getRangeAt(0);
163
+ if (!isShareableNode(range.startContainer) || !isShareableNode(range.endContainer)) {
164
+ return null;
165
+ }
166
+ const rect = range.getBoundingClientRect();
167
+ if (rect.width === 0 && rect.height === 0) return null;
168
+ return { text, rect };
169
+ }
170
+ function isShareableNode(node) {
171
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
172
+ if (!element) return false;
173
+ if (element.closest(EXCLUDED_SELECTOR)) return false;
174
+ return element.closest(ARTICLE_SELECTOR) !== null;
175
+ }
176
+ function positionPopover(popover, rect) {
177
+ const width = popover.offsetWidth;
178
+ const height = popover.offsetHeight;
179
+ let left = rect.left + rect.width / 2 - width / 2;
180
+ let top = rect.top - height - POPOVER_GAP;
181
+ if (top < POPOVER_GAP) top = rect.bottom + POPOVER_GAP;
182
+ left = Math.max(
183
+ POPOVER_GAP,
184
+ Math.min(left, window.innerWidth - width - POPOVER_GAP)
185
+ );
186
+ popover.style.left = `${Math.round(left)}px`;
187
+ popover.style.top = `${Math.round(top)}px`;
188
+ }
189
+ function resolvePageUrl() {
190
+ return window.location.href.split("#")[0] ?? window.location.href;
191
+ }
192
+ async function copyToClipboard(value) {
193
+ try {
194
+ if (window.isSecureContext && navigator.clipboard) {
195
+ await navigator.clipboard.writeText(value);
196
+ return true;
197
+ }
198
+ } catch {
199
+ }
200
+ return copyWithExecCommand(value);
201
+ }
202
+ function copyWithExecCommand(value) {
203
+ const selection = window.getSelection();
204
+ const savedRanges = [];
205
+ if (selection) {
206
+ for (let index = 0; index < selection.rangeCount; index += 1) {
207
+ savedRanges.push(selection.getRangeAt(index).cloneRange());
208
+ }
209
+ }
210
+ const textarea = document.createElement("textarea");
211
+ textarea.value = value;
212
+ textarea.setAttribute("readonly", "");
213
+ textarea.style.position = "fixed";
214
+ textarea.style.top = "-1000px";
215
+ textarea.style.opacity = "0";
216
+ document.body.appendChild(textarea);
217
+ textarea.select();
218
+ let copied = false;
219
+ try {
220
+ copied = document.execCommand("copy");
221
+ } catch {
222
+ copied = false;
223
+ } finally {
224
+ textarea.remove();
225
+ if (selection && savedRanges.length > 0) {
226
+ selection.removeAllRanges();
227
+ for (const range of savedRanges) selection.addRange(range);
228
+ }
229
+ }
230
+ return copied;
231
+ }
232
+ export {
233
+ initTextFragmentShare
234
+ };
@@ -0,0 +1,8 @@
1
+ import { type RiebeckitePlugin } from "@riebeckite/core";
2
+ export { buildQuoteMarkdown, buildTextFragmentUrl, encodeTextFragment, type TextFragmentOptions, } from "./src/text-fragment.js";
3
+ export { initTextFragmentShare } from "./src/text-fragment.client.js";
4
+ /**
5
+ * Registers the client-only text fragment share plugin: a selection popover
6
+ * that copies a `#:~:text=` deep link or a Markdown quote.
7
+ */
8
+ export declare function textFragmentPlugin(): RiebeckitePlugin;
package/dist/index.js ADDED
@@ -0,0 +1,256 @@
1
+ // index.ts
2
+ import {
3
+ createClientEntry,
4
+ createStyleAsset,
5
+ definePlugin
6
+ } from "@riebeckite/core";
7
+
8
+ // src/text-fragment.ts
9
+ var TEXT_FRAGMENT_PREFIX = "#:~:text=";
10
+ var MAX_TEXT_FRAGMENT_LENGTH = 200;
11
+ var NEWLINE_PATTERN = /\r\n|\r|\n/g;
12
+ var NEWLINE_TEST = /[\r\n]/;
13
+ function encodeTextFragment(text) {
14
+ let encoded;
15
+ try {
16
+ encoded = encodeURIComponent(text);
17
+ } catch {
18
+ encoded = encodeURIComponent(text.replace(/[\uD800-\uDFFF]/g, "�"));
19
+ }
20
+ return encoded.replace(/&/g, "%26").replace(/,/g, "%2C").replace(/-/g, "%2D");
21
+ }
22
+ function buildTextFragmentUrl(pageUrl, selection, options = {}) {
23
+ const directive = buildTextDirective(selection, options);
24
+ if (directive.length === 0) return "";
25
+ return `${stripUrlFragment(pageUrl)}${TEXT_FRAGMENT_PREFIX}${directive}`;
26
+ }
27
+ function buildQuoteMarkdown(args) {
28
+ const quoted = normalizeNewlines(args.selection).split("\n").map((line) => line.length > 0 ? `> ${line}` : ">").join("\n");
29
+ return `${quoted}
30
+ > — [${args.title}](${args.url})`;
31
+ }
32
+ function buildTextDirective(selection, options) {
33
+ const normalized = normalizeNewlines(selection).trim();
34
+ if (normalized.length === 0) return "";
35
+ const prefix = normalizeNewlines(options.prefix ?? "").trim();
36
+ const suffix = normalizeNewlines(options.suffix ?? "").trim();
37
+ const useRange = normalized.length > MAX_TEXT_FRAGMENT_LENGTH || NEWLINE_TEST.test(selection);
38
+ let match;
39
+ if (useRange) {
40
+ const tokens = normalized.split(/\s+/).filter(Boolean);
41
+ const start = tokens[0] ?? normalized;
42
+ const end = tokens.length > 1 ? tokens[tokens.length - 1] : "";
43
+ match = end.length > 0 ? `${encodeTextFragment(start)},${encodeTextFragment(end)}` : encodeTextFragment(start);
44
+ } else {
45
+ match = encodeTextFragment(normalized);
46
+ }
47
+ const prefixPart = prefix.length > 0 ? `${encodeTextFragment(prefix)}-,` : "";
48
+ const suffixPart = suffix.length > 0 ? `,-${encodeTextFragment(suffix)}` : "";
49
+ return `${prefixPart}${match}${suffixPart}`;
50
+ }
51
+ function normalizeNewlines(value) {
52
+ return value.replace(NEWLINE_PATTERN, "\n");
53
+ }
54
+ function stripUrlFragment(url) {
55
+ const index = url.indexOf("#");
56
+ return index === -1 ? url : url.slice(0, index);
57
+ }
58
+
59
+ // src/text-fragment.client.ts
60
+ var ARTICLE_SELECTOR = "[data-slot='article-body'], .rb-article-body, .prose, article";
61
+ var EXCLUDED_SELECTOR = "pre, code, a[href], [data-no-share]";
62
+ var POPOVER_GAP = 8;
63
+ var initialized = false;
64
+ function initTextFragmentShare() {
65
+ if (typeof document === "undefined") return;
66
+ if (initialized) return;
67
+ initialized = true;
68
+ const popover = document.createElement("div");
69
+ popover.className = "rr-text-fragment";
70
+ popover.hidden = true;
71
+ popover.setAttribute("role", "group");
72
+ popover.setAttribute("aria-label", "選択したテキストを共有");
73
+ const actions = document.createElement("div");
74
+ actions.className = "rr-text-fragment__actions";
75
+ const linkButton = createButton("リンクをコピー");
76
+ const quoteButton = createButton("引用をコピー");
77
+ const status = document.createElement("p");
78
+ status.className = "rr-text-fragment__status";
79
+ status.setAttribute("role", "status");
80
+ status.setAttribute("aria-live", "polite");
81
+ actions.append(linkButton, quoteButton);
82
+ popover.append(actions, status);
83
+ document.body.appendChild(popover);
84
+ let active = null;
85
+ let isCopying = false;
86
+ const hide = () => {
87
+ active = null;
88
+ popover.hidden = true;
89
+ status.textContent = "";
90
+ };
91
+ const show = (selection, resetStatus) => {
92
+ active = selection;
93
+ if (resetStatus) status.textContent = "";
94
+ popover.hidden = false;
95
+ positionPopover(popover, selection.rect);
96
+ };
97
+ const refresh = () => {
98
+ if (isCopying) return;
99
+ const selection = readShareableSelection();
100
+ if (!selection) {
101
+ hide();
102
+ return;
103
+ }
104
+ show(selection, active?.text !== selection.text);
105
+ };
106
+ const copy = async (buildValue, successMessage) => {
107
+ const selection = active;
108
+ if (!selection) return;
109
+ isCopying = true;
110
+ try {
111
+ const copied = await copyToClipboard(buildValue(selection.text));
112
+ status.textContent = copied ? successMessage : "コピーできませんでした。テキストを選び直してください。";
113
+ active = selection;
114
+ popover.hidden = false;
115
+ positionPopover(popover, selection.rect);
116
+ } finally {
117
+ window.setTimeout(() => {
118
+ isCopying = false;
119
+ }, 0);
120
+ }
121
+ };
122
+ linkButton.addEventListener("click", () => {
123
+ void copy(
124
+ (selection) => buildTextFragmentUrl(resolvePageUrl(), selection),
125
+ "リンクをコピーしました"
126
+ );
127
+ });
128
+ quoteButton.addEventListener("click", () => {
129
+ void copy(
130
+ (selection) => buildQuoteMarkdown({
131
+ url: resolvePageUrl(),
132
+ title: document.title,
133
+ selection
134
+ }),
135
+ "引用をコピーしました"
136
+ );
137
+ });
138
+ popover.addEventListener("mousedown", (event) => event.preventDefault());
139
+ document.addEventListener("selectionchange", refresh);
140
+ document.addEventListener("mouseup", refresh);
141
+ document.addEventListener("keyup", refresh);
142
+ document.addEventListener("keydown", (event) => {
143
+ if (event.key === "Escape" && !popover.hidden) {
144
+ event.preventDefault();
145
+ hide();
146
+ }
147
+ });
148
+ document.addEventListener("mousedown", (event) => {
149
+ if (popover.hidden) return;
150
+ if (event.target instanceof Node && popover.contains(event.target)) return;
151
+ hide();
152
+ });
153
+ window.addEventListener("scroll", hide, { passive: true });
154
+ }
155
+ function createButton(label) {
156
+ const button = document.createElement("button");
157
+ button.type = "button";
158
+ button.className = "rr-text-fragment__button";
159
+ button.textContent = label;
160
+ return button;
161
+ }
162
+ function readShareableSelection() {
163
+ const selection = window.getSelection();
164
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
165
+ return null;
166
+ }
167
+ const text = selection.toString().trim();
168
+ if (text.length === 0) return null;
169
+ const range = selection.getRangeAt(0);
170
+ if (!isShareableNode(range.startContainer) || !isShareableNode(range.endContainer)) {
171
+ return null;
172
+ }
173
+ const rect = range.getBoundingClientRect();
174
+ if (rect.width === 0 && rect.height === 0) return null;
175
+ return { text, rect };
176
+ }
177
+ function isShareableNode(node) {
178
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
179
+ if (!element) return false;
180
+ if (element.closest(EXCLUDED_SELECTOR)) return false;
181
+ return element.closest(ARTICLE_SELECTOR) !== null;
182
+ }
183
+ function positionPopover(popover, rect) {
184
+ const width = popover.offsetWidth;
185
+ const height = popover.offsetHeight;
186
+ let left = rect.left + rect.width / 2 - width / 2;
187
+ let top = rect.top - height - POPOVER_GAP;
188
+ if (top < POPOVER_GAP) top = rect.bottom + POPOVER_GAP;
189
+ left = Math.max(
190
+ POPOVER_GAP,
191
+ Math.min(left, window.innerWidth - width - POPOVER_GAP)
192
+ );
193
+ popover.style.left = `${Math.round(left)}px`;
194
+ popover.style.top = `${Math.round(top)}px`;
195
+ }
196
+ function resolvePageUrl() {
197
+ return window.location.href.split("#")[0] ?? window.location.href;
198
+ }
199
+ async function copyToClipboard(value) {
200
+ try {
201
+ if (window.isSecureContext && navigator.clipboard) {
202
+ await navigator.clipboard.writeText(value);
203
+ return true;
204
+ }
205
+ } catch {
206
+ }
207
+ return copyWithExecCommand(value);
208
+ }
209
+ function copyWithExecCommand(value) {
210
+ const selection = window.getSelection();
211
+ const savedRanges = [];
212
+ if (selection) {
213
+ for (let index = 0; index < selection.rangeCount; index += 1) {
214
+ savedRanges.push(selection.getRangeAt(index).cloneRange());
215
+ }
216
+ }
217
+ const textarea = document.createElement("textarea");
218
+ textarea.value = value;
219
+ textarea.setAttribute("readonly", "");
220
+ textarea.style.position = "fixed";
221
+ textarea.style.top = "-1000px";
222
+ textarea.style.opacity = "0";
223
+ document.body.appendChild(textarea);
224
+ textarea.select();
225
+ let copied = false;
226
+ try {
227
+ copied = document.execCommand("copy");
228
+ } catch {
229
+ copied = false;
230
+ } finally {
231
+ textarea.remove();
232
+ if (selection && savedRanges.length > 0) {
233
+ selection.removeAllRanges();
234
+ for (const range of savedRanges) selection.addRange(range);
235
+ }
236
+ }
237
+ return copied;
238
+ }
239
+
240
+ // index.ts
241
+ function textFragmentPlugin() {
242
+ return definePlugin({
243
+ name: "text-fragment",
244
+ assets: [createStyleAsset("text-fragment")],
245
+ clientEntries: [
246
+ createClientEntry("text-fragment", "initTextFragmentShare")
247
+ ]
248
+ });
249
+ }
250
+ export {
251
+ buildQuoteMarkdown,
252
+ buildTextFragmentUrl,
253
+ encodeTextFragment,
254
+ initTextFragmentShare,
255
+ textFragmentPlugin
256
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Enables a popover with "リンクをコピー" (text fragment deep link) and
3
+ * "引用をコピー" (Markdown quote) actions for the current text selection.
4
+ *
5
+ * Client-only: returns immediately when there is no `document`, and only wires
6
+ * its listeners once per page.
7
+ */
8
+ export declare function initTextFragmentShare(): void;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Pure helpers for URL Fragment Text Directives.
3
+ *
4
+ * Syntax (WICG scroll-to-text-fragment):
5
+ * `#:~:text=[prefix-,]start[,end][,-suffix]`
6
+ */
7
+ export type TextFragmentOptions = {
8
+ /** Text immediately before the selection, used to disambiguate it. */
9
+ prefix?: string;
10
+ /** Text immediately after the selection, used to disambiguate it. */
11
+ suffix?: string;
12
+ };
13
+ /**
14
+ * Percent-encodes a text fragment term.
15
+ *
16
+ * `,` `-` and `&` are reserved by the text directive grammar and are always
17
+ * encoded (`%2C`, `%2D`, `%26`). Everything else is encoded per UTF-8, so
18
+ * multibyte characters (Japanese, emoji) survive the round trip and newlines
19
+ * become `%0A`.
20
+ */
21
+ export declare function encodeTextFragment(text: string): string;
22
+ /**
23
+ * Builds a deep link that highlights `selection` on `pageUrl`.
24
+ *
25
+ * Returns `""` for an empty or whitespace-only selection. Any existing hash on
26
+ * `pageUrl` is dropped before the fragment directive is appended. When the
27
+ * selection is longer than ~200 characters or contains a newline, it is reduced
28
+ * to a `start,end` range built from its first and last token.
29
+ */
30
+ export declare function buildTextFragmentUrl(pageUrl: string, selection: string, options?: TextFragmentOptions): string;
31
+ /**
32
+ * Builds a Markdown block quote for `selection` followed by a credit line that
33
+ * links to `url`. Every line of the selection is prefixed with `> `.
34
+ */
35
+ export declare function buildQuoteMarkdown(args: {
36
+ url: string;
37
+ title: string;
38
+ selection: string;
39
+ }): string;
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@riebeckite/plugin-text-fragment",
3
+ "version": "0.0.1",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "source": "./index.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./client": {
16
+ "types": "./dist/client.d.ts",
17
+ "import": "./dist/client.js",
18
+ "source": "./client.ts",
19
+ "default": "./dist/client.js"
20
+ },
21
+ "./style.css": "./style.css"
22
+ },
23
+ "dependencies": {
24
+ "@riebeckite/core": "0.0.1"
25
+ },
26
+ "devDependencies": {
27
+ "tsx": "^4.22.4"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "LICENSE",
34
+ "README.md",
35
+ "README_ja.md",
36
+ "dist",
37
+ "style.css"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/Rerurate514/riebeckite.git",
42
+ "directory": "packages/plugins/text-fragment"
43
+ },
44
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
47
+ },
48
+ "description": "Text Fragment links and quotes for Riebeckite articles.",
49
+ "keywords": [
50
+ "riebeckite",
51
+ "plugin",
52
+ "text-fragment",
53
+ "sharing"
54
+ ],
55
+ "engines": {
56
+ "node": "^20.19.0 || >=22.12.0"
57
+ },
58
+ "sideEffects": [
59
+ "./style.css"
60
+ ],
61
+ "scripts": {
62
+ "build": "node ../../../scripts/build_package.mjs",
63
+ "test": "node --import tsx --test \"test/*.test.ts\""
64
+ }
65
+ }
package/style.css ADDED
@@ -0,0 +1,53 @@
1
+ .rr-text-fragment {
2
+ position: fixed;
3
+ z-index: 900;
4
+ display: grid;
5
+ gap: 4px;
6
+ padding: 6px;
7
+ border: 1px solid var(--rb-color-border-strong, #9a9a9a);
8
+ background: var(--rb-color-surface, #ffffff);
9
+ color: var(--rb-color-ink, #1a1a1a);
10
+ }
11
+
12
+ .rr-text-fragment[hidden] {
13
+ display: none;
14
+ }
15
+
16
+ .rr-text-fragment__actions {
17
+ display: flex;
18
+ gap: 4px;
19
+ }
20
+
21
+ .rr-text-fragment__button {
22
+ border: 1px solid var(--rb-color-border, #d0d0d0);
23
+ background: transparent;
24
+ color: inherit;
25
+ padding: 4px 10px;
26
+ font: inherit;
27
+ font-size: 0.8rem;
28
+ line-height: 1.4;
29
+ white-space: nowrap;
30
+ cursor: pointer;
31
+ }
32
+
33
+ .rr-text-fragment__button:hover {
34
+ border-color: var(--rb-color-accent, #686868);
35
+ color: var(--rb-color-accent, #686868);
36
+ }
37
+
38
+ .rr-text-fragment__button:focus-visible {
39
+ outline: 2px solid var(--rb-color-accent, #686868);
40
+ outline-offset: 1px;
41
+ }
42
+
43
+ .rr-text-fragment__status {
44
+ margin: 0;
45
+ max-width: 16rem;
46
+ font-size: 0.72rem;
47
+ line-height: 1.4;
48
+ color: var(--rb-color-muted, #5a5a5a);
49
+ }
50
+
51
+ .rr-text-fragment__status:empty {
52
+ display: none;
53
+ }