@builder.io/sdk-svelte 0.12.5 → 0.12.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/lib/browser/components/block/animator.d.ts +5 -0
  2. package/lib/browser/components/block/animator.js +243 -0
  3. package/lib/browser/components/block/block.svelte +15 -1
  4. package/lib/browser/components/content/components/enable-editor.svelte +14 -6
  5. package/lib/browser/constants/sdk-version.d.ts +1 -1
  6. package/lib/browser/constants/sdk-version.js +1 -1
  7. package/lib/browser/functions/evaluate/browser-runtime/browser.d.ts +5 -1
  8. package/lib/browser/functions/evaluate/browser-runtime/browser.js +22 -10
  9. package/lib/browser/functions/evaluate/should-force-browser-runtime-in-node.js +0 -4
  10. package/lib/browser/types/builder-block.d.ts +18 -1
  11. package/lib/edge/components/block/animator.d.ts +5 -0
  12. package/lib/edge/components/block/animator.js +243 -0
  13. package/lib/edge/components/block/block.svelte +15 -1
  14. package/lib/edge/components/content/components/enable-editor.svelte +14 -6
  15. package/lib/edge/constants/sdk-version.d.ts +1 -1
  16. package/lib/edge/constants/sdk-version.js +1 -1
  17. package/lib/edge/functions/evaluate/browser-runtime/browser.d.ts +5 -1
  18. package/lib/edge/functions/evaluate/browser-runtime/browser.js +22 -10
  19. package/lib/edge/functions/evaluate/should-force-browser-runtime-in-node.js +0 -4
  20. package/lib/edge/types/builder-block.d.ts +18 -1
  21. package/lib/node/components/block/animator.d.ts +5 -0
  22. package/lib/node/components/block/animator.js +243 -0
  23. package/lib/node/components/block/block.svelte +15 -1
  24. package/lib/node/components/content/components/enable-editor.svelte +14 -6
  25. package/lib/node/constants/sdk-version.d.ts +1 -1
  26. package/lib/node/constants/sdk-version.js +1 -1
  27. package/lib/node/functions/evaluate/browser-runtime/browser.d.ts +5 -1
  28. package/lib/node/functions/evaluate/browser-runtime/browser.js +22 -10
  29. package/lib/node/functions/evaluate/should-force-browser-runtime-in-node.js +0 -4
  30. package/lib/node/types/builder-block.d.ts +18 -1
  31. package/package.json +1 -1
  32. package/src/blocks/embed/embed.svelte +1 -0
  33. package/src/blocks/symbol/symbol.svelte +1 -0
  34. package/src/components/block/animator.ts +254 -0
  35. package/src/components/block/block.svelte +17 -0
  36. package/src/components/content/components/enable-editor.svelte +20 -8
  37. package/src/constants/sdk-version.ts +1 -1
  38. package/src/functions/evaluate/browser-runtime/browser.ts +30 -10
  39. package/src/functions/evaluate/should-force-browser-runtime-in-node.ts +0 -6
  40. package/src/types/builder-block.ts +23 -2
