@streamline-pulse/formkrafter-wc 0.3.0 → 0.5.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.
Files changed (159) hide show
  1. package/README.md +23 -9
  2. package/dist/components/fk-brick-actions.js +1 -1
  3. package/dist/components/fk-brick-list.js +1 -1
  4. package/dist/components/fk-brick-mold-item.js +1 -1
  5. package/dist/components/fk-brick-render.js +1 -1
  6. package/dist/components/fk-code-editor.js +1 -1
  7. package/dist/components/fk-data-grid.js +1 -1
  8. package/dist/components/fk-drop-area.js +1 -1
  9. package/dist/components/fk-empty-form.js +1 -1
  10. package/dist/components/fk-file-input.js +1 -1
  11. package/dist/components/fk-form-builder.js +1 -1
  12. package/dist/components/fk-form-render.js +1 -1
  13. package/dist/components/fk-property-panel.js +1 -1
  14. package/dist/components/fk-rules-editor.js +1 -1
  15. package/dist/components/fk-select-input.js +1 -1
  16. package/dist/components/fk-signature-input.js +1 -1
  17. package/dist/components/fk-stepper.js +1 -1
  18. package/dist/components/fk-tabs.js +1 -1
  19. package/dist/components/index.js +1 -1
  20. package/dist/components/{p-DYchD23x.js → p-BerMKKKo.js} +1 -1
  21. package/dist/components/p-Bey6yx4S.js +1 -0
  22. package/dist/{formkrafter-wc/p-C-wnqV3i.js → components/p-BietHxaT.js} +1 -1
  23. package/dist/components/p-Bj48EXdM.js +1 -0
  24. package/dist/components/p-BkqqQX6U.js +1 -0
  25. package/dist/components/p-BnxDCFjv.js +1 -0
  26. package/dist/components/p-BpkKcCCr.js +1 -0
  27. package/dist/components/p-C0Y8qh8R.js +1 -0
  28. package/dist/components/{p-BGkZP87K.js → p-CIzLjMz0.js} +1 -1
  29. package/dist/components/{p--vL6GR31.js → p-C_8wUoZ4.js} +1 -1
  30. package/dist/components/p-CeeVZgCr.js +1 -0
  31. package/dist/components/{p-4COASNrZ.js → p-CehxuHtl.js} +1 -1
  32. package/dist/components/{p-D6n74M9d.js → p-CjnF4RZI.js} +1 -1
  33. package/dist/components/{p-CIfjRTky.js → p-CsHWN99R.js} +1 -1
  34. package/dist/components/p-CyZA17qf.js +1 -0
  35. package/dist/components/p-DlqnIm46.js +1 -0
  36. package/dist/components/{p-v7LxwCAc.js → p-DwN4nM7G.js} +1 -1
  37. package/dist/components/{p-DMCkrZqi.js → p-RzeBwfwG.js} +1 -1
  38. package/dist/components/{p-BWdm2a6q.js → p-_64WINOr.js} +1 -1
  39. package/dist/components/p-bZPtT8wr.js +1 -0
  40. package/dist/components/{p-fDJP6whN.js → p-hELMtJ9v.js} +1 -1
  41. package/dist/components/{p-CKMHMpID.js → p-l7ULqDJ3.js} +4 -4
  42. package/dist/components/{p-wuC5rVU7.js → p-tSZpD5I-.js} +1 -1
  43. package/dist/components/p-tTJg_I4V.js +1 -0
  44. package/dist/formkrafter-wc/formkrafter-wc.css +1 -1
  45. package/dist/formkrafter-wc/formkrafter-wc.esm.js +1 -1
  46. package/dist/formkrafter-wc/index.esm.js +1 -1
  47. package/dist/{components/p-C-wnqV3i.js → formkrafter-wc/p-BietHxaT.js} +1 -1
  48. package/dist/formkrafter-wc/p-C0Y8qh8R.js +1 -0
  49. package/dist/formkrafter-wc/p-C5tYszq2.js +12 -0
  50. package/dist/formkrafter-wc/{p-4COASNrZ.js → p-CehxuHtl.js} +1 -1
  51. package/dist/formkrafter-wc/p-DYsf28oe.js +1 -0
  52. package/dist/formkrafter-wc/p-DlqnIm46.js +1 -0
  53. package/dist/formkrafter-wc/{p-DMCkrZqi.js → p-RzeBwfwG.js} +1 -1
  54. package/dist/formkrafter-wc/p-WWmY5Z05.js +1 -0
  55. package/dist/formkrafter-wc/p-bf962b94.entry.js +1 -0
  56. package/dist/formkrafter-wc/p-ca200eec.entry.js +1 -0
  57. package/dist/types/components/fk-code-editor/fk-code-editor.d.ts +1 -0
  58. package/dist/types/components/fk-data-grid/fk-data-grid.d.ts +1 -0
  59. package/dist/types/components/fk-drop-area/fk-drop-area.d.ts +1 -0
  60. package/dist/types/components/fk-form-render/fk-form-render.d.ts +7 -1
  61. package/dist/types/components/fk-select-input/fk-select-input.d.ts +5 -1
  62. package/dist/types/components.d.ts +17 -0
  63. package/dist/types/index.d.ts +1 -1
  64. package/dist/types/registry/default-bricks.d.ts +36 -0
  65. package/dist/types/utils/mask.d.ts +1 -0
  66. package/package.json +10 -15
  67. package/dist/cjs/app-globals-V2Kpy_OQ.js +0 -5
  68. package/dist/cjs/fk-brick-actions_18.cjs.entry.js +0 -4224
  69. package/dist/cjs/formkrafter-wc.cjs.js +0 -25
  70. package/dist/cjs/index-Bhy1RJMV.js +0 -3042
  71. package/dist/cjs/index-CImTe9BG.js +0 -2126
  72. package/dist/cjs/index-CdaT3-qx.js +0 -5444
  73. package/dist/cjs/index-CkPPRg03.js +0 -17548
  74. package/dist/cjs/index-DHgK3reD.js +0 -12233
  75. package/dist/cjs/index-Ds0sDbXV.js +0 -4019
  76. package/dist/cjs/index-c9BL7y3N.js +0 -1922
  77. package/dist/cjs/index.cjs.js +0 -48
  78. package/dist/cjs/loader.cjs.js +0 -13
  79. package/dist/collection/collection-manifest.json +0 -30
  80. package/dist/collection/components/fk-brick-actions/fk-brick-actions.css +0 -78
  81. package/dist/collection/components/fk-brick-actions/fk-brick-actions.js +0 -215
  82. package/dist/collection/components/fk-brick-list/fk-brick-list.css +0 -71
  83. package/dist/collection/components/fk-brick-list/fk-brick-list.js +0 -55
  84. package/dist/collection/components/fk-brick-mold-item/fk-brick-mold-item.css +0 -33
  85. package/dist/collection/components/fk-brick-mold-item/fk-brick-mold-item.js +0 -73
  86. package/dist/collection/components/fk-brick-not-found/fk-brick-not-found.css +0 -8
  87. package/dist/collection/components/fk-brick-not-found/fk-brick-not-found.js +0 -18
  88. package/dist/collection/components/fk-brick-render/fk-brick-render.js +0 -447
  89. package/dist/collection/components/fk-code-editor/fk-code-editor.css +0 -26
  90. package/dist/collection/components/fk-code-editor/fk-code-editor.js +0 -145
  91. package/dist/collection/components/fk-data-grid/fk-data-grid.css +0 -75
  92. package/dist/collection/components/fk-data-grid/fk-data-grid.js +0 -300
  93. package/dist/collection/components/fk-drop-area/fk-drop-area.css +0 -18
  94. package/dist/collection/components/fk-drop-area/fk-drop-area.js +0 -98
  95. package/dist/collection/components/fk-empty-form/fk-empty-form.css +0 -22
  96. package/dist/collection/components/fk-empty-form/fk-empty-form.js +0 -19
  97. package/dist/collection/components/fk-file-input/fk-file-input.css +0 -95
  98. package/dist/collection/components/fk-file-input/fk-file-input.js +0 -239
  99. package/dist/collection/components/fk-form-builder/fk-form-builder.css +0 -112
  100. package/dist/collection/components/fk-form-builder/fk-form-builder.js +0 -431
  101. package/dist/collection/components/fk-form-render/fk-form-render.css +0 -7
  102. package/dist/collection/components/fk-form-render/fk-form-render.js +0 -352
  103. package/dist/collection/components/fk-property-panel/fk-property-panel.css +0 -153
  104. package/dist/collection/components/fk-property-panel/fk-property-panel.js +0 -388
  105. package/dist/collection/components/fk-rules-editor/fk-rules-editor.css +0 -166
  106. package/dist/collection/components/fk-rules-editor/fk-rules-editor.js +0 -250
  107. package/dist/collection/components/fk-select-input/fk-select-input.css +0 -153
  108. package/dist/collection/components/fk-select-input/fk-select-input.js +0 -454
  109. package/dist/collection/components/fk-signature-input/fk-signature-input.css +0 -42
  110. package/dist/collection/components/fk-signature-input/fk-signature-input.js +0 -158
  111. package/dist/collection/components/fk-stepper/fk-stepper.css +0 -99
  112. package/dist/collection/components/fk-stepper/fk-stepper.js +0 -285
  113. package/dist/collection/components/fk-tabs/fk-tabs.css +0 -38
  114. package/dist/collection/components/fk-tabs/fk-tabs.js +0 -249
  115. package/dist/collection/i18n/i18n.js +0 -265
  116. package/dist/collection/index.js +0 -5
  117. package/dist/collection/registry/create-brick.js +0 -34
  118. package/dist/collection/registry/default-bricks.js +0 -564
  119. package/dist/collection/registry/registry.js +0 -44
  120. package/dist/collection/utils/brick-data.js +0 -16
  121. package/dist/collection/utils/drop.js +0 -14
  122. package/dist/collection/utils/events.js +0 -1
  123. package/dist/collection/utils/options.js +0 -21
  124. package/dist/collection/utils/remote.js +0 -27
  125. package/dist/collection/utils/rule-condition.js +0 -72
  126. package/dist/collection/utils/style.js +0 -11
  127. package/dist/components/p-BOmBVgfJ.js +0 -1
  128. package/dist/components/p-B_-x-GlA.js +0 -1
  129. package/dist/components/p-Br1s4Ujx.js +0 -1
  130. package/dist/components/p-CUF31e-P.js +0 -1
  131. package/dist/components/p-CWQX0sXS.js +0 -1
  132. package/dist/components/p-DFe3zZCI.js +0 -1
  133. package/dist/components/p-DOInQkG6.js +0 -1
  134. package/dist/components/p-PAr7WoWG.js +0 -1
  135. package/dist/components/p-YyGnQmX-.js +0 -1
  136. package/dist/components/p-swxZqinH.js +0 -1
  137. package/dist/esm/app-globals-DQuL1Twl.js +0 -3
  138. package/dist/esm/fk-brick-actions_18.entry.js +0 -4205
  139. package/dist/esm/formkrafter-wc.js +0 -21
  140. package/dist/esm/index-BAcz7b5u.js +0 -5416
  141. package/dist/esm/index-BkRMoLXK.js +0 -3029
  142. package/dist/esm/index-CGMDfZ5m.js +0 -1808
  143. package/dist/esm/index-D7Cta1UB.js +0 -17488
  144. package/dist/esm/index-DtcM1yw5.js +0 -3991
  145. package/dist/esm/index-DuVf3NlP.js +0 -12222
  146. package/dist/esm/index-qLZlXROB.js +0 -2117
  147. package/dist/esm/index.js +0 -2
  148. package/dist/esm/loader.js +0 -11
  149. package/dist/formkrafter-wc/p-6d29555b.entry.js +0 -1
  150. package/dist/formkrafter-wc/p-DOInQkG6.js +0 -1
  151. package/dist/formkrafter-wc/p-Ddu6BquK.js +0 -12
  152. package/dist/index.cjs.js +0 -1
  153. package/dist/index.js +0 -1
  154. package/dist/stencil.config.js +0 -34
  155. package/loader/cdn.js +0 -1
  156. package/loader/index.cjs.js +0 -1
  157. package/loader/index.d.ts +0 -24
  158. package/loader/index.es2017.js +0 -1
  159. package/loader/index.js +0 -2
