sanity-plugin-hotspot-array 0.0.8 → 0.1.0-v3-studio.2

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.
@@ -0,0 +1,188 @@
1
+ /* eslint-disable react/display-name */
2
+
3
+ import {getImageDimensions} from '@sanity/asset-utils'
4
+ import {
5
+ ArrayOfObjectsInputProps,
6
+ ImageValue,
7
+ insert,
8
+ ObjectSchemaType,
9
+ PatchEvent,
10
+ set,
11
+ setIfMissing,
12
+ useClient,
13
+ useFormValue,
14
+ } from 'sanity'
15
+ import imageUrlBuilder from '@sanity/image-url'
16
+ import {Card, Flex, Stack} from '@sanity/ui'
17
+ import {randomKey} from '@sanity/util/content'
18
+ import get from 'lodash/get'
19
+ import React, {useCallback, useMemo, useRef, useState} from 'react'
20
+
21
+ import {IUseResizeObserverCallback, useDebouncedCallback, useResizeObserver} from '@react-hookz/web'
22
+ import Feedback from './Feedback'
23
+ import Spot from './Spot'
24
+ import {ImageHotspotOptions} from './plugin'
25
+
26
+ const imageStyle = {width: `100%`, height: `auto`}
27
+
28
+ const VALID_ROOT_PATHS = ['document', 'parent']
29
+
30
+ export type FnHotspotMove = (key: string, x: number, y: number) => void
31
+
32
+ export type HotspotItem<HotspotFields = {[key: string]: unknown}> = {
33
+ _key: string
34
+ _type: string
35
+ x: number
36
+ y: number
37
+ } & HotspotFields
38
+
39
+ export function ImageHotspotArray(
40
+ props: ArrayOfObjectsInputProps<HotspotItem> & {imageHotspotOptions: ImageHotspotOptions}
41
+ ) {
42
+ const {value, onChange, imageHotspotOptions, schemaType, renderPreview} = props
43
+
44
+ const sanityClient = useClient({apiVersion: '2022-01-01'})
45
+
46
+ const imageHotspotPathRoot = useMemo(() => {
47
+ const pathRoot = VALID_ROOT_PATHS.includes(imageHotspotOptions.pathRoot ?? '')
48
+ ? imageHotspotOptions.pathRoot
49
+ : 'document'
50
+ return pathRoot === 'document' ? [] : props.path.slice(0, -1)
51
+ }, [imageHotspotOptions.pathRoot, props.path])
52
+
53
+ const rootObject = useFormValue(imageHotspotPathRoot)
54
+
55
+ /**
56
+ * Finding the image from the imageHotspotPathRoot (defaults to document),
57
+ * using the path from the hotspot's `options` field
58
+ *
59
+ * when changes in imageHotspotPathRoot (e.g. document) occur,
60
+ * check if there are any changes to the hotspotImage and update the reference
61
+ */
62
+ const hotspotImage = useMemo(() => {
63
+ return get(rootObject, imageHotspotOptions.imagePath) as ImageValue | undefined
64
+ }, [rootObject, imageHotspotOptions.imagePath])
65
+
66
+ const displayImage = useMemo(() => {
67
+ const builder = imageUrlBuilder(sanityClient).dataset(sanityClient.config().dataset ?? '')
68
+ const urlFor = (source: ImageValue) => builder.image(source)
69
+
70
+ if (hotspotImage?.asset?._ref) {
71
+ const {aspectRatio} = getImageDimensions(hotspotImage.asset._ref)
72
+ const width = 1200
73
+ const height = Math.round(width / aspectRatio)
74
+ const url = urlFor(hotspotImage).width(width).url()
75
+
76
+ return {width, height, url}
77
+ }
78
+
79
+ return null
80
+ }, [hotspotImage, sanityClient])
81
+
82
+ const handleHotspotImageClick = useCallback(
83
+ (event: any) => {
84
+ const {nativeEvent} = event
85
+
86
+ // Calculate the x/y percentage of the click position
87
+ const x = Number(((nativeEvent.offsetX * 100) / nativeEvent.srcElement.width).toFixed(2))
88
+ const y = Number(((nativeEvent.offsetY * 100) / nativeEvent.srcElement.height).toFixed(2))
89
+ const description = `New Hotspot at ${x}% x ${y}%`
90
+
91
+ const newRow: HotspotItem = {
92
+ _key: randomKey(12),
93
+ _type: schemaType.of[0].name,
94
+ x,
95
+ y,
96
+ }
97
+
98
+ if (imageHotspotOptions?.descriptionPath) {
99
+ newRow[imageHotspotOptions.descriptionPath] = description
100
+ }
101
+
102
+ onChange(PatchEvent.from([setIfMissing([]), insert([newRow], 'after', [-1])]))
103
+ },
104
+ [imageHotspotOptions, onChange, schemaType]
105
+ )
106
+
107
+ const handleHotspotMove: FnHotspotMove = useCallback(
108
+ (key, x, y) => {
109
+ onChange(
110
+ PatchEvent.from([
111
+ // Set the `x` value of this array key item
112
+ set(x, [{_key: key}, 'x']),
113
+ // Set the `y` value of this array key item
114
+ set(y, [{_key: key}, 'y']),
115
+ ])
116
+ )
117
+ },
118
+ [onChange]
119
+ )
120
+
121
+ const hotspotImageRef = useRef<HTMLImageElement | null>(null)
122
+
123
+ const [imageRect, setImageRect] = useState<DOMRectReadOnly>()
124
+ const updateImageRectCallback = useDebouncedCallback(
125
+ ((e) => setImageRect(e.contentRect)) as IUseResizeObserverCallback,
126
+ [setImageRect],
127
+ 200
128
+ )
129
+ useResizeObserver(hotspotImageRef, updateImageRectCallback)
130
+
131
+ return (
132
+ <Stack space={[2, 2, 3]}>
133
+ {displayImage?.url ? (
134
+ <div style={{position: `relative`}}>
135
+ {imageRect &&
136
+ (value?.length ?? 0) > 0 &&
137
+ value?.map((spot, index) => (
138
+ <Spot
139
+ index={index}
140
+ key={spot._key}
141
+ value={spot}
142
+ bounds={imageRect}
143
+ update={handleHotspotMove}
144
+ hotspotDescriptionPath={imageHotspotOptions?.descriptionPath}
145
+ tooltip={imageHotspotOptions?.tooltip}
146
+ renderPreview={renderPreview}
147
+ schemaType={schemaType.of[0] as ObjectSchemaType}
148
+ />
149
+ ))}
150
+
151
+ <Card __unstable_checkered shadow={1}>
152
+ <Flex align="center" justify="center">
153
+ <img
154
+ ref={hotspotImageRef}
155
+ src={displayImage.url}
156
+ width={displayImage.width}
157
+ height={displayImage.height}
158
+ alt=""
159
+ style={imageStyle}
160
+ onClick={handleHotspotImageClick}
161
+ />
162
+ </Flex>
163
+ </Card>
164
+ </div>
165
+ ) : (
166
+ <Feedback>
167
+ {imageHotspotOptions.imagePath ? (
168
+ <>
169
+ No Hotspot image found at path <code>{imageHotspotOptions.imagePath}</code>
170
+ </>
171
+ ) : (
172
+ <>
173
+ Define a path in this field using to the image field in this document at{' '}
174
+ <code>options.hotspotImagePath</code>
175
+ </>
176
+ )}
177
+ </Feedback>
178
+ )}
179
+ {imageHotspotOptions.pathRoot && !VALID_ROOT_PATHS.includes(imageHotspotOptions.pathRoot) && (
180
+ <Feedback>
181
+ The supplied imageHotspotPathRoot "{imageHotspotOptions.pathRoot}" is not valid, falling
182
+ back to "document". Available values are "{VALID_ROOT_PATHS.join(', ')}".
183
+ </Feedback>
184
+ )}
185
+ {props.renderDefault(props as unknown as ArrayOfObjectsInputProps)}
186
+ </Stack>
187
+ )
188
+ }
package/src/Spot.tsx CHANGED
@@ -1,8 +1,10 @@
1
+ /* eslint-disable */
1
2
  import {Box, Text, Tooltip} from '@sanity/ui'