@@ -0,0 +1,254 @@
1
+ import type { BuilderAnimation } from '../../types/builder-block.js';
2
+
3
+ // eslint-disable-next-line @typescript-eslint/ban-types
4
+ function throttle(func: Function, wait: number, options: any = {}) {
5
+ let context: any;
6
+ let args: any;
7
+ let result: any;
8
+ let timeout = (null as any);
9
+ let previous = 0;
10
+ const later = function () {
11
+ previous = options.leading === false ? 0 : Date.now();
12
+ timeout = null;
13
+ result = func.apply(context, args);
14
+ if (!timeout) context = args = null;
15
+ };
16
+ return function (this: any) {
17
+ const now = Date.now();
18
+ if (!previous && options.leading === false) previous = now;
19
+ const remaining = wait - (now - previous);
20
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
21
+ context = this;
22
+ // eslint-disable-next-line prefer-rest-params
23
+ args = arguments;
24
+ if (remaining <= 0 || remaining > wait) {
25
+ if (timeout) {
26
+ clearTimeout(timeout);
27
+ timeout = null;
28
+ }
29
+ previous = now;
30
+ result = func.apply(context, args);
31
+ if (!timeout) context = args = null;
32
+ } else if (!timeout && options.trailing !== false) {
33
+ timeout = setTimeout(later, remaining);
34
+ }
35
+ return result;
36
+ };
37
+ }
38
+ function assign(target: object, ..._args: any[]) {
39
+ const to = Object(target);
40
+ for (let index = 1; index < arguments.length; index++) {
41
+ // eslint-disable-next-line prefer-rest-params
42
+ const nextSource = arguments[index];
43
+ if (nextSource != null) {
44
+ // Skip over if undefined or null
45
+ for (const nextKey in nextSource) {
46
+ // Avoid bugs when hasOwnProperty is shadowed
47
+ if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
48
+ to[nextKey] = nextSource[nextKey];
49
+ }
50
+ }
51
+ }
52
+ }
53
+ return to;
54
+ }
55
+ const camelCaseToKebabCase = (str?: string) => str ? str.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`) : '';
56
+ export function bindAnimations(animations: BuilderAnimation[]) {
57
+ for (const animation of animations) {
58
+ switch (animation.trigger) {
59
+ case 'pageLoad':
60
+ triggerAnimation(animation);
61
+ break;
62
+ case 'hover':
63
+ bindHoverAnimation(animation);
64
+ break;
65
+ case 'scrollInView':
66
+ bindScrollInViewAnimation(animation);
67
+ break;
68
+ }
69
+ }
70
+ }
71
+ function warnElementNotPresent(id: string) {
72
+ console.warn(`Cannot animate element: element with ID ${id} not found!`);
73
+ }
74
+ function augmentAnimation(animation: BuilderAnimation, element: HTMLElement) {
75
+ const stylesUsed = getAllStylesUsed(animation);
76
+ const computedStyle: any = getComputedStyle(element);
77
+ // const computedStyle = getComputedStyle(element);
78
+ // // FIXME: this will break if original load is in one reponsive size then resize to another hmmm
79
+ // Need to use transform instead of left since left can change on screen sizes
80
+ const firstStyles = animation.steps[0].styles;
81
+ const lastStyles = animation.steps[animation.steps.length - 1]!.styles;
82
+ const bothStyles = [firstStyles, lastStyles];
83
+
84
+ // FIXME: this won't work as expected for augmented animations - may need the editor itself to manage this
85
+ for (const styles of bothStyles) {
86
+ for (const style of stylesUsed) {
87
+ if (!(style in styles)) {
88
+ styles[(style as any)] = computedStyle[style];
89
+ }
90
+ }
91
+ }
92
+ }
93
+ function getAllStylesUsed(animation: BuilderAnimation) {
94
+ const properties: (keyof CSSStyleDeclaration)[] = [];
95
+ for (const step of animation.steps) {
96
+ for (const key in step.styles) {
97
+ if (properties.indexOf((key as any)) === -1) {
98
+ properties.push((key as any));
99
+ }
100
+ }
101
+ }
102
+ return properties;
103
+ }
104
+ export function triggerAnimation(animation: BuilderAnimation) {
105
+ // TODO: do for ALL elements
106
+ const elements = (Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || '')) as HTMLElement[]);
107
+ if (!elements.length) {
108
+ warnElementNotPresent(animation.elementId || animation.id || '');
109
+ return;
110
+ }
111
+ Array.from(elements).forEach(element => {
112
+ augmentAnimation(animation, element);
113
+ // TODO: do this properly, may have other animations of different properties
114
+
115
+ // TODO: only override the properties
116
+ // TODO: if there is an entrance and hover animation, the transition duration will get effed
117
+ // element.setAttribute('style', '');
118
+
119
+ // const styledUsed = this.getAllStylesUsed(animation);
120
+ element.style.transition = 'none';
121
+ element.style.transitionDelay = '0';
122
+ assign(element.style, animation.steps[0].styles);
123
+ // TODO: queue/batch these timeouts
124
+ // TODO: only include properties explicitly set in the animation
125
+ // using Object.keys(styles)
126
+ setTimeout(() => {
127
+ element.style.transition = `all ${animation.duration}s ${camelCaseToKebabCase(animation.easing)}`;
128
+ if (animation.delay) {
129
+ element.style.transitionDelay = animation.delay + 's';
130
+ }
131
+ assign(element.style, animation.steps[1].styles);
132
+ // TODO: maybe remove/reset transitoin property after animation duration
133
+
134
+ // TODO: queue timers
135
+ setTimeout(() => {
136
+ // TODO: what if has other transition (reset back to what it was)
137
+ element.style.transition = '';
138
+ element.style.transitionDelay = '';
139
+ }, (animation.delay || 0) * 1000 + animation.duration * 1000 + 100);
140
+ });
141
+ });
142
+ }
143
+ export function bindHoverAnimation(animation: BuilderAnimation) {
144
+ // TODO: is it multiple binding when editing...?
145
+ // TODO: unbind on element remove
146
+ // TODO: apply to ALL elements
147
+ const elements = (Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || '')) as HTMLElement[]);
148
+ if (!elements.length) {
149
+ warnElementNotPresent(animation.elementId || animation.id || '');
150
+ return;
151
+ }
152
+ Array.from(elements).forEach(element => {
153
+ augmentAnimation(animation, element);
154
+ const defaultState = animation.steps[0].styles;
155
+ const hoverState = animation.steps[1].styles;
156
+ function attachDefaultState() {
157
+ assign(element!.style, defaultState);
158
+ }
159
+ function attachHoverState() {
160
+ assign(element!.style, hoverState);
161
+ }
162
+ attachDefaultState();
163
+ element.addEventListener('mouseenter', attachHoverState);
164
+ element.addEventListener('mouseleave', attachDefaultState);
165
+ // TODO: queue/batch these timeouts
166
+ setTimeout(() => {
167
+ element.style.transition = `all ${animation.duration}s ${camelCaseToKebabCase(animation.easing)}`;
168
+ if (animation.delay) {
169
+ element.style.transitionDelay = animation.delay + 's';
170
+ }
171
+ });
172
+ });
173
+ }
174
+
175
+ // TODO: unbind on element remove
176
+ export function bindScrollInViewAnimation(animation: BuilderAnimation) {
177
+ // TODO: apply to ALL matching elements
178
+ const elements = (Array.prototype.slice.call(document.getElementsByClassName(animation.elementId || animation.id || '')) as HTMLElement[]);
179
+ if (!elements.length) {
180
+ warnElementNotPresent(animation.elementId || animation.id || '');
181
+ return;
182
+ }
183
+
184
+ // TODO: if server side rendered and scrolled into view don't animate...
185
+ Array.from(elements).forEach(element => {
186
+ augmentAnimation(animation, element);
187
+ let triggered = false;
188
+ let pendingAnimation = false;
189
+ function immediateOnScroll() {
190
+ if (!triggered && isScrolledIntoView(element)) {
191
+ triggered = true;
192
+ pendingAnimation = true;
193
+ setTimeout(() => {
194
+ assign(element!.style, animation.steps[1].styles);
195
+ if (!animation.repeat) {
196
+ document.removeEventListener('scroll', onScroll);
197
+ }
198
+ setTimeout(() => {
199
+ pendingAnimation = false;
200
+ if (!animation.repeat) {
201
+ element.style.transition = '';
202
+ element.style.transitionDelay = '';
203
+ }
204
+ }, (animation.duration + (animation.delay || 0)) * 1000 + 100);
205
+ });
206
+ } else if (animation.repeat && triggered && !pendingAnimation && !isScrolledIntoView(element)) {
207
+ // we want to repeat the animation every time the the element is out of view and back again
208
+ triggered = false;
209
+ assign(element!.style, animation.steps[0].styles);
210
+ }
211
+ }
212
+
213
+ // TODO: roll all of these in one for more efficiency of checking all the rects
214
+ const onScroll = throttle(immediateOnScroll, 200, {
215
+ leading: false
216
+ });
217
+
218
+ // TODO: fully in view or partially
219
+ function isScrolledIntoView(elem: HTMLElement) {
220
+ const rect = elem.getBoundingClientRect();
221
+ const windowHeight = window.innerHeight;
222
+ const thresholdPercent = (animation.thresholdPercent || 0) / 100;
223
+ const threshold = thresholdPercent * windowHeight;
224
+
225
+ // TODO: partial in view? or what if element is larger than screen itself
226
+ return rect.bottom > threshold && rect.top < windowHeight - threshold // Element is peeking top or bottom
227
+ // (rect.top > 0 && rect.bottom < window.innerHeight) || // element fits within the screen and is fully on screen (not hanging off at all)
228
+ // (rect.top < 0 && rect.bottom > window.innerHeight) // element is larger than the screen and hangs over the top and bottom
229
+ ;
230
+ }
231
+ const defaultState = animation.steps[0].styles;
232
+ function attachDefaultState() {
233
+ assign(element!.style, defaultState);
234
+ }
235
+ attachDefaultState();
236
+
237
+ // TODO: queue/batch these timeouts!
238
+ setTimeout(() => {
239
+ element.style.transition = `all ${animation.duration}s ${camelCaseToKebabCase(animation.easing)}`;
240
+ if (animation.delay) {
241
+ element.style.transitionDelay = animation.delay + 's';
242
+ }
243
+ });
244
+
245
+ // TODO: one listener for everything
246
+ document.addEventListener('scroll', onScroll, ({
247
+ capture: true,
248
+ passive: true
249
+ } as any));
250
+
251
+ // Do an initial check
252
+ immediateOnScroll();
253
+ });
254
+ }
@@ -8,6 +8,7 @@
8
8
  </script>
9
9
 
10
10
  <script lang="ts">
11
+ import { onMount } from "svelte";
11
12
  import { writable } from "svelte/store";
12
13
 
13
14
  import type {
@@ -19,6 +20,7 @@
19
20
  import { getProcessedBlock } from "../../functions/get-processed-block.js";
20
21
  import { getStyle } from "../../functions/get-style.js";
21
22
  import type { BuilderBlock } from "../../types/builder-block.js";
23
+ import { bindAnimations } from "./animator.js";
22
24
  import { getComponent, getRepeatItemData } from "./block.helpers.js";
23
25
  import BlockStyles from "./components/block-styles.svelte";
24
26
  import BlockWrapper from "./components/block-wrapper.svelte";
@@ -122,6 +124,21 @@
122
124
  };
123
125
 
124
126
  let childrenContext = writable($context);
127
+
128
+ onMount(() => {
129
+ const blockId = processedBlock().id;
130
+ const animations = processedBlock().animations;
131
+ if (animations && blockId) {
132
+ bindAnimations(
133
+ animations
134
+ .filter((item) => item.trigger !== "hover")
135
+ .map((animation) => ({
136
+ ...animation,
137
+ elementId: blockId,
138
+ }))
139
+ );
140
+ }
141
+ });
125
142
  </script>
126
143
 
127
144
  {#if canShowBlock()}
@@ -39,6 +39,7 @@
39
39
  import type { BuilderContent } from "../../../types/builder-content.js";
40
40
  import type { ComponentInfo } from "../../../types/components.js";
41
41
  import type { Dictionary } from "../../../types/typescript.js";
42
+ import { triggerAnimation } from "../../block/animator.js";
42
43
  import type {
43
44
  BuilderComponentStateChange,
44
45
  ContentProps,
@@ -114,6 +115,10 @@
114
115
  forceReRenderCount = forceReRenderCount + 1; // This is a hack to force Qwik to re-render.
115
116
  break;
116
117
  }
118
+ case "builder.triggerAnimation": {
119
+ triggerAnimation(data.data);
120
+ break;
121
+ }
117
122
  case "builder.contentUpdate": {
118
123
  const messageContent = data.data;
119
124
  const key =
@@ -343,31 +348,37 @@
343
348
  mergeNewContent(content);
344
349
  }
345
350
  }
351
+
346
352
  $: onUpdateFn_0(...[content]);
347
353
  function onUpdateFn_1(..._args: any[]) {}
354
+
348
355
  $: onUpdateFn_1(...[shouldSendResetCookie]);
349
356
  function onUpdateFn_2(..._args: any[]) {
350
357
  evaluateJsCode();
351
358
  }
352
- $: onUpdateFn_2(
353
- ...[
354
- $builderContextSignal.content?.data?.jsCode,
355
- $builderContextSignal.rootState,
356
- ]
357
- );
359
+ $: onUpdateFn_2_builderContextSignal_content__data__jsCode =
360
+ $builderContextSignal.content?.data?.jsCode;
361
+ $: onUpdateFn_2(...[onUpdateFn_2_builderContextSignal_content__data__jsCode]);
358
362
  function onUpdateFn_3(..._args: any[]) {
359
363
  runHttpRequests();
360
364
  }
361
- $: onUpdateFn_3(...[$builderContextSignal.content?.data?.httpRequests]);
365
+ $: onUpdateFn_3_builderContextSignal_content__data__httpRequests =
366
+ $builderContextSignal.content?.data?.httpRequests;
367
+ $: onUpdateFn_3(
368
+ ...[onUpdateFn_3_builderContextSignal_content__data__httpRequests]
369
+ );
362
370
  function onUpdateFn_4(..._args: any[]) {
363
371
  emitStateUpdate();
364
372
  }
365
- $: onUpdateFn_4(...[$builderContextSignal.rootState]);
373
+ $: onUpdateFn_4_builderContextSignal_rootState =
374
+ $builderContextSignal.rootState;
375
+ $: onUpdateFn_4(...[onUpdateFn_4_builderContextSignal_rootState]);
366
376
  function onUpdateFn_5(..._args: any[]) {
367
377
  if (data) {
368
378
  mergeNewRootState(data);
369
379
  }
370
380
  }
381
+
371
382
  $: onUpdateFn_5(...[data]);
372
383
  function onUpdateFn_6(..._args: any[]) {
373
384
  if (locale) {
@@ -376,6 +387,7 @@
376
387
  });
377
388
  }
378
389
  }
390
+
379
391
  $: onUpdateFn_6(...[locale]);
380
392
 
381
393
  setContext(builderContext.key, builderContextSignal);
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.12.5"
1
+ export const SDK_VERSION = "0.12.7"
@@ -14,27 +14,47 @@ export const runInBrowser = ({
14
14
  builder,
15
15
  context,
16
16
  event,
17
- state: flattenState(rootState, localState, rootSetState)
17
+ state: flattenState({
18
+ rootState,
19
+ localState,
20
+ rootSetState
21
+ })
18
22
  });
19
23
  return new Function(...functionArgs.map(([name]) => name), code)(...functionArgs.map(([, value]) => value));
20
24
  };
21
- export function flattenState(rootState: Record<string | symbol, any>, localState: Record<string | symbol, any> | undefined, rootSetState: ((rootState: BuilderRenderState) => void) | undefined): BuilderRenderState {
22
- if (rootState === localState) {
23
- throw new Error('rootState === localState');
24
- }
25
+ export function flattenState({
26
+ rootState,
27
+ localState,
28
+ rootSetState
29
+ }: {
30
+ rootState: Record<string | symbol, any>;
31
+ localState: Record<string | symbol, any> | undefined;
32
+ rootSetState: ((rootState: BuilderRenderState) => void) | undefined;
33
+ }): BuilderRenderState {
25
34
  return new Proxy(rootState, {
26
- get: (_, prop) => {
35
+ get: (target, prop) => {
27
36
  if (localState && prop in localState) {
28
37
  return localState[prop];
29
38
  }
30
- return rootState[(prop as string)];
39
+ const val = target[prop];
40
+ if (typeof val === 'object') {
41
+ return flattenState({
42
+ rootState: val,
43
+ localState: undefined,
44
+ rootSetState: rootSetState ? subState => {
45
+ target[prop] = subState;
46
+ rootSetState(target);
47
+ } : undefined
48
+ });
49
+ }
50
+ return val;
31
51
  },
32
- set: (_, prop, value) => {
52
+ set: (target, prop, value) => {
33
53
  if (localState && prop in localState) {
34
54
  throw new Error('Writing to local state is not allowed as it is read-only.');
35
55
  }
36
- rootState[(prop as string)] = value;
37
- rootSetState?.(rootState);
56
+ target[prop] = value;
57
+ rootSetState?.(target);
38
58
  return true;
39
59
  }
40
60
  });
@@ -4,13 +4,7 @@ export const shouldForceBrowserRuntimeInNode = () => {
4
4
  if (!isNodeRuntime()) return false;
5
5
  const isArm64 = process.arch === 'arm64';
6
6
  const isNode20 = process.version.startsWith('v20');
7
-
8
- // if the user passed this node option, then the `isolated-vm` package will work
9
7
  const hasNoNodeSnapshotNodeOption = process.env.NODE_OPTIONS?.includes('--no-node-snapshot');
10
-
11
- /**
12
- * https://github.com/laverdet/isolated-vm/issues/424
13
- */
14
8
  if (isArm64 && isNode20 && !hasNoNodeSnapshotNodeOption) {
15
9
  logger.log(`Skipping usage of \`isolated-vm\` to avoid crashes in Node v20 on an arm64 machine.
16
10
  If you would like to use the \`isolated-vm\` package on this machine, please provide the \`NODE_OPTIONS=--no-node-snapshot\` config to your Node process.
@@ -3,7 +3,28 @@ interface JSONObject {
3
3
  [x: string]: JSONValue;
4
4
  }
5
5
  interface JSONArray extends Array<JSONValue> {}
6
-
6
+ export interface AnimationStep {
7
+ // First one is always start state
8
+ // isStartState?: boolean;
9
+ styles: {
10
+ [key: string]: string;
11
+ };
12
+ delay?: number;
13
+ }
14
+ export interface BuilderAnimation {
15
+ elementId: string;
16
+ trigger: string;
17
+ steps: AnimationStep[];
18
+ duration: number;
19
+ delay?: number;
20
+ easing?: string;
21
+ // TODO: deprecate - only here because of an API bug
22
+ id?: string;
23
+ // only apply in scrollInView
24
+ repeat?: boolean;
25
+ // only apply in scrollInView, number from -1 to 1
26
+ thresholdPercent?: number;
27
+ }
7
28
  /** @todo typedoc this */
8
29
  export interface BuilderBlock {
9
30
  '@type': '@builder.io/sdk:Element';
@@ -52,7 +73,7 @@ export interface BuilderBlock {
52
73
  collection: string;
53
74
  itemName?: string;
54
75
  } | null;
55
- animations?: any[]; // TODO: type the animation spec
76
+ animations?: BuilderAnimation[];
56
77
  style?: Partial<CSSStyleDeclaration>;
57
78
  href?: string;
58
79