sanity-plugin-hotspot-array 0.1.0 → 1.0.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/lib/Spot.js DELETED
@@ -1,157 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = Spot;
7
- var _ui = require("@sanity/ui");
8
- var _framerMotion = require("framer-motion");
9
- var _get = _interopRequireDefault(require("lodash/get"));
10
- var _react = _interopRequireWildcard(require("react"));
11
- 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); }
12
- 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; }
13
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
15
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
16
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
17
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
18
- 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."); }
19
- 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); }
20
- 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; }
21
- 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; }
22
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
23
- var dragStyle = {
24
- width: '1.4rem',
25
- height: '1.4rem',
26
- position: 'absolute',
27
- boxSizing: 'border-box',
28
- top: 0,
29
- left: 0,
30
- margin: '-0.7rem 0 0 -0.7rem',
31
- cursor: 'pointer',
32
- display: 'flex',
33
- justifyContent: 'center',
34
- alignItems: 'center',
35
- borderRadius: '50%',
36
- background: '#000',
37
- color: 'white'
38
- };
39
- var dragStyleWhileDrag = {
40
- background: 'rgba(0, 0, 0, 0.1)',
41
- border: '1px solid #fff',
42
- cursor: 'none'
43
- };
44
- var dragStyleWhileHover = {
45
- background: 'rgba(0, 0, 0, 0.1)',
46
- border: '1px solid #fff'
47
- };
48
- var dotStyle = {
49
- position: 'absolute',
50
- left: '50%',
51
- top: '50%',
52
- height: '0.2rem',
53
- width: '0.2rem',
54
- margin: '-0.1rem 0 0 -0.1rem',
55
- background: '#fff',
56
- visibility: 'hidden',
57
- borderRadius: '50%',
58
- // make sure pointer events only run on the parent
59
- pointerEvents: 'none'
60
- };
61
- var dotStyleWhileActive = {
62
- visibility: 'visible'
63
- };
64
- var labelStyle = {
65
- color: 'white',
66
- fontSize: '0.7rem',
67
- fontWeight: 600,
68
- lineHeight: '1'
69
- };
70
- var labelStyleWhileActive = {
71
- visibility: 'hidden'
72
- };
73
- var round = num => Math.round(num * 100) / 100;
74
- function Spot(_ref) {
75
- var spot = _ref.spot,
76
- bounds = _ref.bounds,
77
- update = _ref.update,
78
- hotspotDescriptionPath = _ref.hotspotDescriptionPath,
79
- tooltip = _ref.tooltip,
80
- index = _ref.index;
81
- var _React$useState = _react.default.useState(false),
82
- _React$useState2 = _slicedToArray(_React$useState, 2),
83
- isDragging = _React$useState2[0],
84
- setIsDragging = _React$useState2[1];
85
- var _React$useState3 = _react.default.useState(false),
86
- _React$useState4 = _slicedToArray(_React$useState3, 2),
87
- isHovering = _React$useState4[0],
88
- setIsHovering = _React$useState4[1];
89
-
90
- // x/y are stored as % but need to be converted to px
91
- var x = (0, _framerMotion.useMotionValue)(round(bounds.width * (spot.x / 100)));
92
- var y = (0, _framerMotion.useMotionValue)(round(bounds.height * (spot.y / 100)));
93
-
94
- /**
95
- * update x/y if the bounds change when resizing the window
96
- */
97
- (0, _react.useEffect)(() => {
98
- x.set(round(bounds.width * (spot.x / 100)));
99
- y.set(round(bounds.height * (spot.y / 100)));
100
- }, [bounds]);
101
- var handleDragEnd = _react.default.useCallback(() => {
102
- setIsDragging(false);
103
-
104
- // get current values for x/y in px
105
- var currentX = x.get();
106
- var currentY = y.get();
107
-
108
- // Which we need to convert back to `%` to patch the document
109
- var newX = round(currentX * 100 / bounds.width);
110
- var newY = round(currentY * 100 / bounds.height);
111
-
112
- // Don't go below 0 or above 100
113
- var safeX = Math.max(0, Math.min(100, newX));
114
- var safeY = Math.max(0, Math.min(100, newY));
115
- update(spot._key, safeX, safeY);
116
- }, [spot]);
117
- var handleDragStart = _react.default.useCallback(() => setIsDragging(true), []);
118
- var handleHoverStart = _react.default.useCallback(() => setIsHovering(true), []);
119
- var handleHoverEnd = _react.default.useCallback(() => setIsHovering(false), []);
120
- if (!x || !y) {
121
- return null;
122
- }
123
- return /*#__PURE__*/_react.default.createElement(_ui.Tooltip, {
124
- key: spot._key,
125
- disabled: isDragging,
126
- portal: true,
127
- content: tooltip && typeof tooltip === 'function' ? /*#__PURE__*/_react.default.createElement(tooltip, {
128
- spot
129
- }) : /*#__PURE__*/_react.default.createElement(_ui.Box, {
130
- padding: 2,
131
- style: {
132
- maxWidth: 200,
133
- pointerEvents: "none"
134
- }
135
- }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
136
- textOverflow: "ellipsis"
137
- }, hotspotDescriptionPath ? (0, _get.default)(spot, hotspotDescriptionPath) : "".concat(spot.x, "% x ").concat(spot.y, "%")))
138
- }, /*#__PURE__*/_react.default.createElement(_framerMotion.motion.div, {
139
- drag: true,
140
- dragConstraints: bounds,
141
- dragElastic: 0,
142
- dragMomentum: false,
143
- onDragEnd: handleDragEnd,
144
- onDragStart: handleDragStart,
145
- onHoverStart: handleHoverStart,
146
- onHoverEnd: handleHoverEnd,
147
- style: _objectSpread(_objectSpread(_objectSpread({}, dragStyle), {}, {
148
- x,
149
- y
150
- }, isDragging && _objectSpread({}, dragStyleWhileDrag)), isHovering && _objectSpread({}, dragStyleWhileHover))
151
- }, /*#__PURE__*/_react.default.createElement(_ui.Box, {
152
- style: _objectSpread(_objectSpread({}, dotStyle), (isDragging || isHovering) && _objectSpread({}, dotStyleWhileActive))
153
- }), /*#__PURE__*/_react.default.createElement("div", {
154
- style: _objectSpread(_objectSpread({}, labelStyle), (isDragging || isHovering) && _objectSpread({}, labelStyleWhileActive))
155
- }, index + 1)));
156
- }
157
- //# sourceMappingURL=Spot.js.map
package/lib/Spot.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"Spot.js","names":["dragStyle","width","height","position","boxSizing","top","left","margin","cursor","display","justifyContent","alignItems","borderRadius","background","color","dragStyleWhileDrag","border","dragStyleWhileHover","dotStyle","visibility","pointerEvents","dotStyleWhileActive","labelStyle","fontSize","fontWeight","lineHeight","labelStyleWhileActive","round","num","Math","Spot","spot","bounds","update","hotspotDescriptionPath","tooltip","index","React","useState","isDragging","setIsDragging","isHovering","setIsHovering","x","useMotionValue","y","useEffect","set","handleDragEnd","useCallback","currentX","get","currentY","newX","newY","safeX","max","min","safeY","_key","handleDragStart","handleHoverStart","handleHoverEnd","createElement","maxWidth"],"sources":["../src/Spot.tsx"],"sourcesContent":["import {Box, Text, Tooltip} from '@sanity/ui'\nimport {motion, useMotionValue} from 'framer-motion'\nimport get from 'lodash/get'\nimport React, {CSSProperties, ReactElement, useEffect} from 'react'\nimport {FnHotspotMove, TSpot} from './HotspotArray'\n\nconst dragStyle: CSSProperties = {\n width: '1.4rem',\n height: '1.4rem',\n position: 'absolute',\n boxSizing: 'border-box',\n top: 0,\n left: 0,\n margin: '-0.7rem 0 0 -0.7rem',\n cursor: 'pointer',\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n borderRadius: '50%',\n background: '#000',\n color: 'white',\n}\n\nconst dragStyleWhileDrag: CSSProperties = {\n background: 'rgba(0, 0, 0, 0.1)',\n border: '1px solid #fff',\n cursor: 'none',\n}\n\nconst dragStyleWhileHover: CSSProperties = {\n background: 'rgba(0, 0, 0, 0.1)',\n border: '1px solid #fff',\n}\n\nconst dotStyle: CSSProperties = {\n position: 'absolute',\n left: '50%',\n top: '50%',\n height: '0.2rem',\n width: '0.2rem',\n margin: '-0.1rem 0 0 -0.1rem',\n background: '#fff',\n visibility: 'hidden',\n borderRadius: '50%',\n // make sure pointer events only run on the parent\n pointerEvents: 'none',\n}\n\nconst dotStyleWhileActive: CSSProperties = {\n visibility: 'visible',\n}\n\nconst labelStyle: CSSProperties = {\n color: 'white',\n fontSize: '0.7rem',\n fontWeight: 600,\n lineHeight: '1',\n}\n\nconst labelStyleWhileActive: CSSProperties = {\n visibility: 'hidden',\n}\n\nconst round = (num) => Math.round(num * 100) / 100\n\ninterface IHotspot {\n spot: TSpot\n bounds: DOMRectReadOnly\n update: FnHotspotMove\n hotspotDescriptionPath?: string\n tooltip?: ReactElement\n index: number\n}\n\nexport default function Spot({\n spot,\n bounds,\n update,\n hotspotDescriptionPath,\n tooltip,\n index,\n}: IHotspot) {\n const [isDragging, setIsDragging] = React.useState(false)\n const [isHovering, setIsHovering] = React.useState(false)\n\n // x/y are stored as % but need to be converted to px\n const x = useMotionValue(round(bounds.width * (spot.x / 100)))\n const y = useMotionValue(round(bounds.height * (spot.y / 100)))\n\n /**\n * update x/y if the bounds change when resizing the window\n */\n useEffect(() => {\n x.set(round(bounds.width * (spot.x / 100)))\n y.set(round(bounds.height * (spot.y / 100)))\n }, [bounds])\n\n const handleDragEnd = React.useCallback(() => {\n setIsDragging(false)\n\n // get current values for x/y in px\n const currentX = x.get()\n const currentY = y.get()\n\n // Which we need to convert back to `%` to patch the document\n const newX = round((currentX * 100) / bounds.width)\n const newY = round((currentY * 100) / bounds.height)\n\n // Don't go below 0 or above 100\n const safeX = Math.max(0, Math.min(100, newX))\n const safeY = Math.max(0, Math.min(100, newY))\n\n update(spot._key, safeX, safeY)\n }, [spot])\n const handleDragStart = React.useCallback(() => setIsDragging(true), [])\n\n const handleHoverStart = React.useCallback(() => setIsHovering(true), [])\n const handleHoverEnd = React.useCallback(() => setIsHovering(false), [])\n\n if (!x || !y) {\n return null\n }\n\n return (\n <Tooltip\n key={spot._key}\n disabled={isDragging}\n portal\n content={\n tooltip && typeof tooltip === 'function' ? (\n React.createElement(tooltip, {spot})\n ) : (\n <Box padding={2} style={{maxWidth: 200, pointerEvents: `none`}}>\n <Text textOverflow=\"ellipsis\">\n {hotspotDescriptionPath\n ? (get(spot, hotspotDescriptionPath) as string)\n : `${spot.x}% x ${spot.y}%`}\n </Text>\n </Box>\n )\n }\n >\n <motion.div\n drag\n dragConstraints={bounds}\n dragElastic={0}\n dragMomentum={false}\n onDragEnd={handleDragEnd}\n onDragStart={handleDragStart}\n onHoverStart={handleHoverStart}\n onHoverEnd={handleHoverEnd}\n style={{\n ...dragStyle,\n x,\n y,\n ...(isDragging && {...dragStyleWhileDrag}),\n ...(isHovering && {...dragStyleWhileHover}),\n }}\n >\n {/* Dot */}\n <Box\n style={{\n ...dotStyle,\n ...((isDragging || isHovering) && {...dotStyleWhileActive}),\n }}\n />\n {/* Label */}\n <div\n style={{\n ...labelStyle,\n ...((isDragging || isHovering) && {...labelStyleWhileActive}),\n }}\n >\n {index + 1}\n </div>\n </motion.div>\n </Tooltip>\n )\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AAAmE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGnE,IAAMA,SAAwB,GAAG;EAC/BC,KAAK,EAAE,QAAQ;EACfC,MAAM,EAAE,QAAQ;EAChBC,QAAQ,EAAE,UAAU;EACpBC,SAAS,EAAE,YAAY;EACvBC,GAAG,EAAE,CAAC;EACNC,IAAI,EAAE,CAAC;EACPC,MAAM,EAAE,qBAAqB;EAC7BC,MAAM,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6BAAC,oBAAM,CAAC,GAAG;IACT,IAAI;IACJ,eAAe,EAAEb,MAAO;IACxB,WAAW,EAAE,CAAE;IACf,YAAY,EAAE,KAAM;IACpB,SAAS,EAAEgB,aAAc;IACzB,WAAW,EAAEY,eAAgB;IAC7B,YAAY,EAAEC,gBAAiB;IAC/B,UAAU,EAAEC,cAAe;IAC3B,KAAK,gDACA9D,SAAS;MACZ2C,CAAC;MACDE;IAAC,GACGN,UAAU,sBAAQxB,kBAAkB,CAAC,GACrC0B,UAAU,sBAAQxB,mBAAmB,CAAC;EAC1C,gBAGF,6BAAC,OAAG;IACF,KAAK,kCACAC,QAAQ,GACP,CAACqB,UAAU,IAAIE,UAAU,uBAASpB,mBAAmB,CAAC;EAC1D,EACF,eAEF;IACE,KAAK,kCACAC,UAAU,GACT,CAACiB,UAAU,IAAIE,UAAU,uBAASf,qBAAqB,CAAC;EAC5D,GAEDU,KAAK,GAAG,CAAC,CACN,CACK,CACL;AAEd"}
@@ -1,24 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.useUnsetInputComponent = useUnsetInputComponent;
7
- var _react = _interopRequireDefault(require("react"));
8
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
10
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
11
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
- function useUnsetInputComponent(type, component) {
13
- return _react.default.useMemo(() => unsetInputComponent(type, component), [type, component]);
14
- }
15
- function unsetInputComponent(type, component) {
16
- var t = _objectSpread(_objectSpread({}, type), {}, {
17
- inputComponent: type.inputComponent === component ? undefined : type.inputComponent
18
- });
19
- var typeOfType = t.type ? unsetInputComponent(t.type, component) : undefined;
20
- return _objectSpread(_objectSpread({}, t), {}, {
21
- type: typeOfType
22
- });
23
- }
24
- //# sourceMappingURL=useUnsetInputComponent.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useUnsetInputComponent.js","names":["useUnsetInputComponent","type","component","React","useMemo","unsetInputComponent","t","inputComponent","undefined","typeOfType"],"sources":["../src/useUnsetInputComponent.ts"],"sourcesContent":["import React from 'react'\n\nexport function useUnsetInputComponent(type, component) {\n return React.useMemo(() => unsetInputComponent(type, component), [type, component])\n}\n\nfunction unsetInputComponent(type, component) {\n const t = {\n ...type,\n inputComponent: type.inputComponent === component ? undefined : type.inputComponent,\n }\n const typeOfType = t.type ? unsetInputComponent(t.type, component) : undefined\n return {\n ...t,\n type: typeOfType,\n }\n}\n"],"mappings":";;;;;;AAAA;AAAyB;AAAA;AAAA;AAAA;AAElB,SAASA,sBAAsB,CAACC,IAAI,EAAEC,SAAS,EAAE;EACtD,OAAOC,cAAK,CAACC,OAAO,CAAC,MAAMC,mBAAmB,CAACJ,IAAI,EAAEC,SAAS,CAAC,EAAE,CAACD,IAAI,EAAEC,SAAS,CAAC,CAAC;AACrF;AAEA,SAASG,mBAAmB,CAACJ,IAAI,EAAEC,SAAS,EAAE;EAC5C,IAAMI,CAAC,mCACFL,IAAI;IACPM,cAAc,EAAEN,IAAI,CAACM,cAAc,KAAKL,SAAS,GAAGM,SAAS,GAAGP,IAAI,CAACM;EAAc,EACpF;EACD,IAAME,UAAU,GAAGH,CAAC,CAACL,IAAI,GAAGI,mBAAmB,CAACC,CAAC,CAACL,IAAI,EAAEC,SAAS,CAAC,GAAGM,SAAS;EAC9E,uCACKF,CAAC;IACJL,IAAI,EAAEQ;EAAU;AAEpB"}
@@ -1,178 +0,0 @@
1
- /* eslint-disable react/display-name */
2
-
3
- // @ts-ignore
4
- import sanityClient from 'part:@sanity/base/client'
5
- // @ts-ignore
6
- import {withDocument, withParent} from 'part:@sanity/form-builder'
7
-
8
- import {getImageDimensions} from '@sanity/asset-utils'
9
- import {insert, PatchEvent, set, setIfMissing} from '@sanity/form-builder/PatchEvent'
10
- import imageUrlBuilder from '@sanity/image-url'
11
- import {Card, Flex, Stack} from '@sanity/ui'
12
- import {randomKey} from '@sanity/util/content'
13
- import get from 'lodash/get'
14
- import React, {useState} from 'react'
15
-
16
- import {IUseResizeObserverCallback, useDebouncedCallback, useResizeObserver} from '@react-hookz/web'
17
- import Feedback from './Feedback'
18
- import Spot from './Spot'
19
- import {useUnsetInputComponent} from './useUnsetInputComponent'
20
- import { NestedFormBuilder } from './NestedFormBuilder'
21
-
22
- const imageStyle = {width: `100%`, height: `auto`}
23
-
24
- const VALID_ROOT_PATHS = ['document', 'parent']
25
-
26
- export type FnHotspotMove = (key: string, x: number, y: number) => void
27
-
28
- export type TSpot = {
29
- _key: string
30
- _type: `spot`
31
- x: number
32
- y: number
33
- } & {[key: string]: unknown}
34
-
35
- const HotspotArray = React.forwardRef((props: any, ref) => {
36
- console.log(props);
37
- const {type, value, onChange, document} = props
38
- const {options} = type ?? {}
39
-
40
- // Attempt prevention of infinite loop in <FormBuilderInput />
41
- // Re-renders can still occur if this Component is used again in a nested field
42
- const typeWithoutInputComponent = useUnsetInputComponent(type, type?.inputComponent)
43
- const imageHotspotPathRoot = VALID_ROOT_PATHS.includes(options?.imageHotspotPathRoot)
44
- ? props[options.imageHotspotPathRoot]
45
- : document
46
-
47
- /**
48
- * Finding the image from the imageHotspotPathRoot (defaults to document),
49
- * using the path from the hotspot's `options` field
50
- *
51
- * when changes in imageHotspotPathRoot (e.g. document) occur,
52
- * check if there are any changes to the hotspotImage and update the reference
53
- */
54
- const hotspotImage = React.useMemo(() => {
55
- return get(imageHotspotPathRoot, options?.hotspotImagePath)
56
- }, [imageHotspotPathRoot])
57
-
58
- const displayImage = React.useMemo(() => {
59
- const builder = imageUrlBuilder(sanityClient).dataset(sanityClient.config().dataset)
60
- const urlFor = (source) => builder.image(source)
61
-
62
- if (hotspotImage?.asset?._ref) {
63
- const {aspectRatio} = getImageDimensions(hotspotImage.asset._ref)
64
- const width = 1200
65
- const height = Math.round(width / aspectRatio)
66
- const url = urlFor(hotspotImage).width(width).url()
67
-
68
- return {width, height, url}
69
- }
70
-
71
- return null
72
- }, [hotspotImage])
73
-
74
- const handleHotspotImageClick = React.useCallback((event) => {
75
- const {nativeEvent} = event
76
-
77
- // Calculate the x/y percentage of the click position
78
- const x = Number(((nativeEvent.offsetX * 100) / nativeEvent.srcElement.width).toFixed(2))
79
- const y = Number(((nativeEvent.offsetY * 100) / nativeEvent.srcElement.height).toFixed(2))
80
- const description = `New Hotspot at ${x}% x ${y}%`
81
-
82
- const newRow: TSpot = {
83
- _key: randomKey(12),
84
- _type: `spot`,
85
- x,
86
- y,
87
- }
88
-
89
- if (options?.hotspotDescriptionPath) {
90
- newRow[options.hotspotDescriptionPath] = description
91
- }
92
-
93
- onChange(PatchEvent.from(setIfMissing([]), insert([newRow], 'after', [-1])))
94
- }, [])
95
-
96
- const handleHotspotMove: FnHotspotMove = React.useCallback(
97
- (key, x, y) => {
98
- onChange(
99
- PatchEvent.from(
100
- // Set the `x` value of this array key item
101
- set(x, [{_key: key}, 'x']),
102
- // Set the `y` value of this array key item
103
- set(y, [{_key: key}, 'y'])
104
- )
105
- )
106
- },
107
- [value]
108
- )
109
-
110
- const hotspotImageRef = React.useRef<HTMLImageElement | null>(null)
111
-
112
- const [imageRect, setImageRect] = useState<DOMRectReadOnly>()
113
- const updateImageRectCallback = useDebouncedCallback(
114
- ((e) => setImageRect(e.contentRect)) as IUseResizeObserverCallback,
115
- [setImageRect],
116
- 200
117
- )
118
- useResizeObserver(hotspotImageRef, updateImageRectCallback)
119
-
120
- return (
121
- <Stack space={[2, 2, 3]}>
122
- {displayImage?.url ? (
123
- <div style={{position: `relative`}}>
124
- {imageRect &&
125
- value?.length > 0 &&
126
- value.map((spot, index) => (
127
- <Spot
128
- index={index}
129
- key={spot._key}
130
- spot={spot}
131
- bounds={imageRect}
132
- update={handleHotspotMove}
133
- hotspotDescriptionPath={options?.hotspotDescriptionPath}
134
- tooltip={options?.hotspotTooltip}
135
- />
136
- ))}
137
-
138
- <Card __unstable_checkered shadow={1}>
139
- <Flex align="center" justify="center">
140
- <img
141
- ref={hotspotImageRef}
142
- src={displayImage.url}
143
- width={displayImage.width}
144
- height={displayImage.height}
145
- alt=""
146
- style={imageStyle}
147
- onClick={handleHotspotImageClick}
148
- />
149
- </Flex>
150
- </Card>
151
- </div>
152
- ) : (
153
- <Feedback>
154
- {type?.options?.hotspotImagePath ? (
155
- <>
156
- No Hotspot image found at path <code>{type?.options?.hotspotImagePath}</code>
157
- </>
158
- ) : (
159
- <>
160
- Define a path in this field using to the image field in this document at{' '}
161
- <code>options.hotspotImagePath</code>
162
- </>
163
- )}
164
- </Feedback>
165
- )}
166
- {type?.options?.imageHotspotPathRoot &&
167
- !VALID_ROOT_PATHS.includes(type.options.imageHotspotPathRoot) && (
168
- <Feedback>
169
- The supplied imageHotspotPathRoot "{type.options.imageHotspotPathRoot}" is not valid,
170
- falling back to "document". Available values are "{VALID_ROOT_PATHS.join(', ')}".
171
- </Feedback>
172
- )}
173
- <NestedFormBuilder {...props} type={typeWithoutInputComponent} ref={ref} />
174
- </Stack>
175
- )
176
- })
177
-
178
- export default withParent(withDocument(HotspotArray))
@@ -1,44 +0,0 @@
1
- import React from 'react';
2
- import { FormBuilderInput } from '@sanity/form-builder/lib/FormBuilderInput';
3
-
4
- /**
5
- * Nesting FormBuilderInput components results in inconsistent focus & tab-index behaviour.
6
- *
7
- * FormBuilderInputs requests focus if props.focusPath matches the input.focusPath
8
- * when mounted and when props change. If multiple components "handle" the same focus path,
9
- * there is a race-condition on which component will receive the focus, often resulting
10
- * in seemingly random scrollbehaviour.
11
- *
12
- * This is a workaround, reusing as much of FormBuilderInput as possible.
13
- *
14
- * Use FormBuilderInput when you need to render a field obtained from a SchemaType (type.fields or type.fieldset[].field).
15
- *
16
- * Use NestedFormBuilder for decorator components that are used as inputComponent or in input-resolver.ts.
17
- *
18
- * Decorator components are components that just want to modify a type, add some markup or so on,
19
- * then delegate back to Sanity to obtain an actual input implementation.
20
- *
21
- * FormBuilderInput should only be used as the outermost component when resolving
22
- * inputs recursively.
23
- */
24
-
25
- export class NestedFormBuilder extends FormBuilderInput {
26
- componentDidMount() {
27
- // do nothing - prevent focus-bug when nesting FormBuilderInput
28
- }
29
-
30
- // eslint-disable-next-line camelcase
31
- UNSAFE_componentWillReceiveProps() {
32
- // do nothing - prevent focus-bug when nesting FormBuilderInput
33
- }
34
-
35
- componentDidUpdate() {
36
- // do nothing - prevent focus-bug when nesting FormBuilderInput
37
- }
38
-
39
- render(): JSX.Element {
40
- const { type } = this.props;
41
- const InputComponent = this.resolveInputComponent(type);
42
- return <InputComponent {...this.props} ref={this.setInput} />;
43
- }
44
- }
@@ -1,17 +0,0 @@
1
- import React from 'react'
2
-
3
- export function useUnsetInputComponent(type, component) {
4
- return React.useMemo(() => unsetInputComponent(type, component), [type, component])
5
- }
6
-
7
- function unsetInputComponent(type, component) {
8
- const t = {
9
- ...type,
10
- inputComponent: type.inputComponent === component ? undefined : type.inputComponent,
11
- }
12
- const typeOfType = t.type ? unsetInputComponent(t.type, component) : undefined
13
- return {
14
- ...t,
15
- type: typeOfType,
16
- }
17
- }