UNPKG

sanity-plugin-utils

Version:

Handy hooks and clever components for Sanity Studio v3

653 lines (649 loc) 32.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var jsxRuntime = require("react/jsx-runtime"), ui = require("@sanity/ui"), styledComponents = require("styled-components"), icons = require("@sanity/icons"), react = require("react"), sanity = require("sanity"), isEqual = require("react-fast-compare"), operators = require("rxjs/operators"), router = require("sanity/router"), structure = require("sanity/structure"); function _interopDefaultCompat(e) { return e && typeof e == "object" && "default" in e ? e : { default: e }; } var isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), __defProp$3 = Object.defineProperty, __getOwnPropSymbols$3 = Object.getOwnPropertySymbols, __hasOwnProp$3 = Object.prototype.hasOwnProperty, __propIsEnum$3 = Object.prototype.propertyIsEnumerable, __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$3 = (a, b) => { for (var prop in b || (b = {})) __hasOwnProp$3.call(b, prop) && __defNormalProp$3(a, prop, b[prop]); if (__getOwnPropSymbols$3) for (var prop of __getOwnPropSymbols$3(b)) __propIsEnum$3.call(b, prop) && __defNormalProp$3(a, prop, b[prop]); return a; }; const DEFAULT_PROPS = { tone: "primary" }; function Feedback(props) { const { title, description, icon, tone, children } = __spreadValues$3(__spreadValues$3({}, DEFAULT_PROPS), props); return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { tone, padding: 4, radius: 3, border: !0, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { children: [ icon ? "display icon" : null, children || /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { flex: 1, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 4, children: [ title ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { weight: "semibold", children: title }) : null, description ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 2, children: description }) : null ] }) }) ] }) }); } var __defProp$2 = Object.defineProperty, __defProps$1 = Object.defineProperties, __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors, __getOwnPropSymbols$2 = Object.getOwnPropertySymbols, __hasOwnProp$2 = Object.prototype.hasOwnProperty, __propIsEnum$2 = Object.prototype.propertyIsEnumerable, __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$2 = (a, b) => { for (var prop in b || (b = {})) __hasOwnProp$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]); if (__getOwnPropSymbols$2) for (var prop of __getOwnPropSymbols$2(b)) __propIsEnum$2.call(b, prop) && __defNormalProp$2(a, prop, b[prop]); return a; }, __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)), __objRest = (source, exclude) => { var target = {}; for (var prop in source) __hasOwnProp$2.call(source, prop) && exclude.indexOf(prop) < 0 && (target[prop] = source[prop]); if (source != null && __getOwnPropSymbols$2) for (var prop of __getOwnPropSymbols$2(source)) exclude.indexOf(prop) < 0 && __propIsEnum$2.call(source, prop) && (target[prop] = source[prop]); return target; }; const TableWrapper = (props = {}) => /* @__PURE__ */ jsxRuntime.jsx(ui.Card, __spreadValues$2({ as: "table" }, props)), StyledTable = styledComponents.styled(TableWrapper)( () => styledComponents.css` display: table; width: 100%; border-collapse: collapse; &:not([hidden]) { display: table; border-collapse: collapse; } ` ); function Table(props) { const _a = props, { children } = _a, rest = __objRest(_a, ["children"]); return /* @__PURE__ */ jsxRuntime.jsx(StyledTable, __spreadProps$1(__spreadValues$2({}, rest), { children })); } const RowWrapper = (props = {}) => /* @__PURE__ */ jsxRuntime.jsx(ui.Card, __spreadValues$2({ as: "tr" }, props)), StyledRow = styledComponents.styled(RowWrapper)( () => styledComponents.css` display: table-row; &:not([hidden]) { display: table-row; } ` ); function Row(props) { const _a = props, { children } = _a, rest = __objRest(_a, ["children"]); return /* @__PURE__ */ jsxRuntime.jsx(StyledRow, __spreadProps$1(__spreadValues$2({}, rest), { children })); } const CellWrapper = (props = {}) => /* @__PURE__ */ jsxRuntime.jsx(ui.Card, __spreadValues$2({ as: "td" }, props)), StyledCell = styledComponents.styled(CellWrapper)( () => styledComponents.css` display: table-cell; &:not([hidden]) { display: table-cell; } ` ); function Cell(props) { const _a = props, { children } = _a, rest = __objRest(_a, ["children"]); return /* @__PURE__ */ jsxRuntime.jsx(StyledCell, __spreadProps$1(__spreadValues$2({}, rest), { children })); } var __defProp$1 = Object.defineProperty, __getOwnPropSymbols$1 = Object.getOwnPropertySymbols, __hasOwnProp$1 = Object.prototype.hasOwnProperty, __propIsEnum$1 = Object.prototype.propertyIsEnumerable, __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues$1 = (a, b) => { for (var prop in b || (b = {})) __hasOwnProp$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]); if (__getOwnPropSymbols$1) for (var prop of __getOwnPropSymbols$1(b)) __propIsEnum$1.call(b, prop) && __defNormalProp$1(a, prop, b[prop]); return a; }; function searchUsers(users, searchString) { return users.filter((user) => !!((user.displayName || "").toLowerCase().startsWith(searchString) || (user.givenName || "").toLowerCase().startsWith(searchString) || (user.middleName || "").toLowerCase().startsWith(searchString) || (user.familyName || "").toLowerCase().startsWith(searchString))); } const LABELS = { addMe: "Assign myself", removeMe: "Unassign myself", clear: "Clear assignees", searchPlaceholder: "Search users", notFound: "No users found" }; function UserSelectMenu(props) { const { value = [], userList = [], onAdd, onRemove, onClear, style = {} } = props, labels = props != null && props.labels ? __spreadValues$1(__spreadValues$1({}, LABELS), props.labels) : LABELS, [searchString, setSearchString] = react.useState(""), searchResults = searchUsers(userList || [], searchString), me = userList.find((u) => u.isCurrentUser), meAssigned = me && value.includes(me.id), input = react.useRef(null), handleSearchChange = (event) => { setSearchString(event.target.value); }, handleSelect = (isChecked, user) => { isChecked ? onRemove && onRemove(user.id) : onAdd && onAdd(user.id); }, handleAssignMyself = () => { me && onAdd && onAdd(me.id); }, handleUnassignMyself = () => { me && onRemove && onRemove(me.id); }, handleClearAssigneesClick = () => { onClear && onClear(); }; return /* @__PURE__ */ jsxRuntime.jsxs(ui.Menu, { style, children: [ meAssigned ? /* @__PURE__ */ jsxRuntime.jsx( ui.MenuItem, { tone: "caution", disabled: !me, onClick: handleUnassignMyself, icon: icons.RemoveCircleIcon, text: labels.removeMe } ) : /* @__PURE__ */ jsxRuntime.jsx( ui.MenuItem, { tone: "positive", onClick: handleAssignMyself, icon: icons.AddCircleIcon, text: labels.addMe } ), /* @__PURE__ */ jsxRuntime.jsx( ui.MenuItem, { tone: "critical", disabled: value.length === 0, onClick: handleClearAssigneesClick, icon: icons.RestoreIcon, text: labels.clear } ), /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 1, children: /* @__PURE__ */ jsxRuntime.jsx( ui.TextInput, { ref: input, onChange: handleSearchChange, placeholder: labels.searchPlaceholder, value: searchString } ) }), searchString && (searchResults == null ? void 0 : searchResults.length) === 0 && /* @__PURE__ */ jsxRuntime.jsx(ui.MenuItem, { disabled: !0, text: labels.notFound }), searchResults && searchResults.map((user) => /* @__PURE__ */ jsxRuntime.jsx( ui.MenuItem, { pressed: value.includes(user.id), onClick: () => handleSelect(value.indexOf(user.id) > -1, user), children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { align: "center", children: [ /* @__PURE__ */ jsxRuntime.jsx(sanity.UserAvatar, { user, size: 1 }), /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { paddingX: 2, flex: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: user.displayName }) }), user.isCurrentUser && /* @__PURE__ */ jsxRuntime.jsx(ui.Badge, { fontSize: 1, tone: "positive", mode: "outline", children: "Me" }) ] }) }, user.id )) ] }); } function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x; } var builder = {}, urlForImage = {}, parseAssetId = {}, hasRequiredParseAssetId; function requireParseAssetId() { if (hasRequiredParseAssetId) return parseAssetId; hasRequiredParseAssetId = 1, Object.defineProperty(parseAssetId, "__esModule", { value: !0 }); var example = "image-Tb9Ew8CXIwaY6R1kjMvI0uRR-2000x3000-jpg"; function parseAssetId$1(ref) { var _a = ref.split("-"), id = _a[1], dimensionString = _a[2], format = _a[3]; if (!id || !dimensionString || !format) throw new Error("Malformed asset _ref '".concat(ref, `'. Expected an id like "`).concat(example, '".')); var _b = dimensionString.split("x"), imgWidthStr = _b[0], imgHeightStr = _b[1], width = +imgWidthStr, height = +imgHeightStr, isValidAssetId = isFinite(width) && isFinite(height); if (!isValidAssetId) throw new Error("Malformed asset _ref '".concat(ref, `'. Expected an id like "`).concat(example, '".')); return { id, width, height, format }; } return parseAssetId.default = parseAssetId$1, parseAssetId; } var parseSource = {}, hasRequiredParseSource; function requireParseSource() { if (hasRequiredParseSource) return parseSource; hasRequiredParseSource = 1; var __assign = parseSource && parseSource.__assign || function() { return __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]); } return t; }, __assign.apply(this, arguments); }; Object.defineProperty(parseSource, "__esModule", { value: !0 }); var isRef = function(src) { var source = src; return source ? typeof source._ref == "string" : !1; }, isAsset = function(src) { var source = src; return source ? typeof source._id == "string" : !1; }, isAssetStub = function(src) { var source = src; return source && source.asset ? typeof source.asset.url == "string" : !1; }; function parseSource$1(source) { if (!source) return null; var image; if (typeof source == "string" && isUrl(source)) image = { asset: { _ref: urlToId(source) } }; else if (typeof source == "string") image = { asset: { _ref: source } }; else if (isRef(source)) image = { asset: source }; else if (isAsset(source)) image = { asset: { _ref: source._id || "" } }; else if (isAssetStub(source)) image = { asset: { _ref: urlToId(source.asset.url) } }; else if (typeof source.asset == "object") image = __assign({}, source); else return null; var img = source; return img.crop && (image.crop = img.crop), img.hotspot && (image.hotspot = img.hotspot), applyDefaults(image); } parseSource.default = parseSource$1; function isUrl(url) { return /^https?:\/\//.test("".concat(url)); } function urlToId(url) { var parts = url.split("/").slice(-1); return "image-".concat(parts[0]).replace(/\.([a-z]+)$/, "-$1"); } function applyDefaults(image) { if (image.crop && image.hotspot) return image; var result = __assign({}, image); return result.crop || (result.crop = { left: 0, top: 0, bottom: 0, right: 0 }), result.hotspot || (result.hotspot = { x: 0.5, y: 0.5, height: 1, width: 1 }), result; } return parseSource; } var hasRequiredUrlForImage; function requireUrlForImage() { return hasRequiredUrlForImage || (hasRequiredUrlForImage = 1, function(exports2) { var __assign = urlForImage && urlForImage.__assign || function() { return __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]); } return t; }, __assign.apply(this, arguments); }, __importDefault = urlForImage && urlForImage.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports2, "__esModule", { value: !0 }), exports2.parseSource = exports2.SPEC_NAME_TO_URL_NAME_MAPPINGS = void 0; var parseAssetId_1 = __importDefault(requireParseAssetId()), parseSource_1 = __importDefault(requireParseSource()); exports2.parseSource = parseSource_1.default, exports2.SPEC_NAME_TO_URL_NAME_MAPPINGS = [ ["width", "w"], ["height", "h"], ["format", "fm"], ["download", "dl"], ["blur", "blur"], ["sharpen", "sharp"], ["invert", "invert"], ["orientation", "or"], ["minHeight", "min-h"], ["maxHeight", "max-h"], ["minWidth", "min-w"], ["maxWidth", "max-w"], ["quality", "q"], ["fit", "fit"], ["crop", "crop"], ["saturation", "sat"], ["auto", "auto"], ["dpr", "dpr"], ["pad", "pad"] ]; function urlForImage$1(options) { var spec = __assign({}, options || {}), source = spec.source; delete spec.source; var image = (0, parseSource_1.default)(source); if (!image) throw new Error("Unable to resolve image URL from source (".concat(JSON.stringify(source), ")")); var id = image.asset._ref || image.asset._id || "", asset = (0, parseAssetId_1.default)(id), cropLeft = Math.round(image.crop.left * asset.width), cropTop = Math.round(image.crop.top * asset.height), crop = { left: cropLeft, top: cropTop, width: Math.round(asset.width - image.crop.right * asset.width - cropLeft), height: Math.round(asset.height - image.crop.bottom * asset.height - cropTop) }, hotSpotVerticalRadius = image.hotspot.height * asset.height / 2, hotSpotHorizontalRadius = image.hotspot.width * asset.width / 2, hotSpotCenterX = image.hotspot.x * asset.width, hotSpotCenterY = image.hotspot.y * asset.height, hotspot = { left: hotSpotCenterX - hotSpotHorizontalRadius, top: hotSpotCenterY - hotSpotVerticalRadius, right: hotSpotCenterX + hotSpotHorizontalRadius, bottom: hotSpotCenterY + hotSpotVerticalRadius }; return spec.rect || spec.focalPoint || spec.ignoreImageParams || spec.crop || (spec = __assign(__assign({}, spec), fit({ crop, hotspot }, spec))), specToImageUrl(__assign(__assign({}, spec), { asset })); } exports2.default = urlForImage$1; function specToImageUrl(spec) { var cdnUrl = (spec.baseUrl || "https://cdn.sanity.io").replace(/\/+$/, ""), filename = "".concat(spec.asset.id, "-").concat(spec.asset.width, "x").concat(spec.asset.height, ".").concat(spec.asset.format), baseUrl = "".concat(cdnUrl, "/images/").concat(spec.projectId, "/").concat(spec.dataset, "/").concat(filename), params = []; if (spec.rect) { var _a = spec.rect, left = _a.left, top_1 = _a.top, width = _a.width, height = _a.height, isEffectiveCrop = left !== 0 || top_1 !== 0 || height !== spec.asset.height || width !== spec.asset.width; isEffectiveCrop && params.push("rect=".concat(left, ",").concat(top_1, ",").concat(width, ",").concat(height)); } spec.bg && params.push("bg=".concat(spec.bg)), spec.focalPoint && (params.push("fp-x=".concat(spec.focalPoint.x)), params.push("fp-y=".concat(spec.focalPoint.y))); var flip = [spec.flipHorizontal && "h", spec.flipVertical && "v"].filter(Boolean).join(""); return flip && params.push("flip=".concat(flip)), exports2.SPEC_NAME_TO_URL_NAME_MAPPINGS.forEach(function(mapping) { var specName = mapping[0], param = mapping[1]; typeof spec[specName] < "u" ? params.push("".concat(param, "=").concat(encodeURIComponent(spec[specName]))) : typeof spec[param] < "u" && params.push("".concat(param, "=").concat(encodeURIComponent(spec[param]))); }), params.length === 0 ? baseUrl : "".concat(baseUrl, "?").concat(params.join("&")); } function fit(source, spec) { var cropRect, imgWidth = spec.width, imgHeight = spec.height; if (!(imgWidth && imgHeight)) return { width: imgWidth, height: imgHeight, rect: source.crop }; var crop = source.crop, hotspot = source.hotspot, desiredAspectRatio = imgWidth / imgHeight, cropAspectRatio = crop.width / crop.height; if (cropAspectRatio > desiredAspectRatio) { var height = Math.round(crop.height), width = Math.round(height * desiredAspectRatio), top_2 = Math.max(0, Math.round(crop.top)), hotspotXCenter = Math.round((hotspot.right - hotspot.left) / 2 + hotspot.left), left = Math.max(0, Math.round(hotspotXCenter - width / 2)); left < crop.left ? left = crop.left : left + width > crop.left + crop.width && (left = crop.left + crop.width - width), cropRect = { left, top: top_2, width, height }; } else { var width = crop.width, height = Math.round(width / desiredAspectRatio), left = Math.max(0, Math.round(crop.left)), hotspotYCenter = Math.round((hotspot.bottom - hotspot.top) / 2 + hotspot.top), top_3 = Math.max(0, Math.round(hotspotYCenter - height / 2)); top_3 < crop.top ? top_3 = crop.top : top_3 + height > crop.top + crop.height && (top_3 = crop.top + crop.height - height), cropRect = { left, top: top_3, width, height }; } return { width: imgWidth, height: imgHeight, rect: cropRect }; } }(urlForImage)), urlForImage; } var hasRequiredBuilder; function requireBuilder() { if (hasRequiredBuilder) return builder; hasRequiredBuilder = 1; var __assign = builder && builder.__assign || function() { return __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]); } return t; }, __assign.apply(this, arguments); }, __createBinding = builder && builder.__createBinding || (Object.create ? function(o, m, k, k2) { k2 === void 0 && (k2 = k), Object.defineProperty(o, k2, { enumerable: !0, get: function() { return m[k]; } }); } : function(o, m, k, k2) { k2 === void 0 && (k2 = k), o[k2] = m[k]; }), __setModuleDefault = builder && builder.__setModuleDefault || (Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: !0, value: v }); } : function(o, v) { o.default = v; }), __importStar = builder && builder.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) k !== "default" && Object.prototype.hasOwnProperty.call(mod, k) && __createBinding(result, mod, k); return __setModuleDefault(result, mod), result; }; Object.defineProperty(builder, "__esModule", { value: !0 }), builder.ImageUrlBuilder = void 0; var urlForImage_1 = __importStar(requireUrlForImage()), validFits = ["clip", "crop", "fill", "fillmax", "max", "scale", "min"], validCrops = ["top", "bottom", "left", "right", "center", "focalpoint", "entropy"], validAutoModes = ["format"]; function isSanityModernClientLike(client) { return client && "config" in client ? typeof client.config == "function" : !1; } function isSanityClientLike(client) { return client && "clientConfig" in client ? typeof client.clientConfig == "object" : !1; } function rewriteSpecName(key) { for (var specs = urlForImage_1.SPEC_NAME_TO_URL_NAME_MAPPINGS, _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { var entry = specs_1[_i], specName = entry[0], param = entry[1]; if (key === specName || key === param) return specName; } return key; } function urlBuilder(options) { if (isSanityModernClientLike(options)) { var _a = options.config(), apiUrl = _a.apiHost, projectId = _a.projectId, dataset = _a.dataset, apiHost = apiUrl || "https://api.sanity.io"; return new ImageUrlBuilder(null, { baseUrl: apiHost.replace(/^https:\/\/api\./, "https://cdn."), projectId, dataset }); } var client = options; if (isSanityClientLike(client)) { var _b = client.clientConfig, apiUrl = _b.apiHost, projectId = _b.projectId, dataset = _b.dataset, apiHost = apiUrl || "https://api.sanity.io"; return new ImageUrlBuilder(null, { baseUrl: apiHost.replace(/^https:\/\/api\./, "https://cdn."), projectId, dataset }); } return new ImageUrlBuilder(null, options); } builder.default = urlBuilder; var ImageUrlBuilder = ( /** @class */ function() { function ImageUrlBuilder2(parent, options) { this.options = parent ? __assign(__assign({}, parent.options || {}), options || {}) : __assign({}, options || {}); } return ImageUrlBuilder2.prototype.withOptions = function(options) { var baseUrl = options.baseUrl || this.options.baseUrl, newOptions = { baseUrl }; for (var key in options) if (options.hasOwnProperty(key)) { var specKey = rewriteSpecName(key); newOptions[specKey] = options[key]; } return new ImageUrlBuilder2(this, __assign({ baseUrl }, newOptions)); }, ImageUrlBuilder2.prototype.image = function(source) { return this.withOptions({ source }); }, ImageUrlBuilder2.prototype.dataset = function(dataset) { return this.withOptions({ dataset }); }, ImageUrlBuilder2.prototype.projectId = function(projectId) { return this.withOptions({ projectId }); }, ImageUrlBuilder2.prototype.bg = function(bg) { return this.withOptions({ bg }); }, ImageUrlBuilder2.prototype.dpr = function(dpr) { return this.withOptions(dpr && dpr !== 1 ? { dpr } : {}); }, ImageUrlBuilder2.prototype.width = function(width) { return this.withOptions({ width }); }, ImageUrlBuilder2.prototype.height = function(height) { return this.withOptions({ height }); }, ImageUrlBuilder2.prototype.focalPoint = function(x, y) { return this.withOptions({ focalPoint: { x, y } }); }, ImageUrlBuilder2.prototype.maxWidth = function(maxWidth) { return this.withOptions({ maxWidth }); }, ImageUrlBuilder2.prototype.minWidth = function(minWidth) { return this.withOptions({ minWidth }); }, ImageUrlBuilder2.prototype.maxHeight = function(maxHeight) { return this.withOptions({ maxHeight }); }, ImageUrlBuilder2.prototype.minHeight = function(minHeight) { return this.withOptions({ minHeight }); }, ImageUrlBuilder2.prototype.size = function(width, height) { return this.withOptions({ width, height }); }, ImageUrlBuilder2.prototype.blur = function(blur) { return this.withOptions({ blur }); }, ImageUrlBuilder2.prototype.sharpen = function(sharpen) { return this.withOptions({ sharpen }); }, ImageUrlBuilder2.prototype.rect = function(left, top, width, height) { return this.withOptions({ rect: { left, top, width, height } }); }, ImageUrlBuilder2.prototype.format = function(format) { return this.withOptions({ format }); }, ImageUrlBuilder2.prototype.invert = function(invert) { return this.withOptions({ invert }); }, ImageUrlBuilder2.prototype.orientation = function(orientation) { return this.withOptions({ orientation }); }, ImageUrlBuilder2.prototype.quality = function(quality) { return this.withOptions({ quality }); }, ImageUrlBuilder2.prototype.forceDownload = function(download) { return this.withOptions({ download }); }, ImageUrlBuilder2.prototype.flipHorizontal = function() { return this.withOptions({ flipHorizontal: !0 }); }, ImageUrlBuilder2.prototype.flipVertical = function() { return this.withOptions({ flipVertical: !0 }); }, ImageUrlBuilder2.prototype.ignoreImageParams = function() { return this.withOptions({ ignoreImageParams: !0 }); }, ImageUrlBuilder2.prototype.fit = function(value) { if (validFits.indexOf(value) === -1) throw new Error('Invalid fit mode "'.concat(value, '"')); return this.withOptions({ fit: value }); }, ImageUrlBuilder2.prototype.crop = function(value) { if (validCrops.indexOf(value) === -1) throw new Error('Invalid crop mode "'.concat(value, '"')); return this.withOptions({ crop: value }); }, ImageUrlBuilder2.prototype.saturation = function(saturation) { return this.withOptions({ saturation }); }, ImageUrlBuilder2.prototype.auto = function(value) { if (validAutoModes.indexOf(value) === -1) throw new Error('Invalid auto mode "'.concat(value, '"')); return this.withOptions({ auto: value }); }, ImageUrlBuilder2.prototype.pad = function(pad) { return this.withOptions({ pad }); }, ImageUrlBuilder2.prototype.url = function() { return (0, urlForImage_1.default)(this.options); }, ImageUrlBuilder2.prototype.toString = function() { return this.url(); }, ImageUrlBuilder2; }() ); return builder.ImageUrlBuilder = ImageUrlBuilder, builder; } var node, hasRequiredNode; function requireNode() { if (hasRequiredNode) return node; hasRequiredNode = 1; var __importDefault = node && node.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { default: mod }; }, builder_1 = __importDefault(requireBuilder()); return node = builder_1.default, node; } var nodeExports = /* @__PURE__ */ requireNode(), createImageUrlBuilder = /* @__PURE__ */ getDefaultExportFromCjs(nodeExports); function useImageUrlBuilder(clientOptions) { const client = sanity.useClient(clientOptions); return react.useMemo(() => createImageUrlBuilder(client), [client]); } function useImageUrlBuilderImage(source, clientOptions) { const builder2 = useImageUrlBuilder(clientOptions); return react.useMemo( () => source && builder2 ? builder2.image(source) : null, [builder2, source] ); } const DEFAULT_PARAMS = {}, DEFAULT_OPTIONS = { apiVersion: "v2023-05-01" }, DEFAULT_INITIAL_VALUE = null; function useParams(params) { const stringifiedParams = react.useMemo( () => JSON.stringify(params || {}), [params] ); return react.useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams]); } function useListeningQuery(query, { params = DEFAULT_PARAMS, options = DEFAULT_OPTIONS, initialValue = DEFAULT_INITIAL_VALUE }) { const [loading, setLoading] = react.useState(!0), [error, setError] = react.useState(!1), [data, setData] = react.useState(initialValue), memoParams = useParams(params), memoOptions = useParams(options), subscription = react.useRef(null), documentStore = sanity.useDocumentStore(); return react.useEffect(() => { if (query && !error && !subscription.current) try { subscription.current = documentStore.listenQuery(query, memoParams, memoOptions).pipe( operators.distinctUntilChanged(isEqual__default.default), operators.catchError((err) => (console.error(err), setError(err), setLoading(!1), setData(null), err)) ).subscribe((documents) => { setData( (current) => isEqual__default.default(current, documents) ? current : documents ), setLoading(!1), setError(!1); }); } catch (err) { console.error(err), setLoading(!1), setError(err); } return error && subscription.current && subscription.current.unsubscribe(), () => { var _a; subscription.current && ((_a = subscription == null ? void 0 : subscription.current) == null || _a.unsubscribe(), subscription.current = null); }; }, [query, error, memoParams, memoOptions, documentStore]), { data, loading, error }; } function useOpenInNewPane(id, type) { const routerContext = react.useContext(router.RouterContext), { routerPanesState, groupIndex } = structure.usePaneRouter(); return react.useCallback(() => { if (!routerContext || !id || !type) return; const panes = [...routerPanesState]; panes.splice(groupIndex + 1, 0, [ { id, params: { type } } ]); const href = routerContext.resolvePathFromState({ panes }); routerContext.navigateUrl({ path: href }); }, [id, type, routerContext, routerPanesState, groupIndex]); } var __defProp = Object.defineProperty, __defProps = Object.defineProperties, __getOwnPropDescs = Object.getOwnPropertyDescriptors, __getOwnPropSymbols = Object.getOwnPropertySymbols, __hasOwnProp = Object.prototype.hasOwnProperty, __propIsEnum = Object.prototype.propertyIsEnumerable, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value, __spreadValues = (a, b) => { for (var prop in b || (b = {})) __hasOwnProp.call(b, prop) && __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) __propIsEnum.call(b, prop) && __defNormalProp(a, prop, b[prop]); return a; }, __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); function chunkArray(array, size) { const chunks = []; for (let i = 0; i < array.length; i += size) chunks.push(array.slice(i, i + size)); return chunks; } function useProjectUsers({ apiVersion }) { const { currentUser } = sanity.useWorkspace(), client = sanity.useClient({ apiVersion: apiVersion != null ? apiVersion : "2023-01-01" }), [users, setUsers] = react.useState([]); return react.useEffect(() => { const { projectId } = client.config(); async function getUsersWithRoles() { try { const aclData = await client.request({ url: `/projects/${projectId}/acl` }), userIds = aclData.map((user) => user.projectUserId), userIdChunks = chunkArray(userIds, 200); let usersData = []; for (const chunk of userIdChunks) { const chunkedUserIds = chunk.join(","), response = await client.request({ url: `/projects/${projectId}/users/${chunkedUserIds}` }); usersData = [...usersData, ...response]; } const usersWithRoles = usersData.map((user) => { var _a; const userRoles = ((_a = aclData.find( (aclUser) => aclUser.projectUserId === user.id )) == null ? void 0 : _a.roles) || []; return __spreadProps(__spreadValues({}, user), { isCurrentUser: user.id === (currentUser == null ? void 0 : currentUser.id), roles: userRoles }); }); setUsers(usersWithRoles); } catch (err) { console.error("Failed to fetch users:", err); } } users.length || getUsersWithRoles(); }, [client, currentUser == null ? void 0 : currentUser.id, users.length]), users; } exports.Cell = Cell; exports.Feedback = Feedback; exports.Row = Row; exports.Table = Table; exports.UserSelectMenu = UserSelectMenu; exports.useImageUrlBuilder = useImageUrlBuilder; exports.useImageUrlBuilderImage = useImageUrlBuilderImage; exports.useListeningQuery = useListeningQuery; exports.useOpenInNewPane = useOpenInNewPane; exports.useProjectUsers = useProjectUsers; //# sourceMappingURL=index.cjs.map