2
3
  import {motion, useMotionValue} from 'framer-motion'
3
4
  import get from 'lodash/get'
4
- import React, {CSSProperties, ReactElement, useEffect} from 'react'
5
- import {FnHotspotMove, TSpot} from './HotspotArray'
5
+ import React, {ComponentType, CSSProperties, ReactElement, useEffect} from 'react'
6
+ import {FnHotspotMove, HotspotItem} from './ImageHotspotArray'
7
+ import {ObjectSchemaType, RenderPreviewCallback} from 'sanity'
6
8
 
7
9
  const dragStyle: CSSProperties = {
8
10
  width: '1.4rem',
@@ -61,39 +63,49 @@ const labelStyleWhileActive: CSSProperties = {
61
63
  visibility: 'hidden',
62
64
  }
63
65
 
64
- const round = (num) => Math.round(num * 100) / 100
66
+ const round = (num: number) => Math.round(num * 100) / 100
65
67
 
66
- interface IHotspot {
67
- spot: TSpot
68
+ export interface HotspotTooltipProps<HotspotFields = {[key: string]: unknown}> {
69
+ value: HotspotItem<HotspotFields>
70
+ schemaType: ObjectSchemaType
71
+ renderPreview: RenderPreviewCallback
72
+ }
73
+
74
+ interface HotspotProps<HotspotFields = {[key: string]: unknown}> {
75
+ value: HotspotItem
68
76
  bounds: DOMRectReadOnly
69
77
  update: FnHotspotMove
70
78
  hotspotDescriptionPath?: string
71
- tooltip?: ReactElement
79
+ tooltip?: ComponentType<HotspotTooltipProps<HotspotFields>>
72
80
  index: number
81
+ schemaType: ObjectSchemaType
82
+ renderPreview: RenderPreviewCallback
73
83
  }
74
84
 
75
85
  export default function Spot({
76
- spot,
86
+ value,
77
87
  bounds,
78
88
  update,
79
89
  hotspotDescriptionPath,
80
90
  tooltip,
81
91
  index,
82
- }: IHotspot) {
92
+ schemaType,
93
+ renderPreview,
94
+ }: HotspotProps) {
83
95
  const [isDragging, setIsDragging] = React.useState(false)
84
96
  const [isHovering, setIsHovering] = React.useState(false)
85
97
 
86
98
  // x/y are stored as % but need to be converted to px
87
- const x = useMotionValue(round(bounds.width * (spot.x / 100)))
88
- const y = useMotionValue(round(bounds.height * (spot.y / 100)))
99
+ const x = useMotionValue(round(bounds.width * (value.x / 100)))
100
+ const y = useMotionValue(round(bounds.height * (value.y / 100)))
89
101
 
90
102
  /**
91
103
  * update x/y if the bounds change when resizing the window
92
104
  */
93
105
  useEffect(() => {
94
- x.set(round(bounds.width * (spot.x / 100)))
95
- y.set(round(bounds.height * (spot.y / 100)))
96
- }, [bounds])
106
+ x.set(round(bounds.width * (value.x / 100)))
107
+ y.set(round(bounds.height * (value.y / 100)))
108
+ }, [x, y, value, bounds])
97
109
 
