sanity-plugin-utils 1.8.0 → 2.0.0

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/index.cjs DELETED
@@ -1,650 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- 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");
4
- function _interopDefaultCompat(e) {
5
- return e && typeof e == "object" && "default" in e ? e : { default: e };
6
- }
7
- var isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual);
8
- const DEFAULT_PROPS = {
9
- tone: "primary"
10
- };
11
- function Feedback(props) {
12
- const { title, description, icon, tone, children } = {
13
- ...DEFAULT_PROPS,
14
- ...props
15
- };
16
- return /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { tone, padding: 4, radius: 3, border: !0, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { children: [
17
- icon ? "display icon" : null,
18
- children || /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { flex: 1, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Stack, { space: 4, children: [
19
- title ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { weight: "semibold", children: title }) : null,
20
- description ? /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: 2, children: description }) : null
21
- ] }) })
22
- ] }) });
23
- }
24
- const TableWrapper = (props = {}) => /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { as: "table", ...props }), StyledTable = styledComponents.styled(TableWrapper)(
25
- () => styledComponents.css`
26
- display: table;
27
- width: 100%;
28
- border-collapse: collapse;
29
-
30
- &:not([hidden]) {
31
- display: table;
32
- border-collapse: collapse;
33
- }
34
- `
35
- );
36
- function Table(props) {
37
- const { children, ...rest } = props;
38
- return /* @__PURE__ */ jsxRuntime.jsx(StyledTable, { ...rest, children });
39
- }
40
- const RowWrapper = (props = {}) => /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { as: "tr", ...props }), StyledRow = styledComponents.styled(RowWrapper)(
41
- () => styledComponents.css`
42
- display: table-row;
43
-
44
- &:not([hidden]) {
45
- display: table-row;
46
- }
47
- `
48
- );
49
- function Row(props) {
50
- const { children, ...rest } = props;
51
- return /* @__PURE__ */ jsxRuntime.jsx(StyledRow, { ...rest, children });
52
- }
53
- const CellWrapper = (props = {}) => /* @__PURE__ */ jsxRuntime.jsx(ui.Card, { as: "td", ...props }), StyledCell = styledComponents.styled(CellWrapper)(
54
- () => styledComponents.css`
55
- display: table-cell;
56
-
57
- &:not([hidden]) {
58
- display: table-cell;
59
- }
60
- `
61
- );
62
- function Cell(props) {
63
- const { children, ...rest } = props;
64
- return /* @__PURE__ */ jsxRuntime.jsx(StyledCell, { ...rest, children });
65
- }
66
- function searchUsers(users, searchString) {
67
- return users.filter((user) => !!((user.displayName || "").toLowerCase().startsWith(searchString) || (user.givenName || "").toLowerCase().startsWith(searchString) || (user.middleName || "").toLowerCase().startsWith(searchString) || (user.familyName || "").toLowerCase().startsWith(searchString)));
68
- }
69
- const LABELS = {
70
- addMe: "Assign myself",
71
- removeMe: "Unassign myself",
72
- clear: "Clear assignees",
73
- searchPlaceholder: "Search users",
74
- notFound: "No users found"
75
- };
76
- function UserSelectMenu(props) {
77
- const {
78
- value = [],
79
- userList = [],
80
- onAdd,
81
- onRemove,
82
- onClear,
83
- style = {}
84
- } = props, labels = props?.labels ? { ...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) => {
85
- setSearchString(event.target.value);
86
- }, handleSelect = (isChecked, user) => {
87
- isChecked ? onRemove && onRemove(user.id) : onAdd && onAdd(user.id);
88
- }, handleAssignMyself = () => {
89
- me && onAdd && onAdd(me.id);
90
- }, handleUnassignMyself = () => {
91
- me && onRemove && onRemove(me.id);
92
- }, handleClearAssigneesClick = () => {
93
- onClear && onClear();
94
- };
95
- return /* @__PURE__ */ jsxRuntime.jsxs(ui.Menu, { style, children: [
96
- meAssigned ? /* @__PURE__ */ jsxRuntime.jsx(
97
- ui.MenuItem,
98
- {
99
- tone: "caution",
100
- disabled: !me,
101
- onClick: handleUnassignMyself,
102
- icon: icons.RemoveCircleIcon,
103
- text: labels.removeMe
104
- }
105
- ) : /* @__PURE__ */ jsxRuntime.jsx(
106
- ui.MenuItem,
107
- {
108
- tone: "positive",
109
- onClick: handleAssignMyself,
110
- icon: icons.AddCircleIcon,
111
- text: labels.addMe
112
- }
113
- ),
114
- /* @__PURE__ */ jsxRuntime.jsx(
115
- ui.MenuItem,
116
- {
117
- tone: "critical",
118
- disabled: value.length === 0,
119
- onClick: handleClearAssigneesClick,
120
- icon: icons.RestoreIcon,
121
- text: labels.clear
122
- }
123
- ),
124
- /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { padding: 1, children: /* @__PURE__ */ jsxRuntime.jsx(
125
- ui.TextInput,
126
- {
127
- ref: input,
128
- onChange: handleSearchChange,
129
- placeholder: labels.searchPlaceholder,
130
- value: searchString
131
- }
132
- ) }),
133
- searchString && searchResults?.length === 0 && /* @__PURE__ */ jsxRuntime.jsx(ui.MenuItem, { disabled: !0, text: labels.notFound }),
134
- searchResults && searchResults.map((user) => /* @__PURE__ */ jsxRuntime.jsx(
135
- ui.MenuItem,
136
- {
137
- pressed: value.includes(user.id),
138
- onClick: () => handleSelect(value.indexOf(user.id) > -1, user),
139
- children: /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { align: "center", children: [
140
- /* @__PURE__ */ jsxRuntime.jsx(sanity.UserAvatar, { user, size: 1 }),
141
- /* @__PURE__ */ jsxRuntime.jsx(ui.Box, { paddingX: 2, flex: 1, children: /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { children: user.displayName }) }),
142
- user.isCurrentUser && /* @__PURE__ */ jsxRuntime.jsx(ui.Badge, { fontSize: 1, tone: "positive", mode: "outline", children: "Me" })
143
- ] })
144
- },
145
- user.id
146
- ))
147
- ] });
148
- }
149
- function getDefaultExportFromCjs(x) {
150
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x;
151
- }
152
- var builder = {}, urlForImage = {}, parseAssetId = {}, hasRequiredParseAssetId;
153
- function requireParseAssetId() {
154
- if (hasRequiredParseAssetId) return parseAssetId;
155
- hasRequiredParseAssetId = 1, Object.defineProperty(parseAssetId, "__esModule", { value: !0 });
156
- var example = "image-Tb9Ew8CXIwaY6R1kjMvI0uRR-2000x3000-jpg";
157
- function parseAssetId$1(ref) {
158
- var _a = ref.split("-"), id = _a[1], dimensionString = _a[2], format = _a[3];
159
- if (!id || !dimensionString || !format)
160
- throw new Error("Malformed asset _ref '".concat(ref, `'. Expected an id like "`).concat(example, '".'));
161
- var _b = dimensionString.split("x"), imgWidthStr = _b[0], imgHeightStr = _b[1], width = +imgWidthStr, height = +imgHeightStr, isValidAssetId = isFinite(width) && isFinite(height);
162
- if (!isValidAssetId)
163
- throw new Error("Malformed asset _ref '".concat(ref, `'. Expected an id like "`).concat(example, '".'));
164
- return { id, width, height, format };
165
- }
166
- return parseAssetId.default = parseAssetId$1, parseAssetId;
167
- }
168
- var parseSource = {}, hasRequiredParseSource;
169
- function requireParseSource() {
170
- if (hasRequiredParseSource) return parseSource;
171
- hasRequiredParseSource = 1;
172
- var __assign = parseSource && parseSource.__assign || function() {
173
- return __assign = Object.assign || function(t) {
174
- for (var s, i = 1, n = arguments.length; i < n; i++) {
175
- s = arguments[i];
176
- for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]);
177
- }
178
- return t;
179
- }, __assign.apply(this, arguments);
180
- };
181
- Object.defineProperty(parseSource, "__esModule", { value: !0 }), parseSource.isInProgressUpload = void 0;
182
- var isRef = function(src) {
183
- var source = src;
184
- return source ? typeof source._ref == "string" : !1;
185
- }, isAsset = function(src) {
186
- var source = src;
187
- return source ? typeof source._id == "string" : !1;
188
- }, isAssetStub = function(src) {
189
- var source = src;
190
- return source && source.asset ? typeof source.asset.url == "string" : !1;
191
- }, isInProgressUpload = function(src) {
192
- if (typeof src == "object" && src !== null) {
193
- var obj = src;
194
- return obj._upload && (!obj.asset || !obj.asset._ref);
195
- }
196
- return !1;
197
- };
198
- parseSource.isInProgressUpload = isInProgressUpload;
199
- function parseSource$1(source) {
200
- if (!source)
201
- return null;
202
- var image;
203
- if (typeof source == "string" && isUrl(source))
204
- image = {
205
- asset: { _ref: urlToId(source) }
206
- };
207
- else if (typeof source == "string")
208
- image = {
209
- asset: { _ref: source }
210
- };
211
- else if (isRef(source))
212
- image = {
213
- asset: source
214
- };
215
- else if (isAsset(source))
216
- image = {
217
- asset: {
218
- _ref: source._id || ""
219
- }
220
- };
221
- else if (isAssetStub(source))
222
- image = {
223
- asset: {
224
- _ref: urlToId(source.asset.url)
225
- }
226
- };
227
- else if (typeof source.asset == "object")
228
- image = __assign({}, source);
229
- else
230
- return null;
231
- var img = source;
232
- return img.crop && (image.crop = img.crop), img.hotspot && (image.hotspot = img.hotspot), applyDefaults(image);
233
- }
234
- parseSource.default = parseSource$1;
235
- function isUrl(url) {
236
- return /^https?:\/\//.test("".concat(url));
237
- }
238
- function urlToId(url) {
239
- var parts = url.split("/").slice(-1);
240
- return "image-".concat(parts[0]).replace(/\.([a-z]+)$/, "-$1");
241
- }
242
- function applyDefaults(image) {
243
- if (image.crop && image.hotspot)
244
- return image;
245
- var result = __assign({}, image);
246
- return result.crop || (result.crop = {
247
- left: 0,
248
- top: 0,
249
- bottom: 0,
250
- right: 0
251
- }), result.hotspot || (result.hotspot = {
252
- x: 0.5,
253
- y: 0.5,
254
- height: 1,
255
- width: 1
256
- }), result;
257
- }
258
- return parseSource;
259
- }
260
- var hasRequiredUrlForImage;
261
- function requireUrlForImage() {
262
- return hasRequiredUrlForImage || (hasRequiredUrlForImage = 1, function(exports$1) {
263
- var __assign = urlForImage && urlForImage.__assign || function() {
264
- return __assign = Object.assign || function(t) {
265
- for (var s, i = 1, n = arguments.length; i < n; i++) {
266
- s = arguments[i];
267
- for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]);
268
- }
269
- return t;
270
- }, __assign.apply(this, arguments);
271
- }, __createBinding = urlForImage && urlForImage.__createBinding || (Object.create ? function(o, m, k, k2) {
272
- k2 === void 0 && (k2 = k);
273
- var desc = Object.getOwnPropertyDescriptor(m, k);
274
- (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) && (desc = { enumerable: !0, get: function() {
275
- return m[k];
276
- } }), Object.defineProperty(o, k2, desc);
277
- } : function(o, m, k, k2) {
278
- k2 === void 0 && (k2 = k), o[k2] = m[k];
279
- }), __setModuleDefault = urlForImage && urlForImage.__setModuleDefault || (Object.create ? function(o, v) {
280
- Object.defineProperty(o, "default", { enumerable: !0, value: v });
281
- } : function(o, v) {
282
- o.default = v;
283
- }), __importStar = urlForImage && urlForImage.__importStar || function(mod) {
284
- if (mod && mod.__esModule) return mod;
285
- var result = {};
286
- if (mod != null) for (var k in mod) k !== "default" && Object.prototype.hasOwnProperty.call(mod, k) && __createBinding(result, mod, k);
287
- return __setModuleDefault(result, mod), result;
288
- }, __importDefault = urlForImage && urlForImage.__importDefault || function(mod) {
289
- return mod && mod.__esModule ? mod : { default: mod };
290
- };
291
- Object.defineProperty(exports$1, "__esModule", { value: !0 }), exports$1.parseSource = exports$1.SPEC_NAME_TO_URL_NAME_MAPPINGS = void 0;
292
- var parseAssetId_1 = __importDefault(requireParseAssetId()), parseSource_1 = __importStar(requireParseSource());
293
- exports$1.parseSource = parseSource_1.default, exports$1.SPEC_NAME_TO_URL_NAME_MAPPINGS = [
294
- ["width", "w"],
295
- ["height", "h"],
296
- ["format", "fm"],
297
- ["download", "dl"],
298
- ["blur", "blur"],
299
- ["sharpen", "sharp"],
300
- ["invert", "invert"],
301
- ["orientation", "or"],
302
- ["minHeight", "min-h"],
303
- ["maxHeight", "max-h"],
304
- ["minWidth", "min-w"],
305
- ["maxWidth", "max-w"],
306
- ["quality", "q"],
307
- ["fit", "fit"],
308
- ["crop", "crop"],
309
- ["saturation", "sat"],
310
- ["auto", "auto"],
311
- ["dpr", "dpr"],
312
- ["pad", "pad"],
313
- ["frame", "frame"]
314
- ];
315
- function urlForImage$1(options) {
316
- var spec = __assign({}, options || {}), source = spec.source;
317
- delete spec.source;
318
- var image = (0, parseSource_1.default)(source);
319
- if (!image) {
320
- if (source && (0, parseSource_1.isInProgressUpload)(source))
321
- return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8HwQACfsD/QNViZkAAAAASUVORK5CYII=";
322
- throw new Error("Unable to resolve image URL from source (".concat(JSON.stringify(source), ")"));
323
- }
324
- 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 = {
325
- left: cropLeft,
326
- top: cropTop,
327
- width: Math.round(asset.width - image.crop.right * asset.width - cropLeft),
328
- height: Math.round(asset.height - image.crop.bottom * asset.height - cropTop)
329
- }, 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 = {
330
- left: hotSpotCenterX - hotSpotHorizontalRadius,
331
- top: hotSpotCenterY - hotSpotVerticalRadius,
332
- right: hotSpotCenterX + hotSpotHorizontalRadius,
333
- bottom: hotSpotCenterY + hotSpotVerticalRadius
334
- };
335
- return spec.rect || spec.focalPoint || spec.ignoreImageParams || spec.crop || (spec = __assign(__assign({}, spec), fit({ crop, hotspot }, spec))), specToImageUrl(__assign(__assign({}, spec), { asset }));
336
- }
337
- exports$1.default = urlForImage$1;
338
- function specToImageUrl(spec) {
339
- var cdnUrl = (spec.baseUrl || "https://cdn.sanity.io").replace(/\/+$/, ""), vanityStub = spec.vanityName ? "/".concat(spec.vanityName) : "", filename = "".concat(spec.asset.id, "-").concat(spec.asset.width, "x").concat(spec.asset.height, ".").concat(spec.asset.format).concat(vanityStub), baseUrl = "".concat(cdnUrl, "/images/").concat(spec.projectId, "/").concat(spec.dataset, "/").concat(filename), params = [];
340
- if (spec.rect) {
341
- 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;
342
- isEffectiveCrop && params.push("rect=".concat(left, ",").concat(top_1, ",").concat(width, ",").concat(height));
343
- }
344
- 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)));
345
- var flip = [spec.flipHorizontal && "h", spec.flipVertical && "v"].filter(Boolean).join("");
346
- return flip && params.push("flip=".concat(flip)), exports$1.SPEC_NAME_TO_URL_NAME_MAPPINGS.forEach(function(mapping) {
347
- var specName = mapping[0], param = mapping[1];
348
- typeof spec[specName] < "u" ? params.push("".concat(param, "=").concat(encodeURIComponent(spec[specName]))) : typeof spec[param] < "u" && params.push("".concat(param, "=").concat(encodeURIComponent(spec[param])));
349
- }), params.length === 0 ? baseUrl : "".concat(baseUrl, "?").concat(params.join("&"));
350
- }
351
- function fit(source, spec) {
352
- var cropRect, imgWidth = spec.width, imgHeight = spec.height;
353
- if (!(imgWidth && imgHeight))
354
- return { width: imgWidth, height: imgHeight, rect: source.crop };
355
- var crop = source.crop, hotspot = source.hotspot, desiredAspectRatio = imgWidth / imgHeight, cropAspectRatio = crop.width / crop.height;
356
- if (cropAspectRatio > desiredAspectRatio) {
357
- 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));
358
- 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 };
359
- } else {
360
- 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));
361
- 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 };
362
- }
363
- return {
364
- width: imgWidth,
365
- height: imgHeight,
366
- rect: cropRect
367
- };
368
- }
369
- }(urlForImage)), urlForImage;
370
- }
371
- var hasRequiredBuilder;
372
- function requireBuilder() {
373
- if (hasRequiredBuilder) return builder;
374
- hasRequiredBuilder = 1;
375
- var __assign = builder && builder.__assign || function() {
376
- return __assign = Object.assign || function(t) {
377
- for (var s, i = 1, n = arguments.length; i < n; i++) {
378
- s = arguments[i];
379
- for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]);
380
- }
381
- return t;
382
- }, __assign.apply(this, arguments);
383
- }, __createBinding = builder && builder.__createBinding || (Object.create ? function(o, m, k, k2) {
384
- k2 === void 0 && (k2 = k);
385
- var desc = Object.getOwnPropertyDescriptor(m, k);
386
- (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) && (desc = { enumerable: !0, get: function() {
387
- return m[k];
388
- } }), Object.defineProperty(o, k2, desc);
389
- } : function(o, m, k, k2) {
390
- k2 === void 0 && (k2 = k), o[k2] = m[k];
391
- }), __setModuleDefault = builder && builder.__setModuleDefault || (Object.create ? function(o, v) {
392
- Object.defineProperty(o, "default", { enumerable: !0, value: v });
393
- } : function(o, v) {
394
- o.default = v;
395
- }), __importStar = builder && builder.__importStar || function(mod) {
396
- if (mod && mod.__esModule) return mod;
397
- var result = {};
398
- if (mod != null) for (var k in mod) k !== "default" && Object.prototype.hasOwnProperty.call(mod, k) && __createBinding(result, mod, k);
399
- return __setModuleDefault(result, mod), result;
400
- };
401
- Object.defineProperty(builder, "__esModule", { value: !0 }), builder.ImageUrlBuilder = void 0;
402
- var urlForImage_1 = __importStar(requireUrlForImage()), validFits = ["clip", "crop", "fill", "fillmax", "max", "scale", "min"], validCrops = ["top", "bottom", "left", "right", "center", "focalpoint", "entropy"], validAutoModes = ["format"];
403
- function isSanityModernClientLike(client) {
404
- return client && "config" in client ? typeof client.config == "function" : !1;
405
- }
406
- function isSanityClientLike(client) {
407
- return client && "clientConfig" in client ? typeof client.clientConfig == "object" : !1;
408
- }
409
- function rewriteSpecName(key) {
410
- for (var specs = urlForImage_1.SPEC_NAME_TO_URL_NAME_MAPPINGS, _i = 0, specs_1 = specs; _i < specs_1.length; _i++) {
411
- var entry = specs_1[_i], specName = entry[0], param = entry[1];
412
- if (key === specName || key === param)
413
- return specName;
414
- }
415
- return key;
416
- }
417
- function urlBuilder(options) {
418
- if (isSanityModernClientLike(options)) {
419
- var _a = options.config(), apiUrl = _a.apiHost, projectId = _a.projectId, dataset = _a.dataset, apiHost = apiUrl || "https://api.sanity.io";
420
- return new ImageUrlBuilder(null, {
421
- baseUrl: apiHost.replace(/^https:\/\/api\./, "https://cdn."),
422
- projectId,
423
- dataset
424
- });
425
- }
426
- if (isSanityClientLike(options)) {
427
- var _b = options.clientConfig, apiUrl = _b.apiHost, projectId = _b.projectId, dataset = _b.dataset, apiHost = apiUrl || "https://api.sanity.io";
428
- return new ImageUrlBuilder(null, {
429
- baseUrl: apiHost.replace(/^https:\/\/api\./, "https://cdn."),
430
- projectId,
431
- dataset
432
- });
433
- }
434
- return new ImageUrlBuilder(null, options || {});
435
- }
436
- builder.default = urlBuilder;
437
- var ImageUrlBuilder = (
438
- /** @class */
439
- function() {
440
- function ImageUrlBuilder2(parent, options) {
441
- this.options = parent ? __assign(__assign({}, parent.options || {}), options || {}) : __assign({}, options || {});
442
- }
443
- return ImageUrlBuilder2.prototype.withOptions = function(options) {
444
- var baseUrl = options.baseUrl || this.options.baseUrl, newOptions = { baseUrl };
445
- for (var key in options)
446
- if (options.hasOwnProperty(key)) {
447
- var specKey = rewriteSpecName(key);
448
- newOptions[specKey] = options[key];
449
- }
450
- return new ImageUrlBuilder2(this, __assign({ baseUrl }, newOptions));
451
- }, ImageUrlBuilder2.prototype.image = function(source) {
452
- return this.withOptions({ source });
453
- }, ImageUrlBuilder2.prototype.dataset = function(dataset) {
454
- return this.withOptions({ dataset });
455
- }, ImageUrlBuilder2.prototype.projectId = function(projectId) {
456
- return this.withOptions({ projectId });
457
- }, ImageUrlBuilder2.prototype.bg = function(bg) {
458
- return this.withOptions({ bg });
459
- }, ImageUrlBuilder2.prototype.dpr = function(dpr) {
460
- return this.withOptions(dpr && dpr !== 1 ? { dpr } : {});
461
- }, ImageUrlBuilder2.prototype.width = function(width) {
462
- return this.withOptions({ width });
463
- }, ImageUrlBuilder2.prototype.height = function(height) {
464
- return this.withOptions({ height });
465
- }, ImageUrlBuilder2.prototype.focalPoint = function(x, y) {
466
- return this.withOptions({ focalPoint: { x, y } });
467
- }, ImageUrlBuilder2.prototype.maxWidth = function(maxWidth) {
468
- return this.withOptions({ maxWidth });
469
- }, ImageUrlBuilder2.prototype.minWidth = function(minWidth) {
470
- return this.withOptions({ minWidth });
471
- }, ImageUrlBuilder2.prototype.maxHeight = function(maxHeight) {
472
- return this.withOptions({ maxHeight });
473
- }, ImageUrlBuilder2.prototype.minHeight = function(minHeight) {
474
- return this.withOptions({ minHeight });
475
- }, ImageUrlBuilder2.prototype.size = function(width, height) {
476
- return this.withOptions({ width, height });
477
- }, ImageUrlBuilder2.prototype.blur = function(blur) {
478
- return this.withOptions({ blur });
479
- }, ImageUrlBuilder2.prototype.sharpen = function(sharpen) {
480
- return this.withOptions({ sharpen });
481
- }, ImageUrlBuilder2.prototype.rect = function(left, top, width, height) {
482
- return this.withOptions({ rect: { left, top, width, height } });
483
- }, ImageUrlBuilder2.prototype.format = function(format) {
484
- return this.withOptions({ format });
485
- }, ImageUrlBuilder2.prototype.invert = function(invert) {
486
- return this.withOptions({ invert });
487
- }, ImageUrlBuilder2.prototype.orientation = function(orientation) {
488
- return this.withOptions({ orientation });
489
- }, ImageUrlBuilder2.prototype.quality = function(quality) {
490
- return this.withOptions({ quality });
491
- }, ImageUrlBuilder2.prototype.forceDownload = function(download) {
492
- return this.withOptions({ download });
493
- }, ImageUrlBuilder2.prototype.flipHorizontal = function() {
494
- return this.withOptions({ flipHorizontal: !0 });
495
- }, ImageUrlBuilder2.prototype.flipVertical = function() {
496
- return this.withOptions({ flipVertical: !0 });
497
- }, ImageUrlBuilder2.prototype.ignoreImageParams = function() {
498
- return this.withOptions({ ignoreImageParams: !0 });
499
- }, ImageUrlBuilder2.prototype.fit = function(value) {
500
- if (validFits.indexOf(value) === -1)
501
- throw new Error('Invalid fit mode "'.concat(value, '"'));
502
- return this.withOptions({ fit: value });
503
- }, ImageUrlBuilder2.prototype.crop = function(value) {
504
- if (validCrops.indexOf(value) === -1)
505
- throw new Error('Invalid crop mode "'.concat(value, '"'));
506
- return this.withOptions({ crop: value });
507
- }, ImageUrlBuilder2.prototype.saturation = function(saturation) {
508
- return this.withOptions({ saturation });
509
- }, ImageUrlBuilder2.prototype.auto = function(value) {
510
- if (validAutoModes.indexOf(value) === -1)
511
- throw new Error('Invalid auto mode "'.concat(value, '"'));
512
- return this.withOptions({ auto: value });
513
- }, ImageUrlBuilder2.prototype.pad = function(pad) {
514
- return this.withOptions({ pad });
515
- }, ImageUrlBuilder2.prototype.vanityName = function(value) {
516
- return this.withOptions({ vanityName: value });
517
- }, ImageUrlBuilder2.prototype.frame = function(frame) {
518
- if (frame !== 1)
519
- throw new Error('Invalid frame value "'.concat(frame, '"'));
520
- return this.withOptions({ frame });
521
- }, ImageUrlBuilder2.prototype.url = function() {
522
- return (0, urlForImage_1.default)(this.options);
523
- }, ImageUrlBuilder2.prototype.toString = function() {
524
- return this.url();
525
- }, ImageUrlBuilder2;
526
- }()
527
- );
528
- return builder.ImageUrlBuilder = ImageUrlBuilder, builder;
529
- }
530
- var node, hasRequiredNode;
531
- function requireNode() {
532
- if (hasRequiredNode) return node;
533
- hasRequiredNode = 1;
534
- var __importDefault = node && node.__importDefault || function(mod) {
535
- return mod && mod.__esModule ? mod : { default: mod };
536
- }, builder_1 = __importDefault(requireBuilder());
537
- return node = builder_1.default, node;
538
- }
539
- var nodeExports = /* @__PURE__ */ requireNode(), createImageUrlBuilder = /* @__PURE__ */ getDefaultExportFromCjs(nodeExports);
540
- function useImageUrlBuilder(clientOptions) {
541
- const client = sanity.useClient(clientOptions);
542
- return react.useMemo(() => createImageUrlBuilder(client), [client]);
543
- }
544
- function useImageUrlBuilderImage(source, clientOptions) {
545
- const builder2 = useImageUrlBuilder(clientOptions);
546
- return react.useMemo(
547
- () => source && builder2 ? builder2.image(source) : null,
548
- [builder2, source]
549
- );
550
- }
551
- const DEFAULT_PARAMS = {}, DEFAULT_OPTIONS = { apiVersion: "v2023-05-01" }, DEFAULT_INITIAL_VALUE = null;
552
- function useParams(params) {
553
- const stringifiedParams = react.useMemo(
554
- () => JSON.stringify(params || {}),
555
- [params]
556
- );
557
- return react.useMemo(() => JSON.parse(stringifiedParams), [stringifiedParams]);
558
- }
559
- function useListeningQuery(query, {
560
- params = DEFAULT_PARAMS,
561
- options = DEFAULT_OPTIONS,
562
- initialValue = DEFAULT_INITIAL_VALUE
563
- }) {
564
- 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();
565
- return react.useEffect(() => {
566
- if (query && !error && !subscription.current)
567
- try {
568
- subscription.current = documentStore.listenQuery(query, memoParams, memoOptions).pipe(
569
- operators.distinctUntilChanged(isEqual__default.default),
570
- operators.catchError((err) => (console.error(err), setError(err), setLoading(!1), setData(null), err))
571
- ).subscribe((documents) => {
572
- setData(
573
- (current) => isEqual__default.default(current, documents) ? current : documents
574
- ), setLoading(!1), setError(!1);
575
- });
576
- } catch (err) {
577
- console.error(err), setLoading(!1), setError(err);
578
- }
579
- return error && subscription.current && subscription.current.unsubscribe(), () => {
580
- subscription.current && (subscription?.current?.unsubscribe(), subscription.current = null);
581
- };
582
- }, [query, error, memoParams, memoOptions, documentStore]), { data, loading, error };
583
- }
584
- function useOpenInNewPane(id, type) {
585
- const routerContext = react.useContext(router.RouterContext), { routerPanesState, groupIndex } = structure.usePaneRouter();
586
- return react.useCallback(() => {
587
- if (!routerContext || !id || !type)
588
- return;
589
- const panes = [...routerPanesState];
590
- panes.splice(groupIndex + 1, 0, [
591
- {
592
- id,
593
- params: { type }
594
- }
595
- ]);
596
- const href = routerContext.resolvePathFromState({ panes });
597
- routerContext.navigateUrl({ path: href });
598
- }, [id, type, routerContext, routerPanesState, groupIndex]);
599
- }
600
- function chunkArray(array, size) {
601
- const chunks = [];
602
- for (let i = 0; i < array.length; i += size)
603
- chunks.push(array.slice(i, i + size));
604
- return chunks;
605
- }
606
- function useProjectUsers({ apiVersion }) {
607
- const { currentUser } = sanity.useWorkspace(), client = sanity.useClient({ apiVersion: apiVersion ?? "2023-01-01" }), [users, setUsers] = react.useState([]);
608
- return react.useEffect(() => {
609
- const { projectId } = client.config();
610
- async function getUsersWithRoles() {
611
- try {
612
- const aclData = await client.request({
613
- url: `/projects/${projectId}/acl`
614
- }), userIds = aclData.map((user) => user.projectUserId), userIdChunks = chunkArray(userIds, 200);
615
- let usersData = [];
616
- for (const chunk of userIdChunks) {
617
- const chunkedUserIds = chunk.join(","), response = await client.request({
618
- url: `/projects/${projectId}/users/${chunkedUserIds}`
619
- });
620
- usersData = [...usersData, ...response];
621
- }
622
- const usersWithRoles = usersData.map((user) => {
623
- const userRoles = aclData.find(
624
- (aclUser) => aclUser.projectUserId === user.id
625
- )?.roles || [];
626
- return {
627
- ...user,
628
- isCurrentUser: user.id === currentUser?.id,
629
- roles: userRoles
630
- };
631
- });
632
- setUsers(usersWithRoles);
633
- } catch (err) {
634
- console.error("Failed to fetch users:", err);
635
- }
636
- }
637
- users.length || getUsersWithRoles();
638
- }, [client, currentUser?.id, users.length]), users;
639
- }
640
- exports.Cell = Cell;
641
- exports.Feedback = Feedback;
642
- exports.Row = Row;
643
- exports.Table = Table;
644
- exports.UserSelectMenu = UserSelectMenu;
645
- exports.useImageUrlBuilder = useImageUrlBuilder;
646
- exports.useImageUrlBuilderImage = useImageUrlBuilderImage;
647
- exports.useListeningQuery = useListeningQuery;
648
- exports.useOpenInNewPane = useOpenInNewPane;
649
- exports.useProjectUsers = useProjectUsers;
650
- //# sourceMappingURL=index.cjs.map