@shapio/visual 0.2.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/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 [yyyy] [name of copyright owner]
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,36 @@
1
+ # @shapio/visual
2
+
3
+ Visual editing for sites built on [Shapio](https://github.com/mybrokengnome/shapio): mark the elements that show
4
+ a field, run one script on the preview page, and in Shapio's preview pane a click on the page focuses that field
5
+ in the document. Saves re-render the page. No dependencies, no framework required.
6
+
7
+ ```sh
8
+ npm install @shapio/visual
9
+ ```
10
+
11
+ ```tsx
12
+ import { initVisualEditing, shapioAttr } from '@shapio/visual';
13
+
14
+ // Anywhere a field is rendered (published pages may carry the attributes too):
15
+ <h1 {...shapioAttr(article, 'title')}>{article.title}</h1>
16
+ <h2 {...shapioAttr(page, `sections/${index}/heading`)}>{section.heading}</h2>
17
+
18
+ // On the preview page, once:
19
+ initVisualEditing({ origin: 'https://cms.example.com', onRefresh: () => renderDraft() });
20
+ ```
21
+
22
+ - `shapioAttr(entry, path, locale?)` returns `data-shapio-entry`, `data-shapio-path` and `data-shapio-locale` as
23
+ an object to spread. `entry` is a delivery item (`{ id, locale }`) or an entry ID; `path` uses API IDs, with
24
+ list positions and nested fields after slashes.
25
+ - `initVisualEditing({ origin, onRefresh? })` runs only inside a frame on a URL with `?shapio-visual=1`. It
26
+ outlines marked elements on hover, posts the clicked field to the parent window with `origin` as the target
27
+ (the only origin it talks to), and on a refresh request from that origin calls `onRefresh`, or reloads the
28
+ page when there is none. It returns a function that turns it off.
29
+ - Plain script: `dist/visual.iife.js` (`@shapio/visual/global`) exposes `window.ShapioVisual`, and starts by
30
+ itself when its `<script>` tag has `data-shapio-origin="https://cms.example.com"`.
31
+
32
+ The site also sends `Content-Security-Policy: frame-ancestors 'self' https://cms.example.com`, so only it and
33
+ Shapio can frame its pages. The full guide, including the security model:
34
+ [Visual editing](https://github.com/mybrokengnome/shapio/blob/main/documentation/visual-editing.md).
35
+
36
+ Apache-2.0.
@@ -0,0 +1,86 @@
1
+ //#region src/attributes.d.ts
2
+ /**
3
+ * The attributes a site puts on an element that shows a field, so Shapio's preview can take a click on it back
4
+ * to that field: `<h1 {...shapioAttr(article, 'title')}>`. Paths are API IDs, with list positions and nested
5
+ * fields after slashes (`sections/2/heading`), the same paths the admin uses.
6
+ */
7
+ export declare const ENTRY_ATTRIBUTE = "data-shapio-entry";
8
+ export declare const PATH_ATTRIBUTE = "data-shapio-path";
9
+ export declare const LOCALE_ATTRIBUTE = "data-shapio-locale";
10
+ type ShapioAttributes = {
11
+ 'data-shapio-entry': string;
12
+ 'data-shapio-path': string;
13
+ 'data-shapio-locale'?: string;
14
+ };
15
+ /** An entry as delivery returns it (`{ id, locale }`), or its ID. */
16
+ type EntryRef = string | {
17
+ id: string;
18
+ locale?: string | null | undefined;
19
+ };
20
+ /**
21
+ * A spreadable attribute object for the element that renders `path` of `entry`. The locale is the one given,
22
+ * else the entry's own (delivery items carry the locale that served them); it is left out when unknown.
23
+ */
24
+ export declare const shapioAttr: (entry: EntryRef, path: string, locale?: string) => ShapioAttributes;
25
+ //#endregion
26
+ //#region src/messages.d.ts
27
+ /**
28
+ * The messages between a site in Shapio's preview frame and the admin around it. Every message carries the
29
+ * protocol version; anything that does not parse is ignored. Who may send a message (the frame's window from
30
+ * the preview origin, the parent from the Shapio origin) is checked by each side before parsing.
31
+ */
32
+ export declare const VISUAL_PROTOCOL_VERSION = 1;
33
+ /** The query parameter the admin adds to a preview URL it frames (`?shapio-visual=1`). */
34
+ export declare const VISUAL_QUERY_PARAM = "shapio-visual";
35
+ type VisualReadyMessage = {
36
+ type: 'shapio:ready';
37
+ v: typeof VISUAL_PROTOCOL_VERSION;
38
+ };
39
+ type VisualFocusMessage = {
40
+ type: 'shapio:focus';
41
+ v: typeof VISUAL_PROTOCOL_VERSION;
42
+ entryId: string;
43
+ /** A JSON pointer of API IDs (`/title`, `/sections/2/heading`). */
44
+ path: string;
45
+ locale?: string;
46
+ };
47
+ type VisualRefreshMessage = {
48
+ type: 'shapio:refresh';
49
+ v: typeof VISUAL_PROTOCOL_VERSION;
50
+ };
51
+ /** What the site posts to the admin. */
52
+ type SiteMessage = VisualReadyMessage | VisualFocusMessage;
53
+ /** What the admin posts to the site. */
54
+ type AdminMessage = VisualRefreshMessage;
55
+ /** `title`, `/title` or `sections/2/heading` → a JSON pointer (`/sections/2/heading`); undefined if malformed. */
56
+ export declare const normalizeFieldPath: (path: unknown) => string | undefined;
57
+ /** A message from the site, or undefined when the data is not one. */
58
+ export declare const parseSiteMessage: (data: unknown) => SiteMessage | undefined;
59
+ /** A message from the admin, or undefined when the data is not one. */
60
+ export declare const parseAdminMessage: (data: unknown) => AdminMessage | undefined;
61
+ //#endregion
62
+ //#region src/visualEditing.d.ts
63
+ type VisualEditingOptions = {
64
+ /** Shapio's public URL (or origin). Messages go to this origin only, and only its messages are accepted. */
65
+ origin: string;
66
+ /**
67
+ * Re-renders the page with the current draft after an edit. Without it the page reloads, which is right for a
68
+ * page that reads its preview token from the URL on every load; a page that drops the token from the address
69
+ * bar must re-fetch here instead.
70
+ */
71
+ onRefresh?: () => void | Promise<void>;
72
+ /** The window to run in (tests); defaults to the global one. */
73
+ window?: Window;
74
+ };
75
+ /** Visual editing runs only inside a frame, on a URL the admin opened with `?shapio-visual=1`. */
76
+ export declare const isVisualEditingRequested: (win: Window) => boolean;
77
+ /**
78
+ * Turns on visual editing when the page is in Shapio's preview frame: outlines elements carrying
79
+ * `shapioAttr(...)` attributes on hover, tells the admin which field was clicked, and re-renders when the admin
80
+ * saves. Posts only to the configured Shapio origin and accepts only that origin's messages from the parent
81
+ * window. Outside the preview frame it does nothing. Returns a function that turns it off.
82
+ */
83
+ export declare const initVisualEditing: (options: VisualEditingOptions) => (() => void);
84
+ //#endregion
85
+ export type { AdminMessage, EntryRef, ShapioAttributes, SiteMessage, VisualEditingOptions, VisualFocusMessage, VisualReadyMessage, VisualRefreshMessage };
86
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,163 @@
1
+ //#region src/attributes.ts
2
+ /**
3
+ * The attributes a site puts on an element that shows a field, so Shapio's preview can take a click on it back
4
+ * to that field: `<h1 {...shapioAttr(article, 'title')}>`. Paths are API IDs, with list positions and nested
5
+ * fields after slashes (`sections/2/heading`), the same paths the admin uses.
6
+ */
7
+ const ENTRY_ATTRIBUTE = "data-shapio-entry";
8
+ const PATH_ATTRIBUTE = "data-shapio-path";
9
+ const LOCALE_ATTRIBUTE = "data-shapio-locale";
10
+ /**
11
+ * A spreadable attribute object for the element that renders `path` of `entry`. The locale is the one given,
12
+ * else the entry's own (delivery items carry the locale that served them); it is left out when unknown.
13
+ */
14
+ const shapioAttr = (entry, path, locale) => {
15
+ const id = typeof entry === "string" ? entry : entry.id;
16
+ const entryLocale = locale ?? (typeof entry === "string" ? void 0 : entry.locale ?? void 0);
17
+ return {
18
+ [ENTRY_ATTRIBUTE]: id,
19
+ [PATH_ATTRIBUTE]: path.replace(/^\/+/, ""),
20
+ ...entryLocale ? { [LOCALE_ATTRIBUTE]: entryLocale } : {}
21
+ };
22
+ };
23
+ //#endregion
24
+ //#region src/messages.ts
25
+ /**
26
+ * The messages between a site in Shapio's preview frame and the admin around it. Every message carries the
27
+ * protocol version; anything that does not parse is ignored. Who may send a message (the frame's window from
28
+ * the preview origin, the parent from the Shapio origin) is checked by each side before parsing.
29
+ */
30
+ const VISUAL_PROTOCOL_VERSION = 1;
31
+ /** The query parameter the admin adds to a preview URL it frames (`?shapio-visual=1`). */
32
+ const VISUAL_QUERY_PARAM = "shapio-visual";
33
+ const MAX_PATH_LENGTH = 512;
34
+ const MAX_PATH_SEGMENTS = 32;
35
+ const SEGMENT = /^[A-Za-z0-9_~-]+$/;
36
+ const ENTRY_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
37
+ const LOCALE = /^[A-Za-z0-9-]{1,35}$/;
38
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
39
+ /** `title`, `/title` or `sections/2/heading` → a JSON pointer (`/sections/2/heading`); undefined if malformed. */
40
+ const normalizeFieldPath = (path) => {
41
+ if (typeof path !== "string" || path.length === 0 || path.length > MAX_PATH_LENGTH) return;
42
+ const segments = path.replace(/^\//, "").split("/");
43
+ if (segments.length > MAX_PATH_SEGMENTS || !segments.every((segment) => SEGMENT.test(segment))) return;
44
+ return `/${segments.join("/")}`;
45
+ };
46
+ /** A message from the site, or undefined when the data is not one. */
47
+ const parseSiteMessage = (data) => {
48
+ if (!isRecord(data) || data.v !== 1) return;
49
+ if (data.type === "shapio:ready") return {
50
+ type: "shapio:ready",
51
+ v: 1
52
+ };
53
+ if (data.type !== "shapio:focus") return;
54
+ const path = normalizeFieldPath(data.path);
55
+ if (typeof data.entryId !== "string" || !ENTRY_ID.test(data.entryId) || !path) return;
56
+ if (data.locale !== void 0 && (typeof data.locale !== "string" || !LOCALE.test(data.locale))) return;
57
+ return {
58
+ type: "shapio:focus",
59
+ v: 1,
60
+ entryId: data.entryId,
61
+ path,
62
+ ...typeof data.locale === "string" ? { locale: data.locale } : {}
63
+ };
64
+ };
65
+ /** A message from the admin, or undefined when the data is not one. */
66
+ const parseAdminMessage = (data) => isRecord(data) && data.v === 1 && data.type === "shapio:refresh" ? {
67
+ type: "shapio:refresh",
68
+ v: 1
69
+ } : void 0;
70
+ //#endregion
71
+ //#region src/visualEditing.ts
72
+ /** The attribute on `<html>` while visual editing is on, and on the element under the pointer. */
73
+ const ACTIVE_DOCUMENT_ATTRIBUTE = "data-shapio-visual";
74
+ const HOVER_ATTRIBUTE = "data-shapio-hover";
75
+ const STYLE = `[${ACTIVE_DOCUMENT_ATTRIBUTE}] [${HOVER_ATTRIBUTE}] { outline: 2px dashed #2563eb; outline-offset: 2px; cursor: pointer; }`;
76
+ const NOOP = () => void 0;
77
+ /** Visual editing runs only inside a frame, on a URL the admin opened with `?shapio-visual=1`. */
78
+ const isVisualEditingRequested = (win) => {
79
+ let framed;
80
+ try {
81
+ framed = win.self !== win.top;
82
+ } catch {
83
+ framed = true;
84
+ }
85
+ return framed && new URL(win.location.href).searchParams.get("shapio-visual") === "1";
86
+ };
87
+ const originOf = (value) => {
88
+ try {
89
+ const url = new URL(value);
90
+ return url.protocol === "http:" || url.protocol === "https:" ? url.origin : void 0;
91
+ } catch {
92
+ return;
93
+ }
94
+ };
95
+ const annotatedFrom = (target) => {
96
+ const element = target;
97
+ return typeof element?.closest === "function" ? element.closest(`[${ENTRY_ATTRIBUTE}]`) : null;
98
+ };
99
+ /**
100
+ * Turns on visual editing when the page is in Shapio's preview frame: outlines elements carrying
101
+ * `shapioAttr(...)` attributes on hover, tells the admin which field was clicked, and re-renders when the admin
102
+ * saves. Posts only to the configured Shapio origin and accepts only that origin's messages from the parent
103
+ * window. Outside the preview frame it does nothing. Returns a function that turns it off.
104
+ */
105
+ const initVisualEditing = (options) => {
106
+ const win = options.window ?? window;
107
+ const origin = originOf(options.origin);
108
+ if (!origin || !isVisualEditingRequested(win)) return NOOP;
109
+ const doc = win.document;
110
+ const post = (message) => win.parent.postMessage(message, origin);
111
+ let hovered = null;
112
+ const style = doc.createElement("style");
113
+ style.textContent = STYLE;
114
+ doc.head.append(style);
115
+ doc.documentElement.setAttribute(ACTIVE_DOCUMENT_ATTRIBUTE, "");
116
+ const onPointerOver = (event) => {
117
+ const element = annotatedFrom(event.target);
118
+ if (element === hovered) return;
119
+ hovered?.removeAttribute(HOVER_ATTRIBUTE);
120
+ hovered = element;
121
+ hovered?.setAttribute(HOVER_ATTRIBUTE, "");
122
+ };
123
+ const onClick = (event) => {
124
+ const element = annotatedFrom(event.target);
125
+ const entryId = element?.getAttribute(ENTRY_ATTRIBUTE);
126
+ const path = element?.getAttribute(PATH_ATTRIBUTE);
127
+ if (!element || !entryId || !path) return;
128
+ event.preventDefault();
129
+ event.stopPropagation();
130
+ const locale = element.getAttribute(LOCALE_ATTRIBUTE);
131
+ post({
132
+ type: "shapio:focus",
133
+ v: 1,
134
+ entryId,
135
+ path,
136
+ ...locale ? { locale } : {}
137
+ });
138
+ };
139
+ const onMessage = (event) => {
140
+ if (event.source !== win.parent || event.origin !== origin || !parseAdminMessage(event.data)) return;
141
+ if (options.onRefresh) Promise.resolve().then(options.onRefresh);
142
+ else win.location.reload();
143
+ };
144
+ doc.addEventListener("pointerover", onPointerOver);
145
+ doc.addEventListener("click", onClick, true);
146
+ win.addEventListener("message", onMessage);
147
+ post({
148
+ type: "shapio:ready",
149
+ v: 1
150
+ });
151
+ return () => {
152
+ doc.removeEventListener("pointerover", onPointerOver);
153
+ doc.removeEventListener("click", onClick, true);
154
+ win.removeEventListener("message", onMessage);
155
+ hovered?.removeAttribute(HOVER_ATTRIBUTE);
156
+ doc.documentElement.removeAttribute(ACTIVE_DOCUMENT_ATTRIBUTE);
157
+ style.remove();
158
+ };
159
+ };
160
+ //#endregion
161
+ export { ENTRY_ATTRIBUTE, LOCALE_ATTRIBUTE, PATH_ATTRIBUTE, VISUAL_PROTOCOL_VERSION, VISUAL_QUERY_PARAM, initVisualEditing, isVisualEditingRequested, normalizeFieldPath, parseAdminMessage, parseSiteMessage, shapioAttr };
162
+
163
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/attributes.ts","../src/messages.ts","../src/visualEditing.ts"],"sourcesContent":["/**\n * The attributes a site puts on an element that shows a field, so Shapio's preview can take a click on it back\n * to that field: `<h1 {...shapioAttr(article, 'title')}>`. Paths are API IDs, with list positions and nested\n * fields after slashes (`sections/2/heading`), the same paths the admin uses.\n */\nexport const ENTRY_ATTRIBUTE = 'data-shapio-entry';\nexport const PATH_ATTRIBUTE = 'data-shapio-path';\nexport const LOCALE_ATTRIBUTE = 'data-shapio-locale';\n\nexport type ShapioAttributes = {\n 'data-shapio-entry': string;\n 'data-shapio-path': string;\n 'data-shapio-locale'?: string;\n};\n\n/** An entry as delivery returns it (`{ id, locale }`), or its ID. */\nexport type EntryRef = string | { id: string; locale?: string | null | undefined };\n\n/**\n * A spreadable attribute object for the element that renders `path` of `entry`. The locale is the one given,\n * else the entry's own (delivery items carry the locale that served them); it is left out when unknown.\n */\nexport const shapioAttr = (entry: EntryRef, path: string, locale?: string): ShapioAttributes => {\n const id = typeof entry === 'string' ? entry : entry.id;\n const entryLocale = locale ?? (typeof entry === 'string' ? undefined : (entry.locale ?? undefined));\n return {\n [ENTRY_ATTRIBUTE]: id,\n [PATH_ATTRIBUTE]: path.replace(/^\\/+/, ''),\n ...(entryLocale ? { [LOCALE_ATTRIBUTE]: entryLocale } : {}),\n };\n};\n","/**\n * The messages between a site in Shapio's preview frame and the admin around it. Every message carries the\n * protocol version; anything that does not parse is ignored. Who may send a message (the frame's window from\n * the preview origin, the parent from the Shapio origin) is checked by each side before parsing.\n */\nexport const VISUAL_PROTOCOL_VERSION = 1;\n/** The query parameter the admin adds to a preview URL it frames (`?shapio-visual=1`). */\nexport const VISUAL_QUERY_PARAM = 'shapio-visual';\n\nexport type VisualReadyMessage = { type: 'shapio:ready'; v: typeof VISUAL_PROTOCOL_VERSION };\nexport type VisualFocusMessage = {\n type: 'shapio:focus';\n v: typeof VISUAL_PROTOCOL_VERSION;\n entryId: string;\n /** A JSON pointer of API IDs (`/title`, `/sections/2/heading`). */\n path: string;\n locale?: string;\n};\nexport type VisualRefreshMessage = { type: 'shapio:refresh'; v: typeof VISUAL_PROTOCOL_VERSION };\n\n/** What the site posts to the admin. */\nexport type SiteMessage = VisualReadyMessage | VisualFocusMessage;\n/** What the admin posts to the site. */\nexport type AdminMessage = VisualRefreshMessage;\n\nconst MAX_PATH_LENGTH = 512;\nconst MAX_PATH_SEGMENTS = 32;\nconst SEGMENT = /^[A-Za-z0-9_~-]+$/;\nconst ENTRY_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst LOCALE = /^[A-Za-z0-9-]{1,35}$/;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** `title`, `/title` or `sections/2/heading` → a JSON pointer (`/sections/2/heading`); undefined if malformed. */\nexport const normalizeFieldPath = (path: unknown): string | undefined => {\n if (typeof path !== 'string' || path.length === 0 || path.length > MAX_PATH_LENGTH) {\n return undefined;\n }\n const segments = path.replace(/^\\//, '').split('/');\n if (segments.length > MAX_PATH_SEGMENTS || !segments.every((segment) => SEGMENT.test(segment))) {\n return undefined;\n }\n return `/${segments.join('/')}`;\n};\n\n/** A message from the site, or undefined when the data is not one. */\nexport const parseSiteMessage = (data: unknown): SiteMessage | undefined => {\n if (!isRecord(data) || data.v !== VISUAL_PROTOCOL_VERSION) {\n return undefined;\n }\n if (data.type === 'shapio:ready') {\n return { type: 'shapio:ready', v: VISUAL_PROTOCOL_VERSION };\n }\n if (data.type !== 'shapio:focus') {\n return undefined;\n }\n const path = normalizeFieldPath(data.path);\n if (typeof data.entryId !== 'string' || !ENTRY_ID.test(data.entryId) || !path) {\n return undefined;\n }\n if (data.locale !== undefined && (typeof data.locale !== 'string' || !LOCALE.test(data.locale))) {\n return undefined;\n }\n return {\n type: 'shapio:focus',\n v: VISUAL_PROTOCOL_VERSION,\n entryId: data.entryId,\n path,\n ...(typeof data.locale === 'string' ? { locale: data.locale } : {}),\n };\n};\n\n/** A message from the admin, or undefined when the data is not one. */\nexport const parseAdminMessage = (data: unknown): AdminMessage | undefined =>\n isRecord(data) && data.v === VISUAL_PROTOCOL_VERSION && data.type === 'shapio:refresh'\n ? { type: 'shapio:refresh', v: VISUAL_PROTOCOL_VERSION }\n : undefined;\n","import { ENTRY_ATTRIBUTE, LOCALE_ATTRIBUTE, PATH_ATTRIBUTE } from './attributes.js';\nimport {\n parseAdminMessage,\n VISUAL_PROTOCOL_VERSION,\n VISUAL_QUERY_PARAM,\n type SiteMessage,\n} from './messages.js';\n\nexport type VisualEditingOptions = {\n /** Shapio's public URL (or origin). Messages go to this origin only, and only its messages are accepted. */\n origin: string;\n /**\n * Re-renders the page with the current draft after an edit. Without it the page reloads, which is right for a\n * page that reads its preview token from the URL on every load; a page that drops the token from the address\n * bar must re-fetch here instead.\n */\n onRefresh?: () => void | Promise<void>;\n /** The window to run in (tests); defaults to the global one. */\n window?: Window;\n};\n\n/** The attribute on `<html>` while visual editing is on, and on the element under the pointer. */\nconst ACTIVE_DOCUMENT_ATTRIBUTE = 'data-shapio-visual';\nconst HOVER_ATTRIBUTE = 'data-shapio-hover';\nconst STYLE = `[${ACTIVE_DOCUMENT_ATTRIBUTE}] [${HOVER_ATTRIBUTE}] { outline: 2px dashed #2563eb; outline-offset: 2px; cursor: pointer; }`;\n\nconst NOOP = () => undefined;\n\n/** Visual editing runs only inside a frame, on a URL the admin opened with `?shapio-visual=1`. */\nexport const isVisualEditingRequested = (win: Window): boolean => {\n let framed: boolean;\n try {\n framed = win.self !== win.top;\n } catch {\n // A cross-origin top window can throw on access in some browsers: that is a frame.\n framed = true;\n }\n return framed && new URL(win.location.href).searchParams.get(VISUAL_QUERY_PARAM) === '1';\n};\n\nconst originOf = (value: string): string | undefined => {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst annotatedFrom = (target: EventTarget | null): HTMLElement | null => {\n const element = target as Element | null;\n return typeof element?.closest === 'function' ? element.closest<HTMLElement>(`[${ENTRY_ATTRIBUTE}]`) : null;\n};\n\n/**\n * Turns on visual editing when the page is in Shapio's preview frame: outlines elements carrying\n * `shapioAttr(...)` attributes on hover, tells the admin which field was clicked, and re-renders when the admin\n * saves. Posts only to the configured Shapio origin and accepts only that origin's messages from the parent\n * window. Outside the preview frame it does nothing. Returns a function that turns it off.\n */\nexport const initVisualEditing = (options: VisualEditingOptions): (() => void) => {\n const win = options.window ?? window;\n const origin = originOf(options.origin);\n if (!origin || !isVisualEditingRequested(win)) {\n return NOOP;\n }\n const doc = win.document;\n const post = (message: SiteMessage) => win.parent.postMessage(message, origin);\n let hovered: HTMLElement | null = null;\n\n const style = doc.createElement('style');\n style.textContent = STYLE;\n doc.head.append(style);\n doc.documentElement.setAttribute(ACTIVE_DOCUMENT_ATTRIBUTE, '');\n\n const onPointerOver = (event: Event) => {\n const element = annotatedFrom(event.target);\n if (element === hovered) {\n return;\n }\n hovered?.removeAttribute(HOVER_ATTRIBUTE);\n hovered = element;\n hovered?.setAttribute(HOVER_ATTRIBUTE, '');\n };\n const onClick = (event: Event) => {\n const element = annotatedFrom(event.target);\n const entryId = element?.getAttribute(ENTRY_ATTRIBUTE);\n const path = element?.getAttribute(PATH_ATTRIBUTE);\n if (!element || !entryId || !path) {\n return;\n }\n // A click on an annotated link or button edits the field instead of navigating inside the frame.\n event.preventDefault();\n event.stopPropagation();\n const locale = element.getAttribute(LOCALE_ATTRIBUTE);\n post({\n type: 'shapio:focus',\n v: VISUAL_PROTOCOL_VERSION,\n entryId,\n path,\n ...(locale ? { locale } : {}),\n });\n };\n const onMessage = (event: MessageEvent) => {\n if (event.source !== win.parent || event.origin !== origin || !parseAdminMessage(event.data)) {\n return;\n }\n if (options.onRefresh) {\n // A failing re-render surfaces as an unhandled rejection in the site's console, like any page error.\n void Promise.resolve().then(options.onRefresh);\n } else {\n win.location.reload();\n }\n };\n\n doc.addEventListener('pointerover', onPointerOver);\n doc.addEventListener('click', onClick, true);\n win.addEventListener('message', onMessage);\n post({ type: 'shapio:ready', v: VISUAL_PROTOCOL_VERSION });\n\n return () => {\n doc.removeEventListener('pointerover', onPointerOver);\n doc.removeEventListener('click', onClick, true);\n win.removeEventListener('message', onMessage);\n hovered?.removeAttribute(HOVER_ATTRIBUTE);\n doc.documentElement.removeAttribute(ACTIVE_DOCUMENT_ATTRIBUTE);\n style.remove();\n };\n};\n"],"mappings":";;;;;;AAKA,MAAa,kBAAk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ual=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=`data-shapio-entry`,n=`data-shapio-path`,r=`data-shapio-locale`,i=(e,i,a)=>{let o=typeof e==`string`?e:e.id,s=a??(typeof e==`string`?void 0:e.locale??void 0);return{[t]:o,[n]:i.replace(/^\/+/,``),...s?{[r]:s}:{}}},a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>a(e)&&e.v===1&&e.type===`shapio:refresh`?{type:`shapio:refresh`,v:1}:void 0,s=`data-shapio-visual`,c=`data-shapio-hover`,l=`[${s}] [${c}] { outline: 2px dashed #2563eb; outline-offset: 2px; cursor: pointer; }`,u=()=>void 0,d=e=>{let t;try{t=e.self!==e.top}catch{t=!0}return t&&new URL(e.location.href).searchParams.get(`shapio-visual`)===`1`},f=e=>{try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t.origin:void 0}catch{return}},p=e=>{let n=e;return typeof n?.closest==`function`?n.closest(`[${t}]`):null},m=e=>{let i=e.window??window,a=f(e.origin);if(!a||!d(i))return u;let m=i.document,h=e=>i.parent.postMessage(e,a),g=null,_=m.createElement(`style`);_.textContent=l,m.head.append(_),m.documentElement.setAttribute(s,``);let v=e=>{let t=p(e.target);t!==g&&(g?.removeAttribute(c),g=t,g?.setAttribute(c,``))},y=e=>{let i=p(e.target),a=i?.getAttribute(t),o=i?.getAttribute(n);if(!i||!a||!o)return;e.preventDefault(),e.stopPropagation();let s=i.getAttribute(r);h({type:`shapio:focus`,v:1,entryId:a,path:o,...s?{locale:s}:{}})},b=t=>{t.source===i.parent&&t.origin===a&&o(t.data)&&(e.onRefresh?Promise.resolve().then(e.onRefresh):i.location.reload())};return m.addEventListener(`pointerover`,v),m.addEventListener(`click`,y,!0),i.addEventListener(`message`,b),h({type:`shapio:ready`,v:1}),()=>{m.removeEventListener(`pointerover`,v),m.removeEventListener(`click`,y,!0),i.removeEventListener(`message`,b),g?.removeAttribute(c),m.documentElement.removeAttribute(s),_.remove()}},h=document.currentScript,g=h instanceof HTMLScriptElement?h.dataset.shapioOrigin:void 0;return g&&m({origin:g}),e.initVisualEditing=m,e.shapioAttr=i,e})({});
2
+ //# sourceMappingURL=visual.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visual.iife.js","names":["exports","ENTRY_ATTRIBUTE","PATH_ATTRIBUTE","LOCALE_ATTRIBUTE","shapioAttr","id","entry","entryLocale","locale","path","isRecord","value","parseAdminMessage","data","ACTIVE_DOCUMENT_ATTRIBUTE","HOVER_ATTRIBUTE","STYLE","NOOP","isVisualEditingRequested","framed","win","originOf","url","annotatedFrom","element","target","initVisualEditing","options","origin","doc","post","message","hovered","style","onPointerOver","event","onClick","entryId","onMessage","script"],"sources":["../src/attributes.ts","../src/messages.ts","../src/visualEditing.ts","../src/global.ts"],"sourcesContent":["/**\n * The attributes a site puts on an element that shows a field, so Shapio's preview can take a click on it back\n * to that field: `<h1 {...shapioAttr(article, 'title')}>`. Paths are API IDs, with list positions and nested\n * fields after slashes (`sections/2/heading`), the same paths the admin uses.\n */\nexport const ENTRY_ATTRIBUTE = 'data-shapio-entry';\nexport const PATH_ATTRIBUTE = 'data-shapio-path';\nexport const LOCALE_ATTRIBUTE = 'data-shapio-locale';\n\nexport type ShapioAttributes = {\n 'data-shapio-entry': string;\n 'data-shapio-path': string;\n 'data-shapio-locale'?: string;\n};\n\n/** An entry as delivery returns it (`{ id, locale }`), or its ID. */\nexport type EntryRef = string | { id: string; locale?: string | null | undefined };\n\n/**\n * A spreadable attribute object for the element that renders `path` of `entry`. The locale is the one given,\n * else the entry's own (delivery items carry the locale that served them); it is left out when unknown.\n */\nexport const shapioAttr = (entry: EntryRef, path: string, locale?: string): ShapioAttributes => {\n const id = typeof entry === 'string' ? entry : entry.id;\n const entryLocale = locale ?? (typeof entry === 'string' ? undefined : (entry.locale ?? undefined));\n return {\n [ENTRY_ATTRIBUTE]: id,\n [PATH_ATTRIBUTE]: path.replace(/^\\/+/, ''),\n ...(entryLocale ? { [LOCALE_ATTRIBUTE]: entryLocale } : {}),\n };\n};\n","/**\n * The messages between a site in Shapio's preview frame and the admin around it. Every message carries the\n * protocol version; anything that does not parse is ignored. Who may send a message (the frame's window from\n * the preview origin, the parent from the Shapio origin) is checked by each side before parsing.\n */\nexport const VISUAL_PROTOCOL_VERSION = 1;\n/** The query parameter the admin adds to a preview URL it frames (`?shapio-visual=1`). */\nexport const VISUAL_QUERY_PARAM = 'shapio-visual';\n\nexport type VisualReadyMessage = { type: 'shapio:ready'; v: typeof VISUAL_PROTOCOL_VERSION };\nexport type VisualFocusMessage = {\n type: 'shapio:focus';\n v: typeof VISUAL_PROTOCOL_VERSION;\n entryId: string;\n /** A JSON pointer of API IDs (`/title`, `/sections/2/heading`). */\n path: string;\n locale?: string;\n};\nexport type VisualRefreshMessage = { type: 'shapio:refresh'; v: typeof VISUAL_PROTOCOL_VERSION };\n\n/** What the site posts to the admin. */\nexport type SiteMessage = VisualReadyMessage | VisualFocusMessage;\n/** What the admin posts to the site. */\nexport type AdminMessage = VisualRefreshMessage;\n\nconst MAX_PATH_LENGTH = 512;\nconst MAX_PATH_SEGMENTS = 32;\nconst SEGMENT = /^[A-Za-z0-9_~-]+$/;\nconst ENTRY_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst LOCALE = /^[A-Za-z0-9-]{1,35}$/;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** `title`, `/title` or `sections/2/heading` → a JSON pointer (`/sections/2/heading`); undefined if malformed. */\nexport const normalizeFieldPath = (path: unknown): string | undefined => {\n if (typeof path !== 'string' || path.length === 0 || path.length > MAX_PATH_LENGTH) {\n return undefined;\n }\n const segments = path.replace(/^\\//, '').split('/');\n if (segments.length > MAX_PATH_SEGMENTS || !segments.every((segment) => SEGMENT.test(segment))) {\n return undefined;\n }\n return `/${segments.join('/')}`;\n};\n\n/** A message from the site, or undefined when the data is not one. */\nexport const parseSiteMessage = (data: unknown): SiteMessage | undefined => {\n if (!isRecord(data) || data.v !== VISUAL_PROTOCOL_VERSION) {\n return undefined;\n }\n if (data.type === 'shapio:ready') {\n return { type: 'shapio:ready', v: VISUAL_PROTOCOL_VERSION };\n }\n if (data.type !== 'shapio:focus') {\n return undefined;\n }\n const path = normalizeFieldPath(data.path);\n if (typeof data.entryId !== 'string' || !ENTRY_ID.test(data.entryId) || !path) {\n return undefined;\n }\n if (data.locale !== undefined && (typeof data.locale !== 'string' || !LOCALE.test(data.locale))) {\n return undefined;\n }\n return {\n type: 'shapio:focus',\n v: VISUAL_PROTOCOL_VERSION,\n entryId: data.entryId,\n path,\n ...(typeof data.locale === 'string' ? { locale: data.locale } : {}),\n };\n};\n\n/** A message from the admin, or undefined when the data is not one. */\nexport const parseAdminMessage = (data: unknown): AdminMessage | undefined =>\n isRecord(data) && data.v === VISUAL_PROTOCOL_VERSION && data.type === 'shapio:refresh'\n ? { type: 'shapio:refresh', v: VISUAL_PROTOCOL_VERSION }\n : undefined;\n","import { ENTRY_ATTRIBUTE, LOCALE_ATTRIBUTE, PATH_ATTRIBUTE } from './attributes.js';\nimport {\n parseAdminMessage,\n VISUAL_PROTOCOL_VERSION,\n VISUAL_QUERY_PARAM,\n type SiteMessage,\n} from './messages.js';\n\nexport type VisualEditingOptions = {\n /** Shapio's public URL (or origin). Messages go to this origin only, and only its messages are accepted. */\n origin: string;\n /**\n * Re-renders the page with the current draft after an edit. Without it the page reloads, which is right for a\n * page that reads its preview token from the URL on every load; a page that drops the token from the address\n * bar must re-fetch here instead.\n */\n onRefresh?: () => void | Promise<void>;\n /** The window to run in (tests); defaults to the global one. */\n window?: Window;\n};\n\n/** The attribute on `<html>` while visual editing is on, and on the element under the pointer. */\nconst ACTIVE_DOCUMENT_ATTRIBUTE = 'data-shapio-visual';\nconst HOVER_ATTRIBUTE = 'data-shapio-hover';\nconst STYLE = `[${ACTIVE_DOCUMENT_ATTRIBUTE}] [${HOVER_ATTRIBUTE}] { outline: 2px dashed #2563eb; outline-offset: 2px; cursor: pointer; }`;\n\nconst NOOP = () => undefined;\n\n/** Visual editing runs only inside a frame, on a URL the admin opened with `?shapio-visual=1`. */\nexport const isVisualEditingRequested = (win: Window): boolean => {\n let framed: boolean;\n try {\n framed = win.self !== win.top;\n } catch {\n // A cross-origin top window can throw on access in some browsers: that is a frame.\n framed = true;\n }\n return framed && new URL(win.location.href).searchParams.get(VISUAL_QUERY_PARAM) === '1';\n};\n\nconst originOf = (value: string): string | undefined => {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst annotatedFrom = (target: EventTarget | null): HTMLElement | null => {\n const element = target as Element | null;\n return typeof element?.closest === 'function' ? element.closest<HTMLElement>(`[${ENTRY_ATTRIBUTE}]`) : null;\n};\n\n/**\n * Turns on visual editing when the page is in Shapio's preview frame: outlines elements carrying\n * `shapioAttr(...)` attributes on hover, tells the admin which field was clicked, and re-renders when the admin\n * saves. Posts only to the configured Shapio origin and accepts only that origin's messages from the parent\n * window. Outside the preview frame it does nothing. Returns a function that turns it off.\n */\nexport const initVisualEditing = (options: VisualEditingOptions): (() => void) => {\n const win = options.window ?? window;\n const origin = originOf(options.origin);\n if (!origin || !isVisualEditingRequested(win)) {\n return NOOP;\n }\n const doc = win.document;\n const post = (message: SiteMessage) => win.parent.postMessage(message, origin);\n let hovered: HTMLElement | null = null;\n\n const style = doc.createElement('style');\n style.textContent = STYLE;\n doc.head.append(style);\n doc.documentElement.setAttribute(ACTIVE_DOCUMENT_ATTRIBUTE, '');\n\n const onPointerOver = (event: Event) => {\n const element = annotatedFrom(event.target);\n if (element === hovered) {\n return;\n }\n hovered?.removeAttribute(HOVER_ATTRIBUTE);\n hovered = element;\n hovered?.setAttribute(HOVER_ATTRIBUTE, '');\n };\n const onClick = (event: Event) => {\n const element = annotatedFrom(event.target);\n const entryId = element?.getAttribute(ENTRY_ATTRIBUTE);\n const path = element?.getAttribute(PATH_ATTRIBUTE);\n if (!element || !entryId || !path) {\n return;\n }\n // A click on an annotated link or button edits the field instead of navigating inside the frame.\n event.preventDefault();\n event.stopPropagation();\n const locale = element.getAttribute(LOCALE_ATTRIBUTE);\n post({\n type: 'shapio:focus',\n v: VISUAL_PROTOCOL_VERSION,\n entryId,\n path,\n ...(locale ? { locale } : {}),\n });\n };\n const onMessage = (event: MessageEvent) => {\n if (event.source !== win.parent || event.origin !== origin || !parseAdminMessage(event.data)) {\n return;\n }\n if (options.onRefresh) {\n // A failing re-render surfaces as an unhandled rejection in the site's console, like any page error.\n void Promise.resolve().then(options.onRefresh);\n } else {\n win.location.reload();\n }\n };\n\n doc.addEventListener('pointerover', onPointerOver);\n doc.addEventListener('click', onClick, true);\n win.addEventListener('message', onMessage);\n post({ type: 'shapio:ready', v: VISUAL_PROTOCOL_VERSION });\n\n return () => {\n doc.removeEventListener('pointerover', onPointerOver);\n doc.removeEventListener('click', onClick, true);\n win.removeEventListener('message', onMessage);\n hovered?.removeAttribute(HOVER_ATTRIBUTE);\n doc.documentElement.removeAttribute(ACTIVE_DOCUMENT_ATTRIBUTE);\n style.remove();\n };\n};\n","import { initVisualEditing } from './visualEditing.js';\n\n/**\n * The plain-script build (`window.ShapioVisual`). A `<script>` tag with `data-shapio-origin` turns visual editing\n * on by itself (the page reloads on refresh); otherwise call `ShapioVisual.initVisualEditing({ origin })`.\n */\nconst script = document.currentScript;\nconst origin = script instanceof HTMLScriptElement ? script.dataset.shapioOrigin : undefined;\nif (origin) {\n initVisualEditing({ origin });\n}\n\nexport { shapioAttr } from './attributes.js';\nexport { initVisualEditing };\n"],"mappings":"2FAKA,IAAaC,EAAkB,oBAClBC,EAAiB,mBACjBC,EAAmB,qBAenBC,GAAc,EAAiB,EAAc,IAAsC,CAC9F,IAAMC,EAAK,OAAOC,GAAU,SAAWA,EAAQA,EAAM,GAC/CC,EAAcC,IAAW,OAAOF,GAA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CACf,CACF,EC1HMM,EAAS,SAAS,cAClBX,EAASW,aAAkB,kBAAoBA,EAAO,QAAQ,aAAe,IAAA,UAC/EX,GACFF,EAAkB,CAAE,QAAO,CAAC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@shapio/visual",
3
+ "version": "0.2.0",
4
+ "description": "Visual editing for sites built on Shapio: field attributes and the preview-frame script.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://shapio.dev",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/mybrokengnome/shapio.git",
10
+ "directory": "packages/visual"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/mybrokengnome/shapio/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "@shapio/source": "./src/index.ts",
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
22
+ },
23
+ "./global": "./dist/visual.iife.js"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "devDependencies": {
29
+ "jsdom": "30.1.1",
30
+ "tsdown": "0.23.0",
31
+ "typescript": "6.0.3",
32
+ "vitest": "5.0.3"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "scripts": {
38
+ "build": "tsdown",
39
+ "typecheck": "tsc -p tsconfig.json"
40
+ }
41
+ }