Skip to content

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.

undo/redo for styles + shortcut forwarding from parent window

Oleg Isonencc6c9a6c0c28
diff --git a/app/canvas/features/wrapper-component/use-css.tsx b/app/canvas/features/wrapper-component/use-css.tsx
index 4e75ad8f61..42a12b2f31 100644
--- a/app/canvas/features/wrapper-component/use-css.tsx
+++ b/app/canvas/features/wrapper-component/use-css.tsx
@@ -1,7 +1,13 @@
-import { useMemo } from "react";
-import { type Instance, css as createCss, type CSS } from "@webstudio-is/sdk";
+import { useEffect, useMemo, useState } from "react";
+import {
+ type Instance,
+ css as createCss,
+ type CSS,
+ useSubscribe,
+ toValue,
+} from "@webstudio-is/sdk";
import { useDropData, useSelectedInstance } from "~/canvas/shared/nano-values";
-import { primitives } from "~/shared/component";
+import { primitives, type StyleUpdates } from "~/shared/component";
// @todo this doesn't work with the node at the top edge of the iframe, tag gets hidden.
const componentTagStyle = {
@@ -55,9 +61,40 @@ type UseCssProps = {
css: CSS;
};
+type UpdatesReset = Array<{
+ property: string;
+ value: undefined;
+}>;
+
+const usePreviewCss = ({ instance, css }: UseCssProps) => {
+ const [previewCss, setPreviewCss] = useState<
+ StyleUpdates["updates"] | UpdatesReset
+ >([]);
+
+ useSubscribe<string, StyleUpdates>(
+ `previewStyle:${instance.id}`,
+ ({ updates }) => {
+ setPreviewCss(updates);
+ }
+ );
+
+ useEffect(() => {
+ const reset = previewCss.map(({ property }) => ({
+ property,
+ value: undefined,
+ }));
+ setPreviewCss(reset);
+ // previewCss in deps leads to an infinite loop
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [css]);
+
+ return previewCss;
+};
+
export const useCss = ({ instance, css }: UseCssProps): string => {
const [dropData] = useDropData();
const [selectedInstance] = useSelectedInstance();
+ const previewCss = usePreviewCss({ instance, css });
return useMemo(() => {
const primitive = primitives[instance.component];
@@ -76,6 +113,16 @@ export const useCss = ({ instance, css }: UseCssProps): string => {
}
}
+ for (const update of previewCss) {
+ // Delete ephemeral value
+ if (update.value === undefined) {
+ delete overrides[update.property];
+ continue;
+ }
+ // @todo workaround for Expression produces a union type that is too complex to represent.
+ overrides[update.property as string] = toValue(update.value);
+ }
+
return createCss(css)({ css: overrides });
- }, [dropData, selectedInstance, css, instance]);
+ }, [dropData, selectedInstance, css, previewCss, instance]);
};
diff --git a/app/canvas/shared/style.ts b/app/canvas/shared/style.ts
index 7db3e3337d..29772d1abb 100644
--- a/app/canvas/shared/style.ts
+++ b/app/canvas/shared/style.ts
@@ -1,24 +1,21 @@
+import { createTransaction } from "~/lib/sync-engine";
import { type StyleUpdates } from "~/shared/component";
-import { setInstanceStyle } from "~/shared/tree-utils";
-import { useRootInstance, useSelectedInstance } from "./nano-values";
+import { setInstanceStyleMutable } from "~/shared/tree-utils";
+import { rootInstanceContainer, useSelectedInstance } from "./nano-values";
import { useSubscribe } from "./pubsub";
export const useUpdateInstanceStyle = () => {
- const [rootInstance, setRootInstance] = useRootInstance();
const [selectedInstance] = useSelectedInstance();
- useSubscribe<"updateStyles", StyleUpdates>("updateStyles", (styleUpdates) => {
- if (
- rootInstance === undefined ||
- styleUpdates.id !== selectedInstance?.id
- ) {
- return;
+ useSubscribe<"updateStyle", StyleUpdates>(
+ "updateStyle",
+ ({ id, updates }) => {
+ createTransaction([rootInstanceContainer], (rootInstance) => {
+ if (rootInstance === undefined || id !== selectedInstance?.id) {
+ return;
+ }
+ setInstanceStyleMutable(rootInstance, id, updates);
+ });
}
- const updatedRoot = setInstanceStyle(
- rootInstance,
- styleUpdates.id,
- styleUpdates.updates
- );
- setRootInstance(updatedRoot);
- });
+ );
};
diff --git a/app/canvas/shared/use-shortcuts.ts b/app/canvas/shared/use-shortcuts.ts
index ccebf53e9c..28105915de 100644
--- a/app/canvas/shared/use-shortcuts.ts
+++ b/app/canvas/shared/use-shortcuts.ts
@@ -1,8 +1,14 @@
import { useHotkeys } from "react-hotkeys-hook";
import { type Instance } from "@webstudio-is/sdk";
import { useRootInstance, useSelectedInstance } from "./nano-values";
-import { publish } from "./pubsub";
+import { publish, useSubscribe } from "./pubsub";
import { redo, undo } from "~/lib/sync-engine";
+import { shortcuts } from "~/shared/shortcuts";
+
+const shortcutHandlerMap = {
+ undo,
+ redo,
+} as const;
export const useShortcuts = () => {
const [rootInstance] = useRootInstance();
@@ -43,15 +49,20 @@ export const useShortcuts = () => {
useHotkeys(
// Undo
- "cmd+z, ctrl+z",
- undo,
+ shortcuts.undo,
+ shortcutHandlerMap.undo,
[]
);
useHotkeys(
// Redo
- "cmd+shift+z, ctrl+shift+z",
- redo,
+ shortcuts.redo,
+ shortcutHandlerMap.redo,
[]
);
+
+ // Shortcuts from the parent window
+ useSubscribe<"shortcut", keyof typeof shortcuts>("shortcut", (shortcut) => {
+ shortcutHandlerMap[shortcut]();
+ });
};
diff --git a/app/designer/designer.tsx b/app/designer/designer.tsx
index 37c36d24a2..7030d336df 100644
--- a/app/designer/designer.tsx
+++ b/app/designer/designer.tsx
@@ -23,6 +23,7 @@ import designerStyles from "./designer.css";
import { useSync } from "./features/sync";
import { Breadcrumbs } from "./features/breadcrumbs";
import { TreePrevew } from "./features/tree-preview";
+import { usePublishShortcuts } from "./shared/shortcuts/use-publish-shortcuts";
export const links = () => {
return [
@@ -139,6 +140,7 @@ export const Designer = ({ config, project }: DesignerProps) => {
const [isDragging, setIsDragging] = useState<boolean>();
const [publish, iframeRef] = usePublish();
const [isPreviewMode] = useIsPreviewMode();
+ usePublishShortcuts(publish);
useSubscribe<"dragStartInstance">("dragStartInstance", () => {
setIsDragging(true);
diff --git a/app/designer/features/style-panel/lib/autocomplete.tsx b/app/designer/features/style-panel/lib/autocomplete.tsx
index 3a2bc9590a..5ec3d0c515 100644
--- a/app/designer/features/style-panel/lib/autocomplete.tsx
+++ b/app/designer/features/style-panel/lib/autocomplete.tsx
@@ -25,15 +25,15 @@ const findIndex = (items: Items, value: string, exact = false): number => {
return items.indexOf(item);
};
-type AutocompleteProps = {
+type AutocompleteProps = Omit<ComponentProps<typeof TextField>, "onChange"> & {
items: Items;
- onChangeValue: (value: string) => void;
+ onChange: (value: string) => void;
value: string;
-} & ComponentProps<typeof TextField>;
+};
export const Autocomplete = ({
items,
- onChangeValue,
+ onChange,
value,
...rest
}: AutocompleteProps) => {
@@ -65,7 +65,7 @@ export const Autocomplete = ({
const select = (nextValue?: string) => {
cancelDebounce();
if (nextValue !== undefined && nextValue !== value) {
- onChangeValue(nextValue);
+ onChange(nextValue);
}
};
@@ -145,7 +145,6 @@ export const Autocomplete = ({
const value = event.target.value.trim();
select(value);
open();
- onChangeValue(value);
}}
onKeyDown={(event) => {
switch (event.key) {
diff --git a/app/designer/features/style-panel/lib/color-picker.tsx b/app/designer/features/style-panel/lib/color-picker.tsx
index 8421520697..d96a8de7ea 100644
--- a/app/designer/features/style-panel/lib/color-picker.tsx
+++ b/app/designer/features/style-panel/lib/color-picker.tsx
@@ -16,11 +16,16 @@ const stringifyRGBA = (color: RGBColor) => {
};
type ColorPickerProps = {
- onChangeValue: (value: string) => void;
+ onChange: (value: string) => void;
+ onChangeComplete: (value: string) => void;
value: string;
};
-export const ColorPicker = ({ value, onChangeValue }: ColorPickerProps) => {
+export const ColorPicker = ({
+ value,
+ onChange,
+ onChangeComplete,
+}: ColorPickerProps) => {
const [displayColorPicker, setDisplayColorPicker] = useState(false);
return (
@@ -39,7 +44,7 @@ export const ColorPicker = ({ value, onChangeValue }: ColorPickerProps) => {
}}
/>
<TextField
- onChange={(e) => onChangeValue(e.target.value)}
+ onChange={(e) => onChange(e.target.value)}
onClick={() => setDisplayColorPicker((shown) => !shown)}
variant="ghost"
value={value}
@@ -50,9 +55,10 @@ export const ColorPicker = ({ value, onChangeValue }: ColorPickerProps) => {
<PopoverContent>
<SketchPicker
color={value}
- onChange={(color: ColorResult) =>
- onChangeValue(stringifyRGBA(color.rgb))
- }
+ onChange={(color: ColorResult) => onChange(stringifyRGBA(color.rgb))}
+ onChangeComplete={(color: ColorResult) => {
+ onChangeComplete(stringifyRGBA(color.rgb));
+ }}
// @todo to remove both when we have preset colors
presetColors={[]}
styles={{
diff --git a/app/designer/features/style-panel/lib/spacing-widget.tsx b/app/designer/features/style-panel/lib/spacing-widget.tsx
index a5b7c20d24..01e9c320b8 100644
--- a/app/designer/features/style-panel/lib/spacing-widget.tsx
+++ b/app/designer/features/style-panel/lib/spacing-widget.tsx
@@ -1,9 +1,5 @@
import { Box } from "~/shared/design-system";
-import {
- buildCss,
- type StyleProperty,
- type StyleValue,
-} from "@webstudio-is/sdk";
+import { toCss, type StyleProperty, type StyleValue } from "@webstudio-is/sdk";
import { SetProperty } from "../use-style-data";
type SpacingSingularStyle = { [property in SpacingProperty]?: StyleValue };
@@ -105,8 +101,8 @@ type SpacingWidgetProps = {
};
export const SpacingWidget = ({ setProperty, values }: SpacingWidgetProps) => {
- const margins = buildCss(values.margins);
- const paddings = buildCss(values.paddings);
+ const margins = toCss(values.margins);
+ const paddings = toCss(values.paddings);
const updateSpacing = ({
value,
diff --git a/app/designer/features/style-panel/render-property.tsx b/app/designer/features/style-panel/render-property.tsx
index 5e4c2b3660..8e86b30e58 100644
--- a/app/designer/features/style-panel/render-property.tsx
+++ b/app/designer/features/style-panel/render-property.tsx
@@ -64,6 +64,7 @@ const ColorField = ({
property: styleConfig.property,
});
if (value === undefined) return null;
+ const setValue = setProperty(styleConfig.property);
return (
<Grid columns={2} align="center" gapX="1">
@@ -73,7 +74,10 @@ const ColorField = ({
<Flex align="center" css={{ gridColumn: "2/4" }} gap="1">
<ColorPicker
value={String(value.value)}
- onChangeValue={setProperty(styleConfig.property)}
+ onChange={(value) => {
+ setValue(value, { isEphemeral: true });
+ }}
+ onChangeComplete={setValue}
/>
</Flex>
</Grid>
@@ -240,7 +244,7 @@ const TextFieldWithAutocomplete = ({
}}
state={value.type === "invalid" ? "invalid" : undefined}
value={String(value.value)}
- onChangeValue={setProperty(styleConfig.property)}
+ onChange={setProperty(styleConfig.property)}
/>
<Unit value={value} />
</Flex>
diff --git a/app/designer/features/style-panel/use-style-data.ts b/app/designer/features/style-panel/use-style-data.ts
index 24e09d72f0..91634d61fd 100644
--- a/app/designer/features/style-panel/use-style-data.ts
+++ b/app/designer/features/style-panel/use-style-data.ts
@@ -11,7 +11,11 @@ type UseStyleData = {
selectedInstanceData?: SelectedInstanceData;
};
-export type SetProperty = (property: StyleProperty) => (value: string) => void;
+type StyleUpdateOptions = { isEphemeral: boolean };
+
+export type SetProperty = (
+ property: StyleProperty
+) => (value: string, options?: StyleUpdateOptions) => void;
export const useStyleData = ({
selectedInstanceData,
@@ -40,10 +44,16 @@ export const useStyleData = ({
});
}, [selectedInstanceData?.style, selectedInstanceData?.browserStyle]);
- const publishUpdates = (updates: StyleUpdates["updates"]) => {
+ const publishUpdates = (
+ type: "update" | "preview",
+ updates: StyleUpdates["updates"]
+ ) => {
if (updates.length === 0 || selectedInstanceData === undefined) return;
- publish<"updateStyles", StyleUpdates>({
- type: "updateStyles",
+ publish<string, StyleUpdates>({
+ type:
+ type === "update"
+ ? "updateStyle"
+ : `previewStyle:${selectedInstanceData.id}`,
payload: {
id: selectedInstanceData.id,
updates,
@@ -52,11 +62,13 @@ export const useStyleData = ({
};
const setProperty: SetProperty = (property) => {
- return (input) => {
+ return (input, options = { isEphemeral: false }) => {
if (currentStyle === undefined) return;
const value = parseValue(property, input, currentStyle);
if (value.type !== "invalid") {
- publishUpdates([{ property, value }]);
+ const updates = [{ property, value }];
+ const type = options.isEphemeral ? "preview" : "update";
+ publishUpdates(type, updates);
}
setCurrentStyle({ ...currentStyle, [property]: value });
};
diff --git a/app/designer/features/sync/use-sync.ts b/app/designer/features/sync/use-sync.ts
index 0db8ffdaaf..b44ba24f9e 100644
--- a/app/designer/features/sync/use-sync.ts
+++ b/app/designer/features/sync/use-sync.ts
@@ -1,4 +1,3 @@
-import debounce from "lodash.debounce";
import {
type ChildrenUpdates,
type Instance,
@@ -7,7 +6,6 @@ import {
type Project,
} from "@webstudio-is/sdk";
import type { Config } from "~/config";
-import type { StyleUpdates } from "~/shared/component";
import { useSubscribe } from "~/designer/features/canvas-iframe";
import { enqueue } from "./queue";
import { type SyncItem } from "~/lib/sync-engine";
@@ -17,18 +15,6 @@ import { type SyncItem } from "~/lib/sync-engine";
// and backend fetches and updates big objects, so if we send quickly,
// we end up overwriting things
export const useSync = ({ project }: { config: Config; project: Project }) => {
- useSubscribe<"updateStyles", StyleUpdates>(
- "updateStyles",
- debounce((styleUpdates) => {
- enqueue(() =>
- fetch(`/rest/update-styles/${project.devTreeId}`, {
- method: "post",
- body: JSON.stringify(styleUpdates),
- })
- );
- }, 1000)
- );
-
useSubscribe<"updateProps", UserPropsUpdates>("updateProps", (update) => {
enqueue(() =>
fetch(`/rest/props/update`, {
diff --git a/app/designer/shared/shortcuts/use-publish-shortcuts.ts b/app/designer/shared/shortcuts/use-publish-shortcuts.ts
new file mode 100644
index 0000000000..72d7f40048
--- /dev/null
+++ b/app/designer/shared/shortcuts/use-publish-shortcuts.ts
@@ -0,0 +1,25 @@
+import { useHotkeys } from "react-hotkeys-hook";
+import { type Publish } from "~/designer/features/canvas-iframe";
+import { shortcuts } from "~/shared/shortcuts";
+
+const names = Object.keys(shortcuts) as Array<keyof typeof shortcuts>;
+
+/**
+ * Forwarding shortcuts to the canvas.
+ */
+export const usePublishShortcuts = (publish: Publish) => {
+ names.forEach((name) => {
+ // as long as the array is static, it's ok
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ useHotkeys(
+ shortcuts[name],
+ () => {
+ publish<"shortcut", string>({
+ type: "shortcut",
+ payload: name,
+ });
+ },
+ []
+ );
+ });
+};
diff --git a/app/routes/rest/update-styles.$treeId.ts b/app/routes/rest/update-styles.$treeId.ts
deleted file mode 100644
index 77a3856eb6..0000000000
--- a/app/routes/rest/update-styles.$treeId.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { type ActionFunction } from "remix";
-import * as db from "~/shared/db";
-
-export const action: ActionFunction = async ({ request, params }) => {
- if (params.treeId === undefined) throw new Error("Tree id requred");
- const styleUpdates = await request.json();
- await db.tree.updateStyles(params.treeId, styleUpdates);
- return { status: "ok" };
-};
diff --git a/app/shared/db/tree.server.ts b/app/shared/db/tree.server.ts
index 9a045dd0b9..8c0cf20b77 100644
--- a/app/shared/db/tree.server.ts
+++ b/app/shared/db/tree.server.ts
@@ -6,12 +6,7 @@ import {
} from "@webstudio-is/sdk";
import { applyPatches, type Patch } from "immer";
import { prisma } from "./prisma.server";
-import {
- setInstanceStyle,
- setInstanceChildren,
- createInstance,
-} from "~/shared/tree-utils";
-import type { StyleUpdates } from "~/shared/component";
+import { setInstanceChildren, createInstance } from "~/shared/tree-utils";
const rootConfig = {
// @todo this should be part of a root primitive in primitives
@@ -89,20 +84,6 @@ export const loadByProject = async (
return await loadById(treeId);
};
-export const updateStyles = async (id: string, styleUpdates: StyleUpdates) => {
- // @todo we need to update without fetching the tree
- const tree = await loadById(id);
- const root = setInstanceStyle(
- tree.root,
- styleUpdates.id,
- styleUpdates.updates
- );
- await prisma.tree.update({
- data: { root },
- where: { id },
- });
-};
-
export const updateChildren = async (
id: string,
change: { instanceId: Instance["id"]; updates: ChildrenUpdates }
diff --git a/app/shared/shortcuts/index.ts b/app/shared/shortcuts/index.ts
new file mode 100644
index 0000000000..663e63812f
--- /dev/null
+++ b/app/shared/shortcuts/index.ts
@@ -0,0 +1,4 @@
+export const shortcuts = {
+ undo: "cmd+z, ctrl+z",
+ redo: "cmd+shift+z, ctrl+shift+z",
+} as const;
diff --git a/app/shared/tree-utils/set-instance-style.ts b/app/shared/tree-utils/set-instance-style.ts
index cd3db83a17..556285e112 100644
--- a/app/shared/tree-utils/set-instance-style.ts
+++ b/app/shared/tree-utils/set-instance-style.ts
@@ -1,30 +1,17 @@
-import { type Style, type Instance } from "@webstudio-is/sdk";
+import { type Instance } from "@webstudio-is/sdk";
import { type StyleUpdates } from "~/shared/component";
+import { findInstanceById } from "./find-instance";
-// @todo rewrite using immer
-export const setInstanceStyle = (
- instance: Instance,
+export const setInstanceStyleMutable = (
+ rootInstance: Instance,
id: Instance["id"],
updates: StyleUpdates["updates"]
-): Instance => {
- if (instance.id === id) {
- const style: Style = { ...instance.style };
- for (const update of updates) {
- style[update.property] = update.value;
- }
- return { ...instance, style };
- }
+) => {
+ const instance = findInstanceById(rootInstance, id);
+ if (instance === undefined) return false;
- for (const child of instance.children) {
- if (typeof child === "string") continue;
- const updatedChild = setInstanceStyle(child, id, updates);
- if (updatedChild !== child) {
- const children = [...instance.children];
- const index = children.indexOf(child);
- children[index] = updatedChild;
- return { ...instance, children };
- }
+ for (const update of updates) {
+ instance.style[update.property] = update.value;
}
-
- return instance;
+ return true;
};
diff --git a/package.json b/package.json
index 016cb4bbc4..15be975160 100644
--- a/package.json
+++ b/package.json
@@ -43,7 +43,7 @@
"@remix-run/vercel": "^1.2.3",
"@stitches/react": "^1.2.6",
"@stitches/stringify": "^1.2.6",
- "@webstudio-is/sdk": "^0.1.19",
+ "@webstudio-is/sdk": "^0.1.20",
"bson-objectid": "^2.0.2",
"camelcase": "^6.3.0",
"hyphenate-style-name": "^1.0.4",
diff --git a/yarn.lock b/yarn.lock
index e1526447d5..7683e2e17e 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1820,10 +1820,10 @@
dependencies:
web-streams-polyfill "^3.1.1"
-"@webstudio-is/sdk@^0.1.19":
- version "0.1.19"
- resolved "https://registry.yarnpkg.com/@webstudio-is/sdk/-/sdk-0.1.19.tgz#6075c3095d6f145ee45f3830cbb40044a2f464c5"
- integrity sha512-OnhDlhP9EneFCg5p96saEeRKiGdgcq/ngEq78YrVCQF15AvuLpDrCZ5/P9KLEhvusEteNK0SmUYRKqZ2+IQ5NQ==
+"@webstudio-is/sdk@^0.1.20":
+ version "0.1.20"
+ resolved "https://registry.yarnpkg.com/@webstudio-is/sdk/-/sdk-0.1.20.tgz#134fcc2eb166a0c0b648fac4fb008c98666f88c6"
+ integrity sha512-WI379pIabj6WU05qaP9MeUFE+9uCQu8uoEAXkxQ9mjkFpQUNY8lIn3ncsvmxZvyoKCaFIZ2UBAs2Pb7Q6fwSHQ==
dependencies:
"@prisma/client" "^3.10.0"
"@stitches/react" "^1.2.7"