@contentful/experiences-visual-editor-react 1.5.0 → 1.5.1-beta.1

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.
package/README.md CHANGED
@@ -1,7 +1,23 @@
1
1
  # @contentful/experiences-visual-editor-react
2
2
 
3
- This package provides a visual editor for the [Experiences SDK](https://www.contentful.com/developers/docs/experiences/set-up-experiences-sdk/). It implements drag-and-drop functionality into the canvas, making the creation and editing of experiences more intuitive and user-friendly.
3
+ ### Purpose
4
+ - Handles the canvas interaction logic with dragging, hitboxes, dropzones, reparenting, and communicating with the parent frame to ensure a smooth drag and drop experience.
5
+ - Note that this package is framework specific to React.
4
6
 
5
- ## Documentation
7
+ ### Concepts
8
+ - **Structure components**: Represents components that pertain to the layout of a user's experience such as containers, sections, and columns.
9
+ - **Built-in components**: Contentful-provided components on behalf of the user that are considered universally useful such as an image, text, and the divider component or to get a user quickly started such as a button. Note that these components are not meant to cover every possible component that the user may want to have. Instead users are generally expected to provide their own set of components to build their customized experiences. The exceptions will generally be based on how universally desired such components are, such as Cards or Carousel components in the future.
10
+ - **Custom components**: User-provided components built through a definition provided by the Experiences SDK.
11
+ - **Post messages**: In order for an iFrame to communicate with its parent frame, post messaging is required so that the two frames can communicate with each other. Examples of what information gets shared would be mouse coordinates or what component got picked up and dropped.
12
+ - **Browser limitations**: Currently only Chrome supports both Click/Drag and Drop while Safari and Firefox only allows for Click and Drop.
13
+ - **Trees**: Experiences store their own version of the tree that is separate from the source of truth which is stored as a Contentful entry. This is because by storing its own tree version it can provide UI optimizations and manipulations to the tree to maximize performance-related tasks such as when performing drag and drop or re-ordering of components. A concrete example where this optimization is necessary is when you drop a component onto the canvas. Without its own version, the component would flicker to its original pre-drag spot before being placed on the intended area based on the mouse's location.
14
+ - **Updating the source of truth**: On drag end, the iFrame will update its own tree before sending a post message to the parent frame in `useCanvasInteractions`. Then the parent frame will update its tree which is the source of truth before sending a post msg back in `useEditorSubscriber` to the iFrame ensuring that both trees are the same and any discovered discrepancies are resolved.
15
+ - **@hello-pangea/dnd**: Library providing HOC (higher order components) that Experiences leverages for Drag and Drop. The two components being used from this library is the `Droppable` and `Draggable` component.
16
+ - **Dropzones**: Div wrappers that represent areas for other components to be dropped in. Note that only one can be activated at a time via a hitbox and is a separate div from `Draggables`.
17
+ - **Draggables**: Div wrappers that allow component to be picked up and dropped. Note that this is a separate div from `Dropzones`.
18
+ - **SimulateDnD**: Custom-built DND component which is needed as a visual trick for dragging a component from the sidebar onto the iFrame. Since the drag is initiated in the parent frame when clicking and dragging a new component, a simulated action in the iFrame is also triggered so the iFrame is in a drag state just like the parent frame. Then when the mouse crosses over from the parent frame into the iFrame, post messaging is required where the iFrame will send mouse coordinates to the parentFrame so that the dragged component icon is placed in the correct position while the iFrame will trigger the appropriate hitboxes and dropzones since all the hitboxes and dropzones live in the iFrame.
19
+ - **Component wrapper**: There are several types of div wrappers such as `Dropzones` and `Draggables`. However, there is a third wrapper that is provided as a custom boolean option with `Custom Components`. When this boolean is true, all style options selected from the UI will be applied to this wrapping div. This is done so that the user's CSS styles on their own components are preserved and shielded from the style options chosen in the UI.
6
20
 
7
- Please refer to our [Documentation](https://www.contentful.com/developers/docs/experiences/) to learn more about it.
21
+
22
+ ### Relevant Contentful documentation links
23
+ - [Contentful entry tree data structure](https://www.contentful.com/developers/docs/experiences/data-structures/)
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ import styleInject from 'style-inject';
2
2
  import React, { useRef, useMemo, useEffect, useState, useLayoutEffect, forwardRef, useCallback } from 'react';
3
3
  import md5 from 'md5';
4
4
  import { BLOCKS } from '@contentful/rich-text-types';
5
+ import { z } from 'zod';
5
6
  import { isEqual, get as get$1, omit } from 'lodash-es';
6
7
  import { Draggable, Droppable, DragDropContext } from '@hello-pangea/dnd';
7
8
  import classNames from 'classnames';
@@ -954,6 +955,236 @@ const resolveSimpleDesignToken = (templateString, variableName) => {
954
955
  return '0px';
955
956
  };
956
957
 
958
+ // If more than one version is supported, use z.union
959
+ const SchemaVersions = z.literal('2023-09-28');
960
+ // Keep deprecated versions here just for reference
961
+ z.union([
962
+ z.literal('2023-08-23'),
963
+ z.literal('2023-07-26'),
964
+ z.literal('2023-06-27'),
965
+ ]);
966
+
967
+ const DefinitionPropertyTypeSchema = z.enum([
968
+ 'Text',
969
+ 'RichText',
970
+ 'Number',
971
+ 'Date',
972
+ 'Boolean',
973
+ 'Location',
974
+ 'Media',
975
+ 'Object',
976
+ 'Hyperlink',
977
+ ]);
978
+ const DefinitionPropertyKeySchema = z
979
+ .string()
980
+ .regex(/^[a-zA-Z0-9-_]{1,32}$/, { message: 'Property needs to match: /^[a-zA-Z0-9-_]{1,32}$/' });
981
+ z.object({
982
+ id: DefinitionPropertyKeySchema,
983
+ variables: z.record(DefinitionPropertyKeySchema, z.object({
984
+ // TODO - extend with definition of validations and defaultValue
985
+ displayName: z.string().optional(),
986
+ type: DefinitionPropertyTypeSchema,
987
+ description: z.string().optional(),
988
+ group: z.string().optional(),
989
+ })),
990
+ });
991
+
992
+ const uuidKeySchema = z
993
+ .string()
994
+ .regex(/^[a-zA-Z0-9-_]{1,21}$/, { message: 'Does not match /^[a-zA-Z0-9-_]{1,21}$/' });
995
+ /**
996
+ * Property keys for imported components have a limit of 32 characters (to be implemented) while
997
+ * property keys for patterns have a limit of 54 characters (<32-char-variabl-name>_<21-char-nanoid-id>).
998
+ * Because we cannot distinguish between the two in the componentTree, we will use the larger limit for both.
999
+ */
1000
+ const propertyKeySchema = z
1001
+ .string()
1002
+ .regex(/^[a-zA-Z0-9-_]{1,54}$/, { message: 'Does not match /^[a-zA-Z0-9-_]{1,54}$/' });
1003
+ const DataSourceSchema = z.record(uuidKeySchema, z.object({
1004
+ sys: z.object({
1005
+ type: z.literal('Link'),
1006
+ id: z.string(),
1007
+ linkType: z.enum(['Entry', 'Asset']),
1008
+ }),
1009
+ }));
1010
+ const PrimitiveValueSchema = z.union([
1011
+ z.string(),
1012
+ z.boolean(),
1013
+ z.number(),
1014
+ z.record(z.any(), z.any()),
1015
+ z.undefined(),
1016
+ ]);
1017
+ const ValuesByBreakpointSchema = z.record(z.lazy(() => PrimitiveValueSchema));
1018
+ const DesignValueSchema = z
1019
+ .object({
1020
+ type: z.literal('DesignValue'),
1021
+ valuesByBreakpoint: ValuesByBreakpointSchema,
1022
+ })
1023
+ .strict();
1024
+ const BoundValueSchema = z
1025
+ .object({
1026
+ type: z.literal('BoundValue'),
1027
+ path: z.string(),
1028
+ })
1029
+ .strict();
1030
+ const HyperlinkValueSchema = z
1031
+ .object({
1032
+ type: z.literal('HyperlinkValue'),
1033
+ linkTargetKey: z.string(),
1034
+ overrides: z.object({}).optional(),
1035
+ })
1036
+ .strict();
1037
+ const UnboundValueSchema = z
1038
+ .object({
1039
+ type: z.literal('UnboundValue'),
1040
+ key: z.string(),
1041
+ })
1042
+ .strict();
1043
+ const ComponentValueSchema = z
1044
+ .object({
1045
+ type: z.literal('ComponentValue'),
1046
+ key: z.string(),
1047
+ })
1048
+ .strict();
1049
+ const ComponentPropertyValueSchema = z.discriminatedUnion('type', [
1050
+ DesignValueSchema,
1051
+ BoundValueSchema,
1052
+ UnboundValueSchema,
1053
+ HyperlinkValueSchema,
1054
+ ComponentValueSchema,
1055
+ ]);
1056
+ const BreakpointSchema = z
1057
+ .object({
1058
+ id: propertyKeySchema,
1059
+ query: z.string().regex(/^\*$|^<[0-9*]+px$/),
1060
+ previewSize: z.string(),
1061
+ displayName: z.string(),
1062
+ displayIconUrl: z.string().optional(),
1063
+ })
1064
+ .strict();
1065
+ const UnboundValuesSchema = z.record(uuidKeySchema, z.object({
1066
+ value: PrimitiveValueSchema,
1067
+ }));
1068
+ // Use helper schema to define a recursive schema with its type correctly below
1069
+ const BaseComponentTreeNodeSchema = z.object({
1070
+ definitionId: DefinitionPropertyKeySchema,
1071
+ displayName: z.string().optional(),
1072
+ slotId: z.string().optional(),
1073
+ variables: z.record(propertyKeySchema, ComponentPropertyValueSchema),
1074
+ });
1075
+ const ComponentTreeNodeSchema = BaseComponentTreeNodeSchema.extend({
1076
+ children: z.lazy(() => ComponentTreeNodeSchema.array()),
1077
+ });
1078
+ const ComponentSettingsSchema = z.object({
1079
+ variableDefinitions: z.record(z.string().regex(/^[a-zA-Z0-9-_]{1,54}$/), // Here the key is <variableName>_<nanoidId> so we need to allow for a longer length
1080
+ z.object({
1081
+ displayName: z.string().optional(),
1082
+ type: DefinitionPropertyTypeSchema,
1083
+ defaultValue: PrimitiveValueSchema.or(ComponentPropertyValueSchema).optional(),
1084
+ description: z.string().optional(),
1085
+ group: z.string().optional(),
1086
+ validations: z
1087
+ .object({
1088
+ required: z.boolean().optional(),
1089
+ format: z.literal('URL').optional(),
1090
+ in: z
1091
+ .array(z.object({
1092
+ value: z.union([z.string(), z.number()]),
1093
+ displayName: z.string().optional(),
1094
+ }))
1095
+ .optional(),
1096
+ })
1097
+ .optional(),
1098
+ })),
1099
+ });
1100
+ const UsedComponentsSchema = z.array(z.object({
1101
+ sys: z.object({
1102
+ type: z.literal('Link'),
1103
+ id: z.string(),
1104
+ linkType: z.literal('Entry'),
1105
+ }),
1106
+ }));
1107
+ const breakpointsRefinement = (value, ctx) => {
1108
+ if (!value.length || value[0].query !== '*') {
1109
+ ctx.addIssue({
1110
+ code: z.ZodIssueCode.custom,
1111
+ message: `The first breakpoint should include the following attributes: { "query": "*" }`,
1112
+ });
1113
+ }
1114
+ const hasDuplicateIds = value.some((currentBreakpoint, currentBreakpointIndex) => {
1115
+ // check if the current breakpoint id is found in the rest of the array
1116
+ const breakpointIndex = value.findIndex((breakpoint) => breakpoint.id === currentBreakpoint.id);
1117
+ return breakpointIndex !== currentBreakpointIndex;
1118
+ });
1119
+ if (hasDuplicateIds) {
1120
+ ctx.addIssue({
1121
+ code: z.ZodIssueCode.custom,
1122
+ message: `Breakpoint IDs must be unique`,
1123
+ });
1124
+ }
1125
+ // Extract the queries boundary by removing the special characters around it
1126
+ const queries = value.map((bp) => bp.query === '*' ? bp.query : parseInt(bp.query.replace(/px|<|>/, '')));
1127
+ // sort updates queries array in place so we need to create a copy
1128
+ const originalQueries = [...queries];
1129
+ queries.sort((q1, q2) => {
1130
+ if (q1 === '*') {
1131
+ return -1;
1132
+ }
1133
+ if (q2 === '*') {
1134
+ return 1;
1135
+ }
1136
+ return q1 > q2 ? -1 : 1;
1137
+ });
1138
+ if (originalQueries.join('') !== queries.join('')) {
1139
+ ctx.addIssue({
1140
+ code: z.ZodIssueCode.custom,
1141
+ message: `Breakpoints should be ordered from largest to smallest pixel value`,
1142
+ });
1143
+ }
1144
+ };
1145
+ const componentSettingsRefinement = (value, ctx) => {
1146
+ const { componentSettings, usedComponents } = value;
1147
+ if (!componentSettings || !usedComponents) {
1148
+ return;
1149
+ }
1150
+ const localeKey = Object.keys(componentSettings ?? {})[0];
1151
+ if (componentSettings[localeKey] !== undefined && usedComponents[localeKey] !== undefined) {
1152
+ ctx.addIssue({
1153
+ code: z.ZodIssueCode.custom,
1154
+ message: `'componentSettings' field cannot be used in conjunction with 'usedComponents' field`,
1155
+ path: ['componentSettings', localeKey],
1156
+ });
1157
+ }
1158
+ };
1159
+ const ComponentTreeSchema = z
1160
+ .object({
1161
+ breakpoints: z.array(BreakpointSchema).superRefine(breakpointsRefinement),
1162
+ children: z.array(ComponentTreeNodeSchema),
1163
+ schemaVersion: SchemaVersions,
1164
+ })
1165
+ .strict();
1166
+ const localeWrapper = (fieldSchema) => z.record(z.string(), fieldSchema);
1167
+ z
1168
+ .object({
1169
+ componentTree: localeWrapper(ComponentTreeSchema),
1170
+ dataSource: localeWrapper(DataSourceSchema),
1171
+ unboundValues: localeWrapper(UnboundValuesSchema),
1172
+ usedComponents: localeWrapper(UsedComponentsSchema).optional(),
1173
+ componentSettings: localeWrapper(ComponentSettingsSchema).optional(),
1174
+ })
1175
+ .superRefine(componentSettingsRefinement);
1176
+
1177
+ var CodeNames;
1178
+ (function (CodeNames) {
1179
+ CodeNames["Type"] = "type";
1180
+ CodeNames["Required"] = "required";
1181
+ CodeNames["Unexpected"] = "unexpected";
1182
+ CodeNames["Regex"] = "regex";
1183
+ CodeNames["In"] = "in";
1184
+ CodeNames["Size"] = "size";
1185
+ CodeNames["Custom"] = "custom";
1186
+ })(CodeNames || (CodeNames = {}));
1187
+
957
1188
  const MEDIA_QUERY_REGEXP = /(<|>)(\d{1,})(px|cm|mm|in|pt|pc)$/;
958
1189
  const toCSSMediaQuery = ({ query }) => {
959
1190
  if (query === '*')
@@ -1729,6 +1960,7 @@ const SCROLL_STATES = {
1729
1960
  const OUTGOING_EVENTS = {
1730
1961
  Connected: 'connected',
1731
1962
  DesignTokens: 'registerDesignTokens',
1963
+ RegisteredBreakpoints: 'registeredBreakpoints',
1732
1964
  HoveredSection: 'hoveredSection',
1733
1965
  MouseMove: 'mouseMove',
1734
1966
  NewHoveredElement: 'newHoveredElement',
@@ -2209,7 +2441,7 @@ function getStyle$2(style, snapshot) {
2209
2441
  transitionDuration: `0.001s`,
2210
2442
  };
2211
2443
  }
2212
- const DraggableComponent = ({ children, id, index, isAssemblyBlock = false, isSelected = false, onClick = () => null, onMouseOver = () => null, coordinates, userIsDragging, style, wrapperProps, isContainer, blockId, isDragDisabled = false, placeholder, definition, ...rest }) => {
2444
+ const DraggableComponent = ({ children, id, index, isAssemblyBlock = false, isSelected = false, onClick = () => null, onMouseOver = () => null, coordinates, userIsDragging, style, wrapperProps, isContainer, blockId, isDragDisabled = false, placeholder, definition, displayName, ...rest }) => {
2213
2445
  const ref = useRef(null);
2214
2446
  const setDomRect = useDraggedItemStore((state) => state.setDomRect);
2215
2447
  const isHoveredComponent = useDraggedItemStore((state) => state.hoveredComponentId === id);
@@ -2237,7 +2469,7 @@ const DraggableComponent = ({ children, id, index, isAssemblyBlock = false, isSe
2237
2469
  e.stopPropagation();
2238
2470
  setDomRect(e.currentTarget.getBoundingClientRect());
2239
2471
  }, onMouseOver: onMouseOver, onClick: onClick },
2240
- React.createElement(Tooltip, { id: id, coordinates: coordinates, isAssemblyBlock: isAssemblyBlock, isContainer: isContainer, label: definition.name || 'No label specified' }),
2472
+ React.createElement(Tooltip, { id: id, coordinates: coordinates, isAssemblyBlock: isAssemblyBlock, isContainer: isContainer, label: displayName || definition.name || 'No label specified' }),
2241
2473
  React.createElement(Placeholder, { ...placeholder, id: id }),
2242
2474
  children))));
2243
2475
  };
@@ -2867,7 +3099,7 @@ const useComponent = ({ node: rawNode, resolveDesignValue, renderDropzone, userI
2867
3099
  * component.
2868
3100
  */
2869
3101
  const DraggableChildComponent = (props) => {
2870
- const { elementToRender, id, index, isAssemblyBlock = false, isSelected = false, onClick = () => null, onMouseOver = () => null, coordinates, userIsDragging, style, isContainer, blockId, isDragDisabled = false, wrapperProps, definition, } = props;
3102
+ const { elementToRender, id, index, isAssemblyBlock = false, isSelected = false, onClick = () => null, onMouseOver = () => null, coordinates, userIsDragging, style, isContainer, blockId, isDragDisabled = false, wrapperProps, definition, displayName, } = props;
2871
3103
  const isHoveredComponent = useDraggedItemStore((state) => state.hoveredComponentId === id);
2872
3104
  return (React.createElement(Draggable, { key: id, draggableId: id, index: index, isDragDisabled: isDragDisabled }, (provided, snapshot) => elementToRender({
2873
3105
  ['data-ctfl-draggable-id']: id,
@@ -2889,7 +3121,7 @@ const DraggableChildComponent = (props) => {
2889
3121
  },
2890
3122
  onClick,
2891
3123
  onMouseOver,
2892
- Tooltip: (React.createElement(Tooltip, { id: id, coordinates: coordinates, isAssemblyBlock: isAssemblyBlock, isContainer: isContainer, label: definition.name || 'No label specified' })),
3124
+ Tooltip: (React.createElement(Tooltip, { id: id, coordinates: coordinates, isAssemblyBlock: isAssemblyBlock, isContainer: isContainer, label: displayName || definition.name || 'No label specified' })),
2893
3125
  })));
2894
3126
  };
2895
3127
 
@@ -3415,6 +3647,7 @@ const EditorBlock = ({ node: rawNode, resolveDesignValue, renderDropzone, index,
3415
3647
  userIsDragging,
3416
3648
  });
3417
3649
  const coordinates = useSelectedInstanceCoordinates({ node });
3650
+ const displayName = node.data.displayName;
3418
3651
  const isContainer = node.data.blockId === CONTENTFUL_COMPONENTS.container.id;
3419
3652
  const isSingleColumn = node.data.blockId === CONTENTFUL_COMPONENTS.singleColumn.id;
3420
3653
  const isAssemblyBlock = node.type === ASSEMBLY_BLOCK_NODE_TYPE;
@@ -3447,9 +3680,9 @@ const EditorBlock = ({ node: rawNode, resolveDesignValue, renderDropzone, index,
3447
3680
  });
3448
3681
  };
3449
3682
  if (isSingleColumn) {
3450
- return (React.createElement(DraggableChildComponent, { elementToRender: elementToRender, id: componentId, index: index, isAssemblyBlock: isAssembly || isAssemblyBlock, isDragDisabled: true, isSelected: selectedNodeId === componentId, userIsDragging: userIsDragging, isContainer: isContainer, blockId: node.data.blockId, coordinates: coordinates, wrapperProps: wrapperProps, onClick: onClick, onMouseOver: onMouseOver, definition: definition }));
3683
+ return (React.createElement(DraggableChildComponent, { elementToRender: elementToRender, id: componentId, index: index, isAssemblyBlock: isAssembly || isAssemblyBlock, isDragDisabled: true, isSelected: selectedNodeId === componentId, userIsDragging: userIsDragging, isContainer: isContainer, blockId: node.data.blockId, coordinates: coordinates, wrapperProps: wrapperProps, onClick: onClick, onMouseOver: onMouseOver, definition: definition, displayName: displayName }));
3451
3684
  }
3452
- return (React.createElement(DraggableComponent, { placeholder: placeholder, definition: definition, id: componentId, index: index, isAssemblyBlock: isAssembly || isAssemblyBlock, isDragDisabled: isAssemblyBlock, isSelected: selectedNodeId === componentId, userIsDragging: userIsDragging, isContainer: isContainer, blockId: node.data.blockId, coordinates: coordinates, wrapperProps: wrapperProps, onClick: onClick, onMouseOver: onMouseOver },
3685
+ return (React.createElement(DraggableComponent, { placeholder: placeholder, definition: definition, id: componentId, index: index, isAssemblyBlock: isAssembly || isAssemblyBlock, isDragDisabled: isAssemblyBlock, isSelected: selectedNodeId === componentId, userIsDragging: userIsDragging, isContainer: isContainer, blockId: node.data.blockId, coordinates: coordinates, wrapperProps: wrapperProps, onClick: onClick, onMouseOver: onMouseOver, displayName: displayName },
3453
3686
  elementToRender(),
3454
3687
  isStructureComponent && userIsDragging && (React.createElement(Hitboxes, { parentZoneId: zoneId, zoneId: componentId, isEmptyZone: isEmptyZone }))));
3455
3688
  };