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
Make copy paste data agnostic (#909)
Bogdan Chadkinabee2f1cf45d
diff --git a/apps/designer/app/shared/copy-paste/copy-paste-instance.ts b/apps/designer/app/shared/copy-paste/copy-paste-instance.tsnew file mode 100644index 0000000000..92f2ec8b6b--- /dev/null+++ b/apps/designer/app/shared/copy-paste/copy-paste-instance.ts@@ -0,0 +1,63 @@+import ObjectId from "bson-objectid";+import { useEffect } from "react";+import { z } from "zod";+import { Instance, Props, Styles } from "@webstudio-is/project-build";+import { utils } from "@webstudio-is/project";+import { startCopyPaste } from "./copy-paste";++const InstanceCopyData = z.object({+ instance: Instance,+ props: Props,+ styles: Styles,+});++export type InstanceCopyData = z.infer<typeof InstanceCopyData>;++type InstanceCopyPasteProps = {+ selectedInstanceData?: InstanceCopyData;+ allowAnyTarget?: boolean;+ onPaste: (data: InstanceCopyData) => void;+ onCut: (instance: Instance) => void;+};++// to make it easier to remove React from canvas if we need to+export const useInstanceCopyPaste = (props: InstanceCopyPasteProps): void => {+ const { selectedInstanceData, allowAnyTarget, onPaste, onCut } = props;+ useEffect(() => {+ return startCopyPaste({+ version: "@webstudio/instance/v0.1",+ type: InstanceCopyData,+ onCopy: () => {+ return selectedInstanceData;+ },+ onCut: () => {+ if (selectedInstanceData === undefined) {+ return;+ }+ onCut(selectedInstanceData.instance);+ return selectedInstanceData;+ },+ onPaste: (data: InstanceCopyData) => {+ const instance = utils.tree.cloneInstance(data.instance);++ // copy props with new ids and link to new instance+ const props: Props = data.props.map((prop) => {+ return {+ ...prop,+ id: ObjectId().toString(),+ instanceId: instance.id,+ };+ });++ const styles: Styles = data.styles.map((styleDecl) => {+ return {+ ...styleDecl,+ instanceId: instance.id,+ };+ });++ onPaste({ instance, props, styles });+ },+ });+ }, [selectedInstanceData, allowAnyTarget, onPaste, onCut]);+};diff --git a/apps/designer/app/shared/copy-paste/copy-paste.ts b/apps/designer/app/shared/copy-paste/copy-paste.tsnew file mode 100644index 0000000000..5e2e295614--- /dev/null+++ b/apps/designer/app/shared/copy-paste/copy-paste.ts@@ -0,0 +1,130 @@+import { z } from "zod";++const isValidClipboardEvent = (+ event: ClipboardEvent,+ options: { allowAnyTarget: boolean }+) => {+ const selection = document.getSelection();+ if (selection?.type === "Range") {+ return false;+ }++ // Note on event.target:+ //+ // The spec (https://w3c.github.io/clipboard-apis/#to-fire-a-clipboard-event)+ // says that if the context is not editable, the target should be the focused node.+ //+ // But in practice it seems that the target is based+ // on where the cursor is, rather than which element has focus.+ // For example, if a <button> has focus, the target is the <body> element+ // (at least in Chrome).++ // If cursor is in input,+ // don't copy (we may want to add more exceptions here in the future)+ if (+ options.allowAnyTarget === false &&+ (event.target instanceof HTMLInputElement ||+ event.target instanceof HTMLTextAreaElement)+ ) {+ return false;+ }++ return true;+};++type Props<Data> = {+ version: string;+ type: z.ZodType<Data>;+ allowAnyTarget?: boolean;+ onCopy: () => undefined | Data;+ onCut: () => undefined | Data;+ onPaste: (data: Data) => void;+};++export const startCopyPaste = <Type>(props: Props<Type>) => {+ const { version, type, allowAnyTarget = false } = props;+ const versionLiteral = version;++ const DataType = z.object({ [versionLiteral]: type });++ const serialize = (data: Type) => {+ return JSON.stringify({ [versionLiteral]: data });+ };++ const deserialize = (text: string) => {+ try {+ const data = DataType.parse(JSON.parse(text));+ // zod provides invalid type without versionLiteral+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ return (data as any)[versionLiteral] as Type;+ } catch {+ return;+ }+ };++ const handleCopy = (event: ClipboardEvent) => {+ if (+ event.clipboardData === null ||+ isValidClipboardEvent(event, { allowAnyTarget }) === false+ ) {+ return;+ }++ const data = props.onCopy();+ if (data === undefined) {+ return;+ }++ // must prevent default, otherwise setData() will not work+ event.preventDefault();+ event.clipboardData.setData("application/json", serialize(data));+ };++ const handleCut = (event: ClipboardEvent) => {+ if (+ event.clipboardData === null ||+ isValidClipboardEvent(event, { allowAnyTarget }) === false+ ) {+ return;+ }++ const data = props.onCut();+ if (data === undefined) {+ return;+ }++ // must prevent default, otherwise setData() will not work+ event.preventDefault();+ event.clipboardData.setData("application/json", serialize(data));+ };++ const handlePaste = (event: ClipboardEvent) => {+ if (+ event.clipboardData === null ||+ // we might want a separate predicate for paste,+ // but for now the logic is the same+ isValidClipboardEvent(event, { allowAnyTarget }) === false+ ) {+ return;+ }++ // this shouldn't matter, but just in case+ event.preventDefault();+ const data = deserialize(event.clipboardData.getData("application/json"));+ if (data === undefined) {+ return;+ }++ props.onPaste(data);+ };++ document.addEventListener("copy", handleCopy);+ document.addEventListener("cut", handleCut);+ document.addEventListener("paste", handlePaste);++ return () => {+ document.removeEventListener("copy", handleCopy);+ document.removeEventListener("cut", handleCut);+ document.removeEventListener("paste", handlePaste);+ };+};diff --git a/apps/designer/app/shared/copy-paste/index.ts b/apps/designer/app/shared/copy-paste/index.tsindex 124a3b4d28..41cbf6716c 100644--- a/apps/designer/app/shared/copy-paste/index.ts+++ b/apps/designer/app/shared/copy-paste/index.ts@@ -1,2 +1 @@-export * from "./use-instance-copy-paste";-export * from "./serialize";+export * from "./copy-paste-instance";diff --git a/apps/designer/app/shared/copy-paste/serialize.ts b/apps/designer/app/shared/copy-paste/serialize.tsdeleted file mode 100644index ecab6e090b..0000000000--- a/apps/designer/app/shared/copy-paste/serialize.ts+++ /dev/null@@ -1,26 +0,0 @@-import { z } from "zod";-import { Instance, Props, Styles } from "@webstudio-is/project-build";--const TYPE = "@webstudio/instance/v0.1" as const;--const InstanceCopyData = z.object({- instance: Instance,- props: Props,- styles: Styles,-});--export type InstanceCopyData = z.infer<typeof InstanceCopyData>;--const SerialisedData = z.object({ [TYPE]: InstanceCopyData });--export const serialize = (data: InstanceCopyData) => {- return JSON.stringify({ [TYPE]: data });-};--export const deserialize = (text: string) => {- try {- return SerialisedData.parse(JSON.parse(text))[TYPE];- } catch (e) {- return;- }-};diff --git a/apps/designer/app/shared/copy-paste/use-instance-copy-paste.ts b/apps/designer/app/shared/copy-paste/use-instance-copy-paste.tsdeleted file mode 100644index b33e4035e9..0000000000--- a/apps/designer/app/shared/copy-paste/use-instance-copy-paste.ts+++ /dev/null@@ -1,174 +0,0 @@-import ObjectId from "bson-objectid";-import { useEffect, useMemo } from "react";-import { utils } from "@webstudio-is/project";-import type { Instance, Props, Styles } from "@webstudio-is/project-build";-import { type InstanceCopyData, serialize, deserialize } from "./serialize";--const isInstanceClipboardEvent = (- event: ClipboardEvent,- options: { allowAnyTarget?: boolean }-) => {- const selection = document.getSelection();- if (selection !== null && selection.type === "Range") {- return false;- }-- // Note on event.target:- //- // The spec (https://w3c.github.io/clipboard-apis/#to-fire-a-clipboard-event)- // says that if the context is not editable, the target should be the focused node.- //- // But in practice it seems that the target is based- // on where the cursor is, rather than which element has focus.- // For example, if a <button> has focus, the target is the <body> element- // (at least in Chrome).-- // If cursor is in input,- // don't copy instance (we may want to add more exceptions here in the future)- if (- options.allowAnyTarget !== true &&- (event.target instanceof HTMLInputElement ||- event.target instanceof HTMLTextAreaElement)- ) {- return false;- }-- return true;-};--type InstanceCopyPasteProps = {- selectedInstanceData?: InstanceCopyData | undefined;- allowAnyTarget?: boolean;- onPaste: (data: InstanceCopyData) => void;- onCut: (instance: Instance) => void;-};--const createEventsHandler = () => {- let currentProps: InstanceCopyPasteProps | undefined;-- const handleCopy = (event: ClipboardEvent) => {- if (currentProps === undefined) {- return;- }- const { selectedInstanceData, allowAnyTarget } = currentProps;-- if (- event.clipboardData === null ||- selectedInstanceData === undefined ||- isInstanceClipboardEvent(event, { allowAnyTarget }) === false- ) {- return;- }-- // must prevent default, otherwise setData() will not work- event.preventDefault();-- event.clipboardData.setData(- "application/json",- serialize(selectedInstanceData)- );- };-- const handleCut = (event: ClipboardEvent) => {- if (currentProps === undefined) {- return;- }- const { selectedInstanceData, allowAnyTarget, onCut } = currentProps;-- if (- event.clipboardData === null ||- selectedInstanceData === undefined ||- isInstanceClipboardEvent(event, {- allowAnyTarget: allowAnyTarget,- }) === false- ) {- return;- }-- // must prevent default, otherwise setData() will not work- event.preventDefault();-- event.clipboardData.setData(- "application/json",- serialize(selectedInstanceData)- );-- onCut(selectedInstanceData.instance);- };-- const handlePaste = (event: ClipboardEvent) => {- if (currentProps === undefined) {- return;- }- const { onPaste, allowAnyTarget } = currentProps;-- if (- event.clipboardData === null ||- // we might want a separate predicate for paste,- // but for now the logic is the same- isInstanceClipboardEvent(event, { allowAnyTarget }) === false- ) {- return;- }-- // this shouldn't matter, but just in case- event.preventDefault();-- const data = deserialize(event.clipboardData.getData("application/json"));-- if (data === undefined) {- return;- }-- const instance = utils.tree.cloneInstance(data.instance);-- // copy props with new ids and link to new instance- const props: Props = data.props.map((prop) => {- return {- ...prop,- id: ObjectId().toString(),- instanceId: instance.id,- };- });-- const styles: Styles = data.styles.map((styleDecl) => {- return {- ...styleDecl,- instanceId: instance.id,- };- });-- onPaste({ instance, props, styles });- };-- return {- start() {- document.addEventListener("copy", handleCopy);- document.addEventListener("cut", handleCut);- document.addEventListener("paste", handlePaste);- },- stop() {- document.removeEventListener("copy", handleCopy);- document.removeEventListener("cut", handleCut);- document.removeEventListener("paste", handlePaste);- },- setProps(props: InstanceCopyPasteProps) {- currentProps = props;- },- };-};--// Everything is extrcated from hook,-// to make it easier to remove React from canvas if we need to-export const useInstanceCopyPaste = (props: InstanceCopyPasteProps): void => {- const eventsHandler = useMemo(createEventsHandler, []);-- useEffect(() => {- eventsHandler.setProps(props);- }, [eventsHandler, props]);-- useEffect(() => {- eventsHandler.start();- return eventsHandler.stop;- }, [eventsHandler]);-};