98
110
  const handleDragEnd = React.useCallback(() => {
99
111
  setIsDragging(false)
@@ -110,8 +122,8 @@ export default function Spot({
110
122
  const safeX = Math.max(0, Math.min(100, newX))
111
123
  const safeY = Math.max(0, Math.min(100, newY))
112
124
 
113
- update(spot._key, safeX, safeY)
114
- }, [spot])
125
+ update(value._key, safeX, safeY)
126
+ }, [x, y, value, update, bounds])
115
127
  const handleDragStart = React.useCallback(() => setIsDragging(true), [])
116
128
 
117
129
  const handleHoverStart = React.useCallback(() => setIsHovering(true), [])
@@ -123,18 +135,18 @@ export default function Spot({
123
135
 
124
136
  return (
125
137
  <Tooltip
126
- key={spot._key}
138
+ key={value._key}
127
139
  disabled={isDragging}
128
140
  portal
129
141
  content={
130
142
  tooltip && typeof tooltip === 'function' ? (
131
- React.createElement(tooltip, {spot})
143
+ React.createElement(tooltip, {value, renderPreview, schemaType})
132
144
  ) : (
133
145
  <Box padding={2} style={{maxWidth: 200, pointerEvents: `none`}}>
134
146
  <Text textOverflow="ellipsis">
135
147
  {hotspotDescriptionPath
136
- ? (get(spot, hotspotDescriptionPath) as string)
137
- : `${spot.x}% x ${spot.y}%`}
148
+ ? (get(value, hotspotDescriptionPath) as string)
149
+ : `${value.x}% x ${value.y}%`}
138
150
  </Text>
139
151
  </Box>
140
152
  )
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export {type HotspotItem, ImageHotspotArray} from './ImageHotspotArray'
2
+ export {type HotspotTooltipProps} from './Spot'
3
+
4
+ export {imageHotspotArrayPlugin, type ImageHotspotOptions} from './plugin'
package/src/plugin.tsx ADDED
@@ -0,0 +1,39 @@
1
+ import {ImageHotspotArray, type HotspotItem} from './ImageHotspotArray'
2
+ import React, {ComponentType} from 'react'
3
+ import {ArrayOfObjectsInputProps, definePlugin} from 'sanity'
4
+ import {type HotspotTooltipProps} from './Spot'
5
+
6
+ export interface ImageHotspotOptions<HotspotFields = {[key: string]: unknown}> {
7
+ pathRoot?: 'document' | 'parent'
8
+ imagePath: string
9
+ descriptionPath?: string
10
+ tooltip?: ComponentType<HotspotTooltipProps<HotspotFields>>
11
+ }
12
+
13
+ declare module '@sanity/types' {
14
+ export interface ArrayOptions {
15
+ imageHotspot?: ImageHotspotOptions
16
+ }
17
+ }
18
+
19
+ export const imageHotspotArrayPlugin = definePlugin({
20
+ name: 'image-hotspot-array',
21
+ form: {
22
+ components: {
23
+ input: (props) => {
24
+ if (props.schemaType.jsonType === 'array' && props.schemaType.options?.imageHotspot) {
25
+ const imageHotspotOptions = props.schemaType.options?.imageHotspot
26
+ if (imageHotspotOptions) {
27
+ return (
28
+ <ImageHotspotArray
29
+ {...(props as unknown as ArrayOfObjectsInputProps<HotspotItem>)}
30
+ imageHotspotOptions={imageHotspotOptions}
31
+ />
32
+ )
33
+ }
34
+ }
35
+ return props.renderDefault(props)
36
+ },
37
+ },
38
+ },
39
+ })
@@ -0,0 +1,11 @@
1
+ const {showIncompatiblePluginDialog} = require('@sanity/incompatible-plugin')
2
+ const {name, version, sanityExchangeUrl} = require('./package.json')
3
+
4
+ export default showIncompatiblePluginDialog({
5
+ name: name,
6
+ versions: {
7
+ v3: version,
8
+ v2: undefined,
9
+ },
10
+ sanityExchangeUrl,
11
+ })
package/.babelrc DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "sanipack/babel"
3
- }
package/lib/Feedback.js DELETED
@@ -1,23 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = Feedback;
7
-
8
- var _react = _interopRequireDefault(require("react"));
9
-
10
- var _ui = require("@sanity/ui");
11
-
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
- function Feedback(_ref) {
15
- var children = _ref.children;
16
- return /*#__PURE__*/_react.default.createElement(_ui.Card, {
17
- padding: 4,
18
- radius: 2,
19
- shadow: 1,
20
- tone: "caution"
21
- }, /*#__PURE__*/_react.default.createElement(_ui.Text, null, children));
22
- }
23
- //# sourceMappingURL=Feedback.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Feedback.js","names":["Feedback","children"],"sources":["../src/Feedback.tsx"],"sourcesContent":["import React from 'react'\nimport {Card, Text} from '@sanity/ui'\n\nexport default function Feedback({children}) {\n return (\n <Card padding={4} radius={2} shadow={1} tone=\"caution\">\n <Text>{children}</Text>\n </Card>\n )\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;;;AAEe,SAASA,QAAT,OAA8B;EAAA,IAAXC,QAAW,QAAXA,QAAW;EAC3C,oBACE,6BAAC,QAAD;IAAM,OAAO,EAAE,CAAf;IAAkB,MAAM,EAAE,CAA1B;IAA6B,MAAM,EAAE,CAArC;IAAwC,IAAI,EAAC;EAA7C,gBACE,6BAAC,QAAD,QAAOA,QAAP,CADF,CADF;AAKD"}
@@ -1,189 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- var _client = _interopRequireDefault(require("part:@sanity/base/client"));
9
-
10
- var _formBuilder = require("part:@sanity/form-builder");
11
-
12
- var _assetUtils = require("@sanity/asset-utils");
13
-
14
- var _FormBuilderInput = require("@sanity/form-builder/lib/FormBuilderInput");
15
-
16
- var _PatchEvent = require("@sanity/form-builder/PatchEvent");
17
-
18
- var _imageUrl = _interopRequireDefault(require("@sanity/image-url"));
19
-
20
- var _ui = require("@sanity/ui");
21
-
22
- var _content = require("@sanity/util/content");
23
-
24
- var _get = _interopRequireDefault(require("lodash/get"));
25
-
26
- var _react = _interopRequireWildcard(require("react"));
27
-
28
- var _web = require("@react-hookz/web");
29
-
30
- var _Feedback = _interopRequireDefault(require("./Feedback"));
31
-
32
- var _Spot = _interopRequireDefault(require("./Spot"));
33
-
34
- var _useUnsetInputComponent = require("./useUnsetInputComponent");
35
-
36
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
37
-
38
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
39
-
40
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
41
-
42
- function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
43
-
44
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
45
-
46
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
47
-
48
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
49
-
50
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
51
-
52
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
53
-
54
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
55
-
56
- var imageStyle = {
57
- width: "100%",
58
- height: "auto"
59
- };
60
- var VALID_ROOT_PATHS = ['document', 'parent'];
61
-
62
- var HotspotArray = /*#__PURE__*/_react.default.forwardRef((props, ref) => {
63
- var _type$options, _type$options2, _type$options3;
64
-
65
- var type = props.type,
66
- value = props.value,
67
- onChange = props.onChange,
68
- document = props.document;
69
-
70
- var _ref = type !== null && type !== void 0 ? type : {},
71
- options = _ref.options; // Attempt prevention of infinite loop in <FormBuilderInput />
72
- // Re-renders can still occur if this Component is used again in a nested field
73
-
74
-
75
- var typeWithoutInputComponent = (0, _useUnsetInputComponent.useUnsetInputComponent)(type, type === null || type === void 0 ? void 0 : type.inputComponent);
76
- var imageHotspotPathRoot = VALID_ROOT_PATHS.includes(options === null || options === void 0 ? void 0 : options.imageHotspotPathRoot) ? props[options.imageHotspotPathRoot] : document;
77
- /**
78
- * Finding the image from the imageHotspotPathRoot (defaults to document),
79
- * using the path from the hotspot's `options` field
80
- *
81
- * when changes in imageHotspotPathRoot (e.g. document) occur,
82
- * check if there are any changes to the hotspotImage and update the reference
83
- */
84
-
85
- var hotspotImage = _react.default.useMemo(() => {
86
- return (0, _get.default)(imageHotspotPathRoot, options === null || options === void 0 ? void 0 : options.hotspotImagePath);
87
- }, [imageHotspotPathRoot]);
88
-
89
- var displayImage = _react.default.useMemo(() => {
90
- var _hotspotImage$asset;
91
-
92
- var builder = (0, _imageUrl.default)(_client.default).dataset(_client.default.config().dataset);
93
-
94
- var urlFor = source => builder.image(source);
95
-
96
- if (hotspotImage !== null && hotspotImage !== void 0 && (_hotspotImage$asset = hotspotImage.asset) !== null && _hotspotImage$asset !== void 0 && _hotspotImage$asset._ref) {
97
- var _getImageDimensions = (0, _assetUtils.getImageDimensions)(hotspotImage.asset._ref),
98
- aspectRatio = _getImageDimensions.aspectRatio;
99
-
100
- var width = 1200;
101
- var height = Math.round(width / aspectRatio);
102
- var url = urlFor(hotspotImage).width(width).url();
103
- return {
104
- width,
105
- height,
106
- url
107
- };
108
- }
109
-
110
- return null;
111
- }, [hotspotImage]);
112
-
113
- var handleHotspotImageClick = _react.default.useCallback(event => {
114
- var nativeEvent = event.nativeEvent; // Calculate the x/y percentage of the click position
115
-
116
- var x = Number((nativeEvent.offsetX * 100 / nativeEvent.srcElement.width).toFixed(2));
117
- var y = Number((nativeEvent.offsetY * 100 / nativeEvent.srcElement.height).toFixed(2));
118
- var description = "New Hotspot at ".concat(x, "% x ").concat(y, "%");
119
- var newRow = {
120
- _key: (0, _content.randomKey)(12),
121
- _type: "spot",
122
- x,
123
- y
124
- };
125
-
126
- if (options !== null && options !== void 0 && options.hotspotDescriptionPath) {
127
- newRow[options.hotspotDescriptionPath] = description;
128
- }
129
-
130
- onChange(_PatchEvent.PatchEvent.from((0, _PatchEvent.setIfMissing)([]), (0, _PatchEvent.insert)([newRow], 'after', [-1])));
131
- }, []);
132
-
133
- var handleHotspotMove = _react.default.useCallback((key, x, y) => {
134
- onChange(_PatchEvent.PatchEvent.from( // Set the `x` value of this array key item
135
- (0, _PatchEvent.set)(x, [{
136
- _key: key
137
- }, 'x']), // Set the `y` value of this array key item
138
- (0, _PatchEvent.set)(y, [{
139
- _key: key
140
- }, 'y'])));
141
- }, [value]);
142
-
143
- var hotspotImageRef = _react.default.useRef(null);
144
-
145
- var _useState = (0, _react.useState)(),
146
- _useState2 = _slicedToArray(_useState, 2),
147
- imageRect = _useState2[0],
148
- setImageRect = _useState2[1];
149
-
150
- var updateImageRectCallback = (0, _web.useDebouncedCallback)(e => setImageRect(e.contentRect), [setImageRect], 200);
151
- (0, _web.useResizeObserver)(hotspotImageRef, updateImageRectCallback);
152
- return /*#__PURE__*/_react.default.createElement(_ui.Stack, {
153
- space: [2, 2, 3]
154
- }, displayImage !== null && displayImage !== void 0 && displayImage.url ? /*#__PURE__*/_react.default.createElement("div", {
155
- style: {
156
- position: "relative"
157
- }
158
- }, imageRect && (value === null || value === void 0 ? void 0 : value.length) > 0 && value.map((spot, index) => /*#__PURE__*/_react.default.createElement(_Spot.default, {
159
- index: index,
160
- key: spot._key,
161
- spot: spot,
162
- bounds: imageRect,
163
- update: handleHotspotMove,
164
- hotspotDescriptionPath: options === null || options === void 0 ? void 0 : options.hotspotDescriptionPath,
165
- tooltip: options === null || options === void 0 ? void 0 : options.hotspotTooltip
166
- })), /*#__PURE__*/_react.default.createElement(_ui.Card, {
167
- __unstable_checkered: true,
168
- shadow: 1
169
- }, /*#__PURE__*/_react.default.createElement(_ui.Flex, {
170
- align: "center",
171
- justify: "center"
172
- }, /*#__PURE__*/_react.default.createElement("img", {
173
- ref: hotspotImageRef,
174
- src: displayImage.url,
175
- width: displayImage.width,
176
- height: displayImage.height,
177
- alt: "",
178
- style: imageStyle,
179
- onClick: handleHotspotImageClick
180
- })))) : /*#__PURE__*/_react.default.createElement(_Feedback.default, null, type !== null && type !== void 0 && (_type$options = type.options) !== null && _type$options !== void 0 && _type$options.hotspotImagePath ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "No Hotspot image found at path ", /*#__PURE__*/_react.default.createElement("code", null, type === null || type === void 0 ? void 0 : (_type$options2 = type.options) === null || _type$options2 === void 0 ? void 0 : _type$options2.hotspotImagePath)) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "Define a path in this field using to the image field in this document at", ' ', /*#__PURE__*/_react.default.createElement("code", null, "options.hotspotImagePath"))), (type === null || type === void 0 ? void 0 : (_type$options3 = type.options) === null || _type$options3 === void 0 ? void 0 : _type$options3.imageHotspotPathRoot) && !VALID_ROOT_PATHS.includes(type.options.imageHotspotPathRoot) && /*#__PURE__*/_react.default.createElement(_Feedback.default, null, "The supplied imageHotspotPathRoot \"", type.options.imageHotspotPathRoot, "\" is not valid, falling back to \"document\". Available values are \"", VALID_ROOT_PATHS.join(', '), "\"."), /*#__PURE__*/_react.default.createElement(_FormBuilderInput.FormBuilderInput, _extends({}, props, {
181
- type: typeWithoutInputComponent,
182
- ref: ref
183
- })));
184
- });
185
-
186
- var _default = (0, _formBuilder.withDocument)(HotspotArray);
187
-
188
- exports.default = _default;
189
- //# sourceMappingURL=HotspotArray.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"HotspotArray.js","names":["imageStyle","width","height","VALID_ROOT_PATHS","HotspotArray","React","forwardRef","props","ref","type","value","onChange","document","options","typeWithoutInputComponent","useUnsetInputComponent","inputComponent","imageHotspotPathRoot","includes","hotspotImage","useMemo","get","hotspotImagePath","displayImage","builder","imageUrlBuilder","sanityClient","dataset","config","urlFor","source","image","asset","_ref","getImageDimensions","aspectRatio","Math","round","url","handleHotspotImageClick","useCallback","event","nativeEvent","x","Number","offsetX","srcElement","toFixed","y","offsetY","description","newRow","_key","randomKey","_type","hotspotDescriptionPath","PatchEvent","from","setIfMissing","insert","handleHotspotMove","key","set","hotspotImageRef","useRef","useState","imageRect","setImageRect","updateImageRectCallback","useDebouncedCallback","e","contentRect","useResizeObserver","position","length","map","spot","index","hotspotTooltip","join","withDocument"],"sources":["../src/HotspotArray.tsx"],"sourcesContent":["/* eslint-disable react/display-name */\n\n// @ts-ignore\nimport sanityClient from 'part:@sanity/base/client'\n// @ts-ignore\nimport {withDocument} from 'part:@sanity/form-builder'\n\nimport {getImageDimensions} from '@sanity/asset-utils'\nimport {FormBuilderInput} from '@sanity/form-builder/lib/FormBuilderInput'\nimport {insert, PatchEvent, set, setIfMissing} from '@sanity/form-builder/PatchEvent'\nimport imageUrlBuilder from '@sanity/image-url'\nimport {Card, Flex, Stack} from '@sanity/ui'\nimport {randomKey} from '@sanity/util/content'\nimport get from 'lodash/get'\nimport React, {useState} from 'react'\n\nimport {IUseResizeObserverCallback, useDebouncedCallback, useResizeObserver} from '@react-hookz/web'\nimport Feedback from './Feedback'\nimport Spot from './Spot'\nimport {useUnsetInputComponent} from './useUnsetInputComponent'\n\nconst imageStyle = {width: `100%`, height: `auto`}\n\nconst VALID_ROOT_PATHS = ['document', 'parent']\n\nexport type FnHotspotMove = (key: string, x: number, y: number) => void\n\nexport type TSpot = {\n _key: string\n _type: `spot`\n x: number\n y: number\n} & {[key: string]: unknown}\n\nconst HotspotArray = React.forwardRef((props: any, ref) => {\n const {type, value, onChange, document} = props\n const {options} = type ?? {}\n\n // Attempt prevention of infinite loop in <FormBuilderInput />\n // Re-renders can still occur if this Component is used again in a nested field\n const typeWithoutInputComponent = useUnsetInputComponent(type, type?.inputComponent)\n const imageHotspotPathRoot = VALID_ROOT_PATHS.includes(options?.imageHotspotPathRoot)\n ? props[options.imageHotspotPathRoot]\n : document\n\n /**\n * Finding the image from the imageHotspotPathRoot (defaults to document),\n * using the path from the hotspot's `options` field\n *\n * when changes in imageHotspotPathRoot (e.g. document) occur,\n * check if there are any changes to the hotspotImage and update the reference\n */\n const hotspotImage = React.useMemo(() => {\n return get(imageHotspotPathRoot, options?.hotspotImagePath)\n }, [imageHotspotPathRoot])\n\n const displayImage = React.useMemo(() => {\n const builder = imageUrlBuilder(sanityClient).dataset(sanityClient.config().dataset)\n const urlFor = (source) => builder.image(source)\n\n if (hotspotImage?.asset?._ref) {\n const {aspectRatio} = getImageDimensions(hotspotImage.asset._ref)\n const width = 1200\n const height = Math.round(width / aspectRatio)\n const url = urlFor(hotspotImage).width(width).url()\n\n return {width, height, url}\n }\n\n return null\n }, [hotspotImage])\n\n const handleHotspotImageClick = React.useCallback((event) => {\n const {nativeEvent} = event\n\n // Calculate the x/y percentage of the click position\n const x = Number(((nativeEvent.offsetX * 100) / nativeEvent.srcElement.width).toFixed(2))\n const y = Number(((nativeEvent.offsetY * 100) / nativeEvent.srcElement.height).toFixed(2))\n const description = `New Hotspot at ${x}% x ${y}%`\n\n const newRow: TSpot = {\n _key: randomKey(12),\n _type: `spot`,\n x,\n y,\n }\n\n if (options?.hotspotDescriptionPath) {\n newRow[options.hotspotDescriptionPath] = description\n }\n\n onChange(PatchEvent.from(setIfMissing([]), insert([newRow], 'after', [-1])))\n }, [])\n\n const handleHotspotMove: FnHotspotMove = React.useCallback(\n (key, x, y) => {\n onChange(\n PatchEvent.from(\n // Set the `x` value of this array key item\n set(x, [{_key: key}, 'x']),\n // Set the `y` value of this array key item\n set(y, [{_key: key}, 'y'])\n )\n )\n },\n [value]\n )\n\n const hotspotImageRef = React.useRef<HTMLImageElement | null>(null)\n\n const [imageRect, setImageRect] = useState<DOMRectReadOnly>()\n const updateImageRectCallback = useDebouncedCallback(\n ((e) => setImageRect(e.contentRect)) as IUseResizeObserverCallback,\n [setImageRect],\n 200\n )\n useResizeObserver(hotspotImageRef, updateImageRectCallback)\n\n return (\n <Stack space={[2, 2, 3]}>\n {displayImage?.url ? (\n <div style={{position: `relative`}}>\n {imageRect &&\n value?.length > 0 &&\n value.map((spot, index) => (\n <Spot\n index={index}\n key={spot._key}\n spot={spot}\n bounds={imageRect}\n update={handleHotspotMove}\n hotspotDescriptionPath={options?.hotspotDescriptionPath}\n tooltip={options?.hotspotTooltip}\n />\n ))}\n\n <Card __unstable_checkered shadow={1}>\n <Flex align=\"center\" justify=\"center\">\n <img\n ref={hotspotImageRef}\n src={displayImage.url}\n width={displayImage.width}\n height={displayImage.height}\n alt=\"\"\n style={imageStyle}\n onClick={handleHotspotImageClick}\n />\n </Flex>\n </Card>\n </div>\n ) : (\n <Feedback>\n {type?.options?.hotspotImagePath ? (\n <>\n No Hotspot image found at path <code>{type?.options?.hotspotImagePath}</code>\n </>\n ) : (\n <>\n Define a path in this field using to the image field in this document at{' '}\n <code>options.hotspotImagePath</code>\n </>\n )}\n </Feedback>\n )}\n {type?.options?.imageHotspotPathRoot &&\n !VALID_ROOT_PATHS.includes(type.options.imageHotspotPathRoot) && (\n <Feedback>\n The supplied imageHotspotPathRoot \"{type.options.imageHotspotPathRoot}\" is not valid,\n falling back to \"document\". Available values are \"{VALID_ROOT_PATHS.join(', ')}\".\n </Feedback>\n )}\n <FormBuilderInput {...props} type={typeWithoutInputComponent} ref={ref} />\n </Stack>\n )\n})\n\nexport default withDocument(HotspotArray)\n"],"mappings":";;;;;;;AAGA;;AAEA;;AAEA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AACA;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAMA,UAAU,GAAG;EAACC,KAAK,QAAN;EAAgBC,MAAM;AAAtB,CAAnB;AAEA,IAAMC,gBAAgB,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