@@ -1,4205 +0,0 @@
1
- import { r as registerInstance, c as createEvent, h, g as getElement, H as Host } from './index-qLZlXROB.js';
2
- import { g as getBrickMolds, f as fkT, a as getBrickMoldsGroupedByCategory, b as fkTOr, c as getBrick, d as getAffectedProperties, r as resolveLocalizedRecord, v as validateBrickSpecDataDetailed, s as services, S as SpecHistory, e as registerDefaultBricks, n as newBrickSpec, h as addBrick, i as getBrickAt, m as moveBrick, j as removeBrick, k as duplicateBrick, u as updateBrickConfigs, l as updateBrickStyles, o as updateBrickValidations, p as updateBrickRules, q as iterateBricks, t as isLocalizedObject, w as normalizeOptions, x as evalBrickCode, y as iterateSchemaBricks } from './index-D7Cta1UB.js';
3
-
4
- function _arrayWithHoles(r) {
5
- if (Array.isArray(r)) return r;
6
- }
7
-
8
- function _iterableToArrayLimit(r, l) {
9
- var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
10
- if (null != t) {
11
- var e,
12
- n,
13
- i,
14
- u,
15
- a = [],
16
- f = true,
17
- o = false;
18
- try {
19
- if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = true);
20
- } catch (r) {
21
- o = true, n = r;
22
- } finally {
23
- try {
24
- if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
25
- } finally {
26
- if (o) throw n;
27
- }
28
- }
29
- return a;
30
- }
31
- }
32
-
33
- function _arrayLikeToArray$2(r, a) {
34
- (null == a || a > r.length) && (a = r.length);
35
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
36
- return n;
37
- }
38
-
39
- function _unsupportedIterableToArray$2(r, a) {
40
- if (r) {
41
- if ("string" == typeof r) return _arrayLikeToArray$2(r, a);
42
- var t = {}.toString.call(r).slice(8, -1);
43
- return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$2(r, a) : void 0;
44
- }
45
- }
46
-
47
- function _nonIterableRest() {
48
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
49
- }
50
-
51
- function _slicedToArray(r, e) {
52
- return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray$2(r, e) || _nonIterableRest();
53
- }
54
-
55
- var dist = {};
56
-
57
- var bind = {};
58
-
59
- var hasRequiredBind;
60
-
61
- function requireBind () {
62
- if (hasRequiredBind) return bind;
63
- hasRequiredBind = 1;
64
- Object.defineProperty(bind, "__esModule", { value: true });
65
- bind.bind = void 0;
66
- function bind$1(target, _a) {
67
- var type = _a.type, listener = _a.listener, options = _a.options;
68
- target.addEventListener(type, listener, options);
69
- return function unbind() {
70
- target.removeEventListener(type, listener, options);
71
- };
72
- }
73
- bind.bind = bind$1;
74
- return bind;
75
- }
76
-
77
- var bindAll = {};
78
-
79
- var hasRequiredBindAll;
80
-
81
- function requireBindAll () {
82
- if (hasRequiredBindAll) return bindAll;
83
- hasRequiredBindAll = 1;
84
- var __assign = (bindAll && bindAll.__assign) || function () {
85
- __assign = Object.assign || function(t) {
86
- for (var s, i = 1, n = arguments.length; i < n; i++) {
87
- s = arguments[i];
88
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
89
- t[p] = s[p];
90
- }
91
- return t;
92
- };
93
- return __assign.apply(this, arguments);
94
- };
95
- Object.defineProperty(bindAll, "__esModule", { value: true });
96
- bindAll.bindAll = void 0;
97
- var bind_1 = /*@__PURE__*/ requireBind();
98
- function toOptions(value) {
99
- if (typeof value === 'undefined') {
100
- return undefined;
101
- }
102
- if (typeof value === 'boolean') {
103
- return {
104
- capture: value,
105
- };
106
- }
107
- return value;
108
- }
109
- function getBinding(original, sharedOptions) {
110
- if (sharedOptions == null) {
111
- return original;
112
- }
113
- var binding = __assign(__assign({}, original), { options: __assign(__assign({}, toOptions(sharedOptions)), toOptions(original.options)) });
114
- return binding;
115
- }
116
- function bindAll$1(target, bindings, sharedOptions) {
117
- var unbinds = bindings.map(function (original) {
118
- var binding = getBinding(original, sharedOptions);
119
- return (0, bind_1.bind)(target, binding);
120
- });
121
- return function unbindAll() {
122
- unbinds.forEach(function (unbind) { return unbind(); });
123
- };
124
- }
125
- bindAll.bindAll = bindAll$1;
126
- return bindAll;
127
- }
128
-
129
- var hasRequiredDist;
130
-
131
- function requireDist () {
132
- if (hasRequiredDist) return dist;
133
- hasRequiredDist = 1;
134
- (function (exports) {
135
- Object.defineProperty(exports, "__esModule", { value: true });
136
- exports.bindAll = exports.bind = void 0;
137
- var bind_1 = /*@__PURE__*/ requireBind();
138
- Object.defineProperty(exports, "bind", { enumerable: true, get: function () { return bind_1.bind; } });
139
- var bind_all_1 = /*@__PURE__*/ requireBindAll();
140
- Object.defineProperty(exports, "bindAll", { enumerable: true, get: function () { return bind_all_1.bindAll; } });
141
- } (dist));
142
- return dist;
143
- }
144
-
145
- var distExports = /*@__PURE__*/ requireDist();
146
-
147
- // pulling this into a separate file so adapter(s) that don't
148
- // need the honey pot can pay as little as possible for it.
149
- var honeyPotDataAttribute = 'data-pdnd-honey-pot';
150
-
151
- function isHoneyPotElement(target) {
152
- return target instanceof Element && target.hasAttribute(honeyPotDataAttribute);
153
- }
154
-
155
- function getElementFromPointWithoutHoneypot(client) {
156
- // eslint-disable-next-line no-restricted-syntax
157
- var _document$elementsFro = document.elementsFromPoint(client.x, client.y),
158
- _document$elementsFro2 = _slicedToArray(_document$elementsFro, 2),
159
- top = _document$elementsFro2[0],
160
- second = _document$elementsFro2[1];
161
- if (!top) {
162
- return null;
163
- }
164
- if (isHoneyPotElement(top)) {
165
- return second !== null && second !== void 0 ? second : null;
166
- }
167
- return top;
168
- }
169
-
170
- function _typeof(o) {
171
- "@babel/helpers - typeof";
172
-
173
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
174
- return typeof o;
175
- } : function (o) {
176
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
177
- }, _typeof(o);
178
- }
179
-
180
- function toPrimitive(t, r) {
181
- if ("object" != _typeof(t) || !t) return t;
182
- var e = t[Symbol.toPrimitive];
183
- if (void 0 !== e) {
184
- var i = e.call(t, r);
185
- if ("object" != _typeof(i)) return i;
186
- throw new TypeError("@@toPrimitive must return a primitive value.");
187
- }
188
- return ("string" === r ? String : Number)(t);
189
- }
190
-
191
- function toPropertyKey(t) {
192
- var i = toPrimitive(t, "string");
193
- return "symbol" == _typeof(i) ? i : i + "";
194
- }
195
-
196
- function _defineProperty(e, r, t) {
197
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
198
- value: t,
199
- enumerable: true,
200
- configurable: true,
201
- writable: true
202
- }) : e[r] = t, e;
203
- }
204
-
205
- // Maximum possible z-index
206
- // https://stackoverflow.com/questions/491052/minimum-and-maximum-value-of-z-index
207
- var maxZIndex = 2147483647;
208
-
209
- /**
210
- * Resets user agent styles for `[popover]` elements.
211
- *
212
- * Browsers apply these defaults to popovers (per the WHATWG HTML spec rendering section):
213
- * - `inset: 0` + `margin: auto` → centers the popover in the viewport
214
- * - `border: solid` → visible border
215
- * - `padding: 0.25em` → internal spacing
216
- * - `overflow: auto` → scrollbars when content overflows
217
- * - `color: CanvasText` + `background-color: Canvas` → system theme colors
218
- *
219
- * This object neutralizes those defaults so the popover behaves like a plain
220
- * positioned `<div>`, matching the sizing of the legacy (non-popover)
221
- * fallback container exactly.
222
- *
223
- * **Width and height (`auto`)**
224
- *
225
- * `width` and `height` override the spec user agent value of `fit-content`
226
- * with `auto`.
227
- *
228
- * _Why?_
229
- *
230
- * - When a `[popover]` is sized with `fit-content` and contains a flex
231
- * container, Safari collapses any flex item that uses `overflow: auto`
232
- * to `0px`.
233
- * - Setting the popover's `width` and `height` to `auto` skips the `fit-content`
234
- * pass and avoids the bug in Safari
235
- * - Chromium and Firefox tolerate `fit-content` here, but `auto` is safe
236
- * everywhere and matches our non-popover path
237
- */
238
- var popoverResetUserAgentStyles = {
239
- inset: 'unset',
240
- border: 'none',
241
- padding: 0,
242
- margin: 0,
243
- overflow: 'visible',
244
- color: 'inherit',
245
- background: 'transparent',
246
- width: 'auto',
247
- height: 'auto'
248
- };
249
-
250
- /** Provide a function that you only ever want to be called a single time */
251
- function once(fn) {
252
- var cache = null;
253
- return function wrapped() {
254
- if (!cache) {
255
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
256
- args[_key] = arguments[_key];
257
- }
258
- var result = fn.apply(this, args);
259
- cache = {
260
- result: result
261
- };
262
- }
263
- return cache.result;
264
- };
265
- }
266
-
267
- // Using `once` as the value won't change in a browser
268
-
269
- /**
270
- * Returns `true` if the browser supports the Popover API (top-layer).
271
- *
272
- * When supported, elements with `popover="manual"` can be promoted to the
273
- * browser's top layer via `element.showPopover()`, which is more reliable
274
- * than `z-index` for ensuring an element renders above everything else.
275
- *
276
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Popover_API
277
- */
278
- var supportsPopover = once(function supportsPopover() {
279
- return typeof HTMLElement !== 'undefined' && typeof HTMLElement.prototype.showPopover === 'function';
280
- });
281
-
282
- function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
283
- function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
284
- var honeyPotSize = 2;
285
- var halfHoneyPotSize = honeyPotSize / 2;
286
-
287
- /**
288
- * `clientX` and `clientY` can be in sub pixels (eg `2.332`)
289
- * However, browser hitbox testing is commonly do to the closest pixel.
290
- *
291
- * → https://issues.chromium.org/issues/40940531
292
- *
293
- * To be sure that the honey pot will be over the `client` position,
294
- * we `.floor()` `clientX` and`clientY` and then make it `2px` in size.
295
- **/
296
- function floorToClosestPixel(point) {
297
- return {
298
- x: Math.floor(point.x),
299
- y: Math.floor(point.y)
300
- };
301
- }
302
-
303
- /**
304
- * We want to make sure the honey pot sits around the users position.
305
- * This seemed to be the most resilient while testing.
306
- */
307
- function pullBackByHalfHoneyPotSize(point) {
308
- return {
309
- x: point.x - halfHoneyPotSize,
310
- y: point.y - halfHoneyPotSize
311
- };
312
- }
313
-
314
- /**
315
- * Prevent the honey pot from changing the window size.
316
- * This is super unlikely to occur, but just being safe.
317
- */
318
- function preventGoingBackwardsOffScreen(point) {
319
- return {
320
- x: Math.max(point.x, 0),
321
- y: Math.max(point.y, 0)
322
- };
323
- }
324
-
325
- /**
326
- * Prevent the honey pot from changing the window size.
327
- * This is super unlikely to occur, but just being safe.
328
- */
329
- function preventGoingForwardsOffScreen(point) {
330
- return {
331
- x: Math.min(point.x, window.innerWidth - honeyPotSize),
332
- y: Math.min(point.y, window.innerHeight - honeyPotSize)
333
- };
334
- }
335
-
336
- /**
337
- * Create a `2x2` `DOMRect` around the `client` position
338
- */
339
- function getHoneyPotRectFor(_ref) {
340
- var client = _ref.client;
341
- var point = preventGoingForwardsOffScreen(preventGoingBackwardsOffScreen(pullBackByHalfHoneyPotSize(floorToClosestPixel(client))));
342
-
343
- // When debugging, it is helpful to
344
- // make this element a bit bigger
345
- return DOMRect.fromRect({
346
- x: point.x,
347
- y: point.y,
348
- width: honeyPotSize,
349
- height: honeyPotSize
350
- });
351
- }
352
- function getRectStyles(_ref2) {
353
- var clientRect = _ref2.clientRect;
354
- return {
355
- left: "".concat(clientRect.left, "px"),
356
- top: "".concat(clientRect.top, "px"),
357
- width: "".concat(clientRect.width, "px"),
358
- height: "".concat(clientRect.height, "px")
359
- };
360
- }
361
- function isWithin(_ref3) {
362
- var client = _ref3.client,
363
- clientRect = _ref3.clientRect;
364
- return (
365
- // is within horizontal bounds
366
- client.x >= clientRect.x && client.x <= clientRect.x + clientRect.width &&
367
- // is within vertical bounds
368
- client.y >= clientRect.y && client.y <= clientRect.y + clientRect.height
369
- );
370
- }
371
- /**
372
- * The honey pot fix is designed to get around a painful bug in all browsers.
373
- *
374
- * [Overview](https://www.youtube.com/watch?v=udE9qbFTeQg)
375
- *
376
- * **Background**
377
- *
378
- * When a drag starts, browsers incorrectly think that the users pointer is
379
- * still depressed where the drag started. Any element that goes under this position
380
- * will be entered into, causing `"mouseenter"` events and `":hover"` styles to be applied.
381
- *
382
- * _This is a violation of the spec_
383
- *
384
- * > "From the moment that the user agent is to initiate the drag-and-drop operation,
385
- * > until the end of the drag-and-drop operation, device input events
386
- * > (e.g. mouse and keyboard events) must be suppressed."
387
- * >
388
- * > - https://html.spec.whatwg.org/multipage/dnd.html#drag-and-drop-processing-model
389
- *
390
- * _Some impacts_
391
- *
392
- * - `":hover"` styles being applied where they shouldn't (looks messy)
393
- * - components such as tooltips responding to `"mouseenter"` can show during a drag,
394
- * and on an element the user isn't even over
395
- *
396
- * Bug: https://issues.chromium.org/issues/41129937
397
- *
398
- * **Honey pot fix**
399
- *
400
- * 1. Create an element where the browser thinks the depressed pointer is
401
- * to absorb the incorrect pointer events
402
- * 2. Remove that element when it is no longer needed
403
- */
404
- function mountHoneyPot(_ref4) {
405
- var initial = _ref4.initial;
406
- var element = document.createElement('div');
407
- element.setAttribute(honeyPotDataAttribute, 'true');
408
-
409
- // Using popover="manual" to place the element in the browser's top layer.
410
- // This ensures the honey pot is visually on top of everything else,
411
- // including elements using z-index and other stacking contexts.
412
- // "manual" means no light dismiss — we manage the lifecycle ourselves.
413
- // Falls back to position:fixed + maxZIndex when the popover API is not available.
414
- if (supportsPopover()) {
415
- element.setAttribute('popover', 'manual');
416
- }
417
-
418
- // can shift during the drag thanks to Firefox
419
- var clientRect = getHoneyPotRectFor({
420
- client: initial
421
- });
422
- Object.assign(element.style, _objectSpread$2(_objectSpread$2({
423
- position: 'fixed'
424
- }, supportsPopover() ?
425
- // needs to come first as it has 'inset: unset' which
426
- // needs to be overridden by our top / left values
427
- popoverResetUserAgentStyles : {
428
- // Fallback: using maximum possible z-index so that this element
429
- // will always be on top of other positioned content.
430
- zIndex: maxZIndex
431
- }), {}, {
432
- // Setting a background color explicitly to avoid any inherited styles.
433
- // Looks like this could be `opacity: 0`, but worried that _might_
434
- // cause the element to be ignored on some platforms.
435
- // When debugging, set backgroundColor to something like "red".
436
- backgroundColor: 'transparent',
437
- // Being explicit to avoid inheriting styles
438
- padding: 0,
439
- margin: 0,
440
- boxSizing: 'border-box',
441
- // We want this element to absorb pointer events,
442
- // it's kind of the whole point 😉
443
- pointerEvents: 'auto'
444
- }, getRectStyles({
445
- clientRect: clientRect
446
- })));
447
- document.body.appendChild(element);
448
- if (supportsPopover()) {
449
- element.showPopover();
450
- }
451
-
452
- /**
453
- * 🦊 In firefox we can get `"pointermove"` events after the drag
454
- * has started, which is a spec violation.
455
- * The final `"pointermove"` will reveal where the "depressed" position
456
- * is for our honey pot fix.
457
- */
458
- var unbindPointerMove = distExports.bind(window, {
459
- type: 'pointermove',
460
- listener: function listener(event) {
461
- var client = {
462
- x: event.clientX,
463
- y: event.clientY
464
- };
465
- clientRect = getHoneyPotRectFor({
466
- client: client
467
- });
468
- Object.assign(element.style, getRectStyles({
469
- clientRect: clientRect
470
- }));
471
- },
472
- // using capture so we are less likely to be impacted by event stopping
473
- options: {
474
- capture: true
475
- }
476
- });
477
- return function finish(_ref5) {
478
- var current = _ref5.current;
479
- // Don't need this any more
480
- unbindPointerMove();
481
-
482
- // If the user is hover the honey pot, we remove it
483
- // so that the user can continue to interact with the page normally.
484
- if (isWithin({
485
- client: current,
486
- clientRect: clientRect
487
- })) {
488
- element.remove();
489
- return;
490
- }
491
- function cleanup() {
492
- unbindPostDragEvents();
493
- element.remove();
494
- }
495
- var unbindPostDragEvents = distExports.bindAll(window, [{
496
- type: 'pointerdown',
497
- listener: cleanup
498
- }, {
499
- type: 'pointermove',
500
- listener: cleanup
501
- }, {
502
- type: 'focusin',
503
- listener: cleanup
504
- }, {
505
- type: 'focusout',
506
- listener: cleanup
507
- },
508
- // a 'pointerdown' should happen before 'dragstart', but just being super safe
509
- {
510
- type: 'dragstart',
511
- listener: cleanup
512
- },
513
- // if the user has dragged something out of the window
514
- // and then is dragging something back into the window
515
- // the first events we will see are "dragenter" (and then "dragover").
516
- // So if we see any of these we need to clear the post drag fix.
517
- {
518
- type: 'dragenter',
519
- listener: cleanup
520
- }, {
521
- type: 'dragover',
522
- listener: cleanup
523
- }
524
-
525
- // Not adding a "wheel" event listener, as "wheel" by itself does not
526
- // resolve the bug.
527
- ], {
528
- // Using `capture` so less likely to be impacted by other code stopping events
529
- capture: true
530
- });
531
- };
532
- }
533
- function makeHoneyPotFix() {
534
- var latestPointerMove = null;
535
- function bindEvents() {
536
- // For sanity, only collecting this value from when events are first bound.
537
- // This prevents the case where a super old "pointermove" could be used
538
- // from a prior interaction.
539
- latestPointerMove = null;
540
- return distExports.bind(window, {
541
- type: 'pointermove',
542
- listener: function listener(event) {
543
- latestPointerMove = {
544
- x: event.clientX,
545
- y: event.clientY
546
- };
547
- },
548
- // listening for pointer move in capture phase
549
- // so we are less likely to be impacted by events being stopped.
550
- options: {
551
- capture: true
552
- }
553
- });
554
- }
555
- function getOnPostDispatch() {
556
- var finish = null;
557
- return function onPostEvent(_ref6) {
558
- var eventName = _ref6.eventName,
559
- payload = _ref6.payload;
560
- // We are adding the honey pot `onDragStart` so we don't
561
- // impact the creation of the native drag preview.
562
- if (eventName === 'onDragStart') {
563
- var input = payload.location.initial.input;
564
-
565
- // Sometimes there will be no latest "pointermove" (eg iOS).
566
- // In which case, we use the start position of the drag.
567
- var initial = latestPointerMove !== null && latestPointerMove !== void 0 ? latestPointerMove : {
568
- x: input.clientX,
569
- y: input.clientY
570
- };
571
-
572
- // Don't need to defensively call `finish()` as `onDrop` from
573
- // one interaction is guaranteed to be called before `onDragStart`
574
- // of the next.
575
- finish = mountHoneyPot({
576
- initial: initial
577
- });
578
- }
579
- if (eventName === 'onDrop') {
580
- var _finish;
581
- var _input = payload.location.current.input;
582
- (_finish = finish) === null || _finish === void 0 || _finish({
583
- current: {
584
- x: _input.clientX,
585
- y: _input.clientY
586
- }
587
- });
588
- finish = null;
589
- // this interaction is finished, we want to use
590
- // the latest "pointermove" for each interaction
591
- latestPointerMove = null;
592
- }
593
- };
594
- }
595
- return {
596
- bindEvents: bindEvents,
597
- getOnPostDispatch: getOnPostDispatch
598
- };
599
- }
600
-
601
- function _arrayWithoutHoles(r) {
602
- if (Array.isArray(r)) return _arrayLikeToArray$2(r);
603
- }
604
-
605
- function _iterableToArray(r) {
606
- if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
607
- }
608
-
609
- function _nonIterableSpread() {
610
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
611
- }
612
-
613
- function _toConsumableArray(r) {
614
- return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray$2(r) || _nonIterableSpread();
615
- }
616
-
617
- // using `cache` as our `isFirefox()` result will not change in a browser
618
-
619
- /**
620
- * Returns `true` if a `Firefox` browser
621
- * */
622
- var isFirefox = once(function isFirefox() {
623
- return navigator.userAgent.includes('Firefox');
624
- });
625
-
626
- // using `cache` as our `isSafari()` result will not change in a browser
627
-
628
- /**
629
- * Returns `true` if a `Safari` browser.
630
- * Returns `true` if the browser is running on iOS (they are all Safari).
631
- *
632
- * Use `isSafariOnIOS` if you want to check if something is Safari + iOS
633
- * */
634
- var isSafari = once(function isSafari() {
635
- var _navigator = navigator,
636
- userAgent = _navigator.userAgent;
637
- return userAgent.includes('AppleWebKit') && !userAgent.includes('Chrome');
638
- });
639
-
640
- /* For "dragenter" events, the browser should set `relatedTarget` to the previous element.
641
- * For external drag operations, our first "dragenter" event should have a `event.relatedTarget` of `null`.
642
- *
643
- * Unfortunately in Safari `event.relatedTarget` is *always* set to `null`
644
- * Safari bug: https://bugs.webkit.org/show_bug.cgi?id=242627
645
- * To work around this we count "dragenter" and "dragleave" events */
646
-
647
- // Using symbols for event properties so we don't clash with
648
- // anything on the `event` object
649
- var symbols = {
650
- isLeavingWindow: Symbol('leaving'),
651
- isEnteringWindow: Symbol('entering')
652
- };
653
-
654
- // eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
655
- function isLeavingWindowInSafari(_ref2) {
656
- var dragLeave = _ref2.dragLeave;
657
- if (!isSafari()) {
658
- return false;
659
- }
660
- return dragLeave.hasOwnProperty(symbols.isLeavingWindow);
661
- }
662
- (function fixSafari() {
663
- // Don't do anything when server side rendering
664
- if (typeof window === 'undefined') {
665
- return;
666
- }
667
- if (!isSafari()) {
668
- return;
669
- }
670
- function getInitialState() {
671
- return {
672
- enterCount: 0,
673
- isOverWindow: false
674
- };
675
- }
676
- var state = getInitialState();
677
- function resetState() {
678
- state = getInitialState();
679
- }
680
-
681
- // These event listeners are bound _forever_ and _never_ removed
682
- // We don't bother cleaning up these event listeners (for now)
683
- // as this workaround is only for Safari
684
-
685
- // This is how the event count works:
686
- //
687
- // lift (+1 enterCount)
688
- // - dragstart(draggable) [enterCount: 0]
689
- // - dragenter(draggable) [enterCount: 1]
690
- // leaving draggable (+0 enterCount)
691
- // - dragenter(document.body) [enterCount: 2]
692
- // - dragleave(draggable) [enterCount: 1]
693
- // leaving window (-1 enterCount)
694
- // - dragleave(document.body) [enterCount: 0] {leaving the window}
695
-
696
- // Things to note:
697
- // - dragenter and dragleave bubble
698
- // - the first dragenter when entering a window might not be on `window`
699
- // - it could be on an element that is pressed up against the window
700
- // - (so we cannot rely on `event.target` values)
701
-
702
- distExports.bindAll(window, [{
703
- type: 'dragstart',
704
- listener: function listener() {
705
- state.enterCount = 0;
706
- // drag start occurs in the source window
707
- state.isOverWindow = true;
708
- // When a drag first starts it will also trigger a "dragenter" on the draggable element
709
- }
710
- }, {
711
- type: 'drop',
712
- listener: resetState
713
- }, {
714
- type: 'dragend',
715
- listener: resetState
716
- }, {
717
- type: 'dragenter',
718
- listener: function listener(event) {
719
- if (!state.isOverWindow && state.enterCount === 0) {
720
- // Patching the `event` object
721
- // The `event` object is shared with all event listeners for the event
722
- event[symbols.isEnteringWindow] = true;
723
- }
724
- state.isOverWindow = true;
725
- state.enterCount++;
726
- }
727
- }, {
728
- type: 'dragleave',
729
- listener: function listener(event) {
730
- state.enterCount--;
731
- if (state.isOverWindow && state.enterCount === 0) {
732
- // Patching the `event` object as it is shared with all event listeners
733
- // The `event` object is shared with all event listeners for the event
734
- event[symbols.isLeavingWindow] = true;
735
- state.isOverWindow = false;
736
- }
737
- }
738
- }],
739
- // using `capture: true` so that adding event listeners
740
- // in bubble phase will have the correct symbols
741
- {
742
- capture: true
743
- });
744
- })();
745
-
746
- /**
747
- * Does the `EventTarget` look like a `Node` based on "duck typing".
748
- *
749
- * Helpful when the `Node` might be outside of the current document
750
- * so we cannot to an `target instanceof Node` check.
751
- */
752
- function isNodeLike(target) {
753
- return 'nodeName' in target;
754
- }
755
-
756
- /**
757
- * Is an `EventTarget` a `Node` from another `window`?
758
- */
759
- function isFromAnotherWindow(eventTarget) {
760
- return isNodeLike(eventTarget) && eventTarget.ownerDocument !== document;
761
- }
762
-
763
- function isLeavingWindow(_ref) {
764
- var dragLeave = _ref.dragLeave;
765
- var type = dragLeave.type,
766
- relatedTarget = dragLeave.relatedTarget;
767
- if (type !== 'dragleave') {
768
- return false;
769
- }
770
- if (isSafari()) {
771
- return isLeavingWindowInSafari({
772
- dragLeave: dragLeave
773
- });
774
- }
775
-
776
- // Standard check: if going to `null` we are leaving the `window`
777
- if (relatedTarget == null) {
778
- return true;
779
- }
780
-
781
- /**
782
- * 🦊 Exception: `iframe` in Firefox (`125.0`)
783
- *
784
- * Case 1: parent `window` → child `iframe`
785
- * `dragLeave.relatedTarget` is element _inside_ the child `iframe`
786
- * (foreign element)
787
- *
788
- * Case 2: child `iframe` → parent `window`
789
- * `dragLeave.relatedTarget` is the `iframe` in the parent `window`
790
- * (foreign element)
791
- */
792
-
793
- if (isFirefox()) {
794
- return isFromAnotherWindow(relatedTarget);
795
- }
796
-
797
- /**
798
- * 🌏 Exception: `iframe` in Chrome (`124.0`)
799
- *
800
- * Case 1: parent `window` → child `iframe`
801
- * `dragLeave.relatedTarget` is the `iframe` in the parent `window`
802
- *
803
- * Case 2: child `iframe` → parent `window`
804
- * `dragLeave.relatedTarget` is `null` *(standard check)*
805
- */
806
-
807
- // Case 2
808
- // Using `instanceof` check as the element will be in the same `window`
809
- return relatedTarget instanceof HTMLIFrameElement;
810
- }
811
-
812
- function getBindingsForBrokenDrags(_ref) {
813
- var onDragEnd = _ref.onDragEnd;
814
- return [
815
- // ## Detecting drag ending for removed draggables
816
- //
817
- // If a draggable element is removed during a drag and the user drops:
818
- // 1. if over a valid drop target: we get a "drop" event to know the drag is finished
819
- // 2. if not over a valid drop target (or cancelled): we get nothing
820
- // The "dragend" event will not fire on the source draggable if it has been
821
- // removed from the DOM.
822
- // So we need to figure out if a drag operation has finished by looking at other events
823
- // We can do this by looking at other events
824
-
825
- // ### First detection: "pointermove" events
826
-
827
- // 1. "pointermove" events cannot fire during a drag and drop operation
828
- // according to the spec. So if we get a "pointermove" it means that
829
- // the drag and drop operations has finished. So if we get a "pointermove"
830
- // we know that the drag is over
831
- // 2. 🦊😤 Drag and drop operations are _supposed_ to suppress
832
- // other pointer events. However, firefox will allow a few
833
- // pointer event to get through after a drag starts.
834
- // The most I've seen is 3
835
- {
836
- type: 'pointermove',
837
- listener: function () {
838
- var callCount = 0;
839
- return function listener() {
840
- // Using 20 as it is far bigger than the most observed (3)
841
- if (callCount < 20) {
842
- callCount++;
843
- return;
844
- }
845
- onDragEnd();
846
- };
847
- }()
848
- },
849
- // ### Second detection: "pointerdown" events
850
-
851
- // If we receive this event then we know that a drag operation has finished
852
- // and potentially another one is about to start.
853
- // Note: `pointerdown` fires on all browsers / platforms before "dragstart"
854
- {
855
- type: 'pointerdown',
856
- listener: onDragEnd
857
- }];
858
- }
859
-
860
- function getInput(event) {
861
- return {
862
- altKey: event.altKey,
863
- button: event.button,
864
- buttons: event.buttons,
865
- ctrlKey: event.ctrlKey,
866
- metaKey: event.metaKey,
867
- shiftKey: event.shiftKey,
868
- clientX: event.clientX,
869
- clientY: event.clientY,
870
- pageX: event.pageX,
871
- pageY: event.pageY
872
- };
873
- }
874
-
875
- var rafSchd = function rafSchd(fn) {
876
- var lastArgs = [];
877
- var frameId = null;
878
-
879
- var wrapperFn = function wrapperFn() {
880
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
881
- args[_key] = arguments[_key];
882
- }
883
-
884
- lastArgs = args;
885
-
886
- if (frameId) {
887
- return;
888
- }
889
-
890
- frameId = requestAnimationFrame(function () {
891
- frameId = null;
892
- fn.apply(void 0, lastArgs);
893
- });
894
- };
895
-
896
- wrapperFn.cancel = function () {
897
- if (!frameId) {
898
- return;
899
- }
900
-
901
- cancelAnimationFrame(frameId);
902
- frameId = null;
903
- };
904
-
905
- return wrapperFn;
906
- };
907
-
908
- var scheduleOnDrag = rafSchd(function (fn) {
909
- return fn();
910
- });
911
- var dragStart = function () {
912
- var scheduled = null;
913
- function schedule(fn) {
914
- var frameId = requestAnimationFrame(function () {
915
- scheduled = null;
916
- fn();
917
- });
918
- scheduled = {
919
- frameId: frameId,
920
- fn: fn
921
- };
922
- }
923
- function flush() {
924
- if (scheduled) {
925
- cancelAnimationFrame(scheduled.frameId);
926
- scheduled.fn();
927
- scheduled = null;
928
- }
929
- }
930
- return {
931
- schedule: schedule,
932
- flush: flush
933
- };
934
- }();
935
- function makeDispatch(_ref) {
936
- var source = _ref.source,
937
- initial = _ref.initial,
938
- dispatchEvent = _ref.dispatchEvent;
939
- var previous = {
940
- dropTargets: []
941
- };
942
- function safeDispatch(args) {
943
- dispatchEvent(args);
944
- previous = {
945
- dropTargets: args.payload.location.current.dropTargets
946
- };
947
- }
948
- var dispatch = {
949
- start: function start(_ref2) {
950
- var nativeSetDragImage = _ref2.nativeSetDragImage;
951
- // Ensuring that both `onGenerateDragPreview` and `onDragStart` get the same location.
952
- // We do this so that `previous` is`[]` in `onDragStart` (which is logical)
953
- var location = {
954
- current: initial,
955
- previous: previous,
956
- initial: initial
957
- };
958
- // a `onGenerateDragPreview` does _not_ add another entry for `previous`
959
- // onDragPreview
960
- safeDispatch({
961
- eventName: 'onGenerateDragPreview',
962
- payload: {
963
- source: source,
964
- location: location,
965
- nativeSetDragImage: nativeSetDragImage
966
- }
967
- });
968
- dragStart.schedule(function () {
969
- safeDispatch({
970
- eventName: 'onDragStart',
971
- payload: {
972
- source: source,
973
- location: location
974
- }
975
- });
976
- });
977
- },
978
- dragUpdate: function dragUpdate(_ref3) {
979
- var current = _ref3.current;
980
- dragStart.flush();
981
- scheduleOnDrag.cancel();
982
- safeDispatch({
983
- eventName: 'onDropTargetChange',
984
- payload: {
985
- source: source,
986
- location: {
987
- initial: initial,
988
- previous: previous,
989
- current: current
990
- }
991
- }
992
- });
993
- },
994
- drag: function drag(_ref4) {
995
- var current = _ref4.current;
996
- scheduleOnDrag(function () {
997
- dragStart.flush();
998
- var location = {
999
- initial: initial,
1000
- previous: previous,
1001
- current: current
1002
- };
1003
- safeDispatch({
1004
- eventName: 'onDrag',
1005
- payload: {
1006
- source: source,
1007
- location: location
1008
- }
1009
- });
1010
- });
1011
- },
1012
- drop: function drop(_ref5) {
1013
- var current = _ref5.current,
1014
- updatedSourcePayload = _ref5.updatedSourcePayload;
1015
- dragStart.flush();
1016
- scheduleOnDrag.cancel();
1017
- safeDispatch({
1018
- eventName: 'onDrop',
1019
- payload: {
1020
- source: updatedSourcePayload !== null && updatedSourcePayload !== void 0 ? updatedSourcePayload : source,
1021
- location: {
1022
- current: current,
1023
- previous: previous,
1024
- initial: initial
1025
- }
1026
- }
1027
- });
1028
- }
1029
- };
1030
- return dispatch;
1031
- }
1032
-
1033
- var globalState = {
1034
- isActive: false
1035
- };
1036
- function canStart() {
1037
- return !globalState.isActive;
1038
- }
1039
- function getNativeSetDragImage(event) {
1040
- if (event.dataTransfer) {
1041
- // need to use `.bind` as `setDragImage` is required
1042
- // to be run with `event.dataTransfer` as the "this" context
1043
- return event.dataTransfer.setDragImage.bind(event.dataTransfer);
1044
- }
1045
- return null;
1046
- }
1047
- function hasHierarchyChanged(_ref) {
1048
- var current = _ref.current,
1049
- next = _ref.next;
1050
- if (current.length !== next.length) {
1051
- return true;
1052
- }
1053
- // not checking stickiness, data or dropEffect,
1054
- // just whether the hierarchy has changed
1055
- for (var i = 0; i < current.length; i++) {
1056
- if (current[i].element !== next[i].element) {
1057
- return true;
1058
- }
1059
- }
1060
- return false;
1061
- }
1062
- function start(_ref2) {
1063
- var event = _ref2.event,
1064
- dragType = _ref2.dragType,
1065
- getDropTargetsOver = _ref2.getDropTargetsOver,
1066
- dispatchEvent = _ref2.dispatchEvent;
1067
- if (!canStart()) {
1068
- return;
1069
- }
1070
- var initial = getStartLocation({
1071
- event: event,
1072
- dragType: dragType,
1073
- getDropTargetsOver: getDropTargetsOver
1074
- });
1075
- globalState.isActive = true;
1076
- var state = {
1077
- current: initial
1078
- };
1079
-
1080
- // Setting initial drop effect for the drag
1081
- setDropEffectOnEvent({
1082
- event: event,
1083
- current: initial.dropTargets
1084
- });
1085
- var dispatch = makeDispatch({
1086
- source: dragType.payload,
1087
- dispatchEvent: dispatchEvent,
1088
- initial: initial
1089
- });
1090
- function updateState(next) {
1091
- // only looking at whether hierarchy has changed to determine whether something as 'changed'
1092
- var hasChanged = hasHierarchyChanged({
1093
- current: state.current.dropTargets,
1094
- next: next.dropTargets
1095
- });
1096
-
1097
- // Always updating the state to include latest data, dropEffect and stickiness
1098
- // Only updating consumers if the hierarchy has changed in some way
1099
- // Consumers can get the latest data by using `onDrag`
1100
- state.current = next;
1101
- if (hasChanged) {
1102
- dispatch.dragUpdate({
1103
- current: state.current
1104
- });
1105
- }
1106
- }
1107
- function onUpdateEvent(event) {
1108
- var input = getInput(event);
1109
-
1110
- // If we are over the honey pot, we need to get the element
1111
- // that the user would have been over if not for the honey pot
1112
- var target = isHoneyPotElement(event.target) ? getElementFromPointWithoutHoneypot({
1113
- x: input.clientX,
1114
- y: input.clientY
1115
- }) : event.target;
1116
- var nextDropTargets = getDropTargetsOver({
1117
- target: target,
1118
- input: input,
1119
- source: dragType.payload,
1120
- current: state.current.dropTargets
1121
- });
1122
- if (nextDropTargets.length) {
1123
- // 🩸 must call `event.preventDefault()` to allow a browser drop to occur
1124
- event.preventDefault();
1125
- setDropEffectOnEvent({
1126
- event: event,
1127
- current: nextDropTargets
1128
- });
1129
- }
1130
- updateState({
1131
- dropTargets: nextDropTargets,
1132
- input: input
1133
- });
1134
- }
1135
- function cancel() {
1136
- // The spec behaviour is that when a drag is cancelled, or when dropping on no drop targets,
1137
- // a "dragleave" event is fired on the active drop target before a "dragend" event.
1138
- // We are replicating that behaviour in `cancel` if there are any active drop targets to
1139
- // ensure consistent behaviour.
1140
- //
1141
- // Note: When cancelling, or dropping on no drop targets, a "dragleave" event
1142
- // will have already cleared the dropTargets to `[]` (as that particular "dragleave" has a `relatedTarget` of `null`)
1143
-
1144
- if (state.current.dropTargets.length) {
1145
- updateState({
1146
- dropTargets: [],
1147
- input: state.current.input
1148
- });
1149
- }
1150
- dispatch.drop({
1151
- current: state.current,
1152
- updatedSourcePayload: null
1153
- });
1154
- finish();
1155
- }
1156
- function finish() {
1157
- globalState.isActive = false;
1158
- unbindEvents();
1159
- }
1160
- var unbindEvents = distExports.bindAll(window, [{
1161
- // 👋 Note: we are repurposing the `dragover` event as our `drag` event
1162
- // this is because firefox does not publish pointer coordinates during
1163
- // a `drag` event, but does for every other type of drag event
1164
- // `dragover` fires on all elements that are being dragged over
1165
- // Because we are binding to `window` - our `dragover` is effectively the same as a `drag`
1166
- // 🦊😤
1167
- type: 'dragover',
1168
- listener: function listener(event) {
1169
- // We need to regularly calculate the drop targets in order to allow:
1170
- // - dynamic `canDrop()` checks
1171
- // - rapid updating `getData()` calls to attach data in response to user input (eg for edge detection)
1172
- // Sadly we cannot schedule inspecting changes resulting from this event
1173
- // we need to be able to conditionally cancel the event with `event.preventDefault()`
1174
- // to enable the correct native drop experience.
1175
-
1176
- // 1. check to see if anything has changed
1177
- onUpdateEvent(event);
1178
-
1179
- // 2. let consumers know a move has occurred
1180
- // This will include the latest 'input' values
1181
- dispatch.drag({
1182
- current: state.current
1183
- });
1184
- }
1185
- }, {
1186
- type: 'dragenter',
1187
- listener: onUpdateEvent
1188
- }, {
1189
- type: 'dragleave',
1190
- listener: function listener(event) {
1191
- if (!isLeavingWindow({
1192
- dragLeave: event
1193
- })) {
1194
- return;
1195
- }
1196
-
1197
- /**
1198
- * At this point we don't know if a drag is being cancelled,
1199
- * or if a drag is leaving the `window`.
1200
- *
1201
- * Both have:
1202
- * 1. "dragleave" (with `relatedTarget: null`)
1203
- * 2. "dragend" (a "dragend" can occur when outside the `window`)
1204
- *
1205
- * **Clearing drop targets**
1206
- *
1207
- * For either case we are clearing the the drop targets
1208
- *
1209
- * - cancelling: we clear drop targets in `"dragend"` anyway
1210
- * - leaving the `window`: we clear the drop targets (to clear stickiness)
1211
- *
1212
- * **Leaving the window and finishing the drag**
1213
- *
1214
- * _internal drags_
1215
- *
1216
- * - The drag continues when the user is outside the `window`
1217
- * and can resume if the user drags back over the `window`,
1218
- * or end when the user drops in an external `window`.
1219
- * - We will get a `"dragend"`, or we can listen for other
1220
- * events to determine the drag is finished when the user re-enters the `window`).
1221
- *
1222
- * _external drags_
1223
- *
1224
- * - We conclude the drag operation.
1225
- * - We have no idea if the user will drag back over the `window`,
1226
- * or if the drag ends elsewhere.
1227
- * - We will create a new drag if the user re-enters the `window`.
1228
- *
1229
- * **Not updating `input`**
1230
- *
1231
- * 🐛 Bug[Chrome] the final `"dragleave"` has default input values (eg `clientX == 0`)
1232
- * Workaround: intentionally not updating `input` in "dragleave"
1233
- * rather than the users current input values
1234
- * - [Conversation](https://twitter.com/alexandereardon/status/1642697633864241152)
1235
- * - [Bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1429937)
1236
- **/
1237
-
1238
- updateState({
1239
- input: state.current.input,
1240
- dropTargets: []
1241
- });
1242
- if (dragType.startedFrom === 'external') {
1243
- cancel();
1244
- }
1245
- }
1246
- }, {
1247
- // A "drop" can only happen if the browser allowed the drop
1248
- type: 'drop',
1249
- listener: function listener(event) {
1250
- // Capture the final input.
1251
- // We are capturing the final `input` for the
1252
- // most accurate honey pot experience
1253
- state.current = {
1254
- dropTargets: state.current.dropTargets,
1255
- input: getInput(event)
1256
- };
1257
-
1258
- /** If there are no drop targets, then we will get
1259
- * a "drop" event if:
1260
- * - `preventUnhandled()` is being used
1261
- * - there is an unmanaged drop target (eg another library)
1262
- * In these cases, it's up to the consumer
1263
- * to handle the drop if it's not over one of our drop targets
1264
- * - `preventUnhandled()` will cancel the "drop"
1265
- * - unmanaged drop targets can handle the "drop" how they want to
1266
- * We won't call `event.preventDefault()` in this call path */
1267
-
1268
- if (!state.current.dropTargets.length) {
1269
- cancel();
1270
- return;
1271
- }
1272
- event.preventDefault();
1273
-
1274
- // applying the latest drop effect to the event
1275
- setDropEffectOnEvent({
1276
- event: event,
1277
- current: state.current.dropTargets
1278
- });
1279
- dispatch.drop({
1280
- current: state.current,
1281
- // When dropping something native, we need to extract the latest
1282
- // `.items` from the "drop" event as it is now accessible
1283
- updatedSourcePayload: dragType.type === 'external' ? dragType.getDropPayload(event) : null
1284
- });
1285
- finish();
1286
- }
1287
- }, {
1288
- // "dragend" fires when on the drag source (eg a draggable element)
1289
- // when the drag is finished.
1290
- // "dragend" will fire after "drop" (if there was a successful drop)
1291
- // "dragend" does not fire if the draggable source has been removed during the drag
1292
- // or for external drag sources (eg files)
1293
-
1294
- // This "dragend" listener will not fire if there was a successful drop
1295
- // as we will have already removed the event listener
1296
-
1297
- type: 'dragend',
1298
- listener: function listener(event) {
1299
- // In firefox, the position of the "dragend" event can
1300
- // be a bit different to the last "dragover" event.
1301
- // Updating the input so we can get the best possible
1302
- // information for the honey pot.
1303
- state.current = {
1304
- dropTargets: state.current.dropTargets,
1305
- input: getInput(event)
1306
- };
1307
- cancel();
1308
- }
1309
- }].concat(_toConsumableArray(getBindingsForBrokenDrags({
1310
- onDragEnd: cancel
1311
- }))),
1312
- // Once we have started a managed drag operation it is important that we see / own all drag events
1313
- // We got one adoption bug pop up where some code was stopping (`event.stopPropagation()`)
1314
- // all "drop" events in the bubble phase on the `document.body`.
1315
- // This meant that we never saw the "drop" event.
1316
- {
1317
- capture: true
1318
- });
1319
- dispatch.start({
1320
- nativeSetDragImage: getNativeSetDragImage(event)
1321
- });
1322
- }
1323
- function setDropEffectOnEvent(_ref3) {
1324
- var _current$;
1325
- var event = _ref3.event,
1326
- current = _ref3.current;
1327
- // setting the `dropEffect` to be the innerMost drop targets dropEffect
1328
- var innerMost = (_current$ = current[0]) === null || _current$ === void 0 ? void 0 : _current$.dropEffect;
1329
- if (innerMost != null && event.dataTransfer) {
1330
- event.dataTransfer.dropEffect = innerMost;
1331
- }
1332
- }
1333
- function getStartLocation(_ref4) {
1334
- var event = _ref4.event,
1335
- dragType = _ref4.dragType,
1336
- getDropTargetsOver = _ref4.getDropTargetsOver;
1337
- var input = getInput(event);
1338
-
1339
- // When dragging from outside of the browser,
1340
- // the drag is not being sourced from any local drop targets
1341
- if (dragType.startedFrom === 'external') {
1342
- return {
1343
- input: input,
1344
- dropTargets: []
1345
- };
1346
- }
1347
- var dropTargets = getDropTargetsOver({
1348
- input: input,
1349
- source: dragType.payload,
1350
- target: event.target,
1351
- current: []
1352
- });
1353
- return {
1354
- input: input,
1355
- dropTargets: dropTargets
1356
- };
1357
- }
1358
- var lifecycle = {
1359
- canStart: canStart,
1360
- start: start
1361
- };
1362
-
1363
- // Extending `Map` to allow us to link Key and Values together
1364
-
1365
- var ledger = new Map();
1366
- function registerUsage(_ref) {
1367
- var typeKey = _ref.typeKey,
1368
- mount = _ref.mount;
1369
- var entry = ledger.get(typeKey);
1370
- if (entry) {
1371
- entry.usageCount++;
1372
- return entry;
1373
- }
1374
- var initial = {
1375
- typeKey: typeKey,
1376
- unmount: mount(),
1377
- usageCount: 1
1378
- };
1379
- ledger.set(typeKey, initial);
1380
- return initial;
1381
- }
1382
- function register(args) {
1383
- var entry = registerUsage(args);
1384
- return function unregister() {
1385
- entry.usageCount--;
1386
- if (entry.usageCount > 0) {
1387
- return;
1388
- }
1389
- // Only a single usage left, remove it
1390
- entry.unmount();
1391
- ledger.delete(args.typeKey);
1392
- };
1393
- }
1394
-
1395
- /** Create a new combined function that will call all the provided functions */
1396
- function combine() {
1397
- for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
1398
- fns[_key] = arguments[_key];
1399
- }
1400
- return function cleanup() {
1401
- fns.forEach(function (fn) {
1402
- return fn();
1403
- });
1404
- };
1405
- }
1406
-
1407
- function addAttribute(element, _ref) {
1408
- var attribute = _ref.attribute,
1409
- value = _ref.value;
1410
- element.setAttribute(attribute, value);
1411
- return function () {
1412
- return element.removeAttribute(attribute);
1413
- };
1414
- }
1415
-
1416
- function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
1417
- function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1418
- function _createForOfIteratorHelper$1(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$1(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: true } : { done: false, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = true, u = false; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = true, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
1419
- function _unsupportedIterableToArray$1(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$1(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0; } }
1420
- function _arrayLikeToArray$1(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
1421
- function copyReverse(array) {
1422
- return array.slice(0).reverse();
1423
- }
1424
- function makeDropTarget(_ref) {
1425
- var typeKey = _ref.typeKey,
1426
- defaultDropEffect = _ref.defaultDropEffect;
1427
- var registry = new WeakMap();
1428
- var dropTargetDataAtt = "data-drop-target-for-".concat(typeKey);
1429
- var dropTargetSelector = "[".concat(dropTargetDataAtt, "]");
1430
- function addToRegistry(args) {
1431
- registry.set(args.element, args);
1432
- return function () {
1433
- return registry.delete(args.element);
1434
- };
1435
- }
1436
- function dropTargetForConsumers(args) {
1437
- var cleanup = combine(addAttribute(args.element, {
1438
- attribute: dropTargetDataAtt,
1439
- value: 'true'
1440
- }), addToRegistry(args));
1441
-
1442
- // Wrapping in `once` to prevent unexpected side effects if consumers call
1443
- // the clean up function multiple times.
1444
- return once(cleanup);
1445
- }
1446
- function getActualDropTargets(_ref2) {
1447
- var _args$getData, _args$getData2, _args$getDropEffect, _args$getDropEffect2;
1448
- var source = _ref2.source,
1449
- target = _ref2.target,
1450
- input = _ref2.input,
1451
- _ref2$result = _ref2.result,
1452
- result = _ref2$result === void 0 ? [] : _ref2$result;
1453
- if (target == null) {
1454
- return result;
1455
- }
1456
- if (!(target instanceof Element)) {
1457
- // For "text-selection" drags, the original `target`
1458
- // is not an `Element`, so we need to start looking from
1459
- // the parent element
1460
- if (target instanceof Node) {
1461
- return getActualDropTargets({
1462
- source: source,
1463
- target: target.parentElement,
1464
- input: input,
1465
- result: result
1466
- });
1467
- }
1468
-
1469
- // not sure what we are working with,
1470
- // so we can exit.
1471
- return result;
1472
- }
1473
- var closest = target.closest(dropTargetSelector);
1474
-
1475
- // Cannot find anything else
1476
- if (closest == null) {
1477
- return result;
1478
- }
1479
- var args = registry.get(closest);
1480
-
1481
- // error: something had a dropTargetSelector but we could not
1482
- // find a match. For now, failing silently
1483
- if (args == null) {
1484
- return result;
1485
- }
1486
- var feedback = {
1487
- input: input,
1488
- source: source,
1489
- element: args.element
1490
- };
1491
-
1492
- // if dropping is not allowed, skip this drop target
1493
- // and continue looking up the DOM tree
1494
- if (args.canDrop && !args.canDrop(feedback)) {
1495
- return getActualDropTargets({
1496
- source: source,
1497
- target: args.element.parentElement,
1498
- input: input,
1499
- result: result
1500
- });
1501
- }
1502
-
1503
- // calculate our new record
1504
- var data = (_args$getData = (_args$getData2 = args.getData) === null || _args$getData2 === void 0 ? void 0 : _args$getData2.call(args, feedback)) !== null && _args$getData !== void 0 ? _args$getData : {};
1505
- var dropEffect = (_args$getDropEffect = (_args$getDropEffect2 = args.getDropEffect) === null || _args$getDropEffect2 === void 0 ? void 0 : _args$getDropEffect2.call(args, feedback)) !== null && _args$getDropEffect !== void 0 ? _args$getDropEffect : defaultDropEffect;
1506
- var record = {
1507
- data: data,
1508
- element: args.element,
1509
- dropEffect: dropEffect,
1510
- // we are collecting _actual_ drop targets, so these are
1511
- // being applied _not_ due to stickiness
1512
- isActiveDueToStickiness: false
1513
- };
1514
- return getActualDropTargets({
1515
- source: source,
1516
- target: args.element.parentElement,
1517
- input: input,
1518
- // Using bubble ordering. Same ordering as `event.getPath()`
1519
- result: [].concat(_toConsumableArray(result), [record])
1520
- });
1521
- }
1522
- function notifyCurrent(_ref3) {
1523
- var eventName = _ref3.eventName,
1524
- payload = _ref3.payload;
1525
- var _iterator = _createForOfIteratorHelper$1(payload.location.current.dropTargets),
1526
- _step;
1527
- try {
1528
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1529
- var _entry$eventName;
1530
- var record = _step.value;
1531
- var entry = registry.get(record.element);
1532
- var args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
1533
- self: record
1534
- });
1535
- entry === null || entry === void 0 || (_entry$eventName = entry[eventName]) === null || _entry$eventName === void 0 || _entry$eventName.call(entry,
1536
- // I cannot seem to get the types right here.
1537
- // TS doesn't seem to like that one event can need `nativeSetDragImage`
1538
- // @ts-expect-error
1539
- args);
1540
- }
1541
- } catch (err) {
1542
- _iterator.e(err);
1543
- } finally {
1544
- _iterator.f();
1545
- }
1546
- }
1547
- var actions = {
1548
- onGenerateDragPreview: notifyCurrent,
1549
- onDrag: notifyCurrent,
1550
- onDragStart: notifyCurrent,
1551
- onDrop: notifyCurrent,
1552
- onDropTargetChange: function onDropTargetChange(_ref4) {
1553
- var payload = _ref4.payload;
1554
- var isCurrent = new Set(payload.location.current.dropTargets.map(function (record) {
1555
- return record.element;
1556
- }));
1557
- var visited = new Set();
1558
- var _iterator2 = _createForOfIteratorHelper$1(payload.location.previous.dropTargets),
1559
- _step2;
1560
- try {
1561
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1562
- var _entry$onDropTargetCh;
1563
- var record = _step2.value;
1564
- visited.add(record.element);
1565
- var entry = registry.get(record.element);
1566
- var isOver = isCurrent.has(record.element);
1567
- var args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
1568
- self: record
1569
- });
1570
- entry === null || entry === void 0 || (_entry$onDropTargetCh = entry.onDropTargetChange) === null || _entry$onDropTargetCh === void 0 || _entry$onDropTargetCh.call(entry, args);
1571
-
1572
- // if we cannot find the drop target in the current array, then it has been left
1573
- if (!isOver) {
1574
- var _entry$onDragLeave;
1575
- entry === null || entry === void 0 || (_entry$onDragLeave = entry.onDragLeave) === null || _entry$onDragLeave === void 0 || _entry$onDragLeave.call(entry, args);
1576
- }
1577
- }
1578
- } catch (err) {
1579
- _iterator2.e(err);
1580
- } finally {
1581
- _iterator2.f();
1582
- }
1583
- var _iterator3 = _createForOfIteratorHelper$1(payload.location.current.dropTargets),
1584
- _step3;
1585
- try {
1586
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1587
- var _entry$onDropTargetCh2, _entry$onDragEnter;
1588
- var _record = _step3.value;
1589
- // already published an update to this drop target
1590
- if (visited.has(_record.element)) {
1591
- continue;
1592
- }
1593
- // at this point we have a new drop target that is being entered into
1594
- var _args = _objectSpread$1(_objectSpread$1({}, payload), {}, {
1595
- self: _record
1596
- });
1597
- var _entry = registry.get(_record.element);
1598
- _entry === null || _entry === void 0 || (_entry$onDropTargetCh2 = _entry.onDropTargetChange) === null || _entry$onDropTargetCh2 === void 0 || _entry$onDropTargetCh2.call(_entry, _args);
1599
- _entry === null || _entry === void 0 || (_entry$onDragEnter = _entry.onDragEnter) === null || _entry$onDragEnter === void 0 || _entry$onDragEnter.call(_entry, _args);
1600
- }
1601
- } catch (err) {
1602
- _iterator3.e(err);
1603
- } finally {
1604
- _iterator3.f();
1605
- }
1606
- }
1607
- };
1608
- function dispatchEvent(args) {
1609
- actions[args.eventName](args);
1610
- }
1611
- function getIsOver(_ref5) {
1612
- var source = _ref5.source,
1613
- target = _ref5.target,
1614
- input = _ref5.input,
1615
- current = _ref5.current;
1616
- var actual = getActualDropTargets({
1617
- source: source,
1618
- target: target,
1619
- input: input
1620
- });
1621
-
1622
- // stickiness is only relevant when we have less
1623
- // drop targets than we did before
1624
- if (actual.length >= current.length) {
1625
- return actual;
1626
- }
1627
-
1628
- // less 'actual' drop targets than before,
1629
- // we need to see if 'stickiness' applies
1630
-
1631
- // An old drop target will continue to be dropped on if:
1632
- // 1. it has the same parent
1633
- // 2. nothing exists in it's previous index
1634
-
1635
- var lastCaptureOrdered = copyReverse(current);
1636
- var actualCaptureOrdered = copyReverse(actual);
1637
- var resultCaptureOrdered = [];
1638
- for (var index = 0; index < lastCaptureOrdered.length; index++) {
1639
- var _argsForLast$getIsSti;
1640
- var last = lastCaptureOrdered[index];
1641
- var fresh = actualCaptureOrdered[index];
1642
-
1643
- // if a record is in the new index -> use that
1644
- // it will have the latest data + dropEffect
1645
- if (fresh != null) {
1646
- resultCaptureOrdered.push(fresh);
1647
- continue;
1648
- }
1649
-
1650
- // At this point we have no drop target in the old spot
1651
- // Check to see if we can use a previous sticky drop target
1652
-
1653
- // The "parent" is the one inside of `resultCaptureOrdered`
1654
- // (the parent might be a drop target that was sticky)
1655
- var parent = resultCaptureOrdered[index - 1];
1656
- var lastParent = lastCaptureOrdered[index - 1];
1657
-
1658
- // Stickiness is based on parent relationships, so if the parent relationship has change
1659
- // then we can stop our search
1660
- if ((parent === null || parent === void 0 ? void 0 : parent.element) !== (lastParent === null || lastParent === void 0 ? void 0 : lastParent.element)) {
1661
- break;
1662
- }
1663
-
1664
- // We need to check whether the old drop target can still be dropped on
1665
-
1666
- var argsForLast = registry.get(last.element);
1667
-
1668
- // We cannot drop on a drop target that is no longer mounted
1669
- if (!argsForLast) {
1670
- break;
1671
- }
1672
- var feedback = {
1673
- input: input,
1674
- source: source,
1675
- element: argsForLast.element
1676
- };
1677
-
1678
- // We cannot drop on a drop target that no longer allows being dropped on
1679
- if (argsForLast.canDrop && !argsForLast.canDrop(feedback)) {
1680
- break;
1681
- }
1682
-
1683
- // We cannot drop on a drop target that is no longer sticky
1684
- if (!((_argsForLast$getIsSti = argsForLast.getIsSticky) !== null && _argsForLast$getIsSti !== void 0 && _argsForLast$getIsSti.call(argsForLast, feedback))) {
1685
- break;
1686
- }
1687
-
1688
- // Note: intentionally not recollecting `getData()` or `getDropEffect()`
1689
- // Previous values for `data` and `dropEffect` will be borrowed
1690
- // This is to prevent things like the 'closest edge' changing when
1691
- // no longer over a drop target.
1692
- // We could change our mind on this behaviour in the future
1693
-
1694
- resultCaptureOrdered.push(_objectSpread$1(_objectSpread$1({}, last), {}, {
1695
- // making it clear to consumers this drop target is active due to stickiness
1696
- isActiveDueToStickiness: true
1697
- }));
1698
- }
1699
-
1700
- // return bubble ordered result
1701
- return copyReverse(resultCaptureOrdered);
1702
- }
1703
- return {
1704
- dropTargetForConsumers: dropTargetForConsumers,
1705
- getIsOver: getIsOver,
1706
- dispatchEvent: dispatchEvent
1707
- };
1708
- }
1709
-
1710
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: true } : { done: false, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = true, u = false; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = true, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
1711
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
1712
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
1713
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
1714
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1715
- function makeMonitor() {
1716
- var registry = new Set();
1717
- var dragging = null;
1718
- function tryAddToActive(monitor) {
1719
- if (!dragging) {
1720
- return;
1721
- }
1722
- // Monitor is allowed to monitor events if:
1723
- // 1. It has no `canMonitor` function (default is that a monitor can listen to everything)
1724
- // 2. `canMonitor` returns true
1725
- if (!monitor.canMonitor || monitor.canMonitor(dragging.canMonitorArgs)) {
1726
- dragging.active.add(monitor);
1727
- }
1728
- }
1729
- function monitorForConsumers(args) {
1730
- // We are giving each `args` a new reference so that you
1731
- // can create multiple monitors with the same `args`.
1732
- var entry = _objectSpread({}, args);
1733
- registry.add(entry);
1734
-
1735
- // if there is an active drag we need to see if this new monitor is relevant
1736
- tryAddToActive(entry);
1737
- function cleanup() {
1738
- registry.delete(entry);
1739
-
1740
- // We need to stop publishing events during a drag to this monitor!
1741
- if (dragging) {
1742
- dragging.active.delete(entry);
1743
- }
1744
- }
1745
-
1746
- // Wrapping in `once` to prevent unexpected side effects if consumers call
1747
- // the clean up function multiple times.
1748
- return once(cleanup);
1749
- }
1750
- function dispatchEvent(_ref) {
1751
- var eventName = _ref.eventName,
1752
- payload = _ref.payload;
1753
- if (eventName === 'onGenerateDragPreview') {
1754
- dragging = {
1755
- canMonitorArgs: {
1756
- initial: payload.location.initial,
1757
- source: payload.source
1758
- },
1759
- active: new Set()
1760
- };
1761
- var _iterator = _createForOfIteratorHelper(registry),
1762
- _step;
1763
- try {
1764
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1765
- var monitor = _step.value;
1766
- tryAddToActive(monitor);
1767
- }
1768
- } catch (err) {
1769
- _iterator.e(err);
1770
- } finally {
1771
- _iterator.f();
1772
- }
1773
- }
1774
-
1775
- // This should never happen.
1776
- if (!dragging) {
1777
- return;
1778
- }
1779
-
1780
- // Creating an array from the set _before_ iterating
1781
- // This is so that monitors added during the current event will not be called.
1782
- // This behaviour matches native EventTargets where an event listener
1783
- // cannot add another event listener during an active event to the same
1784
- // event target in the same event (for us we have a single global event target)
1785
- var active = Array.from(dragging.active);
1786
- for (var _i = 0, _active = active; _i < _active.length; _i++) {
1787
- var _monitor = _active[_i];
1788
- // A monitor can be removed by another monitor during an event.
1789
- // We need to check that the monitor is still registered before calling it
1790
- if (dragging.active.has(_monitor)) {
1791
- var _monitor$eventName;
1792
- // @ts-expect-error: I cannot get this type working!
1793
- (_monitor$eventName = _monitor[eventName]) === null || _monitor$eventName === void 0 || _monitor$eventName.call(_monitor, payload);
1794
- }
1795
- }
1796
- if (eventName === 'onDrop') {
1797
- dragging.active.clear();
1798
- dragging = null;
1799
- }
1800
- }
1801
- return {
1802
- dispatchEvent: dispatchEvent,
1803
- monitorForConsumers: monitorForConsumers
1804
- };
1805
- }
1806
-
1807
- function makeAdapter(_ref) {
1808
- var typeKey = _ref.typeKey,
1809
- mount = _ref.mount,
1810
- dispatchEventToSource = _ref.dispatchEventToSource,
1811
- onPostDispatch = _ref.onPostDispatch,
1812
- defaultDropEffect = _ref.defaultDropEffect;
1813
- var monitorAPI = makeMonitor();
1814
- var dropTargetAPI = makeDropTarget({
1815
- typeKey: typeKey,
1816
- defaultDropEffect: defaultDropEffect
1817
- });
1818
- function dispatchEvent(args) {
1819
- // 1. forward the event to source
1820
- dispatchEventToSource === null || dispatchEventToSource === void 0 || dispatchEventToSource(args);
1821
-
1822
- // 2. forward the event to relevant dropTargets
1823
- dropTargetAPI.dispatchEvent(args);
1824
-
1825
- // 3. forward event to monitors
1826
- monitorAPI.dispatchEvent(args);
1827
-
1828
- // 4. post consumer dispatch (used for honey pot fix)
1829
- onPostDispatch === null || onPostDispatch === void 0 || onPostDispatch(args);
1830
- }
1831
- function start(_ref2) {
1832
- var event = _ref2.event,
1833
- dragType = _ref2.dragType;
1834
- lifecycle.start({
1835
- event: event,
1836
- dragType: dragType,
1837
- getDropTargetsOver: dropTargetAPI.getIsOver,
1838
- dispatchEvent: dispatchEvent
1839
- });
1840
- }
1841
- function registerUsage() {
1842
- function mountAdapter() {
1843
- var api = {
1844
- canStart: lifecycle.canStart,
1845
- start: start
1846
- };
1847
- return mount(api);
1848
- }
1849
- return register({
1850
- typeKey: typeKey,
1851
- mount: mountAdapter
1852
- });
1853
- }
1854
- return {
1855
- registerUsage: registerUsage,
1856
- dropTarget: dropTargetAPI.dropTargetForConsumers,
1857
- monitor: monitorAPI.monitorForConsumers
1858
- };
1859
- }
1860
-
1861
- // Using `once` as the value won't change in a browser
1862
-
1863
- var isAndroid = once(function isAndroid() {
1864
- return navigator.userAgent.toLocaleLowerCase().includes('android');
1865
- });
1866
-
1867
- // eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
1868
- var androidFallbackText = 'pdnd:android-fallback';
1869
-
1870
- // Why we put the media types in their own files:
1871
- //
1872
- // - we are not putting them all in one file as not all adapters need all types
1873
- // - we are not putting them in the external helpers as some things just need the
1874
- // types and not the external functions code
1875
- var textMediaType = 'text/plain';
1876
-
1877
- // Why we put the media types in their own files:
1878
- //
1879
- // - we are not putting them all in one file as not all adapters need all types
1880
- // - we are not putting them in the external helpers as some things just need the
1881
- // types and not the external functions code
1882
- var URLMediaType = 'text/uri-list';
1883
-
1884
- /**
1885
- * This key has been pulled into a separate module
1886
- * so that the external adapter does not need to import
1887
- * the element adapter
1888
- */
1889
- var elementAdapterNativeDataKey = 'application/vnd.pdnd';
1890
-
1891
- var draggableRegistry = new WeakMap();
1892
- function addToRegistry(args) {
1893
- draggableRegistry.set(args.element, args);
1894
- return function cleanup() {
1895
- draggableRegistry.delete(args.element);
1896
- };
1897
- }
1898
- var honeyPotFix = makeHoneyPotFix();
1899
- var adapter = makeAdapter({
1900
- typeKey: 'element',
1901
- defaultDropEffect: 'move',
1902
- mount: function mount(api) {
1903
- /** Binding event listeners the `document` rather than `window` so that
1904
- * this adapter always gets preference over the text adapter.
1905
- * `document` is the first `EventTarget` under `window`
1906
- * https://twitter.com/alexandereardon/status/1604658588311465985
1907
- */
1908
- return combine(honeyPotFix.bindEvents(), distExports.bind(document, {
1909
- type: 'dragstart',
1910
- listener: function listener(event) {
1911
- var _entry$dragHandle, _entry$getInitialData, _entry$getInitialData2, _entry$dragHandle2, _entry$getInitialData3, _entry$getInitialData4;
1912
- if (!api.canStart(event)) {
1913
- return;
1914
- }
1915
-
1916
- // If the "dragstart" event is cancelled, then a drag won't start
1917
- // There will be no further drag operation events (eg no "dragend" event)
1918
- if (event.defaultPrevented) {
1919
- return;
1920
- }
1921
-
1922
- // Technically `dataTransfer` can be `null` according to the types
1923
- // But that behaviour does not seem to appear in the spec.
1924
- // If there is not `dataTransfer`, we can assume something is wrong and not
1925
- // start a drag
1926
- if (!event.dataTransfer) {
1927
- return;
1928
- }
1929
-
1930
- // the closest parent that is a draggable element will be marked as
1931
- // the `event.target` for the event
1932
- var target = event.target;
1933
-
1934
- // this source is only for elements
1935
- // Note: only HTMLElements can have the "draggable" attribute
1936
- if (!(target instanceof HTMLElement)) {
1937
- return;
1938
- }
1939
-
1940
- // see if the thing being dragged is owned by us
1941
- var entry = draggableRegistry.get(target);
1942
-
1943
- // no matching element found
1944
- // → dragging an element with `draggable="true"` that is not controlled by us
1945
- if (!entry) {
1946
- return;
1947
- }
1948
-
1949
- /**
1950
- * A text selection drag _can_ have the `draggable` element be
1951
- * the `event.target` if the user is dragging the text selection
1952
- * from the `draggable`.
1953
- *
1954
- * To know if the `draggable` is being dragged, we look at whether any
1955
- * `"text/plain"` data is being dragged. If it is, then a text selection
1956
- * drag is occurring.
1957
- *
1958
- * This behaviour has been validated on:
1959
- *
1960
- * - Chrome@128 on Android@14
1961
- * - Chrome@128 on iOS@17.6.1
1962
- * - Chrome@128 on Windows@11
1963
- * - Chrome@128 on MacOS@14.6.1
1964
- * - Firefox@129 on Windows@11 (not possible for user to select text in a draggable)
1965
- * - Firefox@129 on MacOS@14.6.1 (not possible for user to select text in a draggable)
1966
- *
1967
- * Note: Could usually just use: `event.dataTransfer.types.includes(textMediaType)`
1968
- * but unfortunately ProseMirror is always setting `""` as the dragged text
1969
- *
1970
- * Note: Unfortunately editor is (heavily) leaning on the current functionality today
1971
- * and unwinding it will be a decent amount of effort. So for now, a text selection
1972
- * where the `event.target` is a `draggable` element will still trigger the
1973
- * element adapter.
1974
- *
1975
- * // Future state:
1976
- * if(event.dataTransfer.getData(textMediaType)) {
1977
- * return;
1978
- * }
1979
- *
1980
- */
1981
-
1982
- var input = getInput(event);
1983
- var feedback = {
1984
- element: entry.element,
1985
- dragHandle: (_entry$dragHandle = entry.dragHandle) !== null && _entry$dragHandle !== void 0 ? _entry$dragHandle : null,
1986
- input: input
1987
- };
1988
-
1989
- // Check: does the draggable want to allow dragging?
1990
- if (entry.canDrag && !entry.canDrag(feedback)) {
1991
- // cancel drag operation if we cannot drag
1992
- event.preventDefault();
1993
- return;
1994
- }
1995
-
1996
- // Check: is there a drag handle and is the user using it?
1997
- if (entry.dragHandle) {
1998
- // technically don't need this util, but just being
1999
- // consistent with how we look up what is under the users
2000
- // cursor.
2001
- var over = getElementFromPointWithoutHoneypot({
2002
- x: input.clientX,
2003
- y: input.clientY
2004
- });
2005
-
2006
- // if we are not dragging from the drag handle (or something inside the drag handle)
2007
- // then we will cancel the active drag
2008
- if (!entry.dragHandle.contains(over)) {
2009
- event.preventDefault();
2010
- return;
2011
- }
2012
- }
2013
-
2014
- /**
2015
- * **Goal**
2016
- * Pass information to other applications
2017
- *
2018
- * **Approach**
2019
- * Put data into the native data store
2020
- *
2021
- * **What about the native adapter?**
2022
- * When the element adapter puts native data into the native data store
2023
- * the native adapter is not triggered in the current window,
2024
- * but a native adapter in an external window _can_ be triggered
2025
- *
2026
- * **Why bake this into core?**
2027
- * This functionality could be pulled out and exposed inside of
2028
- * `onGenerateDragPreview`. But decided to make it a part of the
2029
- * base API as it felt like a common enough use case and ended
2030
- * up being a similar amount of code to include this function as
2031
- * it was to expose the hook for it
2032
- */
2033
- var nativeData = (_entry$getInitialData = (_entry$getInitialData2 = entry.getInitialDataForExternal) === null || _entry$getInitialData2 === void 0 ? void 0 : _entry$getInitialData2.call(entry, feedback)) !== null && _entry$getInitialData !== void 0 ? _entry$getInitialData : null;
2034
- if (nativeData) {
2035
- for (var _i = 0, _Object$entries = Object.entries(nativeData); _i < _Object$entries.length; _i++) {
2036
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
2037
- key = _Object$entries$_i[0],
2038
- data = _Object$entries$_i[1];
2039
- event.dataTransfer.setData(key, data !== null && data !== void 0 ? data : '');
2040
- }
2041
- }
2042
-
2043
- /**
2044
- * 📱 For Android devices, a drag operation will not start unless
2045
- * "text/plain" or "text/uri-list" data exists in the native data store
2046
- * https://twitter.com/alexandereardon/status/1732189803754713424
2047
- *
2048
- * Tested on:
2049
- * Device: Google Pixel 5
2050
- * Android version: 14 (November 5, 2023)
2051
- * Chrome version: 120.0
2052
- */
2053
- if (isAndroid() && !event.dataTransfer.types.includes(textMediaType) && !event.dataTransfer.types.includes(URLMediaType)) {
2054
- event.dataTransfer.setData(textMediaType, androidFallbackText);
2055
- }
2056
-
2057
- /**
2058
- * 1. Must set any media type for `iOS15` to work
2059
- * 2. We are also doing adding data so that the native adapter
2060
- * can know that the element adapter has handled this drag
2061
- *
2062
- * We used to wrap this `setData()` in a `try/catch` for Firefox,
2063
- * but it looks like that was not needed.
2064
- *
2065
- * Tested using: https://codesandbox.io/s/checking-firefox-throw-behaviour-on-dragstart-qt8h4f
2066
- *
2067
- * - ✅ Firefox@70.0 (Oct 2019) on macOS Sonoma
2068
- * - ✅ Firefox@70.0 (Oct 2019) on macOS Big Sur
2069
- * - ✅ Firefox@70.0 (Oct 2019) on Windows 10
2070
- *
2071
- * // just checking a few more combinations to be super safe
2072
- *
2073
- * - ✅ Chrome@78 (Oct 2019) on macOS Big Sur
2074
- * - ✅ Chrome@78 (Oct 2019) on Windows 10
2075
- * - ✅ Safari@14.1 on macOS Big Sur
2076
- */
2077
- event.dataTransfer.setData(elementAdapterNativeDataKey, '');
2078
- var payload = {
2079
- element: entry.element,
2080
- dragHandle: (_entry$dragHandle2 = entry.dragHandle) !== null && _entry$dragHandle2 !== void 0 ? _entry$dragHandle2 : null,
2081
- data: (_entry$getInitialData3 = (_entry$getInitialData4 = entry.getInitialData) === null || _entry$getInitialData4 === void 0 ? void 0 : _entry$getInitialData4.call(entry, feedback)) !== null && _entry$getInitialData3 !== void 0 ? _entry$getInitialData3 : {}
2082
- };
2083
- var dragType = {
2084
- type: 'element',
2085
- payload: payload,
2086
- startedFrom: 'internal'
2087
- };
2088
- api.start({
2089
- event: event,
2090
- dragType: dragType
2091
- });
2092
- }
2093
- }));
2094
- },
2095
- dispatchEventToSource: function dispatchEventToSource(_ref) {
2096
- var _draggableRegistry$ge, _draggableRegistry$ge2;
2097
- var eventName = _ref.eventName,
2098
- payload = _ref.payload;
2099
- // During a drag operation, a draggable can be:
2100
- // - remounted with different functions
2101
- // - removed completely
2102
- // So we need to get the latest entry from the registry in order
2103
- // to call the latest event functions
2104
-
2105
- (_draggableRegistry$ge = draggableRegistry.get(payload.source.element)) === null || _draggableRegistry$ge === void 0 || (_draggableRegistry$ge2 = _draggableRegistry$ge[eventName]) === null || _draggableRegistry$ge2 === void 0 || _draggableRegistry$ge2.call(_draggableRegistry$ge,
2106
- // I cannot seem to get the types right here.
2107
- // TS doesn't seem to like that one event can need `nativeSetDragImage`
2108
- // @ts-expect-error
2109
- payload);
2110
- },
2111
- onPostDispatch: honeyPotFix.getOnPostDispatch()
2112
- });
2113
- var dropTargetForElements = adapter.dropTarget;
2114
-
2115
- // eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
2116
- function draggable(args) {
2117
- var cleanup = combine(
2118
- // making the draggable register the adapter rather than drop targets
2119
- // this is because you *must* have a draggable element to start a drag
2120
- // but you _might_ not have any drop targets immediately
2121
- // (You might create drop targets async)
2122
- adapter.registerUsage(), addToRegistry(args), addAttribute(args.element, {
2123
- attribute: 'draggable',
2124
- value: 'true'
2125
- }));
2126
-
2127
- // Wrapping in `once` to prevent unexpected side effects if consumers call
2128
- // the clean up function multiple times.
2129
- return once(cleanup);
2130
- }
2131
-
2132
- /** Common event payload for all events */
2133
-
2134
- /** A map containing payloads for all events */
2135
-
2136
- /** Common event payload for all drop target events */
2137
-
2138
- /** A map containing payloads for all events on drop targets */
2139
-
2140
- /** Arguments given to all feedback functions (eg `canDrag()`) on for a `draggable()` */
2141
-
2142
- /** Arguments given to all feedback functions (eg `canDrop()`) on a `dropTargetForElements()` */
2143
-
2144
- /** Arguments given to all monitor feedback functions (eg `canMonitor()`) for a `monitorForElements` */
2145
-
2146
- function toBrickDropDetail(data, parentPath, index) {
2147
- if (data.kind === 'new-brick') {
2148
- const mold = getBrickMolds().find((candidate) => candidate.type === data.moldType &&
2149
- candidate.id === data.moldId);
2150
- if (!mold)
2151
- return undefined;
2152
- return { source: 'new', mold, parentPath, index };
2153
- }
2154
- if (data.kind === 'move-brick') {
2155
- return { source: 'move', from: data.path, parentPath, index };
2156
- }
2157
- return undefined;
2158
- }
2159
-
2160
- const fkBrickActionsCss = () => `.fk-actions.sc-fk-brick-actions{position:relative;padding:calc(var(--fk-spacing) / 2);border:1px solid transparent;border-radius:var(--fk-radius)}.fk-actions.sc-fk-brick-actions:hover{border-color:var(--fk-color-border)}.fk-actions--selected.sc-fk-brick-actions,.fk-actions--selected.sc-fk-brick-actions:hover{border-color:var(--fk-color-primary);box-shadow:0 0 0 2px color-mix(in srgb, var(--fk-color-primary) 20%, transparent)}.fk-actions--dragging.sc-fk-brick-actions{opacity:0.5}.fk-actions--drop-before.sc-fk-brick-actions::before{content:'';position:absolute;top:-2px;left:0;right:0;height:3px;border-radius:2px;background:var(--fk-color-primary)}.fk-actions__toolbar.sc-fk-brick-actions{position:absolute;top:calc(var(--fk-spacing) / -2);right:var(--fk-spacing);z-index:1;display:none;gap:2px;padding:2px;border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:var(--fk-color-surface);box-shadow:0 2px 6px var(--fk-color-shadow)}.fk-actions.sc-fk-brick-actions:hover>.fk-actions__toolbar.sc-fk-brick-actions{display:flex}.fk-actions__button.sc-fk-brick-actions{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;border-radius:calc(var(--fk-radius) / 2);background:transparent;color:var(--fk-color-muted);font-size:0.8rem;cursor:pointer}.fk-actions__button.sc-fk-brick-actions:hover{background:color-mix(in srgb, var(--fk-color-primary) 12%, transparent);color:var(--fk-color-primary)}.fk-actions__button--danger.sc-fk-brick-actions:hover{background:color-mix(in srgb, var(--fk-color-danger) 12%, transparent);color:var(--fk-color-danger)}.fk-actions__handle.sc-fk-brick-actions{cursor:grab}`;
2161
-
2162
- const FkBrickActions = class {
2163
- constructor(hostRef) {
2164
- registerInstance(this, hostRef);
2165
- this.brickRemove = createEvent(this, "brickRemove");
2166
- this.brickDuplicate = createEvent(this, "brickDuplicate");
2167
- this.brickDrop = createEvent(this, "brickDrop");
2168
- this.brickSelect = createEvent(this, "brickSelect");
2169
- this.selected = false;
2170
- this.isDragging = false;
2171
- this.isDropTarget = false;
2172
- this.cleanups = [];
2173
- }
2174
- componentDidLoad() {
2175
- if (this.handleEl) {
2176
- this.cleanups.push(draggable({
2177
- element: this.handleEl,
2178
- getInitialData: () => ({ kind: 'move-brick', path: this.path }),
2179
- onDragStart: () => (this.isDragging = true),
2180
- onDrop: () => (this.isDragging = false),
2181
- }));
2182
- }
2183
- this.cleanups.push(dropTargetForElements({
2184
- element: this.host,
2185
- onDrag: ({ location }) => {
2186
- var _a;
2187
- return (this.isDropTarget =
2188
- ((_a = location.current.dropTargets[0]) === null || _a === void 0 ? void 0 : _a.element) === this.host);
2189
- },
2190
- onDragLeave: () => (this.isDropTarget = false),
2191
- onDrop: ({ source, location }) => {
2192
- var _a;
2193
- this.isDropTarget = false;
2194
- if (((_a = location.current.dropTargets[0]) === null || _a === void 0 ? void 0 : _a.element) !== this.host)
2195
- return;
2196
- const segments = this.path.split('.');
2197
- const detail = toBrickDropDetail(source.data, segments.slice(0, -1).join('.'), Number(segments[segments.length - 1]));
2198
- if (detail)
2199
- this.brickDrop.emit(detail);
2200
- },
2201
- }));
2202
- }
2203
- disconnectedCallback() {
2204
- this.cleanups.forEach((cleanup) => cleanup());
2205
- this.cleanups = [];
2206
- }
2207
- render() {
2208
- return (h("div", { key: 'ea1cc1c7af646f403330c98b251714f3968c1aae', class: {
2209
- 'fk-actions': true,
2210
- 'fk-actions--dragging': this.isDragging,
2211
- 'fk-actions--drop-before': this.isDropTarget,
2212
- 'fk-actions--selected': this.selected,
2213
- }, onClick: (event) => {
2214
- event.stopPropagation();
2215
- this.brickSelect.emit({ path: this.path });
2216
- } }, h("div", { key: '99c08de8c78ff6362103f9e355ff6aa3da1367ee', class: "fk-actions__toolbar" }, h("button", { key: '8702b1f565ea639585614d4c6e88b2dc44c7ed7c', type: "button", class: "fk-actions__button fk-actions__handle", ref: (el) => (this.handleEl = el), title: fkT('actions.move') }, "\u283F"), h("button", { key: '7394adc36780dbd61195b69cd21fce3c8a852f2a', type: "button", class: "fk-actions__button", title: fkT('actions.duplicate'), onClick: (event) => {
2217
- event.stopPropagation();
2218
- this.brickDuplicate.emit({ path: this.path });
2219
- } }, "\u29C9"), h("button", { key: 'ddea0decbc02a4b0627170c973ed19180aa6f651', type: "button", class: "fk-actions__button fk-actions__button--danger", title: fkT('actions.delete'), onClick: (event) => {
2220
- event.stopPropagation();
2221
- this.brickRemove.emit({ path: this.path });
2222
- } }, "\u2715")), h("slot", { key: '44fa7c12a7581ff6b62f29fb1249d427594b5e1f' })));
2223
- }
2224
- get host() { return getElement(this); }
2225
- };
2226
- FkBrickActions.style = fkBrickActionsCss();
2227
-
2228
- const fkBrickListCss = () => `.fk-palette.sc-fk-brick-list{display:flex;flex-direction:column;gap:var(--fk-spacing);font-family:var(--fk-font)}.fk-palette__search.sc-fk-brick-list{font:inherit;font-size:0.85rem;padding:calc(var(--fk-spacing) / 1.5) var(--fk-spacing);border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 1.5);background:var(--fk-color-surface);color:var(--fk-color-text)}.fk-palette__search.sc-fk-brick-list:focus{outline:none;border-color:var(--fk-color-primary);box-shadow:0 0 0 2px color-mix(in srgb, var(--fk-color-primary) 20%, transparent)}.fk-palette__category.sc-fk-brick-list{display:flex;align-items:center;gap:calc(var(--fk-spacing) / 2);width:100%;margin:0 0 calc(var(--fk-spacing) / 2);padding:calc(var(--fk-spacing) / 2) 0;border:none;background:transparent;font:inherit;font-size:0.7rem;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;color:var(--fk-color-muted);cursor:pointer}.fk-palette__category.sc-fk-brick-list:hover{color:var(--fk-color-text)}.fk-palette__chevron.sc-fk-brick-list{display:inline-block;transition:transform 120ms ease}.fk-palette__chevron--collapsed.sc-fk-brick-list{transform:rotate(-90deg)}.fk-palette__count.sc-fk-brick-list{margin-left:auto;font-weight:600;color:var(--fk-color-muted)}.fk-palette__items.sc-fk-brick-list{display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:calc(var(--fk-spacing) / 2)}.fk-palette__empty.sc-fk-brick-list{margin:0;font-size:0.8rem;color:var(--fk-color-muted)}`;
2229
-
2230
- const FkBrickList = class {
2231
- constructor(hostRef) {
2232
- registerInstance(this, hostRef);
2233
- this.query = '';
2234
- this.collapsed = {};
2235
- }
2236
- toggle(category) {
2237
- this.collapsed = Object.assign(Object.assign({}, this.collapsed), { [category]: !this.collapsed[category] });
2238
- }
2239
- render() {
2240
- const grouped = getBrickMoldsGroupedByCategory();
2241
- const query = this.query.trim().toLowerCase();
2242
- const filtered = Object.entries(grouped)
2243
- .map(([category, molds]) => ({
2244
- category,
2245
- molds: query
2246
- ? molds.filter((mold) => [
2247
- mold.name,
2248
- fkTOr(`brick.${mold.id}.name`, mold.name),
2249
- mold.id,
2250
- category,
2251
- fkTOr(`category.${category}`, category),
2252
- ].some((candidate) => candidate.toLowerCase().includes(query)))
2253
- : molds,
2254
- }))
2255
- .filter((group) => group.molds.length > 0);
2256
- return (h(Host, { key: '93facfae49363bb2fe1ceeb5ab84105fc5f339fa' }, h("div", { key: 'dc68df2c48929c7e5d6c4037b755761f0f581898', class: "fk-palette" }, h("input", { key: '6acf14db7433b4a4bfb4cca2ca0fd51465785d7f', class: "fk-palette__search", type: "search", placeholder: fkT('palette.search'), value: this.query, onInput: (event) => (this.query = event.target.value) }), filtered.map(({ category, molds }) => {
2257
- const isCollapsed = !query && this.collapsed[category];
2258
- return (h("section", { class: "fk-palette__group", key: category }, h("button", { type: "button", class: "fk-palette__category", onClick: () => this.toggle(category) }, h("span", { class: {
2259
- 'fk-palette__chevron': true,
2260
- 'fk-palette__chevron--collapsed': isCollapsed,
2261
- } }, "\u25BE"), fkTOr(`category.${category}`, category), h("span", { class: "fk-palette__count" }, molds.length)), !isCollapsed ? (h("div", { class: "fk-palette__items" }, molds.map((mold) => (h("fk-brick-mold-item", { brickMold: mold, key: `${mold.type}:${mold.id}` }))))) : null));
2262
- }), filtered.length === 0 ? (h("p", { class: "fk-palette__empty" }, fkT('palette.empty', { query: this.query }))) : null)));
2263
- }
2264
- };
2265
- FkBrickList.style = fkBrickListCss();
2266
-
2267
- const fkBrickMoldItemCss = () => `.sc-fk-brick-mold-item-h{display:block;cursor:grab;min-width:0}.fk-mold.sc-fk-brick-mold-item{display:flex;align-items:center;padding:calc(var(--fk-spacing) / 1.5) var(--fk-spacing);border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 1.5);background:var(--fk-color-surface);font-size:0.8rem;transition:border-color 120ms ease, box-shadow 120ms ease}.fk-mold.sc-fk-brick-mold-item:hover{border-color:var(--fk-color-primary);box-shadow:0 1px 4px var(--fk-color-shadow)}.fk-mold--dragging.sc-fk-brick-mold-item{opacity:0.5}.fk-mold__name.sc-fk-brick-mold-item{font-weight:500;color:var(--fk-color-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}`;
2268
-
2269
- const FkBrickMoldItem = class {
2270
- constructor(hostRef) {
2271
- registerInstance(this, hostRef);
2272
- this.isDragging = false;
2273
- }
2274
- componentDidLoad() {
2275
- this.cleanup = draggable({
2276
- element: this.host,
2277
- getInitialData: () => ({
2278
- kind: 'new-brick',
2279
- moldType: this.brickMold.type,
2280
- moldId: this.brickMold.id,
2281
- }),
2282
- onDragStart: () => (this.isDragging = true),
2283
- onDrop: () => (this.isDragging = false),
2284
- });
2285
- }
2286
- disconnectedCallback() {
2287
- var _a;
2288
- (_a = this.cleanup) === null || _a === void 0 ? void 0 : _a.call(this);
2289
- }
2290
- render() {
2291
- return (h("div", { key: '0570015fb47b6be613f900a333b061537006edec', class: { 'fk-mold': true, 'fk-mold--dragging': this.isDragging }, title: fkTOr(`brick.${this.brickMold.id}.name`, this.brickMold.name) }, h("span", { key: 'bf3ab329f7a4b054c56e042dd83822706546c93b', class: "fk-mold__name" }, fkTOr(`brick.${this.brickMold.id}.name`, this.brickMold.name))));
2292
- }
2293
- get host() { return getElement(this); }
2294
- };
2295
- FkBrickMoldItem.style = fkBrickMoldItemCss();
2296
-
2297
- const fkBrickNotFoundCss = () => `.fk-not-found.sc-fk-brick-not-found{margin:0;padding:calc(var(--fk-spacing) * 1.5);border:1px dashed var(--fk-color-danger);border-radius:var(--fk-radius);color:var(--fk-color-danger);font-size:0.875rem}`;
2298
-
2299
- const FkBrickNotFound = class {
2300
- constructor(hostRef) {
2301
- registerInstance(this, hostRef);
2302
- }
2303
- render() {
2304
- return (h(Host, { key: '558231ac77ac07f7b40bd08081a498dc5623442c' }, h("p", { key: 'f1ca1f59750c6ed2b1a3c2e22bd6f7f1dc721496', class: "fk-not-found" }, "Brick ", h("slot", { key: '0003d9dcc23c52cb8d466d794eafd4dd6be4b708' }), " not found")));
2305
- }
2306
- };
2307
- FkBrickNotFound.style = fkBrickNotFoundCss();
2308
-
2309
- function getBrickData(brickSpec, data) {
2310
- var _a;
2311
- if (!((_a = brickSpec.configs) === null || _a === void 0 ? void 0 : _a.key) || !data)
2312
- return undefined;
2313
- if (brickSpec.unWrapData)
2314
- return data;
2315
- return data[brickSpec.configs.key];
2316
- }
2317
- function wrapBrickData(brickSpec, value) {
2318
- var _a;
2319
- if (!((_a = brickSpec.configs) === null || _a === void 0 ? void 0 : _a.key))
2320
- return undefined;
2321
- if (brickSpec.unWrapData)
2322
- return value;
2323
- return { [brickSpec.configs.key]: value };
2324
- }
2325
-
2326
- const FkBrickRender = class {
2327
- constructor(hostRef) {
2328
- registerInstance(this, hostRef);
2329
- this.brickDataChange = createEvent(this, "brickDataChange");
2330
- this.brickConfigsChange = createEvent(this, "brickConfigsChange");
2331
- this.brickStylesChange = createEvent(this, "brickStylesChange");
2332
- this.brickValidationsChange = createEvent(this, "brickValidationsChange");
2333
- this.brickRulesChange = createEvent(this, "brickRulesChange");
2334
- this.brickRemove = createEvent(this, "brickRemove");
2335
- this.brickDuplicate = createEvent(this, "brickDuplicate");
2336
- this.path = '0';
2337
- this.editable = false;
2338
- this.errors = {};
2339
- }
2340
- render() {
2341
- var _a, _b, _c, _d, _e, _f;
2342
- const spec = this.brickSpec;
2343
- if (!spec)
2344
- return null;
2345
- const brick = getBrick(spec.type, spec.id);
2346
- if (!brick) {
2347
- return h("fk-brick-not-found", null, `${spec.type}:${spec.id}`);
2348
- }
2349
- const editing = this.editable && ((_a = spec.editable) !== null && _a !== void 0 ? _a : true);
2350
- const affected = getAffectedProperties(spec.rules, this.dataMap);
2351
- if (!editing && affected.hidden === true)
2352
- return null;
2353
- const isContainer = spec.type === 'panel' || spec.type === 'collection';
2354
- const uid = (_b = spec.configs) === null || _b === void 0 ? void 0 : _b.uid;
2355
- const childNodes = ((_c = spec.children) !== null && _c !== void 0 ? _c : []).map((childSpec, index) => {
2356
- var _a;
2357
- return (h("fk-brick-render", { brickSpec: childSpec, rootSpec: (_a = this.rootSpec) !== null && _a !== void 0 ? _a : this.brickSpec, data: this.data, dataMap: this.dataMap, errors: this.errors, locale: this.locale, path: `${this.path}.${index}`, editable: this.editable, selectedUid: this.selectedUid, utils: this.utils }));
2358
- });
2359
- if (editing && isContainer) {
2360
- childNodes.push(h("fk-drop-area", { path: this.path }));
2361
- }
2362
- const props = {
2363
- brickSpec: spec,
2364
- configsForm: spec.configsForm,
2365
- configs: resolveLocalizedRecord(spec.configs, this.locale),
2366
- locale: this.locale,
2367
- styles: (_d = spec.styles) !== null && _d !== void 0 ? _d : {},
2368
- data: getBrickData(spec, this.data),
2369
- dataMap: this.dataMap,
2370
- rootSpec: (_e = this.rootSpec) !== null && _e !== void 0 ? _e : this.brickSpec,
2371
- error: ((_f = spec.configs) === null || _f === void 0 ? void 0 : _f.key) ? this.errors[spec.configs.key] : undefined,
2372
- disabled: editing ? false : affected.disabled === true,
2373
- path: this.path,
2374
- editable: editing,
2375
- children: childNodes,
2376
- validations: spec.validations,
2377
- rules: spec.rules,
2378
- utils: this.utils,
2379
- onDataChange: (value) => {
2380
- const wrapped = wrapBrickData(spec, value);
2381
- if (wrapped !== undefined)
2382
- this.brickDataChange.emit(wrapped);
2383
- },
2384
- onConfigsChange: (configs, changedUid) => this.brickConfigsChange.emit({ configs, uid: changedUid !== null && changedUid !== void 0 ? changedUid : uid }),
2385
- onStylesChange: (styles, changedUid) => this.brickStylesChange.emit({
2386
- styles: styles,
2387
- uid: changedUid !== null && changedUid !== void 0 ? changedUid : uid,
2388
- }),
2389
- onValidationsChange: (validations, changedUid) => this.brickValidationsChange.emit({ validations, uid: changedUid !== null && changedUid !== void 0 ? changedUid : uid }),
2390
- onRulesChange: (rules, changedUid) => this.brickRulesChange.emit({ rules, uid: changedUid !== null && changedUid !== void 0 ? changedUid : uid }),
2391
- onDelete: (path) => this.brickRemove.emit({ path }),
2392
- onDuplicate: (path) => this.brickDuplicate.emit({ path }),
2393
- };
2394
- const node = (editing ? brick.renderBuilder(props) : brick.render(props));
2395
- if (!editing || this.path === '0')
2396
- return node;
2397
- return (h("fk-brick-actions", { path: this.path, selected: uid !== undefined && uid === this.selectedUid }, node));
2398
- }
2399
- };
2400
-
2401
- const fkCodeEditorCss = () => `.sc-fk-code-editor-h{display:block}.sc-fk-code-editor-h .cm-editor.sc-fk-code-editor{min-height:88px;font-size:0.75rem;border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:var(--fk-color-surface)}.sc-fk-code-editor-h .cm-editor.cm-focused.sc-fk-code-editor{outline:none;border-color:var(--fk-color-primary)}.sc-fk-code-editor-h .cm-gutters.sc-fk-code-editor{border-right:1px solid var(--fk-color-border);background:color-mix(in srgb, var(--fk-color-surface) 70%, transparent);color:var(--fk-color-muted)}.sc-fk-code-editor-h .cm-content.sc-fk-code-editor{font-family:ui-monospace, SFMono-Regular, Menlo, monospace}`;
2402
-
2403
- const fetchCodeMirror = () => Promise.all([
2404
- import('./index-DtcM1yw5.js'),
2405
- import('./index-DuVf3NlP.js').then(function (n) { return n.i; }),
2406
- import('./index-CGMDfZ5m.js'),
2407
- import('./index-BAcz7b5u.js').then(function (n) { return n.v; }),
2408
- import('./index-BkRMoLXK.js'),
2409
- ]);
2410
- let codeMirrorModules;
2411
- const loadCodeMirror = () => (codeMirrorModules !== null && codeMirrorModules !== void 0 ? codeMirrorModules : (codeMirrorModules = fetchCodeMirror()));
2412
- const FkCodeEditor = class {
2413
- constructor(hostRef) {
2414
- registerInstance(this, hostRef);
2415
- this.codeChange = createEvent(this, "codeChange");
2416
- this.value = '';
2417
- this.placeholder = '';
2418
- this.disconnected = false;
2419
- }
2420
- async componentDidLoad() {
2421
- const [{ EditorState }, { EditorView: View, keymap, lineNumbers, placeholder: cmPlaceholder }, { defaultKeymap, history, historyKeymap }, { defaultHighlightStyle, syntaxHighlighting }, { javascript },] = await loadCodeMirror();
2422
- if (this.disconnected)
2423
- return;
2424
- this.view = new View({
2425
- parent: this.host,
2426
- state: EditorState.create({
2427
- doc: this.value,
2428
- extensions: [
2429
- lineNumbers(),
2430
- history(),
2431
- keymap.of([...defaultKeymap, ...historyKeymap]),
2432
- javascript(),
2433
- syntaxHighlighting(defaultHighlightStyle),
2434
- cmPlaceholder(this.placeholder),
2435
- View.domEventHandlers({
2436
- blur: () => this.emitIfChanged(),
2437
- }),
2438
- ],
2439
- }),
2440
- });
2441
- }
2442
- syncValue(next) {
2443
- if (!this.view || this.view.hasFocus)
2444
- return;
2445
- const current = this.view.state.doc.toString();
2446
- if (current !== next) {
2447
- this.view.dispatch({
2448
- changes: { from: 0, to: current.length, insert: next },
2449
- });
2450
- }
2451
- }
2452
- emitIfChanged() {
2453
- if (!this.view)
2454
- return;
2455
- const doc = this.view.state.doc.toString();
2456
- if (doc !== this.value)
2457
- this.codeChange.emit(doc);
2458
- }
2459
- disconnectedCallback() {
2460
- var _a;
2461
- this.disconnected = true;
2462
- (_a = this.view) === null || _a === void 0 ? void 0 : _a.destroy();
2463
- this.view = undefined;
2464
- }
2465
- render() {
2466
- return null;
2467
- }
2468
- get host() { return getElement(this); }
2469
- static get watchers() { return {
2470
- "value": [{
2471
- "syncValue": 0
2472
- }]
2473
- }; }
2474
- };
2475
- FkCodeEditor.style = fkCodeEditorCss();
2476
-
2477
- const fkDataGridCss = () => `.sc-fk-data-grid-h{display:block}.fk-grid.sc-fk-data-grid{display:flex;flex-direction:column;gap:var(--fk-spacing)}.fk-grid__empty.sc-fk-data-grid{margin:0;padding:var(--fk-spacing);border:1px dashed var(--fk-color-border);border-radius:var(--fk-radius);font-size:0.85rem;color:var(--fk-color-muted);text-align:center}.fk-grid__row.sc-fk-data-grid{display:flex;align-items:flex-start;gap:var(--fk-spacing);padding:var(--fk-spacing);border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:color-mix(in srgb, var(--fk-color-surface) 60%, transparent)}.fk-grid__cells.sc-fk-data-grid{display:flex;flex:1;flex-wrap:wrap;gap:var(--fk-spacing);min-width:0}.fk-grid__cells.sc-fk-data-grid>*.sc-fk-data-grid{flex:1;min-width:160px}.fk-grid__remove.sc-fk-data-grid{border:none;background:transparent;color:var(--fk-color-muted);font-size:0.8rem;cursor:pointer;padding:4px 6px;border-radius:calc(var(--fk-radius) / 2)}.fk-grid__remove.sc-fk-data-grid:hover:not(:disabled){color:var(--fk-color-danger);background:color-mix(in srgb, var(--fk-color-danger) 10%, transparent)}.fk-grid__add.sc-fk-data-grid{align-self:flex-start;font:inherit;font-size:0.8rem;font-weight:600;padding:calc(var(--fk-spacing) / 1.5) var(--fk-spacing);border:1px dashed var(--fk-color-border);border-radius:var(--fk-radius);background:transparent;color:var(--fk-color-muted);cursor:pointer}.fk-grid__add.sc-fk-data-grid:hover:not(:disabled){border-color:var(--fk-color-primary);color:var(--fk-color-primary)}`;
2478
-
2479
- const FkDataGrid = class {
2480
- constructor(hostRef) {
2481
- registerInstance(this, hostRef);
2482
- this.gridValueChange = createEvent(this, "gridValueChange");
2483
- this.disabled = false;
2484
- this.touched = {};
2485
- this.addRow = (event) => {
2486
- event.preventDefault();
2487
- this.gridValueChange.emit([...this.rows(), {}]);
2488
- };
2489
- }
2490
- rows() {
2491
- return Array.isArray(this.value)
2492
- ? this.value
2493
- : [];
2494
- }
2495
- rowSpec() {
2496
- var _a, _b;
2497
- if (((_a = this.rowSpecCache) === null || _a === void 0 ? void 0 : _a.source) !== this.spec) {
2498
- this.rowSpecCache = {
2499
- source: this.spec,
2500
- rowSpec: {
2501
- type: 'panel',
2502
- id: 'grid-row',
2503
- name: 'Row',
2504
- configs: { key: 'row' },
2505
- children: (_b = this.spec.children) !== null && _b !== void 0 ? _b : [],
2506
- },
2507
- };
2508
- }
2509
- return this.rowSpecCache.rowSpec;
2510
- }
2511
- rowErrors(row) {
2512
- const present = Object.fromEntries(Object.entries(row).filter(([, value]) => value !== '' && value !== null && value !== undefined));
2513
- return validateBrickSpecDataDetailed(this.rowSpec(), present, this.locale)
2514
- .errors;
2515
- }
2516
- visibleRowErrors(index) {
2517
- var _a, _b;
2518
- const row = (_a = this.rows()[index]) !== null && _a !== void 0 ? _a : {};
2519
- const touched = (_b = this.touched[index]) !== null && _b !== void 0 ? _b : {};
2520
- const errors = {};
2521
- for (const [key, message] of Object.entries(this.rowErrors(row))) {
2522
- if (touched[key])
2523
- errors[key] = message;
2524
- }
2525
- return errors;
2526
- }
2527
- handleRowChange(event) {
2528
- var _a, _b;
2529
- event.stopPropagation();
2530
- const origin = event.target;
2531
- const rowEl = origin.closest('[data-grid-row]');
2532
- const index = Number((_a = rowEl === null || rowEl === void 0 ? void 0 : rowEl.getAttribute('data-grid-row')) !== null && _a !== void 0 ? _a : -1);
2533
- if (index < 0)
2534
- return;
2535
- const rowTouched = Object.assign({}, ((_b = this.touched[index]) !== null && _b !== void 0 ? _b : {}));
2536
- for (const key of Object.keys(event.detail))
2537
- rowTouched[key] = true;
2538
- this.touched = Object.assign(Object.assign({}, this.touched), { [index]: rowTouched });
2539
- const rows = this.rows().map((row, i) => i === index ? Object.assign(Object.assign({}, row), event.detail) : row);
2540
- this.gridValueChange.emit(rows);
2541
- }
2542
- async validateRows() {
2543
- var _a, _b;
2544
- const rows = this.rows();
2545
- const gridKey = (_b = (_a = this.spec.configs) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : 'grid';
2546
- const allTouched = {};
2547
- const errors = {};
2548
- rows.forEach((row, index) => {
2549
- var _a, _b;
2550
- const rowTouched = {};
2551
- for (const child of (_a = this.spec.children) !== null && _a !== void 0 ? _a : []) {
2552
- if ((_b = child.configs) === null || _b === void 0 ? void 0 : _b.key)
2553
- rowTouched[child.configs.key] = true;
2554
- }
2555
- allTouched[index] = rowTouched;
2556
- for (const [key, message] of Object.entries(this.rowErrors(row))) {
2557
- errors[`${gridKey}[${index}].${key}`] = message;
2558
- }
2559
- });
2560
- this.touched = allTouched;
2561
- return { valid: Object.keys(errors).length === 0, errors };
2562
- }
2563
- removeRow(index) {
2564
- const rows = this.rows().filter((_, i) => i !== index);
2565
- const touched = {};
2566
- for (const [key, value] of Object.entries(this.touched)) {
2567
- const i = Number(key);
2568
- if (i < index)
2569
- touched[i] = value;
2570
- else if (i > index)
2571
- touched[i - 1] = value;
2572
- }
2573
- this.touched = touched;
2574
- this.gridValueChange.emit(rows.length ? rows : undefined);
2575
- }
2576
- render() {
2577
- var _a;
2578
- const children = (_a = this.spec.children) !== null && _a !== void 0 ? _a : [];
2579
- const rows = this.rows();
2580
- return (h("div", { key: '1c77d72cd1482d673ffdb5b7d67ca200e55919d7', class: "fk-grid" }, rows.length === 0 ? (h("p", { class: "fk-grid__empty" }, fkT('grid.empty'))) : null, rows.map((row, index) => (h("div", { class: "fk-grid__row", "data-grid-row": index, key: index }, h("div", { class: "fk-grid__cells" }, children.map((child, childIndex) => (h("fk-brick-render", { brickSpec: child, data: row, dataMap: row, errors: this.visibleRowErrors(index), locale: this.locale, path: `grid.${index}.${childIndex}`, utils: this.utils })))), h("button", { type: "button", class: "fk-grid__remove", title: fkT('grid.removeRow'), disabled: this.disabled, onClick: (event) => {
2581
- event.preventDefault();
2582
- this.removeRow(index);
2583
- } }, "\u2715")))), h("button", { key: '9bf04c364b3262c436ffb580daf802d15f29de57', type: "button", class: "fk-grid__add", disabled: this.disabled, onClick: this.addRow }, fkT('grid.addRow'))));
2584
- }
2585
- };
2586
- FkDataGrid.style = fkDataGridCss();
2587
-
2588
- const fkDropAreaCss = () => `.fk-drop.sc-fk-drop-area{display:flex;align-items:center;justify-content:center;min-height:40px;margin-top:calc(var(--fk-spacing) / 2);border:1px dashed var(--fk-color-border);border-radius:var(--fk-radius);color:var(--fk-color-muted);font-size:0.75rem;transition:border-color 120ms ease, background-color 120ms ease}.fk-drop--over.sc-fk-drop-area{border-color:var(--fk-color-primary);background:color-mix(in srgb, var(--fk-color-primary) 8%, transparent);color:var(--fk-color-primary)}`;
2589
-
2590
- const FkDropArea = class {
2591
- constructor(hostRef) {
2592
- registerInstance(this, hostRef);
2593
- this.brickDrop = createEvent(this, "brickDrop");
2594
- this.isOver = false;
2595
- }
2596
- componentDidLoad() {
2597
- this.cleanup = dropTargetForElements({
2598
- element: this.host,
2599
- onDragEnter: () => (this.isOver = true),
2600
- onDragLeave: () => (this.isOver = false),
2601
- onDrop: ({ source, location }) => {
2602
- var _a;
2603
- this.isOver = false;
2604
- if (((_a = location.current.dropTargets[0]) === null || _a === void 0 ? void 0 : _a.element) !== this.host)
2605
- return;
2606
- const detail = toBrickDropDetail(source.data, this.path);
2607
- if (detail)
2608
- this.brickDrop.emit(detail);
2609
- },
2610
- });
2611
- }
2612
- disconnectedCallback() {
2613
- var _a;
2614
- (_a = this.cleanup) === null || _a === void 0 ? void 0 : _a.call(this);
2615
- }
2616
- render() {
2617
- return (h("div", { key: '727b7005fcc58e3b6b2f455b03312fd91e3b063b', class: { 'fk-drop': true, 'fk-drop--over': this.isOver } }, h("span", { key: '41d1158e101100ebb229b74aec2ddfaf1aa57202', class: "fk-drop__hint" }, fkT('drop.hint'))));
2618
- }
2619
- get host() { return getElement(this); }
2620
- };
2621
- FkDropArea.style = fkDropAreaCss();
2622
-
2623
- const fkEmptyFormCss = () => `.fk-empty.sc-fk-empty-form{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:calc(var(--fk-spacing) / 2);min-height:160px;border:2px dashed var(--fk-color-border);border-radius:var(--fk-radius);color:var(--fk-color-muted);text-align:center}.fk-empty__title.sc-fk-empty-form{margin:0;font-weight:600}.fk-empty__hint.sc-fk-empty-form{margin:0;font-size:0.875rem}`;
2624
-
2625
- const FkEmptyForm = class {
2626
- constructor(hostRef) {
2627
- registerInstance(this, hostRef);
2628
- }
2629
- render() {
2630
- return (h(Host, { key: '1b0ab4cd1d988a4800deeb6e3cfd8f5074520f6b' }, h("div", { key: '65b551e1cab6162514ad941b21e318c5f19b824a', class: "fk-empty" }, h("p", { key: 'c4eba1c6fecb4f2669f1c4dfb09cd816790a5ebf', class: "fk-empty__title" }, fkT('empty.title')), h("p", { key: '751bb3a2fc07982c90a214bd1e71592ec03d988d', class: "fk-empty__hint" }, fkT('empty.hint')))));
2631
- }
2632
- };
2633
- FkEmptyForm.style = fkEmptyFormCss();
2634
-
2635
- const fkFileInputCss = () => `.sc-fk-file-input-h{display:block}.fk-file.sc-fk-file-input{display:flex;flex-direction:column;gap:calc(var(--fk-spacing) / 2);align-items:flex-start}.fk-file__native.sc-fk-file-input{display:none}.fk-file__choose.sc-fk-file-input{font:inherit;font-size:0.85rem;padding:calc(var(--fk-spacing) / 1.5) var(--fk-spacing);border:1px dashed var(--fk-color-border);border-radius:var(--fk-radius);background:transparent;color:var(--fk-color-muted);cursor:pointer}.fk-file__choose.sc-fk-file-input:hover:not(:disabled){border-color:var(--fk-color-primary);color:var(--fk-color-primary)}.fk-file__choose.sc-fk-file-input:disabled{opacity:0.55;cursor:not-allowed}.fk-file__selected.sc-fk-file-input{display:flex;align-items:center;gap:var(--fk-spacing);width:100%;box-sizing:border-box;padding:calc(var(--fk-spacing) * 0.75) var(--fk-spacing);border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface)}.fk-file__icon.sc-fk-file-input{display:inline-flex;flex-shrink:0;color:var(--fk-color-primary)}.fk-file__meta.sc-fk-file-input{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}.fk-file__name.sc-fk-file-input{font-size:0.85rem;font-weight:600;color:var(--fk-color-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fk-file__size.sc-fk-file-input{font-size:0.72rem;color:var(--fk-color-muted);white-space:nowrap}.fk-file__remove.sc-fk-file-input{border:none;background:transparent;color:var(--fk-color-muted);font-size:0.8rem;cursor:pointer;padding:4px 6px;border-radius:calc(var(--fk-radius) / 2);flex-shrink:0}.fk-file__remove.sc-fk-file-input:hover:not(:disabled){background:color-mix(in srgb, var(--fk-color-danger) 12%, transparent)}.fk-file__remove.sc-fk-file-input:hover:not(:disabled){color:var(--fk-color-danger)}`;
2636
-
2637
- const FkFileInput = class {
2638
- constructor(hostRef) {
2639
- registerInstance(this, hostRef);
2640
- this.fileValueChange = createEvent(this, "fileValueChange");
2641
- this.disabled = false;
2642
- this.multiple = false;
2643
- this.uploading = false;
2644
- this.handleFile = async (event) => {
2645
- var _a;
2646
- const input = event.target;
2647
- const selected = Array.from((_a = input.files) !== null && _a !== void 0 ? _a : []);
2648
- if (!selected.length)
2649
- return;
2650
- this.uploading = true;
2651
- this.uploadError = undefined;
2652
- try {
2653
- const uploaded = [];
2654
- for (const file of this.multiple ? selected : selected.slice(0, 1)) {
2655
- uploaded.push(await services.fileUploadService.upload(file, { url: this.uploadUrl }));
2656
- }
2657
- this.emitFiles(this.multiple ? [...this.files, ...uploaded] : uploaded);
2658
- }
2659
- catch (error) {
2660
- this.uploadError =
2661
- error instanceof Error ? error.message : String(error);
2662
- }
2663
- finally {
2664
- this.uploading = false;
2665
- input.value = '';
2666
- }
2667
- };
2668
- this.handleRemove = async (file) => {
2669
- var _a, _b;
2670
- this.removingUrl = file.url;
2671
- this.uploadError = undefined;
2672
- try {
2673
- await ((_b = (_a = services.fileUploadService).remove) === null || _b === void 0 ? void 0 : _b.call(_a, file, { url: this.uploadUrl }));
2674
- }
2675
- catch (error) {
2676
- this.uploadError = error instanceof Error ? error.message : String(error);
2677
- }
2678
- finally {
2679
- this.removingUrl = undefined;
2680
- this.emitFiles(this.files.filter((item) => item !== file));
2681
- }
2682
- };
2683
- }
2684
- get files() {
2685
- if (Array.isArray(this.value))
2686
- return this.value;
2687
- return this.value ? [this.value] : [];
2688
- }
2689
- emitFiles(files) {
2690
- if (this.multiple) {
2691
- this.fileValueChange.emit(files.length ? files : undefined);
2692
- }
2693
- else {
2694
- this.fileValueChange.emit(files[0]);
2695
- }
2696
- }
2697
- formatSize(size) {
2698
- if (size < 1024)
2699
- return `${size} B`;
2700
- if (size < 1024 * 1024)
2701
- return `${(size / 1024).toFixed(1)} KB`;
2702
- return `${(size / (1024 * 1024)).toFixed(1)} MB`;
2703
- }
2704
- renderFile(file) {
2705
- const removing = this.removingUrl !== undefined && this.removingUrl === file.url;
2706
- return (h("div", { class: "fk-file__selected", key: `${file.url}:${file.name}` }, h("span", { class: "fk-file__icon", "aria-hidden": "true" }, h("svg", { viewBox: "0 0 24 24", width: "16", height: "16", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }, h("path", { d: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" }), h("polyline", { points: "14 2 14 8 20 8" }))), h("span", { class: "fk-file__meta" }, h("span", { class: "fk-file__name", title: file.name }, file.name), h("span", { class: "fk-file__size" }, this.formatSize(file.size))), h("button", { type: "button", class: "fk-file__remove", title: fkT('file.remove'), disabled: this.disabled || removing, onClick: (event) => {
2707
- event.preventDefault();
2708
- void this.handleRemove(file);
2709
- } }, removing ? '…' : '✕')));
2710
- }
2711
- render() {
2712
- const files = this.files;
2713
- const showChoose = this.multiple || files.length === 0;
2714
- return (h("div", { key: '883cb0627b948d807f59ed5c62e44b0db421c3c6', class: "fk-file" }, files.map((file) => this.renderFile(file)), showChoose ? (h("button", { type: "button", class: "fk-file__choose", disabled: this.disabled || this.uploading, onClick: (event) => {
2715
- var _a;
2716
- event.preventDefault();
2717
- (_a = this.inputEl) === null || _a === void 0 ? void 0 : _a.click();
2718
- } }, this.uploading
2719
- ? fkT('file.uploading')
2720
- : this.multiple && files.length
2721
- ? fkTOr('file.addAnother', '+ Add a file')
2722
- : fkT('file.choose'))) : null, h("input", { key: 'a35947614d82f94eba8453b1f43382d2754cb36f', class: "fk-file__native", type: "file", accept: this.accept, multiple: this.multiple, disabled: this.disabled, ref: (element) => (this.inputEl = element), onChange: this.handleFile }), this.uploadError ? (h("span", { class: "fk-field__error" }, this.uploadError)) : null));
2723
- }
2724
- };
2725
- FkFileInput.style = fkFileInputCss();
2726
-
2727
- const fkFormBuilderCss = () => `.sc-fk-form-builder-h{display:block;container-type:inline-size}.fk-builder.sc-fk-form-builder{display:flex;gap:calc(var(--fk-spacing) * 2);align-items:flex-start;font-family:var(--fk-font);color:var(--fk-color-text)}@container (max-width: 820px){.fk-builder{flex-wrap:wrap}.fk-builder__palette,.fk-builder__inspector{width:100%}.fk-builder__main{order:2;flex-basis:100%}.fk-builder__palette{order:1}.fk-builder__inspector{order:3}}.fk-builder__palette.sc-fk-form-builder{width:220px;flex-shrink:0;padding:calc(var(--fk-spacing) * 1.5);border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface)}.fk-builder__main.sc-fk-form-builder{flex:1;min-width:0;display:flex;flex-direction:column;gap:var(--fk-spacing)}.fk-builder__toolbar.sc-fk-form-builder{display:flex;align-items:center;gap:calc(var(--fk-spacing) / 2)}.fk-builder__spacer.sc-fk-form-builder{flex:1}.fk-builder__import-error.sc-fk-form-builder{font-size:0.75rem;color:var(--fk-color-danger)}.fk-builder__tool.sc-fk-form-builder{padding:calc(var(--fk-spacing) / 2) var(--fk-spacing);border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:var(--fk-color-surface);color:var(--fk-color-text);font-size:0.8rem;cursor:pointer}.fk-builder__tool.sc-fk-form-builder:hover:not(:disabled){border-color:var(--fk-color-primary);color:var(--fk-color-primary)}.fk-builder__tool.sc-fk-form-builder:disabled{opacity:0.4;cursor:default}.fk-builder__canvas.sc-fk-form-builder{min-height:320px;padding:calc(var(--fk-spacing) * 2);border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface);overflow-x:auto}.fk-builder__inspector.sc-fk-form-builder{width:260px;flex-shrink:0;padding:calc(var(--fk-spacing) * 1.5);border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface)}.fk-builder__hint.sc-fk-form-builder{margin:0;font-size:0.8rem;color:var(--fk-color-muted)}`;
2728
-
2729
- const FkFormBuilder = class {
2730
- constructor(hostRef) {
2731
- registerInstance(this, hostRef);
2732
- this.specChange = createEvent(this, "specChange");
2733
- this.locales = [];
2734
- this.currentData = {};
2735
- this.copied = false;
2736
- this.history = new SpecHistory();
2737
- this.importFromClipboard = async () => {
2738
- try {
2739
- const text = await navigator.clipboard.readText();
2740
- this.importSpec(text, false);
2741
- }
2742
- catch (_a) {
2743
- this.flashImportError(fkT('builder.pasteHint'));
2744
- }
2745
- };
2746
- this.copySpec = async () => {
2747
- if (!this.currentSpec)
2748
- return;
2749
- await navigator.clipboard.writeText(this.specJson());
2750
- this.copied = true;
2751
- setTimeout(() => (this.copied = false), 1500);
2752
- };
2753
- this.downloadSpec = () => {
2754
- if (!this.currentSpec)
2755
- return;
2756
- const blob = new Blob([this.specJson()], { type: 'application/json' });
2757
- const url = URL.createObjectURL(blob);
2758
- const link = document.createElement('a');
2759
- link.href = url;
2760
- link.download = 'form-spec.json';
2761
- link.click();
2762
- URL.revokeObjectURL(url);
2763
- };
2764
- this.undo = () => {
2765
- if (!this.currentSpec)
2766
- return;
2767
- const spec = this.history.undo(this.currentSpec);
2768
- if (spec === undefined)
2769
- return;
2770
- this.currentSpec = spec;
2771
- this.specChange.emit({ spec, patches: [], inverse: [] });
2772
- };
2773
- this.redo = () => {
2774
- if (!this.currentSpec)
2775
- return;
2776
- const spec = this.history.redo(this.currentSpec);
2777
- if (spec === undefined)
2778
- return;
2779
- this.currentSpec = spec;
2780
- this.specChange.emit({ spec, patches: [], inverse: [] });
2781
- };
2782
- }
2783
- componentWillLoad() {
2784
- if (getBrickMolds().length === 0)
2785
- registerDefaultBricks();
2786
- this.editLocale = this.locales[0];
2787
- this.currentSpec = this.spec;
2788
- this.currentData = Object.assign({}, this.data);
2789
- }
2790
- syncSpec(next) {
2791
- this.currentSpec = next;
2792
- this.history.clear();
2793
- }
2794
- handleBrickDrop(event) {
2795
- var _a, _b;
2796
- event.stopPropagation();
2797
- const { source, mold, from, parentPath, index } = event.detail;
2798
- if (source === 'new' && mold) {
2799
- const brickSpec = newBrickSpec(mold.type, mold.id);
2800
- if (!brickSpec)
2801
- return;
2802
- if (!this.currentSpec) {
2803
- this.setRootSpec(brickSpec.type === 'panel'
2804
- ? brickSpec
2805
- : this.wrapInRootGroup(brickSpec));
2806
- return;
2807
- }
2808
- this.applyUpdate(addBrick(this.currentSpec, brickSpec, parentPath, index));
2809
- return;
2810
- }
2811
- if (source === 'move' && from && this.currentSpec) {
2812
- if (parentPath === from || parentPath.startsWith(`${from}.`))
2813
- return;
2814
- const parent = getBrickAt(this.currentSpec, parentPath);
2815
- if (!parent)
2816
- return;
2817
- const count = (_b = (_a = parent.children) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
2818
- const fromSegments = from.split('.');
2819
- const fromParent = fromSegments.slice(0, -1).join('.');
2820
- const fromIndex = Number(fromSegments[fromSegments.length - 1]);
2821
- const targetIndex = index !== null && index !== void 0 ? index : count;
2822
- if (fromParent === parentPath &&
2823
- (targetIndex === fromIndex || targetIndex === fromIndex + 1)) {
2824
- return;
2825
- }
2826
- this.applyUpdate(moveBrick(this.currentSpec, from, `${parentPath}.${targetIndex}`));
2827
- }
2828
- }
2829
- handleBrickRemove(event) {
2830
- event.stopPropagation();
2831
- if (!this.currentSpec)
2832
- return;
2833
- if (event.detail.path === '0') {
2834
- this.setRootSpec(undefined);
2835
- return;
2836
- }
2837
- this.applyUpdate(removeBrick(this.currentSpec, event.detail.path));
2838
- }
2839
- handleBrickDuplicate(event) {
2840
- event.stopPropagation();
2841
- if (!this.currentSpec)
2842
- return;
2843
- this.applyUpdate(duplicateBrick(this.currentSpec, event.detail.path));
2844
- }
2845
- handleConfigsChange(event) {
2846
- event.stopPropagation();
2847
- if (!this.currentSpec || !event.detail.uid)
2848
- return;
2849
- this.applyUpdate(updateBrickConfigs(this.currentSpec, event.detail.uid, event.detail.configs));
2850
- }
2851
- handleStylesChange(event) {
2852
- event.stopPropagation();
2853
- if (!this.currentSpec || !event.detail.uid)
2854
- return;
2855
- this.applyUpdate(updateBrickStyles(this.currentSpec, event.detail.uid, event.detail.styles));
2856
- }
2857
- handleValidationsChange(event) {
2858
- event.stopPropagation();
2859
- if (!this.currentSpec || !event.detail.uid)
2860
- return;
2861
- this.applyUpdate(updateBrickValidations(this.currentSpec, event.detail.uid, event.detail.validations));
2862
- }
2863
- handleRulesChange(event) {
2864
- event.stopPropagation();
2865
- if (!this.currentSpec || !event.detail.uid)
2866
- return;
2867
- this.applyUpdate(updateBrickRules(this.currentSpec, event.detail.uid, event.detail.rules));
2868
- }
2869
- handleDataChange(event) {
2870
- this.currentData = event.detail.data;
2871
- }
2872
- handlePaste(event) {
2873
- var _a;
2874
- const target = event.target;
2875
- if (target === null || target === void 0 ? void 0 : target.closest('input, textarea, select, [contenteditable]'))
2876
- return;
2877
- this.importSpec((_a = event.clipboardData) === null || _a === void 0 ? void 0 : _a.getData('text/plain'), true);
2878
- }
2879
- importSpec(text, silent) {
2880
- if (!text) {
2881
- if (!silent)
2882
- this.flashImportError(fkT('builder.importInvalid'));
2883
- return;
2884
- }
2885
- try {
2886
- const parsed = JSON.parse(text);
2887
- if (typeof parsed !== 'object' ||
2888
- parsed === null ||
2889
- typeof parsed.type !== 'string' ||
2890
- typeof parsed.id !== 'string') {
2891
- throw new Error('not a brick spec');
2892
- }
2893
- this.selectedUid = undefined;
2894
- this.importError = undefined;
2895
- this.setRootSpec(this.ensureUids(parsed));
2896
- }
2897
- catch (_a) {
2898
- if (!silent)
2899
- this.flashImportError(fkT('builder.importInvalid'));
2900
- }
2901
- }
2902
- ensureUids(spec) {
2903
- var _a;
2904
- const clone = structuredClone(spec);
2905
- for (const { brick } of iterateBricks(clone)) {
2906
- if (!((_a = brick.configs) === null || _a === void 0 ? void 0 : _a.uid)) {
2907
- brick.configs = Object.assign(Object.assign({}, brick.configs), { uid: crypto.randomUUID() });
2908
- }
2909
- }
2910
- return clone;
2911
- }
2912
- flashImportError(message) {
2913
- this.importError = message;
2914
- setTimeout(() => (this.importError = undefined), 4000);
2915
- }
2916
- handleBrickSelect(event) {
2917
- var _a, _b;
2918
- event.stopPropagation();
2919
- if (!this.currentSpec)
2920
- return;
2921
- this.selectedUid = (_b = (_a = getBrickAt(this.currentSpec, event.detail.path)) === null || _a === void 0 ? void 0 : _a.configs) === null || _b === void 0 ? void 0 : _b.uid;
2922
- }
2923
- findSelected() {
2924
- var _a;
2925
- if (!this.currentSpec || !this.selectedUid)
2926
- return undefined;
2927
- for (const { brick, path } of iterateBricks(this.currentSpec)) {
2928
- if (((_a = brick.configs) === null || _a === void 0 ? void 0 : _a.uid) === this.selectedUid)
2929
- return { brick, path };
2930
- }
2931
- return undefined;
2932
- }
2933
- inputFieldKeys() {
2934
- var _a;
2935
- const keys = [];
2936
- for (const { brick } of iterateBricks(this.currentSpec)) {
2937
- const key = (_a = brick.configs) === null || _a === void 0 ? void 0 : _a.key;
2938
- if (brick.type === 'input' && key)
2939
- keys.push(key);
2940
- }
2941
- return keys;
2942
- }
2943
- wrapInRootGroup(brickSpec) {
2944
- const root = newBrickSpec('panel', 'column');
2945
- if (!root)
2946
- return brickSpec;
2947
- return Object.assign(Object.assign({}, root), { name: 'Form', children: [brickSpec] });
2948
- }
2949
- setRootSpec(spec) {
2950
- this.currentSpec = spec;
2951
- this.history.clear();
2952
- this.specChange.emit({ spec, patches: [], inverse: [] });
2953
- }
2954
- applyUpdate(update) {
2955
- this.history.record(update);
2956
- this.currentSpec = update.spec;
2957
- this.specChange.emit({
2958
- spec: update.spec,
2959
- patches: update.patches,
2960
- inverse: update.inverse,
2961
- });
2962
- }
2963
- specJson() {
2964
- return JSON.stringify(this.currentSpec, null, 2);
2965
- }
2966
- render() {
2967
- return (h("div", { key: 'f23b549325059ff00dc9b4dcce05f82e7905f646', class: "fk-builder" }, h("aside", { key: '76d630af39352b324fa1160945953bcc92f7e678', class: "fk-builder__palette" }, h("fk-brick-list", { key: 'a2fbf6fb78febd993e1972a3077e07cd952501f9' })), h("main", { key: 'e65836c299ef0b102bf99da9263823cb8506aa87', class: "fk-builder__main" }, h("div", { key: 'cf6681fdc4f36720919f3e52852eeaf247b4cd3f', class: "fk-builder__toolbar" }, h("button", { key: '8669e0c0bff778cee7b5a0f8dc85d762cd923309', type: "button", class: "fk-builder__tool", disabled: !this.history.canUndo, onClick: this.undo }, "\u21A9 ", fkT('builder.undo')), h("button", { key: 'e8f1b9e73a97ce7fc134628ec9dd80c43ef27f16', type: "button", class: "fk-builder__tool", disabled: !this.history.canRedo, onClick: this.redo }, "\u21AA ", fkT('builder.redo')), h("span", { key: 'e0af911cdb8686c8276ef3b48f75cf65b3f300ea', class: "fk-builder__spacer" }), this.locales.length > 1 ? (h("select", { class: "fk-builder__tool", onChange: (event) => (this.editLocale = event.target.value) }, this.locales.map((locale) => (h("option", { value: locale, selected: locale === this.editLocale }, locale.toUpperCase()))))) : null, this.importError ? (h("span", { class: "fk-builder__import-error" }, this.importError)) : null, h("button", { key: '5eb508486721587353400365ca3826bed2037620', type: "button", class: "fk-builder__tool", onClick: this.importFromClipboard }, "\u2913 ", fkT('builder.importJson')), h("button", { key: '4e60dd9edeef51da8871c34ea042cb828c6a547b', type: "button", class: "fk-builder__tool", disabled: !this.currentSpec, onClick: this.copySpec }, "\u29C9 ", this.copied ? fkT('builder.copied') : fkT('builder.copyJson')), h("button", { key: '40fc0afc683894136b6be5f73fd7f9803e0cc34c', type: "button", class: "fk-builder__tool", disabled: !this.currentSpec, onClick: this.downloadSpec }, "\u2B07 ", fkT('builder.downloadJson'))), h("div", { key: '317a25b31e4fa22204b923457a507f94bcbe5fbe', class: "fk-builder__canvas" }, this.currentSpec ? (h("fk-form-render", { spec: this.currentSpec, data: this.currentData, editable: true, selectedUid: this.selectedUid, locale: this.editLocale })) : ([h("fk-empty-form", null), h("fk-drop-area", { path: "0" })]))), h("aside", { key: '7d6491acc432ed158eec6727db75f152fa8398d4', class: "fk-builder__inspector" }, (() => {
2968
- const selected = this.findSelected();
2969
- return selected ? (h("fk-property-panel", { brick: selected.brick, fields: this.inputFieldKeys(), locales: this.locales, editLocale: this.editLocale })) : (h("p", { class: "fk-builder__hint" }, fkT('builder.hint')));
2970
- })())));
2971
- }
2972
- static get watchers() { return {
2973
- "spec": [{
2974
- "syncSpec": 0
2975
- }]
2976
- }; }
2977
- };
2978
- FkFormBuilder.style = fkFormBuilderCss();
2979
-
2980
- const fkFormRenderCss = () => `.fk-form.sc-fk-form-render{display:flex;flex-direction:column;gap:var(--fk-spacing);font-family:var(--fk-font);color:var(--fk-color-text)}`;
2981
-
2982
- const FkFormRender = class {
2983
- constructor(hostRef) {
2984
- registerInstance(this, hostRef);
2985
- this.formDataChange = createEvent(this, "formDataChange");
2986
- this.formSubmit = createEvent(this, "formSubmit");
2987
- this.editable = false;
2988
- this.currentData = {};
2989
- this.touched = {};
2990
- this.utils = {
2991
- validateForm: () => ({
2992
- isValid: this.runValidation().valid,
2993
- }),
2994
- };
2995
- }
2996
- componentWillLoad() {
2997
- this.currentData = Object.assign({}, this.data);
2998
- }
2999
- syncData(next) {
3000
- this.currentData = Object.assign({}, next);
3001
- }
3002
- publicData() {
3003
- return Object.fromEntries(Object.entries(this.currentData).filter(([key]) => !key.startsWith('_')));
3004
- }
3005
- handleBrickDataChange(event) {
3006
- event.stopPropagation();
3007
- this.currentData = this.applyValueEffects(Object.assign(Object.assign({}, this.currentData), event.detail));
3008
- const touched = Object.assign({}, this.touched);
3009
- for (const key of Object.keys(event.detail))
3010
- touched[key] = true;
3011
- this.touched = touched;
3012
- const { valid, errors } = this.runValidation();
3013
- this.formDataChange.emit({
3014
- data: this.publicData(),
3015
- isValid: valid,
3016
- errors,
3017
- });
3018
- }
3019
- applyValueEffects(data) {
3020
- var _a, _b;
3021
- let result = data;
3022
- for (const { brick } of iterateBricks(this.spec)) {
3023
- const key = (_a = brick.configs) === null || _a === void 0 ? void 0 : _a.key;
3024
- if (!key || !((_b = brick.rules) === null || _b === void 0 ? void 0 : _b.length))
3025
- continue;
3026
- const affected = getAffectedProperties(brick.rules, result);
3027
- if (affected.value !== undefined && result[key] !== affected.value) {
3028
- result = Object.assign(Object.assign({}, result), { [key]: affected.value });
3029
- }
3030
- }
3031
- return result;
3032
- }
3033
- async validate() {
3034
- var _a;
3035
- const touched = {};
3036
- for (const { brick } of iterateBricks(this.spec)) {
3037
- const key = (_a = brick.configs) === null || _a === void 0 ? void 0 : _a.key;
3038
- if (key)
3039
- touched[key] = true;
3040
- }
3041
- this.touched = touched;
3042
- const flat = this.runValidation();
3043
- const errors = Object.assign({}, flat.errors);
3044
- let valid = flat.valid;
3045
- const grids = Array.from(this.host.querySelectorAll('fk-data-grid'));
3046
- for (const grid of grids) {
3047
- const rowResult = await grid.validateRows();
3048
- valid = valid && rowResult.valid;
3049
- Object.assign(errors, rowResult.errors);
3050
- }
3051
- const result = { valid, errors };
3052
- this.formDataChange.emit({
3053
- data: this.publicData(),
3054
- isValid: result.valid,
3055
- errors: result.errors,
3056
- });
3057
- return result;
3058
- }
3059
- handleStepTouch(event) {
3060
- event.stopPropagation();
3061
- const touched = Object.assign({}, this.touched);
3062
- for (const key of event.detail.keys)
3063
- touched[key] = true;
3064
- this.touched = touched;
3065
- }
3066
- async handleStepperSubmit(event) {
3067
- event.stopPropagation();
3068
- const result = await this.validate();
3069
- this.formSubmit.emit({
3070
- data: this.publicData(),
3071
- isValid: result.valid,
3072
- errors: result.errors,
3073
- });
3074
- }
3075
- runValidation() {
3076
- const presentData = Object.fromEntries(Object.entries(this.currentData).filter(([, value]) => value !== '' && value !== null && value !== undefined));
3077
- return validateBrickSpecDataDetailed(this.spec, presentData, this.locale);
3078
- }
3079
- visibleErrors() {
3080
- if (this.editable)
3081
- return {};
3082
- const errors = {};
3083
- for (const [key, message] of Object.entries(this.runValidation().errors)) {
3084
- if (this.touched[key])
3085
- errors[key] = message;
3086
- }
3087
- return errors;
3088
- }
3089
- render() {
3090
- if (!this.spec)
3091
- return null;
3092
- return (h("form", { class: "fk-form", onSubmit: (event) => event.preventDefault() }, h("fk-brick-render", { brickSpec: this.spec, rootSpec: this.spec, data: this.currentData, dataMap: this.currentData, errors: this.visibleErrors(), locale: this.locale, path: "0", editable: this.editable, selectedUid: this.selectedUid, utils: this.utils })));
3093
- }
3094
- get host() { return getElement(this); }
3095
- static get watchers() { return {
3096
- "data": [{
3097
- "syncData": 0
3098
- }]
3099
- }; }
3100
- };
3101
- FkFormRender.style = fkFormRenderCss();
3102
-
3103
- const fkPropertyPanelCss = () => `.sc-fk-property-panel-h{display:block}.fk-props.sc-fk-property-panel{display:flex;flex-direction:column;gap:calc(var(--fk-spacing) * 1.5)}.fk-props__header.sc-fk-property-panel{display:flex;flex-direction:column;gap:2px}.fk-props__type.sc-fk-property-panel{font-size:0.65rem;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;color:var(--fk-color-primary)}.fk-props__title.sc-fk-property-panel{margin:0;font-size:0.95rem;color:var(--fk-color-text)}.fk-props__section.sc-fk-property-panel{display:flex;flex-direction:column;gap:var(--fk-spacing);padding-top:var(--fk-spacing)}.fk-props__tabs.sc-fk-property-panel{display:flex;gap:2px;border-bottom:1px solid var(--fk-color-border)}.fk-props__tab.sc-fk-property-panel{font:inherit;font-size:0.72rem;font-weight:600;padding:5px 9px;border:none;border-bottom:2px solid transparent;background:transparent;color:var(--fk-color-muted);cursor:pointer}.fk-props__tab.sc-fk-property-panel:hover{color:var(--fk-color-text)}.fk-props__tab--active.sc-fk-property-panel{color:var(--fk-color-primary);border-bottom-color:var(--fk-color-primary)}.fk-props__section-title.sc-fk-property-panel{margin:0;font-size:0.7rem;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;color:var(--fk-color-muted)}.fk-props__field.sc-fk-property-panel{display:flex;flex-direction:column;gap:4px}.fk-props__field--inline.sc-fk-property-panel{flex-direction:row;align-items:center;gap:8px}.fk-props__label.sc-fk-property-panel{font-size:0.75rem;font-weight:600;color:var(--fk-color-muted)}.fk-props__input.sc-fk-property-panel{font:inherit;font-size:0.85rem;padding:6px 8px;border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:var(--fk-color-surface);color:var(--fk-color-text)}.fk-props__input.sc-fk-property-panel:focus{outline:none;border-color:var(--fk-color-primary);box-shadow:0 0 0 2px color-mix(in srgb, var(--fk-color-primary) 20%, transparent)}.fk-props__input--textarea.sc-fk-property-panel{min-height:72px;resize:vertical}.fk-props__vrule.sc-fk-property-panel{display:flex;flex-direction:column;gap:6px;padding:calc(var(--fk-spacing) / 1.5);border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 1.5)}.fk-props__style-row.sc-fk-property-panel{display:flex;align-items:center;gap:6px}.fk-props__style-key.sc-fk-property-panel{font-family:ui-monospace, SFMono-Regular, Menlo, monospace;font-size:0.75rem;color:var(--fk-color-text);min-width:72px}.fk-props__input--grow.sc-fk-property-panel{flex:1;min-width:0}.fk-props__remove.sc-fk-property-panel{border:none;background:transparent;color:var(--fk-color-muted);font-size:0.75rem;cursor:pointer;padding:2px 4px;border-radius:calc(var(--fk-radius) / 2)}.fk-props__remove.sc-fk-property-panel:hover{color:var(--fk-color-danger);background:color-mix(in srgb, var(--fk-color-danger) 10%, transparent)}`;
3104
-
3105
- const FkPropertyPanel = class {
3106
- constructor(hostRef) {
3107
- registerInstance(this, hostRef);
3108
- this.brickConfigsChange = createEvent(this, "brickConfigsChange");
3109
- this.brickValidationsChange = createEvent(this, "brickValidationsChange");
3110
- this.brickStylesChange = createEvent(this, "brickStylesChange");
3111
- this.fields = [];
3112
- this.locales = [];
3113
- this.activeTab = 'config';
3114
- this.newStyleKey = '';
3115
- }
3116
- onBrickChange() {
3117
- if (!this.availableTabs().some((tab) => tab.id === this.activeTab)) {
3118
- this.activeTab = 'config';
3119
- }
3120
- }
3121
- availableTabs() {
3122
- const tabs = [
3123
- { id: 'config', label: fkT('panel.tab.config') },
3124
- ];
3125
- if (this.brick.type === 'input') {
3126
- tabs.push({ id: 'validation', label: fkT('panel.tab.validation') });
3127
- }
3128
- tabs.push({ id: 'styles', label: fkT('panel.tab.styles') }, { id: 'rules', label: fkT('panel.tab.rules') });
3129
- return tabs;
3130
- }
3131
- localized(current, value) {
3132
- var _a;
3133
- if (this.locales.length <= 1)
3134
- return value || undefined;
3135
- const map = isLocalizedObject(current)
3136
- ? Object.assign({}, current) : {};
3137
- if (typeof current === 'string' && current && !isLocalizedObject(current)) {
3138
- map[this.locales[0]] = current;
3139
- }
3140
- map[(_a = this.editLocale) !== null && _a !== void 0 ? _a : this.locales[0]] = value;
3141
- return map;
3142
- }
3143
- readLocalized(current) {
3144
- var _a, _b, _c;
3145
- if (isLocalizedObject(current)) {
3146
- return (_b = current[(_a = this.editLocale) !== null && _a !== void 0 ? _a : this.locales[0]]) !== null && _b !== void 0 ? _b : '';
3147
- }
3148
- return (_c = current) !== null && _c !== void 0 ? _c : '';
3149
- }
3150
- writeTextConfig(key, value) {
3151
- var _a;
3152
- this.emitConfigs({ [key]: this.localized((_a = this.brick.configs) === null || _a === void 0 ? void 0 : _a[key], value) });
3153
- }
3154
- emitConfigs(patch) {
3155
- var _a;
3156
- const uid = (_a = this.brick.configs) === null || _a === void 0 ? void 0 : _a.uid;
3157
- if (!uid)
3158
- return;
3159
- this.brickConfigsChange.emit({ configs: patch, uid });
3160
- }
3161
- emitValidations(validations) {
3162
- var _a;
3163
- const uid = (_a = this.brick.configs) === null || _a === void 0 ? void 0 : _a.uid;
3164
- if (!uid)
3165
- return;
3166
- this.brickValidationsChange.emit({ validations, uid });
3167
- }
3168
- emitStyles(patch) {
3169
- var _a;
3170
- const uid = (_a = this.brick.configs) === null || _a === void 0 ? void 0 : _a.uid;
3171
- if (!uid)
3172
- return;
3173
- this.brickStylesChange.emit({ styles: patch, uid });
3174
- }
3175
- validationOf(validator) {
3176
- var _a;
3177
- return (_a = this.brick.validations) === null || _a === void 0 ? void 0 : _a.find((validation) => validation.validator === validator);
3178
- }
3179
- setValidation(validator, active, patch = {}) {
3180
- var _a;
3181
- const current = this.validationOf(validator);
3182
- const others = ((_a = this.brick.validations) !== null && _a !== void 0 ? _a : []).filter((validation) => validation.validator !== validator);
3183
- this.emitValidations(active ? [...others, Object.assign(Object.assign(Object.assign({}, current), { validator }), patch)] : others);
3184
- }
3185
- addStyle(value) {
3186
- const key = this.newStyleKey.trim();
3187
- if (!key)
3188
- return;
3189
- this.emitStyles({ [key]: value });
3190
- this.newStyleKey = '';
3191
- }
3192
- textField(label, value, onCommit) {
3193
- var _a;
3194
- return (h("label", { class: "fk-props__field" }, h("span", { class: "fk-props__label" }, label), h("input", { class: "fk-props__input", type: "text", value: (_a = value) !== null && _a !== void 0 ? _a : '', onChange: (event) => onCommit(event.target.value) })));
3195
- }
3196
- optionsFields() {
3197
- var _a, _b, _c;
3198
- const configs = this.brick.configs;
3199
- if (!configs || !('options' in configs || 'optionsSource' in configs)) {
3200
- return [];
3201
- }
3202
- const supportsSources = 'optionsSource' in configs;
3203
- const source = supportsSources
3204
- ? ((_a = configs.optionsSource) !== null && _a !== void 0 ? _a : 'static')
3205
- : 'static';
3206
- const nodes = supportsSources
3207
- ? [
3208
- h("label", { class: "fk-props__field" }, h("span", { class: "fk-props__label" }, fkT('panel.optionsSource')), h("select", { class: "fk-props__input", onChange: (event) => this.emitConfigs({
3209
- optionsSource: event.target.value,
3210
- }) }, ['static', 'dataMap', 'remote', 'js'].map((candidate) => (h("option", { value: candidate, selected: candidate === source }, candidate))))),
3211
- ]
3212
- : [];
3213
- if (source === 'static') {
3214
- nodes.push(h("label", { class: "fk-props__field" }, h("span", { class: "fk-props__label" }, fkT('panel.options')), h("textarea", { class: "fk-props__input fk-props__input--textarea", onChange: (event) => this.writeTextConfig('options', event.target.value) }, this.readLocalized(configs.options))));
3215
- }
3216
- if (source === 'dataMap') {
3217
- nodes.push(this.textField(fkT('panel.dataKey'), configs.optionsPath, (value) => this.emitConfigs({ optionsPath: value })));
3218
- }
3219
- if (source === 'remote') {
3220
- nodes.push(this.textField(fkT('panel.url'), configs.optionsUrl, (value) => this.emitConfigs({ optionsUrl: value })), h("label", { class: "fk-props__field" }, h("span", { class: "fk-props__label" }, fkT('panel.headers')), h("textarea", { class: "fk-props__input fk-props__input--textarea", placeholder: 'Authorization: Bearer {token}', onChange: (event) => this.emitConfigs({
3221
- optionsHeaders: event.target.value || undefined,
3222
- }) }, (_b = configs.optionsHeaders) !== null && _b !== void 0 ? _b : '')), this.textField(fkT('panel.searchParam'), configs.searchParam, (value) => this.emitConfigs({ searchParam: value || undefined })));
3223
- }
3224
- if (source === 'js') {
3225
- nodes.push(h("label", { class: "fk-props__field" }, h("span", { class: "fk-props__label" }, "Code"), h("fk-code-editor", { value: (_c = configs.optionsCode) !== null && _c !== void 0 ? _c : '', placeholder: "return dataMap.country === 'BJ' ? ['Cotonou'] : ['Paris'];", onCodeChange: (event) => this.emitConfigs({ optionsCode: event.detail }) })));
3226
- }
3227
- if (source === 'remote' || source === 'js') {
3228
- nodes.push(this.textField(fkT('panel.labelKey'), configs.labelKey, (value) => this.emitConfigs({ labelKey: value })), this.textField(fkT('panel.valueKey'), configs.valueKey, (value) => this.emitConfigs({ valueKey: value })));
3229
- }
3230
- return nodes;
3231
- }
3232
- renderConfigTab() {
3233
- const configs = this.brick.configs;
3234
- const isInput = this.brick.type === 'input';
3235
- return (h("section", { class: "fk-props__section" }, this.textField(fkT('panel.key'), configs === null || configs === void 0 ? void 0 : configs.key, (value) => this.emitConfigs({ key: value })), this.textField(fkT('panel.label'), this.readLocalized(configs === null || configs === void 0 ? void 0 : configs.label), (value) => this.writeTextConfig('label', value)), isInput
3236
- ? [
3237
- this.textField(fkT('panel.placeholder'), this.readLocalized(configs === null || configs === void 0 ? void 0 : configs.placeholder), (value) => this.writeTextConfig('placeholder', value)),
3238
- this.textField(fkT('panel.prefix'), configs === null || configs === void 0 ? void 0 : configs.prefix, (value) => this.emitConfigs({ prefix: value || undefined })),
3239
- this.textField(fkT('panel.suffix'), configs === null || configs === void 0 ? void 0 : configs.suffix, (value) => this.emitConfigs({ suffix: value || undefined })),
3240
- ]
3241
- : null, configs && 'accept' in configs
3242
- ? this.textField(fkTOr('panel.accept', 'Accepted file types'), configs.accept, (value) => this.emitConfigs({ accept: value }))
3243
- : null, configs && 'uploadUrl' in configs
3244
- ? this.textField(fkTOr('panel.uploadUrl', 'Upload URL'), configs.uploadUrl, (value) => this.emitConfigs({ uploadUrl: value }))
3245
- : null, this.optionsFields(), Object.entries(configs !== null && configs !== void 0 ? configs : {})
3246
- .filter(([, value]) => typeof value === 'boolean')
3247
- .map(([key, value]) => (h("label", { class: "fk-props__field fk-props__field--inline", key: key }, h("input", { type: "checkbox", checked: value === true, onChange: (event) => this.emitConfigs({
3248
- [key]: event.target.checked,
3249
- }) }), h("span", { class: "fk-props__label" }, fkTOr(`panel.cfg.${key}`, key))))), configs && 'content' in configs ? (h("label", { class: "fk-props__field" }, h("span", { class: "fk-props__label" }, fkT('panel.content')), h("textarea", { class: "fk-props__input fk-props__input--textarea", onChange: (event) => this.writeTextConfig('content', event.target.value) }, this.readLocalized(configs.content)))) : null));
3250
- }
3251
- validationRow(validator, label, valueType) {
3252
- const rule = this.validationOf(validator);
3253
- return (h("div", { class: "fk-props__vrule" }, h("label", { class: "fk-props__field fk-props__field--inline" }, h("input", { type: "checkbox", checked: !!rule, onChange: (event) => this.setValidation(validator, event.target.checked) }), h("span", { class: "fk-props__label" }, label)), rule && valueType ? (h("input", { class: "fk-props__input", type: valueType, placeholder: valueType === 'number' ? 'value' : 'regex', value: rule.value == null ? '' : String(rule.value), onChange: (event) => {
3254
- const raw = event.target.value;
3255
- this.setValidation(validator, true, {
3256
- value: valueType === 'number'
3257
- ? raw === ''
3258
- ? undefined
3259
- : Number(raw)
3260
- : raw || undefined,
3261
- });
3262
- } })) : null, rule
3263
- ? this.textField(fkT('panel.errorMessage'), this.readLocalized(rule.message), (value) => this.setValidation(validator, true, {
3264
- message: this.localized(rule.message, value),
3265
- }))
3266
- : null));
3267
- }
3268
- renderValidationTab() {
3269
- var _a;
3270
- const dataType = this.brick.dataType;
3271
- const custom = this.validationOf('custom');
3272
- return (h("section", { class: "fk-props__section" }, this.validationRow('required', fkT('panel.required')), dataType === 'string'
3273
- ? [
3274
- this.validationRow('minLength', fkT('panel.minLength'), 'number'),
3275
- this.validationRow('maxLength', fkT('panel.maxLength'), 'number'),
3276
- this.validationRow('pattern', fkT('panel.pattern'), 'text'),
3277
- this.validationRow('email', fkT('panel.emailFormat')),
3278
- this.validationRow('url', fkT('panel.urlFormat')),
3279
- ]
3280
- : null, dataType === 'number'
3281
- ? [
3282
- this.validationRow('min', fkT('panel.min'), 'number'),
3283
- this.validationRow('max', fkT('panel.max'), 'number'),
3284
- ]
3285
- : null, dataType === 'array'
3286
- ? [
3287
- this.validationRow('minItems', fkT('panel.minItems'), 'number'),
3288
- this.validationRow('maxItems', fkT('panel.maxItems'), 'number'),
3289
- ]
3290
- : null, h("div", { class: "fk-props__vrule" }, h("label", { class: "fk-props__field fk-props__field--inline" }, h("input", { type: "checkbox", checked: !!custom, onChange: (event) => {
3291
- var _a;
3292
- return this.setValidation('custom', event.target.checked, { customValidator: (_a = custom === null || custom === void 0 ? void 0 : custom.customValidator) !== null && _a !== void 0 ? _a : 'return true;' });
3293
- } }), h("span", { class: "fk-props__label" }, fkT('panel.custom'))), custom ? (h("fk-code-editor", { value: (_a = custom.customValidator) !== null && _a !== void 0 ? _a : '', placeholder: 'return value?.startsWith("BJ-") ? true : "Must start with BJ-";', onCodeChange: (event) => this.setValidation('custom', true, {
3294
- customValidator: event.detail,
3295
- }) })) : null, custom
3296
- ? this.textField(fkT('panel.fallbackMessage'), this.readLocalized(custom.message), (value) => this.setValidation('custom', true, {
3297
- message: this.localized(custom.message, value),
3298
- }))
3299
- : null)));
3300
- }
3301
- renderStylesTab() {
3302
- var _a;
3303
- return (h("section", { class: "fk-props__section" }, Object.entries((_a = this.brick.styles) !== null && _a !== void 0 ? _a : {}).map(([key, value]) => (h("div", { class: "fk-props__style-row", key: key }, h("span", { class: "fk-props__style-key" }, key), h("input", { class: "fk-props__input fk-props__input--grow", type: "text", value: String(value !== null && value !== void 0 ? value : ''), onChange: (event) => this.emitStyles({
3304
- [key]: event.target.value,
3305
- }) }), h("button", { type: "button", class: "fk-props__remove", title: "Remove style", onClick: () => this.emitStyles({ [key]: undefined }) }, "\u2715")))), h("div", { class: "fk-props__style-row" }, h("input", { class: "fk-props__input", type: "text", placeholder: fkT('panel.styleProperty'), value: this.newStyleKey, onInput: (event) => (this.newStyleKey = event.target.value) }), h("input", { class: "fk-props__input fk-props__input--grow", type: "text", placeholder: fkT('panel.styleValue'), onChange: (event) => {
3306
- const target = event.target;
3307
- this.addStyle(target.value);
3308
- target.value = '';
3309
- } }))));
3310
- }
3311
- render() {
3312
- return (h("div", { key: '095fc127131cc509f0fb27ae2853042d3ca97e8f', class: "fk-props" }, h("header", { key: '5e5c3eb0cc844dbc023336c93e7b347bc87f5501', class: "fk-props__header" }, h("span", { key: 'f01a54c31c5885741c3671bbcd2bb46ec9deff32', class: "fk-props__type" }, this.brick.type), h("h4", { key: 'a558c48e018a228084eeac289b98e76495d7e630', class: "fk-props__title" }, fkTOr(`brick.${this.brick.id}.name`, this.brick.name))), h("div", { key: 'c11ee0bf0f17754abc00b561fef398bf9cdd9416', class: "fk-props__tabs" }, this.availableTabs().map((tab) => (h("button", { key: tab.id, type: "button", class: {
3313
- 'fk-props__tab': true,
3314
- 'fk-props__tab--active': this.activeTab === tab.id,
3315
- }, onClick: () => (this.activeTab = tab.id) }, tab.label)))), this.activeTab === 'config' ? this.renderConfigTab() : null, this.activeTab === 'validation' ? this.renderValidationTab() : null, this.activeTab === 'styles' ? this.renderStylesTab() : null, this.activeTab === 'rules' ? (h("section", { class: "fk-props__section" }, h("fk-rules-editor", { brick: this.brick, fields: this.fields }))) : null));
3316
- }
3317
- static get watchers() { return {
3318
- "brick": [{
3319
- "onBrickChange": 0
3320
- }]
3321
- }; }
3322
- };
3323
- FkPropertyPanel.style = fkPropertyPanelCss();
3324
-
3325
- const OPERATORS = [
3326
- { id: 'equals', label: 'equals' },
3327
- { id: 'notEquals', label: 'does not equal' },
3328
- { id: 'greaterThan', label: 'is greater than' },
3329
- { id: 'lessThan', label: 'is less than' },
3330
- { id: 'isEmpty', label: 'is empty' },
3331
- { id: 'isNotEmpty', label: 'is not empty' },
3332
- ];
3333
- function buildLogic(condition) {
3334
- const variable = { var: condition.field };
3335
- switch (condition.operator) {
3336
- case 'equals':
3337
- return { '==': [variable, condition.value] };
3338
- case 'notEquals':
3339
- return { '!=': [variable, condition.value] };
3340
- case 'greaterThan':
3341
- return { '>': [variable, condition.value] };
3342
- case 'lessThan':
3343
- return { '<': [variable, condition.value] };
3344
- case 'isEmpty':
3345
- return { '!': variable };
3346
- case 'isNotEmpty':
3347
- return { '!!': variable };
3348
- }
3349
- }
3350
- const varName = (value) => value !== null &&
3351
- typeof value === 'object' &&
3352
- typeof value.var === 'string'
3353
- ? value.var
3354
- : undefined;
3355
- const BINARY_OPERATORS = {
3356
- '==': 'equals',
3357
- '!=': 'notEquals',
3358
- '>': 'greaterThan',
3359
- '<': 'lessThan',
3360
- };
3361
- function parseLogic(logic) {
3362
- if (!logic || typeof logic !== 'object')
3363
- return undefined;
3364
- const entries = Object.entries(logic);
3365
- if (entries.length !== 1)
3366
- return undefined;
3367
- const [operator, args] = entries[0];
3368
- if (operator === '!' || operator === '!!') {
3369
- const field = varName(Array.isArray(args) ? args[0] : args);
3370
- if (!field)
3371
- return undefined;
3372
- return { field, operator: operator === '!' ? 'isEmpty' : 'isNotEmpty' };
3373
- }
3374
- const mapped = BINARY_OPERATORS[operator];
3375
- if (!mapped || !Array.isArray(args) || args.length !== 2)
3376
- return undefined;
3377
- const field = varName(args[0]);
3378
- if (!field)
3379
- return undefined;
3380
- return { field, operator: mapped, value: args[1] };
3381
- }
3382
- function parseValueInput(raw) {
3383
- if (raw === '')
3384
- return '';
3385
- try {
3386
- return JSON.parse(raw);
3387
- }
3388
- catch (_a) {
3389
- return raw;
3390
- }
3391
- }
3392
- function formatValue(value) {
3393
- if (value === undefined)
3394
- return '';
3395
- return typeof value === 'string' ? value : JSON.stringify(value);
3396
- }
3397
-
3398
- const fkRulesEditorCss = () => `.sc-fk-rules-editor-h{display:block}.fk-rules.sc-fk-rules-editor{display:flex;flex-direction:column;gap:var(--fk-spacing)}.fk-rule.sc-fk-rules-editor{display:flex;flex-direction:column;gap:calc(var(--fk-spacing) / 1.5);padding:var(--fk-spacing);border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 1.5);background:color-mix(in srgb, var(--fk-color-surface) 60%, transparent)}.fk-rule__header.sc-fk-rules-editor{display:flex;align-items:center;gap:6px}.fk-rule__name.sc-fk-rules-editor{flex:1;min-width:0;font:inherit;font-size:0.8rem;font-weight:600;padding:4px 6px;border:1px solid transparent;border-radius:calc(var(--fk-radius) / 2);background:transparent;color:var(--fk-color-text)}.fk-rule__name.sc-fk-rules-editor:hover,.fk-rule__name.sc-fk-rules-editor:focus{border-color:var(--fk-color-border);background:var(--fk-color-surface);outline:none}.fk-rule__modes.sc-fk-rules-editor{display:flex;gap:4px}.fk-rule__mode.sc-fk-rules-editor{font:inherit;font-size:0.65rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;padding:3px 8px;border:1px solid var(--fk-color-border);border-radius:999px;background:transparent;color:var(--fk-color-muted);cursor:pointer}.fk-rule__mode--active.sc-fk-rules-editor{border-color:var(--fk-color-primary);background:color-mix(in srgb, var(--fk-color-primary) 12%, transparent);color:var(--fk-color-primary)}.fk-rule__condition.sc-fk-rules-editor,.fk-rule__effect.sc-fk-rules-editor{display:flex;flex-wrap:wrap;align-items:center;gap:4px}.fk-rule__keyword.sc-fk-rules-editor{font-size:0.65rem;font-weight:700;text-transform:uppercase;letter-spacing:0.08em;color:var(--fk-color-muted)}.fk-rule__control.sc-fk-rules-editor{font:inherit;font-size:0.78rem;padding:4px 6px;max-width:100%;min-width:0;border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:var(--fk-color-surface);color:var(--fk-color-text)}.fk-rule__control.sc-fk-rules-editor:focus{outline:none;border-color:var(--fk-color-primary)}.fk-rule__advanced.sc-fk-rules-editor{display:flex;flex-direction:column;gap:4px}.fk-rule__code.sc-fk-rules-editor{font-family:ui-monospace, SFMono-Regular, Menlo, monospace;font-size:0.75rem;min-height:72px;padding:6px 8px;border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:var(--fk-color-surface);color:var(--fk-color-text);resize:vertical}.fk-rule__error.sc-fk-rules-editor{margin:0;font-size:0.72rem;color:var(--fk-color-danger)}.fk-rule__effects.sc-fk-rules-editor{display:flex;flex-direction:column;gap:6px}.fk-rule__remove.sc-fk-rules-editor{border:none;background:transparent;color:var(--fk-color-muted);font-size:0.75rem;cursor:pointer;padding:2px 4px;border-radius:calc(var(--fk-radius) / 2)}.fk-rule__remove.sc-fk-rules-editor:hover{color:var(--fk-color-danger);background:color-mix(in srgb, var(--fk-color-danger) 10%, transparent)}.fk-rule__add.sc-fk-rules-editor{align-self:flex-start;font:inherit;font-size:0.75rem;font-weight:600;padding:4px 10px;border:1px dashed var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:transparent;color:var(--fk-color-muted);cursor:pointer}.fk-rule__add.sc-fk-rules-editor:hover{border-color:var(--fk-color-primary);color:var(--fk-color-primary)}`;
3399
-
3400
- const EFFECT_TARGETS = ['hidden', 'disabled', 'required', 'value'];
3401
- const FkRulesEditor = class {
3402
- constructor(hostRef) {
3403
- registerInstance(this, hostRef);
3404
- this.brickRulesChange = createEvent(this, "brickRulesChange");
3405
- this.fields = [];
3406
- this.forcedModes = {};
3407
- this.jsonErrors = {};
3408
- this.codeErrors = {};
3409
- this.addRule = () => {
3410
- var _a;
3411
- this.commit([
3412
- ...this.rules(),
3413
- {
3414
- name: `Rule ${this.rules().length + 1}`,
3415
- type: 'jsonLogic',
3416
- logic: buildLogic({
3417
- field: (_a = this.fields[0]) !== null && _a !== void 0 ? _a : '',
3418
- operator: 'equals',
3419
- value: '',
3420
- }),
3421
- effects: [{ property: { target: 'hidden', type: 'boolean' }, boolean: true }],
3422
- },
3423
- ]);
3424
- };
3425
- }
3426
- rules() {
3427
- var _a;
3428
- return (_a = this.brick.rules) !== null && _a !== void 0 ? _a : [];
3429
- }
3430
- commit(rules) {
3431
- var _a;
3432
- const uid = (_a = this.brick.configs) === null || _a === void 0 ? void 0 : _a.uid;
3433
- if (!uid)
3434
- return;
3435
- this.brickRulesChange.emit({ rules, uid });
3436
- }
3437
- updateRule(index, patch) {
3438
- this.commit(this.rules().map((rule, i) => (i === index ? Object.assign(Object.assign({}, rule), patch) : rule)));
3439
- }
3440
- removeRule(index) {
3441
- this.commit(this.rules().filter((_, i) => i !== index));
3442
- this.forcedModes = Object.assign(Object.assign({}, this.forcedModes), { [index]: undefined });
3443
- }
3444
- modeOf(index, rule) {
3445
- if (rule.type === 'javaScript')
3446
- return 'javaScript';
3447
- if (this.forcedModes[index])
3448
- return this.forcedModes[index];
3449
- return parseLogic(rule.logic) ? 'simple' : 'json';
3450
- }
3451
- setMode(index, rule, mode) {
3452
- var _a, _b, _c;
3453
- this.forcedModes = Object.assign(Object.assign({}, this.forcedModes), { [index]: mode });
3454
- this.jsonErrors = Object.assign(Object.assign({}, this.jsonErrors), { [index]: '' });
3455
- this.codeErrors = Object.assign(Object.assign({}, this.codeErrors), { [index]: '' });
3456
- if (mode === 'javaScript' && rule.type !== 'javaScript') {
3457
- this.updateRule(index, { type: 'javaScript', code: (_a = rule.code) !== null && _a !== void 0 ? _a : 'return true;' });
3458
- return;
3459
- }
3460
- if (mode !== 'javaScript' && rule.type !== 'jsonLogic') {
3461
- this.updateRule(index, {
3462
- type: 'jsonLogic',
3463
- logic: (_b = rule.logic) !== null && _b !== void 0 ? _b : buildLogic({ field: (_c = this.fields[0]) !== null && _c !== void 0 ? _c : '', operator: 'equals', value: '' }),
3464
- });
3465
- }
3466
- }
3467
- updateCondition(index, rule, patch) {
3468
- var _a, _b;
3469
- const current = (_a = parseLogic(rule.logic)) !== null && _a !== void 0 ? _a : {
3470
- field: (_b = this.fields[0]) !== null && _b !== void 0 ? _b : '',
3471
- operator: 'equals',
3472
- value: '',
3473
- };
3474
- this.updateRule(index, {
3475
- logic: buildLogic(Object.assign(Object.assign({}, current), patch)),
3476
- });
3477
- }
3478
- commitJson(index, raw) {
3479
- try {
3480
- const logic = JSON.parse(raw);
3481
- this.jsonErrors = Object.assign(Object.assign({}, this.jsonErrors), { [index]: '' });
3482
- this.updateRule(index, { logic });
3483
- }
3484
- catch (error) {
3485
- this.jsonErrors = Object.assign(Object.assign({}, this.jsonErrors), { [index]: error instanceof Error ? error.message : String(error) });
3486
- }
3487
- }
3488
- commitCode(index, code) {
3489
- var _a, _b;
3490
- const validation = services.jsRunnerService.validateJs(`(() => {${code}})();`);
3491
- this.codeErrors = Object.assign(Object.assign({}, this.codeErrors), { [index]: validation.valide ? '' : ((_b = (_a = validation.error) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : 'Invalid code') });
3492
- this.updateRule(index, { code });
3493
- }
3494
- updateEffect(ruleIndex, effectIndex, effect) {
3495
- var _a;
3496
- const rule = this.rules()[ruleIndex];
3497
- const effects = ((_a = rule.effects) !== null && _a !== void 0 ? _a : []).map((current, i) => i === effectIndex ? effect : current);
3498
- this.updateRule(ruleIndex, { effects });
3499
- }
3500
- addEffect(ruleIndex) {
3501
- var _a;
3502
- const rule = this.rules()[ruleIndex];
3503
- this.updateRule(ruleIndex, {
3504
- effects: [
3505
- ...((_a = rule.effects) !== null && _a !== void 0 ? _a : []),
3506
- { property: { target: 'hidden', type: 'boolean' }, boolean: true },
3507
- ],
3508
- });
3509
- }
3510
- removeEffect(ruleIndex, effectIndex) {
3511
- var _a;
3512
- const rule = this.rules()[ruleIndex];
3513
- this.updateRule(ruleIndex, {
3514
- effects: ((_a = rule.effects) !== null && _a !== void 0 ? _a : []).filter((_, i) => i !== effectIndex),
3515
- });
3516
- }
3517
- renderCondition(index, rule) {
3518
- var _a, _b;
3519
- const condition = (_a = parseLogic(rule.logic)) !== null && _a !== void 0 ? _a : {
3520
- field: (_b = this.fields[0]) !== null && _b !== void 0 ? _b : '',
3521
- operator: 'equals',
3522
- value: '',
3523
- };
3524
- const needsValue = condition.operator !== 'isEmpty' && condition.operator !== 'isNotEmpty';
3525
- return (h("div", { class: "fk-rule__condition" }, h("span", { class: "fk-rule__keyword" }, fkT('rules.when')), h("select", { class: "fk-rule__control", onChange: (event) => this.updateCondition(index, rule, {
3526
- field: event.target.value,
3527
- }) }, this.fields.map((field) => (h("option", { value: field, selected: field === condition.field }, field)))), h("select", { class: "fk-rule__control", onChange: (event) => this.updateCondition(index, rule, {
3528
- operator: event.target.value,
3529
- }) }, OPERATORS.map((operator) => (h("option", { value: operator.id, selected: operator.id === condition.operator }, operator.label)))), needsValue ? (h("input", { class: "fk-rule__control", type: "text", value: formatValue(condition.value), onChange: (event) => this.updateCondition(index, rule, {
3530
- value: parseValueInput(event.target.value),
3531
- }) })) : null));
3532
- }
3533
- renderEffect(ruleIndex, effect, effectIndex) {
3534
- var _a, _b, _c, _d, _e;
3535
- const target = (_b = (_a = effect.property) === null || _a === void 0 ? void 0 : _a.target) !== null && _b !== void 0 ? _b : 'hidden';
3536
- const type = (_d = (_c = effect.property) === null || _c === void 0 ? void 0 : _c.type) !== null && _d !== void 0 ? _d : 'boolean';
3537
- return (h("div", { class: "fk-rule__effect" }, h("select", { class: "fk-rule__control", onChange: (event) => this.updateEffect(ruleIndex, effectIndex, Object.assign(Object.assign({}, effect), { property: {
3538
- target: event.target.value,
3539
- type: type,
3540
- } })) }, EFFECT_TARGETS.map((candidate) => (h("option", { value: candidate, selected: candidate === target }, candidate)))), h("select", { class: "fk-rule__control", onChange: (event) => {
3541
- const nextType = event.target.value;
3542
- this.updateEffect(ruleIndex, effectIndex, Object.assign({ property: { target, type: nextType } }, (nextType === 'boolean' ? { boolean: true } : { string: '' })));
3543
- } }, h("option", { value: "boolean", selected: type === 'boolean' }, "boolean"), h("option", { value: "string", selected: type === 'string' }, "string")), type === 'boolean' ? (h("select", { class: "fk-rule__control", onChange: (event) => this.updateEffect(ruleIndex, effectIndex, Object.assign(Object.assign({}, effect), { boolean: event.target.value === 'true' })) }, h("option", { value: "true", selected: effect.boolean !== false }, "true"), h("option", { value: "false", selected: effect.boolean === false }, "false"))) : (h("input", { class: "fk-rule__control", type: "text", value: (_e = effect.string) !== null && _e !== void 0 ? _e : '', onChange: (event) => this.updateEffect(ruleIndex, effectIndex, Object.assign(Object.assign({}, effect), { string: event.target.value })) })), h("button", { type: "button", class: "fk-rule__remove", title: fkT('rules.removeEffect'), onClick: () => this.removeEffect(ruleIndex, effectIndex) }, "\u2715")));
3544
- }
3545
- render() {
3546
- return (h("div", { key: '24bddb2835ae3148acc15bef38c855e0b5de0bf8', class: "fk-rules" }, this.rules().map((rule, index) => {
3547
- var _a, _b, _c;
3548
- const mode = this.modeOf(index, rule);
3549
- return (h("article", { class: "fk-rule" }, h("header", { class: "fk-rule__header" }, h("input", { class: "fk-rule__name", type: "text", value: rule.name, onChange: (event) => this.updateRule(index, {
3550
- name: event.target.value,
3551
- }) }), h("button", { type: "button", class: "fk-rule__remove", title: fkT('rules.removeRule'), onClick: () => this.removeRule(index) }, "\u2715")), h("div", { class: "fk-rule__modes" }, ['simple', 'json', 'javaScript'].map((candidate) => (h("button", { type: "button", class: {
3552
- 'fk-rule__mode': true,
3553
- 'fk-rule__mode--active': mode === candidate,
3554
- }, onClick: () => this.setMode(index, rule, candidate) }, fkT(`rules.mode.${candidate === 'javaScript' ? 'js' : candidate}`))))), mode === 'simple' ? this.renderCondition(index, rule) : null, mode === 'json' ? (h("div", { class: "fk-rule__advanced" }, h("textarea", { class: "fk-rule__code", onChange: (event) => this.commitJson(index, event.target.value) }, JSON.stringify((_a = rule.logic) !== null && _a !== void 0 ? _a : null, null, 2)), this.jsonErrors[index] ? (h("p", { class: "fk-rule__error" }, this.jsonErrors[index])) : null)) : null, mode === 'javaScript' ? (h("div", { class: "fk-rule__advanced" }, h("fk-code-editor", { value: (_b = rule.code) !== null && _b !== void 0 ? _b : '', placeholder: "return dataMap.country === 'BJ';", onCodeChange: (event) => this.commitCode(index, event.detail) }), this.codeErrors[index] ? (h("p", { class: "fk-rule__error" }, this.codeErrors[index])) : null)) : null, h("div", { class: "fk-rule__effects" }, h("span", { class: "fk-rule__keyword" }, fkT('rules.then')), ((_c = rule.effects) !== null && _c !== void 0 ? _c : []).map((effect, effectIndex) => this.renderEffect(index, effect, effectIndex)), h("button", { type: "button", class: "fk-rule__add", onClick: () => this.addEffect(index) }, fkT('rules.addEffect')))));
3555
- }), h("button", { key: '55f42fc21a6054d46f53835e0b9638391d12bf6f', type: "button", class: "fk-rule__add", onClick: this.addRule }, fkT('rules.addRule'))));
3556
- }
3557
- };
3558
- FkRulesEditor.style = fkRulesEditorCss();
3559
-
3560
- function interpolateTemplate(template, dataMap) {
3561
- return template.replace(/\{(\w+)\}/g, (_, token) => {
3562
- const value = dataMap === null || dataMap === void 0 ? void 0 : dataMap[token];
3563
- return value === undefined || value === null ? '' : String(value);
3564
- });
3565
- }
3566
- function parseHeaderLines(raw, dataMap) {
3567
- if (typeof raw !== 'string' || !raw.trim())
3568
- return undefined;
3569
- const headers = {};
3570
- for (const line of raw.split('\n')) {
3571
- const separator = line.indexOf(':');
3572
- if (separator <= 0)
3573
- continue;
3574
- const name = line.slice(0, separator).trim();
3575
- const value = interpolateTemplate(line.slice(separator + 1).trim(), dataMap);
3576
- if (name)
3577
- headers[name] = value;
3578
- }
3579
- return Object.keys(headers).length ? headers : undefined;
3580
- }
3581
- function appendSearchParam(url, param, term) {
3582
- if (!term)
3583
- return url;
3584
- const separator = url.includes('?') ? '&' : '?';
3585
- return `${url}${separator}${encodeURIComponent(param)}=${encodeURIComponent(term)}`;
3586
- }
3587
-
3588
- const fkSelectInputCss = () => `.sc-fk-select-input-h{display:block}.fk-select.sc-fk-select-input{position:relative;font-family:var(--fk-font)}.fk-select__trigger.sc-fk-select-input{display:flex;align-items:center;gap:calc(var(--fk-spacing) / 2);min-height:38px;padding:calc(var(--fk-spacing) / 2) var(--fk-spacing);border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface);color:var(--fk-color-text);cursor:pointer}.fk-select--disabled.sc-fk-select-input .fk-select__trigger.sc-fk-select-input{cursor:not-allowed;opacity:0.6}.fk-select__trigger--open.sc-fk-select-input{border-color:var(--fk-color-primary)}.fk-select__values.sc-fk-select-input{display:flex;flex:1;flex-wrap:wrap;align-items:center;gap:4px;min-width:0;font-size:0.9rem}.fk-select__placeholder.sc-fk-select-input{color:var(--fk-color-muted)}.fk-select__chip.sc-fk-select-input{display:inline-flex;align-items:center;gap:4px;padding:1px 8px;border-radius:999px;background:color-mix(in srgb, var(--fk-color-primary) 14%, transparent);color:var(--fk-color-primary);font-size:0.8rem;font-weight:600}.fk-select__chip-remove.sc-fk-select-input,.fk-select__clear.sc-fk-select-input{border:none;background:transparent;color:inherit;font-size:0.7rem;cursor:pointer;padding:0 2px}.fk-select__clear.sc-fk-select-input{color:var(--fk-color-muted)}.fk-select__clear.sc-fk-select-input:hover{color:var(--fk-color-danger)}.fk-select__caret.sc-fk-select-input{color:var(--fk-color-muted);font-size:0.8rem}.fk-select__dropdown.sc-fk-select-input{position:absolute;top:calc(100% + 4px);left:0;right:0;z-index:20;display:flex;flex-direction:column;border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface);box-shadow:0 8px 24px var(--fk-color-shadow);overflow:hidden}.fk-select__search.sc-fk-select-input{font:inherit;font-size:0.85rem;padding:calc(var(--fk-spacing) / 1.5) var(--fk-spacing);border:none;border-bottom:1px solid var(--fk-color-border);background:transparent;color:var(--fk-color-text)}.fk-select__search.sc-fk-select-input:focus{outline:none}.fk-select__options.sc-fk-select-input{max-height:220px;overflow-y:auto}.fk-select__option.sc-fk-select-input{display:flex;align-items:center;justify-content:space-between;gap:var(--fk-spacing);padding:calc(var(--fk-spacing) / 1.5) var(--fk-spacing);font-size:0.9rem;color:var(--fk-color-text);cursor:pointer}.fk-select__option.sc-fk-select-input:hover{background:color-mix(in srgb, var(--fk-color-primary) 8%, transparent)}.fk-select__option--selected.sc-fk-select-input{color:var(--fk-color-primary);font-weight:600}.fk-select__check.sc-fk-select-input{font-size:0.8rem}.fk-select__empty.sc-fk-select-input{margin:0;padding:var(--fk-spacing);font-size:0.85rem;color:var(--fk-color-muted)}.fk-select__trigger.sc-fk-select-input:focus-visible{outline:2px solid color-mix(in srgb, var(--fk-color-primary) 55%, transparent);outline-offset:1px}.fk-select__option--active.sc-fk-select-input{background:color-mix(in srgb, var(--fk-color-primary) 12%, transparent)}`;
3589
-
3590
- let selectInstanceCounter = 0;
3591
- const FkSelectInput = class {
3592
- constructor(hostRef) {
3593
- registerInstance(this, hostRef);
3594
- this.selectValueChange = createEvent(this, "selectValueChange");
3595
- this.disabled = false;
3596
- this.multiple = false;
3597
- this.invalid = false;
3598
- this.open = false;
3599
- this.query = '';
3600
- this.activeIndex = 0;
3601
- this.instanceId = `fk-select-${++selectInstanceCounter}`;
3602
- this.remoteOptions = [];
3603
- this.outsideClick = (event) => {
3604
- if (!this.host.contains(event.target))
3605
- this.close();
3606
- };
3607
- this.onTriggerKeyDown = (event) => {
3608
- if (this.disabled)
3609
- return;
3610
- if (['Enter', ' ', 'ArrowDown', 'ArrowUp'].includes(event.key)) {
3611
- event.preventDefault();
3612
- this.openDropdown();
3613
- }
3614
- else if (event.key === 'Escape' && this.open) {
3615
- event.preventDefault();
3616
- this.close();
3617
- }
3618
- };
3619
- }
3620
- componentWillLoad() {
3621
- return this.resolveRemote();
3622
- }
3623
- disconnectedCallback() {
3624
- this.unbindOutsideClick();
3625
- }
3626
- onConfigsChange() {
3627
- this.resolveRemote();
3628
- }
3629
- onDataMapChange() {
3630
- this.resolveRemote();
3631
- }
3632
- searchParam() {
3633
- var _a;
3634
- return ((_a = this.configs) === null || _a === void 0 ? void 0 : _a.searchParam) || undefined;
3635
- }
3636
- remoteUrl() {
3637
- var _a;
3638
- const raw = (_a = this.configs) === null || _a === void 0 ? void 0 : _a.optionsUrl;
3639
- if (!raw)
3640
- return undefined;
3641
- let url = interpolateTemplate(raw, this.dataMap);
3642
- const param = this.searchParam();
3643
- if (param)
3644
- url = appendSearchParam(url, param, this.query.trim());
3645
- return url;
3646
- }
3647
- bindOutsideClick() {
3648
- document.addEventListener('mousedown', this.outsideClick);
3649
- }
3650
- unbindOutsideClick() {
3651
- document.removeEventListener('mousedown', this.outsideClick);
3652
- }
3653
- toggleOpen() {
3654
- if (this.disabled)
3655
- return;
3656
- if (this.open)
3657
- this.close();
3658
- else
3659
- this.openDropdown();
3660
- }
3661
- openDropdown() {
3662
- if (this.disabled || this.open)
3663
- return;
3664
- this.open = true;
3665
- this.query = '';
3666
- const { options } = this.resolve();
3667
- const selected = this.selectedValues();
3668
- const selectedIndex = options.findIndex((option) => selected.includes(option.value));
3669
- this.activeIndex = selectedIndex >= 0 ? selectedIndex : 0;
3670
- this.bindOutsideClick();
3671
- }
3672
- close(refocusTrigger = false) {
3673
- var _a;
3674
- this.open = false;
3675
- this.unbindOutsideClick();
3676
- if (refocusTrigger)
3677
- (_a = this.triggerEl) === null || _a === void 0 ? void 0 : _a.focus();
3678
- }
3679
- moveActive(delta, count) {
3680
- if (!count)
3681
- return;
3682
- this.activeIndex = (this.activeIndex + delta + count) % count;
3683
- this.scrollActiveIntoView();
3684
- }
3685
- scrollActiveIntoView() {
3686
- requestAnimationFrame(() => {
3687
- var _a;
3688
- const active = this.host.querySelector(`#${this.instanceId}-opt-${this.activeIndex}`);
3689
- (_a = active === null || active === void 0 ? void 0 : active.scrollIntoView) === null || _a === void 0 ? void 0 : _a.call(active, { block: 'nearest' });
3690
- });
3691
- }
3692
- onSearchKeyDown(event, filtered) {
3693
- var _a;
3694
- switch (event.key) {
3695
- case 'ArrowDown':
3696
- event.preventDefault();
3697
- this.moveActive(1, filtered.length);
3698
- break;
3699
- case 'ArrowUp':
3700
- event.preventDefault();
3701
- this.moveActive(-1, filtered.length);
3702
- break;
3703
- case 'Home':
3704
- event.preventDefault();
3705
- this.activeIndex = 0;
3706
- this.scrollActiveIntoView();
3707
- break;
3708
- case 'End':
3709
- event.preventDefault();
3710
- this.activeIndex = Math.max(filtered.length - 1, 0);
3711
- this.scrollActiveIntoView();
3712
- break;
3713
- case 'Enter': {
3714
- event.preventDefault();
3715
- const option = (_a = filtered[this.activeIndex]) !== null && _a !== void 0 ? _a : filtered[0];
3716
- if (option)
3717
- this.pick(option);
3718
- break;
3719
- }
3720
- case 'Escape':
3721
- event.preventDefault();
3722
- this.close(true);
3723
- break;
3724
- case 'Tab':
3725
- this.close();
3726
- break;
3727
- }
3728
- }
3729
- source() {
3730
- var _a, _b;
3731
- return (_b = (_a = this.configs) === null || _a === void 0 ? void 0 : _a.optionsSource) !== null && _b !== void 0 ? _b : 'static';
3732
- }
3733
- async resolveRemote(force = false) {
3734
- var _a;
3735
- if (this.source() !== 'remote')
3736
- return;
3737
- const url = this.remoteUrl();
3738
- if (!url) {
3739
- this.remoteOptions = [];
3740
- return;
3741
- }
3742
- const headers = parseHeaderLines((_a = this.configs) === null || _a === void 0 ? void 0 : _a.optionsHeaders, this.dataMap);
3743
- const signature = `${url}|${JSON.stringify(headers !== null && headers !== void 0 ? headers : {})}`;
3744
- if (!force && signature === this.lastRemoteSignature)
3745
- return;
3746
- this.lastRemoteSignature = signature;
3747
- try {
3748
- this.remoteError = undefined;
3749
- this.remoteOptions = await services.dataSourceService.fetchOptions(url, headers ? { headers } : undefined);
3750
- }
3751
- catch (error) {
3752
- this.remoteOptions = [];
3753
- this.remoteError = error instanceof Error ? error.message : String(error);
3754
- }
3755
- }
3756
- onSearchInput(value) {
3757
- this.query = value;
3758
- if (this.source() !== 'remote' || !this.searchParam())
3759
- return;
3760
- if (this.searchTimer)
3761
- clearTimeout(this.searchTimer);
3762
- this.searchTimer = setTimeout(() => this.resolveRemote(), 250);
3763
- }
3764
- resolve() {
3765
- var _a, _b, _c, _d, _e, _f;
3766
- const labelKey = ((_a = this.configs) === null || _a === void 0 ? void 0 : _a.labelKey) || undefined;
3767
- const valueKey = ((_b = this.configs) === null || _b === void 0 ? void 0 : _b.valueKey) || undefined;
3768
- switch (this.source()) {
3769
- case 'remote':
3770
- return {
3771
- options: normalizeOptions(this.remoteOptions, labelKey, valueKey),
3772
- error: this.remoteError,
3773
- };
3774
- case 'dataMap': {
3775
- const path = (_c = this.configs) === null || _c === void 0 ? void 0 : _c.optionsPath;
3776
- return {
3777
- options: normalizeOptions(path ? (_d = this.dataMap) === null || _d === void 0 ? void 0 : _d[path] : [], labelKey, valueKey),
3778
- };
3779
- }
3780
- case 'js': {
3781
- const code = (_e = this.configs) === null || _e === void 0 ? void 0 : _e.optionsCode;
3782
- if (!code)
3783
- return { options: [] };
3784
- const result = evalBrickCode(code, this.dataMap);
3785
- if (result instanceof Error) {
3786
- return { options: [], error: result.message };
3787
- }
3788
- return { options: normalizeOptions(result, labelKey, valueKey) };
3789
- }
3790
- default:
3791
- return {
3792
- options: normalizeOptions((_f = this.configs) === null || _f === void 0 ? void 0 : _f.options, labelKey, valueKey),
3793
- };
3794
- }
3795
- }
3796
- selectedValues() {
3797
- if (this.multiple) {
3798
- return Array.isArray(this.value) ? this.value : [];
3799
- }
3800
- return typeof this.value === 'string' && this.value !== '' ? [this.value] : [];
3801
- }
3802
- labelOf(value, options) {
3803
- var _a, _b;
3804
- return (_b = (_a = options.find((option) => option.value === value)) === null || _a === void 0 ? void 0 : _a.label) !== null && _b !== void 0 ? _b : value;
3805
- }
3806
- pick(option) {
3807
- if (this.multiple) {
3808
- const selected = this.selectedValues();
3809
- const next = selected.includes(option.value)
3810
- ? selected.filter((value) => value !== option.value)
3811
- : [...selected, option.value];
3812
- this.selectValueChange.emit(next.length ? next : undefined);
3813
- return;
3814
- }
3815
- this.selectValueChange.emit(option.value);
3816
- this.close(true);
3817
- }
3818
- unpick(value) {
3819
- const next = this.selectedValues().filter((entry) => entry !== value);
3820
- this.selectValueChange.emit(next.length ? next : undefined);
3821
- }
3822
- filteredOptions(options) {
3823
- if (this.source() === 'remote' && this.searchParam())
3824
- return options;
3825
- const query = this.query.trim().toLowerCase();
3826
- if (!query)
3827
- return options;
3828
- return options.filter((option) => option.label.toLowerCase().includes(query));
3829
- }
3830
- render() {
3831
- var _a, _b;
3832
- const { options, error } = this.resolve();
3833
- const selected = this.selectedValues();
3834
- const filtered = this.filteredOptions(options);
3835
- return (h("div", { key: 'b891babd7bf125b1e388618ed12be7283136def1', class: { 'fk-select': true, 'fk-select--disabled': this.disabled } }, h("div", { key: 'ef9d0b05e422f78f92a74fcd7dd589c25bc2cbe0', class: { 'fk-select__trigger': true, 'fk-select__trigger--open': this.open }, role: "combobox", tabIndex: this.disabled ? undefined : 0, "aria-expanded": this.open ? 'true' : 'false', "aria-haspopup": "listbox", "aria-controls": `${this.instanceId}-listbox`, "aria-disabled": this.disabled ? 'true' : undefined, "aria-invalid": this.invalid ? 'true' : undefined, ref: (element) => (this.triggerEl = element), onKeyDown: this.onTriggerKeyDown, onClick: (event) => {
3836
- event.preventDefault();
3837
- this.toggleOpen();
3838
- } }, h("div", { key: '9f803f11783a2730865685c34770171a8bf92850', class: "fk-select__values" }, selected.length === 0 ? (h("span", { class: "fk-select__placeholder" }, String((_b = (_a = this.configs) === null || _a === void 0 ? void 0 : _a.placeholder) !== null && _b !== void 0 ? _b : ''))) : this.multiple ? (selected.map((value) => (h("span", { class: "fk-select__chip", key: value }, this.labelOf(value, options), h("button", { type: "button", class: "fk-select__chip-remove", "aria-label": `${fkT('select.clear')} — ${this.labelOf(value, options)}`, disabled: this.disabled, onClick: (event) => {
3839
- event.preventDefault();
3840
- event.stopPropagation();
3841
- this.unpick(value);
3842
- } }, "\u2715"))))) : (h("span", { class: "fk-select__value" }, this.labelOf(selected[0], options)))), !this.multiple && selected.length > 0 && !this.disabled ? (h("button", { type: "button", class: "fk-select__clear", title: fkT('select.clear'), "aria-label": fkT('select.clear'), onClick: (event) => {
3843
- event.preventDefault();
3844
- event.stopPropagation();
3845
- this.selectValueChange.emit(undefined);
3846
- } }, "\u2715")) : null, h("span", { key: '2fabef683d5007a58b1b2c34e7005cd4d3eaef04', class: "fk-select__caret" }, "\u25BE")), this.open ? (h("div", { class: "fk-select__dropdown" }, h("input", { class: "fk-select__search", type: "text", placeholder: fkT('select.search'), value: this.query, role: "combobox", "aria-expanded": "true", "aria-autocomplete": "list", "aria-controls": `${this.instanceId}-listbox`, "aria-activedescendant": filtered.length
3847
- ? `${this.instanceId}-opt-${Math.min(this.activeIndex, filtered.length - 1)}`
3848
- : undefined, ref: (element) => setTimeout(() => element === null || element === void 0 ? void 0 : element.focus(), 0), onInput: (event) => {
3849
- this.activeIndex = 0;
3850
- this.onSearchInput(event.target.value);
3851
- }, onKeyDown: (event) => this.onSearchKeyDown(event, filtered) }), h("div", { class: "fk-select__options", role: "listbox", id: `${this.instanceId}-listbox`, "aria-multiselectable": this.multiple ? 'true' : undefined }, filtered.map((option, index) => {
3852
- const isSelected = selected.includes(option.value);
3853
- const isActive = index === Math.min(this.activeIndex, filtered.length - 1);
3854
- return (h("div", { key: option.value, id: `${this.instanceId}-opt-${index}`, role: "option", "aria-selected": isSelected ? 'true' : 'false', class: {
3855
- 'fk-select__option': true,
3856
- 'fk-select__option--selected': isSelected,
3857
- 'fk-select__option--active': isActive,
3858
- }, onMouseEnter: () => (this.activeIndex = index), onClick: (event) => {
3859
- event.preventDefault();
3860
- this.pick(option);
3861
- } }, h("span", { class: "fk-select__option-label" }, option.label), isSelected ? h("span", { class: "fk-select__check" }, "\u2713") : null));
3862
- }), filtered.length === 0 ? (h("p", { class: "fk-select__empty" }, fkT('select.empty'))) : null))) : null, error ? h("span", { class: "fk-field__error" }, error) : null));
3863
- }
3864
- get host() { return getElement(this); }
3865
- static get watchers() { return {
3866
- "configs": [{
3867
- "onConfigsChange": 0
3868
- }],
3869
- "dataMap": [{
3870
- "onDataMapChange": 0
3871
- }]
3872
- }; }
3873
- };
3874
- FkSelectInput.style = fkSelectInputCss();
3875
-
3876
- const fkSignatureInputCss = () => `.sc-fk-signature-input-h{display:block}.fk-signature.sc-fk-signature-input{display:flex;flex-direction:column;gap:calc(var(--fk-spacing) / 2);align-items:flex-start}.fk-signature__canvas.sc-fk-signature-input{width:100%;max-width:480px;border:1px dashed var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface);color:var(--fk-color-text);touch-action:none;cursor:crosshair}.fk-signature--disabled.sc-fk-signature-input .fk-signature__canvas.sc-fk-signature-input{cursor:not-allowed;opacity:0.6}.fk-signature__clear.sc-fk-signature-input{font:inherit;font-size:0.75rem;padding:3px 10px;border:1px solid var(--fk-color-border);border-radius:calc(var(--fk-radius) / 2);background:transparent;color:var(--fk-color-muted);cursor:pointer}.fk-signature__clear.sc-fk-signature-input:hover:not(:disabled){color:var(--fk-color-danger);border-color:var(--fk-color-danger)}`;
3877
-
3878
- const FkSignatureInput = class {
3879
- constructor(hostRef) {
3880
- registerInstance(this, hostRef);
3881
- this.signatureChange = createEvent(this, "signatureChange");
3882
- this.disabled = false;
3883
- this.drawing = false;
3884
- this.start = (event) => {
3885
- if (this.disabled || !this.canvas)
3886
- return;
3887
- this.drawing = true;
3888
- this.canvas.setPointerCapture(event.pointerId);
3889
- const ctx = this.context();
3890
- if (!ctx)
3891
- return;
3892
- ctx.lineWidth = 2;
3893
- ctx.lineCap = 'round';
3894
- ctx.strokeStyle = getComputedStyle(this.canvas).color;
3895
- ctx.beginPath();
3896
- ctx.moveTo(...this.position(event));
3897
- };
3898
- this.move = (event) => {
3899
- if (!this.drawing)
3900
- return;
3901
- const ctx = this.context();
3902
- if (!ctx)
3903
- return;
3904
- ctx.lineTo(...this.position(event));
3905
- ctx.stroke();
3906
- };
3907
- this.end = () => {
3908
- if (!this.drawing || !this.canvas)
3909
- return;
3910
- this.drawing = false;
3911
- this.lastEmitted = this.canvas.toDataURL('image/png');
3912
- this.signatureChange.emit(this.lastEmitted);
3913
- };
3914
- this.clear = () => {
3915
- const ctx = this.context();
3916
- if (!ctx || !this.canvas)
3917
- return;
3918
- ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
3919
- this.lastEmitted = undefined;
3920
- this.signatureChange.emit(undefined);
3921
- };
3922
- }
3923
- componentDidLoad() {
3924
- this.restore();
3925
- }
3926
- onValueChange(next) {
3927
- if (next === this.lastEmitted)
3928
- return;
3929
- this.restore();
3930
- }
3931
- context() {
3932
- var _a, _b;
3933
- return (_b = (_a = this.canvas) === null || _a === void 0 ? void 0 : _a.getContext('2d')) !== null && _b !== void 0 ? _b : undefined;
3934
- }
3935
- restore() {
3936
- const ctx = this.context();
3937
- if (!ctx || !this.canvas)
3938
- return;
3939
- ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
3940
- if (!this.value)
3941
- return;
3942
- const image = new Image();
3943
- image.onload = () => ctx.drawImage(image, 0, 0);
3944
- image.src = this.value;
3945
- }
3946
- position(event) {
3947
- const rect = this.canvas.getBoundingClientRect();
3948
- return [
3949
- ((event.clientX - rect.left) * this.canvas.width) / rect.width,
3950
- ((event.clientY - rect.top) * this.canvas.height) / rect.height,
3951
- ];
3952
- }
3953
- render() {
3954
- return (h("div", { key: 'e81687b01b30d71794b09cae1eb2215cc10a894f', class: { 'fk-signature': true, 'fk-signature--disabled': this.disabled } }, h("canvas", { key: '9a1031b1c89ee5c9d3ab465b06433125eaa7ee8c', class: "fk-signature__canvas", width: 480, height: 140, ref: (element) => (this.canvas = element), onPointerDown: this.start, onPointerMove: this.move, onPointerUp: this.end, onPointerLeave: this.end }), h("button", { key: '09e36234ffbd7367b65596a1eadf3cb019aeedad', type: "button", class: "fk-signature__clear", disabled: this.disabled, onClick: this.clear }, fkT('signature.clear'))));
3955
- }
3956
- static get watchers() { return {
3957
- "value": [{
3958
- "onValueChange": 0
3959
- }]
3960
- }; }
3961
- };
3962
- FkSignatureInput.style = fkSignatureInputCss();
3963
-
3964
- const fkStepperCss = () => `.sc-fk-stepper-h{display:block}.fk-stepper.sc-fk-stepper{display:flex;flex-direction:column;gap:var(--fk-spacing)}.fk-stepper__nav.sc-fk-stepper{display:flex;flex-wrap:wrap;gap:calc(var(--fk-spacing) * 1.5);margin:0;padding:0 0 var(--fk-spacing);list-style:none;border-bottom:1px solid var(--fk-color-border)}.fk-stepper__step.sc-fk-stepper{display:flex;align-items:center;gap:calc(var(--fk-spacing) / 2);cursor:pointer;color:var(--fk-color-muted);font-size:0.85rem}.fk-stepper__index.sc-fk-stepper{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:50%;border:1px solid var(--fk-color-border);font-size:0.72rem;font-weight:700}.fk-stepper__step--active.sc-fk-stepper{color:var(--fk-color-text);font-weight:600}.fk-stepper__step--active.sc-fk-stepper .fk-stepper__index.sc-fk-stepper{border-color:var(--fk-color-primary);background:var(--fk-color-primary);color:#ffffff}.fk-stepper__step--done.sc-fk-stepper .fk-stepper__index.sc-fk-stepper{border-color:var(--fk-color-primary);color:var(--fk-color-primary)}.fk-stepper__actions.sc-fk-stepper{display:flex;justify-content:space-between;padding-top:var(--fk-spacing);border-top:1px solid var(--fk-color-border)}.fk-stepper__button.sc-fk-stepper{font:inherit;font-size:0.85rem;padding:calc(var(--fk-spacing) / 1.5) calc(var(--fk-spacing) * 1.5);border:1px solid var(--fk-color-border);border-radius:var(--fk-radius);background:var(--fk-color-surface);color:var(--fk-color-text);cursor:pointer}.fk-stepper__button--primary.sc-fk-stepper{border-color:var(--fk-color-primary);background:var(--fk-color-primary);color:#ffffff}.fk-stepper__button.sc-fk-stepper:disabled{opacity:0.45;cursor:not-allowed}.fk-stepper__step-button.sc-fk-stepper{all:unset;display:inline-flex;align-items:center;gap:inherit;cursor:pointer}.fk-stepper__step-button.sc-fk-stepper:focus-visible{outline:2px solid color-mix(in srgb, var(--fk-color-primary) 55%, transparent);outline-offset:2px;border-radius:calc(var(--fk-radius) / 2)}`;
3965
-
3966
- const FkStepper = class {
3967
- constructor(hostRef) {
3968
- registerInstance(this, hostRef);
3969
- this.stepTouch = createEvent(this, "stepTouch");
3970
- this.stepperSubmit = createEvent(this, "stepperSubmit");
3971
- this.stepLabels = [];
3972
- this.editable = false;
3973
- this.active = 0;
3974
- this.next = (event) => {
3975
- event.preventDefault();
3976
- if (this.config('validateSteps', false) && !this.stepValid(this.active)) {
3977
- this.stepTouch.emit({ keys: this.stepKeys(this.active) });
3978
- return;
3979
- }
3980
- this.active = Math.min(this.active + 1, this.stepLabels.length - 1);
3981
- };
3982
- this.back = (event) => {
3983
- event.preventDefault();
3984
- this.active = Math.max(this.active - 1, 0);
3985
- };
3986
- this.submit = (event) => {
3987
- event.preventDefault();
3988
- if (this.config('validateSteps', false) && !this.stepValid(this.active)) {
3989
- this.stepTouch.emit({ keys: this.stepKeys(this.active) });
3990
- return;
3991
- }
3992
- this.stepperSubmit.emit();
3993
- };
3994
- }
3995
- clampActive() {
3996
- if (this.active > Math.max(this.stepLabels.length - 1, 0)) {
3997
- this.active = 0;
3998
- }
3999
- }
4000
- componentDidRender() {
4001
- const body = this.host.querySelector('.fk-stepper__body');
4002
- if (!body)
4003
- return;
4004
- Array.from(body.children).forEach((child, index) => {
4005
- const element = child;
4006
- if (this.editable)
4007
- element.style.removeProperty('display');
4008
- else
4009
- element.style.display = index === this.active ? '' : 'none';
4010
- });
4011
- }
4012
- config(name, fallback) {
4013
- var _a, _b;
4014
- const raw = (_b = (_a = this.spec) === null || _a === void 0 ? void 0 : _a.configs) === null || _b === void 0 ? void 0 : _b[name];
4015
- return typeof raw === 'boolean' ? raw : fallback;
4016
- }
4017
- stepSpec(index) {
4018
- var _a, _b, _c;
4019
- const child = (_b = (_a = this.spec) === null || _a === void 0 ? void 0 : _a.children) === null || _b === void 0 ? void 0 : _b[index];
4020
- if (!child || !this.spec)
4021
- return undefined;
4022
- if (((_c = this.stepCache) === null || _c === void 0 ? void 0 : _c.source) !== this.spec) {
4023
- this.stepCache = { source: this.spec, specs: [] };
4024
- }
4025
- if (!this.stepCache.specs[index]) {
4026
- this.stepCache.specs[index] = {
4027
- type: 'panel',
4028
- id: 'step',
4029
- name: 'Step',
4030
- configs: { key: `step_${index}` },
4031
- children: [child],
4032
- };
4033
- }
4034
- return this.stepCache.specs[index];
4035
- }
4036
- stepKeys(index) {
4037
- var _a, _b, _c;
4038
- const child = (_b = (_a = this.spec) === null || _a === void 0 ? void 0 : _a.children) === null || _b === void 0 ? void 0 : _b[index];
4039
- if (!child)
4040
- return [];
4041
- const keys = [];
4042
- for (const brick of iterateSchemaBricks(child)) {
4043
- if ((_c = brick.configs) === null || _c === void 0 ? void 0 : _c.key)
4044
- keys.push(brick.configs.key);
4045
- }
4046
- return keys;
4047
- }
4048
- stepValid(index) {
4049
- var _a;
4050
- const stepSpec = this.stepSpec(index);
4051
- if (!stepSpec)
4052
- return true;
4053
- const present = Object.fromEntries(Object.entries((_a = this.dataMap) !== null && _a !== void 0 ? _a : {}).filter(([, value]) => value !== '' && value !== null && value !== undefined));
4054
- return validateBrickSpecDataDetailed(stepSpec, present, this.locale).valid;
4055
- }
4056
- goToStep(index) {
4057
- if (this.editable || index <= this.active) {
4058
- this.active = index;
4059
- return;
4060
- }
4061
- if (!this.config('allowStepClick', true))
4062
- return;
4063
- if (this.config('validateSteps', false)) {
4064
- for (let i = this.active; i < index; i++) {
4065
- if (!this.stepValid(i)) {
4066
- this.active = i;
4067
- this.stepTouch.emit({ keys: this.stepKeys(i) });
4068
- return;
4069
- }
4070
- }
4071
- }
4072
- this.active = index;
4073
- }
4074
- render() {
4075
- const lastStep = Math.max(this.stepLabels.length - 1, 0);
4076
- const showSubmit = !this.editable && this.config('showSubmit', false) && this.active === lastStep;
4077
- return (h("div", { key: '3a5a9d1aa6e870241cf5a353359fe89a7c4a376a', class: "fk-stepper" }, h("ol", { key: '8d6b154016d12cd00827b8bddbe4d476dc378fab', class: "fk-stepper__nav" }, this.stepLabels.map((label, index) => (h("li", { key: `${index}-${label}`, class: {
4078
- 'fk-stepper__step': true,
4079
- 'fk-stepper__step--active': index === this.active,
4080
- 'fk-stepper__step--done': !this.editable && index < this.active,
4081
- } }, h("button", { type: "button", class: "fk-stepper__step-button", "aria-current": index === this.active ? 'step' : undefined, onClick: (event) => {
4082
- event.preventDefault();
4083
- this.goToStep(index);
4084
- } }, h("span", { class: "fk-stepper__index" }, index + 1), h("span", { class: "fk-stepper__label" }, label)))))), h("div", { key: 'cd902a9df2d72a4d7f452e7621287df50a89d3c4', class: "fk-stepper__body" }, h("slot", { key: 'ab689448817eaf7b5ddfc9146e18411fe6b5924c' })), !this.editable && this.stepLabels.length > 1 ? (h("div", { class: "fk-stepper__actions" }, h("button", { type: "button", class: "fk-stepper__button", disabled: this.active === 0, onClick: this.back }, fkT('stepper.back')), this.active < lastStep ? (h("button", { type: "button", class: "fk-stepper__button fk-stepper__button--primary", onClick: this.next }, fkT('stepper.next'))) : null, showSubmit ? (h("button", { type: "button", class: "fk-stepper__button fk-stepper__button--primary", onClick: this.submit }, fkT('stepper.submit'))) : null)) : null));
4085
- }
4086
- get host() { return getElement(this); }
4087
- static get watchers() { return {
4088
- "stepLabels": [{
4089
- "clampActive": 0
4090
- }]
4091
- }; }
4092
- };
4093
- FkStepper.style = fkStepperCss();
4094
-
4095
- const fkTabsCss = () => `.sc-fk-tabs-h{display:block}.fk-tabs.sc-fk-tabs{display:flex;flex-direction:column;gap:var(--fk-spacing)}.fk-tabs__nav.sc-fk-tabs{display:flex;flex-wrap:wrap;gap:2px;border-bottom:1px solid var(--fk-color-border)}.fk-tabs__tab.sc-fk-tabs{font:inherit;font-size:0.85rem;font-weight:500;padding:calc(var(--fk-spacing) / 1.5) var(--fk-spacing);border:none;border-bottom:2px solid transparent;background:transparent;color:var(--fk-color-muted);cursor:pointer}.fk-tabs__tab.sc-fk-tabs:hover{color:var(--fk-color-text)}.fk-tabs__tab--active.sc-fk-tabs{color:var(--fk-color-primary);border-bottom-color:var(--fk-color-primary);font-weight:600}`;
4096
-
4097
- const FkTabs = class {
4098
- constructor(hostRef) {
4099
- registerInstance(this, hostRef);
4100
- this.stepTouch = createEvent(this, "stepTouch");
4101
- this.tabLabels = [];
4102
- this.editable = false;
4103
- this.active = 0;
4104
- }
4105
- clampActive() {
4106
- if (this.active > Math.max(this.tabLabels.length - 1, 0)) {
4107
- this.active = 0;
4108
- }
4109
- }
4110
- componentDidRender() {
4111
- const body = this.host.querySelector('.fk-tabs__body');
4112
- if (!body)
4113
- return;
4114
- Array.from(body.children).forEach((child, index) => {
4115
- const element = child;
4116
- if (this.editable)
4117
- element.style.removeProperty('display');
4118
- else
4119
- element.style.display = index === this.active ? '' : 'none';
4120
- });
4121
- }
4122
- validateTabs() {
4123
- var _a, _b;
4124
- return ((_b = (_a = this.spec) === null || _a === void 0 ? void 0 : _a.configs) === null || _b === void 0 ? void 0 : _b.validateTabs) === true;
4125
- }
4126
- tabSpec(index) {
4127
- var _a, _b, _c;
4128
- const child = (_b = (_a = this.spec) === null || _a === void 0 ? void 0 : _a.children) === null || _b === void 0 ? void 0 : _b[index];
4129
- if (!child || !this.spec)
4130
- return undefined;
4131
- if (((_c = this.tabCache) === null || _c === void 0 ? void 0 : _c.source) !== this.spec) {
4132
- this.tabCache = { source: this.spec, specs: [] };
4133
- }
4134
- if (!this.tabCache.specs[index]) {
4135
- this.tabCache.specs[index] = {
4136
- type: 'panel',
4137
- id: 'tab',
4138
- name: 'Tab',
4139
- configs: { key: `tab_${index}` },
4140
- children: [child],
4141
- };
4142
- }
4143
- return this.tabCache.specs[index];
4144
- }
4145
- tabKeys(index) {
4146
- var _a, _b, _c;
4147
- const child = (_b = (_a = this.spec) === null || _a === void 0 ? void 0 : _a.children) === null || _b === void 0 ? void 0 : _b[index];
4148
- if (!child)
4149
- return [];
4150
- const keys = [];
4151
- for (const brick of iterateSchemaBricks(child)) {
4152
- if ((_c = brick.configs) === null || _c === void 0 ? void 0 : _c.key)
4153
- keys.push(brick.configs.key);
4154
- }
4155
- return keys;
4156
- }
4157
- tabValid(index) {
4158
- var _a;
4159
- const tabSpec = this.tabSpec(index);
4160
- if (!tabSpec)
4161
- return true;
4162
- const present = Object.fromEntries(Object.entries((_a = this.dataMap) !== null && _a !== void 0 ? _a : {}).filter(([, value]) => value !== '' && value !== null && value !== undefined));
4163
- return validateBrickSpecDataDetailed(tabSpec, present, this.locale).valid;
4164
- }
4165
- goToTab(index) {
4166
- if (index === this.active)
4167
- return;
4168
- if (!this.editable && this.validateTabs() && !this.tabValid(this.active)) {
4169
- this.stepTouch.emit({ keys: this.tabKeys(this.active) });
4170
- return;
4171
- }
4172
- this.active = index;
4173
- }
4174
- render() {
4175
- return (h("div", { key: 'dc3d42e16d4dd2c948b780326d13afce15bbd908', class: "fk-tabs" }, h("div", { key: 'a5cfd97f5decd63774b9054559f392c5c23447cc', class: "fk-tabs__nav", role: "tablist" }, this.tabLabels.map((label, index) => (h("button", { key: `${index}-${label}`, type: "button", role: "tab", "aria-selected": index === this.active ? 'true' : 'false', tabIndex: index === this.active ? 0 : -1, class: {
4176
- 'fk-tabs__tab': true,
4177
- 'fk-tabs__tab--active': index === this.active,
4178
- }, onKeyDown: (event) => {
4179
- const count = this.tabLabels.length;
4180
- if (!count)
4181
- return;
4182
- if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {
4183
- event.preventDefault();
4184
- const delta = event.key === 'ArrowRight' ? 1 : -1;
4185
- this.goToTab((index + delta + count) % count);
4186
- requestAnimationFrame(() => {
4187
- var _a;
4188
- (_a = this.host.querySelector('.fk-tabs__tab--active')) === null || _a === void 0 ? void 0 : _a.focus();
4189
- });
4190
- }
4191
- }, onClick: (event) => {
4192
- event.preventDefault();
4193
- this.goToTab(index);
4194
- } }, label)))), h("div", { key: 'fe33c5bdfe8a876452850abfd8082b8e4325c355', class: "fk-tabs__body" }, h("slot", { key: 'b3de83a128f36d328c34554cc6df7b1cbeae4761' }))));
4195
- }
4196
- get host() { return getElement(this); }
4197
- static get watchers() { return {
4198
- "tabLabels": [{
4199
- "clampActive": 0
4200
- }]
4201
- }; }
4202
- };
4203
- FkTabs.style = fkTabsCss();
4204
-
4205
- export { FkBrickActions as fk_brick_actions, FkBrickList as fk_brick_list, FkBrickMoldItem as fk_brick_mold_item, FkBrickNotFound as fk_brick_not_found, FkBrickRender as fk_brick_render, FkCodeEditor as fk_code_editor, FkDataGrid as fk_data_grid, FkDropArea as fk_drop_area, FkEmptyForm as fk_empty_form, FkFileInput as fk_file_input, FkFormBuilder as fk_form_builder, FkFormRender as fk_form_render, FkPropertyPanel as fk_property_panel, FkRulesEditor as fk_rules_editor, FkSelectInput as fk_select_input, FkSignatureInput as fk_signature_input, FkStepper as fk_stepper, FkTabs as fk_tabs };