@joryio/web-sdk 1.4.0-beta.5 → 1.4.0-beta.7

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.
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The editor's words. English is built in; the dashboard sends the same keys
3
+ * in the marketer's language with `joryio:editor-context` (`strings`, plus
4
+ * `dir` for Hebrew and Arabic), so the five dashboard locales reach the
5
+ * editor without shipping every translation to the customer's site. A key
6
+ * the dashboard does not send stays English. `{name}` placeholders are
7
+ * filled with text, never parsed as HTML.
8
+ */
9
+ export const EDITOR_STRINGS = {
10
+ title: 'Joryio editor',
11
+ variant: 'Variant {name}',
12
+ hintPoint: 'Point at anything on the page',
13
+ hintEditing: 'Editing · changes show live',
14
+ editsOne: '1 edit',
15
+ editsMany: '{n} edits',
16
+ noEdits: 'No edits yet.',
17
+ undo: 'Undo last edit',
18
+ undoOffline: 'Undo is available once the Joryio dashboard is connected',
19
+ saveReturn: 'Save & return to Joryio',
20
+ clickToEdit: 'click to edit',
21
+ helpTitle: 'Not the right box?',
22
+ helpUp: 'Select the section around it',
23
+ helpDown: 'Select something inside it',
24
+ helpClickKey: 'Click',
25
+ helpClick: 'Edit this one',
26
+ dismiss: 'Dismiss',
27
+ page: 'Page',
28
+ up: 'Select the element around it',
29
+ down: 'Select the first element inside it',
30
+ matchOne: '1 match on page',
31
+ matchMany: 'Matches {n} - all will change',
32
+ matchNone: 'Not found',
33
+ whatToDo: 'What do you want to do?',
34
+ actText: 'Change text',
35
+ actLink: 'Change link',
36
+ actImage: 'Change image',
37
+ actHide: 'Hide it',
38
+ actSlot: 'Add content slot',
39
+ noText: 'No text here',
40
+ notLink: 'Not a link',
41
+ notImage: 'Not an image',
42
+ newText: 'New text',
43
+ was: 'Was: "{value}"',
44
+ insert: 'Insert',
45
+ fallbackFor: 'If {name} is missing',
46
+ fallbackHelp: "Shown to visitors we don't know yet.",
47
+ fallbackBad: 'Plain text only - no Liquid here.',
48
+ fallbackDone: 'Done',
49
+ liquid: 'Liquid code',
50
+ more: 'More…',
51
+ search: 'Search fields',
52
+ noMatch: 'No matching fields',
53
+ rawNote: 'Shown as code: this text uses Liquid beyond profile fields and fallbacks.',
54
+ newLink: 'New link address',
55
+ newImage: 'New image address',
56
+ urlBad: 'Enter an address starting with https:// (or http://).',
57
+ hideNote: "The {kind} is removed for people in this campaign's audience. Everyone else still sees it.",
58
+ hiddenFor: 'Hidden for this audience',
59
+ slotName: 'Slot name',
60
+ savedAs: 'Saved as',
61
+ slotHelp: 'Filled by a Placement campaign or a journey step.',
62
+ slotEmpty: 'Enter a name for the slot.',
63
+ slotCreate: 'Create content for this slot →',
64
+ slotIn: 'In this slot:',
65
+ slotAddAnother: '+ Add another campaign',
66
+ where: 'Where',
67
+ posBefore: 'Above it',
68
+ posAfter: 'Below it',
69
+ posReplace: 'Instead of it',
70
+ posPrepend: 'Inside, at the start',
71
+ posAppend: 'Inside, at the end',
72
+ slotPreview: 'Content slot',
73
+ css: 'CSS selector',
74
+ cssHelp: 'For developers. Matches {n} on this page.',
75
+ cssBad: 'Not a selector this page can use.',
76
+ cancel: 'Cancel',
77
+ save: 'Save · {action}',
78
+ noSelector: 'This element has no stable selector. Choose the element around it (arrow up) or another one.',
79
+ kHeading: 'Heading',
80
+ kText: 'Text',
81
+ kLink: 'Link',
82
+ kButton: 'Button',
83
+ kImage: 'Image',
84
+ kList: 'List',
85
+ kSection: 'Section',
86
+ kMain: 'Main',
87
+ kHeader: 'Header',
88
+ kFooter: 'Footer',
89
+ kNav: 'Navigation',
90
+ kForm: 'Form',
91
+ kElement: 'Element',
92
+ };
93
+
94
+ export type EditorStringKey = keyof typeof EDITOR_STRINGS;
95
+ export type EditorStrings = Record<EditorStringKey, string>;
96
+
97
+ /** The built-in English, with the dashboard's translations over it (strings only, at most 500 characters each). */
98
+ export function mergeStrings(over: unknown): EditorStrings {
99
+ const out: EditorStrings = { ...EDITOR_STRINGS };
100
+ if (over && typeof over === 'object') {
101
+ for (const k of Object.keys(EDITOR_STRINGS) as EditorStringKey[]) {
102
+ const v = (over as Record<string, unknown>)[k];
103
+ if (typeof v === 'string' && v.trim() && v.length <= 500) out[k] = v;
104
+ }
105
+ }
106
+ return out;
107
+ }
108
+
109
+ /** `{name}` placeholders filled in; the result is only ever set as text. */
110
+ export function fill(text: string, vars: Record<string, string | number> = {}): string {
111
+ return text.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));
112
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Building blocks of the editor's UI: an element helper that only ever sets
3
+ * attributes and text (never HTML), the icons (fixed SVG paths), and the
4
+ * stylesheet. Everything lives inside the editor's shadow root, so the
5
+ * site's CSS cannot restyle it and this CSS cannot reach the site.
6
+ *
7
+ * Colours are the Joryio product tokens of the design handoff
8
+ * (design_handoff_web_personalization, joryio-tokens.css): navy #071342,
9
+ * teal #31D6C8 / #00A99A, slot lavender #7A6CFF, light panel like the app.
10
+ */
11
+
12
+ type Kid = Node | string | null | undefined | false;
13
+
14
+ export function h<K extends keyof HTMLElementTagNameMap>(tag: K, attrs?: Record<string, string | boolean | undefined> | null, ...kids: Kid[]): HTMLElementTagNameMap[K] {
15
+ const el = document.createElement(tag);
16
+ for (const [k, v] of Object.entries(attrs || {})) {
17
+ if (v === undefined || v === false) continue;
18
+ el.setAttribute(k, v === true ? '' : v);
19
+ }
20
+ for (const kid of kids) if (kid !== null && kid !== undefined && kid !== false) el.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);
21
+ return el;
22
+ }
23
+
24
+ const SVG_NS = 'http://www.w3.org/2000/svg';
25
+ const ICONS = {
26
+ text: ['M4 7V5h16v2M9 19h6M12 5v14'],
27
+ link: ['M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71', 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'],
28
+ image: ['M3 5h18v14H3z', 'm3 16 5-5 4 4 3-3 6 6', 'M15.5 8.5h.01'],
29
+ hide: ['M9.88 9.88a3 3 0 1 0 4.24 4.24', 'M10.73 5.08A10.4 10.4 0 0 1 12 5c7 0 10 7 10 7a13.2 13.2 0 0 1-1.67 2.68', 'M6.61 6.61A13.5 13.5 0 0 0 2 12s3 7 10 7a9.7 9.7 0 0 0 5.39-1.61', 'm2 2 20 20'],
30
+ slot: ['M3 3h18v18H3z', 'M7 9h10v6H7z'],
31
+ undo: ['M3 7v6h6', 'M21 17a9 9 0 0 0-15-6.7L3 13'],
32
+ up: ['m18 15-6-6-6 6'],
33
+ down: ['m6 9 6 6 6-6'],
34
+ cursor: ['m4 4 7.07 17 2.51-7.39L21 11.07z'],
35
+ code: ['m16 18 6-6-6-6M8 6l-6 6 6 6'],
36
+ chevron: ['m9 18 6-6-6-6'],
37
+ check: ['M20 6 9 17l-5-5'],
38
+ close: ['M18 6 6 18M6 6l12 12'],
39
+ };
40
+ export type IconName = keyof typeof ICONS;
41
+
42
+ export function icon(name: IconName, size = 15): SVGSVGElement {
43
+ const s = document.createElementNS(SVG_NS, 'svg');
44
+ for (const [k, v] of Object.entries({ width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.9', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) s.setAttribute(k, v);
45
+ for (const d of ICONS[name]) {
46
+ const p = document.createElementNS(SVG_NS, 'path');
47
+ p.setAttribute('d', d);
48
+ s.appendChild(p);
49
+ }
50
+ return s as SVGSVGElement;
51
+ }
52
+
53
+ /** The host element's own inline style: nothing of the site's CSS reaches inside, and the host takes no room. */
54
+ export const HOST_STYLE = 'all:initial !important;position:fixed !important;top:0 !important;left:0 !important;width:0 !important;height:0 !important;z-index:2147483647 !important;display:block !important';
55
+
56
+ /** A preview element the editor puts IN the page (a slot, a hidden-element note): its own shadow root too. */
57
+ export const PREVIEW_HOST_STYLE = 'all:initial !important;display:block !important;margin:10px 0 !important';
58
+
59
+ const FONT = 'Inter,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif';
60
+ const MONO = 'ui-monospace,"SF Mono",Menlo,monospace';
61
+
62
+ /**
63
+ * A variable with no sample value and no fallback, in the page preview: an
64
+ * inline host that takes the site's font and line from the element it is in
65
+ * (`all: unset`, so nothing else of the site's CSS applies) and is its own
66
+ * bidi island, so it sits right in a right-to-left text too.
67
+ */
68
+ export const PREVIEW_VAR_HOST_STYLE = 'all:unset !important;display:inline !important;unicode-bidi:isolate !important';
69
+
70
+ /** The placeholder pill, the same in the page preview and in the text field: inline, never taller than the line. */
71
+ const PILL = `font-family:${MONO};font-size:.8em;font-weight:600;line-height:1;padding:.12em .5em;border-radius:999px;background:rgba(0,169,154,.14);color:#0F766E;box-shadow:inset 0 0 0 1px rgba(0,169,154,.5);white-space:nowrap;unicode-bidi:isolate;font-style:normal;text-transform:none;letter-spacing:0`;
72
+
73
+ export const PREVIEW_CSS = `.v{${PILL}}.s,.x{font:12.5px/1.4 ${FONT};border-radius:10px;padding:14px 16px;text-align:center}.s{border:2px dashed #7A6CFF;background:#F4F2FF;color:#4C3FD1}.s b{font-weight:700}.s code{font-family:${MONO}}.s div{font-size:11.5px;color:#6B5FD9;margin-top:3px}.x{border:1.5px dashed #F04438;background:#FEF3F2;color:#B42318;text-align:start;padding:10px 12px;font-size:12px}`;
74
+
75
+ export const EDITOR_CSS = `
76
+ *{box-sizing:border-box}
77
+ .r{font:13px/1.4 ${FONT};color:#242B3A;-webkit-font-smoothing:antialiased}
78
+ button{font:inherit;color:inherit;cursor:pointer}
79
+ button:disabled{cursor:not-allowed}
80
+ button:focus-visible,input:focus-visible,textarea:focus-visible,.ce:focus{outline:2px solid #31D6C8;outline-offset:1px}
81
+ .box{position:fixed;pointer-events:none;border:2px dashed #00A99A;background:rgba(0,169,154,.07);border-radius:4px;display:none}
82
+ .box.sel{border-style:solid;background:rgba(0,169,154,.04)}
83
+ .chip{position:absolute;bottom:100%;inset-inline-start:-2px;margin-bottom:2px;background:#00A99A;color:#fff;font-size:11px;font-weight:600;padding:3px 8px;border-radius:6px 6px 6px 0;white-space:nowrap;max-width:60vw;overflow:hidden;text-overflow:ellipsis}
84
+ .help{position:fixed;top:16px;inset-inline-end:16px;width:240px;background:#fff;border:1px solid #E5EAF2;border-radius:10px;box-shadow:0 8px 24px rgba(10,18,64,.14);padding:10px 12px}
85
+ .help h3{margin:0 0 6px;font-size:11px;font-weight:700;color:#6B7280;letter-spacing:.5px;text-transform:uppercase}
86
+ .help .row{display:flex;align-items:center;gap:8px;font-size:12px;padding:3px 0}
87
+ .kbd{min-width:38px;text-align:center;font-size:11px;font-weight:600;border:1px solid #E5EAF2;border-radius:5px;padding:1px 5px;background:#F8FAFC}
88
+ .help .x{position:absolute;top:6px;inset-inline-end:6px;border:0;background:none;color:#8990A8;padding:2px;display:grid}
89
+ .dock{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:6px;background:#071342;color:#fff;border-radius:14px;padding:7px 7px 7px 14px;box-shadow:0 12px 32px rgba(10,18,64,.35);white-space:nowrap;max-width:calc(100vw - 24px)}
90
+ .r.open .dock{left:calc(50% - 190px)}
91
+ .r.open[dir=rtl] .dock{left:calc(50% + 190px)}
92
+ .logo{width:22px;height:22px;border-radius:6px;background:#fff;color:#071342;display:grid;place-items:center;font-weight:800;font-size:13px;flex:none}
93
+ .name{font-size:12.5px;font-weight:600;margin-inline-start:4px;overflow:hidden;text-overflow:ellipsis;max-width:200px}
94
+ .sub{font-size:12px;color:#A8AEC1;overflow:hidden;text-overflow:ellipsis;max-width:220px}
95
+ .sep{width:1px;height:22px;background:#2A3366;margin:0 8px;flex:none}
96
+ .hint{font-size:12px;color:#C9CEDD;display:inline-flex;align-items:center;gap:6px}
97
+ .hint svg{color:#31D6C8}
98
+ .db{display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 10px;border-radius:8px;border:0;background:#1B245A;color:#fff;font-size:12.5px;font-weight:600}
99
+ .ib{height:32px;width:32px;border-radius:8px;border:0;background:transparent;color:#fff;display:grid;place-items:center}
100
+ .ib:disabled{color:#4A527A}
101
+ .go{height:32px;padding:0 14px;border-radius:8px;border:0;background:#31D6C8;color:#071342;font-size:12.5px;font-weight:700}
102
+ .pop{position:absolute;bottom:calc(100% + 10px);left:0;right:0;min-width:280px;max-height:50vh;overflow:auto;background:#fff;color:#242B3A;border-radius:12px;border:1px solid #E5EAF2;box-shadow:0 12px 32px rgba(10,18,64,.18);padding:6px;white-space:normal}
103
+ .pop .e{display:flex;align-items:center;gap:10px;width:100%;padding:8px 10px;border:0;background:none;border-radius:8px;font-size:12.5px;text-align:start}
104
+ .pop .e:hover{background:#F8FAFC}
105
+ .pop .empty{padding:12px;font-size:12.5px;color:#6B7280}
106
+ .num{width:20px;height:20px;border-radius:99px;background:#071342;color:#fff;font-size:11px;font-weight:700;display:grid;place-items:center;flex:none}
107
+ .panel{position:fixed;top:0;bottom:0;inset-inline-end:0;width:380px;max-width:100vw;background:#fff;border-inline-start:1px solid #E5EAF2;box-shadow:-8px 0 24px rgba(10,18,64,.06);display:flex;flex-direction:column}
108
+ .hd{padding:16px 18px 14px;border-bottom:1px solid #E5EAF2}
109
+ .crumbs{display:flex;align-items:center;flex-wrap:wrap;gap:4px;font-size:11.5px;color:#6B7280;margin-bottom:6px}
110
+ .crumbs svg{color:#A8AEC1}
111
+ .crumb{border:0;background:transparent;color:#6B7280;font-weight:500;font-size:11.5px;padding:2px 6px;border-radius:5px}
112
+ .crumb.cur{background:#E5F9F6;color:#0F766E;font-weight:600}
113
+ .nav{margin-inline-start:auto;display:flex;gap:2px}
114
+ .nav button{border:1px solid #E5EAF2;background:#fff;border-radius:6px;width:24px;height:22px;display:grid;place-items:center;color:#3A4060;padding:0}
115
+ .nav button:disabled{opacity:.4}
116
+ .tr{display:flex;align-items:center;gap:10px}
117
+ .title{font-size:17px;font-weight:700;color:#0A1240;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
118
+ .pill{margin-inline-start:auto;display:inline-flex;align-items:center;gap:4px;font-size:11.5px;font-weight:600;padding:3px 8px;border-radius:999px;white-space:nowrap;flex:none}
119
+ .pill.ok{background:#E5F9F6;color:#0F766E}
120
+ .pill.many{background:#FFF7E6;color:#92400E}
121
+ .pill.none{background:#FEF3F2;color:#B42318}
122
+ .bd{padding:16px 18px;overflow:auto;flex:1}
123
+ .lbl{display:block;font-size:12.5px;font-weight:600;color:#242B3A;margin-bottom:8px}
124
+ .tiles{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:18px}
125
+ .tile{display:flex;align-items:center;gap:9px;padding:10px 11px;border-radius:10px;text-align:start;background:#fff;border:1.5px solid #E5EAF2;color:#3A4060}
126
+ .tile[aria-checked=true]{background:#E5F9F6;border-color:#00C8B7;color:#0F766E}
127
+ .tile.slot[aria-checked=true]{background:#F4F2FF;border-color:#7A6CFF;color:#4C3FD1}
128
+ .tile:disabled{opacity:.55}
129
+ .tile[data-e]>span::after{content:'';display:inline-block;width:6px;height:6px;border-radius:9px;background:#00A99A;margin-inline-start:6px;vertical-align:middle}
130
+ .tile b{display:block;font-size:12.5px;font-weight:600;color:#0A1240}
131
+ .tile small{display:block;font-size:10.5px;color:#6B7280}
132
+ .fr{display:flex;align-items:baseline;margin-bottom:8px}
133
+ .fr .lbl{margin:0}
134
+ .was{margin-inline-start:auto;font-size:11.5px;color:#6B7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:55%}
135
+ textarea,input,.ce{width:100%;font:inherit;font-size:13.5px;color:#0F1424;padding:10px 12px;border-radius:10px;border:1.5px solid #E5EAF2;background:#fff;outline:none}
136
+ textarea,.ce{line-height:1.5;resize:vertical;border-color:#00C8B7}
137
+ .ce{min-height:72px;white-space:pre-wrap;overflow-wrap:anywhere;cursor:text}
138
+ .vp{${PILL};cursor:pointer}
139
+ .vp .vfb{font-weight:400;opacity:.75}
140
+ .fbp .vc{margin-top:8px}
141
+ .slotc{display:flex;flex-direction:column;align-items:flex-start;gap:6px}
142
+ .slotc .lbl{margin:0}
143
+ .lnk{border:0;background:none;padding:0;color:#4C3FD1;font-size:12.5px;font-weight:600;text-align:start}
144
+ textarea.mono{height:auto}
145
+ input{height:40px;padding:0 12px}
146
+ input.slotin{border-color:#7A6CFF}
147
+ .mono{font-family:${MONO};font-size:12px;height:36px;background:#F8FAFC;border-width:1px}
148
+ .chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px;align-items:center}
149
+ .chips span{font-size:11.5px;color:#6B7280;margin-inline-end:2px}
150
+ .vc{font-family:${MONO};font-size:11.5px;padding:3px 8px;border-radius:6px;border:1px solid #E5EAF2;background:#F8FAFC;color:#3A4060}
151
+ .pk{margin-top:8px;border:1px solid #E5EAF2;border-radius:10px;padding:6px;background:#fff;box-shadow:0 8px 24px rgba(10,18,64,.1)}
152
+ .pk input{height:34px}
153
+ .pk [role=listbox]{max-height:220px;overflow:auto;margin-top:4px}
154
+ .pk .g{font-size:10.5px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:.4px;padding:8px 8px 3px}
155
+ .pk .o{display:flex;justify-content:space-between;align-items:baseline;gap:8px;padding:6px 8px;border-radius:7px;font-size:12.5px;cursor:pointer}
156
+ .pk .o[aria-selected=true],.pk .o:hover{background:#E5F9F6}
157
+ .pk code{font-family:${MONO};font-size:11px;color:#6B7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
158
+ [hidden]{display:none!important}
159
+ .help2{font-size:11.5px;color:#6B7280;margin-top:5px}
160
+ .err{font-size:11.5px;color:#B42318;margin-top:5px}
161
+ .mt{margin-top:14px}
162
+ .note{background:#FFF7E6;border:1px solid #FCD34D;border-radius:10px;padding:10px 12px;font-size:12.5px;color:#92400E;line-height:1.5}
163
+ .key{font-family:${MONO};color:#4C3FD1;background:#F4F2FF;padding:1px 6px;border-radius:4px}
164
+ .seg{display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;background:#F3F5FA;border-radius:9px;padding:3px}
165
+ .seg button{border:0;background:transparent;border-radius:7px;padding:6px 4px;font-size:12px;color:#3A4060}
166
+ .seg button[aria-checked=true]{background:#fff;color:#0A1240;font-weight:600;box-shadow:0 1px 2px rgba(10,18,64,.08)}
167
+ .css{margin-top:20px;display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;padding:0;color:#6B7280;font-size:12px}
168
+ .ft{padding:12px 18px;border-top:1px solid #E5EAF2;display:flex;gap:10px;background:#F8FAFC}
169
+ .cancel{height:38px;padding:0 14px;border-radius:10px;border:1px solid #E5EAF2;background:#fff;color:#242B3A;font-size:13px;font-weight:600}
170
+ .save{flex:1;height:38px;border-radius:10px;border:0;background:#071342;color:#fff;font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
171
+ .save:disabled{opacity:.45}
172
+ @media (max-width:760px){.r.open .dock{display:none}.help{display:none}}
173
+ `;
@@ -0,0 +1,301 @@
1
+ /**
2
+ * The "New text" field: the text with its variables as placeholder pills
3
+ * (the same pill as the page preview), the stored value unchanged Liquid.
4
+ *
5
+ * - Pill mode (the text has only plain text, `{{ user.x }}` and
6
+ * `| default: "..."`): a contenteditable box; each variable is an atomic
7
+ * `contenteditable=false` pill carrying its exact Liquid, so the value
8
+ * round-trips byte for byte. Backspace / Delete next to a pill removes the
9
+ * whole pill, arrow keys step over it (the browser's own handling of a
10
+ * non-editable inline), copy and cut put the Liquid on the clipboard, paste
11
+ * is plain text only (Liquid in it becomes pills). Enter is ignored - a
12
+ * page text edit is one run of text.
13
+ * - Raw mode (anything a pill cannot show: `{% if %}`, other filters): a
14
+ * textarea with the Liquid and a short note, so nothing is lost.
15
+ *
16
+ * - Each pill has its own fallback: a click on it (or Enter / Space on it)
17
+ * opens a small popover, "If <field> is missing" + one input, that writes
18
+ * `| default: "..."` on THAT variable only. A pill with a fallback shows it
19
+ * after its name ("firstName · friend"). The fallback is plain text - Liquid
20
+ * in it is refused. Esc, Enter or Done closes the popover.
21
+ *
22
+ * Inside the editor's closed shadow root the caret comes from the root's
23
+ * own getSelection() where the browser has it (Chromium), else the
24
+ * document's; with no caret in the box an Insert appends, as before.
25
+ */
26
+ import { isPlainFallback, liquidParts, setVarFallback, varFallback, type LiquidVar } from './editor-model';
27
+ import { fill } from './editor-strings';
28
+ import { h } from './editor-ui';
29
+
30
+ export interface LiquidField {
31
+ el: HTMLElement;
32
+ /** Show a value (re-renders; the mode follows the value). */
33
+ set(value: string): void;
34
+ /** Insert one variable's Liquid at the caret (or at the end). */
35
+ insert(tag: string): void;
36
+ /** Close a pill's fallback popover; true when one was open. */
37
+ closePop(): boolean;
38
+ }
39
+
40
+ /** The words of a pill's fallback popover: `title` has `{name}`, the field's label. */
41
+ export interface FallbackWords {
42
+ title: string;
43
+ help: string;
44
+ bad: string;
45
+ done: string;
46
+ }
47
+
48
+ const PILL_ATTR = 'data-liquid';
49
+ const isPill = (n: Node | null | undefined): n is HTMLElement => !!n && n.nodeType === 1 && (n as Element).hasAttribute(PILL_ATTR);
50
+
51
+ /** A box's content as Liquid: text as is, a pill as its Liquid, a browser-inserted `<br>` as nothing. */
52
+ export function serialize(n: Node): string {
53
+ if (n.nodeType === 3) return (n as Text).data;
54
+ if (isPill(n)) return n.getAttribute(PILL_ATTR) || '';
55
+ let s = '';
56
+ for (const k of Array.from(n.childNodes)) s += serialize(k);
57
+ return s;
58
+ }
59
+
60
+ export function liquidField(opts: {
61
+ label: string;
62
+ rawNote: string;
63
+ root: ShadowRoot | null;
64
+ onChange: (value: string) => void;
65
+ labelOf?: (path: string) => string | undefined;
66
+ fallback?: FallbackWords;
67
+ }): LiquidField {
68
+ const el = h('div', { 'data-j': 'text-box' });
69
+ let value = '';
70
+ let box: HTMLElement | null = null;
71
+ let saved: Range | null = null;
72
+ let pop: HTMLElement | null = null;
73
+
74
+ const selection = (): Selection | null => {
75
+ const r = opts.root as unknown as { getSelection?: () => Selection | null } | null;
76
+ return (r && typeof r.getSelection === 'function' ? r.getSelection() : null) || document.getSelection();
77
+ };
78
+ /** The selection as a Range in the box: Chromium's root.getSelection(), else getComposedRanges (Safari, Firefox), else the plain range. */
79
+ const caret = (): Range | null => {
80
+ const s = selection();
81
+ if (!s || !s.rangeCount) return null;
82
+ let r: Range | null = s.getRangeAt(0);
83
+ const composed = (s as unknown as { getComposedRanges?: (o: unknown) => StaticRange[] }).getComposedRanges;
84
+ if (opts.root && composed && !(box && box.contains(r.startContainer))) {
85
+ try {
86
+ const sr = composed.call(s, { shadowRoots: [opts.root] })[0];
87
+ r = document.createRange();
88
+ r.setStart(sr.startContainer, sr.startOffset);
89
+ r.setEnd(sr.endContainer, sr.endOffset);
90
+ } catch {
91
+ r = null;
92
+ }
93
+ }
94
+ return box && r && box.contains(r.startContainer) && box.contains(r.endContainer) ? r : null;
95
+ };
96
+ const remember = () => {
97
+ const r = caret();
98
+ if (r) saved = r.cloneRange();
99
+ };
100
+ const emit = () => {
101
+ if (box && box.tagName === 'DIV') value = serialize(box);
102
+ remember();
103
+ opts.onChange(value);
104
+ };
105
+ const putCaret = (r: Range) => {
106
+ const s = selection();
107
+ try {
108
+ if (s && s.setBaseAndExtent) s.setBaseAndExtent(r.startContainer, r.startOffset, r.endContainer, r.endOffset);
109
+ else if (s) {
110
+ s.removeAllRanges();
111
+ s.addRange(r);
112
+ }
113
+ } catch {
114
+ /* no selection here */
115
+ }
116
+ saved = r.cloneRange();
117
+ };
118
+ const labelOf = (v: LiquidVar) => (opts.labelOf && opts.labelOf(v.path)) || v.name;
119
+ const pill = (v: LiquidVar) => {
120
+ const fb = varFallback(v.src);
121
+ const label = labelOf(v);
122
+ const words = opts.fallback;
123
+ return h(
124
+ 'span',
125
+ {
126
+ class: 'vp',
127
+ contenteditable: 'false',
128
+ dir: 'auto',
129
+ title: v.src,
130
+ [PILL_ATTR]: v.src,
131
+ 'data-path': v.path,
132
+ ...(words ? { role: 'button', tabindex: '0', 'aria-haspopup': 'dialog', 'aria-label': fb ? `${label} · ${fb}` : label } : {}),
133
+ },
134
+ label,
135
+ fb ? h('span', { class: 'vfb', 'data-j': 'pill-fallback' }, ` · ${fb}`) : null,
136
+ );
137
+ };
138
+
139
+ const closePop = (): boolean => {
140
+ if (!pop) return false;
141
+ pop.remove();
142
+ pop = null;
143
+ return true;
144
+ };
145
+ /** A pill's own fallback: the popover under the field, writing that pill's `| default:` as it is typed. */
146
+ const openPop = (target: HTMLElement) => {
147
+ const words = opts.fallback;
148
+ if (!words || !box || box.tagName !== 'DIV') return;
149
+ closePop();
150
+ let cur = target;
151
+ const v = { path: cur.getAttribute('data-path') || '', name: '', src: cur.getAttribute(PILL_ATTR) || '' };
152
+ v.name = v.path.replace(/^user\.(custom\.)?/, '');
153
+ const title = fill(words.title, { name: labelOf(v) });
154
+ const input = h('input', { dir: 'auto', 'data-j': 'fallback', 'aria-label': title, maxlength: '200' });
155
+ input.value = varFallback(v.src) || '';
156
+ const err = h('div', { class: 'err', 'data-j': 'fallback-error', role: 'alert' });
157
+ const done = h('button', { class: 'vc', type: 'button', 'data-j': 'fallback-done' }, words.done);
158
+ const p = h('div', { class: 'pk fbp', role: 'dialog', 'aria-label': title, 'data-j': 'fallback-pop' }, h('label', { class: 'lbl' }, title), input, err, h('div', { class: 'help2' }, words.help), done);
159
+ const finish = () => {
160
+ closePop();
161
+ try {
162
+ cur.focus();
163
+ } catch {
164
+ /* gone */
165
+ }
166
+ };
167
+ input.addEventListener('input', () => {
168
+ const ok = isPlainFallback(input.value);
169
+ err.textContent = ok ? '' : words.bad;
170
+ if (!ok) return;
171
+ const src = setVarFallback(cur.getAttribute(PILL_ATTR) || '', input.value);
172
+ const next = pill({ ...v, src });
173
+ if (cur.parentNode) cur.parentNode.replaceChild(next, cur);
174
+ cur = next;
175
+ if (box && box.tagName === 'DIV') value = serialize(box);
176
+ opts.onChange(value);
177
+ });
178
+ input.addEventListener('keydown', (e) => {
179
+ if (e.key === 'Enter' || e.key === 'Escape') {
180
+ e.preventDefault();
181
+ e.stopPropagation();
182
+ finish();
183
+ }
184
+ });
185
+ done.addEventListener('click', finish);
186
+ pop = p;
187
+ el.appendChild(p);
188
+ input.focus();
189
+ };
190
+
191
+ const set = (v: string) => {
192
+ value = v;
193
+ saved = null;
194
+ pop = null;
195
+ el.textContent = '';
196
+ const parts = liquidParts(v);
197
+ if (!parts) {
198
+ const area = h('textarea', { rows: '3', dir: 'auto', 'data-j': 'text', 'aria-label': opts.label });
199
+ area.value = v;
200
+ area.addEventListener('input', () => {
201
+ value = area.value;
202
+ opts.onChange(value);
203
+ });
204
+ area.addEventListener('blur', () => liquidParts(value) && set(value));
205
+ box = area;
206
+ el.append(area, h('div', { class: 'help2', 'data-j': 'raw-note' }, opts.rawNote));
207
+ return;
208
+ }
209
+ const ce = h('div', { class: 'ce', contenteditable: 'true', role: 'textbox', 'aria-multiline': 'true', dir: 'auto', spellcheck: 'false', 'data-j': 'text', 'aria-label': opts.label });
210
+ for (const p of parts) ce.append(typeof p === 'string' ? document.createTextNode(p) : pill(p));
211
+ ce.addEventListener('input', emit);
212
+ ce.addEventListener('keyup', remember);
213
+ ce.addEventListener('mouseup', remember);
214
+ ce.addEventListener('click', (e) => {
215
+ const t = e.target instanceof Element ? (e.target.closest(`[${PILL_ATTR}]`) as HTMLElement | null) : null;
216
+ if (t && ce.contains(t)) openPop(t);
217
+ });
218
+ ce.addEventListener('keydown', (e) => {
219
+ const onPill = e.target instanceof Element && isPill(e.target) ? (e.target as HTMLElement) : null;
220
+ if (onPill && (e.key === 'Enter' || e.key === ' ')) {
221
+ e.preventDefault();
222
+ return openPop(onPill);
223
+ }
224
+ if (e.key === 'Enter') return e.preventDefault();
225
+ if (e.key !== 'Backspace' && e.key !== 'Delete') return;
226
+ const r = caret();
227
+ if (!r || !r.collapsed) return;
228
+ const back = e.key === 'Backspace';
229
+ const c = r.startContainer;
230
+ const o = r.startOffset;
231
+ let next: Node | null = null;
232
+ if (c.nodeType === 3) {
233
+ if (back && o === 0) next = c.previousSibling;
234
+ else if (!back && o === (c as Text).length) next = c.nextSibling;
235
+ } else next = c.childNodes[back ? o - 1 : o] || null;
236
+ if (!isPill(next)) return;
237
+ e.preventDefault();
238
+ next.remove();
239
+ emit();
240
+ });
241
+ const clip = (cut: boolean) => (e: ClipboardEvent) => {
242
+ const r = caret();
243
+ if (!r || r.collapsed || !e.clipboardData) return;
244
+ e.preventDefault();
245
+ e.clipboardData.setData('text/plain', serialize(r.cloneContents()));
246
+ if (cut) {
247
+ r.deleteContents();
248
+ emit();
249
+ }
250
+ };
251
+ ce.addEventListener('copy', clip(false));
252
+ ce.addEventListener('cut', clip(true));
253
+ ce.addEventListener('paste', (e) => {
254
+ e.preventDefault();
255
+ const text = ((e.clipboardData && e.clipboardData.getData('text/plain')) || '').replace(/\r/g, '');
256
+ const r = caret();
257
+ if (!text || !r) return;
258
+ r.deleteContents();
259
+ const t = document.createTextNode(text);
260
+ r.insertNode(t);
261
+ r.setStartAfter(t);
262
+ r.collapse(true);
263
+ putCaret(r);
264
+ emit();
265
+ if (/\{[{%]/.test(text)) set(value);
266
+ });
267
+ // Liquid typed by hand becomes pills (or the raw box) once the field is left.
268
+ ce.addEventListener('blur', () => Array.from(ce.childNodes).some((n) => n.nodeType === 3 && /\{[{%]/.test((n as Text).data)) && set(value));
269
+ box = ce;
270
+ el.appendChild(ce);
271
+ };
272
+
273
+ const insert = (tag: string) => {
274
+ const live = caret();
275
+ const r = live || (saved && box && box.isConnected && box.contains(saved.startContainer) ? saved : null);
276
+ if (!r || !box || box.tagName !== 'DIV') {
277
+ set(value ? `${value.replace(/\s+$/, '')} ${tag}` : tag);
278
+ return opts.onChange(value);
279
+ }
280
+ const parts = liquidParts(tag);
281
+ const v = parts && parts[0];
282
+ if (!v || typeof v === 'string') return;
283
+ box.focus();
284
+ r.deleteContents();
285
+ const before = document.createRange();
286
+ before.selectNodeContents(box);
287
+ before.setEnd(r.startContainer, r.startOffset);
288
+ const prev = serialize(before.cloneContents());
289
+ const frag = document.createDocumentFragment();
290
+ if (prev && !/\s$/.test(prev)) frag.appendChild(document.createTextNode(' '));
291
+ const p = pill(v);
292
+ frag.appendChild(p);
293
+ r.insertNode(frag);
294
+ r.setStartAfter(p);
295
+ r.collapse(true);
296
+ putCaret(r);
297
+ emit();
298
+ };
299
+
300
+ return { el, set, insert, closePop };
301
+ }