Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
experimental: Animation reorder keyframes on offset change (#4923)
Ivan Starkov9f0ee54d2662
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsxindex c93070891e..4a4fa7f3ea 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-keyframes.tsx@@ -7,10 +7,13 @@ import {Label,Separator,Tooltip,+ ScrollArea,+ theme,+ Box,} from "@webstudio-is/design-system";import { MinusIcon, PlusIcon } from "@webstudio-is/icons";import type { AnimationKeyframe } from "@webstudio-is/sdk";-import { Fragment, useMemo, useState } from "react";+import { Fragment, useMemo, useRef, useState } from "react";import {CssValueInput,type IntermediateStyleValue,@@ -18,6 +21,7 @@ import {import { toKebabCase } from "~/builder/features/style-panel/shared/keyword-utils";import { CodeEditor } from "~/builder/shared/code-editor";import { useIds } from "~/shared/form-utils";+import { calcOffsets, findInsertionIndex, moveItem } from "./keyframe-helpers";const unitOptions = [{@@ -30,10 +34,12 @@ const unitOptions = [const OffsetInput = ({id,value,+ placeholder,onChange,}: {id: string;value: number | undefined;+ placeholder: number;onChange: (value: number | undefined) => void;}) => {const [intermediateValue, setIntermediateValue] = useState<@@ -43,7 +49,11 @@ const OffsetInput = ({return (<CssValueInputid={id}- placeholder="auto"+ placeholder={+ value === undefined+ ? `auto (${Math.round(placeholder * 1000) / 10}%)`+ : "auto"+ }getOptions={() => []}unitOptions={unitOptions}intermediateValue={intermediateValue}@@ -107,9 +117,11 @@ const OffsetInput = ({const Keyframe = ({value,+ offsetPlaceholder,onChange,}: {value: AnimationKeyframe;+ offsetPlaceholder: number;onChange: (value: AnimationKeyframe | undefined) => void;}) => {const ids = useIds(["offset"]);@@ -133,6 +145,7 @@ const Keyframe = ({<OffsetInputid={ids.offset}value={value.offset}+ placeholder={offsetPlaceholder}onChange={(offset) => {onChange({ ...value, offset });}}@@ -176,43 +189,97 @@ export const Keyframes = ({}) => {const ids = useIds(["addKeyframe"]);+ // To preserve focus on children swap+ const keyRefs = useRef(+ Array.from({ length: keyframes.length }, (_, index) => index)+ );++ if (keyframes.length !== keyRefs.current.length) {+ keyRefs.current = Array.from(+ { length: keyframes.length },+ (_, index) => index+ );+ }++ const offsets = calcOffsets(keyframes);+return (- <Grid gap={2}>- <Grid gap={1} align={"center"} css={{ gridTemplateColumns: "1fr auto" }}>+ <Grid+ css={{+ minHeight: 0,+ }}+ gap={1}+ >+ <Grid+ gap={1}+ align={"center"}+ css={{+ paddingInline: theme.panel.paddingInline,+ gridTemplateColumns: "1fr auto",+ }}+ ><Label htmlFor={ids.addKeyframe}><Text variant={"titles"}>Keyframes</Text></Label><IconButtonid={ids.addKeyframe}- onClick={() =>- onChange([...keyframes, { offset: undefined, styles: {} }])- }+ onClick={() => {+ onChange([...keyframes, { offset: undefined, styles: {} }]);+ keyRefs.current = [...keyRefs.current, keyframes.length];+ }}><PlusIcon /></IconButton></Grid>+ <Box+ css={{+ paddingInline: theme.panel.paddingInline,+ }}+ >+ <Separator />+ </Box>++ <ScrollArea>+ <Grid gap={2} css={{ padding: theme.panel.padding }}>+ {keyframes.map((value, index) => (+ <Fragment key={keyRefs.current[index]}>+ {index > 0 && <Separator />}+ <Keyframe+ key={keyRefs.current[index]}+ value={value}+ offsetPlaceholder={offsets[index]}+ onChange={(newValue) => {+ if (newValue === undefined) {+ const newValues = [...keyframes];+ newValues.splice(index, 1);+ onChange(newValues);+ return;+ }++ let newValues = [...keyframes];+ newValues[index] = newValue;++ const { offset } = newValue;+ if (offset === undefined) {+ onChange(newValues);+ return;+ }++ const insertionIndex = findInsertionIndex(newValues, index);+ newValues = moveItem(newValues, index, insertionIndex);+ keyRefs.current = moveItem(+ keyRefs.current,+ index,+ insertionIndex+ );- {keyframes.map((value, index) => (- <Fragment key={index}>- <Separator />- <Keyframe- key={index}- value={value}- onChange={(newValue) => {- if (newValue === undefined) {- const newValues = [...keyframes];- newValues.splice(index, 1);- onChange(newValues);- return;- }-- const newValues = [...keyframes];- newValues[index] = newValue;- onChange(newValues);- }}- />- </Fragment>- ))}+ onChange(newValues);+ }}+ />+ </Fragment>+ ))}+ </Grid>+ </ScrollArea></Grid>);};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsxindex 96239dc4ce..60f1fb1897 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-panel-content.tsx@@ -1,5 +1,6 @@import {Box,+ Flex,Grid,Label,Select,@@ -40,12 +41,12 @@ const fillModeDescriptions: Record<NonNullable<ViewAnimation["timing"]["fill"]>,string> = {- none: "No animation is applied before or after the active period",- forwards:- "The animation state is applied after the active period. Prefered for Out Animations",+ both: "The animation state is applied before and after the active period. Set if unsure whether it's In or Out.",backwards:"The animation state is applied before the active period. Prefered for In Animations",- both: "The animation state is applied before and after the active period",+ forwards:+ "The animation state is applied after the active period. Prefered for Out Animations",+ none: "No animation is applied before or after the active period.",};const fillModeNames = Object.keys(fillModeDescriptions) as NonNullable<@@ -223,9 +224,22 @@ export const AnimationPanelContent = ({ onChange, value, type }: Props) => {toast.error("Animation schema is incompatible, try fix");};+ // Flex is used to allow the Keyframes to overflow without setting+ // gridTemplateRows: auto auto 1frreturn (- <Grid gap="2" css={{ padding: theme.panel.padding }}>- <Grid gap={1} align={"center"} css={{ gridTemplateColumns: "1fr 1fr" }}>+ <Flex+ gap="2"+ direction="column"+ css={{+ maxHeight: "60dvh",+ paddingBottom: theme.panel.paddingBlock,+ }}+ >+ <Grid+ gap={1}+ align={"center"}+ css={{ gridTemplateColumns: "1fr 1fr", padding: theme.panel.padding }}+ ><Label htmlFor={fieldIds.fill}>Fill Mode</Label><Label htmlFor={fieldIds.easing}>Easing</Label><Select@@ -270,7 +284,11 @@ export const AnimationPanelContent = ({ onChange, value, type }: Props) => {}}/></Grid>- <Grid gap={1} align={"center"} css={{ gridTemplateColumns: "2fr 1fr" }}>+ <Grid+ gap={1}+ align={"center"}+ css={{ gridTemplateColumns: "2fr 1fr", padding: theme.panel.padding }}+ ><Label htmlFor={fieldIds.rangeStartName}>Range Start</Label><Label htmlFor={fieldIds.rangeStartValue}>Value</Label>@@ -405,6 +423,6 @@ export const AnimationPanelContent = ({ onChange, value, type }: Props) => {value={value.keyframes}onChange={(keyframes) => handleChange({ ...value, keyframes })}/>- </Grid>+ </Flex>);};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsxindex a4b3507ec0..93164ccc2a 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animation-section.tsx@@ -47,7 +47,7 @@ const animationTypes: AnimationAction["type"][] = Object.keys() as AnimationAction["type"][];const defaultActionValue: AnimationAction = {- type: "scroll",+ type: "view",animations: [],};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/keyframe-helpers.test.ts b/apps/builder/app/builder/features/settings-panel/props-section/animation/keyframe-helpers.test.tsnew file mode 100644index 0000000000..c524cb6ed6--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/keyframe-helpers.test.ts@@ -0,0 +1,235 @@+import { describe, test, expect } from "vitest";+import { calcOffsets, findInsertionIndex, moveItem } from "./keyframe-helpers";++describe("calcOffsets", () => {+ test("returns empty array for empty input", () => {+ expect(calcOffsets([])).toEqual([]);+ });++ test("handles array with all offsets defined", () => {+ const keyframes = [{ offset: 0 }, { offset: 0.5 }, { offset: 1 }];+ expect(calcOffsets(keyframes)).toEqual([0, 0.5, 1]);+ });++ test("adds implicit start and end offsets", () => {+ const keyframes = [+ { offset: undefined },+ { offset: 0.5 },+ { offset: undefined },+ ];+ expect(calcOffsets(keyframes)).toEqual([0, 0.5, 1]);+ });++ test("interpolates missing middle offsets", () => {+ const keyframes = [{ offset: 0 }, { offset: undefined }, { offset: 1 }];+ expect(calcOffsets(keyframes)).toEqual([0, 0.5, 1]);+ });++ test("handles multiple gaps in offsets", () => {+ const keyframes = [+ { offset: 0 },+ { offset: undefined },+ { offset: undefined },+ { offset: undefined },+ { offset: 1 },+ ];+ expect(calcOffsets(keyframes)).toEqual([0, 0.25, 0.5, 0.75, 1]);+ });++ test("handles multiple gaps in offsets", () => {+ const keyframes = [+ { offset: 0 },+ { offset: undefined },+ { offset: undefined },+ { offset: 0.51 },+ { offset: undefined },+ { offset: 1 },+ ];++ expect(calcOffsets(keyframes)).toEqual([0, 0.17, 0.34, 0.51, 0.755, 1]);+ });++ test("handles multiple gaps in offsets", () => {+ const keyframes = [+ { offset: 0 },+ { offset: undefined },+ { offset: undefined },+ { offset: undefined },+ { offset: undefined },+ { offset: 0.5 },+ { offset: undefined },+ { offset: undefined },+ { offset: undefined },+ { offset: undefined },+ { offset: 1 },+ ];++ expect(calcOffsets(keyframes)).toEqual([+ 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1,+ ]);+ });+});++describe("findInsertionIndex", () => {+ test("should keep current index when it's in the correct position", () => {+ const keyframes = [+ { offset: 0 },+ { offset: 0.5, current: true },+ { offset: 0.7 },+ { offset: 1 },+ ];+ const currentIndex = keyframes.findIndex((k) => k.current)!;++ expect(+ moveItem(+ keyframes,+ currentIndex,+ findInsertionIndex(keyframes, currentIndex)+ )+ ).toEqual(keyframes);+ });++ test("should move index forward when current position is too early", () => {+ const keyframes = [+ { offset: 0 },+ { offset: 0.8, current: true },+ { offset: 0.7 },+ { offset: 1 },+ ];+ const currentIndex = keyframes.findIndex((k) => k.current)!;++ expect(+ moveItem(+ keyframes,+ currentIndex,+ findInsertionIndex(keyframes, currentIndex)+ )+ ).toEqual([+ { offset: 0 },+ { offset: 0.7 },+ { offset: 0.8, current: true },+ { offset: 1 },+ ]);+ });++ test("should move index backward when current position is too late", () => {+ const keyframes = [+ { offset: 0 },+ { offset: 0.3 },+ { offset: 0.7 },+ { offset: 0.35, current: true },+ ];+ const currentIndex = keyframes.findIndex((k) => k.current)!;++ expect(+ moveItem(+ keyframes,+ currentIndex,+ findInsertionIndex(keyframes, currentIndex)+ )+ ).toEqual([+ { offset: 0 },+ { offset: 0.3 },+ { offset: 0.35, current: true },+ { offset: 0.7 },+ ]);+ });++ test("should move index backward at 1 when current position is too late", () => {+ const keyframes = [+ { offset: 0 },+ { offset: 0.3 },+ { offset: 0.7 },+ { offset: 0, current: true },+ ];+ const currentIndex = keyframes.findIndex((k) => k.current)!;++ expect(+ moveItem(+ keyframes,+ currentIndex,+ findInsertionIndex(keyframes, currentIndex)+ )+ ).toEqual([+ { offset: 0 },+ { offset: 0, current: true },+ { offset: 0.3 },+ { offset: 0.7 },+ ]);+ });++ test("should move index backward at 0 when current position is too late", () => {+ const keyframes = [+ { offset: 0.1 },+ { offset: 0.3 },+ { offset: 0.7 },+ { offset: 0, current: true },+ ];+ const currentIndex = keyframes.findIndex((k) => k.current)!;++ expect(+ moveItem(+ keyframes,+ currentIndex,+ findInsertionIndex(keyframes, currentIndex)+ )+ ).toEqual([+ { offset: 0, current: true },+ { offset: 0.1 },+ { offset: 0.3 },+ { offset: 0.7 },+ ]);+ });++ test("should preserve position with undefined around", () => {+ const keyframes = [+ { offset: 0 },+ { offset: undefined },+ { offset: 0.2, current: true },+ { offset: undefined },+ ];+ const currentIndex = keyframes.findIndex((k) => k.current)!;++ expect(+ moveItem(+ keyframes,+ currentIndex,+ findInsertionIndex(keyframes, currentIndex)+ )+ ).toEqual([+ { offset: 0 },+ { offset: undefined },+ { offset: 0.2, current: true },+ { offset: undefined },+ ]);+ });++ test("should move position with undefined around if needed", () => {+ const keyframes = [+ { offset: 0 },+ { offset: undefined },+ { offset: 0.5, current: true },+ { offset: undefined },+ { offset: 0.3 },+ { offset: undefined },+ { offset: undefined },+ ];+ const currentIndex = keyframes.findIndex((k) => k.current)!;++ expect(+ moveItem(+ keyframes,+ currentIndex,+ findInsertionIndex(keyframes, currentIndex)+ )+ ).toEqual([+ { offset: 0 },+ { offset: undefined },+ { offset: undefined },+ { offset: 0.3 },+ { offset: 0.5, current: true },+ { offset: undefined },+ { offset: undefined },+ ]);+ });+});diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/keyframe-helpers.ts b/apps/builder/app/builder/features/settings-panel/props-section/animation/keyframe-helpers.tsnew file mode 100644index 0000000000..4467623326--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/keyframe-helpers.ts@@ -0,0 +1,98 @@+const multiplier = 10000;++export const calcOffsets = (+ keyframes: { offset?: number | undefined }[]+): number[] => {+ if (keyframes.length === 0) {+ return [];+ }++ const offsets = keyframes.map((k) =>+ k.offset !== undefined ? k.offset * multiplier : undefined+ );+ if (offsets[0] === undefined) {+ offsets[0] = 0;+ }++ if (offsets.at(-1) === undefined) {+ offsets[offsets.length - 1] = 1 * multiplier;+ }++ let prev = 0;++ for (let i = 1; i < offsets.length - 1; ) {+ if (offsets[i] !== undefined) {+ prev = i;+ i++;+ continue;+ }++ if (offsets[i] === undefined) {+ const next = offsets.findIndex((v, vi) => vi >= i && v !== undefined);++ const step = (offsets[next]! - offsets[prev]!) / (next - prev);++ for (let j = prev + 1; j < next; j++) {+ offsets[j] = offsets[j - 1]! + step; // offsets[prev]! + step * (j - prev);+ }+ prev = next;++ i = next + 1;+ }+ }+ return offsets.map((v) => v! / multiplier);+};++// [0, undefined, undefined, 0.5, undefined, 1]+export const findInsertionIndex = (+ keyframes: { offset?: number | undefined }[],+ currentIndex: number+) => {+ const offset = keyframes[currentIndex].offset;+ if (offset === undefined) {+ return currentIndex;+ }++ // There are 2 ways to approach this. Using calcOffsets to find the index would be technically more correct,+ // as it would place the keyframe in the right position. However, visually placing something between "auto" keyframes+ // is not very intuitive. Let's try the "visually correct" way first.++ // Check ordering+ const minLastIndex = keyframes.findLastIndex(+ (keyframe, keyframeIndex) =>+ keyframeIndex !== currentIndex &&+ keyframe.offset !== undefined &&+ keyframe.offset < offset+ );++ const maxFirstIndex = keyframes.findIndex(+ (keyframe, keyframeIndex) =>+ keyframeIndex !== currentIndex &&+ keyframe.offset !== undefined &&+ keyframe.offset > offset+ );++ if (currentIndex < minLastIndex) {+ // [0, 0.5, 0.6, 1], currentIndex = 1, offset = 0.8+ return minLastIndex;+ }++ if (currentIndex > maxFirstIndex && maxFirstIndex !== -1) {+ // [0, 0.5, 0.6, 1], currentIndex = 2, offset = 0.4+ return maxFirstIndex;+ }++ // Do nothing if the current index is already in the right place+ return currentIndex;+};++export const moveItem = <T>(+ keyframes: T[],+ currentIndex: number,+ newIndex: number+): T[] => {+ const newKeyframes = [...keyframes];+ const [keyframe] = newKeyframes.splice(currentIndex, 1);+ newKeyframes.splice(newIndex, 0, keyframe);+ return newKeyframes;+};diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/new-scroll-animations.ts b/apps/builder/app/builder/features/settings-panel/props-section/animation/new-scroll-animations.tsindex d2f23f9e92..33aaa3a201 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/new-scroll-animations.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/new-scroll-animations.ts@@ -8,7 +8,7 @@ const newScrollAnimation: ScrollAnimation = {timing: {rangeStart: ["start", { type: "unit", value: 0, unit: "px" }],rangeEnd: ["end", { type: "unit", value: 0, unit: "px" }],- fill: "backwards",+ fill: "both",easing: "linear",},keyframes: [diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/new-view-animations.ts b/apps/builder/app/builder/features/settings-panel/props-section/animation/new-view-animations.tsindex 76cd77ddb0..f721214a09 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/new-view-animations.ts+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/new-view-animations.ts@@ -6,9 +6,9 @@ const newViewAnimation: ViewAnimation = {description: "Create a new animation.",timing: {- rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],- rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],- fill: "backwards",+ rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],+ rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],+ fill: "both",easing: "linear",},keyframes: [diff --git a/apps/builder/tsconfig.json b/apps/builder/tsconfig.jsonindex 0dcd9e22e2..34474f526e 100644--- a/apps/builder/tsconfig.json+++ b/apps/builder/tsconfig.json@@ -3,6 +3,7 @@"include": ["app", "**/*.ts", "**/*.tsx", "../../@types/**/*.d.ts"],"compilerOptions": {+ "target": "ES2023","types": ["@remix-run/node","vite/client",