sanity 6.9.2 → 6.9.3-next.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.
- package/lib/{AddonDatasetProvider-CIq0vehp.js → AddonDatasetProvider-DDQrh5ob.js} +2 -2
- package/lib/{AddonDatasetProvider-CIq0vehp.js.map → AddonDatasetProvider-DDQrh5ob.js.map} +1 -1
- package/lib/{CalendarFilter-DRKSPTWd.js → CalendarFilter-DYbHmp_x.js} +3 -3
- package/lib/{CalendarFilter-DRKSPTWd.js.map → CalendarFilter-DYbHmp_x.js.map} +1 -1
- package/lib/{CommentsDocumentLayout-NGghzPWZ.js → CommentsDocumentLayout-qdF_HKSC.js} +2 -2
- package/lib/{CommentsDocumentLayout-NGghzPWZ.js.map → CommentsDocumentLayout-qdF_HKSC.js.map} +1 -1
- package/lib/{CommentsField-_QkW9aLe.js → CommentsField-i8xs45PB.js} +3 -3
- package/lib/{CommentsField-_QkW9aLe.js.map → CommentsField-i8xs45PB.js.map} +1 -1
- package/lib/{CommentsInput-DdtI0Naj.js → CommentsInput-B9iSSi8A.js} +6 -6
- package/lib/{CommentsInput-DdtI0Naj.js.map → CommentsInput-B9iSSi8A.js.map} +1 -1
- package/lib/{CommentsInspector-BQtqxGsK.js → CommentsInspector-rGGP9buL.js} +5 -5
- package/lib/{CommentsInspector-BQtqxGsK.js.map → CommentsInspector-rGGP9buL.js.map} +1 -1
- package/lib/{CommentsListItem-B0yR0R5a.js → CommentsListItem-DKS6V_TV.js} +3 -3
- package/lib/{CommentsListItem-B0yR0R5a.js.map → CommentsListItem-DKS6V_TV.js.map} +1 -1
- package/lib/{CommentsSelectedPathProvider-BYZ2OmJ9.js → CommentsSelectedPathProvider-BnZ6GdNc.js} +3 -3
- package/lib/{CommentsSelectedPathProvider-BYZ2OmJ9.js.map → CommentsSelectedPathProvider-BnZ6GdNc.js.map} +1 -1
- package/lib/{CommentsStudioLayout-DK4W-hTe.js → CommentsStudioLayout-YlpSH_2Y.js} +4 -4
- package/lib/{CommentsStudioLayout-DK4W-hTe.js.map → CommentsStudioLayout-YlpSH_2Y.js.map} +1 -1
- package/lib/{DateInputs-enUB1fG8.js → DateInputs-DioSKqY0.js} +7 -7
- package/lib/{DateInputs-enUB1fG8.js.map → DateInputs-DioSKqY0.js.map} +1 -1
- package/lib/{DocumentStatusIndicator-BP3N2GwG.js → DocumentStatusIndicator-BPBTH84U.js} +5 -5
- package/lib/{DocumentStatusIndicator-BP3N2GwG.js.map → DocumentStatusIndicator-BPBTH84U.js.map} +1 -1
- package/lib/{FormValue-4tVuOoGw.js → FormValue-CJg43LyM.js} +2 -2
- package/lib/{FormValue-4tVuOoGw.js.map → FormValue-CJg43LyM.js.map} +1 -1
- package/lib/{LoadingBlock-Cy2Pckab.js → LoadingBlock-DPTVJ58M.js} +3 -3
- package/lib/{LoadingBlock-Cy2Pckab.js.map → LoadingBlock-DPTVJ58M.js.map} +1 -1
- package/lib/{ReleaseTitle-CkEMIfmx.js → ReleaseTitle-ln13W3P1.js} +4 -4
- package/lib/{ReleaseTitle-CkEMIfmx.js.map → ReleaseTitle-ln13W3P1.js.map} +1 -1
- package/lib/{ReleasesMetadataProvider-DuAzHgpz.js → ReleasesMetadataProvider-DbxROVyw.js} +2 -2
- package/lib/{ReleasesMetadataProvider-DuAzHgpz.js.map → ReleasesMetadataProvider-DbxROVyw.js.map} +1 -1
- package/lib/{ReleasesNav-DozstCwb.js → ReleasesNav-DNwncim0.js} +15 -15
- package/lib/{ReleasesNav-DozstCwb.js.map → ReleasesNav-DNwncim0.js.map} +1 -1
- package/lib/{ReleasesStudioLayout-CXoRbIpf.js → ReleasesStudioLayout-gzl7rMMp.js} +8 -8
- package/lib/{ReleasesStudioLayout-CXoRbIpf.js.map → ReleasesStudioLayout-gzl7rMMp.js.map} +1 -1
- package/lib/{ReleasesTool-Bxru9khS.js → ReleasesTool-CsHniZCP.js} +20 -20
- package/lib/{ReleasesTool-Bxru9khS.js.map → ReleasesTool-CsHniZCP.js.map} +1 -1
- package/lib/{SchedulePublishingStudioLayout-CjJ-nu3Q.js → SchedulePublishingStudioLayout-BzSSDp9x.js} +3 -3
- package/lib/{SchedulePublishingStudioLayout-CjJ-nu3Q.js.map → SchedulePublishingStudioLayout-BzSSDp9x.js.map} +1 -1
- package/lib/{SchedulePublishingUpsellProvider-CxpMXwyA.js → SchedulePublishingUpsellProvider-DQqIZsCc.js} +2 -2
- package/lib/{SchedulePublishingUpsellProvider-CxpMXwyA.js.map → SchedulePublishingUpsellProvider-DQqIZsCc.js.map} +1 -1
- package/lib/{ScheduledPublishingEnabledProvider-Bvx140h2.js → ScheduledPublishingEnabledProvider-BcWaBJw5.js} +3 -3
- package/lib/{ScheduledPublishingEnabledProvider-Bvx140h2.js.map → ScheduledPublishingEnabledProvider-BcWaBJw5.js.map} +1 -1
- package/lib/{SearchProvider-DSLbCdgY.js → SearchProvider-D3w4Bvul.js} +10 -10
- package/lib/{SearchProvider-DSLbCdgY.js.map → SearchProvider-D3w4Bvul.js.map} +1 -1
- package/lib/{SingleDocReleaseLayout-DQicfsKs.js → SingleDocReleaseLayout-CQCkL8-0.js} +2 -2
- package/lib/{SingleDocReleaseLayout-DQicfsKs.js.map → SingleDocReleaseLayout-CQCkL8-0.js.map} +1 -1
- package/lib/{SingleDocReleaseUpsellProvider-DXNTZGTk.js → SingleDocReleaseUpsellProvider-YDBCGrHT.js} +4 -4
- package/lib/{SingleDocReleaseUpsellProvider-DXNTZGTk.js.map → SingleDocReleaseUpsellProvider-YDBCGrHT.js.map} +1 -1
- package/lib/{TasksStudioActiveToolLayout-CNpB5xLh.js → TasksStudioActiveToolLayout-DAmh3t6t.js} +16 -16
- package/lib/{TasksStudioActiveToolLayout-CNpB5xLh.js.map → TasksStudioActiveToolLayout-DAmh3t6t.js.map} +1 -1
- package/lib/{TasksStudioLayout-CnsvBNfw.js → TasksStudioLayout-6qNY69FD.js} +5 -5
- package/lib/{TasksStudioLayout-CnsvBNfw.js.map → TasksStudioLayout-6qNY69FD.js.map} +1 -1
- package/lib/{TimeZoneButton-DMd-M_ri.js → TimeZoneButton-TmrFye13.js} +4 -4
- package/lib/{TimeZoneButton-DMd-M_ri.js.map → TimeZoneButton-TmrFye13.js.map} +1 -1
- package/lib/{Tool-VgnYCwyZ.js → Tool-tpq9K4o7.js} +14 -14
- package/lib/{Tool-VgnYCwyZ.js.map → Tool-tpq9K4o7.js.map} +1 -1
- package/lib/{UnpublishVersionDialog-Fow5nBrc.js → UnpublishVersionDialog-6zyP9rCr.js} +5 -5
- package/lib/{UnpublishVersionDialog-Fow5nBrc.js.map → UnpublishVersionDialog-6zyP9rCr.js.map} +1 -1
- package/lib/{UpsellDialog-BqP2wmnt.js → UpsellDialog-CM238V3B.js} +3 -3
- package/lib/{UpsellDialog-BqP2wmnt.js.map → UpsellDialog-CM238V3B.js.map} +1 -1
- package/lib/{VariantsStudioNavbar-CvwRIsWJ.js → VariantsStudioNavbar-lFO2yrMq.js} +7 -7
- package/lib/{VariantsStudioNavbar-CvwRIsWJ.js.map → VariantsStudioNavbar-lFO2yrMq.js.map} +1 -1
- package/lib/{VariantsTool-CmQqDiwU.js → VariantsTool-B0OS4fku.js} +9 -9
- package/lib/{VariantsTool-CmQqDiwU.js.map → VariantsTool-B0OS4fku.js.map} +1 -1
- package/lib/{WorkspaceLoader-Ailj0PR9.js → WorkspaceLoader-CiJ6lGBu.js} +32 -32
- package/lib/{WorkspaceLoader-Ailj0PR9.js.map → WorkspaceLoader-CiJ6lGBu.js.map} +1 -1
- package/lib/_createContext.js +1 -1
- package/lib/{buildTextSelectionFromFragment-QpFfw3b7.js → buildTextSelectionFromFragment-CFZdgjpp.js} +3 -3
- package/lib/{buildTextSelectionFromFragment-QpFfw3b7.js.map → buildTextSelectionFromFragment-CFZdgjpp.js.map} +1 -1
- package/lib/{datastores-D4iZNSXV.js → datastores-wbjstxMt.js} +2 -2
- package/lib/{datastores-D4iZNSXV.js.map → datastores-wbjstxMt.js.map} +1 -1
- package/lib/{getTransactionsLogs-C-_o7nGx.js → getTransactionsLogs-Di50JBPB.js} +2 -2
- package/lib/{getTransactionsLogs-C-_o7nGx.js.map → getTransactionsLogs-Di50JBPB.js.map} +1 -1
- package/lib/index.js +35 -35
- package/lib/{inputResolver-Dpo4FxTy.js → inputResolver-DuUEGuH5.js} +4 -4
- package/lib/{inputResolver-Dpo4FxTy.js.map → inputResolver-DuUEGuH5.js.map} +1 -1
- package/lib/{navigation.telemetry-syjEPEw-.js → navigation.telemetry-EsdzXa34.js} +9 -9
- package/lib/{navigation.telemetry-syjEPEw-.js.map → navigation.telemetry-EsdzXa34.js.map} +1 -1
- package/lib/{plugin-B8Op6DFi.js → plugin-C_6lw0l3.js} +3 -3
- package/lib/{plugin-B8Op6DFi.js.map → plugin-C_6lw0l3.js.map} +1 -1
- package/lib/{plugin-CmF53OT5.js → plugin-ClT8-pVM.js} +4 -4
- package/lib/{plugin-CmF53OT5.js.map → plugin-ClT8-pVM.js.map} +1 -1
- package/lib/{plugin-Bk41RRuC.js → plugin-DRuKGgrO.js} +6 -6
- package/lib/{plugin-Bk41RRuC.js.map → plugin-DRuKGgrO.js.map} +1 -1
- package/lib/{plugin-BhEK2rZ8.js → plugin-wJP1ECFq.js} +6 -6
- package/lib/{plugin-BhEK2rZ8.js.map → plugin-wJP1ECFq.js.map} +1 -1
- package/lib/{scheduleItem-sJhB8YzX.js → scheduleItem-9PFIH7_h.js} +15 -15
- package/lib/{scheduleItem-sJhB8YzX.js.map → scheduleItem-9PFIH7_h.js.map} +1 -1
- package/lib/{schedules-CLC2KygL.js → schedules-DniNrpFJ.js} +3 -3
- package/lib/{schedules-CLC2KygL.js.map → schedules-DniNrpFJ.js.map} +1 -1
- package/lib/{searchDocumentRelease-CtPYZAZk.js → searchDocumentRelease-TrunKdQg.js} +5 -5
- package/lib/{searchDocumentRelease-CtPYZAZk.js.map → searchDocumentRelease-TrunKdQg.js.map} +1 -1
- package/lib/{studioClient-WYiCwgfZ.js → studioClient-BpYJ_yYC.js} +2 -2
- package/lib/{studioClient-WYiCwgfZ.js.map → studioClient-BpYJ_yYC.js.map} +1 -1
- package/lib/{useBundleDocuments-CiRQnzQh.js → useBundleDocuments-C58ExRpX.js} +5 -5
- package/lib/{useBundleDocuments-CiRQnzQh.js.map → useBundleDocuments-C58ExRpX.js.map} +1 -1
- package/lib/{useComments-CxUK5MNb.js → useComments-BcMCyjIE.js} +2 -2
- package/lib/{useComments-CxUK5MNb.js.map → useComments-BcMCyjIE.js.map} +1 -1
- package/lib/{useCommentsTelemetry-BWqcsQ1u.js → useCommentsTelemetry-CL97yuwT.js} +4 -4
- package/lib/{useCommentsTelemetry-BWqcsQ1u.js.map → useCommentsTelemetry-CL97yuwT.js.map} +1 -1
- package/lib/{useDocumentPreviewValues-B4jUnACZ.js → useDocumentPreviewValues-Cy9aUMu2.js} +5 -5
- package/lib/{useDocumentPreviewValues-B4jUnACZ.js.map → useDocumentPreviewValues-Cy9aUMu2.js.map} +1 -1
- package/lib/{useFeatureEnabled-sRpDeLLJ.js → useFeatureEnabled-C5qTffLc.js} +2 -2
- package/lib/{useFeatureEnabled-sRpDeLLJ.js.map → useFeatureEnabled-C5qTffLc.js.map} +1 -1
- package/lib/{useFieldActions-CrPgIiyl.js → useFieldActions-MFJIkobn.js} +2 -2
- package/lib/{useFieldActions-CrPgIiyl.js.map → useFieldActions-MFJIkobn.js.map} +1 -1
- package/lib/{useProjectId-bGwoCAuz.js → useProjectId-BRSQ8kIo.js} +2 -2
- package/lib/{useProjectId-bGwoCAuz.js.map → useProjectId-BRSQ8kIo.js.map} +1 -1
- package/lib/{useReleasesToolAvailable-BevhFmt9.js → useReleasesToolAvailable-BOlw1HWL.js} +3 -3
- package/lib/{useReleasesToolAvailable-BevhFmt9.js.map → useReleasesToolAvailable-BOlw1HWL.js.map} +1 -1
- package/lib/{useScheduledDraftMenuActions-DqsFlU0p.js → useScheduledDraftMenuActions-DIQYFw0x.js} +6 -6
- package/lib/{useScheduledDraftMenuActions-DqsFlU0p.js.map → useScheduledDraftMenuActions-DIQYFw0x.js.map} +1 -1
- package/lib/{useStudioUrl-DbfIwS1P.js → useStudioUrl-Dc5LnOvR.js} +5 -5
- package/lib/{useStudioUrl-DbfIwS1P.js.map → useStudioUrl-Dc5LnOvR.js.map} +1 -1
- package/lib/{useTimeZone-DnxQlCGS.js → useTimeZone-Da8WK1q-.js} +2 -2
- package/lib/{useTimeZone-DnxQlCGS.js.map → useTimeZone-Da8WK1q-.js.map} +1 -1
- package/lib/{validationUtils-Bcu-PkHm.js → validationUtils-B9CLn9F7.js} +4 -4
- package/lib/{validationUtils-Bcu-PkHm.js.map → validationUtils-B9CLn9F7.js.map} +1 -1
- package/lib/{version-DTqx_kFw.js → version-D7qSwBVE.js} +2 -2
- package/lib/{version-DTqx_kFw.js.map → version-D7qSwBVE.js.map} +1 -1
- package/package.json +11 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBundleDocuments-CiRQnzQh.js","names":["ReleaseDocument","ReleaseType","DocumentSystem","Dispatch","Observable","RELEASE_DOCUMENT_TYPE","MetadataWrapper","ReleasesReducerAction","ReleasesReducerState","releaseTypes","const","isReleaseType","maybeReleaseType","includes","isReleaseDocument","doc","_type","ReleaseStore","state$","errorCount$","getMetadataStateForSlugs$","slugs","dispatch","VersionInfoDocumentStub","_id","_rev","_createdAt","_updatedAt","_system","ReleaseDocument","isReleaseDocument","CardinalityOneRelease","metadata","cardinality","isCardinalityOneRelease","release","isCardinalityOnePerspective","perspective","isPausedCardinalityOneRelease","state","releaseType","Boolean","intendedPublishAt","ReleaseType","BadgeTone","LATEST","const","PUBLISHED","DEFAULT_RELEASE_TYPE","ARCHIVED_RELEASE_STATES","RELEASE_TYPES_TONES","Record","tone","asap","scheduled","undecided","tz","tzHelper","formatRelative","isValid","parse","DateInput","Date","RUNTIME_TIME_ZONE","Intl","DateTimeFormat","resolvedOptions","timeZone","formatRelativeLocale","date","baseDate","relative","in","toLocaleDateString","undefined","customAlphabet","RELEASE_DOCUMENTS_PATH","createBundleId","createReleaseId","EditableReleaseDocument","ReleaseDocument","ReleaseState","DocumentSystem","TargetPerspective","getVersionFromId","isVersionId","formatRelativeLocale","isCardinalityOneRelease","isPausedCardinalityOneRelease","CardinalityView","Mode","DEFAULT_RELEASE_TYPE","LATEST","createReleaseId","getReleaseIdFromReleaseDocumentId","NotArchivedRelease","state","Exclude","getDocumentIsInPerspective","documentId","perspective","releaseId","getPublishDateFromRelease","release","Date","dateString","publishedAt","publishAt","metadata","intendedPublishAt","formatRelativeLocalePublishDate","timeZone","publishDate","isPublishedPerspective","isDraftPerspective","isReleaseScheduledOrScheduling","releaseType","getReleaseDefaults","_id","title","description","cardinality","isNotArchivedRelease","shouldShowReleaseInView","cardinalityView","isCardinalityOne","FilterReleasesOptions","releases","T","archivedReleases","releaseGroupMode","dateFilter","filterDate","getTimezoneAdjustedDateTimeRange","date","filterReleasesForOverview","options","sourceReleases","applyDateFilter","items","startOfDayForTimeZone","endOfDayForTimeZone","filter","publishDateUTC","dateFiltered","BadgeTone","TargetPerspective","isAgentBundleName","isPausedCardinalityOneRelease","isReleaseDocument","RELEASE_TYPES_TONES","isDraftPerspective","isPublishedPerspective","getReleaseTone","release","state","metadata","releaseType","asap","tone","undecided","scheduled","ClientPerspective","ReleaseDocument","PerspectiveStack","ReleaseId","getReleaseIdFromReleaseDocumentId","sortReleases","releases","sort","a","b","metadata","releaseType","Date","_createdAt","getTime","aPublishAt","publishAt","intendedPublishAt","bPublishAt","DRAFTS","PUBLISHED","EMPTY","getReleasesPerspectiveStack","selectedPerspectiveName","excludedPerspectives","isDraftModelEnabled","defaultPerspective","sorted","map","release","_id","selectedIndex","indexOf","slice","concat","filter","name","includes","SanityClient","bufferTime","catchError","EMPTY","filter","iif","merge","Observable","of","startWith","switchMap","getReleaseIdFromReleaseDocumentId","ReleasesMetadata","ReleasesMetadataMap","Record","MetadataWrapper","data","error","loading","getFetchQuery","releaseIds","getSafeKey","id","replaceAll","reduce","subquery","accSubquery","projection","accProjection","releaseId","bundleId","safeId","createReleaseMetadataAggregator","client","aggregatorFetch$","isInitialLoad","length","queryAllDocumentsInReleases","projectionToBundleMetadata","fetchData$","observable","fetch","Omit","documentIds","tag","pipe","releaseDocumentIdResponse","Object","entries","existing","el","metadata","documentCount","console","aggregatorListener$","listen","accQuery","index","includeResult","includeAllVersions","visibility","events","entriesArray","mutatedReleaseIds","accReleaseIds","event","type","documentId","split","includes","ReleaseDocument","BundleDeletedAction","id","currentUserId","deletedByUserId","type","ReleasesSetAction","payload","LoadingStateChangedAction","loading","error","Error","ReleasesReducerAction","ReleasesReducerState","releases","Map","state","createReleasesSet","reduce","acc","bundle","set","_id","releasesReducer","action","releasesById","ReleaseDocument","ReleaseType","SanityClient","BehaviorSubject","catchError","concat","concatWith","count","filter","from","merge","Observable","of","OperatorFunction","pipe","scan","shareReplay","Subject","switchMap","tap","distinctUntilChanged","map","startWith","DocumentPreviewStore","listenQuery","RELEASE_DOCUMENT_TYPE","RELEASE_DOCUMENTS_PATH","createReleaseMetadataAggregator","releasesReducer","ReleasesReducerAction","ReleasesReducerState","ReleaseStore","ActionWrapper","action","ResponseWrapper","response","SORT_FIELD","SORT_ORDER","QUERY_FILTER","DEFAULT_RELEASE_TYPE","QUERY_PROJECTION","QUERY_SORT_ORDER","QUERY","INITIAL_STATE","releases","Map","state","const","createReleaseStore","context","previewStore","client","dispatch$","fetchPending$","dispatch","next","listFetch$","type","payload","loading","error","undefined","value","tag","entry","state$","errorCount$","releaseStoreErrorCount","getMetadataStateForSlugs$","values","release","useMemo","useClient","useDocumentPreviewStore","useResourceCache","useWorkspace","RELEASES_STUDIO_CLIENT_OPTIONS","createReleaseStore","ReleaseStore","useReleasesStore","$","_c","resourceCache","workspace","previewStore","studioClient","releaseStore","get","dependencies","namespace","client","set","value","ReleaseDocument","useMemo","useSyncObservable","sortReleases","ARCHIVED_RELEASE_STATES","ReleasesReducerAction","useReleasesStore","ReleasesState","data","error","Error","loading","dispatch","event","useActiveReleases","$","_c","state$","state","t0","releases","Array","from","values","filter","_temp","reverse","releasesAsArray","t1","t2","Symbol","for","t3","includes","t4","release","PreviewLayoutKey","PREVIEW_SIZES","Record","icon","media","height","width","block","blockImage","compact","default","detail","inline","rem","css","styled","PREVIEW_SIZES","PreviewLayoutKey","PreviewMediaDimensions","MediaWrapper","span","$dimensions","$layout","$radius","$responsive","props","width","height","iconSize","icon","undefined","theme","sanity","radius","displayName","Text","ComponentType","isValidElement","ReactNode","isValidElementType","PreviewLayoutKey","PreviewMediaDimensions","PreviewProps","MediaWrapper","MediaProps","border","dimensions","layout","media","radius","responsive","styles","mediaString","Media","props","$","_c","t0","t1","t2","undefined","t3","t4","renderMedia","t5","t6","MediaComponent","tryGetImageDimensions","ElementType","isValidElement","ReactNode","isValidElementType","getDevicePixelRatio","PREVIEW_SIZES","PreviewProps","PreviewLayoutKey","PreviewMediaDimensions","renderPreviewMedia","value","Layout","layout","dimensions","Value","isReactNode","renderPreviewNode","fallbackNode","resolveBlockImageDimensions","source","Parameters","sourceDimensions","undefined","max","blockImage","media","scale","Math","min","width","round","height","fit","dpr","Box","Flex","rem","Skeleton","Stack","Text","TextSkeleton","styled","getDevicePixelRatio","useTranslation","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","CompactPreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","compact","media","aspect","fit","dpr","Root","height","TitleSkeleton","attrs","animated","radius","size","CompactPreview","props","$","_c","children","isPlaceholder","status","title","t","t0","statusNode","t1","t2","t3","Symbol","for","t4","t5","color","t6","t7","t8","t9","hues","Card","Theme","css","styled","STROKE_WIDTH","Root","Bar","theme","color","sanity","blue","dark","hex","LinearProgress","props","$","_c","value","t0","t1","transform","Box","Flex","rem","Skeleton","Stack","Text","TextSkeleton","clsx","styled","getDevicePixelRatio","useTranslation","LinearProgress","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","DefaultPreviewProps","Omit","styles","root","placeholder","media","heading","title","subtitle","hasSubtitle","mediaString","status","children","DEFAULT_MEDIA_DIMENSIONS","default","aspect","fit","dpr","Root","height","TitleSkeleton","attrs","animated","radius","size","SubtitleSkeleton","SKELETON_DELAY","DefaultPreview","props","$","_c","isPlaceholder","progress","t","t0","t1","Boolean","t2","rootClassName","isUploading","t3","statusNode","t4","t5","t6","t7","Symbol","for","t8","t9","t10","color","t11","t12","t13","Box","Flex","rem","Skeleton","Text","TextSkeleton","css","styled","PREVIEW_SIZES","RootFlex","attrs","align","detail","media","height","StatusBox","MediaSkeleton","animated","radius","width","TitleSkeleton","size","SubtitleSkeleton","DescriptionSkeleton","DescriptionText","theme","fonts","sanity","textSize1","text","sizes","maxLines","maxHeight","lineHeight","Box","Flex","Stack","Text","getDevicePixelRatio","useTranslation","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","DescriptionSkeleton","DescriptionText","MediaSkeleton","RootFlex","StatusBox","SubtitleSkeleton","TitleSkeleton","DetailPreviewProps","DEFAULT_MEDIA_DIMENSIONS","detail","media","fit","aspect","dpr","DetailPreview","props","$","_c","title","subtitle","description","mediaDimensions","t0","status","children","isPlaceholder","undefined","t","t1","statusNode","t2","t3","t4","t5","Symbol","for","t6","t7","t8","t9","color","t10","t11","t12","t13","hues","Theme","css","styled","SIZE","STROKE_WIDTH","Root","svg","BgCircle","circle","theme","color","sanity","gray","dark","hex","ProgressCircle","blue","CircularProgress","props","$","_c","value","valueProp","Math","min","max","radius","circ","PI","offset","viewBox","t0","Symbol","for","t1","t2","strokeDasharray","strokeDashoffset","Box","Flex","rem","Skeleton","Stack","styled","RootBox","MediaFlex","attrs","align","justify","MediaSkeleton","animated","radius","ProgressFlex","TooltipContentStack","gap","Box","Text","useMemo","getDevicePixelRatio","Tooltip","CircularProgress","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","MediaFlex","MediaSkeleton","ProgressFlex","RootBox","TooltipContentStack","MediaPreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","media","aspect","fit","dpr","MediaPreview","props","$","_c","mediaDimensions","t0","children","isPlaceholder","progress","t1","subtitle","title","withBorder","t2","withRadius","t3","undefined","t4","t5","paddingBottom","STYLES_PADDER","t6","bb0","t7","t8","t9","tooltipContent","t10","t11","t12","t13","Box","Card","Flex","rem","styled","PREVIEW_SIZES","HeaderFlex","attrs","align","block","media","height","MediaCard","$ratio","RootBox","overflow","theme","sanity","radius","Box","Flex","Stack","Text","getDevicePixelRatio","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","HeaderFlex","MediaCard","RootBox","BlockImagePreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","blockImage","media","fit","dpr","getRatio","dimensions","height","width","BlockImagePreview","props","$","_c","actions","title","subtitle","description","fallbackTitle","t0","mediaDimensions","t1","children","status","undefined","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","Box","Flex","rem","Stack","Text","styled","getDevicePixelRatio","LinearProgress","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","DEFAULT_MEDIA_DIMENSIONS","block","media","aspect","fit","dpr","HeaderFlex","attrs","align","height","BlockPreview","props","$","_c","actions","title","subtitle","description","mediaDimensions","t0","progress","status","children","undefined","isUploading","t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","rem","Text","Theme","css","styled","RootSpan","span","MediaSpan","theme","sanity","radius","TextSpan","attrs","forwardedAs","textFont","fonts","text","textSize","sizes","fontSize","weights","medium","lineHeight","getDevicePixelRatio","PREVIEW_SIZES","renderPreviewMedia","renderPreviewNode","PreviewMediaDimensions","PreviewProps","MediaSpan","RootSpan","TextSpan","InlinePreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","inline","media","fit","aspect","dpr","InlinePreview","props","$","_c","title","fallbackTitle","t0","mediaDimensions","t1","undefined","t2","t3","t4","t5","isString","Plugin","PluginOptions","PluginFactory","options","TOptions","validatePlugin","pluginResult","messages","filter","length","Error","map","message","join","definePlugin","arg","pluginFactory","result","createPlugin","useToast","useEffect","definePlugin","LayoutProps","SchedulePublishingStudioLayout","props","$","_c","toast","t0","t1","console","error","push","id","closable","duration","status","title","description","t2","renderDefault","deprecatedScheduledPublishingPlugin","name","studio","components","layout","deprecatedScheduledPublishingPlugin","PluginOptions","DEPRECATED_PLUGINS","flattenConfig","plugins","currentConfig","path","Array","config","rootConfig","name","allPlugins","flatMap","plugin","deprecatedScheduledPublishing","find","p","push","resolved","filter","includes","Skeleton","ComponentType","Fragment","Suspense","useMemo","useSource","flattenConfig","PluginOptions","emptyRender","_createMiddlewareComponent","DefaultComponent","T","middlewareComponents","MiddlewareComponent","outerProps","$","_c","next","_temp","Symbol","for","Middleware","renderDefault","props","t0","t1","useMiddlewareComponents","options","__internal","defaultComponent","pick","flattened","reverse","pickedComponents","map","config","result","filter","Boolean","isString","SanityClient","createMediaLibraryClient","client","libraryId","apiHost","projectId","config","Error","baseUrl","URL","hostname","withConfig","origin","resource","id","type","GlobalDocumentReferenceValue","MediaLibraryRef","hasOwnRecord","PropertyKey","value","key","K","Record","Object","prototype","hasOwnProperty","call","makeMediaLibraryRef","libraryId","assetId","containsMediaProperty","media","_ref","isMediaLibraryRef","ref","resourceType","resourceId","documentId","split","Boolean","getMediaLibraryRef","maybeRef","undefined","SanityClient","DataLoader","QuickLRU","createMediaLibraryClient","makeMediaLibraryRef","MediaLibraryRef","AccessPolicyResult","POLICY_CACHE_MAX_SIZE","POLICY_CACHE_MAX_AGE","loaders","Map","policyCache","maxAge","maxSize","fetchAccessPoliciesBatch","params","assetIds","client","libraryId","Promise","length","results","fetch","_id","cdnAccessPolicy","ids","policyById","Object","fromEntries","map","doc","assetId","policy","assetRef","set","error","console","forEach","undefined","resolveAssetPolicyLoader","existingLoader","get","mediaLibraryClient","loader","cache","enqueueAssetAccessPolicyFetch","split","resolve","has","load","SanityClient","SanityImageSource","AssetSource","useSWR","enqueueAssetAccessPolicyFetch","getMediaLibraryRef","MediaLibraryRef","AssetAccessPolicy","useAccessPolicy","params","$","_c","client","source","t0","ref","canCheck","Boolean","config","token","requestKey","t1","key","fetcher","t2","Symbol","for","dedupingInterval","revalidateOnFocus","revalidateOnReconnect","shouldRetryOnError","options","data","cdnAccessPolicy","isLoading","DEFAULT_API_VERSION","DEPLOYED_FRONTEND_HOST_STAGING","CDN_HOST_STAGING","API_HOST_STAGING","DEPLOYED_FRONTEND_HOST_PRODUCTION","CDN_HOST_PRODUCTION","API_HOST_PRODUCTION","useClient","DEFAULT_API_VERSION","useToken","$","_c","t0","Symbol","for","apiVersion","client","t1","config","token","useEffect","useState","useToken","UseImageObjectUrlResult","error","Error","isLoading","objectUrl","RequestCacheEntry","abortController","AbortController","blob","Blob","cleanupTimer","ReturnType","setTimeout","listeners","Set","status","CACHE_DISPOSE_DELAY","requestCache","Map","IDLE_RESULT","undefined","LOADING_RESULT","createCacheKey","url","token","notifyListeners","entry","forEach","listener","deriveResultFromEntry","createFetchCacheEntry","fetch","cache","headers","Authorization","signal","then","res","ok","URL","createObjectURL","catch","useImageObjectUrl","$","_c","t0","cacheKey","t1","get","state","setState","t2","t3","_temp","entry_0","set","clearTimeout","updateState","add","delete","size","abort","revokeObjectURL","prev","ImageUrlBuilder","SanityImageSource","AssetAccessPolicy","useImageObjectUrl","UseImageUrlParameters","accessPolicy","imageSource","T","imageUrlBuilder","transform","builder","value","UseImageUrlResult","isLoading","url","useImageUrl","params","$","_c","t0","undefined","isPolicyCheckInProgress","isPrivate","t1","bb0","t2","image","networkUrl","objectUrl","objectUrlIsLoading","CompactPreview","DefaultPreview","DetailPreview","MediaPreview","BlockImagePreview","BlockPreview","InlinePreview","_previewComponents","block","blockImage","compact","default","detail","inline","media","const","isImageSource","isSanityImageUrl","parseImageAssetUrl","SanityClient","DocumentIcon","WarningOutlineIcon","createImageUrlBuilder","ImageUrlBuilder","SanityImageSource","Card","Flex","Skeleton","ComponentType","ElementType","isValidElement","memo","ReactNode","useCallback","useMemo","useState","isValidElementType","Tooltip","resolveBlockImageDimensions","PreviewMediaDimensions","PreviewProps","useAccessPolicy","useImageUrl","useClient","DEFAULT_STUDIO_CLIENT_OPTIONS","isString","_previewComponents","FallbackIcon","$","_c","t0","Symbol","for","SanityDefaultPreviewProps","Omit","error","Error","icon","tooltip","SanityDefaultMediaProps","client","dimensions","imageSource","imageUrlBuilder","title","SanityDefaultMedia","t1","builder","val","width","height","fit","dpr","image","withOptions","url","transform","t2","source","accessPolicy","t3","isLoading","hasImageError","setHasImageError","t4","handleError","t5","showAccessWarning","t6","undefined","SanityDefaultPreview","props","Icon","imageUrl","layout","mediaProp","restProps","media","imageBuilder","options","assetId","renderMedia","renderIcon","bb0","bb1","mediaDimensions","resolvedMediaDimensions","previewProps","LayoutComponent","children","t7","t8","t9","t10","displayName","SchemaType","ComponentType","PreviewProps","SanityDefaultPreview","defaultResolvePreviewComponent","schemaType","Omit","components","preview","ComponentType","PreviewProps","PluginOptions","BlockAnnotationProps","BlockProps","PortableTextPluginsProps","FieldProps","InputProps","ItemProps","pickInputComponent","plugin","Omit","form","components","input","pickFieldComponent","field","pickPreviewComponent","preview","pickItemComponent","item","pickBlockComponent","block","pickInlineBlockComponent","inlineBlock","pickAnnotationComponent","annotation","pickPortableTextEditorPluginsComponent","portableText","plugins","SchemaType","ComponentType","useCallback","useMemo","useResolveDefaultComponent","props","$","_c","componentResolver","componentProps","schemaType","Error","t0","DefaultResolvedComponent","t1","parentTypeProps","type","components","restSchemaType","ParentTypeResolvedComponent","renderDefault","t2","ComponentType","PreviewProps","useMiddlewareComponents","defaultResolvePreviewComponent","pickPreviewComponent","useResolveDefaultComponent","DefaultPreview","props","$","_c","t0","componentProps","componentResolver","usePreviewComponent","Symbol","for","defaultComponent","pick","useContext","PerspectiveContext","PerspectiveContextValue","usePerspective","context","Error","SanityDocument","SanityDocumentLike","isGoingToUnpublish","document","Boolean","_system","delete","PreviewValue","SanityDocument","SchemaType","SortOrdering","useMemo","useSyncObservable","Observable","of","catchError","map","PerspectiveStack","usePerspective","isGoingToUnpublish","useDocumentPreviewStore","getPublishedId","Previewable","unstable_useValuePreview","useValuePreview","State","isLoading","error","Error","value","INITIAL_STATE","IDLE_STATE","title","undefined","description","props","$","_c","t0","enabled","t1","ordering","schemaType","previewValue","perspectiveStack","chosenPerspectiveStack","variant","chosenVariant","observeForPreview","selectedVariantName","t2","bb0","t3","Symbol","for","t4","goingToUnpublish","t5","updatedStack","updatedVariant","updatedDocId","_id","restPreviewValue","perspective","viewOptions","pipe","_temp","_temp2","observable","event","snapshot","EMPTY","fromEvent","shareReplay","orientationChange$","window","pipe","EMPTY","fromEvent","shareReplay","resize$","window","pipe","EMPTY","fromEvent","shareReplay","scroll$","window","passive","capture","pipe","merge","Observable","of","observableOf","Subject","filter","map","mergeMap","orientationChange$","resize$","scroll$","ROOT_MARGIN_PX","isIntersectionObserverSupported","window","IntersectionObserverEntry","prototype","Object","defineProperty","get","intersectionRatio","IntersectionEvent","isIntersecting","intersectionObservableFor","createIntersectionObserverBased","createLegacyBased","IntersectionObservableFor","element","Element","intersectionObserverEntriesSubject","intersectionObserver","IntersectionObserver","entries","forEach","entry","next","threshold","rootMargin","observer","observe","unobserve","pipe","asObservable","target","ev","getViewport","left","right","innerWidth","top","bottom","innerHeight","intersects","rect","DOMRect","viewport","margin","inViewport","HTMLElement","getBoundingClientRect","isElementInViewport","EMPTY","fromEvent","Observable","shareReplay","visibilityChange$","Event","window","document","pipe","useMemo","useObservable","concat","of","delay","distinctUntilChanged","map","startWith","switchMap","intersectionObservableFor","visibilityChange$","Props","disabled","element","HTMLElement","hideDelay","useVisibility","props","$","_c","t0","undefined","t1","bb0","t2","Symbol","for","seed","checkVisibility","isDocumentVisible$","document","hidden","pipe","_temp","inViewport$","_temp2","t3","isVisible","isDocumentVisible","visible$","visible","event_0","event","isIntersecting","target","Document","UploadState","isRecord","isString","_extractUploadState","value","_resolveUploadValue","_upload","getStringOrUndefined","undefined","progress","createdAt","initiated","updatedAt","updated","fileName","file","name","fileType","type","previewImage","ComponentType","CSSProperties","useMemo","useState","PreviewProps","RenderPreviewCallbackProps","useTranslation","PerspectiveStack","useValuePreview","useVisibility","_HIDE_DELAY","_extractUploadState","PreviewLoader","props","$","_c","Component","layout","perspectiveStack","restProps","schemaType","skipVisibilityCheck","styleProp","value","variant","component","style","t","element","setElement","isVisible","disabled","hideDelay","t0","t1","enabled","preview","t2","minWidth","t3","minHeight","t4","t5","uploadState","t6","bb0","previewImage","t7","t8","media","undefined","icon","error","t9","isLoading","t10","t11","usePreviewComponent","RenderPreviewCallbackProps","PerspectiveStack","PreviewLoader","Preview","props","$","_c","PreviewComponent","t0","useSource","useDataset","dataset","ReleaseDocument","getVersionFromId","DocumentSystem","useMemo","useSyncObservable","catchError","combineLatest","finalize","map","Observable","of","ReplaySubject","share","startWith","switchMap","timer","useDataset","useProjectId","DOCUMENT_SYSTEM_FIELD","DocumentPreviewStore","useDocumentPreviewStore","isDraftId","getPublishedId","isRecord","createSWR","VersionInfoDocumentStub","useReleasesStore","ARCHIVED_RELEASE_STATES","getReleaseIdFromReleaseDocumentId","DocumentPerspectiveProps","documentId","DocumentPerspectiveState","data","versions","error","loading","INITIAL_VALUE","observableCache","Map","withSystemCache","swr","maxSize","TEARDOWN_GRACE_PERIOD","useDocumentVersions","props","observable","useDocumentVersionsObservable","$","_c","t0","publishedId","dataset","projectId","documentPreviewStore","state$","releasesState$","t1","pipe","_temp2","releases$","t2","getOrCreateDocumentVersionsWithSystemObservable","state","Array","from","releases","values","filter","_temp","release","includes","buildDocumentSystem","id","versionId","releaseDocument","find","_id","bundleId","_ref","_weak","undefined","group","scopeId","resolveVersionSystem","version","_system","DOCUMENT_STUB_PATHS","getOrCreateCachedObservable","cache","T","cacheKey","createObservable","cached","get","delete","connector","resetOnRefCountZero","set","options","getOrCreateDocumentVersionsObservable","result","unstable_observeVersionDocumentIds","value","documentIds","index","length","versions$","observePaths","versionInfo","_rev","_createdAt","_updatedAt","loadingState","useContext","ActiveWorkspaceMatcherContext","ActiveWorkspaceMatcherContextValue","useActiveWorkspace","value","Error","CanvasResource","Events","MediaResource","StudioResource","DocumentHandle","useCallback","useComlinkStore","DocumentInteractionHistory","recordEvent","eventType","UseRecordDocumentHistoryEventProps","resourceType","resourceId","schemaName","useRecordDocumentHistoryEvent","t0","$","_c","documentId","documentType","node","Error","t1","run","message","type","data","document","id","resource","post","t2","error","console","useCallback","useMemo","useState","useSyncObservable","useRenderingContextStore","OperationsAPI","useActiveWorkspace","getVersionId","useRecordDocumentHistoryEvent","Options","api","publishedDocId","docTypeName","version","useDocumentOperationWithComlinkHistory","t0","$","_c","activeWorkspace","t1","t2","dataset","projectId","t3","join","t4","name","resourceType","documentId","documentType","resourceId","schemaName","recordEvent","renderingContextStore","capabilities","hasRecordedEdit","setHasRecordedEdit","t5","next","preRecordPatch","comlink","t6","t7","hasComlink","comlinkContext","t8","withComlinkEvent","operationName","comlinkEventType","withComlinkDelete","t9","withComlinkDel","t10","preRecordEvent","withComlinkPatch","t11","ComlinkEventType","Parameters","ReturnType","ExecuteParameters","OperationName","RecordEvent","PreRecordEvent","WithComlinkEventOptions","execute","args","useMemo","normalizeDocumentPairTarget","DocumentPairTarget","useMemoizedDocumentPairTarget","version","$","_c","t0","target","kind","scopeId","undefined","variantId","allowCreate","t1","bb0","t2","Symbol","for","useMemo","useSyncObservable","useDocumentStore","OperationsAPI","DocumentPairTarget","useDocumentOperationWithComlinkHistory","useMemoizedDocumentPairTarget","useDocumentOperation","publishedDocId","docTypeName","version","$","_c","documentStore","target","t0","pair","editOperations","observable","api","t1","PerspectiveBundle","DocumentPerspectiveState","VersionInfoDocumentStub","getTargetDocument","bundle","documentVersions","variant","find","version","inBundle","_system","bundleId","inVariant","_ref","getVariantPublishedSibling","SystemVariant","VariantDeletedAction","type","payload","id","FetchSucceededAction","VariantsSetAction","LoadingStateChangedAction","loading","error","Error","VariantStoreAction","VariantStoreState","variants","Map","state","createVariantsSet","reduce","acc","variant","set","_id","variantStoreReducer","action","variantsById","undefined","restVariants","delete","SanityClient","Dispatch","catchError","concatWith","merge","Observable","of","scan","shareReplay","Subject","map","startWith","listenQuery","VARIANT_DOCUMENTS_PATH","VARIANT_DOCUMENT_TYPE","variantStoreReducer","VariantStoreAction","VariantStoreState","SORT_FIELD","SORT_ORDER","QUERY_SORT_ORDER","QUERY_FILTER","QUERY_PROJECTION","QUERY","INITIAL_STATE","variants","Map","state","const","VariantStore","state$","dispatch","createVariantsStore","context","client","enabled","disabledState","dispatch$","action","next","listFetch$","type","payload","loading","error","undefined","pipe","tag","useMemo","useClient","useResourceCache","useWorkspace","VARIANTS_STUDIO_CLIENT_OPTIONS","createVariantsStore","VariantStore","useVariantsStore","$","_c","workspace","variantsEnabled","Boolean","beta","variants","enabled","resourceCache","studioClient","variantStore","get","dependencies","namespace","client","set","value","useMemo","useSyncObservable","SystemVariant","useVariantsStore","useAllVariants","$","_c","state$","variants","error","state","t0","Array","from","values","t1","Symbol","for","t2","includes","t3","data","byId","loading","useMemo","PerspectiveBundle","usePerspective","useDocumentVersions","VersionInfoDocumentStub","DocumentPairTarget","getVersionFromId","getTargetDocument","getVariantPublishedSibling","useAllVariants","SystemVariant","CreatableTargetDocument","id","scopeId","TargetDocumentState","status","targetDocument","variant","publishedSibling","bundle","creatableTarget","requestedVariantName","RESOLVING","getCreatableTarget","undefined","draftId","_system","draft","_ref","getTargetScopeId","state","getCreatableVariantTarget","getPairTarget","kind","variantId","_id","allowCreate","getTargetDocumentState","options","selectedVariant","selectedVariantName","variantsLoading","versions","versionsLoading","documentVersions","useTargetDocumentState","documentGroupId","$","_c","t0","documentId","loading","t1","SanityClient","SanityDocument","Schema","SchemaType","useMemo","combineLatest","Observable","of","map","shareReplay","switchMap","useClient","useSchema","DEFAULT_STUDIO_CLIENT_OPTIONS","createHookFromObservableFactory","getDraftId","getPublishedId","getIdPair","PartialExcept","useGrantsStore","snapshotPair","DocumentStoreExtraOptions","memoize","useCurrentUser","GrantsStore","PermissionCheckResult","shareLatestWithRefCount","T","bufferSize","refCount","getSchemaType","schema","typeName","type","get","Error","PairPermissionsOptions","grantsStore","permission","DocumentPermission","draft","version","published","liveEdit","getPairPermissions","Array","effectiveVersion","effectiveVersionType","checkDocumentPermission","_id","DocumentPairPermissionsOptions","client","id","userId","serverActionsEnabled","pairListenerOptions","getDocumentPairPermissionsUncached","v","granted","reason","Boolean","undefined","pipe","pair","snapshots$","pairPermissions","label","observable","length","permissionResults","every","permissionResult","filter","join","getDocumentPairPermissions","options","dataset","projectId","config","useDocumentPairPermissionsFromHookFactory","useDocumentPairPermissions","t0","$","_c","overrideClient","overrideSchema","overrideGrantsStore","defaultClient","defaultSchema","defaultGrantsStore","currentUser","t1","RELEASE_DOCUMENTS_PATH","getReleaseDocumentIdFromReleaseId","name","useContext","ReleasesUpsellContext","ReleasesUpsellContextValue","useReleasesUpsell","value","FALLBACK_CONTEXT_VALUE","upsellDialogOpen","mode","const","onReleaseLimitReached","guardWithReleaseLimitUpsell","undefined","handleOpenDialog","upsellData","telemetryLogs","dialogSecondaryClicked","dialogPrimaryClicked","panelViewed","panelDismissed","panelPrimaryClicked","panelSecondaryClicked","ErrorWithDetails","details","type","isErrorWithDetails","error","isErrorWithDetails","ReleaseLimitError","details","type","limit","isReleaseLimitError","error","BaseActionOptions","CreateVersionAction","DiscardVersionAction","EditableReleaseDocument","IdentifiedSanityDocumentStub","ReleaseDocument","SanityClient","SingleActionResult","getDraftId","getPublishedId","getVersionFromId","getVersionId","ReleasesUpsellContextValue","RevertDocument","getReleaseIdFromReleaseDocumentId","isReleaseLimitError","ReleaseOperationsStore","publishRelease","releaseId","opts","Promise","discardDrafts","documentIds","schedule","date","Date","unschedule","archive","unarchive","updateRelease","release","createRelease","deleteRelease","revertRelease","revertReleaseId","documents","releaseMetadata","revertType","duplicateRelease","releaseDocumentId","releaseDocuments","createVersion","documentId","discardVersion","unpublishVersion","revertUnpublishVersion","createReleaseOperationsStore","options","client","onReleaseLimitReached","handleReleaseLimitError","action","dryRun","catch","error","details","limit","handleCreateRelease","releases","create","_id","metadata","handleUpdateRelease","unsetKeys","Object","entries","filter","_","value","undefined","map","key","edit","patch","set","unset","handlePublishRelease","publish","handleDiscardDrafts","draftIds","Set","length","existingDraftIds","fetch","perspective","tag","discardDraftActions","draftId","actionType","versionId","handleScheduleRelease","publishAt","toISOString","handleUnscheduleRelease","handleArchiveRelease","handleUnarchiveRelease","handleDeleteRelease","delete","handleCreateVersion","document","getDocument","Error","baseId","ifBaseRevisionId","_rev","publishedId","handleDiscardVersion","handleUnpublishVersion","handleRevertRelease","title","description","releaseType","cardinality","newVersionDocumentActions","releaseDocument","handleDuplicateRelease","duplicateVersionDocumentActions","handleRevertUnpublishVersion","useMemo","useClient","useReleasesUpsell","RELEASES_STUDIO_CLIENT_OPTIONS","createReleaseOperationsStore","useReleaseOperations","$","_c","studioClient","onReleaseLimitReached","t0","client","ReleaseDocument","useMemo","useSyncObservable","sortReleases","useReleasesStore","useAllReleases","$","_c","state$","releases","error","state","t0","Array","from","values","t1","Symbol","for","t2","includes","t3","data","map","loading","schedulerYield","promise","Promise","Result","window","scheduler","yield","CurrentUser","isValidationErrorMarker","SanityDocument","Schema","uuid","useMemo","useObservable","combineLatest","from","Observable","of","mergeMapArray","catchError","delay","filter","finalize","map","shareReplay","switchMap","useSchema","LocaleSource","DocumentPreviewStore","useDocumentPreviewStore","useSource","schedulerYield","validateDocumentWithReferences","ValidationStatus","RELEASES_STUDIO_CLIENT_OPTIONS","bundleDocumentsCache","Record","BundleDocumentsObservableResult","Object","create","resetBundleDocumentsCacheForTests","key","keys","DocumentValidationStatus","hasError","BundleDocument","memoKey","isPending","document","publishedDocumentExists","draftDocumentExists","validation","loading","results","error","Error","BundleDocumentsObservableOptions","schema","documentPreviewStore","i18n","getClient","ReturnType","currentUser","Omit","groqFilter","params","skipValidation","buildBundleDocumentsObservable","createValidationObservable","ctx","isValidating","revision","_rev","Promise","resolve","pipe","validationStatus","some","marker","processDocument","id","observeDocument","unstable_observeDocument","observeDocumentPairAvailability","unstable_observeDocumentPairAvailability","document$","apiVersion","Boolean","doc","availability","published","available","draft","validation$","processDocumentIdsGroup","documentIdsGroup","groupIndex","batchDelay","unstable_observeDocumentIdSet","state","documentIds","length","batchSize","documentIdsGroups","i","push","slice","batch","batchIndex","groupResults","flat","getBundleDocumentsObservable","cacheKey","options","BUNDLE_DOCUMENTS_EMPTY","BUNDLE_DOCUMENTS_LOADING","useBundleDocuments","$","_c","enabled","t0","undefined","t1","bundleDocumentsObservable"],"sources":["../src/core/releases/store/types.ts","../src/core/util/releaseUtils.ts","../src/core/releases/util/const.ts","../src/core/util/formatRelativeLocale.ts","../src/core/releases/util/createReleaseId.ts","../src/core/releases/util/util.ts","../src/core/releases/util/getReleaseTone.ts","../src/core/releases/hooks/utils.ts","../src/core/releases/store/createReleaseMetadataAggregator.ts","../src/core/releases/store/reducer.ts","../src/core/releases/store/createReleaseStore.ts","../src/core/releases/store/useReleasesStore.ts","../src/core/releases/store/useActiveReleases.ts","../src/core/components/previews/constants.ts","../src/core/components/previews/_common/Media.styled.ts","../src/core/components/previews/_common/Media.tsx","../src/core/components/previews/helpers.tsx","../src/core/components/previews/general/CompactPreview.tsx","../src/core/components/progress/LinearProgress.tsx","../src/core/components/previews/general/DefaultPreview.tsx","../src/core/components/previews/general/DetailPreview.styled.ts","../src/core/components/previews/general/DetailPreview.tsx","../src/core/components/progress/CircularProgress.tsx","../src/core/components/previews/general/MediaPreview.styled.ts","../src/core/components/previews/general/MediaPreview.tsx","../src/core/components/previews/portableText/BlockImagePreview.styled.tsx","../src/core/components/previews/portableText/BlockImagePreview.tsx","../src/core/components/previews/portableText/BlockPreview.tsx","../src/core/components/previews/portableText/InlinePreview.styled.tsx","../src/core/components/previews/portableText/InlinePreview.tsx","../src/core/config/definePlugin.ts","../src/core/deprecatedPlugins/DeprecatedScheduledPublishing.tsx","../src/core/config/flattenConfig.ts","../src/core/config/components/useMiddlewareComponents.tsx","../src/core/util/isString.ts","../src/core/util/createMediaLibraryClient.ts","../src/core/store/accessPolicy/refs.ts","../src/core/store/accessPolicy/fetch.ts","../src/core/form/inputs/files/ImageInput/useAccessPolicy.ts","../src/core/form/studio/assetSourceMediaLibrary/constants.ts","../src/core/form/studio/assetSourceMediaLibrary/hooks/useToken.ts","../src/core/form/inputs/files/ImageInput/useImageObjectUrl.ts","../src/core/form/inputs/files/ImageInput/useImageUrl.ts","../src/core/preview/components/_previewComponents.ts","../src/core/preview/components/SanityDefaultPreview.tsx","../src/core/form/studio/inputResolver/previewResolver.ts","../src/core/form/form-components-hooks/picks.ts","../src/core/form/form-components-hooks/useResolveDefaultComponent.tsx","../src/core/form/form-components-hooks/usePreviewComponent.tsx","../src/core/perspective/usePerspective.ts","../src/core/releases/util/isGoingToUnpublish.ts","../src/core/preview/useValuePreview.ts","../src/core/preview/streams/orientationChange.ts","../src/core/preview/streams/resize.ts","../src/core/preview/streams/scroll.ts","../src/core/preview/streams/intersectionObservableFor.ts","../src/core/preview/streams/visibilityChange.ts","../src/core/preview/useVisibility.ts","../src/core/preview/components/_constants.ts","../src/core/preview/components/_extractUploadState.ts","../src/core/preview/components/PreviewLoader.tsx","../src/core/preview/components/Preview.tsx","../src/core/hooks/useDataset.ts","../src/core/releases/hooks/useDocumentVersions.tsx","../src/core/studio/activeWorkspaceMatcher/useActiveWorkspace.ts","../src/core/hooks/useRecordDocumentHistoryEvent.ts","../src/core/hooks/useDocumentOperationWithComlinkHistory.ts","../src/core/hooks/useMemoizedDocumentPairTarget.ts","../src/core/hooks/useDocumentOperation.ts","../src/core/util/getTargetDocument.ts","../src/core/variants/store/reducer.ts","../src/core/variants/store/createVariantsStore.ts","../src/core/variants/store/useVariantsStore.ts","../src/core/variants/store/useAllVariants.ts","../src/core/hooks/useTargetDocumentState.ts","../src/core/store/grants/documentPairPermissions.ts","../src/core/releases/util/getReleaseDocumentIdFromReleaseId.ts","../src/core/releases/contexts/upsell/useReleasesUpsell.ts","../src/core/error/types/isErrorWithDetails.ts","../src/core/releases/store/isReleaseLimitError.ts","../src/core/releases/store/createReleaseOperationStore.ts","../src/core/releases/store/useReleaseOperations.ts","../src/core/releases/store/useAllReleases.ts","../src/core/util/schedulerYield.ts","../src/core/releases/tool/detail/useBundleDocuments.ts"],"sourcesContent":["import {type ReleaseDocument, type ReleaseType} from '@sanity/client'\nimport {type DocumentSystem} from '@sanity/types'\nimport {type Dispatch} from 'react'\nimport {type Observable} from 'rxjs'\n\nimport {RELEASE_DOCUMENT_TYPE} from './constants'\nimport {type MetadataWrapper} from './createReleaseMetadataAggregator'\nimport {type ReleasesReducerAction, type ReleasesReducerState} from './reducer'\n\n/**\n * @beta\n */\nexport const releaseTypes = ['asap', 'scheduled', 'undecided'] as const\n\n/**\n * @beta\n */\nexport function isReleaseType(maybeReleaseType: unknown): maybeReleaseType is ReleaseType {\n return (\n typeof maybeReleaseType === 'string' && releaseTypes.includes(maybeReleaseType as ReleaseType)\n )\n}\n\n/**\n * @internal\n */\nexport function isReleaseDocument(doc: unknown): doc is ReleaseDocument {\n return (\n typeof doc === 'object' && doc !== null && '_type' in doc && doc._type === RELEASE_DOCUMENT_TYPE\n )\n}\n\n/**\n * @internal\n */\nexport interface ReleaseStore {\n state$: Observable<ReleasesReducerState>\n /**\n * Counts all loaded release documents that are in an active state and have an error recorded.\n * This is determined by the presence of the `error` field in the release document.\n */\n errorCount$: Observable<number>\n getMetadataStateForSlugs$: (slugs: string[]) => Observable<MetadataWrapper>\n dispatch: Dispatch<ReleasesReducerAction>\n}\n\n/**\n * @internal\n */\nexport interface VersionInfoDocumentStub {\n _id: string\n _rev: string\n _createdAt: string\n _updatedAt: string\n _system: DocumentSystem\n}\n","import {type ReleaseDocument} from '@sanity/client'\n\nimport {isReleaseDocument} from '../releases/store/types'\n\n/**\n * A release document with cardinality 'one'\n *\n * @internal\n */\nexport type CardinalityOneRelease = ReleaseDocument & {\n metadata: ReleaseDocument['metadata'] & {\n cardinality: 'one'\n }\n}\n\n/**\n * Check if the release is a cardinality one release\n *\n * @internal\n */\nexport function isCardinalityOneRelease(\n release: ReleaseDocument,\n): release is CardinalityOneRelease {\n return release.metadata?.cardinality === 'one'\n}\n\n/**\n * Check if perspective represents a cardinality one release\n *\n * @internal\n */\nexport function isCardinalityOnePerspective(\n perspective: unknown,\n): perspective is CardinalityOneRelease {\n return isReleaseDocument(perspective) && isCardinalityOneRelease(perspective)\n}\n\n/**\n * Checks if a release is a paused cardinality one release (scheduled draft).\n *\n * @internal\n */\nexport function isPausedCardinalityOneRelease(release: ReleaseDocument | undefined): boolean {\n if (!release) return false\n return (\n release.state === 'active' &&\n release.metadata.releaseType === 'scheduled' &&\n isCardinalityOneRelease(release) &&\n Boolean(release.metadata.intendedPublishAt)\n )\n}\n","import {type ReleaseType} from '@sanity/client'\nimport {type BadgeTone} from '@sanity/ui'\n\n/**\n * @internal\n */\nexport const LATEST = 'drafts' as const\n\n/**\n * @internal\n */\nexport const PUBLISHED = 'published' as const\n\n/**\n * @internal\n */\nexport const DEFAULT_RELEASE_TYPE = 'asap'\n\n/**\n * @internal\n */\nexport const ARCHIVED_RELEASE_STATES = ['archived', 'published']\n\n/**\n * @internal\n */\nexport const RELEASE_TYPES_TONES: Record<ReleaseType, {tone: BadgeTone}> = {\n asap: {\n tone: 'caution',\n },\n scheduled: {\n tone: 'suggest',\n },\n undecided: {\n tone: 'neutral',\n },\n}\n","import {tz as tzHelper} from '@date-fns/tz'\nimport {formatRelative} from 'date-fns/formatRelative'\nimport {isValid} from 'date-fns/isValid'\nimport {parse} from 'date-fns/parse'\n\ntype DateInput = Date | number | string\n\nconst RUNTIME_TIME_ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone\n\n/**\n * Renders `date` relative to `baseDate` in `timeZone`. Replaces date-fns's en-US\n * `MM/dd/yyyy` fallback (used for dates more than ~6 days out) with the browser's\n * locale date format, so non-en-US users don't see American-style dates.\n *\n * `timeZone` defaults to the host runtime's TZ. Pass an explicit IANA zone for\n * non-browser contexts or to render in the user's selected studio timezone (e.g.\n * via a hook that wraps `useTimeZone`).\n *\n * @internal\n */\nexport const formatRelativeLocale = (\n date: DateInput,\n baseDate: DateInput,\n timeZone: string = RUNTIME_TIME_ZONE,\n): string => {\n const relative = formatRelative(date, baseDate, {in: tzHelper(timeZone)})\n // Detect date-fns's en-US `MM/dd/yyyy` fallback and swap in a browser-locale string.\n if (isValid(parse(relative, 'MM/dd/yyyy', new Date()))) {\n return new Date(date).toLocaleDateString(undefined, {timeZone})\n }\n return relative\n}\n","import {customAlphabet} from 'nanoid'\n\nimport {RELEASE_DOCUMENTS_PATH} from '../store/constants'\n\n/**\n * ~24 years (or 7.54e+8 seconds) needed, in order to have a 1% probability of at least one collision if 10 ID's are generated every hour.\n */\nconst createBundleId = customAlphabet(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',\n 8,\n)\n\n/**\n * Create a unique release id. This is used as the release id for documents included in the release.\n * @internal\n */\nexport function createReleaseId() {\n return `${RELEASE_DOCUMENTS_PATH}.r${createBundleId()}`\n}\n","import {type EditableReleaseDocument, type ReleaseDocument, type ReleaseState} from '@sanity/client'\nimport {type DocumentSystem} from '@sanity/types'\n\nimport {type TargetPerspective} from '../../perspective/types'\nimport {getVersionFromId, isVersionId} from '../../util/draftUtils'\nimport {formatRelativeLocale} from '../../util/formatRelativeLocale'\nimport {isCardinalityOneRelease, isPausedCardinalityOneRelease} from '../../util/releaseUtils'\nimport {type CardinalityView, type Mode} from '../tool/overview/queryParamUtils'\nimport {DEFAULT_RELEASE_TYPE, LATEST} from './const'\nimport {createReleaseId} from './createReleaseId'\nimport {getReleaseIdFromReleaseDocumentId} from './getReleaseIdFromReleaseDocumentId'\n\n/** @internal */\nexport type NotArchivedRelease = ReleaseDocument & {state: Exclude<ReleaseState, 'archived'>}\n\n/**\n * @beta\n * @param documentId - The document id, e.g. `my-document-id` or `drafts.my-document-id` or `summer.my-document-id`\n * @param perspective - The current perspective, e.g. `release.summer` or undefined, it can be obtained from `useRouter().stickyParams.perspective`\n * @returns boolean - `true` if the document is in the current perspective.\n * e.g:\n * - document: `summer.my-document-id`, perspective: `release.summer` : **true**\n * - document: `my-document-id`, perspective: `release.summer` : **false**\n * - document: `summer.my-document-id`perspective: `release.winter` : **false**\n * - document: `summer.my-document-id`, perspective: `undefined` : **false**\n * - document: `my-document-id`, perspective: `undefined` : **true**\n * - document: `drafts.my-document-id`, perspective: `undefined` : **true**\n */\nexport function getDocumentIsInPerspective(\n documentId: string,\n perspective: string | undefined,\n): boolean {\n const releaseId = getVersionFromId(documentId)\n\n if (!perspective) return !isVersionId(documentId)\n\n if (typeof perspective === 'undefined') return false\n // perspective is `release.${releaseId}`\n\n if (releaseId === 'Published') return false\n return releaseId === perspective\n}\n\n/** @internal */\nexport function getPublishDateFromRelease(release: ReleaseDocument): Date | null {\n const dateString = release.publishedAt || release.publishAt || release.metadata.intendedPublishAt\n\n if (!dateString) return null\n\n return new Date(dateString)\n}\n\n/**\n * Formats a release's publish date as a locale-aware relative string. `timeZone`\n * defaults to the host runtime's TZ; inside React components, prefer\n * `useFormatRelativeLocalePublishDate` to bind the studio's selected timezone.\n *\n * @internal\n */\nexport function formatRelativeLocalePublishDate(\n release: ReleaseDocument,\n timeZone?: string,\n): string {\n const publishDate = getPublishDateFromRelease(release)\n\n if (!publishDate) return ''\n return formatRelativeLocale(publishDate, new Date(), timeZone)\n}\n\n/** @internal */\nexport function isPublishedPerspective(\n perspective: TargetPerspective | string,\n): perspective is 'published' {\n return perspective === 'published'\n}\n\n/** @internal */\nexport function isDraftPerspective(\n perspective: TargetPerspective | string,\n): perspective is 'drafts' {\n return perspective === LATEST\n}\n\n/** @internal */\nexport function isReleaseScheduledOrScheduling(release: ReleaseDocument): boolean {\n return (\n release.metadata.releaseType === 'scheduled' &&\n (release.state === 'scheduled' || release.state === 'scheduling')\n )\n}\n\n/** @internal */\nexport const getReleaseDefaults: () => EditableReleaseDocument = () => ({\n _id: createReleaseId(),\n metadata: {\n title: '',\n description: '',\n releaseType: DEFAULT_RELEASE_TYPE,\n cardinality: 'many',\n },\n})\n\n/**\n * Check if the release is archived\n *\n * @internal */\nexport function isNotArchivedRelease(release: ReleaseDocument): release is NotArchivedRelease {\n return release.state !== 'archived'\n}\n\n/**\n * @internal\n */\nexport function shouldShowReleaseInView(\n cardinalityView: CardinalityView,\n): (release: ReleaseDocument) => boolean {\n return (release: ReleaseDocument): boolean => {\n const isCardinalityOne = isCardinalityOneRelease(release)\n // Show cardinality 'one' releases in 'drafts' view, and cardinality 'many'/undefined in 'releases' view\n return cardinalityView === 'drafts' ? isCardinalityOne : !isCardinalityOne\n }\n}\n\n/** @internal */\nexport interface FilterReleasesOptions<T extends ReleaseDocument> {\n releases: T[]\n archivedReleases: T[]\n cardinalityView: CardinalityView\n releaseGroupMode: Mode\n dateFilter?: {\n filterDate: Date\n getTimezoneAdjustedDateTimeRange: (date: Date) => [Date, Date]\n }\n}\n\n/** @internal */\nexport function filterReleasesForOverview<T extends ReleaseDocument>(\n options: FilterReleasesOptions<T>,\n): T[] {\n const {releases, archivedReleases, cardinalityView, releaseGroupMode, dateFilter} = options\n\n const sourceReleases = releaseGroupMode === 'archived' ? archivedReleases : releases\n\n const applyDateFilter = (items: T[]): T[] => {\n if (!dateFilter) return items\n\n const [startOfDayForTimeZone, endOfDayForTimeZone] =\n dateFilter.getTimezoneAdjustedDateTimeRange(dateFilter.filterDate)\n\n return items.filter((release) => {\n const publishAt = release.publishAt || release.metadata.intendedPublishAt\n if (!publishAt || release.metadata.releaseType !== 'scheduled') return false\n\n const publishDateUTC = new Date(publishAt)\n return publishDateUTC >= startOfDayForTimeZone && publishDateUTC <= endOfDayForTimeZone\n })\n }\n\n const dateFiltered = applyDateFilter(sourceReleases)\n\n if (cardinalityView !== 'drafts') return dateFiltered\n\n if (releaseGroupMode === 'active') {\n return dateFiltered.filter(\n (release) => release.state === 'scheduled' || release.state === 'scheduling',\n )\n }\n\n if (releaseGroupMode === 'paused') {\n return dateFiltered.filter((release) => isPausedCardinalityOneRelease(release))\n }\n\n return dateFiltered\n}\n","import {type BadgeTone} from '@sanity/ui'\n\nimport {type TargetPerspective} from '../../perspective/types'\nimport {isAgentBundleName} from '../../store/agent/createAgentBundlesStore'\nimport {isPausedCardinalityOneRelease} from '../../util/releaseUtils'\nimport {isReleaseDocument} from '../store/types'\nimport {RELEASE_TYPES_TONES} from './const'\nimport {isDraftPerspective, isPublishedPerspective} from './util'\n\n/** @internal */\nexport function getReleaseTone(release: TargetPerspective): BadgeTone {\n if (isPublishedPerspective(release)) return 'positive'\n if (isDraftPerspective(release)) return 'default'\n\n if (isReleaseDocument(release)) {\n if (release.state === 'archived') {\n return 'default'\n }\n\n if (release?.metadata?.releaseType === 'asap') {\n return RELEASE_TYPES_TONES.asap.tone\n }\n\n if (release?.metadata?.releaseType === 'undecided') {\n return RELEASE_TYPES_TONES.undecided.tone\n }\n\n if (isPausedCardinalityOneRelease(release)) {\n return 'caution'\n }\n\n if (release?.metadata?.releaseType === 'scheduled') {\n return RELEASE_TYPES_TONES.scheduled.tone\n }\n }\n\n if (isAgentBundleName(release)) return 'suggest'\n\n return 'default'\n}\n","import {type ClientPerspective, type ReleaseDocument} from '@sanity/client'\n\nimport {type PerspectiveStack, type ReleaseId} from '../../perspective/types'\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\n\n/**\n * Sorts releases by their release type and created date.\n * @internal\n */\nexport function sortReleases(releases: ReleaseDocument[] = []): ReleaseDocument[] {\n // The order should always be:\n // [undecided (sortByCreatedAt), scheduled(sortBy publishAt || metadata.intendedPublishAt), asap(sortByCreatedAt)]\n return [...releases].sort((a, b) => {\n // undecided are always first, then by createdAt descending\n if (a.metadata.releaseType === 'undecided' && b.metadata.releaseType !== 'undecided') {\n return -1\n }\n if (a.metadata.releaseType !== 'undecided' && b.metadata.releaseType === 'undecided') {\n return 1\n }\n if (a.metadata.releaseType === 'undecided' && b.metadata.releaseType === 'undecided') {\n // Sort by createdAt\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n\n // Scheduled are always at the middle, then by publishAt descending\n if (a.metadata.releaseType === 'scheduled' && b.metadata.releaseType === 'scheduled') {\n const aPublishAt = a.publishAt || a.metadata.intendedPublishAt\n if (!aPublishAt) {\n return 1\n }\n const bPublishAt = b.publishAt || b.metadata.intendedPublishAt\n if (!bPublishAt) {\n return -1\n }\n return new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime()\n }\n\n // ASAP are always last, then by createdAt descending\n if (a.metadata.releaseType === 'asap' && b.metadata.releaseType !== 'asap') {\n return 1\n }\n if (a.metadata.releaseType !== 'asap' && b.metadata.releaseType === 'asap') {\n return -1\n }\n if (a.metadata.releaseType === 'asap' && b.metadata.releaseType === 'asap') {\n // Sort by createdAt\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n\n return 0\n })\n}\nconst DRAFTS: ['drafts'] = ['drafts']\nconst PUBLISHED: ['published'] = ['published']\nconst EMPTY: [] = []\n\nexport function getReleasesPerspectiveStack({\n selectedPerspectiveName,\n releases,\n excludedPerspectives,\n isDraftModelEnabled,\n}: {\n selectedPerspectiveName: ReleaseId | undefined | 'published'\n releases: ReleaseDocument[]\n excludedPerspectives: string[]\n isDraftModelEnabled: boolean\n}): PerspectiveStack {\n const defaultPerspective = isDraftModelEnabled ? DRAFTS : PUBLISHED\n if (!selectedPerspectiveName) {\n return defaultPerspective\n }\n if (selectedPerspectiveName === 'published') {\n return PUBLISHED\n }\n\n const sorted: ClientPerspective = sortReleases(releases).map((release) =>\n getReleaseIdFromReleaseDocumentId(release._id),\n )\n const selectedIndex = sorted.indexOf(selectedPerspectiveName)\n if (selectedIndex === -1) {\n // we're in a non-release stack\n return [selectedPerspectiveName, ...defaultPerspective]\n }\n return sorted\n .slice(selectedIndex)\n .concat(defaultPerspective)\n .filter((name) => !excludedPerspectives.includes(name))\n}\n","import {type SanityClient} from '@sanity/client'\nimport {\n bufferTime,\n catchError,\n EMPTY,\n filter,\n iif,\n merge,\n type Observable,\n of,\n startWith,\n switchMap,\n} from 'rxjs'\n\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\nimport {type ReleasesMetadata} from './useReleasesMetadata'\n\nexport type ReleasesMetadataMap = Record<string, ReleasesMetadata>\n\nexport type MetadataWrapper = {data: ReleasesMetadataMap | null; error: null; loading: boolean}\n\nconst getFetchQuery = (releaseIds: string[]) => {\n // projection key must be string - cover the case that a bundle has a number as first char\n const getSafeKey = (id: string) => `release_${id.replaceAll('-', '_')}`\n\n return releaseIds.reduce(\n ({subquery: accSubquery, projection: accProjection}, releaseId) => {\n const bundleId = getReleaseIdFromReleaseDocumentId(releaseId)\n // get a version of the id that is safe to use as key in objects\n const safeId = getSafeKey(bundleId)\n\n const subquery = `${accSubquery}\"${safeId}\": *[sanity::partOfRelease(\"${bundleId}\")]{_updatedAt, \"docId\": string::split(_id, \".\")[2] } | order(_updatedAt desc),`\n\n const projection = `${accProjection}\"${releaseId}\": {\n \"updatedAt\": ${safeId}[0]._updatedAt,\n \"documentIds\": ${safeId}[].docId,\n },`\n\n return {subquery, projection}\n },\n {subquery: '', projection: ''},\n )\n}\n\n/**\n * @internal\n *\n * An initial fetch is made. This fetch is polled whenever a listener even is emitted\n * Only releases that have been mutated are re-fetched\n *\n * @returns an Observable that accepts a list of release slugs and returns a stream of metadata\n */\nexport const createReleaseMetadataAggregator = (client: SanityClient | null) => {\n const aggregatorFetch$ = (\n releaseIds: string[],\n isInitialLoad: boolean = false,\n ): Observable<MetadataWrapper> => {\n if (!releaseIds?.length || !client) return of({data: null, error: null, loading: false})\n\n const {subquery: queryAllDocumentsInReleases, projection: projectionToBundleMetadata} =\n getFetchQuery(releaseIds)\n\n const fetchData$ = client.observable\n .fetch<\n Record<\n string,\n Omit<ReleasesMetadata, 'existingDocumentCount'> & {\n documentIds: string[]\n }\n >\n >(\n `{${queryAllDocumentsInReleases}}{${projectionToBundleMetadata}}`,\n {},\n {tag: 'release-docs.fetch'},\n )\n .pipe(\n switchMap((releaseDocumentIdResponse) =>\n of({\n data: Object.entries(releaseDocumentIdResponse).reduce((existing, el) => {\n const [releaseId, metadata] = el\n return {\n ...existing,\n [releaseId]: {...metadata, documentCount: metadata.documentIds?.length || 0},\n }\n }, {}),\n error: null,\n loading: false,\n }),\n ),\n catchError((error) => {\n console.error('Failed to fetch release metadata', error)\n return of({data: null, error, loading: false})\n }),\n )\n\n // initially emit loading empty state if first fetch\n return iif(\n () => isInitialLoad,\n fetchData$.pipe(startWith({loading: true, data: null, error: null})),\n fetchData$,\n )\n }\n\n const aggregatorListener$ = (releaseIds: string[]) => {\n if (!releaseIds?.length || !client) return EMPTY\n\n return client.observable\n .listen(\n `*[(${releaseIds.reduce(\n (accQuery, releaseId, index) =>\n `${accQuery}${index === 0 ? '' : ' ||'} sanity::partOfRelease(\"${releaseId}\")`,\n '',\n )})]`,\n {},\n {\n includeResult: true,\n includeAllVersions: true,\n visibility: 'query',\n events: ['mutation'],\n tag: 'release-docs.listen',\n },\n )\n .pipe(\n catchError((error) => {\n console.error('Failed to listen for release metadata', error)\n return EMPTY\n }),\n bufferTime(1_000),\n filter((entriesArray) => entriesArray.length > 0),\n switchMap((entriesArray) => {\n const mutatedReleaseIds = entriesArray.reduce<string[]>((accReleaseIds, event) => {\n if ('type' in event && event.type === 'mutation') {\n const releaseId = event.documentId.split('.')[1]\n // de-dup mutated bundle slugs\n if (accReleaseIds.includes(releaseId)) return accReleaseIds\n\n return [...accReleaseIds, releaseId]\n }\n return accReleaseIds\n }, [])\n\n if (mutatedReleaseIds.length) {\n return aggregatorFetch$(mutatedReleaseIds)\n }\n\n return EMPTY\n }),\n )\n }\n\n return (releaseIds: string[]) =>\n merge(aggregatorFetch$(releaseIds, true), aggregatorListener$(releaseIds))\n}\n","import {type ReleaseDocument} from '@sanity/client'\n\ninterface BundleDeletedAction {\n id: string\n currentUserId?: string\n deletedByUserId: string\n type: 'BUNDLE_DELETED'\n}\n\ninterface ReleasesSetAction {\n payload: ReleaseDocument[] | null\n type: 'RELEASES_SET'\n}\n\ninterface LoadingStateChangedAction {\n payload: {\n loading: boolean\n error: Error | undefined\n }\n type: 'LOADING_STATE_CHANGED'\n}\n\nexport type ReleasesReducerAction =\n | BundleDeletedAction\n | ReleasesSetAction\n | LoadingStateChangedAction\n\nexport interface ReleasesReducerState {\n releases: Map<string, ReleaseDocument>\n state: 'initialising' | 'loading' | 'loaded' | 'error'\n error?: Error\n}\n\nfunction createReleasesSet(releases: ReleaseDocument[] | null) {\n return (releases ?? []).reduce((acc, bundle) => {\n acc.set(bundle._id, bundle)\n return acc\n }, new Map<string, ReleaseDocument>())\n}\n\nexport function releasesReducer(\n state: ReleasesReducerState,\n action: ReleasesReducerAction,\n): ReleasesReducerState {\n switch (action.type) {\n case 'LOADING_STATE_CHANGED': {\n return {\n ...state,\n state: action.payload.loading ? 'loading' : 'loaded',\n error: action.payload.error,\n }\n }\n\n case 'RELEASES_SET': {\n // Create an object with the BUNDLE id as key\n const releasesById = createReleasesSet(action.payload)\n\n return {\n ...state,\n releases: releasesById,\n }\n }\n\n default:\n return state\n }\n}\n","import {type ReleaseDocument, type ReleaseType, type SanityClient} from '@sanity/client'\nimport {\n BehaviorSubject,\n catchError,\n concat,\n concatWith,\n count,\n filter,\n from,\n merge,\n type Observable,\n of,\n type OperatorFunction,\n pipe,\n scan,\n shareReplay,\n Subject,\n switchMap,\n tap,\n} from 'rxjs'\nimport {distinctUntilChanged, map, startWith} from 'rxjs/operators'\n\nimport {type DocumentPreviewStore} from '../../preview/documentPreviewStore'\nimport {listenQuery} from '../../store/document/listenQuery'\nimport {RELEASE_DOCUMENT_TYPE, RELEASE_DOCUMENTS_PATH} from './constants'\nimport {createReleaseMetadataAggregator} from './createReleaseMetadataAggregator'\nimport {releasesReducer, type ReleasesReducerAction, type ReleasesReducerState} from './reducer'\nimport {type ReleaseStore} from './types'\n\ntype ActionWrapper = {action: ReleasesReducerAction}\ntype ResponseWrapper = {response: ReleaseDocument[]}\n\nconst SORT_FIELD = '_createdAt'\nconst SORT_ORDER = 'desc'\n\nconst QUERY_FILTER = `_type==\"${RELEASE_DOCUMENT_TYPE}\" && _id in path(\"${RELEASE_DOCUMENTS_PATH}.*\")`\n\nconst DEFAULT_RELEASE_TYPE: ReleaseType = 'undecided'\nconst QUERY_PROJECTION = `{\n _id,\n _type,\n _rev,\n _createdAt,\n _updatedAt,\n state,\n finalDocumentStates,\n publishAt,\n publishedAt,\n \"metadata\": coalesce(metadata, {\n \"title\": \"\",\n \"releaseType\": \"${DEFAULT_RELEASE_TYPE}\",\n }),\n // Content Lake initially encoded non-error states as {error: {message: \"\"}}. This projection\n // ensures the error field only appears if the document has a non-empty error message.\n ...select(\n length(error.message) > 0 => { error },\n {}\n ),\n}`\n\n// Newest releases first\nconst QUERY_SORT_ORDER = `order(${SORT_FIELD} ${SORT_ORDER})`\n\nconst QUERY = `*[${QUERY_FILTER}] ${QUERY_PROJECTION} | ${QUERY_SORT_ORDER}`\n\nconst INITIAL_STATE: ReleasesReducerState = {\n releases: new Map(),\n state: 'initialising' as const,\n}\n\n/**\n * The releases store is initialised lazily when first subscribed to. Upon subscription, it will\n * fetch a list of releases and create a listener to keep the locally held state fresh.\n *\n * The store is not disposed of when all subscriptions are closed. After it has been initialised,\n * it will keep listening for the duration of the app's lifecycle. Subsequent subscriptions will be\n * given the latest state upon subscription.\n */\nexport function createReleaseStore(context: {\n previewStore: DocumentPreviewStore\n client: SanityClient\n}): ReleaseStore {\n const {client} = context\n\n const dispatch$ = new Subject<ReleasesReducerAction>()\n const fetchPending$ = new BehaviorSubject<boolean>(false)\n\n function dispatch(action: ReleasesReducerAction): void {\n dispatch$.next(action)\n }\n\n const listFetch$ = of<ActionWrapper>({\n action: {\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: true,\n error: undefined,\n },\n },\n }).pipe(\n // Ignore invocations while the list fetch is pending.\n filter(() => !fetchPending$.value),\n tap(() => fetchPending$.next(true)),\n concatWith(\n listenQuery(client, QUERY, {}, {tag: 'releases.listen'}).pipe(\n tap(() => fetchPending$.next(false)),\n map((releases) => ({response: releases})),\n ),\n ),\n\n catchError((error) =>\n of<ActionWrapper>({\n action: {\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: false,\n error,\n },\n },\n }),\n ),\n switchMap<ActionWrapper | ResponseWrapper, Observable<ReleasesReducerAction | undefined>>(\n (entry) => {\n if ('action' in entry) {\n return of<ReleasesReducerAction>(entry.action)\n }\n\n return of<ReleasesReducerAction[]>(\n {type: 'RELEASES_SET', payload: entry.response},\n {\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: false,\n error: undefined,\n },\n },\n )\n },\n ),\n )\n\n const state$ = concat(merge(listFetch$, dispatch$)).pipe(\n filter((action): action is ReleasesReducerAction => typeof action !== 'undefined'),\n scan((state, action) => releasesReducer(state, action), INITIAL_STATE),\n startWith(INITIAL_STATE),\n shareReplay(1),\n )\n\n const errorCount$ = state$.pipe(releaseStoreErrorCount(), shareReplay(1))\n\n const getMetadataStateForSlugs$ = createReleaseMetadataAggregator(client)\n\n return {\n state$,\n errorCount$,\n getMetadataStateForSlugs$,\n dispatch,\n }\n}\n\n/**\n * @internal\n */\nfunction releaseStoreErrorCount(): OperatorFunction<ReleasesReducerState, number> {\n return pipe(\n switchMap(({releases}) =>\n from(releases.values()).pipe(\n filter((release) => release.state === 'active'),\n filter((release) => typeof release.error !== 'undefined'),\n count(),\n ),\n ),\n distinctUntilChanged(),\n )\n}\n","import {useMemo} from 'react'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useDocumentPreviewStore} from '../../store/datastores'\nimport {useResourceCache} from '../../store/ResourceCacheProvider'\nimport {useWorkspace} from '../../studio/workspace'\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../util/releasesClient'\nimport {createReleaseStore} from './createReleaseStore'\nimport {type ReleaseStore} from './types'\n\n/** @internal */\nexport function useReleasesStore(): ReleaseStore {\n const resourceCache = useResourceCache()\n const workspace = useWorkspace()\n const previewStore = useDocumentPreviewStore()\n const studioClient = useClient(RELEASES_STUDIO_CLIENT_OPTIONS)\n\n return useMemo(() => {\n const releaseStore =\n resourceCache.get<ReleaseStore>({\n dependencies: [workspace, previewStore],\n namespace: 'ReleasesStore',\n }) ||\n createReleaseStore({\n client: studioClient,\n previewStore,\n })\n\n resourceCache.set({\n dependencies: [workspace, previewStore],\n namespace: 'ReleasesStore',\n value: releaseStore,\n })\n\n return releaseStore\n }, [resourceCache, workspace, studioClient, previewStore])\n}\n","import {type ReleaseDocument} from '@sanity/client'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {sortReleases} from '../hooks/utils'\nimport {ARCHIVED_RELEASE_STATES} from '../util/const'\nimport {type ReleasesReducerAction} from './reducer'\nimport {useReleasesStore} from './useReleasesStore'\n\ninterface ReleasesState {\n /**\n * Sorted array of releases, excluding archived releases\n */\n data: ReleaseDocument[]\n error?: Error\n loading: boolean\n dispatch: (event: ReleasesReducerAction) => void\n}\n\n/**\n * Hook to get the (non archived, non published) active releases\n * @internal\n */\nexport function useActiveReleases(): ReleasesState {\n const {state$, dispatch} = useReleasesStore()\n // Kept synchronous: PerspectiveProvider derives `selectedReleaseId` from\n // this list while `selectedPerspectiveName` stays live, so a deferred\n // snapshot could tear the release identity (e.g. reference create-in-place\n // writing `_weak` or opening the wrong version). Executable proof:\n // perspective/__tests__/deferralSafety.test.tsx.\n const state = useSyncObservable(state$)!\n const releasesAsArray = useMemo(\n () =>\n sortReleases(\n Array.from(state.releases.values()).filter(\n (release) => !ARCHIVED_RELEASE_STATES.includes(release.state),\n ),\n ).reverse(),\n [state.releases],\n )\n\n return useMemo(\n () => ({\n data: releasesAsArray,\n dispatch,\n error: state.error,\n loading: ['loading', 'initialising'].includes(state.state),\n }),\n [releasesAsArray, state.error, state.state, dispatch],\n )\n}\n","import {type PreviewLayoutKey} from './types'\n\nexport const PREVIEW_SIZES: Record<\n PreviewLayoutKey,\n {\n icon: number\n media: {height: number; width: number}\n }\n> = {\n block: {\n icon: 25,\n media: {width: 33, height: 33},\n },\n blockImage: {\n icon: 25,\n media: {width: 600, height: 400},\n },\n compact: {\n icon: 21,\n media: {width: 25, height: 25},\n },\n default: {\n icon: 21,\n media: {width: 33, height: 33},\n },\n detail: {\n icon: 25,\n media: {width: 73, height: 73},\n },\n inline: {\n icon: 15,\n media: {width: 15, height: 15},\n },\n media: {\n icon: 25,\n media: {width: 160, height: 160},\n },\n}\n","import {rem} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nimport {PREVIEW_SIZES} from '../constants'\nimport {type PreviewLayoutKey, type PreviewMediaDimensions} from '../types'\n\nexport const MediaWrapper = styled.span<{\n $dimensions: PreviewMediaDimensions\n $layout: PreviewLayoutKey\n $radius: number\n $responsive: boolean\n}>((props) => {\n const {$dimensions, $layout, $radius, $responsive} = props\n const width = $dimensions.width || 0\n const height = $dimensions.width || 0\n const iconSize = PREVIEW_SIZES[$layout].icon\n\n return css`\n position: relative;\n width: ${$responsive ? '100%' : rem(width)};\n height: ${$responsive ? '100%' : rem(height)};\n min-width: ${$responsive ? undefined : rem(width)};\n border-radius: ${({theme}) => rem(theme.sanity.radius[$radius]) /* oxlint-disable-line no-deprecated -- will fix in follow up PR */};\n display: flex;\n overflow: hidden;\n overflow: clip;\n align-items: center;\n justify-content: center;\n\n & img {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n object-fit: contain;\n border-radius: inherit;\n }\n\n & svg {\n // Shared styles for SVG icons\n color: var(--card-icon-color);\n display: block;\n flex: 1;\n\n // Specific styles for non Sanity icons\n &:not([data-sanity-icon]) {\n height: 1em;\n width: 1em;\n max-width: 1em;\n max-height: 1em;\n }\n\n // Specific styles for Sanity icons\n &[data-sanity-icon] {\n display: block;\n font-size: calc(${iconSize} / 16 * 1em);\n }\n }\n\n & > span[data-border] {\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n box-shadow: inset 0 0 0 1px var(--card-fg-color);\n opacity: 0.1;\n border-radius: inherit;\n pointer-events: none;\n }\n `\n})\n\nMediaWrapper.displayName = 'Styled(MediaWrapper)'\n","import {Text} from '@sanity/ui'\nimport {type ComponentType, isValidElement, type ReactNode} from 'react'\nimport {isValidElementType} from 'react-is'\n\nimport {type PreviewLayoutKey, type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {MediaWrapper} from './Media.styled'\n\nexport interface MediaProps {\n border?: boolean\n dimensions: PreviewMediaDimensions\n layout: PreviewLayoutKey\n media: PreviewProps['media']\n radius?: number\n responsive?: boolean\n styles?: {\n media?: string\n mediaString?: string\n }\n}\n\nexport function Media(props: MediaProps) {\n const {border = true, dimensions, layout, media, radius = 1, responsive = false, styles} = props\n\n return (\n <MediaWrapper\n $dimensions={dimensions}\n $layout={layout}\n $radius={radius}\n $responsive={responsive}\n className={styles?.media}\n data-testid=\"Media\"\n >\n {renderMedia({dimensions, layout, media})}\n {border && <span data-border />}\n </MediaWrapper>\n )\n}\n\nfunction renderMedia(props: {\n dimensions: PreviewMediaDimensions\n layout: PreviewLayoutKey\n media: PreviewProps['media']\n styles?: {\n media?: string\n mediaString?: string\n }\n}): ReactNode {\n const {dimensions, layout, media, styles} = props\n\n if (typeof media === 'string') {\n return (\n <Text as=\"span\" className={styles?.mediaString} size={1}>\n {media}\n </Text>\n )\n }\n\n if (isValidElementType(media)) {\n const MediaComponent = media as ComponentType<{\n dimensions: PreviewMediaDimensions\n layout: PreviewLayoutKey\n }>\n return <MediaComponent dimensions={dimensions} layout={layout} />\n }\n\n if (isValidElement(media)) {\n return media\n }\n\n return null\n}\n","import {tryGetImageDimensions} from '@sanity/asset-utils'\nimport {type ElementType, isValidElement, type ReactNode} from 'react'\nimport {isValidElementType} from 'react-is'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {PREVIEW_SIZES} from './constants'\nimport {type PreviewProps, type PreviewLayoutKey, type PreviewMediaDimensions} from './types'\n\nexport function renderPreviewMedia<Layout = PreviewLayoutKey>(\n value: PreviewProps<Layout>['media'],\n layout: Layout,\n dimensions: PreviewMediaDimensions,\n): ReactNode {\n if (isValidElementType(value)) {\n const Value = value\n return <Value layout={layout} dimensions={dimensions} />\n }\n\n if (typeof value === 'string') {\n return <div>{value}</div>\n }\n\n const isReactNode =\n isValidElement(value) ||\n value === null ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n\n if (isReactNode) {\n return value\n }\n\n return null\n}\n\nexport function renderPreviewNode<Layout = PreviewLayoutKey>(\n value: ReactNode | ElementType<{layout: Layout}>,\n layout: Layout,\n fallbackNode?: ReactNode,\n): ReactNode {\n if (typeof value === 'string') {\n return value\n }\n\n if (isValidElementType(value)) {\n const Value = value\n return <Value layout={layout} />\n }\n\n // @todo: find out why `value` isn't infered as `ReactNode` here\n return (value as any) || fallbackNode\n}\n\nexport function resolveBlockImageDimensions(\n source: Parameters<typeof tryGetImageDimensions>[0],\n): PreviewMediaDimensions | undefined {\n const sourceDimensions = tryGetImageDimensions(source)\n\n if (typeof sourceDimensions === 'undefined') {\n return undefined\n }\n\n const max = PREVIEW_SIZES.blockImage.media\n const scale = Math.min(max.width / sourceDimensions.width, 1)\n\n return {\n width: Math.round(sourceDimensions.width * scale),\n height: Math.round(sourceDimensions.height * scale),\n fit: 'max',\n dpr: getDevicePixelRatio(),\n }\n}\n","import {Box, Flex, rem, Skeleton, Stack, Text, TextSkeleton} from '@sanity/ui'\nimport {styled} from 'styled-components'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {useTranslation} from '../../../i18n/hooks/useTranslation'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\n\n/**\n * @hidden\n * @beta */\nexport type CompactPreviewProps = Omit<PreviewProps<'compact'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.compact.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\nconst Root = styled(Flex)`\n height: ${rem(PREVIEW_SIZES.compact.media.height)};\n box-sizing: content-box;\n`\n\nconst TitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(160)};\n width: 80%;\n`\n\n/**\n * @hidden\n * @beta */\nexport function CompactPreview(props: CompactPreviewProps) {\n const {children, isPlaceholder, media, status, title} = props\n\n const {t} = useTranslation()\n\n const statusNode = status && (\n <Box data-testid=\"compact-preview__status\" paddingLeft={4} paddingRight={1}>\n {renderPreviewNode(status, 'compact')}\n </Box>\n )\n\n if (isPlaceholder) {\n return (\n <Root\n align=\"center\"\n data-testid=\"default-preview\"\n paddingLeft={media ? 1 : 2}\n paddingRight={2}\n paddingY={1}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && <Skeleton animated radius={2} style={PREVIEW_SIZES.compact.media} />}\n\n <Stack data-testid=\"compact-preview__heading\" flex={1} gap={2}>\n <TitleSkeleton />\n </Stack>\n\n {statusNode}\n </Flex>\n </Root>\n )\n }\n\n return (\n <Root\n align=\"center\"\n data-testid=\"compact-preview\"\n paddingLeft={media ? 1 : 2}\n paddingRight={2}\n paddingY={1}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && (\n <Media\n border={false}\n dimensions={DEFAULT_MEDIA_DIMENSIONS}\n layout=\"compact\"\n media={media as any}\n />\n )}\n <Stack data-testid=\"compact-preview__header\" flex={1} gap={2}>\n <Text size={1} style={{color: 'inherit'}} textOverflow=\"ellipsis\" weight=\"medium\">\n {title && renderPreviewNode(title, 'compact')}\n {!title && (\n <span style={{color: 'var(--card-muted-fg-color)'}}>\n {t('preview.default.title-fallback')}\n </span>\n )}\n </Text>\n </Stack>\n\n {statusNode}\n </Flex>\n\n {children && <Box marginLeft={1}>{children}</Box>}\n </Root>\n )\n}\n","import {hues} from '@sanity/color'\nimport {Card, type Theme} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nconst STROKE_WIDTH = 0.5\n\nconst Root = styled(Card)`\n overflow: hidden;\n overflow: clip;\n`\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nconst Bar = styled(Card)(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {color} = theme.sanity\n\n return css`\n height: ${STROKE_WIDTH}rem;\n background: ${hues.blue[color.dark ? 400 : 500].hex};\n transition: transform 75ms;\n `\n})\n\n/**\n * @hidden\n * @beta */\nexport function LinearProgress(props: {\n /** Percentage */\n value: number\n}) {\n const {value} = props\n\n return (\n <Root radius={5}>\n <Bar radius={5} style={{transform: `translate3d(${value - 100}%, 0, 0)`}} />\n </Root>\n )\n}\n","import {Box, Flex, rem, Skeleton, Stack, Text, TextSkeleton} from '@sanity/ui'\nimport {clsx} from 'clsx'\nimport {styled} from 'styled-components'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {useTranslation} from '../../../i18n/hooks/useTranslation'\nimport {LinearProgress} from '../../progress/LinearProgress'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\n\n/**\n * @hidden\n * @beta */\nexport interface DefaultPreviewProps extends Omit<PreviewProps<'default'>, 'renderDefault'> {\n styles?: {\n root?: string\n placeholder?: string\n media?: string\n heading?: string\n title?: string\n subtitle?: string\n hasSubtitle?: string\n mediaString?: string\n status?: string\n children?: string\n }\n}\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.default.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\nconst Root = styled(Flex)`\n height: ${rem(PREVIEW_SIZES.default.media.height)};\n box-sizing: content-box;\n`\n\nconst TitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(160)};\n width: 80%;\n`\n\nconst SubtitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(120)};\n width: 60%;\n`\nconst SKELETON_DELAY = 300\n/**\n * @hidden\n * @beta */\nexport function DefaultPreview(props: DefaultPreviewProps) {\n const {title, subtitle, media, status, isPlaceholder, children, styles, progress} = props\n const {t} = useTranslation()\n const rootClassName = clsx(styles?.root, Boolean(subtitle) && styles?.hasSubtitle)\n const isUploading = typeof progress === 'number' && progress > -1\n\n const statusNode = status && (\n <Box className={styles?.status} data-testid=\"default-preview__status\">\n {renderPreviewNode(status, 'default')}\n </Box>\n )\n\n if (isPlaceholder) {\n return (\n <Root\n align=\"center\"\n className={styles?.placeholder}\n data-testid=\"default-preview\"\n padding={2}\n paddingLeft={media ? 2 : 3}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && (\n <Box flex=\"none\">\n <Skeleton\n animated\n delay={SKELETON_DELAY}\n radius={1}\n style={PREVIEW_SIZES.default.media}\n />\n </Box>\n )}\n\n <Stack data-testid=\"default-preview__heading\" flex={1} gap={2}>\n <TitleSkeleton delay={SKELETON_DELAY} />\n <SubtitleSkeleton delay={SKELETON_DELAY} />\n </Stack>\n\n <Box flex=\"none\" padding={1}>\n {statusNode}\n </Box>\n </Flex>\n </Root>\n )\n }\n\n return (\n <Root\n align=\"center\"\n className={rootClassName}\n data-testid=\"default-preview\"\n padding={2}\n paddingLeft={media ? 2 : 3}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && (\n <Box flex=\"none\">\n <Media\n dimensions={DEFAULT_MEDIA_DIMENSIONS}\n layout=\"default\"\n media={media as any}\n styles={styles}\n />\n </Box>\n )}\n\n <Stack className={styles?.heading} data-testid=\"default-preview__header\" flex={1} gap={2}>\n {isUploading && <LinearProgress value={progress} />}\n {!isUploading && (\n <>\n <Text\n className={styles?.title}\n size={1}\n style={{color: 'inherit'}}\n textOverflow=\"ellipsis\"\n weight=\"medium\"\n >\n {title && renderPreviewNode(title, 'default')}\n {!title && (\n <span style={{color: 'var(--card-muted-fg-color)'}}>\n {t('preview.default.title-fallback')}\n </span>\n )}\n </Text>\n\n {subtitle && (\n <Text muted size={1} textOverflow=\"ellipsis\" className={styles?.subtitle}>\n {renderPreviewNode(subtitle, 'default')}\n </Text>\n )}\n </>\n )}\n </Stack>\n\n <Box flex=\"none\" padding={1}>\n {statusNode}\n </Box>\n\n {children && <div className={styles?.children}>{children}</div>}\n </Flex>\n </Root>\n )\n}\n","import {Box, Flex, rem, Skeleton, Text, TextSkeleton} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nimport {PREVIEW_SIZES} from '../constants'\n\nexport const RootFlex = styled(Flex).attrs({align: 'center'})`\n height: ${rem(PREVIEW_SIZES.detail.media.height)};\n`\n\nexport const StatusBox = styled(Box)`\n white-space: nowrap;\n`\n\nexport const MediaSkeleton = styled(Skeleton).attrs({animated: true, radius: 2})`\n width: ${rem(PREVIEW_SIZES.detail.media.width)};\n height: ${rem(PREVIEW_SIZES.detail.media.height)};\n`\n\nexport const TitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(160)}; /* 80% of 200px */\n width: 80%;\n`\n\nexport const SubtitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(120)}; /* 60% of 200px */\n width: 60%;\n`\n\nexport const DescriptionSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(180)}; /* 90% of 200px */\n width: 90%;\n`\n\nexport const DescriptionText = styled(Text)(({theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {fonts} = theme.sanity\n const textSize1 = fonts.text.sizes[1]\n const maxLines = 2\n const maxHeight = textSize1.lineHeight * maxLines\n\n return css`\n & > span {\n max-height: ${rem(maxHeight)};\n\n /* Multi-line text overflow */\n display: -webkit-box;\n overflow: hidden;\n overflow: clip;\n text-overflow: ellipsis;\n -webkit-line-clamp: ${maxLines};\n -webkit-box-orient: vertical;\n }\n `\n})\n","import {Box, Flex, Stack, Text} from '@sanity/ui'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {useTranslation} from '../../../i18n/hooks/useTranslation'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {\n DescriptionSkeleton,\n DescriptionText,\n MediaSkeleton,\n RootFlex,\n StatusBox,\n SubtitleSkeleton,\n TitleSkeleton,\n} from './DetailPreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type DetailPreviewProps = PreviewProps<'detail'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.detail.media,\n fit: 'crop',\n aspect: 1,\n dpr: getDevicePixelRatio(),\n}\n\n/**\n * @hidden\n * @beta */\nexport function DetailPreview(props: DetailPreviewProps) {\n const {\n title,\n subtitle,\n description,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n media,\n status,\n children,\n isPlaceholder,\n } = props\n const {t} = useTranslation()\n\n const statusNode = status && (\n <StatusBox marginLeft={3} paddingRight={1}>\n {renderPreviewNode(status, 'detail')}\n </StatusBox>\n )\n\n if (isPlaceholder) {\n return (\n <RootFlex\n data-testid=\"detail-preview\"\n paddingLeft={media ? 2 : 3}\n paddingRight={2}\n paddingY={2}\n >\n <Flex align=\"center\" flex={1} gap={3}>\n {media && <MediaSkeleton data-testid=\"detail-preview__media\" />}\n\n <Flex align=\"center\" data-testid=\"detail-preview__header\" flex={1}>\n <Stack flex={1} gap={2}>\n <TitleSkeleton />\n <SubtitleSkeleton />\n {description && (\n <Box marginTop={1}>\n <DescriptionSkeleton />\n </Box>\n )}\n </Stack>\n </Flex>\n\n {statusNode}\n </Flex>\n </RootFlex>\n )\n }\n\n return (\n <RootFlex\n data-testid=\"detail-preview\"\n paddingLeft={media ? 2 : 3}\n paddingRight={2}\n paddingY={2}\n >\n <Flex align=\"center\" flex={1} gap={3}>\n {media && <Media dimensions={mediaDimensions} layout=\"detail\" media={media as any} />}\n\n <Flex align=\"center\" data-testid=\"detail-preview__header\" flex={1}>\n <Stack flex={1} gap={2}>\n <Text textOverflow=\"ellipsis\" size={1} style={{color: 'inherit'}} weight=\"medium\">\n {title && renderPreviewNode(title, 'detail')}\n {!title && <>{t('preview.default.title-fallback')}</>}\n </Text>\n\n {subtitle && (\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(subtitle, 'detail')}\n </Text>\n )}\n\n {description && (\n <Box marginTop={1}>\n <DescriptionText muted size={1}>\n {renderPreviewNode(description, 'detail')}\n </DescriptionText>\n </Box>\n )}\n </Stack>\n\n {statusNode}\n </Flex>\n\n {children}\n </Flex>\n </RootFlex>\n )\n}\n","import {hues} from '@sanity/color'\nimport {type Theme} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nconst SIZE = 43\nconst STROKE_WIDTH = 3\n\nconst Root = styled.svg`\n width: ${SIZE}px;\n height: ${SIZE}px;\n transform: rotate(-90deg);\n`\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nconst BgCircle = styled.circle(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {color} = theme.sanity\n\n return css`\n fill: none;\n stroke: ${hues.gray[color.dark ? 900 : 100].hex};\n stroke-width: ${STROKE_WIDTH}px;\n `\n})\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nconst ProgressCircle = styled.circle(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {color} = theme.sanity\n\n return css`\n fill: none;\n stroke: ${hues.blue[color.dark ? 400 : 500].hex};\n stroke-width: ${STROKE_WIDTH}px;\n transition: stroke-dashoffset 75ms;\n `\n})\n\n/**\n * @hidden\n * @beta */\nexport function CircularProgress(props: {\n /** Percentage */\n value: number\n}) {\n const {value: valueProp} = props\n const value = Math.min(Math.max(valueProp, 0), 100)\n const radius = SIZE / 2 - STROKE_WIDTH / 2\n const circ = 2 * Math.PI * radius\n const offset = ((100 - value) / 100) * circ\n const viewBox = `${SIZE / 2} ${SIZE / 2} ${SIZE} ${SIZE}`\n\n return (\n <Root viewBox={viewBox}>\n <BgCircle cx={SIZE} cy={SIZE} r={radius} />\n <ProgressCircle\n cx={SIZE}\n cy={SIZE}\n r={radius}\n style={{\n strokeDasharray: circ,\n strokeDashoffset: `${offset}px`,\n }}\n />\n </Root>\n )\n}\n","import {Box, Flex, rem, Skeleton, Stack} from '@sanity/ui'\nimport {styled} from 'styled-components'\n\nexport const RootBox = styled(Box)`\n position: relative;\n`\n\nexport const MediaFlex = styled(Flex).attrs({align: 'center', justify: 'center'})`\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n`\n\nexport const MediaSkeleton = styled(Skeleton).attrs({animated: true, radius: 2})`\n width: 100%;\n height: 100%;\n`\n\nexport const ProgressFlex = styled(Flex).attrs({align: 'center', justify: 'center'})`\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n\n &:before {\n background-color: var(--card-bg-color);\n opacity: 0.75;\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n }\n\n > svg {\n position: relative;\n z-index: 2;\n }\n`\n\nexport const TooltipContentStack = styled(Stack).attrs({gap: 2})`\n max-width: ${rem(200)};\n`\n","import {Box, Text} from '@sanity/ui'\nimport {useMemo} from 'react'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {Tooltip} from '../../../../ui-components/tooltip/Tooltip'\nimport {CircularProgress} from '../../progress/CircularProgress'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {\n MediaFlex,\n MediaSkeleton,\n ProgressFlex,\n RootBox,\n TooltipContentStack,\n} from './MediaPreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type MediaPreviewProps = Omit<PreviewProps<'media'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.media.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\n/**\n * @hidden\n * @beta */\nexport function MediaPreview(props: MediaPreviewProps) {\n const {\n media,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n children,\n isPlaceholder,\n progress = -1,\n subtitle,\n title,\n withBorder = true,\n withRadius = true,\n } = props\n\n const aspect = mediaDimensions.aspect || 1\n\n const STYLES_PADDER = useMemo(() => ({paddingBottom: `${100 / aspect}%`}), [aspect])\n\n const tooltipContent = useMemo(() => {\n if (!title || !subtitle) {\n return null\n }\n\n return (\n <TooltipContentStack>\n {title && (\n <Text align=\"center\" size={1} weight=\"medium\">\n {renderPreviewNode(title, 'media')}\n </Text>\n )}\n\n {subtitle && (\n <Text align=\"center\" muted size={1}>\n {renderPreviewNode(subtitle, 'media')}\n </Text>\n )}\n </TooltipContentStack>\n )\n }, [subtitle, title])\n\n return (\n <Box padding={2}>\n <RootBox data-testid=\"media-preview\" flex={1} overflow=\"hidden\">\n <div style={STYLES_PADDER} />\n\n <Tooltip content={tooltipContent} disabled={!tooltipContent} placement=\"top\" portal>\n <MediaFlex>\n {isPlaceholder ? (\n <MediaSkeleton />\n ) : (\n <Media\n border={withBorder}\n dimensions={mediaDimensions}\n layout=\"media\"\n media={media as any}\n radius={withRadius ? 1 : 0}\n responsive\n />\n )}\n\n {typeof progress === 'number' && progress > -1 && (\n <ProgressFlex>\n <CircularProgress value={progress} />\n </ProgressFlex>\n )}\n </MediaFlex>\n </Tooltip>\n\n {children}\n </RootBox>\n </Box>\n )\n}\n","import {Box, Card, Flex, rem} from '@sanity/ui'\nimport {styled} from 'styled-components'\n\nimport {PREVIEW_SIZES} from '../constants'\n\nexport const HeaderFlex = styled(Flex).attrs({align: 'center'})`\n height: ${rem(PREVIEW_SIZES.block.media.height)};\n white-space: nowrap;\n position: relative;\n z-index: 1;\n`\n\nexport const MediaCard = styled(Card)<{$ratio: number}>`\n overflow: hidden;\n position: relative;\n padding-bottom: ${({$ratio}) => $ratio}%;\n\n & > span {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n }\n`\n\nexport const RootBox = styled(Box).attrs({overflow: 'hidden'})`\n border-radius: ${({theme}) => theme.sanity.radius[1] /* oxlint-disable-line no-deprecated -- will fix in follow up PR */}px;\n`\n","import {Box, Flex, Stack, Text} from '@sanity/ui'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {HeaderFlex, MediaCard, RootBox} from './BlockImagePreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type BlockImagePreviewProps = Omit<PreviewProps<'blockImage'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.blockImage.media,\n fit: 'fillmax',\n dpr: getDevicePixelRatio(),\n}\n\nconst getRatio = (dimensions: PreviewMediaDimensions) => {\n const {height, width} = dimensions\n\n if (!height || !width) {\n return 1\n }\n\n return (height / width) * 100\n}\n\n/**\n * @hidden\n * @beta */\nexport function BlockImagePreview(props: BlockImagePreviewProps) {\n const {\n actions,\n title,\n subtitle,\n description,\n fallbackTitle = 'Untitled',\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n media,\n children,\n status,\n } = props\n\n return (\n <RootBox>\n <Stack>\n <HeaderFlex paddingBottom={3} paddingLeft={2} paddingRight={1} paddingTop={1}>\n <Stack flex={1} gap={2}>\n {(title || fallbackTitle) && (\n <Text size={1} textOverflow=\"ellipsis\" weight=\"medium\">\n {title ? renderPreviewNode(title as any, 'block') : fallbackTitle}\n </Text>\n )}\n\n {subtitle && (\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(subtitle as any, 'block')}\n </Text>\n )}\n </Stack>\n\n <Flex gap={1} paddingLeft={1}>\n {status && (\n <Box paddingX={2} paddingY={3}>\n {renderPreviewNode(status as any, 'block')}\n </Box>\n )}\n\n {actions as any}\n </Flex>\n </HeaderFlex>\n\n <MediaCard\n $ratio={getRatio(mediaDimensions)}\n __unstable_checkered\n display=\"flex\"\n sizing=\"border\"\n radius={2}\n tone=\"inherit\"\n >\n <Media\n border={false}\n dimensions={mediaDimensions}\n layout=\"blockImage\"\n media={media as any}\n radius={0}\n responsive\n />\n </MediaCard>\n </Stack>\n\n {description && (\n <Box paddingX={2} paddingY={3}>\n <Text muted size={1}>\n {renderPreviewNode(description as any, 'block')}\n </Text>\n </Box>\n )}\n\n {children && <div>{children}</div>}\n </RootBox>\n )\n}\n","import {Box, Flex, rem, Stack, Text} from '@sanity/ui'\nimport {styled} from 'styled-components'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {LinearProgress} from '../../progress/LinearProgress'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.block.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\nconst HeaderFlex = styled(Flex).attrs({align: 'center'})`\n min-height: ${rem(PREVIEW_SIZES.block.media.height)};\n`\n\n/**\n * @hidden\n * @beta */\nexport function BlockPreview(props: Omit<PreviewProps<'block'>, 'renderDefault'>) {\n const {\n actions,\n title,\n subtitle,\n description,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n media,\n progress,\n status,\n children,\n } = props\n\n const isUploading = typeof progress === 'number' && progress > -1\n\n return (\n <Stack data-testid=\"block-preview\" gap={1}>\n <HeaderFlex data-testid=\"block-preview__header\">\n {media && <Media dimensions={mediaDimensions} layout=\"block\" media={media as any} />}\n\n <Box flex={1} paddingLeft={media ? 2 : 1}>\n <Text size={1} textOverflow=\"ellipsis\" weight=\"medium\">\n {title ? renderPreviewNode(title, 'block') : 'Untitled'}\n </Text>\n\n {subtitle && (\n <Box marginTop={2}>\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(subtitle, 'block')}\n </Text>\n </Box>\n )}\n\n {description && (\n <Box marginTop={3}>\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(description, 'block')}\n </Text>\n </Box>\n )}\n\n {isUploading && (\n <Box marginTop={3}>\n <LinearProgress value={progress} />\n </Box>\n )}\n </Box>\n\n <Flex gap={1} paddingLeft={1}>\n {status && (\n <Box paddingX={2} paddingY={3}>\n {renderPreviewNode(status, 'block')}\n </Box>\n )}\n\n {actions as any}\n </Flex>\n </HeaderFlex>\n\n {children && <div data-testid=\"block-preview__children\">{children}</div>}\n </Stack>\n )\n}\n","import {rem, Text, type Theme} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nexport const RootSpan = styled.span`\n display: inline-flex;\n align-items: center;\n vertical-align: top;\n height: calc(1em - 1px);\n max-width: 100%;\n`\n\nexport const MediaSpan = styled.span`\n position: relative;\n display: inline-block;\n width: calc(1em - 1px);\n height: calc(1em - 1px);\n min-width: calc(1em - 1px);\n\n & img {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n object-fit: cover;\n border-radius: ${({theme}) => rem(theme.sanity.radius[1]) /* oxlint-disable-line no-deprecated -- will fix in follow up PR */};\n }\n\n & img + span {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n box-shadow: inset 0 0 0 1px var(--card-fg-color);\n opacity: 0.2;\n border-radius: ${({theme}) => rem(theme.sanity.radius[1]) /* oxlint-disable-line no-deprecated -- will fix in follow up PR */};\n }\n\n & svg {\n display: block;\n font-size: calc(14 / 16 * 1em);\n margin: 1px 0;\n\n &[data-sanity-icon] {\n font-size: calc(18 / 16 * 1em);\n margin: calc(1px + (2 / 18 * -1em)) 0;\n }\n }\n`\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nexport const TextSpan = styled(Text).attrs({forwardedAs: 'span'})(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const textFont = theme.sanity.fonts.text\n const textSize = textFont.sizes[1]\n\n return css`\n font-size: calc(${textSize.fontSize} / 16 * 1em);\n font-weight: ${textFont.weights.medium};\n box-sizing: border-box;\n display: inline-block;\n vertical-align: top;\n line-height: ${textSize.lineHeight / textSize.fontSize};\n padding-left: 0.5em;\n padding-right: calc(0.5em - 2px);\n min-width: 0;\n\n & > span {\n display: block;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n overflow: clip;\n }\n `\n})\n","import {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewMedia, renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {MediaSpan, RootSpan, TextSpan} from './InlinePreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type InlinePreviewProps = Omit<PreviewProps<'inline'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.inline.media,\n fit: 'crop',\n aspect: 1,\n dpr: getDevicePixelRatio(),\n}\n\n/**\n * @hidden\n * @beta */\nexport function InlinePreview(props: InlinePreviewProps) {\n const {\n title,\n fallbackTitle = 'Untitled',\n media,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n } = props\n\n return (\n <RootSpan data-testid=\"inline-preview\">\n {media && (\n <MediaSpan data-testid=\"inline-preview-media\">\n {renderPreviewMedia(media, 'inline', mediaDimensions)}\n <span />\n </MediaSpan>\n )}\n\n <TextSpan data-testid=\"inline-preview-title\" size={1}>\n {renderPreviewNode(title, 'inline', fallbackTitle)}\n </TextSpan>\n </RootSpan>\n )\n}\n","import isString from 'lodash-es/isString.js'\n\nimport {type Plugin, type PluginOptions} from './types'\n\n/**\n * @hidden\n * @beta */\nexport type PluginFactory<TOptions> = (options: TOptions) => PluginOptions\n\nfunction validatePlugin(pluginResult: PluginOptions) {\n // TODO: name is required etc\n const messages = [\n 'projectId' in pluginResult && '`projectId` not allowed in plugin configuration',\n 'dataset' in pluginResult && '`dataset` not allowed in plugin configuration',\n ].filter(isString)\n\n if (messages.length)\n throw new Error(\n `Invalid plugin configuration:\\n${messages.map((message) => `\\t${message}`).join('\\n')}`,\n )\n}\n\n/**\n * @hidden\n * @beta */\nexport function definePlugin<TOptions = void>(\n arg: PluginFactory<TOptions> | PluginOptions,\n): Plugin<TOptions> {\n if (typeof arg === 'function') {\n const pluginFactory = arg\n\n return (options: TOptions) => {\n // TODO: there's a possiblity of passing default arguments to users'\n // plugin factories or reading from default options in `TOptions`\n const result = pluginFactory(options)\n\n validatePlugin(result)\n return result\n }\n }\n\n validatePlugin(arg)\n return () => arg\n}\n\n/**\n * @deprecated Use `definePlugin` instead\n *\n * @hidden\n * @beta\n */\nexport function createPlugin<TOptions = void>(\n arg: PluginFactory<TOptions> | PluginOptions,\n): Plugin<TOptions> {\n return definePlugin(arg)\n}\n","import {useToast} from '@sanity/ui/toast'\nimport {useEffect} from 'react'\n\nimport {definePlugin} from '../config/definePlugin'\nimport {type LayoutProps} from '../config/studio/types'\n\nfunction SchedulePublishingStudioLayout(props: LayoutProps) {\n const toast = useToast()\n useEffect(() => {\n console.error(\n `Scheduled publishing plugin is added by default, please remove this plugin from your config. \n \\nIf you have a custom date config, you can use the scheduledPublishing API to customize the date input.\n \\nSee: https://www.sanity.io/docs/scheduled-publishing.\n `,\n )\n toast.push({\n id: 'scheduled-publishing-deprecated',\n closable: true,\n duration: 60000,\n status: 'error',\n title: 'Scheduled publishing plugin is deprecated',\n description:\n 'The scheduled publishing plugin is now deprecated, you should remove the plugin from your configuration. If you have a custom date config, you can use the scheduledPublishing API to customize the date input. See: https://www.sanity.io/docs/scheduled-publishing.',\n })\n }, [toast])\n\n return props.renderDefault(props)\n}\n\n/**\n * Shows an error in console and a toast to prevent users from importing the deprecated plugin.\n * Gives information about how to upgrade to the new version.\n */\nexport const deprecatedScheduledPublishingPlugin = definePlugin({\n name: 'sanity/deprecated/scheduled-publishing',\n studio: {\n components: {\n layout: SchedulePublishingStudioLayout,\n },\n },\n})\n","import {deprecatedScheduledPublishingPlugin} from '../deprecatedPlugins/DeprecatedScheduledPublishing'\nimport {type PluginOptions} from './types'\n\nconst DEPRECATED_PLUGINS = [\n // Scheduled publishing is added by default, we are filtering to avoid duplicates\n 'scheduled-publishing',\n]\n\n/**\n * @internal\n *\n * This function flattens the config tree into a list of configs in the order they should be applied.\n */\nexport const flattenConfig = (\n {plugins = [], ...currentConfig}: PluginOptions,\n path: string[],\n): Array<{config: PluginOptions; path: string[]}> => {\n // The APIs used at the root config level\n const rootConfig = {config: currentConfig, path: [...path, currentConfig.name]}\n\n // An array with the APIs used in plugins\n const allPlugins = plugins.flatMap((plugin) =>\n flattenConfig(plugin, [...path, currentConfig.name]),\n )\n\n const deprecatedScheduledPublishing = allPlugins.find(\n (p) => p.config.name === 'scheduled-publishing',\n )\n if (deprecatedScheduledPublishing) {\n // Add the deprecated plugin error to the plugins list, to show the error to users.\n allPlugins.push({\n path: deprecatedScheduledPublishing.path,\n config: deprecatedScheduledPublishingPlugin(),\n })\n }\n\n const resolved = [\n ...allPlugins.filter((plugin) => !DEPRECATED_PLUGINS.includes(plugin.config.name)),\n rootConfig,\n ]\n\n return resolved\n}\n","import {Skeleton} from '@sanity/ui'\nimport {type ComponentType, Fragment, Suspense, useMemo} from 'react'\n\nimport {useSource} from '../../studio/source'\nimport {flattenConfig} from '../flattenConfig'\nimport {type PluginOptions} from '../types'\n\nconst emptyRender = () => <Fragment />\n\nfunction _createMiddlewareComponent<T extends {}>(\n DefaultComponent: ComponentType<T>,\n middlewareComponents: ComponentType<T>[],\n): ComponentType<T> {\n function MiddlewareComponent(outerProps: T) {\n // This is the inner \"layer\" of the middleware chain\n // Here we render the _default_ component (typically Sanity's component)\n let next = (props: T) => <DefaultComponent {...props} />\n\n for (const Middleware of middlewareComponents) {\n // As we progress through the chain, the meaning of \"renderDefault\" changes.\n // At a given layer in the chain, the _next_ layer is the \"default\".\n const renderDefault = next\n\n // Here we replace `next` so that the _previous_ layer may use this as its _next_.\n next = (props) => <Middleware {...props} renderDefault={renderDefault} />\n }\n\n return (\n <Suspense fallback={<Skeleton padding={3} radius={1} animated />}>\n {next({\n ...outerProps,\n // NOTE: it's safe to pass the empty render function, since it'll be overwritten in the next step (above).\n // NOTE: it's important that the default component does not use `renderDefault`, since it will\n // get the `emptyRender` callback will be passed when the middleware stack is empty.\n renderDefault: emptyRender,\n })}\n </Suspense>\n )\n }\n return MiddlewareComponent\n}\n\n/**\n * @internal\n * This hook returns a component based on the Components API middleware chain.\n *\n * - The `pick` function is used to select a component from the provided plugin options in the configuration.\n * - The `defaultComponent` is the default component that gets rendered with `renderDefault`.\n * The `renderDefault` function is added to the props of the middleware components so that they can render the default\n * component and continue the middleware chain.\n *\n * @example\n * Example usage of:\n *\n * ```ts\n * const StudioLayout = useMiddlewareComponents({\n * pick: (plugin) => plugin.studio?.components?.layout,\n * defaultComponent: StudioLayout,\n * })\n *\n * return <StudioLayout />\n *```\n */\nexport function useMiddlewareComponents<T extends {}>(props: {\n pick: (plugin: PluginOptions) => ComponentType<T>\n defaultComponent: ComponentType<T>\n}): ComponentType<T> {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {options} = useSource().__internal\n const {defaultComponent, pick} = props\n\n return useMemo(() => {\n // Flatten the config tree into a list of configs\n const flattened = [...flattenConfig(options, [])]\n\n // Since the middleware chain is executed backwards, we need to reverse the list of configs here.\n // This is important because we want the order of the Components API to be consistent with the order of the other APIs.\n flattened.reverse()\n\n // Pick the middleware components from the configs\n const pickedComponents = flattened.map(({config}) => pick(config))\n\n // Since we try to pick the components in all configs, some results may be undefined.\n // Therefore, we filter these values out before passing the result to the middleware creator.\n const result = pickedComponents.filter(Boolean)\n\n // Create the middleware component\n return _createMiddlewareComponent(defaultComponent, result)\n }, [defaultComponent, options, pick])\n}\n","/** @internal */\nexport function isString(value: unknown): value is string {\n return typeof value === 'string'\n}\n","import {type SanityClient} from '@sanity/client'\n\n/**\n * Creates a Media Library-specific client with an explicitly configured API\n * host that includes the project ID in the subdomain. This is to satisfy CORS\n * requirements, as browser requests will fail against the global host because\n * it does not include CORS headers. (Setting `resource` on a client makes it\n * ignore `useProjectHostname` and target the global API host.)\n *\n * @internal\n */\nexport function createMediaLibraryClient(client: SanityClient, libraryId: string): SanityClient {\n const {apiHost, projectId} = client.config()\n\n if (!projectId) {\n throw new Error('Cannot create Media Library client: missing projectId in client config')\n }\n\n const baseUrl = new URL(apiHost)\n baseUrl.hostname = `${projectId}.${baseUrl.hostname}`\n\n return client.withConfig({\n // `origin` (rather than `toString()`) avoids a trailing slash and drops\n // any pathname/search/hash that may have been configured on `apiHost`\n apiHost: baseUrl.origin,\n resource: {\n id: libraryId,\n type: 'media-library',\n },\n })\n}\n","import {type GlobalDocumentReferenceValue} from '@sanity/types'\n\n/**\n * @internal\n */\nexport type MediaLibraryRef = `media-library:${string}:${string}`\n\nfunction hasOwnRecord<K extends PropertyKey>(value: unknown, key: K): value is Record<K, unknown> {\n return (\n typeof value === 'object' && value !== null && Object.prototype.hasOwnProperty.call(value, key)\n )\n}\n\nexport function makeMediaLibraryRef(libraryId: string, assetId: string): MediaLibraryRef {\n return `media-library:${libraryId}:${assetId}`\n}\n\nfunction containsMediaProperty(value: unknown): value is {media: GlobalDocumentReferenceValue} {\n if (!hasOwnRecord(value, 'media') || !hasOwnRecord(value.media, '_ref')) {\n return false\n }\n return typeof value.media._ref === 'string'\n}\n\nfunction isMediaLibraryRef(ref: unknown): ref is MediaLibraryRef {\n if (typeof ref !== 'string') return false\n\n const [resourceType, resourceId, documentId] = ref.split(':', 3)\n\n return resourceType === 'media-library' && Boolean(resourceId) && Boolean(documentId)\n}\n\n/**\n * Attempts to extract a Media Library ref from a source or raw string value.\n *\n * @internal\n */\nexport function getMediaLibraryRef(value: unknown): MediaLibraryRef | undefined {\n const maybeRef = containsMediaProperty(value) ? value?.media?._ref : value\n\n return isMediaLibraryRef(maybeRef) ? maybeRef : undefined\n}\n","import {type SanityClient} from '@sanity/client'\nimport DataLoader from 'dataloader'\nimport QuickLRU from 'quick-lru'\n\nimport {createMediaLibraryClient} from '../../util/createMediaLibraryClient'\nimport {makeMediaLibraryRef, type MediaLibraryRef} from './refs'\n\ntype AccessPolicyResult = 'public' | 'private' | undefined\n\nconst POLICY_CACHE_MAX_SIZE = 2000\nconst POLICY_CACHE_MAX_AGE = 1000 * 60 * 5 // 5 minutes\n\nconst loaders = new Map<string, DataLoader<string, AccessPolicyResult>>()\nconst policyCache = new QuickLRU<string, AccessPolicyResult>({\n maxAge: POLICY_CACHE_MAX_AGE,\n maxSize: POLICY_CACHE_MAX_SIZE,\n})\n\n/**\n * Batch fetch asset access policies from the Media Library API and populate the\n * cache.\n */\nasync function fetchAccessPoliciesBatch(params: {\n assetIds: readonly string[]\n client: SanityClient\n libraryId: string\n}): Promise<AccessPolicyResult[]> {\n const {assetIds, client, libraryId} = params\n\n if (assetIds.length === 0) {\n return []\n }\n\n try {\n const results = await client.fetch<{_id: string; cdnAccessPolicy?: AccessPolicyResult}[]>(\n `*[_id in $ids]{_id, cdnAccessPolicy}`,\n {ids: assetIds},\n )\n\n const policyById = Object.fromEntries(results.map((doc) => [doc._id, doc.cdnAccessPolicy]))\n\n return assetIds.map((assetId) => {\n const policy = policyById[assetId]\n const assetRef = makeMediaLibraryRef(libraryId, assetId)\n policyCache.set(assetRef, policy)\n return policy\n })\n } catch (error) {\n console.error('Error fetching cdnAccessPolicy batch', {\n libraryId,\n assetIds,\n error,\n })\n\n assetIds.forEach((assetId) => {\n const assetRef = makeMediaLibraryRef(libraryId, assetId)\n policyCache.set(assetRef, undefined)\n })\n\n return assetIds.map(() => undefined)\n }\n}\n\n/**\n * Resolve (or create) the DataLoader responsible for fetching asset access\n * policies from a given Media Library.\n *\n * NOTE: The first client passed for a given library ID will be used to create the\n * DataLoader instance, subsequent clients for the same library ID will be ignored.\n */\nfunction resolveAssetPolicyLoader(\n client: SanityClient,\n libraryId: string,\n): DataLoader<string, AccessPolicyResult> {\n const existingLoader = loaders.get(libraryId)\n\n if (existingLoader) {\n return existingLoader\n }\n\n const mediaLibraryClient = createMediaLibraryClient(client, libraryId)\n\n const loader = new DataLoader<string, AccessPolicyResult>(\n (assetIds) =>\n fetchAccessPoliciesBatch({\n assetIds,\n client: mediaLibraryClient,\n libraryId,\n }),\n {cache: false}, // only batch per tick, rely on QuickLRU for caching\n )\n\n loaders.set(libraryId, loader)\n return loader\n}\n\n/**\n * Schedule an asset access policy fetch using the library-specific DataLoader.\n * Returns the cached policy value if it's already been resolved.\n *\n * @internal\n */\nexport function enqueueAssetAccessPolicyFetch(\n assetRef: MediaLibraryRef,\n client?: SanityClient,\n): Promise<AccessPolicyResult> {\n const [, libraryId, assetId] = assetRef.split(':', 3)\n\n if (!libraryId || !assetId || !client) {\n return Promise.resolve(undefined)\n }\n\n if (policyCache.has(assetRef)) {\n const policy = policyCache.get(assetRef) ?? undefined\n return Promise.resolve(policy)\n }\n\n const loader = resolveAssetPolicyLoader(client, libraryId)\n return loader.load(assetId)\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type SanityImageSource} from '@sanity/image-url'\nimport {type AssetSource} from '@sanity/types'\nimport useSWR from 'swr'\n\nimport {enqueueAssetAccessPolicyFetch} from '../../../../store/accessPolicy/fetch'\nimport {getMediaLibraryRef, type MediaLibraryRef} from '../../../../store/accessPolicy/refs'\nimport {type AssetAccessPolicy} from '../types'\n\n/**\n * Resolve the effective access policy for a given image source, including\n * Media Library specific checks when possible.\n *\n * @internal\n */\nexport function useAccessPolicy(params: {\n client: SanityClient\n source?: AssetSource | SanityImageSource\n}): AssetAccessPolicy {\n const {client, source} = params\n\n const ref = getMediaLibraryRef(source)\n\n // If the client doesn't have a token (i.e. cookie auth), set the requestKey\n // to null to bypass the cdnAccessPolicy check as it will always fail.\n const canCheck = Boolean(ref && client.config().token)\n const requestKey = canCheck ? ref : null\n\n // useSWR gives us synchronous access to the cached policy values so the UI\n // can render without a flash of loading state while\n // enqueueAssetAccessPolicyFetch (which always returns a promise) settles.\n const fetcher = async (key: MediaLibraryRef) => enqueueAssetAccessPolicyFetch(key, client)\n const options = {\n dedupingInterval: 0,\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n const {data: cdnAccessPolicy, isLoading} = useSWR(requestKey, fetcher, options)\n\n // Non-Media Library assets are always 'public'\n if (!ref) return 'public'\n // If we can't check for an access policy (no token)\n if (!canCheck) return 'unknown'\n // If we can check AND a check is in progress\n if (isLoading) return 'checking'\n // The actual fetched policy, default to 'unknown' if undefined\n return cdnAccessPolicy ?? 'unknown'\n}\n","// TODO: change this to what the official GDR release version is\nexport const DEFAULT_API_VERSION = 'vX'\n\n// Staging\nexport const DEPLOYED_FRONTEND_HOST_STAGING = 'https://media.sanity.work'\nexport const CDN_HOST_STAGING = 'https://sanity-cdn.work'\nexport const API_HOST_STAGING = 'https://api.sanity.work'\n\n// Production\nexport const DEPLOYED_FRONTEND_HOST_PRODUCTION = 'https://media.sanity.io'\nexport const CDN_HOST_PRODUCTION = 'https://sanity-cdn.com'\nexport const API_HOST_PRODUCTION = 'https://api.sanity.io'\n","import {useClient} from '../../../../hooks/useClient'\nimport {DEFAULT_API_VERSION} from '../constants'\n\nexport function useToken(): string | undefined {\n const client = useClient({apiVersion: DEFAULT_API_VERSION})\n const {token} = client.config()\n return token\n}\n","import {useEffect, useState} from 'react'\n\nimport {useToken} from '../../../studio/assetSourceMediaLibrary/hooks/useToken'\n\n/**\n * @internal\n */\nexport interface UseImageObjectUrlResult {\n error: Error | null\n isLoading: boolean\n objectUrl: string | undefined\n}\n\ninterface RequestCacheEntry {\n abortController: AbortController\n blob: Blob | null\n cleanupTimer?: ReturnType<typeof setTimeout>\n error: Error | null\n listeners: Set<() => void>\n objectUrl?: string\n status: 'pending' | 'success' | 'error'\n}\n\n// Delay before disposing cache entries to handle React Strict Mode re-mounts\nconst CACHE_DISPOSE_DELAY = 2000\n\n// Cache shared across all hook instances keyed by `${token}:${url}` to ensure\n// unique entries per authenticated request.\nconst requestCache = new Map<string, RequestCacheEntry>()\n\nconst IDLE_RESULT: UseImageObjectUrlResult = {\n error: null,\n isLoading: false,\n objectUrl: undefined,\n}\n\nconst LOADING_RESULT: UseImageObjectUrlResult = {\n error: null,\n isLoading: true,\n objectUrl: undefined,\n}\n\nfunction createCacheKey(url: string | undefined, token: string | undefined): string | undefined {\n if (!url || !token) return undefined\n return `${token}:${url}`\n}\n\nfunction notifyListeners(entry: RequestCacheEntry): void {\n entry.listeners.forEach((listener) => listener())\n}\n\nfunction deriveResultFromEntry(entry: RequestCacheEntry): UseImageObjectUrlResult {\n switch (entry.status) {\n case 'pending':\n // While loading, preserve any existing objectUrl for smoother transitions\n return entry.objectUrl\n ? {objectUrl: entry.objectUrl, isLoading: true, error: null}\n : LOADING_RESULT\n case 'success':\n return {objectUrl: entry.objectUrl, isLoading: false, error: null}\n case 'error':\n return {objectUrl: undefined, isLoading: false, error: entry.error}\n default:\n return IDLE_RESULT\n }\n}\n\nfunction createFetchCacheEntry(url: string, token: string): RequestCacheEntry {\n const abortController = new AbortController()\n\n const entry: RequestCacheEntry = {\n abortController,\n blob: null,\n cleanupTimer: undefined,\n error: null,\n listeners: new Set(),\n objectUrl: undefined,\n status: 'pending',\n }\n\n fetch(url, {\n cache: 'force-cache',\n headers: {Authorization: `Bearer ${token}`},\n signal: abortController.signal,\n })\n .then((res) => {\n if (res.ok) return res.blob()\n throw new Error(`Failed to fetch image (HTTP ${res.status})`)\n })\n .then((blob) => {\n entry.blob = blob\n entry.error = null\n entry.status = 'success'\n entry.objectUrl = URL.createObjectURL(blob)\n notifyListeners(entry)\n })\n .catch((error) => {\n entry.blob = null\n entry.error = error as Error\n entry.status = 'error'\n notifyListeners(entry)\n })\n\n return entry\n}\n\n/**\n * Fetches an authenticated image (using a token) and returns an object URL for\n * use as an `<img src>`\n *\n * Caches using a url/token pair so multiple components can share a single\n * fetch, and keeps cache entries alive briefly after the last consumer unmounts\n * to avoid duplicate fetches when in strict mode.\n *\n * Automatically revokes object URLs and disposes cache entries when no longer\n * referenced.\n *\n * @internal\n */\nexport function useImageObjectUrl(url: string | undefined): UseImageObjectUrlResult {\n const token = useToken()\n const cacheKey = createCacheKey(url, token)\n\n // Initialize state from cache if available to ensure we don't flash a loading\n // state if data is already available.\n const [state, setState] = useState<UseImageObjectUrlResult>(() => {\n if (!cacheKey) return IDLE_RESULT\n const entry = requestCache.get(cacheKey)\n return entry ? deriveResultFromEntry(entry) : LOADING_RESULT\n })\n\n useEffect(() => {\n // No cacheKey (i.e. no URL or token) means we can't fetch. Reset to idle state,\n // skipping the update if already in an idle state\n if (!cacheKey) {\n // oxlint-disable-next-line react/react-compiler\n setState((prev) => (prev.objectUrl || prev.isLoading || prev.error ? IDLE_RESULT : prev))\n return undefined\n }\n\n // Get or create cache entry for this URL/token pair\n let entry = requestCache.get(cacheKey)\n if (!entry) {\n // url and token are guaranteed to exist when cacheKey exists\n entry = createFetchCacheEntry(url!, token!)\n requestCache.set(cacheKey, entry)\n }\n\n // Cancel any pending cleanup from a previous unmount (e.g. Strict Mode)\n if (entry.cleanupTimer) {\n clearTimeout(entry.cleanupTimer)\n entry.cleanupTimer = undefined\n }\n\n // Subscribe to fetch completion and sync current state\n const updateState = () => setState(deriveResultFromEntry(entry))\n updateState()\n entry.listeners.add(updateState)\n\n return () => {\n entry.listeners.delete(updateState)\n\n if (entry.listeners.size === 0) {\n // Delay disposal to allow Strict Mode re-mounts to reuse the entry\n entry.cleanupTimer = setTimeout(() => {\n entry.abortController.abort()\n if (entry.objectUrl) {\n URL.revokeObjectURL(entry.objectUrl)\n }\n requestCache.delete(cacheKey)\n }, CACHE_DISPOSE_DELAY)\n }\n }\n }, [cacheKey, token, url])\n\n return state\n}\n","import {type ImageUrlBuilder, type SanityImageSource} from '@sanity/image-url'\n\nimport {type AssetAccessPolicy} from '../types'\nimport {useImageObjectUrl} from './useImageObjectUrl'\n\ninterface UseImageUrlParameters<T extends SanityImageSource | undefined> {\n accessPolicy?: AssetAccessPolicy\n imageSource?: T\n imageUrlBuilder: ImageUrlBuilder\n transform?: (builder: ImageUrlBuilder, value: SanityImageSource) => string | undefined\n}\n\ninterface UseImageUrlResult {\n isLoading: boolean\n url: string | undefined\n}\n\n/**\n * Hook for resolving image URLs with Private asset support.\n *\n * Handles applying URL transformations and object URL generation when needed.\n *\n * @internal\n */\nexport function useImageUrl<T extends SanityImageSource = SanityImageSource>(\n params: UseImageUrlParameters<T>,\n): UseImageUrlResult {\n const {accessPolicy = 'public', imageSource, imageUrlBuilder, transform} = params\n\n const isPolicyCheckInProgress = accessPolicy === 'checking'\n const isPrivate = accessPolicy === 'private'\n\n // The `http:` or `https:` URL. While an access policy check is in progress,\n // this stays undefined as it may change after the check completes.\n const networkUrl = (() => {\n if (!imageSource || isPolicyCheckInProgress) return undefined\n // Apply the transformations if provided.\n if (transform) return transform(imageUrlBuilder, imageSource)\n return imageUrlBuilder.image(imageSource).url()\n })()\n\n // If the asset is Private, fetch the image using the network URL and convert\n // the response into a `blob:` URL so it can be used as an `<img src>`.\n const {objectUrl, isLoading: objectUrlIsLoading} = useImageObjectUrl(\n isPrivate ? networkUrl : undefined,\n )\n\n const isLoading = isPolicyCheckInProgress || objectUrlIsLoading\n const url = isLoading ? undefined : (objectUrl ?? networkUrl)\n\n return {\n isLoading,\n url,\n }\n}\n","import {CompactPreview} from '../../components/previews/general/CompactPreview'\nimport {DefaultPreview} from '../../components/previews/general/DefaultPreview'\nimport {DetailPreview} from '../../components/previews/general/DetailPreview'\nimport {MediaPreview} from '../../components/previews/general/MediaPreview'\nimport {BlockImagePreview} from '../../components/previews/portableText/BlockImagePreview'\nimport {BlockPreview} from '../../components/previews/portableText/BlockPreview'\nimport {InlinePreview} from '../../components/previews/portableText/InlinePreview'\n\nexport const _previewComponents = {\n block: BlockPreview,\n blockImage: BlockImagePreview,\n compact: CompactPreview,\n default: DefaultPreview,\n detail: DetailPreview,\n inline: InlinePreview,\n media: MediaPreview,\n} as const\n","import {isImageSource, isSanityImageUrl, parseImageAssetUrl} from '@sanity/asset-utils'\nimport {type SanityClient} from '@sanity/client'\nimport {DocumentIcon} from '@sanity/icons/Document'\nimport {WarningOutlineIcon} from '@sanity/icons/WarningOutline'\nimport {\n createImageUrlBuilder,\n type ImageUrlBuilder,\n type SanityImageSource,\n} from '@sanity/image-url'\nimport {Card, Flex, Skeleton} from '@sanity/ui'\nimport {\n type ComponentType,\n type ElementType,\n isValidElement,\n memo,\n type ReactNode,\n useCallback,\n useMemo,\n useState,\n} from 'react'\nimport {isValidElementType} from 'react-is'\n\nimport {Tooltip} from '../../../ui-components/tooltip/Tooltip'\nimport {resolveBlockImageDimensions} from '../../components/previews/helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../../components/previews/types'\nimport {useAccessPolicy} from '../../form/inputs/files/ImageInput/useAccessPolicy'\nimport {useImageUrl} from '../../form/inputs/files/ImageInput/useImageUrl'\nimport {useClient} from '../../hooks/useClient'\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../studioClient'\nimport {isString} from '../../util/isString'\nimport {_previewComponents} from './_previewComponents'\n\nfunction FallbackIcon() {\n return <DocumentIcon className=\"sanity-studio__preview-fallback-icon\" />\n}\n\n/** @internal */\nexport interface SanityDefaultPreviewProps extends Omit<PreviewProps, 'renderDefault'> {\n error?: Error | null\n icon?: ElementType | false\n tooltip?: ReactNode\n}\n\ntype SanityDefaultMediaProps = {\n client: SanityClient\n dimensions: PreviewMediaDimensions\n imageSource: SanityImageSource\n imageUrlBuilder: ImageUrlBuilder\n title: PreviewProps['title']\n}\n\nfunction SanityDefaultMedia({\n client,\n dimensions,\n imageSource,\n imageUrlBuilder,\n title,\n}: SanityDefaultMediaProps) {\n const transform = (builder: ImageUrlBuilder, val: SanityImageSource) => {\n const width = dimensions.width ?? 100\n const height = dimensions.height ?? 100\n const fit = dimensions.fit\n const dpr = dimensions.dpr ?? 1\n\n return builder.image(val).withOptions({width, height, fit, dpr}).url() || ''\n }\n\n const accessPolicy = useAccessPolicy({client, source: imageSource})\n\n const {isLoading, url} = useImageUrl({\n accessPolicy,\n imageSource,\n imageUrlBuilder,\n transform,\n })\n\n const [hasImageError, setHasImageError] = useState(false)\n const handleError = () => setHasImageError(true)\n\n if (isLoading) {\n return <Skeleton animated style={{width: '100%', height: '100%'}} />\n }\n\n // Show a warning if we have a media library asset that we couldn't check\n // the access policy for (e.g., cookie auth) and the image failed to load\n const showAccessWarning = accessPolicy === 'unknown' && hasImageError\n\n if (showAccessWarning) {\n return (\n <Card tone=\"critical\" style={{width: '100%', height: '100%'}}>\n <Flex justify=\"center\" align=\"center\" style={{width: '100%', height: '100%'}}>\n <WarningOutlineIcon />\n </Flex>\n </Card>\n )\n }\n\n return (\n <img\n alt={typeof title === 'string' ? title : undefined}\n onError={handleError}\n referrerPolicy=\"strict-origin-when-cross-origin\"\n src={url}\n />\n )\n}\n\n/**\n * Used in cases where no custom preview component is provided\n * @internal\n * */\nexport const SanityDefaultPreview = memo(function SanityDefaultPreview(\n props: SanityDefaultPreviewProps,\n): React.JSX.Element {\n const {icon: Icon, layout, media: mediaProp, imageUrl, title, tooltip, ...restProps} = props\n\n const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const imageBuilder = useMemo(() => createImageUrlBuilder(client), [client])\n\n // NOTE: This function exists because the previews provides options\n // for the rendering of the media (dimensions)\n const renderMedia = useCallback(\n (options: {dimensions: PreviewMediaDimensions}) => {\n let imageSource = mediaProp\n\n // If this is a string and a valid Sanity Image URL, parse it so that we can\n // pass it as a valid asset ID to the image builder\n if (isString(imageSource) && isSanityImageUrl(imageSource)) {\n const {assetId} = parseImageAssetUrl(imageSource)\n\n imageSource = assetId\n }\n\n return (\n <SanityDefaultMedia\n client={client}\n dimensions={options.dimensions}\n imageSource={imageSource as SanityImageSource}\n imageUrlBuilder={imageBuilder}\n title={title}\n />\n )\n },\n [client, imageBuilder, mediaProp, title],\n )\n\n const renderIcon = useCallback(() => {\n return Icon ? <Icon /> : <FallbackIcon />\n }, [Icon])\n\n const media = useMemo(() => {\n if (Icon === false) {\n // Explicitly disabled\n return false\n }\n\n // If this is a string and a valid Sanity Image URL, pass it to the renderMedia function early\n // If we don't do this check early, then isValidElementType will return true for strings and create an\n // exception when used inside the BlockImagePreview\n if (isString(mediaProp) && isSanityImageUrl(mediaProp)) {\n return renderMedia\n }\n\n if (isImageSource(mediaProp)) {\n return renderMedia\n }\n\n if (isValidElementType(mediaProp)) {\n return mediaProp\n }\n\n if (isValidElement(mediaProp)) {\n return mediaProp\n }\n\n // Handle image urls\n if (isString(imageUrl)) {\n return (\n <img\n src={imageUrl}\n alt={isString(title) ? title : undefined}\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n )\n }\n\n // Render fallback icon\n return renderIcon\n }, [Icon, imageUrl, mediaProp, renderIcon, renderMedia, title])\n\n const resolvedMediaDimensions = useMemo<PreviewMediaDimensions | undefined>(() => {\n if (props.mediaDimensions) {\n return props.mediaDimensions\n }\n\n if (layout !== 'blockImage') {\n return undefined\n }\n\n if (!isImageSource(mediaProp)) {\n return undefined\n }\n\n return resolveBlockImageDimensions(mediaProp)\n }, [layout, mediaProp, props.mediaDimensions])\n\n const previewProps: Omit<PreviewProps, 'renderDefault'> = useMemo(\n () => ({\n ...restProps,\n media,\n mediaDimensions: resolvedMediaDimensions,\n title,\n }),\n [media, resolvedMediaDimensions, restProps, title],\n )\n\n const LayoutComponent = _previewComponents[layout || 'default'] as ComponentType<\n Omit<PreviewProps, 'renderDefault'>\n >\n\n const children = <LayoutComponent {...previewProps} />\n\n if (tooltip) {\n return (\n <Tooltip\n content={tooltip}\n disabled={!tooltip}\n fallbackPlacements={['top-end', 'bottom-end']}\n placement=\"right\"\n >\n {/* Currently tooltips won't trigger without a wrapping element */}\n <div>{children}</div>\n </Tooltip>\n )\n }\n\n return children\n})\nSanityDefaultPreview.displayName = 'Memo(SanityDefaultPreview)'\n","import {type SchemaType} from '@sanity/types'\nimport {type ComponentType} from 'react'\n\nimport {type PreviewProps} from '../../../components/previews/types'\nimport {SanityDefaultPreview} from '../../../preview/components/SanityDefaultPreview'\n\n// Kept separate from `inputResolver.tsx`: preview resolution only needs `SanityDefaultPreview`,\n// while the input resolver pulls in every input component. Consumers of `usePreviewComponent`\n// (e.g. `Preview`, which the input tree renders) would otherwise circularly import the whole\n// form input tree.\n\nexport function defaultResolvePreviewComponent(\n schemaType: SchemaType,\n): ComponentType<Omit<PreviewProps, 'renderDefault'>> {\n if (schemaType.components?.preview) return schemaType.components.preview\n\n return SanityDefaultPreview\n}\n","import {type ComponentType} from 'react'\n\nimport {type PreviewProps} from '../../components/previews/types'\nimport {type PluginOptions} from '../../config/types'\nimport {\n type BlockAnnotationProps,\n type BlockProps,\n type PortableTextPluginsProps,\n} from '../types/blockProps'\nimport {type FieldProps} from '../types/fieldProps'\nimport {type InputProps} from '../types/inputProps'\nimport {type ItemProps} from '../types/itemProps'\n\nexport function pickInputComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<InputProps, 'renderDefault'>> {\n return plugin.form?.components?.input as ComponentType<Omit<InputProps, 'renderDefault'>>\n}\n\nexport function pickFieldComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<FieldProps, 'renderDefault'>> {\n return plugin.form?.components?.field as ComponentType<Omit<FieldProps, 'renderDefault'>>\n}\n\nexport function pickPreviewComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<PreviewProps, 'renderDefault'>> {\n return plugin.form?.components?.preview as ComponentType<Omit<PreviewProps, 'renderDefault'>>\n}\n\nexport function pickItemComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<ItemProps, 'renderDefault'>> {\n return plugin.form?.components?.item as ComponentType<Omit<ItemProps, 'renderDefault'>>\n}\n\nexport function pickBlockComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<BlockProps, 'renderDefault'>> {\n return plugin.form?.components?.block as ComponentType<Omit<BlockProps, 'renderDefault'>>\n}\n\nexport function pickInlineBlockComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<BlockProps, 'renderDefault'>> {\n return plugin.form?.components?.inlineBlock as ComponentType<Omit<BlockProps, 'renderDefault'>>\n}\n\nexport function pickAnnotationComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<BlockAnnotationProps, 'renderDefault'>> {\n return plugin.form?.components?.annotation as ComponentType<\n Omit<BlockAnnotationProps, 'renderDefault'>\n >\n}\n\nexport function pickPortableTextEditorPluginsComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<PortableTextPluginsProps, 'renderDefault'>> {\n return plugin.form?.components?.portableText?.plugins as ComponentType<\n Omit<PortableTextPluginsProps, 'renderDefault'>\n >\n}\n","import {type SchemaType} from '@sanity/types'\nimport {type ComponentType, useCallback, useMemo} from 'react'\n\n// Each form component hook lives in its own module (together with the default component it\n// resolves) so that form components which consume a sibling hook (e.g. `ListArrayInput` uses\n// `useItemComponent`, `Preview` uses `usePreviewComponent`) only pull in that hook's resolver\n// subtree instead of every resolver, which would create circular imports through the shared\n// module.\n\n/**\n * @internal\n */\nexport function useResolveDefaultComponent<T extends {schemaType?: SchemaType}>(props: {\n componentProps: Omit<T, 'renderDefault'>\n componentResolver: (schemaType: SchemaType) => ComponentType<Omit<T, 'renderDefault'>>\n}): React.JSX.Element {\n const {componentResolver, componentProps} = props\n const {schemaType} = componentProps\n\n // NOTE: this will not happen, but we do this to avoid updating too many places\n // TODO: We need to clean up the preview machinery + types to remove this\n if (!schemaType) {\n throw new Error('the `schemaType` property must be defined')\n }\n\n // Memoized so the resolved component keeps a stable identity across renders; a new identity\n // would make React unmount and remount the subtree.\n const DefaultResolvedComponent = useMemo(\n () => componentResolver(schemaType),\n [componentResolver, schemaType],\n )\n\n const renderDefault = useCallback(\n (parentTypeProps: T) => {\n if (!parentTypeProps.schemaType?.type) {\n // In theory this should not be possible, and this error should never be thrown\n throw new Error('Attempted to render form component of non-existent parent type')\n }\n\n // The components property is removed from the schemaType object\n // in order to prevent that a component is render itself\n // oxlint-disable-next-line no-unused-vars\n const {components, ...restSchemaType} = parentTypeProps.schemaType\n const ParentTypeResolvedComponent = componentResolver(restSchemaType)\n return <ParentTypeResolvedComponent {...parentTypeProps} />\n },\n [componentResolver],\n )\n\n // oxlint-disable-next-line react/react-compiler -- this is intentional and how the middleware components has to work\n return <DefaultResolvedComponent {...componentProps} renderDefault={renderDefault} />\n}\n","import {type ComponentType} from 'react'\n\nimport {type PreviewProps} from '../../components/previews/types'\nimport {useMiddlewareComponents} from '../../config/components/useMiddlewareComponents'\nimport {defaultResolvePreviewComponent} from '../studio/inputResolver/previewResolver'\nimport {pickPreviewComponent} from './picks'\nimport {useResolveDefaultComponent} from './useResolveDefaultComponent'\n\n/**\n * @internal\n */\nfunction DefaultPreview(props: Omit<PreviewProps, 'renderDefault'>): React.JSX.Element {\n return useResolveDefaultComponent<PreviewProps>({\n componentProps: props,\n componentResolver: defaultResolvePreviewComponent,\n })\n}\n\n/**\n * @internal\n */\nexport function usePreviewComponent(): ComponentType<Omit<PreviewProps, 'renderDefault'>> {\n return useMiddlewareComponents({\n defaultComponent: DefaultPreview,\n pick: pickPreviewComponent,\n })\n}\n","import {useContext} from 'react'\nimport {PerspectiveContext} from 'sanity/_singletons'\n\nimport {type PerspectiveContextValue} from './types'\n\n/**\n * @beta\n *\n * React hook that returns the current studio perspective and perspective stack.\n *\n * This will use the closest PerspectiveContext provider, which is either the global\n * PerspectiveContext or the DocumentPerspectiveProvider.\n *\n * @returns See {@link PerspectiveContextValue}\n * @example Reading the current perspective stack\n * ```ts\n * function MyComponent() {\n * const {perspectiveStack} = usePerspective()\n * // ... do something with the perspective stack , like passing it to the client perspective.\n * }\n * ```\n */\nexport function usePerspective(): PerspectiveContextValue {\n const context = useContext(PerspectiveContext)\n if (!context) {\n throw new Error('usePerspective must be used within a PerspectiveProvider')\n }\n return context\n}\n","import {type SanityDocument} from '@sanity/client'\nimport {type SanityDocumentLike} from '@sanity/types'\n\n/**\n * checks if the document has been set for unpublishing\n * @internal\n *\n * @param document - sanity document\n * @returns boolean if the system delete is set\n */\nexport function isGoingToUnpublish(document: SanityDocument | SanityDocumentLike): boolean {\n return Boolean(document._system?.delete === true)\n}\n","import {\n type PreviewValue,\n type SanityDocument,\n type SchemaType,\n type SortOrdering,\n} from '@sanity/types'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\nimport {type Observable, of} from 'rxjs'\nimport {catchError, map} from 'rxjs/operators'\n\nimport {type PerspectiveStack} from '../perspective/types'\nimport {usePerspective} from '../perspective/usePerspective'\nimport {isGoingToUnpublish} from '../releases/util/isGoingToUnpublish'\nimport {useDocumentPreviewStore} from '../store/datastores'\nimport {getPublishedId} from '../util/draftUtils'\nimport {type Previewable} from './types'\n\n/**\n * @internal\n * @deprecated use useValuePreview instead\n */\nexport const unstable_useValuePreview = useValuePreview\n\ninterface State {\n isLoading: boolean\n error?: Error\n value?: PreviewValue\n}\nconst INITIAL_STATE: State = {\n isLoading: true,\n}\n\nconst IDLE_STATE: State = {\n isLoading: false,\n value: {\n title: undefined,\n description: undefined,\n },\n}\n/**\n * @internal\n */\nexport function useValuePreview(props: {\n enabled?: boolean\n ordering?: SortOrdering\n schemaType?: SchemaType\n value: unknown | undefined\n perspectiveStack?: PerspectiveStack\n /**\n * The variant to preview the value as seen through, as a bare variant id.\n *\n * The variant travels with the perspective: when no `perspectiveStack` is given, both default to\n * the current selection in the perspective context. When a `perspectiveStack` is given, the\n * caller is previewing a specific document version and only the variant it passes here is used.\n */\n variant?: string\n}): State {\n const {\n enabled = true,\n ordering,\n schemaType,\n value: previewValue,\n perspectiveStack: chosenPerspectiveStack,\n variant: chosenVariant,\n } = props || {}\n const {observeForPreview} = useDocumentPreviewStore()\n const {perspectiveStack, selectedVariantName} = usePerspective()\n const observable = useMemo<Observable<State>>(() => {\n // this will render previews as \"loaded\" (i.e. not in loading state) – typically with \"Untitled\" text\n if (!enabled || !previewValue || !schemaType) return of(IDLE_STATE)\n\n const goingToUnpublish = isGoingToUnpublish(previewValue as SanityDocument)\n\n const updatedStack = goingToUnpublish ? [] : (chosenPerspectiveStack ?? perspectiveStack)\n // A document slated for unpublishing is previewed as its published version, which is outside\n // of any variant. Otherwise the variant follows the perspective: only inherited from the\n // context when the perspective is too.\n const updatedVariant = goingToUnpublish\n ? undefined\n : (chosenVariant ?? (chosenPerspectiveStack ? undefined : selectedVariantName))\n const updatedDocId = goingToUnpublish\n ? getPublishedId((previewValue as SanityDocument)._id)\n : (previewValue as SanityDocument)._id\n\n // allow for previewing the published document when a version is slated for unpublishing\n // but if it's not for unpublishing, then we want to preview the content as was before\n const restPreviewValue = goingToUnpublish\n ? {}\n : {\n ...(previewValue as Previewable),\n }\n\n return observeForPreview(\n {\n _id: updatedDocId,\n ...restPreviewValue,\n },\n schemaType,\n {\n perspective: updatedStack,\n variant: updatedVariant,\n viewOptions: {ordering: ordering},\n },\n ).pipe(\n map((event) => ({isLoading: false, value: event.snapshot || undefined})),\n catchError((error) => of({isLoading: false, error})),\n )\n }, [\n enabled,\n previewValue,\n schemaType,\n chosenPerspectiveStack,\n perspectiveStack,\n chosenVariant,\n selectedVariantName,\n observeForPreview,\n ordering,\n ])\n\n // Do not defer: search/reference UIs assert on preview titles synchronously after selection.\n return useSyncObservable(observable, INITIAL_STATE)\n}\n","import {EMPTY, fromEvent} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const orientationChange$ =\n typeof window === 'undefined'\n ? EMPTY\n : fromEvent(window, 'orientationchange').pipe(shareReplay(1))\n","import {EMPTY, fromEvent} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const resize$ =\n typeof window === 'undefined' ? EMPTY : fromEvent(window, 'resize').pipe(shareReplay(1))\n","import {EMPTY, fromEvent} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const scroll$ =\n typeof window === 'undefined'\n ? EMPTY\n : fromEvent(window, 'scroll', {passive: true, capture: true}).pipe(shareReplay(1))\n","import {merge, Observable, of as observableOf, Subject} from 'rxjs'\nimport {filter, map, mergeMap} from 'rxjs/operators'\n\nimport {orientationChange$} from './orientationChange'\nimport {resize$} from './resize'\nimport {scroll$} from './scroll'\n\nconst ROOT_MARGIN_PX = 150\n\n/*\n Adapted from the polyfill at https://github.com/WICG/IntersectionObserver\n*/\nfunction isIntersectionObserverSupported() {\n if (\n typeof window !== 'undefined' &&\n 'IntersectionObserver' in window &&\n 'IntersectionObserverEntry' in window &&\n 'intersectionRatio' in IntersectionObserverEntry.prototype\n ) {\n // Minimal polyfill for Edge 15's lack of `isIntersecting`\n // See: https://github.com/WICG/IntersectionObserver/issues/211\n if (!('isIntersecting' in IntersectionObserverEntry.prototype)) {\n Object.defineProperty(IntersectionObserverEntry.prototype, 'isIntersecting', {\n get() {\n return this.intersectionRatio > 0\n },\n })\n }\n return true\n }\n return false\n}\n\ntype IntersectionEvent = {isIntersecting: boolean}\n\nexport const intersectionObservableFor = isIntersectionObserverSupported()\n ? createIntersectionObserverBased()\n : createLegacyBased()\n\ntype IntersectionObservableFor = (element: Element) => Observable<IntersectionEvent>\n\nfunction createIntersectionObserverBased(): IntersectionObservableFor {\n const intersectionObserverEntriesSubject = new Subject<IntersectionObserverEntry>()\n\n const intersectionObserver = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n intersectionObserverEntriesSubject.next(entry)\n })\n },\n {\n threshold: 0,\n rootMargin: `${ROOT_MARGIN_PX}px`,\n },\n )\n\n return function intersectionObservableFor(element) {\n return new Observable<void>((observer) => {\n intersectionObserver.observe(element)\n observer.next()\n return () => intersectionObserver.unobserve(element)\n }).pipe(\n mergeMap(() => intersectionObserverEntriesSubject.asObservable()),\n filter((entry: IntersectionObserverEntry) => entry.target === element),\n map((ev) => ({\n isIntersecting: ev.isIntersecting,\n })),\n )\n }\n}\n\n// This can be removed when intersection observer are supported by the browsers we support\nfunction createLegacyBased() {\n function getViewport() {\n return {\n left: 0,\n right: window.innerWidth,\n top: 0,\n bottom: window.innerHeight,\n }\n }\n\n function intersects(\n rect: DOMRect,\n viewport: {left: number; right: number; top: number; bottom: number},\n margin: number,\n ) {\n return (\n rect.left <= viewport.right + margin &&\n rect.right >= viewport.left - margin &&\n rect.top <= viewport.bottom + margin &&\n rect.bottom >= viewport.top - margin\n )\n }\n\n function inViewport(element: HTMLElement) {\n return () => intersects(element.getBoundingClientRect(), getViewport(), ROOT_MARGIN_PX)\n }\n\n return function intersectionObservableFor(element: HTMLElement): Observable<IntersectionEvent> {\n const isElementInViewport = inViewport(element)\n return merge(observableOf(isElementInViewport()), resize$, scroll$, orientationChange$).pipe(\n // @todo: consider \"faking\" more of the IntersectionObserverEntry api if possible\n map(isElementInViewport),\n map((isIntersecting) => ({isIntersecting})),\n )\n }\n}\n","import {EMPTY, fromEvent, type Observable} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const visibilityChange$: Observable<Event> =\n typeof window === 'undefined'\n ? EMPTY\n : fromEvent(document, 'visibilitychange').pipe(shareReplay(1))\n","import {useMemo} from 'react'\nimport {useObservable} from 'react-rx'\nimport {concat, of} from 'rxjs'\nimport {delay, distinctUntilChanged, map, startWith, switchMap} from 'rxjs/operators'\n\nimport {intersectionObservableFor} from './streams/intersectionObservableFor'\nimport {visibilityChange$} from './streams/visibilityChange'\n\ninterface Props {\n /**\n * Disable the check. The hook will return false if disabled\n */\n disabled?: boolean\n /** DOM Node to check visibility for */\n element: HTMLElement | null\n /** When element is hidden, wait this delay in milliseconds before reporting it as */\n hideDelay?: number\n}\n\nexport function useVisibility(props: Props): boolean {\n const {element, hideDelay = 0, disabled} = props\n\n const visible$ = useMemo(() => {\n if (!element || disabled) {\n return of(false)\n }\n\n // Seed with the element's current visibility so the first paint is\n // correct — every code path here emits synchronously on subscribe, so\n // useSyncObservable's fallback initial value is never read.\n const seed = 'checkVisibility' in element ? element.checkVisibility() : false\n\n const isDocumentVisible$ = concat(\n of(!document.hidden),\n visibilityChange$.pipe(\n map((event) => (event.target instanceof Document ? !event?.target?.hidden : false)),\n ),\n ).pipe(distinctUntilChanged())\n\n const inViewport$ = intersectionObservableFor(element).pipe(\n map((event) => event.isIntersecting),\n )\n\n return isDocumentVisible$.pipe(\n switchMap((isDocumentVisible) => (isDocumentVisible ? inViewport$ : of(false))),\n switchMap((isVisible) => (isVisible ? of(true) : of(false).pipe(delay(hideDelay)))),\n distinctUntilChanged(),\n startWith(seed),\n )\n }, [element, hideDelay, disabled])\n\n const visible = useObservable(visible$, false)\n\n return disabled ? false : visible\n}\n","export const _HIDE_DELAY = 1000 * 2 // 2 seconds\n","import {type UploadState} from '@sanity/types'\n\nimport {isRecord} from '../../util/isRecord'\nimport {isString} from '../../util/isString'\n\nexport function _extractUploadState(value: any): UploadState | undefined {\n return _resolveUploadValue(value?._upload)\n}\n\nfunction getStringOrUndefined(value: unknown): string | undefined {\n return isString(value) ? value : undefined\n}\nfunction _resolveUploadValue(value: unknown): UploadState | undefined {\n if (!isRecord(value)) return undefined\n\n const progress = typeof value.progress === 'number' ? value.progress : 0\n const createdAt = getStringOrUndefined(value.initiated || value.createdAt)\n const updatedAt = getStringOrUndefined(value.updated || value.updatedAt)\n const fileName = getStringOrUndefined((value?.file as any)?.name)\n const fileType = getStringOrUndefined((value?.file as any)?.type)\n const previewImage = getStringOrUndefined(value.previewImage)\n\n if (createdAt && updatedAt && fileName && fileType) {\n return {\n progress,\n createdAt,\n updatedAt,\n file: {name: fileName, type: fileType},\n previewImage,\n }\n }\n\n return undefined\n}\n","import {type ComponentType, type CSSProperties, useMemo, useState} from 'react'\n\nimport {type PreviewProps} from '../../components/previews/types'\nimport {type RenderPreviewCallbackProps} from '../../form/types/renderCallback'\nimport {useTranslation} from '../../i18n/hooks/useTranslation'\nimport {type PerspectiveStack} from '../../perspective/types'\nimport {useValuePreview} from '../useValuePreview'\nimport {useVisibility} from '../useVisibility'\nimport {_HIDE_DELAY} from './_constants'\nimport {_extractUploadState} from './_extractUploadState'\n\n/**\n * This component is responsible for converting renderPreview() calls into an element.\n * It:\n * - subscribes to \"prepared\" preview value as long as the element is visible on screen\n * - resolves the configured preview component for the schema type\n * - prepares \"preview\"-props and passes this to the configured preview component\n * @internal\n * */\nexport function PreviewLoader(\n props: RenderPreviewCallbackProps & {\n component: ComponentType<Omit<PreviewProps, 'renderDefault'>>\n perspectiveStack?: PerspectiveStack\n variant?: string\n },\n): React.JSX.Element {\n const {\n layout,\n value,\n component: Component,\n style: styleProp,\n schemaType,\n skipVisibilityCheck,\n perspectiveStack,\n variant,\n ...restProps\n } = props\n\n const {t} = useTranslation()\n const [element, setElement] = useState<HTMLDivElement | null>(null)\n\n // Subscribe to visibility\n const isVisible =\n useVisibility({\n disabled: skipVisibilityCheck,\n element: element,\n hideDelay: _HIDE_DELAY,\n }) || skipVisibilityCheck\n\n // Subscribe document preview value\n const preview = useValuePreview({\n enabled: skipVisibilityCheck || isVisible,\n schemaType,\n value,\n perspectiveStack,\n variant,\n })\n\n const style: CSSProperties = useMemo(\n () => ({\n ...styleProp,\n minWidth: styleProp?.minWidth || 1,\n minHeight: styleProp?.minHeight || 1,\n }),\n [styleProp],\n )\n\n const uploadState = useMemo(() => _extractUploadState(value), [value])\n\n const media: PreviewProps['media'] = useMemo(() => {\n if (uploadState?.previewImage) {\n return (\n <img\n alt={t('preview.image.file-is-being-uploaded.alt-text')}\n src={uploadState.previewImage}\n />\n )\n }\n\n // media: null or false explicitly suppresses the icon.\n // All other falsy cases (undefined, missing key) fall back to the schema icon.\n if (preview?.value?.media === null || preview?.value?.media === false) {\n return undefined\n }\n\n if (!preview?.value?.media) {\n return schemaType.icon\n }\n\n // @todo: fix `TS2769: No overload matches this call.`\n return preview?.value?.media as any\n }, [preview, schemaType, uploadState, t])\n\n return (\n <div ref={setElement} style={style}>\n <Component\n {...restProps}\n {...(preview?.value || {})}\n media={media}\n error={preview?.error}\n isPlaceholder={preview?.isLoading}\n layout={layout}\n schemaType={schemaType}\n />\n </div>\n )\n}\n","import {usePreviewComponent} from '../../form/form-components-hooks/usePreviewComponent'\nimport {type RenderPreviewCallbackProps} from '../../form/types/renderCallback'\nimport {type PerspectiveStack} from '../../perspective/types'\nimport {PreviewLoader} from './PreviewLoader'\n\n/**\n * @internal\n */\nexport function Preview(\n props: RenderPreviewCallbackProps & {perspectiveStack?: PerspectiveStack; variant?: string},\n) {\n const PreviewComponent = usePreviewComponent()\n return <PreviewLoader {...props} component={PreviewComponent} />\n}\n","import {useSource} from '../studio/source'\n\n/**\n * React hook that returns the name of the current dataset\n *\n * @public\n * @returns The name of the current dataset\n * @example Using the `useDataset` hook\n * ```ts\n * function MyComponent() {\n * const dataset = useDataset()\n * // ... do something with the dataset name ...\n * }\n * ```\n */\nexport function useDataset(): string {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n return useSource().dataset\n}\n","import {type ReleaseDocument} from '@sanity/client'\nimport {getVersionFromId} from '@sanity/client/csm'\nimport {type DocumentSystem} from '@sanity/types'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\nimport {\n catchError,\n combineLatest,\n finalize,\n map,\n type Observable,\n of,\n ReplaySubject,\n share,\n startWith,\n switchMap,\n timer,\n} from 'rxjs'\n\nimport {useDataset} from '../../hooks/useDataset'\nimport {useProjectId} from '../../hooks/useProjectId'\nimport {DOCUMENT_SYSTEM_FIELD} from '../../preview/constants'\nimport {type DocumentPreviewStore} from '../../preview/documentPreviewStore'\nimport {useDocumentPreviewStore} from '../../store/datastores'\nimport {isDraftId, getPublishedId} from '../../util/draftUtils'\nimport {isRecord} from '../../util/isRecord'\nimport {createSWR} from '../../util/rxSwr'\nimport {type VersionInfoDocumentStub} from '../store/types'\nimport {useReleasesStore} from '../store/useReleasesStore'\nimport {ARCHIVED_RELEASE_STATES} from '../util/const'\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\n\nexport interface DocumentPerspectiveProps {\n documentId: string\n}\n\nexport interface DocumentPerspectiveState {\n data: string[]\n versions: VersionInfoDocumentStub[]\n error?: unknown\n loading: boolean\n}\n\nconst INITIAL_VALUE: DocumentPerspectiveState = {\n data: [],\n versions: [],\n error: null,\n loading: true,\n}\n\n// Create a singleton cache for observables\nexport const observableCache = new Map<string, Observable<DocumentPerspectiveState>>()\n// releases flow via combineLatest, never in the cache key, to avoid cache thrash on every release edit\nexport const withSystemCache = new Map<string, Observable<DocumentPerspectiveState>>()\nconst swr = createSWR<string[]>({maxSize: 100})\n\n// How long to keep the pipeline alive after the last subscriber unsubscribes.\n// Subscriber churn (components re-rendering/remounting around commits) can\n// momentarily drop the refcount to zero. A bare teardown deletes the cache\n// entry, and the re-created pipeline synchronously re-enters the\n// `startWith(loadingState)` path (the version id set is non-empty for any\n// document with a draft or published variant), so `loading: true` reaches\n// `useDocumentForm`'s `ready` gate and flips the form read-only until the\n// `observePaths` round trip settles — silently swallowing keystrokes typed in\n// that window.\nconst TEARDOWN_GRACE_PERIOD = 1_000\n\n/**\n * Fetches the document versions for a given document\n *\n * @param props - document Id of the document (might include release id)\n * @returns - data: document versions, loading, errors\n * @hidden\n * @beta\n */\nexport function useDocumentVersions(props: DocumentPerspectiveProps): DocumentPerspectiveState {\n const observable = useDocumentVersionsObservable(props)\n // Kept synchronous: `useTargetDocumentState` / `useDocumentForm` derive the\n // pair-checkout scope and the form's ready gate from this state, so a\n // deferred snapshot could bind the form to the wrong version scope after\n // navigation or a version change.\n return useSyncObservable(observable, INITIAL_VALUE)\n}\n\n/**\n * Creates an observable that emits the document versions for a given document.\n *\n * @hidden\n * @beta\n */\nexport function useDocumentVersionsObservable(\n props: DocumentPerspectiveProps,\n): Observable<DocumentPerspectiveState> {\n const {documentId} = props\n const publishedId = getPublishedId(documentId)\n\n const dataset = useDataset()\n const projectId = useProjectId()\n const documentPreviewStore = useDocumentPreviewStore()\n const {state$: releasesState$} = useReleasesStore()\n\n const releases$ = useMemo(\n () =>\n releasesState$.pipe(\n map((state) =>\n Array.from(state.releases.values()).filter(\n (release) => !ARCHIVED_RELEASE_STATES.includes(release.state),\n ),\n ),\n ),\n [releasesState$],\n )\n\n const observable: Observable<DocumentPerspectiveState> = useMemo(\n () =>\n getOrCreateDocumentVersionsWithSystemObservable({\n documentPreviewStore,\n publishedId,\n projectId,\n dataset,\n releases$,\n }),\n [dataset, documentPreviewStore, projectId, publishedId, releases$],\n )\n\n return observable\n}\n\n/**\n * Temporarily builds the document _system for a given document id.\n * This is used until the documents are migrated to the new _system.\n * And only if the documents are not variant documents.\n *\n * Variants will include the _system field.\n */\nconst buildDocumentSystem = (id: string, releases: ReleaseDocument[]): DocumentSystem => {\n const versionId = getVersionFromId(id)\n if (versionId) {\n const releaseDocument = releases.find(\n (release) => getReleaseIdFromReleaseDocumentId(release._id) === versionId,\n )\n return {\n bundleId: versionId,\n release: releaseDocument ? {_ref: releaseDocument._id, _weak: true} : undefined,\n group: {\n _ref: getPublishedId(id),\n _weak: true,\n },\n scopeId: versionId,\n }\n }\n\n return {\n bundleId: isDraftId(id) ? 'drafts' : undefined,\n group: {_ref: getPublishedId(id), _weak: true},\n }\n}\n\nconst resolveVersionSystem = (\n version: VersionInfoDocumentStub,\n releases: ReleaseDocument[],\n): DocumentSystem => {\n if (version._system?.group) return version._system\n\n return {\n ...version._system,\n ...buildDocumentSystem(version._id, releases),\n }\n}\n\nconst DOCUMENT_STUB_PATHS = ['_id', '_type', '_rev', '_createdAt', '_updatedAt', '_system']\n\nfunction getOrCreateCachedObservable<T>(\n cache: Map<string, Observable<T>>,\n cacheKey: string,\n createObservable: () => Observable<T>,\n): Observable<T> {\n const cached = cache.get(cacheKey)\n if (cached) return cached\n\n const observable = createObservable().pipe(\n finalize(() => cache.delete(cacheKey)),\n share({\n connector: () => new ReplaySubject(1),\n resetOnRefCountZero: () => timer(TEARDOWN_GRACE_PERIOD),\n }),\n )\n\n cache.set(cacheKey, observable)\n return observable\n}\n\nexport function getOrCreateDocumentVersionsWithSystemObservable(options: {\n documentPreviewStore: DocumentPreviewStore\n publishedId: string\n projectId: string\n dataset: string\n releases$: Observable<ReleaseDocument[]>\n}): Observable<DocumentPerspectiveState> {\n const {documentPreviewStore, projectId, dataset, publishedId, releases$} = options\n const cacheKey = `${projectId}-${dataset}-${publishedId}`\n\n return getOrCreateCachedObservable(withSystemCache, cacheKey, () =>\n combineLatest([\n getOrCreateDocumentVersionsObservable({\n documentPreviewStore,\n publishedId,\n projectId,\n dataset,\n }),\n releases$,\n ]).pipe(\n map(([result, releases]) => ({\n ...result,\n versions: result.versions.map((version) => ({\n ...version,\n [DOCUMENT_SYSTEM_FIELD]: resolveVersionSystem(version, releases),\n })),\n })),\n ),\n )\n}\n\n/**\n * Retrieves an observable that emits document IDs matching the document versions that exist for a specific id\n *\n * @param options - The options for creating or retrieving the observable.\n * options.documentPreviewStore - The store used to observe document IDs.\n * options.publishedId - The ID of the published document.\n * options.projectId - The project ID.\n * options.dataset - The dataset name.\n * @returns An observable that emits the document versions.\n *\n * @hidden\n * @internal\n */\nexport function getOrCreateDocumentVersionsObservable(options: {\n documentPreviewStore: DocumentPreviewStore\n publishedId: string\n projectId: string\n dataset: string\n}): Observable<DocumentPerspectiveState> {\n const {documentPreviewStore, projectId, dataset, publishedId} = options\n const cacheKey = `${projectId}-${dataset}-${publishedId}`\n\n return getOrCreateCachedObservable(observableCache, cacheKey, () =>\n documentPreviewStore.unstable_observeVersionDocumentIds(publishedId).pipe(\n swr(cacheKey),\n map(({value}) => value),\n switchMap((documentIds, index): Observable<DocumentPerspectiveState> => {\n if (documentIds.length === 0) {\n return of({data: [], versions: [], error: null, loading: false})\n }\n\n const versions$ = combineLatest(\n documentIds.map((id) =>\n documentPreviewStore.observePaths({_id: id}, DOCUMENT_STUB_PATHS).pipe(\n map((versionInfo) => (isRecord(versionInfo) ? versionInfo : undefined)),\n map(\n (versionInfo) =>\n ({\n _id: id,\n _rev: versionInfo?._rev ?? '',\n _createdAt: versionInfo?._createdAt ?? '',\n _updatedAt: versionInfo?._updatedAt ?? '',\n [DOCUMENT_SYSTEM_FIELD]: versionInfo?.[DOCUMENT_SYSTEM_FIELD] as DocumentSystem,\n }) satisfies VersionInfoDocumentStub,\n ),\n ),\n ),\n ).pipe(\n map((versions) => ({\n data: documentIds,\n versions,\n error: null,\n loading: false,\n })),\n )\n\n // Only the pipeline's very first id-set emission is a cold start that must block\n // with `loading: true` (it gates `useDocumentForm`'s `ready` state). Later id-set\n // changes happen while the user is editing — e.g. the draft id appearing on the\n // first keystroke in a new document, or publish swapping draft for published — and\n // re-emitting `loading: true` then would flip the whole form read-only mid-typing,\n // silently dropping keystrokes and DOM focus. Keep replaying the last loaded state\n // until the fresh stubs arrive instead.\n if (index > 0) {\n return versions$\n }\n\n const loadingState: DocumentPerspectiveState = {\n data: documentIds,\n versions: [],\n error: null,\n loading: true,\n }\n\n return versions$.pipe(startWith(loadingState))\n }),\n catchError((error) => {\n return of({\n error,\n data: [] as string[],\n versions: [] as VersionInfoDocumentStub[],\n loading: false,\n })\n }),\n ),\n )\n}\n","import {useContext} from 'react'\nimport {ActiveWorkspaceMatcherContext} from 'sanity/_singletons'\n\nimport {type ActiveWorkspaceMatcherContextValue} from './ActiveWorkspaceMatcherContext'\n\n/** @internal */\nexport function useActiveWorkspace(): ActiveWorkspaceMatcherContextValue {\n const value = useContext(ActiveWorkspaceMatcherContext)\n if (!value) throw new Error('Could not find `ActiveWorkspaceMatcher` context')\n return value\n}\n","import {\n type CanvasResource,\n type Events,\n type MediaResource,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useComlinkStore} from '../store/datastores'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n}\n\n/**\n * @public\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * IMPORTANT!\n *\n * Based on the `useRecordDocumentHistoryEvent.ts` from `@sanity/sdk`.\n * This version has been lightly modified to use Studio's Comlink Store.\n *\n * TODO: Adopt `@sanity/sdk` when a compatible version is available.\n *\n * ---\n *\n * Hook for managing document interaction history in Sanity Studio.\n * This hook provides functionality to record document interactions.\n *\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n * - `isConnected` - Boolean indicating if connection to Studio is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent, isConnected} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => recordEvent('viewed')}\n * text={'Viewed'}\n * />\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const {node} = useComlinkStore()\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n // The run() wrapper is a workaround for React Compiler not yet fully supporting try/catch syntax\n const run = () => {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n node?.post?.(message.type, message.data)\n }\n try {\n run()\n } catch (error) {\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, schemaName, node],\n )\n\n return {\n recordEvent,\n }\n}\n","import {useCallback, useMemo, useState} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {useRenderingContextStore} from '../store/datastores'\nimport {type OperationsAPI} from '../store/document/document-pair/operations/types'\nimport {useActiveWorkspace} from '../studio/activeWorkspaceMatcher/useActiveWorkspace'\nimport {getVersionId} from '../util/draftUtils'\nimport {useRecordDocumentHistoryEvent} from './useRecordDocumentHistoryEvent'\n\ninterface Options {\n api: OperationsAPI\n publishedDocId: string\n docTypeName: string\n version?: string\n}\n\n/**\n * Decorate operations API methods with Comlink history capture when relevant operations are executed.\n *\n * Event capture only occurs when Comlink is available.\n *\n * @internal\n */\nexport function useDocumentOperationWithComlinkHistory({\n api,\n publishedDocId,\n docTypeName,\n version,\n}: Options): OperationsAPI {\n const {activeWorkspace} = useActiveWorkspace()\n\n const {recordEvent} = useRecordDocumentHistoryEvent({\n resourceType: 'studio',\n documentId: version ? getVersionId(publishedDocId, version) : publishedDocId,\n documentType: docTypeName,\n resourceId: [activeWorkspace.projectId, activeWorkspace.dataset].join('.'),\n schemaName: activeWorkspace.name,\n })\n\n const renderingContextStore = useRenderingContextStore()\n // Kept synchronous: capabilities emit once at boot and gate whether\n // operations are decorated with comlink history capture; deferring only\n // delays the decoration.\n const capabilities = useSyncObservable(renderingContextStore.capabilities)\n\n // Used to prevent redundant `edited` events being recorded.\n const [hasRecordedEdit, setHasRecordedEdit] = useState<boolean>(false)\n\n // Record history for only the first edit to occur, to avoid inundating Dashboard history.\n const preRecordPatch = useCallback<PreRecordEvent>(\n (next) => {\n if (hasRecordedEdit) {\n return\n }\n next()\n setHasRecordedEdit(true)\n },\n [hasRecordedEdit],\n )\n\n const comlinkContext = useMemo(\n () => ({\n hasComlink: capabilities?.comlink,\n recordEvent,\n }),\n [capabilities?.comlink, recordEvent],\n )\n\n const withComlinkDelete = useMemo(\n () =>\n withComlinkEvent({\n ...comlinkContext,\n operationName: 'delete',\n comlinkEventType: 'deleted',\n }),\n [comlinkContext],\n )\n\n const withComlinkDel = useMemo(\n () =>\n withComlinkEvent({\n ...comlinkContext,\n operationName: 'del',\n comlinkEventType: 'deleted',\n }),\n [comlinkContext],\n )\n\n const withComlinkPatch = useMemo(\n () =>\n withComlinkEvent({\n ...comlinkContext,\n operationName: 'patch',\n comlinkEventType: 'edited',\n preRecordEvent: preRecordPatch,\n }),\n [comlinkContext, preRecordPatch],\n )\n\n return withComlinkDelete(withComlinkDel(withComlinkPatch(api)))\n}\n\ntype ComlinkEventType = Parameters<\n ReturnType<typeof useRecordDocumentHistoryEvent>['recordEvent']\n>[0]\n\ntype ExecuteParameters<OperationName extends keyof OperationsAPI> = Parameters<\n OperationsAPI[OperationName]['execute']\n>\n\ntype RecordEvent = ReturnType<typeof useRecordDocumentHistoryEvent>['recordEvent']\n\ntype PreRecordEvent = (next: () => void) => void\n\ninterface WithComlinkEventOptions<OperationName extends keyof OperationsAPI> {\n operationName: OperationName\n comlinkEventType: ComlinkEventType\n hasComlink?: boolean\n recordEvent: RecordEvent\n preRecordEvent?: PreRecordEvent\n}\n\n/**\n * Decorate the provided API method with Comlink history capture.\n */\nfunction withComlinkEvent<OperationName extends keyof OperationsAPI>({\n operationName,\n comlinkEventType,\n hasComlink,\n recordEvent,\n preRecordEvent = (next) => next(),\n}: WithComlinkEventOptions<OperationName>): (api: OperationsAPI) => OperationsAPI {\n return function (api) {\n if (!hasComlink) {\n return api\n }\n\n return {\n ...api,\n [operationName]: {\n ...api[operationName],\n execute: (...args: ExecuteParameters<OperationName>) => {\n const next = () => recordEvent(comlinkEventType)\n preRecordEvent(next)\n api[operationName].execute(...args)\n },\n },\n }\n }\n}\n","import {useMemo} from 'react'\n\nimport {normalizeDocumentPairTarget} from '../store/document/normalizeDocumentPairTarget'\nimport {type DocumentPairTarget} from '../store/document/types'\n\n/**\n * Returns a referentially stable {@link DocumentPairTarget} for the document pair APIs.\n *\n * Callers commonly build the target inline on every render (e.g. via `getPairTarget(...)`), so\n * keying a memo on the target object directly would recreate it every time — and resubscribing\n * `pair.editOperations` re-checks out the pair. This hook destructures the target into its\n * primitives and memoizes the object on them, so the returned reference only changes when the\n * target's contents change.\n *\n * A bare string is back-compat shorthand for a plain version target (its scope id, i.e. the\n * `<scopeId>` segment of `versions.<scopeId>.<groupId>`); `undefined` means the base\n * draft/published pair.\n *\n * @internal\n */\nexport function useMemoizedDocumentPairTarget(\n version: string | DocumentPairTarget | undefined,\n): DocumentPairTarget | undefined {\n const target = normalizeDocumentPairTarget(version)\n const kind = target?.kind\n const scopeId =\n target?.kind === 'version' || target?.kind === 'variant' ? target.scopeId : undefined\n const variantId =\n target?.kind === 'variant' || target?.kind === 'target-missing' ? target.variantId : undefined\n const allowCreate = target?.kind === 'variant' ? target.allowCreate : undefined\n\n return useMemo((): DocumentPairTarget | undefined => {\n switch (kind) {\n case 'version':\n return {kind: 'version', scopeId: scopeId!}\n case 'variant':\n // Preserve the input shape exactly: no `allowCreate: undefined` key when none was given.\n return allowCreate === undefined\n ? {kind: 'variant', scopeId: scopeId!, variantId: variantId!}\n : {kind: 'variant', scopeId: scopeId!, variantId: variantId!, allowCreate}\n case 'target-missing':\n // Preserve the input shape exactly: no `variantId: undefined` key when none was given.\n return variantId === undefined\n ? {kind: 'target-missing'}\n : {kind: 'target-missing', variantId}\n case 'unresolved':\n return {kind: 'unresolved'}\n default:\n return undefined\n }\n }, [kind, scopeId, variantId, allowCreate])\n}\n","import {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {useDocumentStore} from '../store/datastores'\nimport {type OperationsAPI} from '../store/document/document-pair/operations/types'\nimport {type DocumentPairTarget} from '../store/document/types'\nimport {useDocumentOperationWithComlinkHistory} from './useDocumentOperationWithComlinkHistory'\nimport {useMemoizedDocumentPairTarget} from './useMemoizedDocumentPairTarget'\n\n/**\n * @internal\n * `version` accepts either a plain version name (release/bundle) or a {@link DocumentPairTarget}\n * declaring the resolved target of the selected perspective/variant. With the guarded target\n * kinds (`unresolved`, `target-missing`) the returned operations are disabled and throw if\n * executed, instead of silently operating on the base draft/published pair.\n */\nexport function useDocumentOperation(\n publishedDocId: string,\n docTypeName: string,\n version?: string | DocumentPairTarget,\n): OperationsAPI {\n const documentStore = useDocumentStore()\n\n // A referentially stable target: a caller passing a fresh target object on every render must\n // not recreate the observable (which would resubscribe the pair).\n const target = useMemoizedDocumentPairTarget(version)\n\n const observable = useMemo(\n () => documentStore.pair.editOperations(publishedDocId, docTypeName, target),\n [docTypeName, documentStore.pair, publishedDocId, target],\n )\n\n /**\n * We know that since the observable has a startWith operator, it will always emit a value\n * and that's why the non-null assertion is used here\n *\n * Kept synchronous: the operations are imperative emitters bound to the\n * document id/type they were created for, so a deferred (stale) API could\n * execute an action against the previously viewed document after navigation.\n */\n const api = useSyncObservable(observable)!\n\n return useDocumentOperationWithComlinkHistory({\n api,\n docTypeName,\n publishedDocId,\n })\n}\n","import {type PerspectiveBundle} from '../perspective/types'\nimport {type DocumentPerspectiveState} from '../releases/hooks/useDocumentVersions'\nimport {type VersionInfoDocumentStub} from '../releases/store/types'\n\n/**\n * Finds the document version whose _system metadata matches the selected bundle and variant.\n *\n * `bundle` must be the canonical bundle id (`published`, `drafts` or a release id), matching\n * `_system.bundleId` exactly. For example, `bundle: 'published'` and `variant: undefined` matches\n * a version with no `bundleId` and `variant: null`.\n *\n * @internal\n */\nexport function getTargetDocument({\n bundle,\n documentVersions,\n variant,\n}: {\n variant: string | undefined\n bundle: PerspectiveBundle\n documentVersions: DocumentPerspectiveState['versions']\n}): VersionInfoDocumentStub | undefined {\n return documentVersions.find((version) => {\n const inBundle =\n bundle === 'published' ? !version._system.bundleId : version._system.bundleId === bundle\n const inVariant = variant ? version._system.variant?._ref === variant : !version._system.variant\n return inBundle && inVariant\n })\n}\n\n/**\n * Finds the variant-of-published sibling for a variant: the version stub carrying the same\n * `_system.variant` reference but no `_system.bundleId` (i.e. the published variant document).\n *\n * This is the document that publish-state gating must read for variant targets — the base\n * `published` document says nothing about whether the *variant* is published. `undefined` means\n * the variant has never been published.\n *\n * @internal\n */\nexport function getVariantPublishedSibling({\n documentVersions,\n variant,\n}: {\n variant: string\n documentVersions: DocumentPerspectiveState['versions']\n}): VersionInfoDocumentStub | undefined {\n return getTargetDocument({bundle: 'published', variant, documentVersions})\n}\n","import {type SystemVariant} from '../types'\n\ninterface VariantDeletedAction {\n type: 'VARIANT_DELETED'\n payload: {\n id: string\n }\n}\n\ninterface FetchSucceededAction {\n type: 'FETCH_SUCCEEDED'\n payload: SystemVariant[] | null\n}\ninterface VariantsSetAction {\n type: 'VARIANTS_SET'\n payload: SystemVariant[] | null\n}\n\ninterface LoadingStateChangedAction {\n type: 'LOADING_STATE_CHANGED'\n payload: {\n loading: boolean\n error: Error | undefined\n }\n}\n\nexport type VariantStoreAction =\n | VariantsSetAction\n | LoadingStateChangedAction\n | VariantDeletedAction\n | FetchSucceededAction\n\nexport interface VariantStoreState {\n variants: Map<string, SystemVariant>\n state: 'initialising' | 'loading' | 'loaded' | 'error'\n error?: Error\n}\n\nfunction createVariantsSet(variants: SystemVariant[] | null) {\n return (variants ?? []).reduce((acc, variant) => {\n acc.set(variant._id, variant)\n return acc\n }, new Map<string, SystemVariant>())\n}\n\nexport function variantStoreReducer(\n state: VariantStoreState,\n action: VariantStoreAction,\n): VariantStoreState {\n switch (action.type) {\n case 'LOADING_STATE_CHANGED': {\n return {\n ...state,\n state: action.payload.error ? 'error' : action.payload.loading ? 'loading' : 'loaded',\n error: action.payload.error,\n }\n }\n\n case 'VARIANTS_SET': {\n const variantsById = createVariantsSet(action.payload)\n\n return {\n ...state,\n variants: variantsById,\n }\n }\n case 'FETCH_SUCCEEDED': {\n const variantsById = createVariantsSet(action.payload)\n return {\n ...state,\n variants: variantsById,\n state: 'loaded',\n error: undefined,\n }\n }\n\n case 'VARIANT_DELETED': {\n const {id} = action.payload\n const restVariants = new Map(state.variants)\n restVariants.delete(id)\n\n return {\n ...state,\n variants: restVariants,\n }\n }\n\n default:\n return state\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type Dispatch} from 'react'\nimport {catchError, concatWith, merge, type Observable, of, scan, shareReplay, Subject} from 'rxjs'\nimport {map, startWith} from 'rxjs/operators'\n\nimport {listenQuery} from '../../store/document/listenQuery'\nimport {VARIANT_DOCUMENTS_PATH, VARIANT_DOCUMENT_TYPE} from './constants'\nimport {variantStoreReducer, type VariantStoreAction, type VariantStoreState} from './reducer'\n\nconst SORT_FIELD = '_createdAt'\nconst SORT_ORDER = 'desc'\n// Newest variants first\nconst QUERY_SORT_ORDER = `order(${SORT_FIELD} ${SORT_ORDER})`\nconst QUERY_FILTER = `_type==\"${VARIANT_DOCUMENT_TYPE}\" && _id in path(\"${VARIANT_DOCUMENTS_PATH}.*\")`\nconst QUERY_PROJECTION = `{\n _id,\n _type,\n _rev,\n _createdAt,\n _updatedAt,\n name,\n conditions,\n \"priority\": coalesce(priority, 0),\n metadata,\n}`\n\nconst QUERY = `*[${QUERY_FILTER}] ${QUERY_PROJECTION} | ${QUERY_SORT_ORDER}`\n\nconst INITIAL_STATE: VariantStoreState = {\n variants: new Map(),\n state: 'initialising' as const,\n}\n\nexport interface VariantStore {\n state$: Observable<VariantStoreState>\n dispatch: Dispatch<VariantStoreAction>\n}\n\n/**\n * The variants store is initialised lazily when first subscribed to. Upon subscription, it will\n * fetch a list of variants and create a listener to keep the locally held state fresh.\n *\n * The store is not disposed of when all subscriptions are closed. After it has been initialised,\n * it will keep listening for the duration of the app's lifecycle. Subsequent subscriptions will be\n * given the latest state upon subscription.\n */\nexport function createVariantsStore(context: {\n client: SanityClient\n enabled: boolean\n}): VariantStore {\n const {client, enabled} = context\n\n if (!enabled) {\n const disabledState: VariantStoreState = {\n variants: new Map(),\n state: 'loaded' as const,\n }\n\n return {\n state$: of(disabledState),\n dispatch: () => {\n // noop\n },\n }\n }\n\n const dispatch$ = new Subject<VariantStoreAction>()\n\n function dispatch(action: VariantStoreAction): void {\n dispatch$.next(action)\n }\n\n const listFetch$ = of<VariantStoreAction>({\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: true,\n error: undefined,\n },\n }).pipe(\n concatWith(\n listenQuery(client, QUERY, {}, {tag: 'variants.listen'}).pipe(\n map((variants): VariantStoreAction => ({type: 'FETCH_SUCCEEDED', payload: variants})),\n ),\n ),\n\n catchError((error) =>\n of<VariantStoreAction>({\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: false,\n error,\n },\n }),\n ),\n )\n\n const state$ = merge(listFetch$, dispatch$).pipe(\n scan((state, action) => variantStoreReducer(state, action), INITIAL_STATE),\n startWith(INITIAL_STATE),\n shareReplay(1),\n )\n\n return {\n state$,\n dispatch,\n }\n}\n","import {useMemo} from 'react'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useResourceCache} from '../../store/ResourceCacheProvider'\nimport {useWorkspace} from '../../studio/workspace'\nimport {VARIANTS_STUDIO_CLIENT_OPTIONS} from './constants'\nimport {createVariantsStore, type VariantStore} from './createVariantsStore'\n\n/** @internal */\nexport function useVariantsStore(): VariantStore {\n const workspace = useWorkspace()\n const variantsEnabled = Boolean(workspace.beta?.variants?.enabled)\n const resourceCache = useResourceCache()\n const studioClient = useClient(VARIANTS_STUDIO_CLIENT_OPTIONS)\n\n return useMemo(() => {\n const variantStore =\n resourceCache.get<VariantStore>({\n dependencies: [workspace],\n namespace: 'VariantsStore',\n }) ||\n createVariantsStore({\n client: studioClient,\n enabled: variantsEnabled,\n })\n\n resourceCache.set({\n dependencies: [workspace],\n namespace: 'VariantsStore',\n value: variantStore,\n })\n\n return variantStore\n }, [variantsEnabled, resourceCache, workspace, studioClient])\n}\n","import {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {type SystemVariant} from '../types'\nimport {useVariantsStore} from './useVariantsStore'\n\n/**\n * Gets all variants.\n * @internal\n */\nexport function useAllVariants(): {\n data: SystemVariant[]\n byId: Map<string, SystemVariant>\n error?: Error\n loading: boolean\n} {\n const {state$} = useVariantsStore()\n // Kept synchronous: variant resolution feeds `useTargetDocumentState`'s\n // target scope, so a deferred snapshot could bind the form checkout to the\n // wrong variant after navigation. Executable proof:\n // perspective/__tests__/deferralSafety.test.tsx.\n const {variants, error, state} = useSyncObservable(state$)!\n\n return useMemo(\n () => ({\n data: Array.from(variants.values()),\n byId: variants,\n error: error,\n loading: ['loading', 'initialising'].includes(state),\n }),\n [error, variants, state],\n )\n}\n","import {useMemo} from 'react'\n\nimport {type PerspectiveBundle} from '../perspective/types'\nimport {usePerspective} from '../perspective/usePerspective'\nimport {useDocumentVersions} from '../releases/hooks/useDocumentVersions'\nimport {type VersionInfoDocumentStub} from '../releases/store/types'\nimport {type DocumentPairTarget} from '../store/document/types'\nimport {getVersionFromId} from '../util/draftUtils'\nimport {getTargetDocument, getVariantPublishedSibling} from '../util/getTargetDocument'\nimport {useAllVariants} from '../variants/store/useAllVariants'\nimport {type SystemVariant} from '../variants/types'\n\n/**\n * The id and scope of a missing draft variant that can be created by typing: the id is known\n * ahead of creation because the variant-of-published sibling advertises it (`_system.draft`).\n *\n * @internal\n * @beta\n */\nexport interface CreatableTargetDocument {\n /** The full version id (`versions.<scopeId>.<groupId>`) the draft variant will occupy. */\n id: string\n /** The bundle segment of {@link CreatableTargetDocument.id}, for pair checkout. */\n scopeId: string\n}\n\n/**\n * The resolution state of the document targeted by the selected perspective (bundle) and variant.\n *\n * The union is shaped by what consumers must do, not just by what was observed:\n *\n * - `resolving` — a lookup (variant definitions or version stubs) is still in flight. Consumers\n * must not fall back to the base draft/published pair; treat the target as not ready.\n * - `ready` — resolution finished. `targetDocument` is the version stub matching the current\n * bundle (and variant, when one is selected); it is `undefined` only when no variant is\n * selected and no stub exists for the bundle, in which case base draft/published semantics\n * legitimately apply. `scopeId` is the bundle segment to thread into version-aware hooks\n * (release id for release stubs, opaque scope hash for variant stubs, `undefined` for the\n * base pair).\n * - `variant-missing` — a variant is selected but the document has no variant-scoped version\n * for the current bundle. When `creatableTarget` is set (drafts bundle, published variant\n * advertising its draft sibling id), the document is editable: typing creates the draft\n * variant at the advertised id, seeded from the published sibling. Otherwise consumers must\n * treat the document as read-only and offer creation. Never fall back to the base pair.\n * - `variant-definition-document-not-found` — the requested variant name matches no\n * `system.variant` definition. An error state, never silently treated as \"no variant\".\n *\n * @internal\n * @beta\n */\nexport type TargetDocumentState =\n | {status: 'resolving'}\n | {\n status: 'ready'\n targetDocument: VersionInfoDocumentStub | undefined\n scopeId: string | undefined\n /** The selected variant when the resolved target is a variant-scoped version. */\n variant: SystemVariant | undefined\n /**\n * The variant-of-published sibling stub (same `_system.variant`, no `_system.bundleId`).\n * Only set for variant targets; `undefined` means the variant has never been published.\n * Publish-state gating (already-published, unpublishable, discard copy) must read this\n * instead of the base `published` document.\n */\n publishedSibling: VersionInfoDocumentStub | undefined\n }\n | {\n status: 'variant-missing'\n variant: SystemVariant\n bundle: PerspectiveBundle\n /**\n * The variant-of-published sibling, when the variant is missing in the current bundle but\n * published. Lets consumers distinguish \"never existed\" from \"exists published, not in\n * this bundle\".\n */\n publishedSibling: VersionInfoDocumentStub | undefined\n /**\n * Present when the missing variant document can be created by typing: the drafts-bundle\n * variant of a published variant whose `_system.draft` weak ref advertises the (stable,\n * server-generated) id the draft will occupy. The pair is checked out at this id with\n * `allowCreate` declared to the store, and the display falls back to `publishedSibling`\n * until the document exists.\n */\n creatableTarget?: CreatableTargetDocument\n }\n | {status: 'variant-definition-document-not-found'; requestedVariantName: string}\n\nconst RESOLVING: TargetDocumentState = {status: 'resolving'}\n\n/**\n * Resolves the creatable draft variant for a missing target: only the drafts bundle qualifies\n * (release-scoped variants have no advertised draft refs yet, and the published bundle's missing\n * target *is* the sibling), and only when the variant-of-published sibling advertises\n * `_system.draft`. The id is server-advertised, never computed — this is what keeps the \"never\n * guess a variant scope id client-side\" invariant intact.\n */\nfunction getCreatableTarget(\n bundle: PerspectiveBundle,\n publishedSibling: VersionInfoDocumentStub | undefined,\n): CreatableTargetDocument | undefined {\n if (bundle !== 'drafts' || !publishedSibling) {\n return undefined\n }\n const draftId = publishedSibling._system.draft?._ref\n if (!draftId) {\n return undefined\n }\n const scopeId = getVersionFromId(draftId)\n if (!scopeId) {\n return undefined\n }\n return {id: draftId, scopeId}\n}\n\n/**\n * Returns the scope id to thread into version-aware hooks (`useEditState`,\n * `useDocumentOperation`, etc.) for a resolved target, or `undefined` when the target is not\n * ready or the base draft/published pair applies.\n *\n * A `variant-missing` state with a {@link CreatableTargetDocument} yields the creatable draft's\n * scope id: the pair is checked out at the advertised id from the beginning, so typing (and every\n * version-aware read: edit state, sync state, connection) addresses the document being created —\n * never the base pair, and never the published sibling.\n *\n * @internal\n * @beta\n */\nexport function getTargetScopeId(state: TargetDocumentState): string | undefined {\n if (state.status === 'ready') {\n return state.scopeId\n }\n if (state.status === 'variant-missing') {\n return state.creatableTarget?.scopeId\n }\n return undefined\n}\n\n/**\n * The creatable draft variant of a `variant-missing` state, or `undefined` for every other\n * state. Present when the missing target can be created by typing at a server-advertised id\n * (see {@link CreatableTargetDocument}); consumers use it to exempt the state from the\n * read-only/banner/footer gating that otherwise applies to unresolved variant targets.\n *\n * @internal\n * @beta\n */\nexport function getCreatableVariantTarget(\n state: TargetDocumentState,\n): CreatableTargetDocument | undefined {\n return state.status === 'variant-missing' ? state.creatableTarget : undefined\n}\n\n/**\n * Maps a {@link TargetDocumentState} to the `target` parameter of `useDocumentOperation` /\n * `pair.editOperations`, preserving the guarded states: `resolving` yields `unresolved`\n * (operations stay `NOT_READY`), and `variant-missing` / `variant-definition-document-not-found`\n * yield `target-missing` (operations disabled with `TARGET_NOT_FOUND`). Both throw if executed,\n * so operations can never silently fall back to the base draft/published pair.\n *\n * A `variant-missing` state with a {@link CreatableTargetDocument} yields a `variant` target with\n * `allowCreate`: the store keeps `patch`/`commit` enabled so typing creates the draft variant at\n * the advertised id, while publish/unpublish/discard stay disabled until the document exists.\n *\n * @internal\n * @beta\n */\nexport function getPairTarget(state: TargetDocumentState): DocumentPairTarget | string | undefined {\n switch (state.status) {\n case 'resolving':\n return {kind: 'unresolved'}\n case 'variant-missing':\n if (state.creatableTarget) {\n return {\n kind: 'variant',\n scopeId: state.creatableTarget.scopeId,\n variantId: state.variant._id,\n allowCreate: true,\n }\n }\n return {kind: 'target-missing', variantId: state.variant._id}\n case 'variant-definition-document-not-found':\n return {kind: 'target-missing'}\n case 'ready':\n if (state.variant) {\n // A resolved variant target always carries its scope id; treat a malformed stub without\n // one as missing rather than falling back to the base pair.\n return state.scopeId\n ? {kind: 'variant', scopeId: state.scopeId, variantId: state.variant._id}\n : {kind: 'target-missing', variantId: state.variant._id}\n }\n return state.scopeId\n default:\n return undefined\n }\n}\n\n/**\n * Pure resolution logic for {@link useTargetDocumentState}, extracted for testability.\n *\n * @internal\n */\nexport function getTargetDocumentState(options: {\n bundle: PerspectiveBundle\n selectedVariant: SystemVariant | undefined\n selectedVariantName: string | undefined\n variantsLoading: boolean\n versions: VersionInfoDocumentStub[]\n versionsLoading: boolean\n}): TargetDocumentState {\n const {bundle, selectedVariant, selectedVariantName, variantsLoading, versions, versionsLoading} =\n options\n\n if (!selectedVariantName) {\n if (versionsLoading) {\n return RESOLVING\n }\n const targetDocument = getTargetDocument({\n bundle,\n variant: undefined,\n documentVersions: versions,\n })\n return {\n status: 'ready',\n targetDocument,\n scopeId: targetDocument?._system.scopeId ?? undefined,\n variant: undefined,\n publishedSibling: undefined,\n }\n }\n\n if (variantsLoading) {\n return RESOLVING\n }\n\n if (!selectedVariant) {\n return {\n status: 'variant-definition-document-not-found',\n requestedVariantName: selectedVariantName,\n }\n }\n\n if (versionsLoading) {\n return RESOLVING\n }\n\n const targetDocument = getTargetDocument({\n bundle,\n variant: selectedVariant._id,\n documentVersions: versions,\n })\n\n const publishedSibling = getVariantPublishedSibling({\n variant: selectedVariant._id,\n documentVersions: versions,\n })\n\n if (!targetDocument) {\n return {\n status: 'variant-missing',\n variant: selectedVariant,\n bundle,\n publishedSibling,\n creatableTarget: getCreatableTarget(bundle, publishedSibling),\n }\n }\n\n return {\n status: 'ready',\n targetDocument,\n scopeId: targetDocument._system.scopeId ?? undefined,\n variant: selectedVariant,\n publishedSibling,\n }\n}\n\n/**\n * Resolves the document targeted by the selected perspective and variant for a document group,\n * as an explicit {@link TargetDocumentState}.\n *\n * Unlike a plain \"target document or undefined\" lookup, the returned state distinguishes the\n * in-flight lookups (`resolving`), the definitive absence of a variant-scoped version\n * (`variant-missing`), and an invalid variant selection\n * (`variant-definition-document-not-found`) from the legitimate base draft/published fallback\n * (`ready` without a target document). Consumers must switch on `status` instead of treating\n * `undefined` as \"no variant\".\n *\n * @internal\n * @beta\n */\nexport function useTargetDocumentState(documentGroupId: string): TargetDocumentState {\n const {versions, loading: versionsLoading} = useDocumentVersions({documentId: documentGroupId})\n const {bundle, selectedVariant, selectedVariantName} = usePerspective()\n const {loading: variantsLoading} = useAllVariants()\n\n return useMemo(\n () =>\n getTargetDocumentState({\n bundle,\n selectedVariant,\n selectedVariantName,\n variantsLoading,\n versions,\n versionsLoading,\n }),\n [bundle, selectedVariant, selectedVariantName, variantsLoading, versions, versionsLoading],\n )\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type SanityDocument, type Schema, type SchemaType} from '@sanity/types'\nimport {useMemo} from 'react'\nimport {combineLatest, type Observable, of} from 'rxjs'\nimport {map, shareReplay, switchMap} from 'rxjs/operators'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useSchema} from '../../hooks/useSchema'\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../studioClient'\nimport {createHookFromObservableFactory} from '../../util/createHookFromObservableFactory'\nimport {getDraftId, getPublishedId, getIdPair} from '../../util/draftUtils'\nimport {type PartialExcept} from '../../util/PartialExcept'\nimport {useGrantsStore} from '../datastores'\nimport {snapshotPair} from '../document/document-pair/snapshotPair'\nimport {type DocumentStoreExtraOptions} from '../document/getPairListener'\nimport {memoize} from '../document/utils/createMemoizer'\nimport {useCurrentUser} from '../user/hooks'\nimport {type GrantsStore, type PermissionCheckResult} from './types'\n\nfunction shareLatestWithRefCount<T>() {\n return shareReplay<T>({bufferSize: 1, refCount: true})\n}\n\nfunction getSchemaType(schema: Schema, typeName: string): SchemaType {\n const type = schema.get(typeName)\n\n if (!type) {\n throw new Error(`No such schema type: ${typeName}`)\n }\n\n return type\n}\n\ninterface PairPermissionsOptions {\n grantsStore: GrantsStore\n permission: DocumentPermission\n draft: SanityDocument | null\n version: SanityDocument | null\n published: SanityDocument | null\n liveEdit: boolean\n}\n\nfunction getPairPermissions({\n grantsStore,\n permission,\n draft,\n version,\n published,\n liveEdit,\n}: PairPermissionsOptions): Array<[string, Observable<PermissionCheckResult>]> {\n // this was introduced because we ran into a bug where a user with publish\n // access was marked as not allowed to duplicate a document unless it had a\n // draft variant. this would happen in non-live edit cases where the document\n // pair only had a published variant with the draft variant being null.\n //\n // note: this should _not_ be used if the draft and published versions should\n // be considered separately/explicitly in the permissions.\n const effectiveVersion = version || draft || published\n const effectiveVersionType =\n effectiveVersion === version ? version : effectiveVersion === draft ? 'draft' : 'published'\n\n const {checkDocumentPermission} = grantsStore\n\n switch (permission) {\n case 'delete': {\n if (liveEdit) {\n return [\n ['delete published document (live-edit)', checkDocumentPermission('update', published)],\n ]\n }\n\n return [\n ['delete draft document', checkDocumentPermission('update', draft)],\n ['delete published document', checkDocumentPermission('update', published)],\n ]\n }\n\n case 'discardDraft': {\n if (liveEdit) return []\n\n return [['delete draft document', checkDocumentPermission('update', draft)]]\n }\n\n case 'discardVersion': {\n if (liveEdit) return []\n\n return [['delete version', checkDocumentPermission('update', version || null)]]\n }\n\n case 'publish': {\n if (liveEdit) return []\n\n return [\n // precondition\n [\n 'update published document at its current state',\n checkDocumentPermission('update', published),\n ],\n\n // post condition\n ['delete draft document', checkDocumentPermission('update', draft)],\n [\n 'create published document from draft',\n checkDocumentPermission('create', draft && {...draft, _id: getPublishedId(draft._id)}),\n ],\n ]\n }\n\n case 'unpublish': {\n if (liveEdit) return []\n\n return [\n // precondition\n ['update draft document at its current state', checkDocumentPermission('create', draft)],\n\n // post condition\n ['delete published document', checkDocumentPermission('update', published)],\n [\n 'create draft document from published version',\n checkDocumentPermission(\n 'create',\n published && {...published, _id: getDraftId(published._id)},\n ),\n ],\n ]\n }\n\n case 'update': {\n if (liveEdit) {\n return [\n ['update published document (live-edit)', checkDocumentPermission('update', published)],\n ]\n }\n\n return [\n [\n `update ${effectiveVersionType} document`,\n checkDocumentPermission('update', effectiveVersion),\n ],\n ]\n }\n\n case 'duplicate': {\n if (liveEdit) {\n return [\n [\n 'create new published document from existing document (live-edit)',\n checkDocumentPermission('create', {...published, _id: 'dummy-id'}),\n ],\n ]\n }\n\n return [\n [\n `create new draft document from existing ${effectiveVersionType} document`,\n checkDocumentPermission('create', {...effectiveVersion, _id: getDraftId('dummy-id')}),\n ],\n ]\n }\n\n default: {\n throw new Error(`Could not match permission: ${permission}`)\n }\n }\n}\n\n/** @internal */\nexport type DocumentPermission =\n | 'delete'\n | 'discardDraft'\n | 'discardVersion'\n | 'publish'\n | 'unpublish'\n | 'update'\n | 'duplicate'\n\n/** @internal */\nexport interface DocumentPairPermissionsOptions {\n client: SanityClient\n schema: Schema\n grantsStore: GrantsStore\n id: string\n type: string\n version?: string\n permission: DocumentPermission\n /**\n * Identity of the current user. Included in the memoization key so that an\n * in-place user switch (same project, no reload) does not replay a previous\n * user's grants from the module-level memo cache.\n */\n userId?: string\n /**\n * @deprecated Does nothing. Preserved to avoid breaking changes.\n * Will be removed in the next major version.\n */\n serverActionsEnabled?: Observable<boolean>\n pairListenerOptions?: DocumentStoreExtraOptions\n}\n\n/**\n * The observable version of `useDocumentPairPermissions`\n *\n * @see useDocumentPairPermissions\n *\n * @internal\n */\nfunction getDocumentPairPermissionsUncached({\n client,\n grantsStore,\n schema,\n id,\n permission,\n type,\n version: v,\n pairListenerOptions,\n}: DocumentPairPermissionsOptions): Observable<PermissionCheckResult> {\n // this case was added to fix a crash that would occur if the `schemaType` was\n // omitted from `S.documentList()`\n //\n // see `resolveTypeForDocument` which returns `'*'` if no type is provided\n // https://github.com/sanity-io/sanity/blob/4d49b83a987d5097064d567f75d21b268a410cbf/packages/%40sanity/base/src/datastores/document/resolveTypeForDocument.ts#L7\n if (type === '*') {\n return of({granted: false, reason: 'Type specified was `*`'})\n }\n\n const liveEdit = Boolean(getSchemaType(schema, type).liveEdit)\n\n return snapshotPair(\n client,\n getIdPair(id, {version: v}),\n type,\n undefined,\n pairListenerOptions,\n ).pipe(\n switchMap((pair) =>\n combineLatest([\n pair.draft.snapshots$,\n pair.published.snapshots$,\n pair.version?.snapshots$ || of(null),\n ]).pipe(map(([draft, published, version]) => ({draft, published, version}))),\n ),\n switchMap(({draft, published, version}) => {\n const pairPermissions = getPairPermissions({\n grantsStore,\n permission,\n draft,\n version,\n published,\n liveEdit,\n }).map(([label, observable]) =>\n observable.pipe(\n map(({granted, reason}) => ({\n granted,\n reason: granted ? '' : `not allowed to ${label}: ${reason}`,\n label,\n permission,\n })),\n ),\n )\n\n if (!pairPermissions.length) return of({granted: true, reason: ''})\n\n return combineLatest(pairPermissions).pipe(\n map((permissionResults) => {\n const granted = permissionResults.every((permissionResult) => permissionResult.granted)\n const reason = granted\n ? ''\n : `Unable to ${permission}:\\n\\t${permissionResults\n .filter((permissionResult) => !permissionResult.granted)\n .map((permissionResult) => permissionResult.reason)\n .join('\\n\\t')}`\n\n return {granted, reason}\n }),\n )\n }),\n )\n}\n\nexport const getDocumentPairPermissions = memoize(\n (options: DocumentPairPermissionsOptions): Observable<PermissionCheckResult> =>\n getDocumentPairPermissionsUncached(options).pipe(shareLatestWithRefCount()),\n ({\n client,\n schema,\n id,\n type,\n version,\n permission,\n userId,\n }: DocumentPairPermissionsOptions): string => {\n const {dataset = '', projectId = ''} = client.config()\n // `liveEdit` is derived from the schema and branches the resulting permission\n // observable, so it must be part of the key: workspaces sharing a\n // project/dataset can define the same `type` with a different `liveEdit`.\n const liveEdit = type === '*' ? false : Boolean(schema.get(type)?.liveEdit)\n // `id` is normalized to its published id because the underlying chain reduces\n // (id, version) to `getIdPair(id, {version})`, a pure function of\n // (getPublishedId(id), version). The raw `version` string is kept as-is;\n // never call getIdPair here (it throws on version 'drafts'|'published').\n return [\n dataset,\n projectId,\n getPublishedId(id),\n version ?? '',\n userId ?? '',\n type,\n permission,\n liveEdit,\n ].join('-')\n },\n)\n\n/**\n * Gets document pair permissions based on a document ID and a type.\n *\n * This permissions API is a high-level permissions API that is draft-model\n * aware. In order to determine whether or not the user has the given\n * permission, both the draft and published documents are pulled and run through\n * all of the user's grants. If any pre or post conditions fail a permissions\n * checks, the operations will not be granted.\n *\n * The operations this hook accepts are only relevant to document pairs. E.g.\n * `'create'` is not included as an operation because it's not possible to tell\n * if a document can be created by only using the initial ID and type because an\n * initial template value may not have a matching grant (e.g. locked-document\n * pattern `!locked`). In contrast, the operation `'duplicate'` is supported\n * because the draft value of the document can be live queried and checked for\n * matching grants.\n *\n * Note: for live-edit documents, non-applicable operations (e.g. publish) will\n * return as true.\n *\n * @see useDocumentValuePermissions\n *\n * @internal\n */\nexport const useDocumentPairPermissionsFromHookFactory = createHookFromObservableFactory(\n getDocumentPairPermissions,\n)\n\n/** @internal */\nexport function useDocumentPairPermissions({\n id,\n type,\n version,\n permission,\n client: overrideClient,\n schema: overrideSchema,\n grantsStore: overrideGrantsStore,\n pairListenerOptions,\n}: PartialExcept<DocumentPairPermissionsOptions, 'id' | 'type' | 'permission'>): ReturnType<\n typeof useDocumentPairPermissionsFromHookFactory\n> {\n const defaultClient = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const defaultSchema = useSchema()\n const defaultGrantsStore = useGrantsStore()\n const currentUser = useCurrentUser()\n\n const client = useMemo(() => overrideClient || defaultClient, [defaultClient, overrideClient])\n const schema = useMemo(() => overrideSchema || defaultSchema, [defaultSchema, overrideSchema])\n const grantsStore = useMemo(\n () => overrideGrantsStore || defaultGrantsStore,\n [defaultGrantsStore, overrideGrantsStore],\n )\n const userId = currentUser?.id\n\n return useDocumentPairPermissionsFromHookFactory(\n useMemo(\n () => ({\n client,\n schema,\n grantsStore,\n id,\n permission,\n type,\n pairListenerOptions,\n version,\n userId,\n }),\n [client, schema, grantsStore, id, permission, type, pairListenerOptions, version, userId],\n ),\n )\n}\n","import {RELEASE_DOCUMENTS_PATH} from '../store/constants'\n\nexport function getReleaseDocumentIdFromReleaseId(name: string) {\n return `${RELEASE_DOCUMENTS_PATH}.${name}`\n}\n","import {useContext} from 'react'\nimport {ReleasesUpsellContext} from 'sanity/_singletons'\n\nimport {type ReleasesUpsellContextValue} from './types'\n\n/**\n * @beta\n * @hidden\n */\nexport function useReleasesUpsell(): ReleasesUpsellContextValue {\n const value = useContext(ReleasesUpsellContext)\n\n if (!value) return FALLBACK_CONTEXT_VALUE\n\n return value\n}\n\nconst FALLBACK_CONTEXT_VALUE = {\n upsellDialogOpen: false,\n mode: 'default' as const,\n onReleaseLimitReached: () => null,\n guardWithReleaseLimitUpsell: async () => undefined,\n handleOpenDialog: () => null,\n upsellData: null,\n telemetryLogs: {\n dialogSecondaryClicked: () => null,\n dialogPrimaryClicked: () => null,\n panelViewed: () => null,\n panelDismissed: () => null,\n panelPrimaryClicked: () => null,\n panelSecondaryClicked: () => null,\n },\n} satisfies ReleasesUpsellContextValue\n","type ErrorWithDetails = {details?: {type?: string}}\n\nexport const isErrorWithDetails = (error: unknown): error is ErrorWithDetails =>\n typeof error === 'object' &&\n error !== null &&\n 'details' in error &&\n typeof (error as {details: unknown}).details === 'object'\n","import {isErrorWithDetails} from '../../error/types/isErrorWithDetails'\n\ntype ReleaseLimitError = {details: {type: 'releaseLimitExceededError'; limit: number}}\n\nexport const isReleaseLimitError = (error: unknown): error is ReleaseLimitError =>\n isErrorWithDetails(error) && error.details?.type === 'releaseLimitExceededError'\n","import {\n type BaseActionOptions,\n type CreateVersionAction,\n type DiscardVersionAction,\n type EditableReleaseDocument,\n type IdentifiedSanityDocumentStub,\n type ReleaseDocument,\n type SanityClient,\n type SingleActionResult,\n} from '@sanity/client'\n\nimport {getDraftId, getPublishedId, getVersionFromId, getVersionId} from '../../util/draftUtils'\nimport {type ReleasesUpsellContextValue} from '../contexts/upsell/types'\nimport {type RevertDocument} from '../tool/components/releaseCTAButtons/ReleaseRevertButton/useDocumentRevertStates'\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\nimport {isReleaseLimitError} from './isReleaseLimitError'\n\nexport interface ReleaseOperationsStore {\n publishRelease: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n discardDrafts: (\n documentIds: string[],\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult | undefined>\n schedule: (releaseId: string, date: Date, opts?: BaseActionOptions) => Promise<SingleActionResult>\n unschedule: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n archive: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n unarchive: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n updateRelease: (\n release: EditableReleaseDocument,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n createRelease: (\n release: EditableReleaseDocument,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n deleteRelease: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n revertRelease: (\n revertReleaseId: string,\n documents: RevertDocument[],\n releaseMetadata: ReleaseDocument['metadata'],\n revertType: 'staged' | 'immediate',\n ) => Promise<void>\n duplicateRelease: (\n releaseDocumentId: string,\n releaseMetadata: ReleaseDocument['metadata'],\n releaseDocuments?: IdentifiedSanityDocumentStub[],\n ) => Promise<void>\n createVersion: (\n releaseId: string,\n documentId: string,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n discardVersion: (\n releaseId: string,\n documentId: string,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n unpublishVersion: (documentId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n revertUnpublishVersion: (\n documentId: string,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n}\n\nexport function createReleaseOperationsStore(options: {\n client: SanityClient\n onReleaseLimitReached: ReleasesUpsellContextValue['onReleaseLimitReached']\n}): ReleaseOperationsStore {\n const {client, onReleaseLimitReached} = options\n\n const handleReleaseLimitError = (\n action: Promise<SingleActionResult>,\n opts?: {dryRun?: boolean},\n ) =>\n action.catch((error) => {\n // if dryRunning then essentially this is a silent request\n // so don't want to create disruptive upsell because of limit\n if (!opts?.dryRun && isReleaseLimitError(error)) {\n // free accounts do not return limit, 0 is implied\n onReleaseLimitReached(error.details.limit || 0)\n }\n\n throw error\n })\n\n const handleCreateRelease = (release: EditableReleaseDocument, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.create(\n {releaseId: getReleaseIdFromReleaseDocumentId(release._id), metadata: release.metadata},\n opts,\n ),\n opts,\n )\n\n const handleUpdateRelease = async (\n release: EditableReleaseDocument,\n opts?: BaseActionOptions,\n ) => {\n const releaseId = getReleaseIdFromReleaseDocumentId(release._id)\n\n const unsetKeys = Object.entries(release)\n .filter(([_, value]) => value === undefined)\n .map(([key]) => `metadata.${key}`)\n\n return handleReleaseLimitError(\n client.releases.edit(\n {\n releaseId,\n patch: {\n set: {metadata: release.metadata},\n unset: unsetKeys,\n },\n },\n opts,\n ),\n opts,\n )\n }\n\n const handlePublishRelease = (releaseId: string, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.publish({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts),\n opts,\n )\n\n /**\n * Discards the draft versions of the given documents, if any exist. Used after publishing a\n * release to bring the drafts in line with the newly published content (\"release to drafts\").\n */\n const handleDiscardDrafts = async (documentIds: string[], opts?: BaseActionOptions) => {\n const draftIds = [...new Set(documentIds.map((documentId) => getDraftId(documentId)))]\n\n if (draftIds.length === 0) return undefined\n\n // only discard drafts that still exist, so the transaction doesn't fail on documents whose\n // drafts were removed after the draft ids were resolved\n const existingDraftIds = await client.fetch<string[]>(\n '*[_id in $draftIds]._id',\n {draftIds},\n {perspective: 'raw', tag: 'release.discard-drafts'},\n )\n\n if (existingDraftIds.length === 0) return undefined\n\n const discardDraftActions: DiscardVersionAction[] = existingDraftIds.map((draftId) => ({\n actionType: 'sanity.action.document.version.discard',\n versionId: draftId,\n }))\n\n return client.action(discardDraftActions, {tag: 'release.discard-drafts', ...opts})\n }\n\n const handleScheduleRelease = (releaseId: string, publishAt: Date, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.schedule(\n {\n releaseId: getReleaseIdFromReleaseDocumentId(releaseId),\n publishAt: publishAt.toISOString(),\n },\n opts,\n ),\n opts,\n )\n\n const handleUnscheduleRelease = (releaseId: string, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.unschedule({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts),\n opts,\n )\n\n const handleArchiveRelease = (releaseId: string, opts?: BaseActionOptions) =>\n client.releases.archive({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts)\n\n const handleUnarchiveRelease = (releaseId: string, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.unarchive({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts),\n opts,\n )\n\n const handleDeleteRelease = (releaseId: string, opts?: BaseActionOptions) =>\n client.releases.delete({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts)\n\n const handleCreateVersion = async (\n releaseId: string,\n documentId: string,\n opts?: BaseActionOptions,\n ) => {\n // fetch original document to get the revision id\n const document = await client.getDocument(documentId)\n\n if (!document) {\n throw new Error(`Document with id ${documentId} not found`)\n }\n\n return client.createVersion(\n {\n baseId: documentId,\n ifBaseRevisionId: document?._rev,\n publishedId: getPublishedId(documentId),\n releaseId,\n },\n opts,\n )\n }\n\n const handleDiscardVersion = (releaseId: string, documentId: string, opts?: BaseActionOptions) =>\n client.discardVersion({releaseId, publishedId: getPublishedId(documentId)}, false, opts)\n\n const handleUnpublishVersion = (documentId: string, opts?: BaseActionOptions) => {\n const releaseId = getVersionFromId(documentId)\n // in cases where the document is not part of a release, or document is `drafts.`\n // the releaseId will be undefined\n // cannot unpublish in this case\n if (!releaseId) {\n throw new Error(`Release ID not found for document ${documentId}`)\n }\n\n return client.unpublishVersion({releaseId, publishedId: getPublishedId(documentId)}, opts)\n }\n\n const handleRevertRelease = async (\n revertReleaseId: string,\n releaseDocuments: RevertDocument[],\n releaseMetadata: ReleaseDocument['metadata'],\n revertType: 'staged' | 'immediate',\n ) => {\n await handleCreateRelease({\n _id: revertReleaseId,\n metadata: {\n title: releaseMetadata.title,\n description: releaseMetadata.description,\n releaseType: 'asap',\n cardinality: 'many',\n },\n })\n const versionId = getReleaseIdFromReleaseDocumentId(revertReleaseId)\n const newVersionDocumentActions: CreateVersionAction[] = releaseDocuments.map(\n (releaseDocument) => ({\n actionType: 'sanity.action.document.version.create',\n document: {...releaseDocument, _id: getVersionId(releaseDocument._id, versionId)},\n publishedId: getPublishedId(releaseDocument._id),\n }),\n )\n await client.action(newVersionDocumentActions)\n\n if (revertType === 'immediate') {\n await handlePublishRelease(revertReleaseId)\n }\n }\n\n const handleDuplicateRelease = async (\n releaseDocumentId: string,\n releaseMetadata: ReleaseDocument['metadata'],\n releaseDocuments?: IdentifiedSanityDocumentStub[],\n ) => {\n await handleCreateRelease({\n _id: releaseDocumentId,\n metadata: releaseMetadata,\n })\n\n if (releaseDocuments) {\n const versionId = getReleaseIdFromReleaseDocumentId(releaseDocumentId)\n const duplicateVersionDocumentActions: CreateVersionAction[] = releaseDocuments.map(\n (releaseDocument) => ({\n actionType: 'sanity.action.document.version.create',\n baseId: releaseDocument._id,\n publishedId: getPublishedId(releaseDocument._id),\n versionId: getVersionId(releaseDocument._id, versionId),\n }),\n )\n await client.action(duplicateVersionDocumentActions, {\n tag: 'duplicate-release.create-members',\n })\n }\n }\n\n const handleRevertUnpublishVersion = async (documentId: string, opts?: BaseActionOptions) => {\n return await client.action(\n {\n actionType: 'sanity.action.document.edit',\n draftId: documentId,\n publishedId: getPublishedId(documentId),\n patch: {\n unset: ['_system.delete'],\n },\n },\n opts,\n )\n }\n\n return {\n archive: handleArchiveRelease,\n unarchive: handleUnarchiveRelease,\n schedule: handleScheduleRelease,\n unschedule: handleUnscheduleRelease,\n createRelease: handleCreateRelease,\n updateRelease: handleUpdateRelease,\n publishRelease: handlePublishRelease,\n discardDrafts: handleDiscardDrafts,\n deleteRelease: handleDeleteRelease,\n revertRelease: handleRevertRelease,\n duplicateRelease: handleDuplicateRelease,\n createVersion: handleCreateVersion,\n discardVersion: handleDiscardVersion,\n unpublishVersion: handleUnpublishVersion,\n revertUnpublishVersion: handleRevertUnpublishVersion,\n }\n}\n","import {useMemo} from 'react'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useReleasesUpsell} from '../contexts/upsell/useReleasesUpsell'\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../util/releasesClient'\nimport {createReleaseOperationsStore} from './createReleaseOperationStore'\n\n/**\n * @internal\n */\nexport function useReleaseOperations() {\n const studioClient = useClient(RELEASES_STUDIO_CLIENT_OPTIONS)\n const {onReleaseLimitReached} = useReleasesUpsell()\n return useMemo(\n () =>\n createReleaseOperationsStore({\n client: studioClient,\n onReleaseLimitReached,\n }),\n [onReleaseLimitReached, studioClient],\n )\n}\n","import {type ReleaseDocument} from '@sanity/client'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {sortReleases} from '../hooks/utils'\nimport {useReleasesStore} from './useReleasesStore'\n\n/**\n * Gets all releases including archived and published releases\n * @internal\n */\nexport function useAllReleases(): {\n data: ReleaseDocument[]\n error?: Error\n loading: boolean\n map: Map<string, ReleaseDocument>\n} {\n const {state$} = useReleasesStore()\n // Kept synchronous: release lists feed perspective/version identity\n // resolution alongside live perspective state, so a deferred snapshot could\n // pair a stale release list with the current selection — or disagree with\n // the synchronous `useActiveReleases` read of the same store. Executable\n // proof: perspective/__tests__/deferralSafety.test.tsx.\n const {releases, error, state} = useSyncObservable(state$)!\n\n return useMemo(\n () => ({\n data: sortReleases(Array.from(releases.values())),\n map: releases,\n error: error,\n loading: ['loading', 'initialising'].includes(state),\n }),\n [error, releases, state],\n )\n}\n","/**\n * Schedule the provided callback using `scheduler.yield`, if it's available.\n * This allows long-running work to be broken up so the browser stays responsive.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Scheduler/yield\n * Otherwise, call it immediately.\n */\nexport function schedulerYield<Result>(\n promise: () => Promise<Result>,\n): Promise<Result> | Promise<void> {\n if ('scheduler' in window && typeof window.scheduler?.yield === 'function') {\n return window.scheduler.yield()\n }\n return promise()\n}\n","import {\n type CurrentUser,\n isValidationErrorMarker,\n type SanityDocument,\n type Schema,\n} from '@sanity/types'\nimport {uuid} from '@sanity/uuid'\nimport {useMemo} from 'react'\nimport {useObservable} from 'react-rx'\nimport {combineLatest, from, type Observable, of} from 'rxjs'\nimport {mergeMapArray} from 'rxjs-mergemap-array'\nimport {catchError, delay, filter, finalize, map, shareReplay, switchMap} from 'rxjs/operators'\n\nimport {useSchema} from '../../../hooks/useSchema'\nimport {type LocaleSource} from '../../../i18n/types'\nimport {type DocumentPreviewStore} from '../../../preview/documentPreviewStore'\nimport {useDocumentPreviewStore} from '../../../store/datastores'\nimport {useSource} from '../../../studio/source'\nimport {schedulerYield} from '../../../util/schedulerYield'\nimport {validateDocumentWithReferences, type ValidationStatus} from '../../../validation'\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../../util/releasesClient'\n\nconst bundleDocumentsCache: Record<string, BundleDocumentsObservableResult> = Object.create(null)\n\n/** @internal */\nexport function resetBundleDocumentsCacheForTests(): void {\n for (const key of Object.keys(bundleDocumentsCache)) {\n delete bundleDocumentsCache[key]\n }\n}\n\nexport interface DocumentValidationStatus extends ValidationStatus {\n hasError: boolean\n}\n\n/**\n * A document in a bundle (a set of documents resolved by a GROQ filter, e.g. a release or a\n * variant), along with its validation status. Shared by the release- and variant-specific types.\n *\n * @public\n */\nexport interface BundleDocument {\n memoKey: string\n isPending?: boolean\n document: SanityDocument & {publishedDocumentExists: boolean; draftDocumentExists?: boolean}\n validation: DocumentValidationStatus\n}\n\nexport type BundleDocumentsObservableResult = Observable<{\n loading: boolean\n results: BundleDocument[]\n error: Error | null\n}>\n\ninterface BundleDocumentsObservableOptions {\n schema: Schema\n documentPreviewStore: DocumentPreviewStore\n i18n: LocaleSource\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n getClient: ReturnType<typeof useSource>['getClient']\n currentUser?: Omit<CurrentUser, 'role'> | null\n /**\n * The GROQ filter used to resolve the set of documents to fetch,\n * e.g. `sanity::partOfRelease($releaseId)` or `sanity::partOfVariant($variantId)`.\n */\n groqFilter: string\n /**\n * The params referenced by `groqFilter`, e.g. `{releaseId}` or `{variantId}`.\n */\n params: Record<string, unknown>\n /**\n * Returns `true` for documents that should not be validated (validation is short-circuited).\n * Used, for example, to skip documents that are going to be unpublished in a release.\n */\n skipValidation?: (document: SanityDocument) => boolean\n}\n\nconst buildBundleDocumentsObservable = ({\n schema,\n documentPreviewStore,\n i18n,\n getClient,\n currentUser,\n groqFilter,\n params,\n skipValidation,\n}: Omit<BundleDocumentsObservableOptions, 'cacheKey'>): BundleDocumentsObservableResult => {\n // Helper function to create validation observable\n const createValidationObservable = (ctx: any, document: SanityDocument) => {\n if (skipValidation?.(document)) {\n return of({\n isValidating: false,\n validation: [],\n revision: document._rev,\n hasError: false,\n } satisfies DocumentValidationStatus)\n }\n\n // scheduledYield is used to provide some control over the main thread\n return from(schedulerYield(() => Promise.resolve())).pipe(\n switchMap(() =>\n validateDocumentWithReferences(ctx, of(document), false).pipe(\n map((validationStatus) => ({\n ...validationStatus,\n hasError: validationStatus.validation.some((marker) => isValidationErrorMarker(marker)),\n })),\n ),\n ),\n )\n }\n\n // Helper function to process a single document and set up the associated validation observable\n const processDocument = (id: string) => {\n const ctx = {\n observeDocument: documentPreviewStore.unstable_observeDocument,\n observeDocumentPairAvailability:\n documentPreviewStore.unstable_observeDocumentPairAvailability,\n i18n,\n getClient,\n schema,\n currentUser,\n }\n\n const document$ = documentPreviewStore\n .unstable_observeDocument(id, {\n apiVersion: RELEASES_STUDIO_CLIENT_OPTIONS.apiVersion,\n })\n .pipe(\n filter(Boolean),\n switchMap((doc) => {\n return documentPreviewStore.unstable_observeDocumentPairAvailability(id).pipe(\n map((availability) => ({\n ...doc,\n publishedDocumentExists: availability.published.available,\n draftDocumentExists: availability.draft.available,\n })),\n )\n }),\n )\n\n const validation$ = document$.pipe(\n switchMap((document) => createValidationObservable(ctx, document)),\n )\n\n return combineLatest([document$, validation$]).pipe(\n map(([document, validation]) => ({\n document,\n validation,\n memoKey: uuid(),\n })),\n )\n }\n\n // Helper function to process a group of document Ids\n // Used to process documents as to not overwhelm the main thread\n const processDocumentIdsGroup = (documentIdsGroup: string[], groupIndex: number) => {\n // On the first batch there is no delay\n const batchDelay = groupIndex === 0 ? 0 : 100\n\n return of(documentIdsGroup).pipe(\n delay(batchDelay),\n mergeMapArray((id: string) => processDocument(id)),\n )\n }\n\n return documentPreviewStore\n .unstable_observeDocumentIdSet(groqFilter, params, {\n apiVersion: RELEASES_STUDIO_CLIENT_OPTIONS.apiVersion,\n })\n .pipe(\n map((state) => state.documentIds || []),\n switchMap((documentIds) => {\n // If no documents, return empty results immediately\n if (documentIds.length === 0) {\n return of([])\n }\n\n // Process in smaller groups as to not overwhelm the main thread\n // depending on the browser it can handle a different number of calls at once, this felt like a good balance\n // given the tests done\n const batchSize = 5\n const documentIdsGroups = []\n for (let i = 0; i < documentIds.length; i += batchSize) {\n documentIdsGroups.push(documentIds.slice(i, i + batchSize))\n }\n\n // Process all batches and collect all results\n return combineLatest(\n documentIdsGroups.map((batch, batchIndex) =>\n // The delay is used to control the rate of the requests\n // It increases as it goes on as to allow for some space (in the miliseconds scale)\n // This means that technically one might expect it to take longer to get all the results, but\n // It makes the user experience better as it is not overwhelming the main thread\n // And it allows for the browser to more easily handle the requests\n processDocumentIdsGroup(batch, batchIndex).pipe(delay(batchIndex * 100)),\n ),\n ).pipe(\n // Flatten all batch results into a single array\n // This is done to avoid having to nest the results and keep the strutcture as it was before\n map((groupResults) => groupResults.flat()),\n )\n }),\n map((results) => ({loading: false, results, error: null})),\n catchError((error) => {\n return of({loading: false, results: [], error})\n }),\n )\n}\n\n/**\n * Generic document-fetching machinery shared across releases and variants.\n *\n * Resolves the set of documents matching `groqFilter`/`params`, then observes each document along\n * with its published availability and validation status. Results are batched to avoid overwhelming\n * the main thread, and shared across subscribers via a module-level cache keyed by `cacheKey`.\n *\n * @internal\n */\nexport const getBundleDocumentsObservable = ({\n cacheKey,\n ...options\n}: BundleDocumentsObservableOptions & {cacheKey: string}): BundleDocumentsObservableResult => {\n if (!bundleDocumentsCache[cacheKey]) {\n bundleDocumentsCache[cacheKey] = buildBundleDocumentsObservable(options).pipe(\n finalize(() => {\n delete bundleDocumentsCache[cacheKey]\n }),\n shareReplay(1),\n )\n }\n\n return bundleDocumentsCache[cacheKey]\n}\n\nconst BUNDLE_DOCUMENTS_EMPTY = {\n loading: false,\n results: [],\n error: null,\n}\n\nconst BUNDLE_DOCUMENTS_LOADING = {\n loading: true,\n results: [],\n error: null,\n}\n\n/**\n * Generic hook to fetch the documents matching a GROQ filter, along with their validation and\n * published availability. Used by release- and variant-specific hooks.\n *\n * @internal\n */\nexport function useBundleDocuments(options: {\n groqFilter: string\n params: Record<string, unknown>\n cacheKey: string\n skipValidation?: (document: SanityDocument) => boolean\n enabled?: boolean\n}): {\n loading: boolean\n results: BundleDocument[]\n error: null | Error\n} {\n const {groqFilter, params, cacheKey, skipValidation, enabled = true} = options\n const documentPreviewStore = useDocumentPreviewStore()\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {getClient, i18n, currentUser} = useSource()\n const schema = useSchema()\n\n const bundleDocumentsObservable = useMemo(\n () =>\n enabled\n ? getBundleDocumentsObservable({\n schema,\n documentPreviewStore,\n getClient,\n i18n,\n currentUser,\n groqFilter,\n params,\n cacheKey,\n skipValidation,\n })\n : of(BUNDLE_DOCUMENTS_EMPTY),\n [\n enabled,\n schema,\n documentPreviewStore,\n getClient,\n i18n,\n currentUser,\n groqFilter,\n params,\n cacheKey,\n skipValidation,\n ],\n )\n\n return useObservable(\n bundleDocumentsObservable,\n enabled ? BUNDLE_DOCUMENTS_LOADING : BUNDLE_DOCUMENTS_EMPTY,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAaS,eAAe;CAAC;CAAQ;CAAa;AAAW;;;;AAK7D,SAAgBE,cAAcC,kBAA4D;CACxF,OACE,OAAOA,oBAAqB,YAAYH,aAAaI,SAASD,gBAA+B;AAEjG;;;;AAKA,SAAgBE,kBAAkBC,KAAsC;CACtE,OACE,OAAOA,OAAQ,cAAYA,OAAgB,WAAWA,OAAOA,IAAIC,UAAAA;AAErE;;;;;;ACVA,SAAgBkB,wBACdC,SACkC;CAClC,OAAOA,QAAQH,UAAUC,gBAAgB;AAC3C;;;;;;AAOA,SAAgBG,4BACdC,aACsC;CACtC,OAAOP,kBAAkBO,WAAW,KAAKH,wBAAwBG,WAAW;AAC9E;;;;;;AAOA,SAAgBC,8BAA8BH,SAA+C;CAE3F,OADKA,UAEHA,QAAQI,UAAU,YAClBJ,QAAQH,SAASQ,gBAAgB,eACjCN,wBAAwBC,OAAO,KAC/BM,EAAQN,QAAQH,SAASU,oBALN;AAOvB;;;;AC5CA,MAAaG,SAAS,UAKTE,cAAY,aAKZC,uBAAuB,QAKvBC,0BAA0B,CAAC,YAAY,WAAW,GAKlDC,sBAA8D;CACzEG,MAAM,EACJ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","ReleaseType","DocumentSystem","Dispatch","Observable","RELEASE_DOCUMENT_TYPE","MetadataWrapper","ReleasesReducerAction","ReleasesReducerState","releaseTypes","const","isReleaseType","maybeReleaseType","includes","isReleaseDocument","doc","_type","ReleaseStore","state$","errorCount$","getMetadataStateForSlugs$","slugs","dispatch","VersionInfoDocumentStub","_id","_rev","_createdAt","_updatedAt","_system","ReleaseDocument","isReleaseDocument","CardinalityOneRelease","metadata","cardinality","isCardinalityOneRelease","release","isCardinalityOnePerspective","perspective","isPausedCardinalityOneRelease","state","releaseType","Boolean","intendedPublishAt","ReleaseType","BadgeTone","LATEST","const","PUBLISHED","DEFAULT_RELEASE_TYPE","ARCHIVED_RELEASE_STATES","RELEASE_TYPES_TONES","Record","tone","asap","scheduled","undecided","tz","tzHelper","formatRelative","isValid","parse","DateInput","Date","RUNTIME_TIME_ZONE","Intl","DateTimeFormat","resolvedOptions","timeZone","formatRelativeLocale","date","baseDate","relative","in","toLocaleDateString","undefined","customAlphabet","RELEASE_DOCUMENTS_PATH","createBundleId","createReleaseId","EditableReleaseDocument","ReleaseDocument","ReleaseState","DocumentSystem","TargetPerspective","getVersionFromId","isVersionId","formatRelativeLocale","isCardinalityOneRelease","isPausedCardinalityOneRelease","CardinalityView","Mode","DEFAULT_RELEASE_TYPE","LATEST","createReleaseId","getReleaseIdFromReleaseDocumentId","NotArchivedRelease","state","Exclude","getDocumentIsInPerspective","documentId","perspective","releaseId","getPublishDateFromRelease","release","Date","dateString","publishedAt","publishAt","metadata","intendedPublishAt","formatRelativeLocalePublishDate","timeZone","publishDate","isPublishedPerspective","isDraftPerspective","isReleaseScheduledOrScheduling","releaseType","getReleaseDefaults","_id","title","description","cardinality","isNotArchivedRelease","shouldShowReleaseInView","cardinalityView","isCardinalityOne","FilterReleasesOptions","releases","T","archivedReleases","releaseGroupMode","dateFilter","filterDate","getTimezoneAdjustedDateTimeRange","date","filterReleasesForOverview","options","sourceReleases","applyDateFilter","items","startOfDayForTimeZone","endOfDayForTimeZone","filter","publishDateUTC","dateFiltered","BadgeTone","TargetPerspective","isAgentBundleName","isPausedCardinalityOneRelease","isReleaseDocument","RELEASE_TYPES_TONES","isDraftPerspective","isPublishedPerspective","getReleaseTone","release","state","metadata","releaseType","asap","tone","undecided","scheduled","ClientPerspective","ReleaseDocument","PerspectiveStack","ReleaseId","getReleaseIdFromReleaseDocumentId","sortReleases","releases","sort","a","b","metadata","releaseType","Date","_createdAt","getTime","aPublishAt","publishAt","intendedPublishAt","bPublishAt","DRAFTS","PUBLISHED","EMPTY","getReleasesPerspectiveStack","selectedPerspectiveName","excludedPerspectives","isDraftModelEnabled","defaultPerspective","sorted","map","release","_id","selectedIndex","indexOf","slice","concat","filter","name","includes","SanityClient","bufferTime","catchError","EMPTY","filter","iif","merge","Observable","of","startWith","switchMap","getReleaseIdFromReleaseDocumentId","ReleasesMetadata","ReleasesMetadataMap","Record","MetadataWrapper","data","error","loading","getFetchQuery","releaseIds","getSafeKey","id","replaceAll","reduce","subquery","accSubquery","projection","accProjection","releaseId","bundleId","safeId","createReleaseMetadataAggregator","client","aggregatorFetch$","isInitialLoad","length","queryAllDocumentsInReleases","projectionToBundleMetadata","fetchData$","observable","fetch","Omit","documentIds","tag","pipe","releaseDocumentIdResponse","Object","entries","existing","el","metadata","documentCount","console","aggregatorListener$","listen","accQuery","index","includeResult","includeAllVersions","visibility","events","entriesArray","mutatedReleaseIds","accReleaseIds","event","type","documentId","split","includes","ReleaseDocument","BundleDeletedAction","id","currentUserId","deletedByUserId","type","ReleasesSetAction","payload","LoadingStateChangedAction","loading","error","Error","ReleasesReducerAction","ReleasesReducerState","releases","Map","state","createReleasesSet","reduce","acc","bundle","set","_id","releasesReducer","action","releasesById","ReleaseDocument","ReleaseType","SanityClient","BehaviorSubject","catchError","concat","concatWith","count","filter","from","merge","Observable","of","OperatorFunction","pipe","scan","shareReplay","Subject","switchMap","tap","distinctUntilChanged","map","startWith","DocumentPreviewStore","listenQuery","RELEASE_DOCUMENT_TYPE","RELEASE_DOCUMENTS_PATH","createReleaseMetadataAggregator","releasesReducer","ReleasesReducerAction","ReleasesReducerState","ReleaseStore","ActionWrapper","action","ResponseWrapper","response","SORT_FIELD","SORT_ORDER","QUERY_FILTER","DEFAULT_RELEASE_TYPE","QUERY_PROJECTION","QUERY_SORT_ORDER","QUERY","INITIAL_STATE","releases","Map","state","const","createReleaseStore","context","previewStore","client","dispatch$","fetchPending$","dispatch","next","listFetch$","type","payload","loading","error","undefined","value","tag","entry","state$","errorCount$","releaseStoreErrorCount","getMetadataStateForSlugs$","values","release","useMemo","useClient","useDocumentPreviewStore","useResourceCache","useWorkspace","RELEASES_STUDIO_CLIENT_OPTIONS","createReleaseStore","ReleaseStore","useReleasesStore","$","_c","resourceCache","workspace","previewStore","studioClient","releaseStore","get","dependencies","namespace","client","set","value","ReleaseDocument","useMemo","useSyncObservable","sortReleases","ARCHIVED_RELEASE_STATES","ReleasesReducerAction","useReleasesStore","ReleasesState","data","error","Error","loading","dispatch","event","useActiveReleases","$","_c","state$","state","t0","releases","Array","from","values","filter","_temp","reverse","releasesAsArray","t1","t2","Symbol","for","t3","includes","t4","release","PreviewLayoutKey","PREVIEW_SIZES","Record","icon","media","height","width","block","blockImage","compact","default","detail","inline","rem","css","styled","PREVIEW_SIZES","PreviewLayoutKey","PreviewMediaDimensions","MediaWrapper","span","$dimensions","$layout","$radius","$responsive","props","width","height","iconSize","icon","undefined","theme","sanity","radius","displayName","Text","ComponentType","isValidElement","ReactNode","isValidElementType","PreviewLayoutKey","PreviewMediaDimensions","PreviewProps","MediaWrapper","MediaProps","border","dimensions","layout","media","radius","responsive","styles","mediaString","Media","props","$","_c","t0","t1","t2","undefined","t3","t4","renderMedia","t5","t6","MediaComponent","tryGetImageDimensions","ElementType","isValidElement","ReactNode","isValidElementType","getDevicePixelRatio","PREVIEW_SIZES","PreviewProps","PreviewLayoutKey","PreviewMediaDimensions","renderPreviewMedia","value","Layout","layout","dimensions","Value","isReactNode","renderPreviewNode","fallbackNode","resolveBlockImageDimensions","source","Parameters","sourceDimensions","undefined","max","blockImage","media","scale","Math","min","width","round","height","fit","dpr","Box","Flex","rem","Skeleton","Stack","Text","TextSkeleton","styled","getDevicePixelRatio","useTranslation","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","CompactPreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","compact","media","aspect","fit","dpr","Root","height","TitleSkeleton","attrs","animated","radius","size","CompactPreview","props","$","_c","children","isPlaceholder","status","title","t","t0","statusNode","t1","t2","t3","Symbol","for","t4","t5","color","t6","t7","t8","t9","hues","Card","Theme","css","styled","STROKE_WIDTH","Root","Bar","theme","color","sanity","blue","dark","hex","LinearProgress","props","$","_c","value","t0","t1","transform","Box","Flex","rem","Skeleton","Stack","Text","TextSkeleton","clsx","styled","getDevicePixelRatio","useTranslation","LinearProgress","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","DefaultPreviewProps","Omit","styles","root","placeholder","media","heading","title","subtitle","hasSubtitle","mediaString","status","children","DEFAULT_MEDIA_DIMENSIONS","default","aspect","fit","dpr","Root","height","TitleSkeleton","attrs","animated","radius","size","SubtitleSkeleton","SKELETON_DELAY","DefaultPreview","props","$","_c","isPlaceholder","progress","t","t0","t1","Boolean","t2","rootClassName","isUploading","t3","statusNode","t4","t5","t6","t7","Symbol","for","t8","t9","t10","color","t11","t12","t13","Box","Flex","rem","Skeleton","Text","TextSkeleton","css","styled","PREVIEW_SIZES","RootFlex","attrs","align","detail","media","height","StatusBox","MediaSkeleton","animated","radius","width","TitleSkeleton","size","SubtitleSkeleton","DescriptionSkeleton","DescriptionText","theme","fonts","sanity","textSize1","text","sizes","maxLines","maxHeight","lineHeight","Box","Flex","Stack","Text","getDevicePixelRatio","useTranslation","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","DescriptionSkeleton","DescriptionText","MediaSkeleton","RootFlex","StatusBox","SubtitleSkeleton","TitleSkeleton","DetailPreviewProps","DEFAULT_MEDIA_DIMENSIONS","detail","media","fit","aspect","dpr","DetailPreview","props","$","_c","title","subtitle","description","mediaDimensions","t0","status","children","isPlaceholder","undefined","t","t1","statusNode","t2","t3","t4","t5","Symbol","for","t6","t7","t8","t9","color","t10","t11","t12","t13","hues","Theme","css","styled","SIZE","STROKE_WIDTH","Root","svg","BgCircle","circle","theme","color","sanity","gray","dark","hex","ProgressCircle","blue","CircularProgress","props","$","_c","value","valueProp","Math","min","max","radius","circ","PI","offset","viewBox","t0","Symbol","for","t1","t2","strokeDasharray","strokeDashoffset","Box","Flex","rem","Skeleton","Stack","styled","RootBox","MediaFlex","attrs","align","justify","MediaSkeleton","animated","radius","ProgressFlex","TooltipContentStack","gap","Box","Text","useMemo","getDevicePixelRatio","Tooltip","CircularProgress","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","MediaFlex","MediaSkeleton","ProgressFlex","RootBox","TooltipContentStack","MediaPreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","media","aspect","fit","dpr","MediaPreview","props","$","_c","mediaDimensions","t0","children","isPlaceholder","progress","t1","subtitle","title","withBorder","t2","withRadius","t3","undefined","t4","t5","paddingBottom","STYLES_PADDER","t6","bb0","t7","t8","t9","tooltipContent","t10","t11","t12","t13","Box","Card","Flex","rem","styled","PREVIEW_SIZES","HeaderFlex","attrs","align","block","media","height","MediaCard","$ratio","RootBox","overflow","theme","sanity","radius","Box","Flex","Stack","Text","getDevicePixelRatio","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","HeaderFlex","MediaCard","RootBox","BlockImagePreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","blockImage","media","fit","dpr","getRatio","dimensions","height","width","BlockImagePreview","props","$","_c","actions","title","subtitle","description","fallbackTitle","t0","mediaDimensions","t1","children","status","undefined","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","t15","t16","Box","Flex","rem","Stack","Text","styled","getDevicePixelRatio","LinearProgress","Media","PREVIEW_SIZES","renderPreviewNode","PreviewMediaDimensions","PreviewProps","DEFAULT_MEDIA_DIMENSIONS","block","media","aspect","fit","dpr","HeaderFlex","attrs","align","height","BlockPreview","props","$","_c","actions","title","subtitle","description","mediaDimensions","t0","progress","status","children","undefined","isUploading","t1","t2","t3","t4","t5","t6","t7","t8","t9","t10","t11","t12","t13","t14","rem","Text","Theme","css","styled","RootSpan","span","MediaSpan","theme","sanity","radius","TextSpan","attrs","forwardedAs","textFont","fonts","text","textSize","sizes","fontSize","weights","medium","lineHeight","getDevicePixelRatio","PREVIEW_SIZES","renderPreviewMedia","renderPreviewNode","PreviewMediaDimensions","PreviewProps","MediaSpan","RootSpan","TextSpan","InlinePreviewProps","Omit","DEFAULT_MEDIA_DIMENSIONS","inline","media","fit","aspect","dpr","InlinePreview","props","$","_c","title","fallbackTitle","t0","mediaDimensions","t1","undefined","t2","t3","t4","t5","isString","Plugin","PluginOptions","PluginFactory","options","TOptions","validatePlugin","pluginResult","messages","filter","length","Error","map","message","join","definePlugin","arg","pluginFactory","result","createPlugin","useToast","useEffect","definePlugin","LayoutProps","SchedulePublishingStudioLayout","props","$","_c","toast","t0","t1","console","error","push","id","closable","duration","status","title","description","t2","renderDefault","deprecatedScheduledPublishingPlugin","name","studio","components","layout","deprecatedScheduledPublishingPlugin","PluginOptions","DEPRECATED_PLUGINS","flattenConfig","plugins","currentConfig","path","Array","config","rootConfig","name","allPlugins","flatMap","plugin","deprecatedScheduledPublishing","find","p","push","resolved","filter","includes","Skeleton","ComponentType","Fragment","Suspense","useMemo","useSource","flattenConfig","PluginOptions","emptyRender","_createMiddlewareComponent","DefaultComponent","T","middlewareComponents","MiddlewareComponent","outerProps","$","_c","next","_temp","Symbol","for","Middleware","renderDefault","props","t0","t1","useMiddlewareComponents","options","__internal","defaultComponent","pick","flattened","reverse","pickedComponents","map","config","result","filter","Boolean","isString","SanityClient","createMediaLibraryClient","client","libraryId","apiHost","projectId","config","Error","baseUrl","URL","hostname","withConfig","origin","resource","id","type","GlobalDocumentReferenceValue","MediaLibraryRef","hasOwnRecord","PropertyKey","value","key","K","Record","Object","prototype","hasOwnProperty","call","makeMediaLibraryRef","libraryId","assetId","containsMediaProperty","media","_ref","isMediaLibraryRef","ref","resourceType","resourceId","documentId","split","Boolean","getMediaLibraryRef","maybeRef","undefined","SanityClient","DataLoader","QuickLRU","createMediaLibraryClient","makeMediaLibraryRef","MediaLibraryRef","AccessPolicyResult","POLICY_CACHE_MAX_SIZE","POLICY_CACHE_MAX_AGE","loaders","Map","policyCache","maxAge","maxSize","fetchAccessPoliciesBatch","params","assetIds","client","libraryId","Promise","length","results","fetch","_id","cdnAccessPolicy","ids","policyById","Object","fromEntries","map","doc","assetId","policy","assetRef","set","error","console","forEach","undefined","resolveAssetPolicyLoader","existingLoader","get","mediaLibraryClient","loader","cache","enqueueAssetAccessPolicyFetch","split","resolve","has","load","SanityClient","SanityImageSource","AssetSource","useSWR","enqueueAssetAccessPolicyFetch","getMediaLibraryRef","MediaLibraryRef","AssetAccessPolicy","useAccessPolicy","params","$","_c","client","source","t0","ref","canCheck","Boolean","config","token","requestKey","t1","key","fetcher","t2","Symbol","for","dedupingInterval","revalidateOnFocus","revalidateOnReconnect","shouldRetryOnError","options","data","cdnAccessPolicy","isLoading","DEFAULT_API_VERSION","DEPLOYED_FRONTEND_HOST_STAGING","CDN_HOST_STAGING","API_HOST_STAGING","DEPLOYED_FRONTEND_HOST_PRODUCTION","CDN_HOST_PRODUCTION","API_HOST_PRODUCTION","useClient","DEFAULT_API_VERSION","useToken","$","_c","t0","Symbol","for","apiVersion","client","t1","config","token","useEffect","useState","useToken","UseImageObjectUrlResult","error","Error","isLoading","objectUrl","RequestCacheEntry","abortController","AbortController","blob","Blob","cleanupTimer","ReturnType","setTimeout","listeners","Set","status","CACHE_DISPOSE_DELAY","requestCache","Map","IDLE_RESULT","undefined","LOADING_RESULT","createCacheKey","url","token","notifyListeners","entry","forEach","listener","deriveResultFromEntry","createFetchCacheEntry","fetch","cache","headers","Authorization","signal","then","res","ok","URL","createObjectURL","catch","useImageObjectUrl","$","_c","t0","cacheKey","t1","get","state","setState","t2","t3","_temp","entry_0","set","clearTimeout","updateState","add","delete","size","abort","revokeObjectURL","prev","ImageUrlBuilder","SanityImageSource","AssetAccessPolicy","useImageObjectUrl","UseImageUrlParameters","accessPolicy","imageSource","T","imageUrlBuilder","transform","builder","value","UseImageUrlResult","isLoading","url","useImageUrl","params","$","_c","t0","undefined","isPolicyCheckInProgress","isPrivate","t1","bb0","t2","image","networkUrl","objectUrl","objectUrlIsLoading","CompactPreview","DefaultPreview","DetailPreview","MediaPreview","BlockImagePreview","BlockPreview","InlinePreview","_previewComponents","block","blockImage","compact","default","detail","inline","media","const","isImageSource","isSanityImageUrl","parseImageAssetUrl","SanityClient","DocumentIcon","WarningOutlineIcon","createImageUrlBuilder","ImageUrlBuilder","SanityImageSource","Card","Flex","Skeleton","ComponentType","ElementType","isValidElement","memo","ReactNode","useCallback","useMemo","useState","isValidElementType","Tooltip","resolveBlockImageDimensions","PreviewMediaDimensions","PreviewProps","useAccessPolicy","useImageUrl","useClient","DEFAULT_STUDIO_CLIENT_OPTIONS","isString","_previewComponents","FallbackIcon","$","_c","t0","Symbol","for","SanityDefaultPreviewProps","Omit","error","Error","icon","tooltip","SanityDefaultMediaProps","client","dimensions","imageSource","imageUrlBuilder","title","SanityDefaultMedia","t1","builder","val","width","height","fit","dpr","image","withOptions","url","transform","t2","source","accessPolicy","t3","isLoading","hasImageError","setHasImageError","t4","handleError","t5","showAccessWarning","t6","undefined","SanityDefaultPreview","props","Icon","imageUrl","layout","mediaProp","restProps","media","imageBuilder","options","assetId","renderMedia","renderIcon","bb0","bb1","mediaDimensions","resolvedMediaDimensions","previewProps","LayoutComponent","children","t7","t8","t9","t10","displayName","SchemaType","ComponentType","PreviewProps","SanityDefaultPreview","defaultResolvePreviewComponent","schemaType","Omit","components","preview","ComponentType","PreviewProps","PluginOptions","BlockAnnotationProps","BlockProps","PortableTextPluginsProps","FieldProps","InputProps","ItemProps","pickInputComponent","plugin","Omit","form","components","input","pickFieldComponent","field","pickPreviewComponent","preview","pickItemComponent","item","pickBlockComponent","block","pickInlineBlockComponent","inlineBlock","pickAnnotationComponent","annotation","pickPortableTextEditorPluginsComponent","portableText","plugins","SchemaType","ComponentType","useCallback","useMemo","useResolveDefaultComponent","props","$","_c","componentResolver","componentProps","schemaType","Error","t0","DefaultResolvedComponent","t1","parentTypeProps","type","components","restSchemaType","ParentTypeResolvedComponent","renderDefault","t2","ComponentType","PreviewProps","useMiddlewareComponents","defaultResolvePreviewComponent","pickPreviewComponent","useResolveDefaultComponent","DefaultPreview","props","$","_c","t0","componentProps","componentResolver","usePreviewComponent","Symbol","for","defaultComponent","pick","useContext","PerspectiveContext","PerspectiveContextValue","usePerspective","context","Error","SanityDocument","SanityDocumentLike","isGoingToUnpublish","document","Boolean","_system","delete","PreviewValue","SanityDocument","SchemaType","SortOrdering","useMemo","useSyncObservable","Observable","of","catchError","map","PerspectiveStack","usePerspective","isGoingToUnpublish","useDocumentPreviewStore","getPublishedId","Previewable","unstable_useValuePreview","useValuePreview","State","isLoading","error","Error","value","INITIAL_STATE","IDLE_STATE","title","undefined","description","props","$","_c","t0","enabled","t1","ordering","schemaType","previewValue","perspectiveStack","chosenPerspectiveStack","variant","chosenVariant","observeForPreview","selectedVariantName","t2","bb0","t3","Symbol","for","t4","goingToUnpublish","t5","updatedStack","updatedVariant","updatedDocId","_id","restPreviewValue","perspective","viewOptions","pipe","_temp","_temp2","observable","event","snapshot","EMPTY","fromEvent","shareReplay","orientationChange$","window","pipe","EMPTY","fromEvent","shareReplay","resize$","window","pipe","EMPTY","fromEvent","shareReplay","scroll$","window","passive","capture","pipe","merge","Observable","of","observableOf","Subject","filter","map","mergeMap","orientationChange$","resize$","scroll$","ROOT_MARGIN_PX","isIntersectionObserverSupported","window","IntersectionObserverEntry","prototype","Object","defineProperty","get","intersectionRatio","IntersectionEvent","isIntersecting","intersectionObservableFor","createIntersectionObserverBased","createLegacyBased","IntersectionObservableFor","element","Element","intersectionObserverEntriesSubject","intersectionObserver","IntersectionObserver","entries","forEach","entry","next","threshold","rootMargin","observer","observe","unobserve","pipe","asObservable","target","ev","getViewport","left","right","innerWidth","top","bottom","innerHeight","intersects","rect","DOMRect","viewport","margin","inViewport","HTMLElement","getBoundingClientRect","isElementInViewport","EMPTY","fromEvent","Observable","shareReplay","visibilityChange$","Event","window","document","pipe","useMemo","useObservable","concat","of","delay","distinctUntilChanged","map","startWith","switchMap","intersectionObservableFor","visibilityChange$","Props","disabled","element","HTMLElement","hideDelay","useVisibility","props","$","_c","t0","undefined","t1","bb0","t2","Symbol","for","seed","checkVisibility","isDocumentVisible$","document","hidden","pipe","_temp","inViewport$","_temp2","t3","isVisible","isDocumentVisible","visible$","visible","event_0","event","isIntersecting","target","Document","UploadState","isRecord","isString","_extractUploadState","value","_resolveUploadValue","_upload","getStringOrUndefined","undefined","progress","createdAt","initiated","updatedAt","updated","fileName","file","name","fileType","type","previewImage","ComponentType","CSSProperties","useMemo","useState","PreviewProps","RenderPreviewCallbackProps","useTranslation","PerspectiveStack","useValuePreview","useVisibility","_HIDE_DELAY","_extractUploadState","PreviewLoader","props","$","_c","Component","layout","perspectiveStack","restProps","schemaType","skipVisibilityCheck","styleProp","value","variant","component","style","t","element","setElement","isVisible","disabled","hideDelay","t0","t1","enabled","preview","t2","minWidth","t3","minHeight","t4","t5","uploadState","t6","bb0","previewImage","t7","t8","media","undefined","icon","error","t9","isLoading","t10","t11","usePreviewComponent","RenderPreviewCallbackProps","PerspectiveStack","PreviewLoader","Preview","props","$","_c","PreviewComponent","t0","useSource","useDataset","dataset","ReleaseDocument","getVersionFromId","DocumentSystem","useMemo","useSyncObservable","catchError","combineLatest","finalize","map","Observable","of","ReplaySubject","share","startWith","switchMap","timer","useDataset","useProjectId","DOCUMENT_SYSTEM_FIELD","DocumentPreviewStore","useDocumentPreviewStore","isDraftId","getPublishedId","isRecord","createSWR","VersionInfoDocumentStub","useReleasesStore","ARCHIVED_RELEASE_STATES","getReleaseIdFromReleaseDocumentId","DocumentPerspectiveProps","documentId","DocumentPerspectiveState","data","versions","error","loading","INITIAL_VALUE","observableCache","Map","withSystemCache","swr","maxSize","TEARDOWN_GRACE_PERIOD","useDocumentVersions","props","observable","useDocumentVersionsObservable","$","_c","t0","publishedId","dataset","projectId","documentPreviewStore","state$","releasesState$","t1","pipe","_temp2","releases$","t2","getOrCreateDocumentVersionsWithSystemObservable","state","Array","from","releases","values","filter","_temp","release","includes","buildDocumentSystem","id","versionId","releaseDocument","find","_id","bundleId","_ref","_weak","undefined","group","scopeId","resolveVersionSystem","version","_system","DOCUMENT_STUB_PATHS","getOrCreateCachedObservable","cache","T","cacheKey","createObservable","cached","get","delete","connector","resetOnRefCountZero","set","options","getOrCreateDocumentVersionsObservable","result","unstable_observeVersionDocumentIds","value","documentIds","index","length","versions$","observePaths","versionInfo","_rev","_createdAt","_updatedAt","loadingState","useContext","ActiveWorkspaceMatcherContext","ActiveWorkspaceMatcherContextValue","useActiveWorkspace","value","Error","CanvasResource","Events","MediaResource","StudioResource","DocumentHandle","useCallback","useComlinkStore","DocumentInteractionHistory","recordEvent","eventType","UseRecordDocumentHistoryEventProps","resourceType","resourceId","schemaName","useRecordDocumentHistoryEvent","t0","$","_c","documentId","documentType","node","Error","t1","run","message","type","data","document","id","resource","post","t2","error","console","useCallback","useMemo","useState","useSyncObservable","useRenderingContextStore","OperationsAPI","useActiveWorkspace","getVersionId","useRecordDocumentHistoryEvent","Options","api","publishedDocId","docTypeName","version","useDocumentOperationWithComlinkHistory","t0","$","_c","activeWorkspace","t1","t2","dataset","projectId","t3","join","t4","name","resourceType","documentId","documentType","resourceId","schemaName","recordEvent","renderingContextStore","capabilities","hasRecordedEdit","setHasRecordedEdit","t5","next","preRecordPatch","comlink","t6","t7","hasComlink","comlinkContext","t8","withComlinkEvent","operationName","comlinkEventType","withComlinkDelete","t9","withComlinkDel","t10","preRecordEvent","withComlinkPatch","t11","ComlinkEventType","Parameters","ReturnType","ExecuteParameters","OperationName","RecordEvent","PreRecordEvent","WithComlinkEventOptions","execute","args","useMemo","normalizeDocumentPairTarget","DocumentPairTarget","useMemoizedDocumentPairTarget","version","$","_c","t0","target","kind","scopeId","undefined","variantId","allowCreate","t1","bb0","t2","Symbol","for","useMemo","useSyncObservable","useDocumentStore","OperationsAPI","DocumentPairTarget","useDocumentOperationWithComlinkHistory","useMemoizedDocumentPairTarget","useDocumentOperation","publishedDocId","docTypeName","version","$","_c","documentStore","target","t0","pair","editOperations","observable","api","t1","PerspectiveBundle","DocumentPerspectiveState","VersionInfoDocumentStub","getTargetDocument","bundle","documentVersions","variant","find","version","inBundle","_system","bundleId","inVariant","_ref","getVariantPublishedSibling","SystemVariant","VariantDeletedAction","type","payload","id","FetchSucceededAction","VariantsSetAction","LoadingStateChangedAction","loading","error","Error","VariantStoreAction","VariantStoreState","variants","Map","state","createVariantsSet","reduce","acc","variant","set","_id","variantStoreReducer","action","variantsById","undefined","restVariants","delete","SanityClient","Dispatch","catchError","concatWith","merge","Observable","of","scan","shareReplay","Subject","map","startWith","listenQuery","VARIANT_DOCUMENTS_PATH","VARIANT_DOCUMENT_TYPE","variantStoreReducer","VariantStoreAction","VariantStoreState","SORT_FIELD","SORT_ORDER","QUERY_SORT_ORDER","QUERY_FILTER","QUERY_PROJECTION","QUERY","INITIAL_STATE","variants","Map","state","const","VariantStore","state$","dispatch","createVariantsStore","context","client","enabled","disabledState","dispatch$","action","next","listFetch$","type","payload","loading","error","undefined","pipe","tag","useMemo","useClient","useResourceCache","useWorkspace","VARIANTS_STUDIO_CLIENT_OPTIONS","createVariantsStore","VariantStore","useVariantsStore","$","_c","workspace","variantsEnabled","Boolean","beta","variants","enabled","resourceCache","studioClient","variantStore","get","dependencies","namespace","client","set","value","useMemo","useSyncObservable","SystemVariant","useVariantsStore","useAllVariants","$","_c","state$","variants","error","state","t0","Array","from","values","t1","Symbol","for","t2","includes","t3","data","byId","loading","useMemo","PerspectiveBundle","usePerspective","useDocumentVersions","VersionInfoDocumentStub","DocumentPairTarget","getVersionFromId","getTargetDocument","getVariantPublishedSibling","useAllVariants","SystemVariant","CreatableTargetDocument","id","scopeId","TargetDocumentState","status","targetDocument","variant","publishedSibling","bundle","creatableTarget","requestedVariantName","RESOLVING","getCreatableTarget","undefined","draftId","_system","draft","_ref","getTargetScopeId","state","getCreatableVariantTarget","getPairTarget","kind","variantId","_id","allowCreate","getTargetDocumentState","options","selectedVariant","selectedVariantName","variantsLoading","versions","versionsLoading","documentVersions","useTargetDocumentState","documentGroupId","$","_c","t0","documentId","loading","t1","SanityClient","SanityDocument","Schema","SchemaType","useMemo","combineLatest","Observable","of","map","shareReplay","switchMap","useClient","useSchema","DEFAULT_STUDIO_CLIENT_OPTIONS","createHookFromObservableFactory","getDraftId","getPublishedId","getIdPair","PartialExcept","useGrantsStore","snapshotPair","DocumentStoreExtraOptions","memoize","useCurrentUser","GrantsStore","PermissionCheckResult","shareLatestWithRefCount","T","bufferSize","refCount","getSchemaType","schema","typeName","type","get","Error","PairPermissionsOptions","grantsStore","permission","DocumentPermission","draft","version","published","liveEdit","getPairPermissions","Array","effectiveVersion","effectiveVersionType","checkDocumentPermission","_id","DocumentPairPermissionsOptions","client","id","userId","serverActionsEnabled","pairListenerOptions","getDocumentPairPermissionsUncached","v","granted","reason","Boolean","undefined","pipe","pair","snapshots$","pairPermissions","label","observable","length","permissionResults","every","permissionResult","filter","join","getDocumentPairPermissions","options","dataset","projectId","config","useDocumentPairPermissionsFromHookFactory","useDocumentPairPermissions","t0","$","_c","overrideClient","overrideSchema","overrideGrantsStore","defaultClient","defaultSchema","defaultGrantsStore","currentUser","t1","RELEASE_DOCUMENTS_PATH","getReleaseDocumentIdFromReleaseId","name","useContext","ReleasesUpsellContext","ReleasesUpsellContextValue","useReleasesUpsell","value","FALLBACK_CONTEXT_VALUE","upsellDialogOpen","mode","const","onReleaseLimitReached","guardWithReleaseLimitUpsell","undefined","handleOpenDialog","upsellData","telemetryLogs","dialogSecondaryClicked","dialogPrimaryClicked","panelViewed","panelDismissed","panelPrimaryClicked","panelSecondaryClicked","ErrorWithDetails","details","type","isErrorWithDetails","error","isErrorWithDetails","ReleaseLimitError","details","type","limit","isReleaseLimitError","error","BaseActionOptions","CreateVersionAction","DiscardVersionAction","EditableReleaseDocument","IdentifiedSanityDocumentStub","ReleaseDocument","SanityClient","SingleActionResult","getDraftId","getPublishedId","getVersionFromId","getVersionId","ReleasesUpsellContextValue","RevertDocument","getReleaseIdFromReleaseDocumentId","isReleaseLimitError","ReleaseOperationsStore","publishRelease","releaseId","opts","Promise","discardDrafts","documentIds","schedule","date","Date","unschedule","archive","unarchive","updateRelease","release","createRelease","deleteRelease","revertRelease","revertReleaseId","documents","releaseMetadata","revertType","duplicateRelease","releaseDocumentId","releaseDocuments","createVersion","documentId","discardVersion","unpublishVersion","revertUnpublishVersion","createReleaseOperationsStore","options","client","onReleaseLimitReached","handleReleaseLimitError","action","dryRun","catch","error","details","limit","handleCreateRelease","releases","create","_id","metadata","handleUpdateRelease","unsetKeys","Object","entries","filter","_","value","undefined","map","key","edit","patch","set","unset","handlePublishRelease","publish","handleDiscardDrafts","draftIds","Set","length","existingDraftIds","fetch","perspective","tag","discardDraftActions","draftId","actionType","versionId","handleScheduleRelease","publishAt","toISOString","handleUnscheduleRelease","handleArchiveRelease","handleUnarchiveRelease","handleDeleteRelease","delete","handleCreateVersion","document","getDocument","Error","baseId","ifBaseRevisionId","_rev","publishedId","handleDiscardVersion","handleUnpublishVersion","handleRevertRelease","title","description","releaseType","cardinality","newVersionDocumentActions","releaseDocument","handleDuplicateRelease","duplicateVersionDocumentActions","handleRevertUnpublishVersion","useMemo","useClient","useReleasesUpsell","RELEASES_STUDIO_CLIENT_OPTIONS","createReleaseOperationsStore","useReleaseOperations","$","_c","studioClient","onReleaseLimitReached","t0","client","ReleaseDocument","useMemo","useSyncObservable","sortReleases","useReleasesStore","useAllReleases","$","_c","state$","releases","error","state","t0","Array","from","values","t1","Symbol","for","t2","includes","t3","data","map","loading","schedulerYield","promise","Promise","Result","window","scheduler","yield","CurrentUser","isValidationErrorMarker","SanityDocument","Schema","uuid","useMemo","useObservable","combineLatest","from","Observable","of","mergeMapArray","catchError","delay","filter","finalize","map","shareReplay","switchMap","useSchema","LocaleSource","DocumentPreviewStore","useDocumentPreviewStore","useSource","schedulerYield","validateDocumentWithReferences","ValidationStatus","RELEASES_STUDIO_CLIENT_OPTIONS","bundleDocumentsCache","Record","BundleDocumentsObservableResult","Object","create","resetBundleDocumentsCacheForTests","key","keys","DocumentValidationStatus","hasError","BundleDocument","memoKey","isPending","document","publishedDocumentExists","draftDocumentExists","validation","loading","results","error","Error","BundleDocumentsObservableOptions","schema","documentPreviewStore","i18n","getClient","ReturnType","currentUser","Omit","groqFilter","params","skipValidation","buildBundleDocumentsObservable","createValidationObservable","ctx","isValidating","revision","_rev","Promise","resolve","pipe","validationStatus","some","marker","processDocument","id","observeDocument","unstable_observeDocument","observeDocumentPairAvailability","unstable_observeDocumentPairAvailability","document$","apiVersion","Boolean","doc","availability","published","available","draft","validation$","processDocumentIdsGroup","documentIdsGroup","groupIndex","batchDelay","unstable_observeDocumentIdSet","state","documentIds","length","batchSize","documentIdsGroups","i","push","slice","batch","batchIndex","groupResults","flat","getBundleDocumentsObservable","cacheKey","options","BUNDLE_DOCUMENTS_EMPTY","BUNDLE_DOCUMENTS_LOADING","useBundleDocuments","$","_c","enabled","t0","undefined","t1","bundleDocumentsObservable"],"sources":["../src/core/releases/store/types.ts","../src/core/util/releaseUtils.ts","../src/core/releases/util/const.ts","../src/core/util/formatRelativeLocale.ts","../src/core/releases/util/createReleaseId.ts","../src/core/releases/util/util.ts","../src/core/releases/util/getReleaseTone.ts","../src/core/releases/hooks/utils.ts","../src/core/releases/store/createReleaseMetadataAggregator.ts","../src/core/releases/store/reducer.ts","../src/core/releases/store/createReleaseStore.ts","../src/core/releases/store/useReleasesStore.ts","../src/core/releases/store/useActiveReleases.ts","../src/core/components/previews/constants.ts","../src/core/components/previews/_common/Media.styled.ts","../src/core/components/previews/_common/Media.tsx","../src/core/components/previews/helpers.tsx","../src/core/components/previews/general/CompactPreview.tsx","../src/core/components/progress/LinearProgress.tsx","../src/core/components/previews/general/DefaultPreview.tsx","../src/core/components/previews/general/DetailPreview.styled.ts","../src/core/components/previews/general/DetailPreview.tsx","../src/core/components/progress/CircularProgress.tsx","../src/core/components/previews/general/MediaPreview.styled.ts","../src/core/components/previews/general/MediaPreview.tsx","../src/core/components/previews/portableText/BlockImagePreview.styled.tsx","../src/core/components/previews/portableText/BlockImagePreview.tsx","../src/core/components/previews/portableText/BlockPreview.tsx","../src/core/components/previews/portableText/InlinePreview.styled.tsx","../src/core/components/previews/portableText/InlinePreview.tsx","../src/core/config/definePlugin.ts","../src/core/deprecatedPlugins/DeprecatedScheduledPublishing.tsx","../src/core/config/flattenConfig.ts","../src/core/config/components/useMiddlewareComponents.tsx","../src/core/util/isString.ts","../src/core/util/createMediaLibraryClient.ts","../src/core/store/accessPolicy/refs.ts","../src/core/store/accessPolicy/fetch.ts","../src/core/form/inputs/files/ImageInput/useAccessPolicy.ts","../src/core/form/studio/assetSourceMediaLibrary/constants.ts","../src/core/form/studio/assetSourceMediaLibrary/hooks/useToken.ts","../src/core/form/inputs/files/ImageInput/useImageObjectUrl.ts","../src/core/form/inputs/files/ImageInput/useImageUrl.ts","../src/core/preview/components/_previewComponents.ts","../src/core/preview/components/SanityDefaultPreview.tsx","../src/core/form/studio/inputResolver/previewResolver.ts","../src/core/form/form-components-hooks/picks.ts","../src/core/form/form-components-hooks/useResolveDefaultComponent.tsx","../src/core/form/form-components-hooks/usePreviewComponent.tsx","../src/core/perspective/usePerspective.ts","../src/core/releases/util/isGoingToUnpublish.ts","../src/core/preview/useValuePreview.ts","../src/core/preview/streams/orientationChange.ts","../src/core/preview/streams/resize.ts","../src/core/preview/streams/scroll.ts","../src/core/preview/streams/intersectionObservableFor.ts","../src/core/preview/streams/visibilityChange.ts","../src/core/preview/useVisibility.ts","../src/core/preview/components/_constants.ts","../src/core/preview/components/_extractUploadState.ts","../src/core/preview/components/PreviewLoader.tsx","../src/core/preview/components/Preview.tsx","../src/core/hooks/useDataset.ts","../src/core/releases/hooks/useDocumentVersions.tsx","../src/core/studio/activeWorkspaceMatcher/useActiveWorkspace.ts","../src/core/hooks/useRecordDocumentHistoryEvent.ts","../src/core/hooks/useDocumentOperationWithComlinkHistory.ts","../src/core/hooks/useMemoizedDocumentPairTarget.ts","../src/core/hooks/useDocumentOperation.ts","../src/core/util/getTargetDocument.ts","../src/core/variants/store/reducer.ts","../src/core/variants/store/createVariantsStore.ts","../src/core/variants/store/useVariantsStore.ts","../src/core/variants/store/useAllVariants.ts","../src/core/hooks/useTargetDocumentState.ts","../src/core/store/grants/documentPairPermissions.ts","../src/core/releases/util/getReleaseDocumentIdFromReleaseId.ts","../src/core/releases/contexts/upsell/useReleasesUpsell.ts","../src/core/error/types/isErrorWithDetails.ts","../src/core/releases/store/isReleaseLimitError.ts","../src/core/releases/store/createReleaseOperationStore.ts","../src/core/releases/store/useReleaseOperations.ts","../src/core/releases/store/useAllReleases.ts","../src/core/util/schedulerYield.ts","../src/core/releases/tool/detail/useBundleDocuments.ts"],"sourcesContent":["import {type ReleaseDocument, type ReleaseType} from '@sanity/client'\nimport {type DocumentSystem} from '@sanity/types'\nimport {type Dispatch} from 'react'\nimport {type Observable} from 'rxjs'\n\nimport {RELEASE_DOCUMENT_TYPE} from './constants'\nimport {type MetadataWrapper} from './createReleaseMetadataAggregator'\nimport {type ReleasesReducerAction, type ReleasesReducerState} from './reducer'\n\n/**\n * @beta\n */\nexport const releaseTypes = ['asap', 'scheduled', 'undecided'] as const\n\n/**\n * @beta\n */\nexport function isReleaseType(maybeReleaseType: unknown): maybeReleaseType is ReleaseType {\n return (\n typeof maybeReleaseType === 'string' && releaseTypes.includes(maybeReleaseType as ReleaseType)\n )\n}\n\n/**\n * @internal\n */\nexport function isReleaseDocument(doc: unknown): doc is ReleaseDocument {\n return (\n typeof doc === 'object' && doc !== null && '_type' in doc && doc._type === RELEASE_DOCUMENT_TYPE\n )\n}\n\n/**\n * @internal\n */\nexport interface ReleaseStore {\n state$: Observable<ReleasesReducerState>\n /**\n * Counts all loaded release documents that are in an active state and have an error recorded.\n * This is determined by the presence of the `error` field in the release document.\n */\n errorCount$: Observable<number>\n getMetadataStateForSlugs$: (slugs: string[]) => Observable<MetadataWrapper>\n dispatch: Dispatch<ReleasesReducerAction>\n}\n\n/**\n * @internal\n */\nexport interface VersionInfoDocumentStub {\n _id: string\n _rev: string\n _createdAt: string\n _updatedAt: string\n _system: DocumentSystem\n}\n","import {type ReleaseDocument} from '@sanity/client'\n\nimport {isReleaseDocument} from '../releases/store/types'\n\n/**\n * A release document with cardinality 'one'\n *\n * @internal\n */\nexport type CardinalityOneRelease = ReleaseDocument & {\n metadata: ReleaseDocument['metadata'] & {\n cardinality: 'one'\n }\n}\n\n/**\n * Check if the release is a cardinality one release\n *\n * @internal\n */\nexport function isCardinalityOneRelease(\n release: ReleaseDocument,\n): release is CardinalityOneRelease {\n return release.metadata?.cardinality === 'one'\n}\n\n/**\n * Check if perspective represents a cardinality one release\n *\n * @internal\n */\nexport function isCardinalityOnePerspective(\n perspective: unknown,\n): perspective is CardinalityOneRelease {\n return isReleaseDocument(perspective) && isCardinalityOneRelease(perspective)\n}\n\n/**\n * Checks if a release is a paused cardinality one release (scheduled draft).\n *\n * @internal\n */\nexport function isPausedCardinalityOneRelease(release: ReleaseDocument | undefined): boolean {\n if (!release) return false\n return (\n release.state === 'active' &&\n release.metadata.releaseType === 'scheduled' &&\n isCardinalityOneRelease(release) &&\n Boolean(release.metadata.intendedPublishAt)\n )\n}\n","import {type ReleaseType} from '@sanity/client'\nimport {type BadgeTone} from '@sanity/ui'\n\n/**\n * @internal\n */\nexport const LATEST = 'drafts' as const\n\n/**\n * @internal\n */\nexport const PUBLISHED = 'published' as const\n\n/**\n * @internal\n */\nexport const DEFAULT_RELEASE_TYPE = 'asap'\n\n/**\n * @internal\n */\nexport const ARCHIVED_RELEASE_STATES = ['archived', 'published']\n\n/**\n * @internal\n */\nexport const RELEASE_TYPES_TONES: Record<ReleaseType, {tone: BadgeTone}> = {\n asap: {\n tone: 'caution',\n },\n scheduled: {\n tone: 'suggest',\n },\n undecided: {\n tone: 'neutral',\n },\n}\n","import {tz as tzHelper} from '@date-fns/tz'\nimport {formatRelative} from 'date-fns/formatRelative'\nimport {isValid} from 'date-fns/isValid'\nimport {parse} from 'date-fns/parse'\n\ntype DateInput = Date | number | string\n\nconst RUNTIME_TIME_ZONE = Intl.DateTimeFormat().resolvedOptions().timeZone\n\n/**\n * Renders `date` relative to `baseDate` in `timeZone`. Replaces date-fns's en-US\n * `MM/dd/yyyy` fallback (used for dates more than ~6 days out) with the browser's\n * locale date format, so non-en-US users don't see American-style dates.\n *\n * `timeZone` defaults to the host runtime's TZ. Pass an explicit IANA zone for\n * non-browser contexts or to render in the user's selected studio timezone (e.g.\n * via a hook that wraps `useTimeZone`).\n *\n * @internal\n */\nexport const formatRelativeLocale = (\n date: DateInput,\n baseDate: DateInput,\n timeZone: string = RUNTIME_TIME_ZONE,\n): string => {\n const relative = formatRelative(date, baseDate, {in: tzHelper(timeZone)})\n // Detect date-fns's en-US `MM/dd/yyyy` fallback and swap in a browser-locale string.\n if (isValid(parse(relative, 'MM/dd/yyyy', new Date()))) {\n return new Date(date).toLocaleDateString(undefined, {timeZone})\n }\n return relative\n}\n","import {customAlphabet} from 'nanoid'\n\nimport {RELEASE_DOCUMENTS_PATH} from '../store/constants'\n\n/**\n * ~24 years (or 7.54e+8 seconds) needed, in order to have a 1% probability of at least one collision if 10 ID's are generated every hour.\n */\nconst createBundleId = customAlphabet(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',\n 8,\n)\n\n/**\n * Create a unique release id. This is used as the release id for documents included in the release.\n * @internal\n */\nexport function createReleaseId() {\n return `${RELEASE_DOCUMENTS_PATH}.r${createBundleId()}`\n}\n","import {type EditableReleaseDocument, type ReleaseDocument, type ReleaseState} from '@sanity/client'\nimport {type DocumentSystem} from '@sanity/types'\n\nimport {type TargetPerspective} from '../../perspective/types'\nimport {getVersionFromId, isVersionId} from '../../util/draftUtils'\nimport {formatRelativeLocale} from '../../util/formatRelativeLocale'\nimport {isCardinalityOneRelease, isPausedCardinalityOneRelease} from '../../util/releaseUtils'\nimport {type CardinalityView, type Mode} from '../tool/overview/queryParamUtils'\nimport {DEFAULT_RELEASE_TYPE, LATEST} from './const'\nimport {createReleaseId} from './createReleaseId'\nimport {getReleaseIdFromReleaseDocumentId} from './getReleaseIdFromReleaseDocumentId'\n\n/** @internal */\nexport type NotArchivedRelease = ReleaseDocument & {state: Exclude<ReleaseState, 'archived'>}\n\n/**\n * @beta\n * @param documentId - The document id, e.g. `my-document-id` or `drafts.my-document-id` or `summer.my-document-id`\n * @param perspective - The current perspective, e.g. `release.summer` or undefined, it can be obtained from `useRouter().stickyParams.perspective`\n * @returns boolean - `true` if the document is in the current perspective.\n * e.g:\n * - document: `summer.my-document-id`, perspective: `release.summer` : **true**\n * - document: `my-document-id`, perspective: `release.summer` : **false**\n * - document: `summer.my-document-id`perspective: `release.winter` : **false**\n * - document: `summer.my-document-id`, perspective: `undefined` : **false**\n * - document: `my-document-id`, perspective: `undefined` : **true**\n * - document: `drafts.my-document-id`, perspective: `undefined` : **true**\n */\nexport function getDocumentIsInPerspective(\n documentId: string,\n perspective: string | undefined,\n): boolean {\n const releaseId = getVersionFromId(documentId)\n\n if (!perspective) return !isVersionId(documentId)\n\n if (typeof perspective === 'undefined') return false\n // perspective is `release.${releaseId}`\n\n if (releaseId === 'Published') return false\n return releaseId === perspective\n}\n\n/** @internal */\nexport function getPublishDateFromRelease(release: ReleaseDocument): Date | null {\n const dateString = release.publishedAt || release.publishAt || release.metadata.intendedPublishAt\n\n if (!dateString) return null\n\n return new Date(dateString)\n}\n\n/**\n * Formats a release's publish date as a locale-aware relative string. `timeZone`\n * defaults to the host runtime's TZ; inside React components, prefer\n * `useFormatRelativeLocalePublishDate` to bind the studio's selected timezone.\n *\n * @internal\n */\nexport function formatRelativeLocalePublishDate(\n release: ReleaseDocument,\n timeZone?: string,\n): string {\n const publishDate = getPublishDateFromRelease(release)\n\n if (!publishDate) return ''\n return formatRelativeLocale(publishDate, new Date(), timeZone)\n}\n\n/** @internal */\nexport function isPublishedPerspective(\n perspective: TargetPerspective | string,\n): perspective is 'published' {\n return perspective === 'published'\n}\n\n/** @internal */\nexport function isDraftPerspective(\n perspective: TargetPerspective | string,\n): perspective is 'drafts' {\n return perspective === LATEST\n}\n\n/** @internal */\nexport function isReleaseScheduledOrScheduling(release: ReleaseDocument): boolean {\n return (\n release.metadata.releaseType === 'scheduled' &&\n (release.state === 'scheduled' || release.state === 'scheduling')\n )\n}\n\n/** @internal */\nexport const getReleaseDefaults: () => EditableReleaseDocument = () => ({\n _id: createReleaseId(),\n metadata: {\n title: '',\n description: '',\n releaseType: DEFAULT_RELEASE_TYPE,\n cardinality: 'many',\n },\n})\n\n/**\n * Check if the release is archived\n *\n * @internal */\nexport function isNotArchivedRelease(release: ReleaseDocument): release is NotArchivedRelease {\n return release.state !== 'archived'\n}\n\n/**\n * @internal\n */\nexport function shouldShowReleaseInView(\n cardinalityView: CardinalityView,\n): (release: ReleaseDocument) => boolean {\n return (release: ReleaseDocument): boolean => {\n const isCardinalityOne = isCardinalityOneRelease(release)\n // Show cardinality 'one' releases in 'drafts' view, and cardinality 'many'/undefined in 'releases' view\n return cardinalityView === 'drafts' ? isCardinalityOne : !isCardinalityOne\n }\n}\n\n/** @internal */\nexport interface FilterReleasesOptions<T extends ReleaseDocument> {\n releases: T[]\n archivedReleases: T[]\n cardinalityView: CardinalityView\n releaseGroupMode: Mode\n dateFilter?: {\n filterDate: Date\n getTimezoneAdjustedDateTimeRange: (date: Date) => [Date, Date]\n }\n}\n\n/** @internal */\nexport function filterReleasesForOverview<T extends ReleaseDocument>(\n options: FilterReleasesOptions<T>,\n): T[] {\n const {releases, archivedReleases, cardinalityView, releaseGroupMode, dateFilter} = options\n\n const sourceReleases = releaseGroupMode === 'archived' ? archivedReleases : releases\n\n const applyDateFilter = (items: T[]): T[] => {\n if (!dateFilter) return items\n\n const [startOfDayForTimeZone, endOfDayForTimeZone] =\n dateFilter.getTimezoneAdjustedDateTimeRange(dateFilter.filterDate)\n\n return items.filter((release) => {\n const publishAt = release.publishAt || release.metadata.intendedPublishAt\n if (!publishAt || release.metadata.releaseType !== 'scheduled') return false\n\n const publishDateUTC = new Date(publishAt)\n return publishDateUTC >= startOfDayForTimeZone && publishDateUTC <= endOfDayForTimeZone\n })\n }\n\n const dateFiltered = applyDateFilter(sourceReleases)\n\n if (cardinalityView !== 'drafts') return dateFiltered\n\n if (releaseGroupMode === 'active') {\n return dateFiltered.filter(\n (release) => release.state === 'scheduled' || release.state === 'scheduling',\n )\n }\n\n if (releaseGroupMode === 'paused') {\n return dateFiltered.filter((release) => isPausedCardinalityOneRelease(release))\n }\n\n return dateFiltered\n}\n","import {type BadgeTone} from '@sanity/ui'\n\nimport {type TargetPerspective} from '../../perspective/types'\nimport {isAgentBundleName} from '../../store/agent/createAgentBundlesStore'\nimport {isPausedCardinalityOneRelease} from '../../util/releaseUtils'\nimport {isReleaseDocument} from '../store/types'\nimport {RELEASE_TYPES_TONES} from './const'\nimport {isDraftPerspective, isPublishedPerspective} from './util'\n\n/** @internal */\nexport function getReleaseTone(release: TargetPerspective): BadgeTone {\n if (isPublishedPerspective(release)) return 'positive'\n if (isDraftPerspective(release)) return 'default'\n\n if (isReleaseDocument(release)) {\n if (release.state === 'archived') {\n return 'default'\n }\n\n if (release?.metadata?.releaseType === 'asap') {\n return RELEASE_TYPES_TONES.asap.tone\n }\n\n if (release?.metadata?.releaseType === 'undecided') {\n return RELEASE_TYPES_TONES.undecided.tone\n }\n\n if (isPausedCardinalityOneRelease(release)) {\n return 'caution'\n }\n\n if (release?.metadata?.releaseType === 'scheduled') {\n return RELEASE_TYPES_TONES.scheduled.tone\n }\n }\n\n if (isAgentBundleName(release)) return 'suggest'\n\n return 'default'\n}\n","import {type ClientPerspective, type ReleaseDocument} from '@sanity/client'\n\nimport {type PerspectiveStack, type ReleaseId} from '../../perspective/types'\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\n\n/**\n * Sorts releases by their release type and created date.\n * @internal\n */\nexport function sortReleases(releases: ReleaseDocument[] = []): ReleaseDocument[] {\n // The order should always be:\n // [undecided (sortByCreatedAt), scheduled(sortBy publishAt || metadata.intendedPublishAt), asap(sortByCreatedAt)]\n return [...releases].sort((a, b) => {\n // undecided are always first, then by createdAt descending\n if (a.metadata.releaseType === 'undecided' && b.metadata.releaseType !== 'undecided') {\n return -1\n }\n if (a.metadata.releaseType !== 'undecided' && b.metadata.releaseType === 'undecided') {\n return 1\n }\n if (a.metadata.releaseType === 'undecided' && b.metadata.releaseType === 'undecided') {\n // Sort by createdAt\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n\n // Scheduled are always at the middle, then by publishAt descending\n if (a.metadata.releaseType === 'scheduled' && b.metadata.releaseType === 'scheduled') {\n const aPublishAt = a.publishAt || a.metadata.intendedPublishAt\n if (!aPublishAt) {\n return 1\n }\n const bPublishAt = b.publishAt || b.metadata.intendedPublishAt\n if (!bPublishAt) {\n return -1\n }\n return new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime()\n }\n\n // ASAP are always last, then by createdAt descending\n if (a.metadata.releaseType === 'asap' && b.metadata.releaseType !== 'asap') {\n return 1\n }\n if (a.metadata.releaseType !== 'asap' && b.metadata.releaseType === 'asap') {\n return -1\n }\n if (a.metadata.releaseType === 'asap' && b.metadata.releaseType === 'asap') {\n // Sort by createdAt\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n\n return 0\n })\n}\nconst DRAFTS: ['drafts'] = ['drafts']\nconst PUBLISHED: ['published'] = ['published']\nconst EMPTY: [] = []\n\nexport function getReleasesPerspectiveStack({\n selectedPerspectiveName,\n releases,\n excludedPerspectives,\n isDraftModelEnabled,\n}: {\n selectedPerspectiveName: ReleaseId | undefined | 'published'\n releases: ReleaseDocument[]\n excludedPerspectives: string[]\n isDraftModelEnabled: boolean\n}): PerspectiveStack {\n const defaultPerspective = isDraftModelEnabled ? DRAFTS : PUBLISHED\n if (!selectedPerspectiveName) {\n return defaultPerspective\n }\n if (selectedPerspectiveName === 'published') {\n return PUBLISHED\n }\n\n const sorted: ClientPerspective = sortReleases(releases).map((release) =>\n getReleaseIdFromReleaseDocumentId(release._id),\n )\n const selectedIndex = sorted.indexOf(selectedPerspectiveName)\n if (selectedIndex === -1) {\n // we're in a non-release stack\n return [selectedPerspectiveName, ...defaultPerspective]\n }\n return sorted\n .slice(selectedIndex)\n .concat(defaultPerspective)\n .filter((name) => !excludedPerspectives.includes(name))\n}\n","import {type SanityClient} from '@sanity/client'\nimport {\n bufferTime,\n catchError,\n EMPTY,\n filter,\n iif,\n merge,\n type Observable,\n of,\n startWith,\n switchMap,\n} from 'rxjs'\n\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\nimport {type ReleasesMetadata} from './useReleasesMetadata'\n\nexport type ReleasesMetadataMap = Record<string, ReleasesMetadata>\n\nexport type MetadataWrapper = {data: ReleasesMetadataMap | null; error: null; loading: boolean}\n\nconst getFetchQuery = (releaseIds: string[]) => {\n // projection key must be string - cover the case that a bundle has a number as first char\n const getSafeKey = (id: string) => `release_${id.replaceAll('-', '_')}`\n\n return releaseIds.reduce(\n ({subquery: accSubquery, projection: accProjection}, releaseId) => {\n const bundleId = getReleaseIdFromReleaseDocumentId(releaseId)\n // get a version of the id that is safe to use as key in objects\n const safeId = getSafeKey(bundleId)\n\n const subquery = `${accSubquery}\"${safeId}\": *[sanity::partOfRelease(\"${bundleId}\")]{_updatedAt, \"docId\": string::split(_id, \".\")[2] } | order(_updatedAt desc),`\n\n const projection = `${accProjection}\"${releaseId}\": {\n \"updatedAt\": ${safeId}[0]._updatedAt,\n \"documentIds\": ${safeId}[].docId,\n },`\n\n return {subquery, projection}\n },\n {subquery: '', projection: ''},\n )\n}\n\n/**\n * @internal\n *\n * An initial fetch is made. This fetch is polled whenever a listener even is emitted\n * Only releases that have been mutated are re-fetched\n *\n * @returns an Observable that accepts a list of release slugs and returns a stream of metadata\n */\nexport const createReleaseMetadataAggregator = (client: SanityClient | null) => {\n const aggregatorFetch$ = (\n releaseIds: string[],\n isInitialLoad: boolean = false,\n ): Observable<MetadataWrapper> => {\n if (!releaseIds?.length || !client) return of({data: null, error: null, loading: false})\n\n const {subquery: queryAllDocumentsInReleases, projection: projectionToBundleMetadata} =\n getFetchQuery(releaseIds)\n\n const fetchData$ = client.observable\n .fetch<\n Record<\n string,\n Omit<ReleasesMetadata, 'existingDocumentCount'> & {\n documentIds: string[]\n }\n >\n >(\n `{${queryAllDocumentsInReleases}}{${projectionToBundleMetadata}}`,\n {},\n {tag: 'release-docs.fetch'},\n )\n .pipe(\n switchMap((releaseDocumentIdResponse) =>\n of({\n data: Object.entries(releaseDocumentIdResponse).reduce((existing, el) => {\n const [releaseId, metadata] = el\n return {\n ...existing,\n [releaseId]: {...metadata, documentCount: metadata.documentIds?.length || 0},\n }\n }, {}),\n error: null,\n loading: false,\n }),\n ),\n catchError((error) => {\n console.error('Failed to fetch release metadata', error)\n return of({data: null, error, loading: false})\n }),\n )\n\n // initially emit loading empty state if first fetch\n return iif(\n () => isInitialLoad,\n fetchData$.pipe(startWith({loading: true, data: null, error: null})),\n fetchData$,\n )\n }\n\n const aggregatorListener$ = (releaseIds: string[]) => {\n if (!releaseIds?.length || !client) return EMPTY\n\n return client.observable\n .listen(\n `*[(${releaseIds.reduce(\n (accQuery, releaseId, index) =>\n `${accQuery}${index === 0 ? '' : ' ||'} sanity::partOfRelease(\"${releaseId}\")`,\n '',\n )})]`,\n {},\n {\n includeResult: true,\n includeAllVersions: true,\n visibility: 'query',\n events: ['mutation'],\n tag: 'release-docs.listen',\n },\n )\n .pipe(\n catchError((error) => {\n console.error('Failed to listen for release metadata', error)\n return EMPTY\n }),\n bufferTime(1_000),\n filter((entriesArray) => entriesArray.length > 0),\n switchMap((entriesArray) => {\n const mutatedReleaseIds = entriesArray.reduce<string[]>((accReleaseIds, event) => {\n if ('type' in event && event.type === 'mutation') {\n const releaseId = event.documentId.split('.')[1]\n // de-dup mutated bundle slugs\n if (accReleaseIds.includes(releaseId)) return accReleaseIds\n\n return [...accReleaseIds, releaseId]\n }\n return accReleaseIds\n }, [])\n\n if (mutatedReleaseIds.length) {\n return aggregatorFetch$(mutatedReleaseIds)\n }\n\n return EMPTY\n }),\n )\n }\n\n return (releaseIds: string[]) =>\n merge(aggregatorFetch$(releaseIds, true), aggregatorListener$(releaseIds))\n}\n","import {type ReleaseDocument} from '@sanity/client'\n\ninterface BundleDeletedAction {\n id: string\n currentUserId?: string\n deletedByUserId: string\n type: 'BUNDLE_DELETED'\n}\n\ninterface ReleasesSetAction {\n payload: ReleaseDocument[] | null\n type: 'RELEASES_SET'\n}\n\ninterface LoadingStateChangedAction {\n payload: {\n loading: boolean\n error: Error | undefined\n }\n type: 'LOADING_STATE_CHANGED'\n}\n\nexport type ReleasesReducerAction =\n | BundleDeletedAction\n | ReleasesSetAction\n | LoadingStateChangedAction\n\nexport interface ReleasesReducerState {\n releases: Map<string, ReleaseDocument>\n state: 'initialising' | 'loading' | 'loaded' | 'error'\n error?: Error\n}\n\nfunction createReleasesSet(releases: ReleaseDocument[] | null) {\n return (releases ?? []).reduce((acc, bundle) => {\n acc.set(bundle._id, bundle)\n return acc\n }, new Map<string, ReleaseDocument>())\n}\n\nexport function releasesReducer(\n state: ReleasesReducerState,\n action: ReleasesReducerAction,\n): ReleasesReducerState {\n switch (action.type) {\n case 'LOADING_STATE_CHANGED': {\n return {\n ...state,\n state: action.payload.loading ? 'loading' : 'loaded',\n error: action.payload.error,\n }\n }\n\n case 'RELEASES_SET': {\n // Create an object with the BUNDLE id as key\n const releasesById = createReleasesSet(action.payload)\n\n return {\n ...state,\n releases: releasesById,\n }\n }\n\n default:\n return state\n }\n}\n","import {type ReleaseDocument, type ReleaseType, type SanityClient} from '@sanity/client'\nimport {\n BehaviorSubject,\n catchError,\n concat,\n concatWith,\n count,\n filter,\n from,\n merge,\n type Observable,\n of,\n type OperatorFunction,\n pipe,\n scan,\n shareReplay,\n Subject,\n switchMap,\n tap,\n} from 'rxjs'\nimport {distinctUntilChanged, map, startWith} from 'rxjs/operators'\n\nimport {type DocumentPreviewStore} from '../../preview/documentPreviewStore'\nimport {listenQuery} from '../../store/document/listenQuery'\nimport {RELEASE_DOCUMENT_TYPE, RELEASE_DOCUMENTS_PATH} from './constants'\nimport {createReleaseMetadataAggregator} from './createReleaseMetadataAggregator'\nimport {releasesReducer, type ReleasesReducerAction, type ReleasesReducerState} from './reducer'\nimport {type ReleaseStore} from './types'\n\ntype ActionWrapper = {action: ReleasesReducerAction}\ntype ResponseWrapper = {response: ReleaseDocument[]}\n\nconst SORT_FIELD = '_createdAt'\nconst SORT_ORDER = 'desc'\n\nconst QUERY_FILTER = `_type==\"${RELEASE_DOCUMENT_TYPE}\" && _id in path(\"${RELEASE_DOCUMENTS_PATH}.*\")`\n\nconst DEFAULT_RELEASE_TYPE: ReleaseType = 'undecided'\nconst QUERY_PROJECTION = `{\n _id,\n _type,\n _rev,\n _createdAt,\n _updatedAt,\n state,\n finalDocumentStates,\n publishAt,\n publishedAt,\n \"metadata\": coalesce(metadata, {\n \"title\": \"\",\n \"releaseType\": \"${DEFAULT_RELEASE_TYPE}\",\n }),\n // Content Lake initially encoded non-error states as {error: {message: \"\"}}. This projection\n // ensures the error field only appears if the document has a non-empty error message.\n ...select(\n length(error.message) > 0 => { error },\n {}\n ),\n}`\n\n// Newest releases first\nconst QUERY_SORT_ORDER = `order(${SORT_FIELD} ${SORT_ORDER})`\n\nconst QUERY = `*[${QUERY_FILTER}] ${QUERY_PROJECTION} | ${QUERY_SORT_ORDER}`\n\nconst INITIAL_STATE: ReleasesReducerState = {\n releases: new Map(),\n state: 'initialising' as const,\n}\n\n/**\n * The releases store is initialised lazily when first subscribed to. Upon subscription, it will\n * fetch a list of releases and create a listener to keep the locally held state fresh.\n *\n * The store is not disposed of when all subscriptions are closed. After it has been initialised,\n * it will keep listening for the duration of the app's lifecycle. Subsequent subscriptions will be\n * given the latest state upon subscription.\n */\nexport function createReleaseStore(context: {\n previewStore: DocumentPreviewStore\n client: SanityClient\n}): ReleaseStore {\n const {client} = context\n\n const dispatch$ = new Subject<ReleasesReducerAction>()\n const fetchPending$ = new BehaviorSubject<boolean>(false)\n\n function dispatch(action: ReleasesReducerAction): void {\n dispatch$.next(action)\n }\n\n const listFetch$ = of<ActionWrapper>({\n action: {\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: true,\n error: undefined,\n },\n },\n }).pipe(\n // Ignore invocations while the list fetch is pending.\n filter(() => !fetchPending$.value),\n tap(() => fetchPending$.next(true)),\n concatWith(\n listenQuery(client, QUERY, {}, {tag: 'releases.listen'}).pipe(\n tap(() => fetchPending$.next(false)),\n map((releases) => ({response: releases})),\n ),\n ),\n\n catchError((error) =>\n of<ActionWrapper>({\n action: {\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: false,\n error,\n },\n },\n }),\n ),\n switchMap<ActionWrapper | ResponseWrapper, Observable<ReleasesReducerAction | undefined>>(\n (entry) => {\n if ('action' in entry) {\n return of<ReleasesReducerAction>(entry.action)\n }\n\n return of<ReleasesReducerAction[]>(\n {type: 'RELEASES_SET', payload: entry.response},\n {\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: false,\n error: undefined,\n },\n },\n )\n },\n ),\n )\n\n const state$ = concat(merge(listFetch$, dispatch$)).pipe(\n filter((action): action is ReleasesReducerAction => typeof action !== 'undefined'),\n scan((state, action) => releasesReducer(state, action), INITIAL_STATE),\n startWith(INITIAL_STATE),\n shareReplay(1),\n )\n\n const errorCount$ = state$.pipe(releaseStoreErrorCount(), shareReplay(1))\n\n const getMetadataStateForSlugs$ = createReleaseMetadataAggregator(client)\n\n return {\n state$,\n errorCount$,\n getMetadataStateForSlugs$,\n dispatch,\n }\n}\n\n/**\n * @internal\n */\nfunction releaseStoreErrorCount(): OperatorFunction<ReleasesReducerState, number> {\n return pipe(\n switchMap(({releases}) =>\n from(releases.values()).pipe(\n filter((release) => release.state === 'active'),\n filter((release) => typeof release.error !== 'undefined'),\n count(),\n ),\n ),\n distinctUntilChanged(),\n )\n}\n","import {useMemo} from 'react'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useDocumentPreviewStore} from '../../store/datastores'\nimport {useResourceCache} from '../../store/ResourceCacheProvider'\nimport {useWorkspace} from '../../studio/workspace'\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../util/releasesClient'\nimport {createReleaseStore} from './createReleaseStore'\nimport {type ReleaseStore} from './types'\n\n/** @internal */\nexport function useReleasesStore(): ReleaseStore {\n const resourceCache = useResourceCache()\n const workspace = useWorkspace()\n const previewStore = useDocumentPreviewStore()\n const studioClient = useClient(RELEASES_STUDIO_CLIENT_OPTIONS)\n\n return useMemo(() => {\n const releaseStore =\n resourceCache.get<ReleaseStore>({\n dependencies: [workspace, previewStore],\n namespace: 'ReleasesStore',\n }) ||\n createReleaseStore({\n client: studioClient,\n previewStore,\n })\n\n resourceCache.set({\n dependencies: [workspace, previewStore],\n namespace: 'ReleasesStore',\n value: releaseStore,\n })\n\n return releaseStore\n }, [resourceCache, workspace, studioClient, previewStore])\n}\n","import {type ReleaseDocument} from '@sanity/client'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {sortReleases} from '../hooks/utils'\nimport {ARCHIVED_RELEASE_STATES} from '../util/const'\nimport {type ReleasesReducerAction} from './reducer'\nimport {useReleasesStore} from './useReleasesStore'\n\ninterface ReleasesState {\n /**\n * Sorted array of releases, excluding archived releases\n */\n data: ReleaseDocument[]\n error?: Error\n loading: boolean\n dispatch: (event: ReleasesReducerAction) => void\n}\n\n/**\n * Hook to get the (non archived, non published) active releases\n * @internal\n */\nexport function useActiveReleases(): ReleasesState {\n const {state$, dispatch} = useReleasesStore()\n // Kept synchronous: PerspectiveProvider derives `selectedReleaseId` from\n // this list while `selectedPerspectiveName` stays live, so a deferred\n // snapshot could tear the release identity (e.g. reference create-in-place\n // writing `_weak` or opening the wrong version). Executable proof:\n // perspective/__tests__/deferralSafety.test.tsx.\n const state = useSyncObservable(state$)!\n const releasesAsArray = useMemo(\n () =>\n sortReleases(\n Array.from(state.releases.values()).filter(\n (release) => !ARCHIVED_RELEASE_STATES.includes(release.state),\n ),\n ).reverse(),\n [state.releases],\n )\n\n return useMemo(\n () => ({\n data: releasesAsArray,\n dispatch,\n error: state.error,\n loading: ['loading', 'initialising'].includes(state.state),\n }),\n [releasesAsArray, state.error, state.state, dispatch],\n )\n}\n","import {type PreviewLayoutKey} from './types'\n\nexport const PREVIEW_SIZES: Record<\n PreviewLayoutKey,\n {\n icon: number\n media: {height: number; width: number}\n }\n> = {\n block: {\n icon: 25,\n media: {width: 33, height: 33},\n },\n blockImage: {\n icon: 25,\n media: {width: 600, height: 400},\n },\n compact: {\n icon: 21,\n media: {width: 25, height: 25},\n },\n default: {\n icon: 21,\n media: {width: 33, height: 33},\n },\n detail: {\n icon: 25,\n media: {width: 73, height: 73},\n },\n inline: {\n icon: 15,\n media: {width: 15, height: 15},\n },\n media: {\n icon: 25,\n media: {width: 160, height: 160},\n },\n}\n","import {rem} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nimport {PREVIEW_SIZES} from '../constants'\nimport {type PreviewLayoutKey, type PreviewMediaDimensions} from '../types'\n\nexport const MediaWrapper = styled.span<{\n $dimensions: PreviewMediaDimensions\n $layout: PreviewLayoutKey\n $radius: number\n $responsive: boolean\n}>((props) => {\n const {$dimensions, $layout, $radius, $responsive} = props\n const width = $dimensions.width || 0\n const height = $dimensions.width || 0\n const iconSize = PREVIEW_SIZES[$layout].icon\n\n return css`\n position: relative;\n width: ${$responsive ? '100%' : rem(width)};\n height: ${$responsive ? '100%' : rem(height)};\n min-width: ${$responsive ? undefined : rem(width)};\n border-radius: ${({theme}) => rem(theme.sanity.radius[$radius]) /* oxlint-disable-line no-deprecated -- will fix in follow up PR */};\n display: flex;\n overflow: hidden;\n overflow: clip;\n align-items: center;\n justify-content: center;\n\n & img {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n object-fit: contain;\n border-radius: inherit;\n }\n\n & svg {\n // Shared styles for SVG icons\n color: var(--card-icon-color);\n display: block;\n flex: 1;\n\n // Specific styles for non Sanity icons\n &:not([data-sanity-icon]) {\n height: 1em;\n width: 1em;\n max-width: 1em;\n max-height: 1em;\n }\n\n // Specific styles for Sanity icons\n &[data-sanity-icon] {\n display: block;\n font-size: calc(${iconSize} / 16 * 1em);\n }\n }\n\n & > span[data-border] {\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n box-shadow: inset 0 0 0 1px var(--card-fg-color);\n opacity: 0.1;\n border-radius: inherit;\n pointer-events: none;\n }\n `\n})\n\nMediaWrapper.displayName = 'Styled(MediaWrapper)'\n","import {Text} from '@sanity/ui'\nimport {type ComponentType, isValidElement, type ReactNode} from 'react'\nimport {isValidElementType} from 'react-is'\n\nimport {type PreviewLayoutKey, type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {MediaWrapper} from './Media.styled'\n\nexport interface MediaProps {\n border?: boolean\n dimensions: PreviewMediaDimensions\n layout: PreviewLayoutKey\n media: PreviewProps['media']\n radius?: number\n responsive?: boolean\n styles?: {\n media?: string\n mediaString?: string\n }\n}\n\nexport function Media(props: MediaProps) {\n const {border = true, dimensions, layout, media, radius = 1, responsive = false, styles} = props\n\n return (\n <MediaWrapper\n $dimensions={dimensions}\n $layout={layout}\n $radius={radius}\n $responsive={responsive}\n className={styles?.media}\n data-testid=\"Media\"\n >\n {renderMedia({dimensions, layout, media})}\n {border && <span data-border />}\n </MediaWrapper>\n )\n}\n\nfunction renderMedia(props: {\n dimensions: PreviewMediaDimensions\n layout: PreviewLayoutKey\n media: PreviewProps['media']\n styles?: {\n media?: string\n mediaString?: string\n }\n}): ReactNode {\n const {dimensions, layout, media, styles} = props\n\n if (typeof media === 'string') {\n return (\n <Text as=\"span\" className={styles?.mediaString} size={1}>\n {media}\n </Text>\n )\n }\n\n if (isValidElementType(media)) {\n const MediaComponent = media as ComponentType<{\n dimensions: PreviewMediaDimensions\n layout: PreviewLayoutKey\n }>\n return <MediaComponent dimensions={dimensions} layout={layout} />\n }\n\n if (isValidElement(media)) {\n return media\n }\n\n return null\n}\n","import {tryGetImageDimensions} from '@sanity/asset-utils'\nimport {type ElementType, isValidElement, type ReactNode} from 'react'\nimport {isValidElementType} from 'react-is'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {PREVIEW_SIZES} from './constants'\nimport {type PreviewProps, type PreviewLayoutKey, type PreviewMediaDimensions} from './types'\n\nexport function renderPreviewMedia<Layout = PreviewLayoutKey>(\n value: PreviewProps<Layout>['media'],\n layout: Layout,\n dimensions: PreviewMediaDimensions,\n): ReactNode {\n if (isValidElementType(value)) {\n const Value = value\n return <Value layout={layout} dimensions={dimensions} />\n }\n\n if (typeof value === 'string') {\n return <div>{value}</div>\n }\n\n const isReactNode =\n isValidElement(value) ||\n value === null ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n\n if (isReactNode) {\n return value\n }\n\n return null\n}\n\nexport function renderPreviewNode<Layout = PreviewLayoutKey>(\n value: ReactNode | ElementType<{layout: Layout}>,\n layout: Layout,\n fallbackNode?: ReactNode,\n): ReactNode {\n if (typeof value === 'string') {\n return value\n }\n\n if (isValidElementType(value)) {\n const Value = value\n return <Value layout={layout} />\n }\n\n // @todo: find out why `value` isn't infered as `ReactNode` here\n return (value as any) || fallbackNode\n}\n\nexport function resolveBlockImageDimensions(\n source: Parameters<typeof tryGetImageDimensions>[0],\n): PreviewMediaDimensions | undefined {\n const sourceDimensions = tryGetImageDimensions(source)\n\n if (typeof sourceDimensions === 'undefined') {\n return undefined\n }\n\n const max = PREVIEW_SIZES.blockImage.media\n const scale = Math.min(max.width / sourceDimensions.width, 1)\n\n return {\n width: Math.round(sourceDimensions.width * scale),\n height: Math.round(sourceDimensions.height * scale),\n fit: 'max',\n dpr: getDevicePixelRatio(),\n }\n}\n","import {Box, Flex, rem, Skeleton, Stack, Text, TextSkeleton} from '@sanity/ui'\nimport {styled} from 'styled-components'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {useTranslation} from '../../../i18n/hooks/useTranslation'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\n\n/**\n * @hidden\n * @beta */\nexport type CompactPreviewProps = Omit<PreviewProps<'compact'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.compact.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\nconst Root = styled(Flex)`\n height: ${rem(PREVIEW_SIZES.compact.media.height)};\n box-sizing: content-box;\n`\n\nconst TitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(160)};\n width: 80%;\n`\n\n/**\n * @hidden\n * @beta */\nexport function CompactPreview(props: CompactPreviewProps) {\n const {children, isPlaceholder, media, status, title} = props\n\n const {t} = useTranslation()\n\n const statusNode = status && (\n <Box data-testid=\"compact-preview__status\" paddingLeft={4} paddingRight={1}>\n {renderPreviewNode(status, 'compact')}\n </Box>\n )\n\n if (isPlaceholder) {\n return (\n <Root\n align=\"center\"\n data-testid=\"default-preview\"\n paddingLeft={media ? 1 : 2}\n paddingRight={2}\n paddingY={1}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && <Skeleton animated radius={2} style={PREVIEW_SIZES.compact.media} />}\n\n <Stack data-testid=\"compact-preview__heading\" flex={1} gap={2}>\n <TitleSkeleton />\n </Stack>\n\n {statusNode}\n </Flex>\n </Root>\n )\n }\n\n return (\n <Root\n align=\"center\"\n data-testid=\"compact-preview\"\n paddingLeft={media ? 1 : 2}\n paddingRight={2}\n paddingY={1}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && (\n <Media\n border={false}\n dimensions={DEFAULT_MEDIA_DIMENSIONS}\n layout=\"compact\"\n media={media as any}\n />\n )}\n <Stack data-testid=\"compact-preview__header\" flex={1} gap={2}>\n <Text size={1} style={{color: 'inherit'}} textOverflow=\"ellipsis\" weight=\"medium\">\n {title && renderPreviewNode(title, 'compact')}\n {!title && (\n <span style={{color: 'var(--card-muted-fg-color)'}}>\n {t('preview.default.title-fallback')}\n </span>\n )}\n </Text>\n </Stack>\n\n {statusNode}\n </Flex>\n\n {children && <Box marginLeft={1}>{children}</Box>}\n </Root>\n )\n}\n","import {hues} from '@sanity/color'\nimport {Card, type Theme} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nconst STROKE_WIDTH = 0.5\n\nconst Root = styled(Card)`\n overflow: hidden;\n overflow: clip;\n`\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nconst Bar = styled(Card)(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {color} = theme.sanity\n\n return css`\n height: ${STROKE_WIDTH}rem;\n background: ${hues.blue[color.dark ? 400 : 500].hex};\n transition: transform 75ms;\n `\n})\n\n/**\n * @hidden\n * @beta */\nexport function LinearProgress(props: {\n /** Percentage */\n value: number\n}) {\n const {value} = props\n\n return (\n <Root radius={5}>\n <Bar radius={5} style={{transform: `translate3d(${value - 100}%, 0, 0)`}} />\n </Root>\n )\n}\n","import {Box, Flex, rem, Skeleton, Stack, Text, TextSkeleton} from '@sanity/ui'\nimport {clsx} from 'clsx'\nimport {styled} from 'styled-components'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {useTranslation} from '../../../i18n/hooks/useTranslation'\nimport {LinearProgress} from '../../progress/LinearProgress'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\n\n/**\n * @hidden\n * @beta */\nexport interface DefaultPreviewProps extends Omit<PreviewProps<'default'>, 'renderDefault'> {\n styles?: {\n root?: string\n placeholder?: string\n media?: string\n heading?: string\n title?: string\n subtitle?: string\n hasSubtitle?: string\n mediaString?: string\n status?: string\n children?: string\n }\n}\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.default.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\nconst Root = styled(Flex)`\n height: ${rem(PREVIEW_SIZES.default.media.height)};\n box-sizing: content-box;\n`\n\nconst TitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(160)};\n width: 80%;\n`\n\nconst SubtitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(120)};\n width: 60%;\n`\nconst SKELETON_DELAY = 300\n/**\n * @hidden\n * @beta */\nexport function DefaultPreview(props: DefaultPreviewProps) {\n const {title, subtitle, media, status, isPlaceholder, children, styles, progress} = props\n const {t} = useTranslation()\n const rootClassName = clsx(styles?.root, Boolean(subtitle) && styles?.hasSubtitle)\n const isUploading = typeof progress === 'number' && progress > -1\n\n const statusNode = status && (\n <Box className={styles?.status} data-testid=\"default-preview__status\">\n {renderPreviewNode(status, 'default')}\n </Box>\n )\n\n if (isPlaceholder) {\n return (\n <Root\n align=\"center\"\n className={styles?.placeholder}\n data-testid=\"default-preview\"\n padding={2}\n paddingLeft={media ? 2 : 3}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && (\n <Box flex=\"none\">\n <Skeleton\n animated\n delay={SKELETON_DELAY}\n radius={1}\n style={PREVIEW_SIZES.default.media}\n />\n </Box>\n )}\n\n <Stack data-testid=\"default-preview__heading\" flex={1} gap={2}>\n <TitleSkeleton delay={SKELETON_DELAY} />\n <SubtitleSkeleton delay={SKELETON_DELAY} />\n </Stack>\n\n <Box flex=\"none\" padding={1}>\n {statusNode}\n </Box>\n </Flex>\n </Root>\n )\n }\n\n return (\n <Root\n align=\"center\"\n className={rootClassName}\n data-testid=\"default-preview\"\n padding={2}\n paddingLeft={media ? 2 : 3}\n >\n <Flex align=\"center\" flex={1} gap={2}>\n {media && (\n <Box flex=\"none\">\n <Media\n dimensions={DEFAULT_MEDIA_DIMENSIONS}\n layout=\"default\"\n media={media as any}\n styles={styles}\n />\n </Box>\n )}\n\n <Stack className={styles?.heading} data-testid=\"default-preview__header\" flex={1} gap={2}>\n {isUploading && <LinearProgress value={progress} />}\n {!isUploading && (\n <>\n <Text\n className={styles?.title}\n size={1}\n style={{color: 'inherit'}}\n textOverflow=\"ellipsis\"\n weight=\"medium\"\n >\n {title && renderPreviewNode(title, 'default')}\n {!title && (\n <span style={{color: 'var(--card-muted-fg-color)'}}>\n {t('preview.default.title-fallback')}\n </span>\n )}\n </Text>\n\n {subtitle && (\n <Text muted size={1} textOverflow=\"ellipsis\" className={styles?.subtitle}>\n {renderPreviewNode(subtitle, 'default')}\n </Text>\n )}\n </>\n )}\n </Stack>\n\n <Box flex=\"none\" padding={1}>\n {statusNode}\n </Box>\n\n {children && <div className={styles?.children}>{children}</div>}\n </Flex>\n </Root>\n )\n}\n","import {Box, Flex, rem, Skeleton, Text, TextSkeleton} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nimport {PREVIEW_SIZES} from '../constants'\n\nexport const RootFlex = styled(Flex).attrs({align: 'center'})`\n height: ${rem(PREVIEW_SIZES.detail.media.height)};\n`\n\nexport const StatusBox = styled(Box)`\n white-space: nowrap;\n`\n\nexport const MediaSkeleton = styled(Skeleton).attrs({animated: true, radius: 2})`\n width: ${rem(PREVIEW_SIZES.detail.media.width)};\n height: ${rem(PREVIEW_SIZES.detail.media.height)};\n`\n\nexport const TitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(160)}; /* 80% of 200px */\n width: 80%;\n`\n\nexport const SubtitleSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(120)}; /* 60% of 200px */\n width: 60%;\n`\n\nexport const DescriptionSkeleton = styled(TextSkeleton).attrs({animated: true, radius: 1, size: 1})`\n max-width: ${rem(180)}; /* 90% of 200px */\n width: 90%;\n`\n\nexport const DescriptionText = styled(Text)(({theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {fonts} = theme.sanity\n const textSize1 = fonts.text.sizes[1]\n const maxLines = 2\n const maxHeight = textSize1.lineHeight * maxLines\n\n return css`\n & > span {\n max-height: ${rem(maxHeight)};\n\n /* Multi-line text overflow */\n display: -webkit-box;\n overflow: hidden;\n overflow: clip;\n text-overflow: ellipsis;\n -webkit-line-clamp: ${maxLines};\n -webkit-box-orient: vertical;\n }\n `\n})\n","import {Box, Flex, Stack, Text} from '@sanity/ui'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {useTranslation} from '../../../i18n/hooks/useTranslation'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {\n DescriptionSkeleton,\n DescriptionText,\n MediaSkeleton,\n RootFlex,\n StatusBox,\n SubtitleSkeleton,\n TitleSkeleton,\n} from './DetailPreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type DetailPreviewProps = PreviewProps<'detail'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.detail.media,\n fit: 'crop',\n aspect: 1,\n dpr: getDevicePixelRatio(),\n}\n\n/**\n * @hidden\n * @beta */\nexport function DetailPreview(props: DetailPreviewProps) {\n const {\n title,\n subtitle,\n description,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n media,\n status,\n children,\n isPlaceholder,\n } = props\n const {t} = useTranslation()\n\n const statusNode = status && (\n <StatusBox marginLeft={3} paddingRight={1}>\n {renderPreviewNode(status, 'detail')}\n </StatusBox>\n )\n\n if (isPlaceholder) {\n return (\n <RootFlex\n data-testid=\"detail-preview\"\n paddingLeft={media ? 2 : 3}\n paddingRight={2}\n paddingY={2}\n >\n <Flex align=\"center\" flex={1} gap={3}>\n {media && <MediaSkeleton data-testid=\"detail-preview__media\" />}\n\n <Flex align=\"center\" data-testid=\"detail-preview__header\" flex={1}>\n <Stack flex={1} gap={2}>\n <TitleSkeleton />\n <SubtitleSkeleton />\n {description && (\n <Box marginTop={1}>\n <DescriptionSkeleton />\n </Box>\n )}\n </Stack>\n </Flex>\n\n {statusNode}\n </Flex>\n </RootFlex>\n )\n }\n\n return (\n <RootFlex\n data-testid=\"detail-preview\"\n paddingLeft={media ? 2 : 3}\n paddingRight={2}\n paddingY={2}\n >\n <Flex align=\"center\" flex={1} gap={3}>\n {media && <Media dimensions={mediaDimensions} layout=\"detail\" media={media as any} />}\n\n <Flex align=\"center\" data-testid=\"detail-preview__header\" flex={1}>\n <Stack flex={1} gap={2}>\n <Text textOverflow=\"ellipsis\" size={1} style={{color: 'inherit'}} weight=\"medium\">\n {title && renderPreviewNode(title, 'detail')}\n {!title && <>{t('preview.default.title-fallback')}</>}\n </Text>\n\n {subtitle && (\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(subtitle, 'detail')}\n </Text>\n )}\n\n {description && (\n <Box marginTop={1}>\n <DescriptionText muted size={1}>\n {renderPreviewNode(description, 'detail')}\n </DescriptionText>\n </Box>\n )}\n </Stack>\n\n {statusNode}\n </Flex>\n\n {children}\n </Flex>\n </RootFlex>\n )\n}\n","import {hues} from '@sanity/color'\nimport {type Theme} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nconst SIZE = 43\nconst STROKE_WIDTH = 3\n\nconst Root = styled.svg`\n width: ${SIZE}px;\n height: ${SIZE}px;\n transform: rotate(-90deg);\n`\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nconst BgCircle = styled.circle(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {color} = theme.sanity\n\n return css`\n fill: none;\n stroke: ${hues.gray[color.dark ? 900 : 100].hex};\n stroke-width: ${STROKE_WIDTH}px;\n `\n})\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nconst ProgressCircle = styled.circle(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {color} = theme.sanity\n\n return css`\n fill: none;\n stroke: ${hues.blue[color.dark ? 400 : 500].hex};\n stroke-width: ${STROKE_WIDTH}px;\n transition: stroke-dashoffset 75ms;\n `\n})\n\n/**\n * @hidden\n * @beta */\nexport function CircularProgress(props: {\n /** Percentage */\n value: number\n}) {\n const {value: valueProp} = props\n const value = Math.min(Math.max(valueProp, 0), 100)\n const radius = SIZE / 2 - STROKE_WIDTH / 2\n const circ = 2 * Math.PI * radius\n const offset = ((100 - value) / 100) * circ\n const viewBox = `${SIZE / 2} ${SIZE / 2} ${SIZE} ${SIZE}`\n\n return (\n <Root viewBox={viewBox}>\n <BgCircle cx={SIZE} cy={SIZE} r={radius} />\n <ProgressCircle\n cx={SIZE}\n cy={SIZE}\n r={radius}\n style={{\n strokeDasharray: circ,\n strokeDashoffset: `${offset}px`,\n }}\n />\n </Root>\n )\n}\n","import {Box, Flex, rem, Skeleton, Stack} from '@sanity/ui'\nimport {styled} from 'styled-components'\n\nexport const RootBox = styled(Box)`\n position: relative;\n`\n\nexport const MediaFlex = styled(Flex).attrs({align: 'center', justify: 'center'})`\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n`\n\nexport const MediaSkeleton = styled(Skeleton).attrs({animated: true, radius: 2})`\n width: 100%;\n height: 100%;\n`\n\nexport const ProgressFlex = styled(Flex).attrs({align: 'center', justify: 'center'})`\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n\n &:before {\n background-color: var(--card-bg-color);\n opacity: 0.75;\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n }\n\n > svg {\n position: relative;\n z-index: 2;\n }\n`\n\nexport const TooltipContentStack = styled(Stack).attrs({gap: 2})`\n max-width: ${rem(200)};\n`\n","import {Box, Text} from '@sanity/ui'\nimport {useMemo} from 'react'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {Tooltip} from '../../../../ui-components/tooltip/Tooltip'\nimport {CircularProgress} from '../../progress/CircularProgress'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {\n MediaFlex,\n MediaSkeleton,\n ProgressFlex,\n RootBox,\n TooltipContentStack,\n} from './MediaPreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type MediaPreviewProps = Omit<PreviewProps<'media'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.media.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\n/**\n * @hidden\n * @beta */\nexport function MediaPreview(props: MediaPreviewProps) {\n const {\n media,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n children,\n isPlaceholder,\n progress = -1,\n subtitle,\n title,\n withBorder = true,\n withRadius = true,\n } = props\n\n const aspect = mediaDimensions.aspect || 1\n\n const STYLES_PADDER = useMemo(() => ({paddingBottom: `${100 / aspect}%`}), [aspect])\n\n const tooltipContent = useMemo(() => {\n if (!title || !subtitle) {\n return null\n }\n\n return (\n <TooltipContentStack>\n {title && (\n <Text align=\"center\" size={1} weight=\"medium\">\n {renderPreviewNode(title, 'media')}\n </Text>\n )}\n\n {subtitle && (\n <Text align=\"center\" muted size={1}>\n {renderPreviewNode(subtitle, 'media')}\n </Text>\n )}\n </TooltipContentStack>\n )\n }, [subtitle, title])\n\n return (\n <Box padding={2}>\n <RootBox data-testid=\"media-preview\" flex={1} overflow=\"hidden\">\n <div style={STYLES_PADDER} />\n\n <Tooltip content={tooltipContent} disabled={!tooltipContent} placement=\"top\" portal>\n <MediaFlex>\n {isPlaceholder ? (\n <MediaSkeleton />\n ) : (\n <Media\n border={withBorder}\n dimensions={mediaDimensions}\n layout=\"media\"\n media={media as any}\n radius={withRadius ? 1 : 0}\n responsive\n />\n )}\n\n {typeof progress === 'number' && progress > -1 && (\n <ProgressFlex>\n <CircularProgress value={progress} />\n </ProgressFlex>\n )}\n </MediaFlex>\n </Tooltip>\n\n {children}\n </RootBox>\n </Box>\n )\n}\n","import {Box, Card, Flex, rem} from '@sanity/ui'\nimport {styled} from 'styled-components'\n\nimport {PREVIEW_SIZES} from '../constants'\n\nexport const HeaderFlex = styled(Flex).attrs({align: 'center'})`\n height: ${rem(PREVIEW_SIZES.block.media.height)};\n white-space: nowrap;\n position: relative;\n z-index: 1;\n`\n\nexport const MediaCard = styled(Card)<{$ratio: number}>`\n overflow: hidden;\n position: relative;\n padding-bottom: ${({$ratio}) => $ratio}%;\n\n & > span {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n }\n`\n\nexport const RootBox = styled(Box).attrs({overflow: 'hidden'})`\n border-radius: ${({theme}) => theme.sanity.radius[1] /* oxlint-disable-line no-deprecated -- will fix in follow up PR */}px;\n`\n","import {Box, Flex, Stack, Text} from '@sanity/ui'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {HeaderFlex, MediaCard, RootBox} from './BlockImagePreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type BlockImagePreviewProps = Omit<PreviewProps<'blockImage'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.blockImage.media,\n fit: 'fillmax',\n dpr: getDevicePixelRatio(),\n}\n\nconst getRatio = (dimensions: PreviewMediaDimensions) => {\n const {height, width} = dimensions\n\n if (!height || !width) {\n return 1\n }\n\n return (height / width) * 100\n}\n\n/**\n * @hidden\n * @beta */\nexport function BlockImagePreview(props: BlockImagePreviewProps) {\n const {\n actions,\n title,\n subtitle,\n description,\n fallbackTitle = 'Untitled',\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n media,\n children,\n status,\n } = props\n\n return (\n <RootBox>\n <Stack>\n <HeaderFlex paddingBottom={3} paddingLeft={2} paddingRight={1} paddingTop={1}>\n <Stack flex={1} gap={2}>\n {(title || fallbackTitle) && (\n <Text size={1} textOverflow=\"ellipsis\" weight=\"medium\">\n {title ? renderPreviewNode(title as any, 'block') : fallbackTitle}\n </Text>\n )}\n\n {subtitle && (\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(subtitle as any, 'block')}\n </Text>\n )}\n </Stack>\n\n <Flex gap={1} paddingLeft={1}>\n {status && (\n <Box paddingX={2} paddingY={3}>\n {renderPreviewNode(status as any, 'block')}\n </Box>\n )}\n\n {actions as any}\n </Flex>\n </HeaderFlex>\n\n <MediaCard\n $ratio={getRatio(mediaDimensions)}\n __unstable_checkered\n display=\"flex\"\n sizing=\"border\"\n radius={2}\n tone=\"inherit\"\n >\n <Media\n border={false}\n dimensions={mediaDimensions}\n layout=\"blockImage\"\n media={media as any}\n radius={0}\n responsive\n />\n </MediaCard>\n </Stack>\n\n {description && (\n <Box paddingX={2} paddingY={3}>\n <Text muted size={1}>\n {renderPreviewNode(description as any, 'block')}\n </Text>\n </Box>\n )}\n\n {children && <div>{children}</div>}\n </RootBox>\n )\n}\n","import {Box, Flex, rem, Stack, Text} from '@sanity/ui'\nimport {styled} from 'styled-components'\nimport {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {LinearProgress} from '../../progress/LinearProgress'\nimport {Media} from '../_common/Media'\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.block.media,\n aspect: 1,\n fit: 'crop',\n dpr: getDevicePixelRatio(),\n}\n\nconst HeaderFlex = styled(Flex).attrs({align: 'center'})`\n min-height: ${rem(PREVIEW_SIZES.block.media.height)};\n`\n\n/**\n * @hidden\n * @beta */\nexport function BlockPreview(props: Omit<PreviewProps<'block'>, 'renderDefault'>) {\n const {\n actions,\n title,\n subtitle,\n description,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n media,\n progress,\n status,\n children,\n } = props\n\n const isUploading = typeof progress === 'number' && progress > -1\n\n return (\n <Stack data-testid=\"block-preview\" gap={1}>\n <HeaderFlex data-testid=\"block-preview__header\">\n {media && <Media dimensions={mediaDimensions} layout=\"block\" media={media as any} />}\n\n <Box flex={1} paddingLeft={media ? 2 : 1}>\n <Text size={1} textOverflow=\"ellipsis\" weight=\"medium\">\n {title ? renderPreviewNode(title, 'block') : 'Untitled'}\n </Text>\n\n {subtitle && (\n <Box marginTop={2}>\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(subtitle, 'block')}\n </Text>\n </Box>\n )}\n\n {description && (\n <Box marginTop={3}>\n <Text muted size={1} textOverflow=\"ellipsis\">\n {renderPreviewNode(description, 'block')}\n </Text>\n </Box>\n )}\n\n {isUploading && (\n <Box marginTop={3}>\n <LinearProgress value={progress} />\n </Box>\n )}\n </Box>\n\n <Flex gap={1} paddingLeft={1}>\n {status && (\n <Box paddingX={2} paddingY={3}>\n {renderPreviewNode(status, 'block')}\n </Box>\n )}\n\n {actions as any}\n </Flex>\n </HeaderFlex>\n\n {children && <div data-testid=\"block-preview__children\">{children}</div>}\n </Stack>\n )\n}\n","import {rem, Text, type Theme} from '@sanity/ui'\nimport {css, styled} from 'styled-components'\n\nexport const RootSpan = styled.span`\n display: inline-flex;\n align-items: center;\n vertical-align: top;\n height: calc(1em - 1px);\n max-width: 100%;\n`\n\nexport const MediaSpan = styled.span`\n position: relative;\n display: inline-block;\n width: calc(1em - 1px);\n height: calc(1em - 1px);\n min-width: calc(1em - 1px);\n\n & img {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n object-fit: cover;\n border-radius: ${({theme}) => rem(theme.sanity.radius[1]) /* oxlint-disable-line no-deprecated -- will fix in follow up PR */};\n }\n\n & img + span {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n box-shadow: inset 0 0 0 1px var(--card-fg-color);\n opacity: 0.2;\n border-radius: ${({theme}) => rem(theme.sanity.radius[1]) /* oxlint-disable-line no-deprecated -- will fix in follow up PR */};\n }\n\n & svg {\n display: block;\n font-size: calc(14 / 16 * 1em);\n margin: 1px 0;\n\n &[data-sanity-icon] {\n font-size: calc(18 / 16 * 1em);\n margin: calc(1px + (2 / 18 * -1em)) 0;\n }\n }\n`\n\n// oxlint-disable-next-line no-deprecated -- will fix in follow up PR\nexport const TextSpan = styled(Text).attrs({forwardedAs: 'span'})(({theme}: {theme: Theme}) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const textFont = theme.sanity.fonts.text\n const textSize = textFont.sizes[1]\n\n return css`\n font-size: calc(${textSize.fontSize} / 16 * 1em);\n font-weight: ${textFont.weights.medium};\n box-sizing: border-box;\n display: inline-block;\n vertical-align: top;\n line-height: ${textSize.lineHeight / textSize.fontSize};\n padding-left: 0.5em;\n padding-right: calc(0.5em - 2px);\n min-width: 0;\n\n & > span {\n display: block;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n overflow: clip;\n }\n `\n})\n","import {getDevicePixelRatio} from 'use-device-pixel-ratio'\n\nimport {PREVIEW_SIZES} from '../constants'\nimport {renderPreviewMedia, renderPreviewNode} from '../helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../types'\nimport {MediaSpan, RootSpan, TextSpan} from './InlinePreview.styled'\n\n/**\n * @hidden\n * @beta */\nexport type InlinePreviewProps = Omit<PreviewProps<'inline'>, 'renderDefault'>\n\nconst DEFAULT_MEDIA_DIMENSIONS: PreviewMediaDimensions = {\n ...PREVIEW_SIZES.inline.media,\n fit: 'crop',\n aspect: 1,\n dpr: getDevicePixelRatio(),\n}\n\n/**\n * @hidden\n * @beta */\nexport function InlinePreview(props: InlinePreviewProps) {\n const {\n title,\n fallbackTitle = 'Untitled',\n media,\n mediaDimensions = DEFAULT_MEDIA_DIMENSIONS,\n } = props\n\n return (\n <RootSpan data-testid=\"inline-preview\">\n {media && (\n <MediaSpan data-testid=\"inline-preview-media\">\n {renderPreviewMedia(media, 'inline', mediaDimensions)}\n <span />\n </MediaSpan>\n )}\n\n <TextSpan data-testid=\"inline-preview-title\" size={1}>\n {renderPreviewNode(title, 'inline', fallbackTitle)}\n </TextSpan>\n </RootSpan>\n )\n}\n","import isString from 'lodash-es/isString.js'\n\nimport {type Plugin, type PluginOptions} from './types'\n\n/**\n * @hidden\n * @beta */\nexport type PluginFactory<TOptions> = (options: TOptions) => PluginOptions\n\nfunction validatePlugin(pluginResult: PluginOptions) {\n // TODO: name is required etc\n const messages = [\n 'projectId' in pluginResult && '`projectId` not allowed in plugin configuration',\n 'dataset' in pluginResult && '`dataset` not allowed in plugin configuration',\n ].filter(isString)\n\n if (messages.length)\n throw new Error(\n `Invalid plugin configuration:\\n${messages.map((message) => `\\t${message}`).join('\\n')}`,\n )\n}\n\n/**\n * @hidden\n * @beta */\nexport function definePlugin<TOptions = void>(\n arg: PluginFactory<TOptions> | PluginOptions,\n): Plugin<TOptions> {\n if (typeof arg === 'function') {\n const pluginFactory = arg\n\n return (options: TOptions) => {\n // TODO: there's a possiblity of passing default arguments to users'\n // plugin factories or reading from default options in `TOptions`\n const result = pluginFactory(options)\n\n validatePlugin(result)\n return result\n }\n }\n\n validatePlugin(arg)\n return () => arg\n}\n\n/**\n * @deprecated Use `definePlugin` instead\n *\n * @hidden\n * @beta\n */\nexport function createPlugin<TOptions = void>(\n arg: PluginFactory<TOptions> | PluginOptions,\n): Plugin<TOptions> {\n return definePlugin(arg)\n}\n","import {useToast} from '@sanity/ui/toast'\nimport {useEffect} from 'react'\n\nimport {definePlugin} from '../config/definePlugin'\nimport {type LayoutProps} from '../config/studio/types'\n\nfunction SchedulePublishingStudioLayout(props: LayoutProps) {\n const toast = useToast()\n useEffect(() => {\n console.error(\n `Scheduled publishing plugin is added by default, please remove this plugin from your config. \n \\nIf you have a custom date config, you can use the scheduledPublishing API to customize the date input.\n \\nSee: https://www.sanity.io/docs/scheduled-publishing.\n `,\n )\n toast.push({\n id: 'scheduled-publishing-deprecated',\n closable: true,\n duration: 60000,\n status: 'error',\n title: 'Scheduled publishing plugin is deprecated',\n description:\n 'The scheduled publishing plugin is now deprecated, you should remove the plugin from your configuration. If you have a custom date config, you can use the scheduledPublishing API to customize the date input. See: https://www.sanity.io/docs/scheduled-publishing.',\n })\n }, [toast])\n\n return props.renderDefault(props)\n}\n\n/**\n * Shows an error in console and a toast to prevent users from importing the deprecated plugin.\n * Gives information about how to upgrade to the new version.\n */\nexport const deprecatedScheduledPublishingPlugin = definePlugin({\n name: 'sanity/deprecated/scheduled-publishing',\n studio: {\n components: {\n layout: SchedulePublishingStudioLayout,\n },\n },\n})\n","import {deprecatedScheduledPublishingPlugin} from '../deprecatedPlugins/DeprecatedScheduledPublishing'\nimport {type PluginOptions} from './types'\n\nconst DEPRECATED_PLUGINS = [\n // Scheduled publishing is added by default, we are filtering to avoid duplicates\n 'scheduled-publishing',\n]\n\n/**\n * @internal\n *\n * This function flattens the config tree into a list of configs in the order they should be applied.\n */\nexport const flattenConfig = (\n {plugins = [], ...currentConfig}: PluginOptions,\n path: string[],\n): Array<{config: PluginOptions; path: string[]}> => {\n // The APIs used at the root config level\n const rootConfig = {config: currentConfig, path: [...path, currentConfig.name]}\n\n // An array with the APIs used in plugins\n const allPlugins = plugins.flatMap((plugin) =>\n flattenConfig(plugin, [...path, currentConfig.name]),\n )\n\n const deprecatedScheduledPublishing = allPlugins.find(\n (p) => p.config.name === 'scheduled-publishing',\n )\n if (deprecatedScheduledPublishing) {\n // Add the deprecated plugin error to the plugins list, to show the error to users.\n allPlugins.push({\n path: deprecatedScheduledPublishing.path,\n config: deprecatedScheduledPublishingPlugin(),\n })\n }\n\n const resolved = [\n ...allPlugins.filter((plugin) => !DEPRECATED_PLUGINS.includes(plugin.config.name)),\n rootConfig,\n ]\n\n return resolved\n}\n","import {Skeleton} from '@sanity/ui'\nimport {type ComponentType, Fragment, Suspense, useMemo} from 'react'\n\nimport {useSource} from '../../studio/source'\nimport {flattenConfig} from '../flattenConfig'\nimport {type PluginOptions} from '../types'\n\nconst emptyRender = () => <Fragment />\n\nfunction _createMiddlewareComponent<T extends {}>(\n DefaultComponent: ComponentType<T>,\n middlewareComponents: ComponentType<T>[],\n): ComponentType<T> {\n function MiddlewareComponent(outerProps: T) {\n // This is the inner \"layer\" of the middleware chain\n // Here we render the _default_ component (typically Sanity's component)\n let next = (props: T) => <DefaultComponent {...props} />\n\n for (const Middleware of middlewareComponents) {\n // As we progress through the chain, the meaning of \"renderDefault\" changes.\n // At a given layer in the chain, the _next_ layer is the \"default\".\n const renderDefault = next\n\n // Here we replace `next` so that the _previous_ layer may use this as its _next_.\n next = (props) => <Middleware {...props} renderDefault={renderDefault} />\n }\n\n return (\n <Suspense fallback={<Skeleton padding={3} radius={1} animated />}>\n {next({\n ...outerProps,\n // NOTE: it's safe to pass the empty render function, since it'll be overwritten in the next step (above).\n // NOTE: it's important that the default component does not use `renderDefault`, since it will\n // get the `emptyRender` callback will be passed when the middleware stack is empty.\n renderDefault: emptyRender,\n })}\n </Suspense>\n )\n }\n return MiddlewareComponent\n}\n\n/**\n * @internal\n * This hook returns a component based on the Components API middleware chain.\n *\n * - The `pick` function is used to select a component from the provided plugin options in the configuration.\n * - The `defaultComponent` is the default component that gets rendered with `renderDefault`.\n * The `renderDefault` function is added to the props of the middleware components so that they can render the default\n * component and continue the middleware chain.\n *\n * @example\n * Example usage of:\n *\n * ```ts\n * const StudioLayout = useMiddlewareComponents({\n * pick: (plugin) => plugin.studio?.components?.layout,\n * defaultComponent: StudioLayout,\n * })\n *\n * return <StudioLayout />\n *```\n */\nexport function useMiddlewareComponents<T extends {}>(props: {\n pick: (plugin: PluginOptions) => ComponentType<T>\n defaultComponent: ComponentType<T>\n}): ComponentType<T> {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {options} = useSource().__internal\n const {defaultComponent, pick} = props\n\n return useMemo(() => {\n // Flatten the config tree into a list of configs\n const flattened = [...flattenConfig(options, [])]\n\n // Since the middleware chain is executed backwards, we need to reverse the list of configs here.\n // This is important because we want the order of the Components API to be consistent with the order of the other APIs.\n flattened.reverse()\n\n // Pick the middleware components from the configs\n const pickedComponents = flattened.map(({config}) => pick(config))\n\n // Since we try to pick the components in all configs, some results may be undefined.\n // Therefore, we filter these values out before passing the result to the middleware creator.\n const result = pickedComponents.filter(Boolean)\n\n // Create the middleware component\n return _createMiddlewareComponent(defaultComponent, result)\n }, [defaultComponent, options, pick])\n}\n","/** @internal */\nexport function isString(value: unknown): value is string {\n return typeof value === 'string'\n}\n","import {type SanityClient} from '@sanity/client'\n\n/**\n * Creates a Media Library-specific client with an explicitly configured API\n * host that includes the project ID in the subdomain. This is to satisfy CORS\n * requirements, as browser requests will fail against the global host because\n * it does not include CORS headers. (Setting `resource` on a client makes it\n * ignore `useProjectHostname` and target the global API host.)\n *\n * @internal\n */\nexport function createMediaLibraryClient(client: SanityClient, libraryId: string): SanityClient {\n const {apiHost, projectId} = client.config()\n\n if (!projectId) {\n throw new Error('Cannot create Media Library client: missing projectId in client config')\n }\n\n const baseUrl = new URL(apiHost)\n baseUrl.hostname = `${projectId}.${baseUrl.hostname}`\n\n return client.withConfig({\n // `origin` (rather than `toString()`) avoids a trailing slash and drops\n // any pathname/search/hash that may have been configured on `apiHost`\n apiHost: baseUrl.origin,\n resource: {\n id: libraryId,\n type: 'media-library',\n },\n })\n}\n","import {type GlobalDocumentReferenceValue} from '@sanity/types'\n\n/**\n * @internal\n */\nexport type MediaLibraryRef = `media-library:${string}:${string}`\n\nfunction hasOwnRecord<K extends PropertyKey>(value: unknown, key: K): value is Record<K, unknown> {\n return (\n typeof value === 'object' && value !== null && Object.prototype.hasOwnProperty.call(value, key)\n )\n}\n\nexport function makeMediaLibraryRef(libraryId: string, assetId: string): MediaLibraryRef {\n return `media-library:${libraryId}:${assetId}`\n}\n\nfunction containsMediaProperty(value: unknown): value is {media: GlobalDocumentReferenceValue} {\n if (!hasOwnRecord(value, 'media') || !hasOwnRecord(value.media, '_ref')) {\n return false\n }\n return typeof value.media._ref === 'string'\n}\n\nfunction isMediaLibraryRef(ref: unknown): ref is MediaLibraryRef {\n if (typeof ref !== 'string') return false\n\n const [resourceType, resourceId, documentId] = ref.split(':', 3)\n\n return resourceType === 'media-library' && Boolean(resourceId) && Boolean(documentId)\n}\n\n/**\n * Attempts to extract a Media Library ref from a source or raw string value.\n *\n * @internal\n */\nexport function getMediaLibraryRef(value: unknown): MediaLibraryRef | undefined {\n const maybeRef = containsMediaProperty(value) ? value?.media?._ref : value\n\n return isMediaLibraryRef(maybeRef) ? maybeRef : undefined\n}\n","import {type SanityClient} from '@sanity/client'\nimport DataLoader from 'dataloader'\nimport QuickLRU from 'quick-lru'\n\nimport {createMediaLibraryClient} from '../../util/createMediaLibraryClient'\nimport {makeMediaLibraryRef, type MediaLibraryRef} from './refs'\n\ntype AccessPolicyResult = 'public' | 'private' | undefined\n\nconst POLICY_CACHE_MAX_SIZE = 2000\nconst POLICY_CACHE_MAX_AGE = 1000 * 60 * 5 // 5 minutes\n\nconst loaders = new Map<string, DataLoader<string, AccessPolicyResult>>()\nconst policyCache = new QuickLRU<string, AccessPolicyResult>({\n maxAge: POLICY_CACHE_MAX_AGE,\n maxSize: POLICY_CACHE_MAX_SIZE,\n})\n\n/**\n * Batch fetch asset access policies from the Media Library API and populate the\n * cache.\n */\nasync function fetchAccessPoliciesBatch(params: {\n assetIds: readonly string[]\n client: SanityClient\n libraryId: string\n}): Promise<AccessPolicyResult[]> {\n const {assetIds, client, libraryId} = params\n\n if (assetIds.length === 0) {\n return []\n }\n\n try {\n const results = await client.fetch<{_id: string; cdnAccessPolicy?: AccessPolicyResult}[]>(\n `*[_id in $ids]{_id, cdnAccessPolicy}`,\n {ids: assetIds},\n )\n\n const policyById = Object.fromEntries(results.map((doc) => [doc._id, doc.cdnAccessPolicy]))\n\n return assetIds.map((assetId) => {\n const policy = policyById[assetId]\n const assetRef = makeMediaLibraryRef(libraryId, assetId)\n policyCache.set(assetRef, policy)\n return policy\n })\n } catch (error) {\n console.error('Error fetching cdnAccessPolicy batch', {\n libraryId,\n assetIds,\n error,\n })\n\n assetIds.forEach((assetId) => {\n const assetRef = makeMediaLibraryRef(libraryId, assetId)\n policyCache.set(assetRef, undefined)\n })\n\n return assetIds.map(() => undefined)\n }\n}\n\n/**\n * Resolve (or create) the DataLoader responsible for fetching asset access\n * policies from a given Media Library.\n *\n * NOTE: The first client passed for a given library ID will be used to create the\n * DataLoader instance, subsequent clients for the same library ID will be ignored.\n */\nfunction resolveAssetPolicyLoader(\n client: SanityClient,\n libraryId: string,\n): DataLoader<string, AccessPolicyResult> {\n const existingLoader = loaders.get(libraryId)\n\n if (existingLoader) {\n return existingLoader\n }\n\n const mediaLibraryClient = createMediaLibraryClient(client, libraryId)\n\n const loader = new DataLoader<string, AccessPolicyResult>(\n (assetIds) =>\n fetchAccessPoliciesBatch({\n assetIds,\n client: mediaLibraryClient,\n libraryId,\n }),\n {cache: false}, // only batch per tick, rely on QuickLRU for caching\n )\n\n loaders.set(libraryId, loader)\n return loader\n}\n\n/**\n * Schedule an asset access policy fetch using the library-specific DataLoader.\n * Returns the cached policy value if it's already been resolved.\n *\n * @internal\n */\nexport function enqueueAssetAccessPolicyFetch(\n assetRef: MediaLibraryRef,\n client?: SanityClient,\n): Promise<AccessPolicyResult> {\n const [, libraryId, assetId] = assetRef.split(':', 3)\n\n if (!libraryId || !assetId || !client) {\n return Promise.resolve(undefined)\n }\n\n if (policyCache.has(assetRef)) {\n const policy = policyCache.get(assetRef) ?? undefined\n return Promise.resolve(policy)\n }\n\n const loader = resolveAssetPolicyLoader(client, libraryId)\n return loader.load(assetId)\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type SanityImageSource} from '@sanity/image-url'\nimport {type AssetSource} from '@sanity/types'\nimport useSWR from 'swr'\n\nimport {enqueueAssetAccessPolicyFetch} from '../../../../store/accessPolicy/fetch'\nimport {getMediaLibraryRef, type MediaLibraryRef} from '../../../../store/accessPolicy/refs'\nimport {type AssetAccessPolicy} from '../types'\n\n/**\n * Resolve the effective access policy for a given image source, including\n * Media Library specific checks when possible.\n *\n * @internal\n */\nexport function useAccessPolicy(params: {\n client: SanityClient\n source?: AssetSource | SanityImageSource\n}): AssetAccessPolicy {\n const {client, source} = params\n\n const ref = getMediaLibraryRef(source)\n\n // If the client doesn't have a token (i.e. cookie auth), set the requestKey\n // to null to bypass the cdnAccessPolicy check as it will always fail.\n const canCheck = Boolean(ref && client.config().token)\n const requestKey = canCheck ? ref : null\n\n // useSWR gives us synchronous access to the cached policy values so the UI\n // can render without a flash of loading state while\n // enqueueAssetAccessPolicyFetch (which always returns a promise) settles.\n const fetcher = async (key: MediaLibraryRef) => enqueueAssetAccessPolicyFetch(key, client)\n const options = {\n dedupingInterval: 0,\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n const {data: cdnAccessPolicy, isLoading} = useSWR(requestKey, fetcher, options)\n\n // Non-Media Library assets are always 'public'\n if (!ref) return 'public'\n // If we can't check for an access policy (no token)\n if (!canCheck) return 'unknown'\n // If we can check AND a check is in progress\n if (isLoading) return 'checking'\n // The actual fetched policy, default to 'unknown' if undefined\n return cdnAccessPolicy ?? 'unknown'\n}\n","// TODO: change this to what the official GDR release version is\nexport const DEFAULT_API_VERSION = 'vX'\n\n// Staging\nexport const DEPLOYED_FRONTEND_HOST_STAGING = 'https://media.sanity.work'\nexport const CDN_HOST_STAGING = 'https://sanity-cdn.work'\nexport const API_HOST_STAGING = 'https://api.sanity.work'\n\n// Production\nexport const DEPLOYED_FRONTEND_HOST_PRODUCTION = 'https://media.sanity.io'\nexport const CDN_HOST_PRODUCTION = 'https://sanity-cdn.com'\nexport const API_HOST_PRODUCTION = 'https://api.sanity.io'\n","import {useClient} from '../../../../hooks/useClient'\nimport {DEFAULT_API_VERSION} from '../constants'\n\nexport function useToken(): string | undefined {\n const client = useClient({apiVersion: DEFAULT_API_VERSION})\n const {token} = client.config()\n return token\n}\n","import {useEffect, useState} from 'react'\n\nimport {useToken} from '../../../studio/assetSourceMediaLibrary/hooks/useToken'\n\n/**\n * @internal\n */\nexport interface UseImageObjectUrlResult {\n error: Error | null\n isLoading: boolean\n objectUrl: string | undefined\n}\n\ninterface RequestCacheEntry {\n abortController: AbortController\n blob: Blob | null\n cleanupTimer?: ReturnType<typeof setTimeout>\n error: Error | null\n listeners: Set<() => void>\n objectUrl?: string\n status: 'pending' | 'success' | 'error'\n}\n\n// Delay before disposing cache entries to handle React Strict Mode re-mounts\nconst CACHE_DISPOSE_DELAY = 2000\n\n// Cache shared across all hook instances keyed by `${token}:${url}` to ensure\n// unique entries per authenticated request.\nconst requestCache = new Map<string, RequestCacheEntry>()\n\nconst IDLE_RESULT: UseImageObjectUrlResult = {\n error: null,\n isLoading: false,\n objectUrl: undefined,\n}\n\nconst LOADING_RESULT: UseImageObjectUrlResult = {\n error: null,\n isLoading: true,\n objectUrl: undefined,\n}\n\nfunction createCacheKey(url: string | undefined, token: string | undefined): string | undefined {\n if (!url || !token) return undefined\n return `${token}:${url}`\n}\n\nfunction notifyListeners(entry: RequestCacheEntry): void {\n entry.listeners.forEach((listener) => listener())\n}\n\nfunction deriveResultFromEntry(entry: RequestCacheEntry): UseImageObjectUrlResult {\n switch (entry.status) {\n case 'pending':\n // While loading, preserve any existing objectUrl for smoother transitions\n return entry.objectUrl\n ? {objectUrl: entry.objectUrl, isLoading: true, error: null}\n : LOADING_RESULT\n case 'success':\n return {objectUrl: entry.objectUrl, isLoading: false, error: null}\n case 'error':\n return {objectUrl: undefined, isLoading: false, error: entry.error}\n default:\n return IDLE_RESULT\n }\n}\n\nfunction createFetchCacheEntry(url: string, token: string): RequestCacheEntry {\n const abortController = new AbortController()\n\n const entry: RequestCacheEntry = {\n abortController,\n blob: null,\n cleanupTimer: undefined,\n error: null,\n listeners: new Set(),\n objectUrl: undefined,\n status: 'pending',\n }\n\n fetch(url, {\n cache: 'force-cache',\n headers: {Authorization: `Bearer ${token}`},\n signal: abortController.signal,\n })\n .then((res) => {\n if (res.ok) return res.blob()\n throw new Error(`Failed to fetch image (HTTP ${res.status})`)\n })\n .then((blob) => {\n entry.blob = blob\n entry.error = null\n entry.status = 'success'\n entry.objectUrl = URL.createObjectURL(blob)\n notifyListeners(entry)\n })\n .catch((error) => {\n entry.blob = null\n entry.error = error as Error\n entry.status = 'error'\n notifyListeners(entry)\n })\n\n return entry\n}\n\n/**\n * Fetches an authenticated image (using a token) and returns an object URL for\n * use as an `<img src>`\n *\n * Caches using a url/token pair so multiple components can share a single\n * fetch, and keeps cache entries alive briefly after the last consumer unmounts\n * to avoid duplicate fetches when in strict mode.\n *\n * Automatically revokes object URLs and disposes cache entries when no longer\n * referenced.\n *\n * @internal\n */\nexport function useImageObjectUrl(url: string | undefined): UseImageObjectUrlResult {\n const token = useToken()\n const cacheKey = createCacheKey(url, token)\n\n // Initialize state from cache if available to ensure we don't flash a loading\n // state if data is already available.\n const [state, setState] = useState<UseImageObjectUrlResult>(() => {\n if (!cacheKey) return IDLE_RESULT\n const entry = requestCache.get(cacheKey)\n return entry ? deriveResultFromEntry(entry) : LOADING_RESULT\n })\n\n useEffect(() => {\n // No cacheKey (i.e. no URL or token) means we can't fetch. Reset to idle state,\n // skipping the update if already in an idle state\n if (!cacheKey) {\n // oxlint-disable-next-line react/react-compiler\n setState((prev) => (prev.objectUrl || prev.isLoading || prev.error ? IDLE_RESULT : prev))\n return undefined\n }\n\n // Get or create cache entry for this URL/token pair\n let entry = requestCache.get(cacheKey)\n if (!entry) {\n // url and token are guaranteed to exist when cacheKey exists\n entry = createFetchCacheEntry(url!, token!)\n requestCache.set(cacheKey, entry)\n }\n\n // Cancel any pending cleanup from a previous unmount (e.g. Strict Mode)\n if (entry.cleanupTimer) {\n clearTimeout(entry.cleanupTimer)\n entry.cleanupTimer = undefined\n }\n\n // Subscribe to fetch completion and sync current state\n const updateState = () => setState(deriveResultFromEntry(entry))\n updateState()\n entry.listeners.add(updateState)\n\n return () => {\n entry.listeners.delete(updateState)\n\n if (entry.listeners.size === 0) {\n // Delay disposal to allow Strict Mode re-mounts to reuse the entry\n entry.cleanupTimer = setTimeout(() => {\n entry.abortController.abort()\n if (entry.objectUrl) {\n URL.revokeObjectURL(entry.objectUrl)\n }\n requestCache.delete(cacheKey)\n }, CACHE_DISPOSE_DELAY)\n }\n }\n }, [cacheKey, token, url])\n\n return state\n}\n","import {type ImageUrlBuilder, type SanityImageSource} from '@sanity/image-url'\n\nimport {type AssetAccessPolicy} from '../types'\nimport {useImageObjectUrl} from './useImageObjectUrl'\n\ninterface UseImageUrlParameters<T extends SanityImageSource | undefined> {\n accessPolicy?: AssetAccessPolicy\n imageSource?: T\n imageUrlBuilder: ImageUrlBuilder\n transform?: (builder: ImageUrlBuilder, value: SanityImageSource) => string | undefined\n}\n\ninterface UseImageUrlResult {\n isLoading: boolean\n url: string | undefined\n}\n\n/**\n * Hook for resolving image URLs with Private asset support.\n *\n * Handles applying URL transformations and object URL generation when needed.\n *\n * @internal\n */\nexport function useImageUrl<T extends SanityImageSource = SanityImageSource>(\n params: UseImageUrlParameters<T>,\n): UseImageUrlResult {\n const {accessPolicy = 'public', imageSource, imageUrlBuilder, transform} = params\n\n const isPolicyCheckInProgress = accessPolicy === 'checking'\n const isPrivate = accessPolicy === 'private'\n\n // The `http:` or `https:` URL. While an access policy check is in progress,\n // this stays undefined as it may change after the check completes.\n const networkUrl = (() => {\n if (!imageSource || isPolicyCheckInProgress) return undefined\n // Apply the transformations if provided.\n if (transform) return transform(imageUrlBuilder, imageSource)\n return imageUrlBuilder.image(imageSource).url()\n })()\n\n // If the asset is Private, fetch the image using the network URL and convert\n // the response into a `blob:` URL so it can be used as an `<img src>`.\n const {objectUrl, isLoading: objectUrlIsLoading} = useImageObjectUrl(\n isPrivate ? networkUrl : undefined,\n )\n\n const isLoading = isPolicyCheckInProgress || objectUrlIsLoading\n const url = isLoading ? undefined : (objectUrl ?? networkUrl)\n\n return {\n isLoading,\n url,\n }\n}\n","import {CompactPreview} from '../../components/previews/general/CompactPreview'\nimport {DefaultPreview} from '../../components/previews/general/DefaultPreview'\nimport {DetailPreview} from '../../components/previews/general/DetailPreview'\nimport {MediaPreview} from '../../components/previews/general/MediaPreview'\nimport {BlockImagePreview} from '../../components/previews/portableText/BlockImagePreview'\nimport {BlockPreview} from '../../components/previews/portableText/BlockPreview'\nimport {InlinePreview} from '../../components/previews/portableText/InlinePreview'\n\nexport const _previewComponents = {\n block: BlockPreview,\n blockImage: BlockImagePreview,\n compact: CompactPreview,\n default: DefaultPreview,\n detail: DetailPreview,\n inline: InlinePreview,\n media: MediaPreview,\n} as const\n","import {isImageSource, isSanityImageUrl, parseImageAssetUrl} from '@sanity/asset-utils'\nimport {type SanityClient} from '@sanity/client'\nimport {DocumentIcon} from '@sanity/icons/Document'\nimport {WarningOutlineIcon} from '@sanity/icons/WarningOutline'\nimport {\n createImageUrlBuilder,\n type ImageUrlBuilder,\n type SanityImageSource,\n} from '@sanity/image-url'\nimport {Card, Flex, Skeleton} from '@sanity/ui'\nimport {\n type ComponentType,\n type ElementType,\n isValidElement,\n memo,\n type ReactNode,\n useCallback,\n useMemo,\n useState,\n} from 'react'\nimport {isValidElementType} from 'react-is'\n\nimport {Tooltip} from '../../../ui-components/tooltip/Tooltip'\nimport {resolveBlockImageDimensions} from '../../components/previews/helpers'\nimport {type PreviewMediaDimensions, type PreviewProps} from '../../components/previews/types'\nimport {useAccessPolicy} from '../../form/inputs/files/ImageInput/useAccessPolicy'\nimport {useImageUrl} from '../../form/inputs/files/ImageInput/useImageUrl'\nimport {useClient} from '../../hooks/useClient'\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../studioClient'\nimport {isString} from '../../util/isString'\nimport {_previewComponents} from './_previewComponents'\n\nfunction FallbackIcon() {\n return <DocumentIcon className=\"sanity-studio__preview-fallback-icon\" />\n}\n\n/** @internal */\nexport interface SanityDefaultPreviewProps extends Omit<PreviewProps, 'renderDefault'> {\n error?: Error | null\n icon?: ElementType | false\n tooltip?: ReactNode\n}\n\ntype SanityDefaultMediaProps = {\n client: SanityClient\n dimensions: PreviewMediaDimensions\n imageSource: SanityImageSource\n imageUrlBuilder: ImageUrlBuilder\n title: PreviewProps['title']\n}\n\nfunction SanityDefaultMedia({\n client,\n dimensions,\n imageSource,\n imageUrlBuilder,\n title,\n}: SanityDefaultMediaProps) {\n const transform = (builder: ImageUrlBuilder, val: SanityImageSource) => {\n const width = dimensions.width ?? 100\n const height = dimensions.height ?? 100\n const fit = dimensions.fit\n const dpr = dimensions.dpr ?? 1\n\n return builder.image(val).withOptions({width, height, fit, dpr}).url() || ''\n }\n\n const accessPolicy = useAccessPolicy({client, source: imageSource})\n\n const {isLoading, url} = useImageUrl({\n accessPolicy,\n imageSource,\n imageUrlBuilder,\n transform,\n })\n\n const [hasImageError, setHasImageError] = useState(false)\n const handleError = () => setHasImageError(true)\n\n if (isLoading) {\n return <Skeleton animated style={{width: '100%', height: '100%'}} />\n }\n\n // Show a warning if we have a media library asset that we couldn't check\n // the access policy for (e.g., cookie auth) and the image failed to load\n const showAccessWarning = accessPolicy === 'unknown' && hasImageError\n\n if (showAccessWarning) {\n return (\n <Card tone=\"critical\" style={{width: '100%', height: '100%'}}>\n <Flex justify=\"center\" align=\"center\" style={{width: '100%', height: '100%'}}>\n <WarningOutlineIcon />\n </Flex>\n </Card>\n )\n }\n\n return (\n <img\n alt={typeof title === 'string' ? title : undefined}\n onError={handleError}\n referrerPolicy=\"strict-origin-when-cross-origin\"\n src={url}\n />\n )\n}\n\n/**\n * Used in cases where no custom preview component is provided\n * @internal\n * */\nexport const SanityDefaultPreview = memo(function SanityDefaultPreview(\n props: SanityDefaultPreviewProps,\n): React.JSX.Element {\n const {icon: Icon, layout, media: mediaProp, imageUrl, title, tooltip, ...restProps} = props\n\n const client = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const imageBuilder = useMemo(() => createImageUrlBuilder(client), [client])\n\n // NOTE: This function exists because the previews provides options\n // for the rendering of the media (dimensions)\n const renderMedia = useCallback(\n (options: {dimensions: PreviewMediaDimensions}) => {\n let imageSource = mediaProp\n\n // If this is a string and a valid Sanity Image URL, parse it so that we can\n // pass it as a valid asset ID to the image builder\n if (isString(imageSource) && isSanityImageUrl(imageSource)) {\n const {assetId} = parseImageAssetUrl(imageSource)\n\n imageSource = assetId\n }\n\n return (\n <SanityDefaultMedia\n client={client}\n dimensions={options.dimensions}\n imageSource={imageSource as SanityImageSource}\n imageUrlBuilder={imageBuilder}\n title={title}\n />\n )\n },\n [client, imageBuilder, mediaProp, title],\n )\n\n const renderIcon = useCallback(() => {\n return Icon ? <Icon /> : <FallbackIcon />\n }, [Icon])\n\n const media = useMemo(() => {\n if (Icon === false) {\n // Explicitly disabled\n return false\n }\n\n // If this is a string and a valid Sanity Image URL, pass it to the renderMedia function early\n // If we don't do this check early, then isValidElementType will return true for strings and create an\n // exception when used inside the BlockImagePreview\n if (isString(mediaProp) && isSanityImageUrl(mediaProp)) {\n return renderMedia\n }\n\n if (isImageSource(mediaProp)) {\n return renderMedia\n }\n\n if (isValidElementType(mediaProp)) {\n return mediaProp\n }\n\n if (isValidElement(mediaProp)) {\n return mediaProp\n }\n\n // Handle image urls\n if (isString(imageUrl)) {\n return (\n <img\n src={imageUrl}\n alt={isString(title) ? title : undefined}\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n )\n }\n\n // Render fallback icon\n return renderIcon\n }, [Icon, imageUrl, mediaProp, renderIcon, renderMedia, title])\n\n const resolvedMediaDimensions = useMemo<PreviewMediaDimensions | undefined>(() => {\n if (props.mediaDimensions) {\n return props.mediaDimensions\n }\n\n if (layout !== 'blockImage') {\n return undefined\n }\n\n if (!isImageSource(mediaProp)) {\n return undefined\n }\n\n return resolveBlockImageDimensions(mediaProp)\n }, [layout, mediaProp, props.mediaDimensions])\n\n const previewProps: Omit<PreviewProps, 'renderDefault'> = useMemo(\n () => ({\n ...restProps,\n media,\n mediaDimensions: resolvedMediaDimensions,\n title,\n }),\n [media, resolvedMediaDimensions, restProps, title],\n )\n\n const LayoutComponent = _previewComponents[layout || 'default'] as ComponentType<\n Omit<PreviewProps, 'renderDefault'>\n >\n\n const children = <LayoutComponent {...previewProps} />\n\n if (tooltip) {\n return (\n <Tooltip\n content={tooltip}\n disabled={!tooltip}\n fallbackPlacements={['top-end', 'bottom-end']}\n placement=\"right\"\n >\n {/* Currently tooltips won't trigger without a wrapping element */}\n <div>{children}</div>\n </Tooltip>\n )\n }\n\n return children\n})\nSanityDefaultPreview.displayName = 'Memo(SanityDefaultPreview)'\n","import {type SchemaType} from '@sanity/types'\nimport {type ComponentType} from 'react'\n\nimport {type PreviewProps} from '../../../components/previews/types'\nimport {SanityDefaultPreview} from '../../../preview/components/SanityDefaultPreview'\n\n// Kept separate from `inputResolver.tsx`: preview resolution only needs `SanityDefaultPreview`,\n// while the input resolver pulls in every input component. Consumers of `usePreviewComponent`\n// (e.g. `Preview`, which the input tree renders) would otherwise circularly import the whole\n// form input tree.\n\nexport function defaultResolvePreviewComponent(\n schemaType: SchemaType,\n): ComponentType<Omit<PreviewProps, 'renderDefault'>> {\n if (schemaType.components?.preview) return schemaType.components.preview\n\n return SanityDefaultPreview\n}\n","import {type ComponentType} from 'react'\n\nimport {type PreviewProps} from '../../components/previews/types'\nimport {type PluginOptions} from '../../config/types'\nimport {\n type BlockAnnotationProps,\n type BlockProps,\n type PortableTextPluginsProps,\n} from '../types/blockProps'\nimport {type FieldProps} from '../types/fieldProps'\nimport {type InputProps} from '../types/inputProps'\nimport {type ItemProps} from '../types/itemProps'\n\nexport function pickInputComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<InputProps, 'renderDefault'>> {\n return plugin.form?.components?.input as ComponentType<Omit<InputProps, 'renderDefault'>>\n}\n\nexport function pickFieldComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<FieldProps, 'renderDefault'>> {\n return plugin.form?.components?.field as ComponentType<Omit<FieldProps, 'renderDefault'>>\n}\n\nexport function pickPreviewComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<PreviewProps, 'renderDefault'>> {\n return plugin.form?.components?.preview as ComponentType<Omit<PreviewProps, 'renderDefault'>>\n}\n\nexport function pickItemComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<ItemProps, 'renderDefault'>> {\n return plugin.form?.components?.item as ComponentType<Omit<ItemProps, 'renderDefault'>>\n}\n\nexport function pickBlockComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<BlockProps, 'renderDefault'>> {\n return plugin.form?.components?.block as ComponentType<Omit<BlockProps, 'renderDefault'>>\n}\n\nexport function pickInlineBlockComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<BlockProps, 'renderDefault'>> {\n return plugin.form?.components?.inlineBlock as ComponentType<Omit<BlockProps, 'renderDefault'>>\n}\n\nexport function pickAnnotationComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<BlockAnnotationProps, 'renderDefault'>> {\n return plugin.form?.components?.annotation as ComponentType<\n Omit<BlockAnnotationProps, 'renderDefault'>\n >\n}\n\nexport function pickPortableTextEditorPluginsComponent(\n plugin: PluginOptions,\n): ComponentType<Omit<PortableTextPluginsProps, 'renderDefault'>> {\n return plugin.form?.components?.portableText?.plugins as ComponentType<\n Omit<PortableTextPluginsProps, 'renderDefault'>\n >\n}\n","import {type SchemaType} from '@sanity/types'\nimport {type ComponentType, useCallback, useMemo} from 'react'\n\n// Each form component hook lives in its own module (together with the default component it\n// resolves) so that form components which consume a sibling hook (e.g. `ListArrayInput` uses\n// `useItemComponent`, `Preview` uses `usePreviewComponent`) only pull in that hook's resolver\n// subtree instead of every resolver, which would create circular imports through the shared\n// module.\n\n/**\n * @internal\n */\nexport function useResolveDefaultComponent<T extends {schemaType?: SchemaType}>(props: {\n componentProps: Omit<T, 'renderDefault'>\n componentResolver: (schemaType: SchemaType) => ComponentType<Omit<T, 'renderDefault'>>\n}): React.JSX.Element {\n const {componentResolver, componentProps} = props\n const {schemaType} = componentProps\n\n // NOTE: this will not happen, but we do this to avoid updating too many places\n // TODO: We need to clean up the preview machinery + types to remove this\n if (!schemaType) {\n throw new Error('the `schemaType` property must be defined')\n }\n\n // Memoized so the resolved component keeps a stable identity across renders; a new identity\n // would make React unmount and remount the subtree.\n const DefaultResolvedComponent = useMemo(\n () => componentResolver(schemaType),\n [componentResolver, schemaType],\n )\n\n const renderDefault = useCallback(\n (parentTypeProps: T) => {\n if (!parentTypeProps.schemaType?.type) {\n // In theory this should not be possible, and this error should never be thrown\n throw new Error('Attempted to render form component of non-existent parent type')\n }\n\n // The components property is removed from the schemaType object\n // in order to prevent that a component is render itself\n // oxlint-disable-next-line no-unused-vars\n const {components, ...restSchemaType} = parentTypeProps.schemaType\n const ParentTypeResolvedComponent = componentResolver(restSchemaType)\n return <ParentTypeResolvedComponent {...parentTypeProps} />\n },\n [componentResolver],\n )\n\n // oxlint-disable-next-line react/react-compiler -- this is intentional and how the middleware components has to work\n return <DefaultResolvedComponent {...componentProps} renderDefault={renderDefault} />\n}\n","import {type ComponentType} from 'react'\n\nimport {type PreviewProps} from '../../components/previews/types'\nimport {useMiddlewareComponents} from '../../config/components/useMiddlewareComponents'\nimport {defaultResolvePreviewComponent} from '../studio/inputResolver/previewResolver'\nimport {pickPreviewComponent} from './picks'\nimport {useResolveDefaultComponent} from './useResolveDefaultComponent'\n\n/**\n * @internal\n */\nfunction DefaultPreview(props: Omit<PreviewProps, 'renderDefault'>): React.JSX.Element {\n return useResolveDefaultComponent<PreviewProps>({\n componentProps: props,\n componentResolver: defaultResolvePreviewComponent,\n })\n}\n\n/**\n * @internal\n */\nexport function usePreviewComponent(): ComponentType<Omit<PreviewProps, 'renderDefault'>> {\n return useMiddlewareComponents({\n defaultComponent: DefaultPreview,\n pick: pickPreviewComponent,\n })\n}\n","import {useContext} from 'react'\nimport {PerspectiveContext} from 'sanity/_singletons'\n\nimport {type PerspectiveContextValue} from './types'\n\n/**\n * @beta\n *\n * React hook that returns the current studio perspective and perspective stack.\n *\n * This will use the closest PerspectiveContext provider, which is either the global\n * PerspectiveContext or the DocumentPerspectiveProvider.\n *\n * @returns See {@link PerspectiveContextValue}\n * @example Reading the current perspective stack\n * ```ts\n * function MyComponent() {\n * const {perspectiveStack} = usePerspective()\n * // ... do something with the perspective stack , like passing it to the client perspective.\n * }\n * ```\n */\nexport function usePerspective(): PerspectiveContextValue {\n const context = useContext(PerspectiveContext)\n if (!context) {\n throw new Error('usePerspective must be used within a PerspectiveProvider')\n }\n return context\n}\n","import {type SanityDocument} from '@sanity/client'\nimport {type SanityDocumentLike} from '@sanity/types'\n\n/**\n * checks if the document has been set for unpublishing\n * @internal\n *\n * @param document - sanity document\n * @returns boolean if the system delete is set\n */\nexport function isGoingToUnpublish(document: SanityDocument | SanityDocumentLike): boolean {\n return Boolean(document._system?.delete === true)\n}\n","import {\n type PreviewValue,\n type SanityDocument,\n type SchemaType,\n type SortOrdering,\n} from '@sanity/types'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\nimport {type Observable, of} from 'rxjs'\nimport {catchError, map} from 'rxjs/operators'\n\nimport {type PerspectiveStack} from '../perspective/types'\nimport {usePerspective} from '../perspective/usePerspective'\nimport {isGoingToUnpublish} from '../releases/util/isGoingToUnpublish'\nimport {useDocumentPreviewStore} from '../store/datastores'\nimport {getPublishedId} from '../util/draftUtils'\nimport {type Previewable} from './types'\n\n/**\n * @internal\n * @deprecated use useValuePreview instead\n */\nexport const unstable_useValuePreview = useValuePreview\n\ninterface State {\n isLoading: boolean\n error?: Error\n value?: PreviewValue\n}\nconst INITIAL_STATE: State = {\n isLoading: true,\n}\n\nconst IDLE_STATE: State = {\n isLoading: false,\n value: {\n title: undefined,\n description: undefined,\n },\n}\n/**\n * @internal\n */\nexport function useValuePreview(props: {\n enabled?: boolean\n ordering?: SortOrdering\n schemaType?: SchemaType\n value: unknown | undefined\n perspectiveStack?: PerspectiveStack\n /**\n * The variant to preview the value as seen through, as a bare variant id.\n *\n * The variant travels with the perspective: when no `perspectiveStack` is given, both default to\n * the current selection in the perspective context. When a `perspectiveStack` is given, the\n * caller is previewing a specific document version and only the variant it passes here is used.\n */\n variant?: string\n}): State {\n const {\n enabled = true,\n ordering,\n schemaType,\n value: previewValue,\n perspectiveStack: chosenPerspectiveStack,\n variant: chosenVariant,\n } = props || {}\n const {observeForPreview} = useDocumentPreviewStore()\n const {perspectiveStack, selectedVariantName} = usePerspective()\n const observable = useMemo<Observable<State>>(() => {\n // this will render previews as \"loaded\" (i.e. not in loading state) – typically with \"Untitled\" text\n if (!enabled || !previewValue || !schemaType) return of(IDLE_STATE)\n\n const goingToUnpublish = isGoingToUnpublish(previewValue as SanityDocument)\n\n const updatedStack = goingToUnpublish ? [] : (chosenPerspectiveStack ?? perspectiveStack)\n // A document slated for unpublishing is previewed as its published version, which is outside\n // of any variant. Otherwise the variant follows the perspective: only inherited from the\n // context when the perspective is too.\n const updatedVariant = goingToUnpublish\n ? undefined\n : (chosenVariant ?? (chosenPerspectiveStack ? undefined : selectedVariantName))\n const updatedDocId = goingToUnpublish\n ? getPublishedId((previewValue as SanityDocument)._id)\n : (previewValue as SanityDocument)._id\n\n // allow for previewing the published document when a version is slated for unpublishing\n // but if it's not for unpublishing, then we want to preview the content as was before\n const restPreviewValue = goingToUnpublish\n ? {}\n : {\n ...(previewValue as Previewable),\n }\n\n return observeForPreview(\n {\n _id: updatedDocId,\n ...restPreviewValue,\n },\n schemaType,\n {\n perspective: updatedStack,\n variant: updatedVariant,\n viewOptions: {ordering: ordering},\n },\n ).pipe(\n map((event) => ({isLoading: false, value: event.snapshot || undefined})),\n catchError((error) => of({isLoading: false, error})),\n )\n }, [\n enabled,\n previewValue,\n schemaType,\n chosenPerspectiveStack,\n perspectiveStack,\n chosenVariant,\n selectedVariantName,\n observeForPreview,\n ordering,\n ])\n\n // Do not defer: search/reference UIs assert on preview titles synchronously after selection.\n return useSyncObservable(observable, INITIAL_STATE)\n}\n","import {EMPTY, fromEvent} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const orientationChange$ =\n typeof window === 'undefined'\n ? EMPTY\n : fromEvent(window, 'orientationchange').pipe(shareReplay(1))\n","import {EMPTY, fromEvent} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const resize$ =\n typeof window === 'undefined' ? EMPTY : fromEvent(window, 'resize').pipe(shareReplay(1))\n","import {EMPTY, fromEvent} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const scroll$ =\n typeof window === 'undefined'\n ? EMPTY\n : fromEvent(window, 'scroll', {passive: true, capture: true}).pipe(shareReplay(1))\n","import {merge, Observable, of as observableOf, Subject} from 'rxjs'\nimport {filter, map, mergeMap} from 'rxjs/operators'\n\nimport {orientationChange$} from './orientationChange'\nimport {resize$} from './resize'\nimport {scroll$} from './scroll'\n\nconst ROOT_MARGIN_PX = 150\n\n/*\n Adapted from the polyfill at https://github.com/WICG/IntersectionObserver\n*/\nfunction isIntersectionObserverSupported() {\n if (\n typeof window !== 'undefined' &&\n 'IntersectionObserver' in window &&\n 'IntersectionObserverEntry' in window &&\n 'intersectionRatio' in IntersectionObserverEntry.prototype\n ) {\n // Minimal polyfill for Edge 15's lack of `isIntersecting`\n // See: https://github.com/WICG/IntersectionObserver/issues/211\n if (!('isIntersecting' in IntersectionObserverEntry.prototype)) {\n Object.defineProperty(IntersectionObserverEntry.prototype, 'isIntersecting', {\n get() {\n return this.intersectionRatio > 0\n },\n })\n }\n return true\n }\n return false\n}\n\ntype IntersectionEvent = {isIntersecting: boolean}\n\nexport const intersectionObservableFor = isIntersectionObserverSupported()\n ? createIntersectionObserverBased()\n : createLegacyBased()\n\ntype IntersectionObservableFor = (element: Element) => Observable<IntersectionEvent>\n\nfunction createIntersectionObserverBased(): IntersectionObservableFor {\n const intersectionObserverEntriesSubject = new Subject<IntersectionObserverEntry>()\n\n const intersectionObserver = new IntersectionObserver(\n (entries) => {\n entries.forEach((entry) => {\n intersectionObserverEntriesSubject.next(entry)\n })\n },\n {\n threshold: 0,\n rootMargin: `${ROOT_MARGIN_PX}px`,\n },\n )\n\n return function intersectionObservableFor(element) {\n return new Observable<void>((observer) => {\n intersectionObserver.observe(element)\n observer.next()\n return () => intersectionObserver.unobserve(element)\n }).pipe(\n mergeMap(() => intersectionObserverEntriesSubject.asObservable()),\n filter((entry: IntersectionObserverEntry) => entry.target === element),\n map((ev) => ({\n isIntersecting: ev.isIntersecting,\n })),\n )\n }\n}\n\n// This can be removed when intersection observer are supported by the browsers we support\nfunction createLegacyBased() {\n function getViewport() {\n return {\n left: 0,\n right: window.innerWidth,\n top: 0,\n bottom: window.innerHeight,\n }\n }\n\n function intersects(\n rect: DOMRect,\n viewport: {left: number; right: number; top: number; bottom: number},\n margin: number,\n ) {\n return (\n rect.left <= viewport.right + margin &&\n rect.right >= viewport.left - margin &&\n rect.top <= viewport.bottom + margin &&\n rect.bottom >= viewport.top - margin\n )\n }\n\n function inViewport(element: HTMLElement) {\n return () => intersects(element.getBoundingClientRect(), getViewport(), ROOT_MARGIN_PX)\n }\n\n return function intersectionObservableFor(element: HTMLElement): Observable<IntersectionEvent> {\n const isElementInViewport = inViewport(element)\n return merge(observableOf(isElementInViewport()), resize$, scroll$, orientationChange$).pipe(\n // @todo: consider \"faking\" more of the IntersectionObserverEntry api if possible\n map(isElementInViewport),\n map((isIntersecting) => ({isIntersecting})),\n )\n }\n}\n","import {EMPTY, fromEvent, type Observable} from 'rxjs'\nimport {shareReplay} from 'rxjs/operators'\n\nexport const visibilityChange$: Observable<Event> =\n typeof window === 'undefined'\n ? EMPTY\n : fromEvent(document, 'visibilitychange').pipe(shareReplay(1))\n","import {useMemo} from 'react'\nimport {useObservable} from 'react-rx'\nimport {concat, of} from 'rxjs'\nimport {delay, distinctUntilChanged, map, startWith, switchMap} from 'rxjs/operators'\n\nimport {intersectionObservableFor} from './streams/intersectionObservableFor'\nimport {visibilityChange$} from './streams/visibilityChange'\n\ninterface Props {\n /**\n * Disable the check. The hook will return false if disabled\n */\n disabled?: boolean\n /** DOM Node to check visibility for */\n element: HTMLElement | null\n /** When element is hidden, wait this delay in milliseconds before reporting it as */\n hideDelay?: number\n}\n\nexport function useVisibility(props: Props): boolean {\n const {element, hideDelay = 0, disabled} = props\n\n const visible$ = useMemo(() => {\n if (!element || disabled) {\n return of(false)\n }\n\n // Seed with the element's current visibility so the first paint is\n // correct — every code path here emits synchronously on subscribe, so\n // useSyncObservable's fallback initial value is never read.\n const seed = 'checkVisibility' in element ? element.checkVisibility() : false\n\n const isDocumentVisible$ = concat(\n of(!document.hidden),\n visibilityChange$.pipe(\n map((event) => (event.target instanceof Document ? !event?.target?.hidden : false)),\n ),\n ).pipe(distinctUntilChanged())\n\n const inViewport$ = intersectionObservableFor(element).pipe(\n map((event) => event.isIntersecting),\n )\n\n return isDocumentVisible$.pipe(\n switchMap((isDocumentVisible) => (isDocumentVisible ? inViewport$ : of(false))),\n switchMap((isVisible) => (isVisible ? of(true) : of(false).pipe(delay(hideDelay)))),\n distinctUntilChanged(),\n startWith(seed),\n )\n }, [element, hideDelay, disabled])\n\n const visible = useObservable(visible$, false)\n\n return disabled ? false : visible\n}\n","export const _HIDE_DELAY = 1000 * 2 // 2 seconds\n","import {type UploadState} from '@sanity/types'\n\nimport {isRecord} from '../../util/isRecord'\nimport {isString} from '../../util/isString'\n\nexport function _extractUploadState(value: any): UploadState | undefined {\n return _resolveUploadValue(value?._upload)\n}\n\nfunction getStringOrUndefined(value: unknown): string | undefined {\n return isString(value) ? value : undefined\n}\nfunction _resolveUploadValue(value: unknown): UploadState | undefined {\n if (!isRecord(value)) return undefined\n\n const progress = typeof value.progress === 'number' ? value.progress : 0\n const createdAt = getStringOrUndefined(value.initiated || value.createdAt)\n const updatedAt = getStringOrUndefined(value.updated || value.updatedAt)\n const fileName = getStringOrUndefined((value?.file as any)?.name)\n const fileType = getStringOrUndefined((value?.file as any)?.type)\n const previewImage = getStringOrUndefined(value.previewImage)\n\n if (createdAt && updatedAt && fileName && fileType) {\n return {\n progress,\n createdAt,\n updatedAt,\n file: {name: fileName, type: fileType},\n previewImage,\n }\n }\n\n return undefined\n}\n","import {type ComponentType, type CSSProperties, useMemo, useState} from 'react'\n\nimport {type PreviewProps} from '../../components/previews/types'\nimport {type RenderPreviewCallbackProps} from '../../form/types/renderCallback'\nimport {useTranslation} from '../../i18n/hooks/useTranslation'\nimport {type PerspectiveStack} from '../../perspective/types'\nimport {useValuePreview} from '../useValuePreview'\nimport {useVisibility} from '../useVisibility'\nimport {_HIDE_DELAY} from './_constants'\nimport {_extractUploadState} from './_extractUploadState'\n\n/**\n * This component is responsible for converting renderPreview() calls into an element.\n * It:\n * - subscribes to \"prepared\" preview value as long as the element is visible on screen\n * - resolves the configured preview component for the schema type\n * - prepares \"preview\"-props and passes this to the configured preview component\n * @internal\n * */\nexport function PreviewLoader(\n props: RenderPreviewCallbackProps & {\n component: ComponentType<Omit<PreviewProps, 'renderDefault'>>\n perspectiveStack?: PerspectiveStack\n variant?: string\n },\n): React.JSX.Element {\n const {\n layout,\n value,\n component: Component,\n style: styleProp,\n schemaType,\n skipVisibilityCheck,\n perspectiveStack,\n variant,\n ...restProps\n } = props\n\n const {t} = useTranslation()\n const [element, setElement] = useState<HTMLDivElement | null>(null)\n\n // Subscribe to visibility\n const isVisible =\n useVisibility({\n disabled: skipVisibilityCheck,\n element: element,\n hideDelay: _HIDE_DELAY,\n }) || skipVisibilityCheck\n\n // Subscribe document preview value\n const preview = useValuePreview({\n enabled: skipVisibilityCheck || isVisible,\n schemaType,\n value,\n perspectiveStack,\n variant,\n })\n\n const style: CSSProperties = useMemo(\n () => ({\n ...styleProp,\n minWidth: styleProp?.minWidth || 1,\n minHeight: styleProp?.minHeight || 1,\n }),\n [styleProp],\n )\n\n const uploadState = useMemo(() => _extractUploadState(value), [value])\n\n const media: PreviewProps['media'] = useMemo(() => {\n if (uploadState?.previewImage) {\n return (\n <img\n alt={t('preview.image.file-is-being-uploaded.alt-text')}\n src={uploadState.previewImage}\n />\n )\n }\n\n // media: null or false explicitly suppresses the icon.\n // All other falsy cases (undefined, missing key) fall back to the schema icon.\n if (preview?.value?.media === null || preview?.value?.media === false) {\n return undefined\n }\n\n if (!preview?.value?.media) {\n return schemaType.icon\n }\n\n // @todo: fix `TS2769: No overload matches this call.`\n return preview?.value?.media as any\n }, [preview, schemaType, uploadState, t])\n\n return (\n <div ref={setElement} style={style}>\n <Component\n {...restProps}\n {...(preview?.value || {})}\n media={media}\n error={preview?.error}\n isPlaceholder={preview?.isLoading}\n layout={layout}\n schemaType={schemaType}\n />\n </div>\n )\n}\n","import {usePreviewComponent} from '../../form/form-components-hooks/usePreviewComponent'\nimport {type RenderPreviewCallbackProps} from '../../form/types/renderCallback'\nimport {type PerspectiveStack} from '../../perspective/types'\nimport {PreviewLoader} from './PreviewLoader'\n\n/**\n * @internal\n */\nexport function Preview(\n props: RenderPreviewCallbackProps & {perspectiveStack?: PerspectiveStack; variant?: string},\n) {\n const PreviewComponent = usePreviewComponent()\n return <PreviewLoader {...props} component={PreviewComponent} />\n}\n","import {useSource} from '../studio/source'\n\n/**\n * React hook that returns the name of the current dataset\n *\n * @public\n * @returns The name of the current dataset\n * @example Using the `useDataset` hook\n * ```ts\n * function MyComponent() {\n * const dataset = useDataset()\n * // ... do something with the dataset name ...\n * }\n * ```\n */\nexport function useDataset(): string {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n return useSource().dataset\n}\n","import {type ReleaseDocument} from '@sanity/client'\nimport {getVersionFromId} from '@sanity/client/csm'\nimport {type DocumentSystem} from '@sanity/types'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\nimport {\n catchError,\n combineLatest,\n finalize,\n map,\n type Observable,\n of,\n ReplaySubject,\n share,\n startWith,\n switchMap,\n timer,\n} from 'rxjs'\n\nimport {useDataset} from '../../hooks/useDataset'\nimport {useProjectId} from '../../hooks/useProjectId'\nimport {DOCUMENT_SYSTEM_FIELD} from '../../preview/constants'\nimport {type DocumentPreviewStore} from '../../preview/documentPreviewStore'\nimport {useDocumentPreviewStore} from '../../store/datastores'\nimport {isDraftId, getPublishedId} from '../../util/draftUtils'\nimport {isRecord} from '../../util/isRecord'\nimport {createSWR} from '../../util/rxSwr'\nimport {type VersionInfoDocumentStub} from '../store/types'\nimport {useReleasesStore} from '../store/useReleasesStore'\nimport {ARCHIVED_RELEASE_STATES} from '../util/const'\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\n\nexport interface DocumentPerspectiveProps {\n documentId: string\n}\n\nexport interface DocumentPerspectiveState {\n data: string[]\n versions: VersionInfoDocumentStub[]\n error?: unknown\n loading: boolean\n}\n\nconst INITIAL_VALUE: DocumentPerspectiveState = {\n data: [],\n versions: [],\n error: null,\n loading: true,\n}\n\n// Create a singleton cache for observables\nexport const observableCache = new Map<string, Observable<DocumentPerspectiveState>>()\n// releases flow via combineLatest, never in the cache key, to avoid cache thrash on every release edit\nexport const withSystemCache = new Map<string, Observable<DocumentPerspectiveState>>()\nconst swr = createSWR<string[]>({maxSize: 100})\n\n// How long to keep the pipeline alive after the last subscriber unsubscribes.\n// Subscriber churn (components re-rendering/remounting around commits) can\n// momentarily drop the refcount to zero. A bare teardown deletes the cache\n// entry, and the re-created pipeline synchronously re-enters the\n// `startWith(loadingState)` path (the version id set is non-empty for any\n// document with a draft or published variant), so `loading: true` reaches\n// `useDocumentForm`'s `ready` gate and flips the form read-only until the\n// `observePaths` round trip settles — silently swallowing keystrokes typed in\n// that window.\nconst TEARDOWN_GRACE_PERIOD = 1_000\n\n/**\n * Fetches the document versions for a given document\n *\n * @param props - document Id of the document (might include release id)\n * @returns - data: document versions, loading, errors\n * @hidden\n * @beta\n */\nexport function useDocumentVersions(props: DocumentPerspectiveProps): DocumentPerspectiveState {\n const observable = useDocumentVersionsObservable(props)\n // Kept synchronous: `useTargetDocumentState` / `useDocumentForm` derive the\n // pair-checkout scope and the form's ready gate from this state, so a\n // deferred snapshot could bind the form to the wrong version scope after\n // navigation or a version change.\n return useSyncObservable(observable, INITIAL_VALUE)\n}\n\n/**\n * Creates an observable that emits the document versions for a given document.\n *\n * @hidden\n * @beta\n */\nexport function useDocumentVersionsObservable(\n props: DocumentPerspectiveProps,\n): Observable<DocumentPerspectiveState> {\n const {documentId} = props\n const publishedId = getPublishedId(documentId)\n\n const dataset = useDataset()\n const projectId = useProjectId()\n const documentPreviewStore = useDocumentPreviewStore()\n const {state$: releasesState$} = useReleasesStore()\n\n const releases$ = useMemo(\n () =>\n releasesState$.pipe(\n map((state) =>\n Array.from(state.releases.values()).filter(\n (release) => !ARCHIVED_RELEASE_STATES.includes(release.state),\n ),\n ),\n ),\n [releasesState$],\n )\n\n const observable: Observable<DocumentPerspectiveState> = useMemo(\n () =>\n getOrCreateDocumentVersionsWithSystemObservable({\n documentPreviewStore,\n publishedId,\n projectId,\n dataset,\n releases$,\n }),\n [dataset, documentPreviewStore, projectId, publishedId, releases$],\n )\n\n return observable\n}\n\n/**\n * Temporarily builds the document _system for a given document id.\n * This is used until the documents are migrated to the new _system.\n * And only if the documents are not variant documents.\n *\n * Variants will include the _system field.\n */\nconst buildDocumentSystem = (id: string, releases: ReleaseDocument[]): DocumentSystem => {\n const versionId = getVersionFromId(id)\n if (versionId) {\n const releaseDocument = releases.find(\n (release) => getReleaseIdFromReleaseDocumentId(release._id) === versionId,\n )\n return {\n bundleId: versionId,\n release: releaseDocument ? {_ref: releaseDocument._id, _weak: true} : undefined,\n group: {\n _ref: getPublishedId(id),\n _weak: true,\n },\n scopeId: versionId,\n }\n }\n\n return {\n bundleId: isDraftId(id) ? 'drafts' : undefined,\n group: {_ref: getPublishedId(id), _weak: true},\n }\n}\n\nconst resolveVersionSystem = (\n version: VersionInfoDocumentStub,\n releases: ReleaseDocument[],\n): DocumentSystem => {\n if (version._system?.group) return version._system\n\n return {\n ...version._system,\n ...buildDocumentSystem(version._id, releases),\n }\n}\n\nconst DOCUMENT_STUB_PATHS = ['_id', '_type', '_rev', '_createdAt', '_updatedAt', '_system']\n\nfunction getOrCreateCachedObservable<T>(\n cache: Map<string, Observable<T>>,\n cacheKey: string,\n createObservable: () => Observable<T>,\n): Observable<T> {\n const cached = cache.get(cacheKey)\n if (cached) return cached\n\n const observable = createObservable().pipe(\n finalize(() => cache.delete(cacheKey)),\n share({\n connector: () => new ReplaySubject(1),\n resetOnRefCountZero: () => timer(TEARDOWN_GRACE_PERIOD),\n }),\n )\n\n cache.set(cacheKey, observable)\n return observable\n}\n\nexport function getOrCreateDocumentVersionsWithSystemObservable(options: {\n documentPreviewStore: DocumentPreviewStore\n publishedId: string\n projectId: string\n dataset: string\n releases$: Observable<ReleaseDocument[]>\n}): Observable<DocumentPerspectiveState> {\n const {documentPreviewStore, projectId, dataset, publishedId, releases$} = options\n const cacheKey = `${projectId}-${dataset}-${publishedId}`\n\n return getOrCreateCachedObservable(withSystemCache, cacheKey, () =>\n combineLatest([\n getOrCreateDocumentVersionsObservable({\n documentPreviewStore,\n publishedId,\n projectId,\n dataset,\n }),\n releases$,\n ]).pipe(\n map(([result, releases]) => ({\n ...result,\n versions: result.versions.map((version) => ({\n ...version,\n [DOCUMENT_SYSTEM_FIELD]: resolveVersionSystem(version, releases),\n })),\n })),\n ),\n )\n}\n\n/**\n * Retrieves an observable that emits document IDs matching the document versions that exist for a specific id\n *\n * @param options - The options for creating or retrieving the observable.\n * options.documentPreviewStore - The store used to observe document IDs.\n * options.publishedId - The ID of the published document.\n * options.projectId - The project ID.\n * options.dataset - The dataset name.\n * @returns An observable that emits the document versions.\n *\n * @hidden\n * @internal\n */\nexport function getOrCreateDocumentVersionsObservable(options: {\n documentPreviewStore: DocumentPreviewStore\n publishedId: string\n projectId: string\n dataset: string\n}): Observable<DocumentPerspectiveState> {\n const {documentPreviewStore, projectId, dataset, publishedId} = options\n const cacheKey = `${projectId}-${dataset}-${publishedId}`\n\n return getOrCreateCachedObservable(observableCache, cacheKey, () =>\n documentPreviewStore.unstable_observeVersionDocumentIds(publishedId).pipe(\n swr(cacheKey),\n map(({value}) => value),\n switchMap((documentIds, index): Observable<DocumentPerspectiveState> => {\n if (documentIds.length === 0) {\n return of({data: [], versions: [], error: null, loading: false})\n }\n\n const versions$ = combineLatest(\n documentIds.map((id) =>\n documentPreviewStore.observePaths({_id: id}, DOCUMENT_STUB_PATHS).pipe(\n map((versionInfo) => (isRecord(versionInfo) ? versionInfo : undefined)),\n map(\n (versionInfo) =>\n ({\n _id: id,\n _rev: versionInfo?._rev ?? '',\n _createdAt: versionInfo?._createdAt ?? '',\n _updatedAt: versionInfo?._updatedAt ?? '',\n [DOCUMENT_SYSTEM_FIELD]: versionInfo?.[DOCUMENT_SYSTEM_FIELD] as DocumentSystem,\n }) satisfies VersionInfoDocumentStub,\n ),\n ),\n ),\n ).pipe(\n map((versions) => ({\n data: documentIds,\n versions,\n error: null,\n loading: false,\n })),\n )\n\n // Only the pipeline's very first id-set emission is a cold start that must block\n // with `loading: true` (it gates `useDocumentForm`'s `ready` state). Later id-set\n // changes happen while the user is editing — e.g. the draft id appearing on the\n // first keystroke in a new document, or publish swapping draft for published — and\n // re-emitting `loading: true` then would flip the whole form read-only mid-typing,\n // silently dropping keystrokes and DOM focus. Keep replaying the last loaded state\n // until the fresh stubs arrive instead.\n if (index > 0) {\n return versions$\n }\n\n const loadingState: DocumentPerspectiveState = {\n data: documentIds,\n versions: [],\n error: null,\n loading: true,\n }\n\n return versions$.pipe(startWith(loadingState))\n }),\n catchError((error) => {\n return of({\n error,\n data: [] as string[],\n versions: [] as VersionInfoDocumentStub[],\n loading: false,\n })\n }),\n ),\n )\n}\n","import {useContext} from 'react'\nimport {ActiveWorkspaceMatcherContext} from 'sanity/_singletons'\n\nimport {type ActiveWorkspaceMatcherContextValue} from './ActiveWorkspaceMatcherContext'\n\n/** @internal */\nexport function useActiveWorkspace(): ActiveWorkspaceMatcherContextValue {\n const value = useContext(ActiveWorkspaceMatcherContext)\n if (!value) throw new Error('Could not find `ActiveWorkspaceMatcher` context')\n return value\n}\n","import {\n type CanvasResource,\n type Events,\n type MediaResource,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useComlinkStore} from '../store/datastores'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n}\n\n/**\n * @public\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * IMPORTANT!\n *\n * Based on the `useRecordDocumentHistoryEvent.ts` from `@sanity/sdk`.\n * This version has been lightly modified to use Studio's Comlink Store.\n *\n * TODO: Adopt `@sanity/sdk` when a compatible version is available.\n *\n * ---\n *\n * Hook for managing document interaction history in Sanity Studio.\n * This hook provides functionality to record document interactions.\n *\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n * - `isConnected` - Boolean indicating if connection to Studio is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent, isConnected} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => recordEvent('viewed')}\n * text={'Viewed'}\n * />\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const {node} = useComlinkStore()\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n // The run() wrapper is a workaround for React Compiler not yet fully supporting try/catch syntax\n const run = () => {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n node?.post?.(message.type, message.data)\n }\n try {\n run()\n } catch (error) {\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, schemaName, node],\n )\n\n return {\n recordEvent,\n }\n}\n","import {useCallback, useMemo, useState} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {useRenderingContextStore} from '../store/datastores'\nimport {type OperationsAPI} from '../store/document/document-pair/operations/types'\nimport {useActiveWorkspace} from '../studio/activeWorkspaceMatcher/useActiveWorkspace'\nimport {getVersionId} from '../util/draftUtils'\nimport {useRecordDocumentHistoryEvent} from './useRecordDocumentHistoryEvent'\n\ninterface Options {\n api: OperationsAPI\n publishedDocId: string\n docTypeName: string\n version?: string\n}\n\n/**\n * Decorate operations API methods with Comlink history capture when relevant operations are executed.\n *\n * Event capture only occurs when Comlink is available.\n *\n * @internal\n */\nexport function useDocumentOperationWithComlinkHistory({\n api,\n publishedDocId,\n docTypeName,\n version,\n}: Options): OperationsAPI {\n const {activeWorkspace} = useActiveWorkspace()\n\n const {recordEvent} = useRecordDocumentHistoryEvent({\n resourceType: 'studio',\n documentId: version ? getVersionId(publishedDocId, version) : publishedDocId,\n documentType: docTypeName,\n resourceId: [activeWorkspace.projectId, activeWorkspace.dataset].join('.'),\n schemaName: activeWorkspace.name,\n })\n\n const renderingContextStore = useRenderingContextStore()\n // Kept synchronous: capabilities emit once at boot and gate whether\n // operations are decorated with comlink history capture; deferring only\n // delays the decoration.\n const capabilities = useSyncObservable(renderingContextStore.capabilities)\n\n // Used to prevent redundant `edited` events being recorded.\n const [hasRecordedEdit, setHasRecordedEdit] = useState<boolean>(false)\n\n // Record history for only the first edit to occur, to avoid inundating Dashboard history.\n const preRecordPatch = useCallback<PreRecordEvent>(\n (next) => {\n if (hasRecordedEdit) {\n return\n }\n next()\n setHasRecordedEdit(true)\n },\n [hasRecordedEdit],\n )\n\n const comlinkContext = useMemo(\n () => ({\n hasComlink: capabilities?.comlink,\n recordEvent,\n }),\n [capabilities?.comlink, recordEvent],\n )\n\n const withComlinkDelete = useMemo(\n () =>\n withComlinkEvent({\n ...comlinkContext,\n operationName: 'delete',\n comlinkEventType: 'deleted',\n }),\n [comlinkContext],\n )\n\n const withComlinkDel = useMemo(\n () =>\n withComlinkEvent({\n ...comlinkContext,\n operationName: 'del',\n comlinkEventType: 'deleted',\n }),\n [comlinkContext],\n )\n\n const withComlinkPatch = useMemo(\n () =>\n withComlinkEvent({\n ...comlinkContext,\n operationName: 'patch',\n comlinkEventType: 'edited',\n preRecordEvent: preRecordPatch,\n }),\n [comlinkContext, preRecordPatch],\n )\n\n return withComlinkDelete(withComlinkDel(withComlinkPatch(api)))\n}\n\ntype ComlinkEventType = Parameters<\n ReturnType<typeof useRecordDocumentHistoryEvent>['recordEvent']\n>[0]\n\ntype ExecuteParameters<OperationName extends keyof OperationsAPI> = Parameters<\n OperationsAPI[OperationName]['execute']\n>\n\ntype RecordEvent = ReturnType<typeof useRecordDocumentHistoryEvent>['recordEvent']\n\ntype PreRecordEvent = (next: () => void) => void\n\ninterface WithComlinkEventOptions<OperationName extends keyof OperationsAPI> {\n operationName: OperationName\n comlinkEventType: ComlinkEventType\n hasComlink?: boolean\n recordEvent: RecordEvent\n preRecordEvent?: PreRecordEvent\n}\n\n/**\n * Decorate the provided API method with Comlink history capture.\n */\nfunction withComlinkEvent<OperationName extends keyof OperationsAPI>({\n operationName,\n comlinkEventType,\n hasComlink,\n recordEvent,\n preRecordEvent = (next) => next(),\n}: WithComlinkEventOptions<OperationName>): (api: OperationsAPI) => OperationsAPI {\n return function (api) {\n if (!hasComlink) {\n return api\n }\n\n return {\n ...api,\n [operationName]: {\n ...api[operationName],\n execute: (...args: ExecuteParameters<OperationName>) => {\n const next = () => recordEvent(comlinkEventType)\n preRecordEvent(next)\n api[operationName].execute(...args)\n },\n },\n }\n }\n}\n","import {useMemo} from 'react'\n\nimport {normalizeDocumentPairTarget} from '../store/document/normalizeDocumentPairTarget'\nimport {type DocumentPairTarget} from '../store/document/types'\n\n/**\n * Returns a referentially stable {@link DocumentPairTarget} for the document pair APIs.\n *\n * Callers commonly build the target inline on every render (e.g. via `getPairTarget(...)`), so\n * keying a memo on the target object directly would recreate it every time — and resubscribing\n * `pair.editOperations` re-checks out the pair. This hook destructures the target into its\n * primitives and memoizes the object on them, so the returned reference only changes when the\n * target's contents change.\n *\n * A bare string is back-compat shorthand for a plain version target (its scope id, i.e. the\n * `<scopeId>` segment of `versions.<scopeId>.<groupId>`); `undefined` means the base\n * draft/published pair.\n *\n * @internal\n */\nexport function useMemoizedDocumentPairTarget(\n version: string | DocumentPairTarget | undefined,\n): DocumentPairTarget | undefined {\n const target = normalizeDocumentPairTarget(version)\n const kind = target?.kind\n const scopeId =\n target?.kind === 'version' || target?.kind === 'variant' ? target.scopeId : undefined\n const variantId =\n target?.kind === 'variant' || target?.kind === 'target-missing' ? target.variantId : undefined\n const allowCreate = target?.kind === 'variant' ? target.allowCreate : undefined\n\n return useMemo((): DocumentPairTarget | undefined => {\n switch (kind) {\n case 'version':\n return {kind: 'version', scopeId: scopeId!}\n case 'variant':\n // Preserve the input shape exactly: no `allowCreate: undefined` key when none was given.\n return allowCreate === undefined\n ? {kind: 'variant', scopeId: scopeId!, variantId: variantId!}\n : {kind: 'variant', scopeId: scopeId!, variantId: variantId!, allowCreate}\n case 'target-missing':\n // Preserve the input shape exactly: no `variantId: undefined` key when none was given.\n return variantId === undefined\n ? {kind: 'target-missing'}\n : {kind: 'target-missing', variantId}\n case 'unresolved':\n return {kind: 'unresolved'}\n default:\n return undefined\n }\n }, [kind, scopeId, variantId, allowCreate])\n}\n","import {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {useDocumentStore} from '../store/datastores'\nimport {type OperationsAPI} from '../store/document/document-pair/operations/types'\nimport {type DocumentPairTarget} from '../store/document/types'\nimport {useDocumentOperationWithComlinkHistory} from './useDocumentOperationWithComlinkHistory'\nimport {useMemoizedDocumentPairTarget} from './useMemoizedDocumentPairTarget'\n\n/**\n * @internal\n * `version` accepts either a plain version name (release/bundle) or a {@link DocumentPairTarget}\n * declaring the resolved target of the selected perspective/variant. With the guarded target\n * kinds (`unresolved`, `target-missing`) the returned operations are disabled and throw if\n * executed, instead of silently operating on the base draft/published pair.\n */\nexport function useDocumentOperation(\n publishedDocId: string,\n docTypeName: string,\n version?: string | DocumentPairTarget,\n): OperationsAPI {\n const documentStore = useDocumentStore()\n\n // A referentially stable target: a caller passing a fresh target object on every render must\n // not recreate the observable (which would resubscribe the pair).\n const target = useMemoizedDocumentPairTarget(version)\n\n const observable = useMemo(\n () => documentStore.pair.editOperations(publishedDocId, docTypeName, target),\n [docTypeName, documentStore.pair, publishedDocId, target],\n )\n\n /**\n * We know that since the observable has a startWith operator, it will always emit a value\n * and that's why the non-null assertion is used here\n *\n * Kept synchronous: the operations are imperative emitters bound to the\n * document id/type they were created for, so a deferred (stale) API could\n * execute an action against the previously viewed document after navigation.\n */\n const api = useSyncObservable(observable)!\n\n return useDocumentOperationWithComlinkHistory({\n api,\n docTypeName,\n publishedDocId,\n })\n}\n","import {type PerspectiveBundle} from '../perspective/types'\nimport {type DocumentPerspectiveState} from '../releases/hooks/useDocumentVersions'\nimport {type VersionInfoDocumentStub} from '../releases/store/types'\n\n/**\n * Finds the document version whose _system metadata matches the selected bundle and variant.\n *\n * `bundle` must be the canonical bundle id (`published`, `drafts` or a release id), matching\n * `_system.bundleId` exactly. For example, `bundle: 'published'` and `variant: undefined` matches\n * a version with no `bundleId` and `variant: null`.\n *\n * @internal\n */\nexport function getTargetDocument({\n bundle,\n documentVersions,\n variant,\n}: {\n variant: string | undefined\n bundle: PerspectiveBundle\n documentVersions: DocumentPerspectiveState['versions']\n}): VersionInfoDocumentStub | undefined {\n return documentVersions.find((version) => {\n const inBundle =\n bundle === 'published' ? !version._system.bundleId : version._system.bundleId === bundle\n const inVariant = variant ? version._system.variant?._ref === variant : !version._system.variant\n return inBundle && inVariant\n })\n}\n\n/**\n * Finds the variant-of-published sibling for a variant: the version stub carrying the same\n * `_system.variant` reference but no `_system.bundleId` (i.e. the published variant document).\n *\n * This is the document that publish-state gating must read for variant targets — the base\n * `published` document says nothing about whether the *variant* is published. `undefined` means\n * the variant has never been published.\n *\n * @internal\n */\nexport function getVariantPublishedSibling({\n documentVersions,\n variant,\n}: {\n variant: string\n documentVersions: DocumentPerspectiveState['versions']\n}): VersionInfoDocumentStub | undefined {\n return getTargetDocument({bundle: 'published', variant, documentVersions})\n}\n","import {type SystemVariant} from '../types'\n\ninterface VariantDeletedAction {\n type: 'VARIANT_DELETED'\n payload: {\n id: string\n }\n}\n\ninterface FetchSucceededAction {\n type: 'FETCH_SUCCEEDED'\n payload: SystemVariant[] | null\n}\ninterface VariantsSetAction {\n type: 'VARIANTS_SET'\n payload: SystemVariant[] | null\n}\n\ninterface LoadingStateChangedAction {\n type: 'LOADING_STATE_CHANGED'\n payload: {\n loading: boolean\n error: Error | undefined\n }\n}\n\nexport type VariantStoreAction =\n | VariantsSetAction\n | LoadingStateChangedAction\n | VariantDeletedAction\n | FetchSucceededAction\n\nexport interface VariantStoreState {\n variants: Map<string, SystemVariant>\n state: 'initialising' | 'loading' | 'loaded' | 'error'\n error?: Error\n}\n\nfunction createVariantsSet(variants: SystemVariant[] | null) {\n return (variants ?? []).reduce((acc, variant) => {\n acc.set(variant._id, variant)\n return acc\n }, new Map<string, SystemVariant>())\n}\n\nexport function variantStoreReducer(\n state: VariantStoreState,\n action: VariantStoreAction,\n): VariantStoreState {\n switch (action.type) {\n case 'LOADING_STATE_CHANGED': {\n return {\n ...state,\n state: action.payload.error ? 'error' : action.payload.loading ? 'loading' : 'loaded',\n error: action.payload.error,\n }\n }\n\n case 'VARIANTS_SET': {\n const variantsById = createVariantsSet(action.payload)\n\n return {\n ...state,\n variants: variantsById,\n }\n }\n case 'FETCH_SUCCEEDED': {\n const variantsById = createVariantsSet(action.payload)\n return {\n ...state,\n variants: variantsById,\n state: 'loaded',\n error: undefined,\n }\n }\n\n case 'VARIANT_DELETED': {\n const {id} = action.payload\n const restVariants = new Map(state.variants)\n restVariants.delete(id)\n\n return {\n ...state,\n variants: restVariants,\n }\n }\n\n default:\n return state\n }\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type Dispatch} from 'react'\nimport {catchError, concatWith, merge, type Observable, of, scan, shareReplay, Subject} from 'rxjs'\nimport {map, startWith} from 'rxjs/operators'\n\nimport {listenQuery} from '../../store/document/listenQuery'\nimport {VARIANT_DOCUMENTS_PATH, VARIANT_DOCUMENT_TYPE} from './constants'\nimport {variantStoreReducer, type VariantStoreAction, type VariantStoreState} from './reducer'\n\nconst SORT_FIELD = '_createdAt'\nconst SORT_ORDER = 'desc'\n// Newest variants first\nconst QUERY_SORT_ORDER = `order(${SORT_FIELD} ${SORT_ORDER})`\nconst QUERY_FILTER = `_type==\"${VARIANT_DOCUMENT_TYPE}\" && _id in path(\"${VARIANT_DOCUMENTS_PATH}.*\")`\nconst QUERY_PROJECTION = `{\n _id,\n _type,\n _rev,\n _createdAt,\n _updatedAt,\n name,\n conditions,\n \"priority\": coalesce(priority, 0),\n metadata,\n}`\n\nconst QUERY = `*[${QUERY_FILTER}] ${QUERY_PROJECTION} | ${QUERY_SORT_ORDER}`\n\nconst INITIAL_STATE: VariantStoreState = {\n variants: new Map(),\n state: 'initialising' as const,\n}\n\nexport interface VariantStore {\n state$: Observable<VariantStoreState>\n dispatch: Dispatch<VariantStoreAction>\n}\n\n/**\n * The variants store is initialised lazily when first subscribed to. Upon subscription, it will\n * fetch a list of variants and create a listener to keep the locally held state fresh.\n *\n * The store is not disposed of when all subscriptions are closed. After it has been initialised,\n * it will keep listening for the duration of the app's lifecycle. Subsequent subscriptions will be\n * given the latest state upon subscription.\n */\nexport function createVariantsStore(context: {\n client: SanityClient\n enabled: boolean\n}): VariantStore {\n const {client, enabled} = context\n\n if (!enabled) {\n const disabledState: VariantStoreState = {\n variants: new Map(),\n state: 'loaded' as const,\n }\n\n return {\n state$: of(disabledState),\n dispatch: () => {\n // noop\n },\n }\n }\n\n const dispatch$ = new Subject<VariantStoreAction>()\n\n function dispatch(action: VariantStoreAction): void {\n dispatch$.next(action)\n }\n\n const listFetch$ = of<VariantStoreAction>({\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: true,\n error: undefined,\n },\n }).pipe(\n concatWith(\n listenQuery(client, QUERY, {}, {tag: 'variants.listen'}).pipe(\n map((variants): VariantStoreAction => ({type: 'FETCH_SUCCEEDED', payload: variants})),\n ),\n ),\n\n catchError((error) =>\n of<VariantStoreAction>({\n type: 'LOADING_STATE_CHANGED',\n payload: {\n loading: false,\n error,\n },\n }),\n ),\n )\n\n const state$ = merge(listFetch$, dispatch$).pipe(\n scan((state, action) => variantStoreReducer(state, action), INITIAL_STATE),\n startWith(INITIAL_STATE),\n shareReplay(1),\n )\n\n return {\n state$,\n dispatch,\n }\n}\n","import {useMemo} from 'react'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useResourceCache} from '../../store/ResourceCacheProvider'\nimport {useWorkspace} from '../../studio/workspace'\nimport {VARIANTS_STUDIO_CLIENT_OPTIONS} from './constants'\nimport {createVariantsStore, type VariantStore} from './createVariantsStore'\n\n/** @internal */\nexport function useVariantsStore(): VariantStore {\n const workspace = useWorkspace()\n const variantsEnabled = Boolean(workspace.beta?.variants?.enabled)\n const resourceCache = useResourceCache()\n const studioClient = useClient(VARIANTS_STUDIO_CLIENT_OPTIONS)\n\n return useMemo(() => {\n const variantStore =\n resourceCache.get<VariantStore>({\n dependencies: [workspace],\n namespace: 'VariantsStore',\n }) ||\n createVariantsStore({\n client: studioClient,\n enabled: variantsEnabled,\n })\n\n resourceCache.set({\n dependencies: [workspace],\n namespace: 'VariantsStore',\n value: variantStore,\n })\n\n return variantStore\n }, [variantsEnabled, resourceCache, workspace, studioClient])\n}\n","import {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {type SystemVariant} from '../types'\nimport {useVariantsStore} from './useVariantsStore'\n\n/**\n * Gets all variants.\n * @internal\n */\nexport function useAllVariants(): {\n data: SystemVariant[]\n byId: Map<string, SystemVariant>\n error?: Error\n loading: boolean\n} {\n const {state$} = useVariantsStore()\n // Kept synchronous: variant resolution feeds `useTargetDocumentState`'s\n // target scope, so a deferred snapshot could bind the form checkout to the\n // wrong variant after navigation. Executable proof:\n // perspective/__tests__/deferralSafety.test.tsx.\n const {variants, error, state} = useSyncObservable(state$)!\n\n return useMemo(\n () => ({\n data: Array.from(variants.values()),\n byId: variants,\n error: error,\n loading: ['loading', 'initialising'].includes(state),\n }),\n [error, variants, state],\n )\n}\n","import {useMemo} from 'react'\n\nimport {type PerspectiveBundle} from '../perspective/types'\nimport {usePerspective} from '../perspective/usePerspective'\nimport {useDocumentVersions} from '../releases/hooks/useDocumentVersions'\nimport {type VersionInfoDocumentStub} from '../releases/store/types'\nimport {type DocumentPairTarget} from '../store/document/types'\nimport {getVersionFromId} from '../util/draftUtils'\nimport {getTargetDocument, getVariantPublishedSibling} from '../util/getTargetDocument'\nimport {useAllVariants} from '../variants/store/useAllVariants'\nimport {type SystemVariant} from '../variants/types'\n\n/**\n * The id and scope of a missing draft variant that can be created by typing: the id is known\n * ahead of creation because the variant-of-published sibling advertises it (`_system.draft`).\n *\n * @internal\n * @beta\n */\nexport interface CreatableTargetDocument {\n /** The full version id (`versions.<scopeId>.<groupId>`) the draft variant will occupy. */\n id: string\n /** The bundle segment of {@link CreatableTargetDocument.id}, for pair checkout. */\n scopeId: string\n}\n\n/**\n * The resolution state of the document targeted by the selected perspective (bundle) and variant.\n *\n * The union is shaped by what consumers must do, not just by what was observed:\n *\n * - `resolving` — a lookup (variant definitions or version stubs) is still in flight. Consumers\n * must not fall back to the base draft/published pair; treat the target as not ready.\n * - `ready` — resolution finished. `targetDocument` is the version stub matching the current\n * bundle (and variant, when one is selected); it is `undefined` only when no variant is\n * selected and no stub exists for the bundle, in which case base draft/published semantics\n * legitimately apply. `scopeId` is the bundle segment to thread into version-aware hooks\n * (release id for release stubs, opaque scope hash for variant stubs, `undefined` for the\n * base pair).\n * - `variant-missing` — a variant is selected but the document has no variant-scoped version\n * for the current bundle. When `creatableTarget` is set (drafts bundle, published variant\n * advertising its draft sibling id), the document is editable: typing creates the draft\n * variant at the advertised id, seeded from the published sibling. Otherwise consumers must\n * treat the document as read-only and offer creation. Never fall back to the base pair.\n * - `variant-definition-document-not-found` — the requested variant name matches no\n * `system.variant` definition. An error state, never silently treated as \"no variant\".\n *\n * @internal\n * @beta\n */\nexport type TargetDocumentState =\n | {status: 'resolving'}\n | {\n status: 'ready'\n targetDocument: VersionInfoDocumentStub | undefined\n scopeId: string | undefined\n /** The selected variant when the resolved target is a variant-scoped version. */\n variant: SystemVariant | undefined\n /**\n * The variant-of-published sibling stub (same `_system.variant`, no `_system.bundleId`).\n * Only set for variant targets; `undefined` means the variant has never been published.\n * Publish-state gating (already-published, unpublishable, discard copy) must read this\n * instead of the base `published` document.\n */\n publishedSibling: VersionInfoDocumentStub | undefined\n }\n | {\n status: 'variant-missing'\n variant: SystemVariant\n bundle: PerspectiveBundle\n /**\n * The variant-of-published sibling, when the variant is missing in the current bundle but\n * published. Lets consumers distinguish \"never existed\" from \"exists published, not in\n * this bundle\".\n */\n publishedSibling: VersionInfoDocumentStub | undefined\n /**\n * Present when the missing variant document can be created by typing: the drafts-bundle\n * variant of a published variant whose `_system.draft` weak ref advertises the (stable,\n * server-generated) id the draft will occupy. The pair is checked out at this id with\n * `allowCreate` declared to the store, and the display falls back to `publishedSibling`\n * until the document exists.\n */\n creatableTarget?: CreatableTargetDocument\n }\n | {status: 'variant-definition-document-not-found'; requestedVariantName: string}\n\nconst RESOLVING: TargetDocumentState = {status: 'resolving'}\n\n/**\n * Resolves the creatable draft variant for a missing target: only the drafts bundle qualifies\n * (release-scoped variants have no advertised draft refs yet, and the published bundle's missing\n * target *is* the sibling), and only when the variant-of-published sibling advertises\n * `_system.draft`. The id is server-advertised, never computed — this is what keeps the \"never\n * guess a variant scope id client-side\" invariant intact.\n */\nfunction getCreatableTarget(\n bundle: PerspectiveBundle,\n publishedSibling: VersionInfoDocumentStub | undefined,\n): CreatableTargetDocument | undefined {\n if (bundle !== 'drafts' || !publishedSibling) {\n return undefined\n }\n const draftId = publishedSibling._system.draft?._ref\n if (!draftId) {\n return undefined\n }\n const scopeId = getVersionFromId(draftId)\n if (!scopeId) {\n return undefined\n }\n return {id: draftId, scopeId}\n}\n\n/**\n * Returns the scope id to thread into version-aware hooks (`useEditState`,\n * `useDocumentOperation`, etc.) for a resolved target, or `undefined` when the target is not\n * ready or the base draft/published pair applies.\n *\n * A `variant-missing` state with a {@link CreatableTargetDocument} yields the creatable draft's\n * scope id: the pair is checked out at the advertised id from the beginning, so typing (and every\n * version-aware read: edit state, sync state, connection) addresses the document being created —\n * never the base pair, and never the published sibling.\n *\n * @internal\n * @beta\n */\nexport function getTargetScopeId(state: TargetDocumentState): string | undefined {\n if (state.status === 'ready') {\n return state.scopeId\n }\n if (state.status === 'variant-missing') {\n return state.creatableTarget?.scopeId\n }\n return undefined\n}\n\n/**\n * The creatable draft variant of a `variant-missing` state, or `undefined` for every other\n * state. Present when the missing target can be created by typing at a server-advertised id\n * (see {@link CreatableTargetDocument}); consumers use it to exempt the state from the\n * read-only/banner/footer gating that otherwise applies to unresolved variant targets.\n *\n * @internal\n * @beta\n */\nexport function getCreatableVariantTarget(\n state: TargetDocumentState,\n): CreatableTargetDocument | undefined {\n return state.status === 'variant-missing' ? state.creatableTarget : undefined\n}\n\n/**\n * Maps a {@link TargetDocumentState} to the `target` parameter of `useDocumentOperation` /\n * `pair.editOperations`, preserving the guarded states: `resolving` yields `unresolved`\n * (operations stay `NOT_READY`), and `variant-missing` / `variant-definition-document-not-found`\n * yield `target-missing` (operations disabled with `TARGET_NOT_FOUND`). Both throw if executed,\n * so operations can never silently fall back to the base draft/published pair.\n *\n * A `variant-missing` state with a {@link CreatableTargetDocument} yields a `variant` target with\n * `allowCreate`: the store keeps `patch`/`commit` enabled so typing creates the draft variant at\n * the advertised id, while publish/unpublish/discard stay disabled until the document exists.\n *\n * @internal\n * @beta\n */\nexport function getPairTarget(state: TargetDocumentState): DocumentPairTarget | string | undefined {\n switch (state.status) {\n case 'resolving':\n return {kind: 'unresolved'}\n case 'variant-missing':\n if (state.creatableTarget) {\n return {\n kind: 'variant',\n scopeId: state.creatableTarget.scopeId,\n variantId: state.variant._id,\n allowCreate: true,\n }\n }\n return {kind: 'target-missing', variantId: state.variant._id}\n case 'variant-definition-document-not-found':\n return {kind: 'target-missing'}\n case 'ready':\n if (state.variant) {\n // A resolved variant target always carries its scope id; treat a malformed stub without\n // one as missing rather than falling back to the base pair.\n return state.scopeId\n ? {kind: 'variant', scopeId: state.scopeId, variantId: state.variant._id}\n : {kind: 'target-missing', variantId: state.variant._id}\n }\n return state.scopeId\n default:\n return undefined\n }\n}\n\n/**\n * Pure resolution logic for {@link useTargetDocumentState}, extracted for testability.\n *\n * @internal\n */\nexport function getTargetDocumentState(options: {\n bundle: PerspectiveBundle\n selectedVariant: SystemVariant | undefined\n selectedVariantName: string | undefined\n variantsLoading: boolean\n versions: VersionInfoDocumentStub[]\n versionsLoading: boolean\n}): TargetDocumentState {\n const {bundle, selectedVariant, selectedVariantName, variantsLoading, versions, versionsLoading} =\n options\n\n if (!selectedVariantName) {\n if (versionsLoading) {\n return RESOLVING\n }\n const targetDocument = getTargetDocument({\n bundle,\n variant: undefined,\n documentVersions: versions,\n })\n return {\n status: 'ready',\n targetDocument,\n scopeId: targetDocument?._system.scopeId ?? undefined,\n variant: undefined,\n publishedSibling: undefined,\n }\n }\n\n if (variantsLoading) {\n return RESOLVING\n }\n\n if (!selectedVariant) {\n return {\n status: 'variant-definition-document-not-found',\n requestedVariantName: selectedVariantName,\n }\n }\n\n if (versionsLoading) {\n return RESOLVING\n }\n\n const targetDocument = getTargetDocument({\n bundle,\n variant: selectedVariant._id,\n documentVersions: versions,\n })\n\n const publishedSibling = getVariantPublishedSibling({\n variant: selectedVariant._id,\n documentVersions: versions,\n })\n\n if (!targetDocument) {\n return {\n status: 'variant-missing',\n variant: selectedVariant,\n bundle,\n publishedSibling,\n creatableTarget: getCreatableTarget(bundle, publishedSibling),\n }\n }\n\n return {\n status: 'ready',\n targetDocument,\n scopeId: targetDocument._system.scopeId ?? undefined,\n variant: selectedVariant,\n publishedSibling,\n }\n}\n\n/**\n * Resolves the document targeted by the selected perspective and variant for a document group,\n * as an explicit {@link TargetDocumentState}.\n *\n * Unlike a plain \"target document or undefined\" lookup, the returned state distinguishes the\n * in-flight lookups (`resolving`), the definitive absence of a variant-scoped version\n * (`variant-missing`), and an invalid variant selection\n * (`variant-definition-document-not-found`) from the legitimate base draft/published fallback\n * (`ready` without a target document). Consumers must switch on `status` instead of treating\n * `undefined` as \"no variant\".\n *\n * @internal\n * @beta\n */\nexport function useTargetDocumentState(documentGroupId: string): TargetDocumentState {\n const {versions, loading: versionsLoading} = useDocumentVersions({documentId: documentGroupId})\n const {bundle, selectedVariant, selectedVariantName} = usePerspective()\n const {loading: variantsLoading} = useAllVariants()\n\n return useMemo(\n () =>\n getTargetDocumentState({\n bundle,\n selectedVariant,\n selectedVariantName,\n variantsLoading,\n versions,\n versionsLoading,\n }),\n [bundle, selectedVariant, selectedVariantName, variantsLoading, versions, versionsLoading],\n )\n}\n","import {type SanityClient} from '@sanity/client'\nimport {type SanityDocument, type Schema, type SchemaType} from '@sanity/types'\nimport {useMemo} from 'react'\nimport {combineLatest, type Observable, of} from 'rxjs'\nimport {map, shareReplay, switchMap} from 'rxjs/operators'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useSchema} from '../../hooks/useSchema'\nimport {DEFAULT_STUDIO_CLIENT_OPTIONS} from '../../studioClient'\nimport {createHookFromObservableFactory} from '../../util/createHookFromObservableFactory'\nimport {getDraftId, getPublishedId, getIdPair} from '../../util/draftUtils'\nimport {type PartialExcept} from '../../util/PartialExcept'\nimport {useGrantsStore} from '../datastores'\nimport {snapshotPair} from '../document/document-pair/snapshotPair'\nimport {type DocumentStoreExtraOptions} from '../document/getPairListener'\nimport {memoize} from '../document/utils/createMemoizer'\nimport {useCurrentUser} from '../user/hooks'\nimport {type GrantsStore, type PermissionCheckResult} from './types'\n\nfunction shareLatestWithRefCount<T>() {\n return shareReplay<T>({bufferSize: 1, refCount: true})\n}\n\nfunction getSchemaType(schema: Schema, typeName: string): SchemaType {\n const type = schema.get(typeName)\n\n if (!type) {\n throw new Error(`No such schema type: ${typeName}`)\n }\n\n return type\n}\n\ninterface PairPermissionsOptions {\n grantsStore: GrantsStore\n permission: DocumentPermission\n draft: SanityDocument | null\n version: SanityDocument | null\n published: SanityDocument | null\n liveEdit: boolean\n}\n\nfunction getPairPermissions({\n grantsStore,\n permission,\n draft,\n version,\n published,\n liveEdit,\n}: PairPermissionsOptions): Array<[string, Observable<PermissionCheckResult>]> {\n // this was introduced because we ran into a bug where a user with publish\n // access was marked as not allowed to duplicate a document unless it had a\n // draft variant. this would happen in non-live edit cases where the document\n // pair only had a published variant with the draft variant being null.\n //\n // note: this should _not_ be used if the draft and published versions should\n // be considered separately/explicitly in the permissions.\n const effectiveVersion = version || draft || published\n const effectiveVersionType =\n effectiveVersion === version ? version : effectiveVersion === draft ? 'draft' : 'published'\n\n const {checkDocumentPermission} = grantsStore\n\n switch (permission) {\n case 'delete': {\n if (liveEdit) {\n return [\n ['delete published document (live-edit)', checkDocumentPermission('update', published)],\n ]\n }\n\n return [\n ['delete draft document', checkDocumentPermission('update', draft)],\n ['delete published document', checkDocumentPermission('update', published)],\n ]\n }\n\n case 'discardDraft': {\n if (liveEdit) return []\n\n return [['delete draft document', checkDocumentPermission('update', draft)]]\n }\n\n case 'discardVersion': {\n if (liveEdit) return []\n\n return [['delete version', checkDocumentPermission('update', version || null)]]\n }\n\n case 'publish': {\n if (liveEdit) return []\n\n return [\n // precondition\n [\n 'update published document at its current state',\n checkDocumentPermission('update', published),\n ],\n\n // post condition\n ['delete draft document', checkDocumentPermission('update', draft)],\n [\n 'create published document from draft',\n checkDocumentPermission('create', draft && {...draft, _id: getPublishedId(draft._id)}),\n ],\n ]\n }\n\n case 'unpublish': {\n if (liveEdit) return []\n\n return [\n // precondition\n ['update draft document at its current state', checkDocumentPermission('create', draft)],\n\n // post condition\n ['delete published document', checkDocumentPermission('update', published)],\n [\n 'create draft document from published version',\n checkDocumentPermission(\n 'create',\n published && {...published, _id: getDraftId(published._id)},\n ),\n ],\n ]\n }\n\n case 'update': {\n if (liveEdit) {\n return [\n ['update published document (live-edit)', checkDocumentPermission('update', published)],\n ]\n }\n\n return [\n [\n `update ${effectiveVersionType} document`,\n checkDocumentPermission('update', effectiveVersion),\n ],\n ]\n }\n\n case 'duplicate': {\n if (liveEdit) {\n return [\n [\n 'create new published document from existing document (live-edit)',\n checkDocumentPermission('create', {...published, _id: 'dummy-id'}),\n ],\n ]\n }\n\n return [\n [\n `create new draft document from existing ${effectiveVersionType} document`,\n checkDocumentPermission('create', {...effectiveVersion, _id: getDraftId('dummy-id')}),\n ],\n ]\n }\n\n default: {\n throw new Error(`Could not match permission: ${permission}`)\n }\n }\n}\n\n/** @internal */\nexport type DocumentPermission =\n | 'delete'\n | 'discardDraft'\n | 'discardVersion'\n | 'publish'\n | 'unpublish'\n | 'update'\n | 'duplicate'\n\n/** @internal */\nexport interface DocumentPairPermissionsOptions {\n client: SanityClient\n schema: Schema\n grantsStore: GrantsStore\n id: string\n type: string\n version?: string\n permission: DocumentPermission\n /**\n * Identity of the current user. Included in the memoization key so that an\n * in-place user switch (same project, no reload) does not replay a previous\n * user's grants from the module-level memo cache.\n */\n userId?: string\n /**\n * @deprecated Does nothing. Preserved to avoid breaking changes.\n * Will be removed in the next major version.\n */\n serverActionsEnabled?: Observable<boolean>\n pairListenerOptions?: DocumentStoreExtraOptions\n}\n\n/**\n * The observable version of `useDocumentPairPermissions`\n *\n * @see useDocumentPairPermissions\n *\n * @internal\n */\nfunction getDocumentPairPermissionsUncached({\n client,\n grantsStore,\n schema,\n id,\n permission,\n type,\n version: v,\n pairListenerOptions,\n}: DocumentPairPermissionsOptions): Observable<PermissionCheckResult> {\n // this case was added to fix a crash that would occur if the `schemaType` was\n // omitted from `S.documentList()`\n //\n // see `resolveTypeForDocument` which returns `'*'` if no type is provided\n // https://github.com/sanity-io/sanity/blob/4d49b83a987d5097064d567f75d21b268a410cbf/packages/%40sanity/base/src/datastores/document/resolveTypeForDocument.ts#L7\n if (type === '*') {\n return of({granted: false, reason: 'Type specified was `*`'})\n }\n\n const liveEdit = Boolean(getSchemaType(schema, type).liveEdit)\n\n return snapshotPair(\n client,\n getIdPair(id, {version: v}),\n type,\n undefined,\n pairListenerOptions,\n ).pipe(\n switchMap((pair) =>\n combineLatest([\n pair.draft.snapshots$,\n pair.published.snapshots$,\n pair.version?.snapshots$ || of(null),\n ]).pipe(map(([draft, published, version]) => ({draft, published, version}))),\n ),\n switchMap(({draft, published, version}) => {\n const pairPermissions = getPairPermissions({\n grantsStore,\n permission,\n draft,\n version,\n published,\n liveEdit,\n }).map(([label, observable]) =>\n observable.pipe(\n map(({granted, reason}) => ({\n granted,\n reason: granted ? '' : `not allowed to ${label}: ${reason}`,\n label,\n permission,\n })),\n ),\n )\n\n if (!pairPermissions.length) return of({granted: true, reason: ''})\n\n return combineLatest(pairPermissions).pipe(\n map((permissionResults) => {\n const granted = permissionResults.every((permissionResult) => permissionResult.granted)\n const reason = granted\n ? ''\n : `Unable to ${permission}:\\n\\t${permissionResults\n .filter((permissionResult) => !permissionResult.granted)\n .map((permissionResult) => permissionResult.reason)\n .join('\\n\\t')}`\n\n return {granted, reason}\n }),\n )\n }),\n )\n}\n\nexport const getDocumentPairPermissions = memoize(\n (options: DocumentPairPermissionsOptions): Observable<PermissionCheckResult> =>\n getDocumentPairPermissionsUncached(options).pipe(shareLatestWithRefCount()),\n ({\n client,\n schema,\n id,\n type,\n version,\n permission,\n userId,\n }: DocumentPairPermissionsOptions): string => {\n const {dataset = '', projectId = ''} = client.config()\n // `liveEdit` is derived from the schema and branches the resulting permission\n // observable, so it must be part of the key: workspaces sharing a\n // project/dataset can define the same `type` with a different `liveEdit`.\n const liveEdit = type === '*' ? false : Boolean(schema.get(type)?.liveEdit)\n // `id` is normalized to its published id because the underlying chain reduces\n // (id, version) to `getIdPair(id, {version})`, a pure function of\n // (getPublishedId(id), version). The raw `version` string is kept as-is;\n // never call getIdPair here (it throws on version 'drafts'|'published').\n return [\n dataset,\n projectId,\n getPublishedId(id),\n version ?? '',\n userId ?? '',\n type,\n permission,\n liveEdit,\n ].join('-')\n },\n)\n\n/**\n * Gets document pair permissions based on a document ID and a type.\n *\n * This permissions API is a high-level permissions API that is draft-model\n * aware. In order to determine whether or not the user has the given\n * permission, both the draft and published documents are pulled and run through\n * all of the user's grants. If any pre or post conditions fail a permissions\n * checks, the operations will not be granted.\n *\n * The operations this hook accepts are only relevant to document pairs. E.g.\n * `'create'` is not included as an operation because it's not possible to tell\n * if a document can be created by only using the initial ID and type because an\n * initial template value may not have a matching grant (e.g. locked-document\n * pattern `!locked`). In contrast, the operation `'duplicate'` is supported\n * because the draft value of the document can be live queried and checked for\n * matching grants.\n *\n * Note: for live-edit documents, non-applicable operations (e.g. publish) will\n * return as true.\n *\n * @see useDocumentValuePermissions\n *\n * @internal\n */\nexport const useDocumentPairPermissionsFromHookFactory = createHookFromObservableFactory(\n getDocumentPairPermissions,\n)\n\n/** @internal */\nexport function useDocumentPairPermissions({\n id,\n type,\n version,\n permission,\n client: overrideClient,\n schema: overrideSchema,\n grantsStore: overrideGrantsStore,\n pairListenerOptions,\n}: PartialExcept<DocumentPairPermissionsOptions, 'id' | 'type' | 'permission'>): ReturnType<\n typeof useDocumentPairPermissionsFromHookFactory\n> {\n const defaultClient = useClient(DEFAULT_STUDIO_CLIENT_OPTIONS)\n const defaultSchema = useSchema()\n const defaultGrantsStore = useGrantsStore()\n const currentUser = useCurrentUser()\n\n const client = useMemo(() => overrideClient || defaultClient, [defaultClient, overrideClient])\n const schema = useMemo(() => overrideSchema || defaultSchema, [defaultSchema, overrideSchema])\n const grantsStore = useMemo(\n () => overrideGrantsStore || defaultGrantsStore,\n [defaultGrantsStore, overrideGrantsStore],\n )\n const userId = currentUser?.id\n\n return useDocumentPairPermissionsFromHookFactory(\n useMemo(\n () => ({\n client,\n schema,\n grantsStore,\n id,\n permission,\n type,\n pairListenerOptions,\n version,\n userId,\n }),\n [client, schema, grantsStore, id, permission, type, pairListenerOptions, version, userId],\n ),\n )\n}\n","import {RELEASE_DOCUMENTS_PATH} from '../store/constants'\n\nexport function getReleaseDocumentIdFromReleaseId(name: string) {\n return `${RELEASE_DOCUMENTS_PATH}.${name}`\n}\n","import {useContext} from 'react'\nimport {ReleasesUpsellContext} from 'sanity/_singletons'\n\nimport {type ReleasesUpsellContextValue} from './types'\n\n/**\n * @beta\n * @hidden\n */\nexport function useReleasesUpsell(): ReleasesUpsellContextValue {\n const value = useContext(ReleasesUpsellContext)\n\n if (!value) return FALLBACK_CONTEXT_VALUE\n\n return value\n}\n\nconst FALLBACK_CONTEXT_VALUE = {\n upsellDialogOpen: false,\n mode: 'default' as const,\n onReleaseLimitReached: () => null,\n guardWithReleaseLimitUpsell: async () => undefined,\n handleOpenDialog: () => null,\n upsellData: null,\n telemetryLogs: {\n dialogSecondaryClicked: () => null,\n dialogPrimaryClicked: () => null,\n panelViewed: () => null,\n panelDismissed: () => null,\n panelPrimaryClicked: () => null,\n panelSecondaryClicked: () => null,\n },\n} satisfies ReleasesUpsellContextValue\n","type ErrorWithDetails = {details?: {type?: string}}\n\nexport const isErrorWithDetails = (error: unknown): error is ErrorWithDetails =>\n typeof error === 'object' &&\n error !== null &&\n 'details' in error &&\n typeof (error as {details: unknown}).details === 'object'\n","import {isErrorWithDetails} from '../../error/types/isErrorWithDetails'\n\ntype ReleaseLimitError = {details: {type: 'releaseLimitExceededError'; limit: number}}\n\nexport const isReleaseLimitError = (error: unknown): error is ReleaseLimitError =>\n isErrorWithDetails(error) && error.details?.type === 'releaseLimitExceededError'\n","import {\n type BaseActionOptions,\n type CreateVersionAction,\n type DiscardVersionAction,\n type EditableReleaseDocument,\n type IdentifiedSanityDocumentStub,\n type ReleaseDocument,\n type SanityClient,\n type SingleActionResult,\n} from '@sanity/client'\n\nimport {getDraftId, getPublishedId, getVersionFromId, getVersionId} from '../../util/draftUtils'\nimport {type ReleasesUpsellContextValue} from '../contexts/upsell/types'\nimport {type RevertDocument} from '../tool/components/releaseCTAButtons/ReleaseRevertButton/useDocumentRevertStates'\nimport {getReleaseIdFromReleaseDocumentId} from '../util/getReleaseIdFromReleaseDocumentId'\nimport {isReleaseLimitError} from './isReleaseLimitError'\n\nexport interface ReleaseOperationsStore {\n publishRelease: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n discardDrafts: (\n documentIds: string[],\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult | undefined>\n schedule: (releaseId: string, date: Date, opts?: BaseActionOptions) => Promise<SingleActionResult>\n unschedule: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n archive: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n unarchive: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n updateRelease: (\n release: EditableReleaseDocument,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n createRelease: (\n release: EditableReleaseDocument,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n deleteRelease: (releaseId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n revertRelease: (\n revertReleaseId: string,\n documents: RevertDocument[],\n releaseMetadata: ReleaseDocument['metadata'],\n revertType: 'staged' | 'immediate',\n ) => Promise<void>\n duplicateRelease: (\n releaseDocumentId: string,\n releaseMetadata: ReleaseDocument['metadata'],\n releaseDocuments?: IdentifiedSanityDocumentStub[],\n ) => Promise<void>\n createVersion: (\n releaseId: string,\n documentId: string,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n discardVersion: (\n releaseId: string,\n documentId: string,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n unpublishVersion: (documentId: string, opts?: BaseActionOptions) => Promise<SingleActionResult>\n revertUnpublishVersion: (\n documentId: string,\n opts?: BaseActionOptions,\n ) => Promise<SingleActionResult>\n}\n\nexport function createReleaseOperationsStore(options: {\n client: SanityClient\n onReleaseLimitReached: ReleasesUpsellContextValue['onReleaseLimitReached']\n}): ReleaseOperationsStore {\n const {client, onReleaseLimitReached} = options\n\n const handleReleaseLimitError = (\n action: Promise<SingleActionResult>,\n opts?: {dryRun?: boolean},\n ) =>\n action.catch((error) => {\n // if dryRunning then essentially this is a silent request\n // so don't want to create disruptive upsell because of limit\n if (!opts?.dryRun && isReleaseLimitError(error)) {\n // free accounts do not return limit, 0 is implied\n onReleaseLimitReached(error.details.limit || 0)\n }\n\n throw error\n })\n\n const handleCreateRelease = (release: EditableReleaseDocument, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.create(\n {releaseId: getReleaseIdFromReleaseDocumentId(release._id), metadata: release.metadata},\n opts,\n ),\n opts,\n )\n\n const handleUpdateRelease = async (\n release: EditableReleaseDocument,\n opts?: BaseActionOptions,\n ) => {\n const releaseId = getReleaseIdFromReleaseDocumentId(release._id)\n\n const unsetKeys = Object.entries(release)\n .filter(([_, value]) => value === undefined)\n .map(([key]) => `metadata.${key}`)\n\n return handleReleaseLimitError(\n client.releases.edit(\n {\n releaseId,\n patch: {\n set: {metadata: release.metadata},\n unset: unsetKeys,\n },\n },\n opts,\n ),\n opts,\n )\n }\n\n const handlePublishRelease = (releaseId: string, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.publish({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts),\n opts,\n )\n\n /**\n * Discards the draft versions of the given documents, if any exist. Used after publishing a\n * release to bring the drafts in line with the newly published content (\"release to drafts\").\n */\n const handleDiscardDrafts = async (documentIds: string[], opts?: BaseActionOptions) => {\n const draftIds = [...new Set(documentIds.map((documentId) => getDraftId(documentId)))]\n\n if (draftIds.length === 0) return undefined\n\n // only discard drafts that still exist, so the transaction doesn't fail on documents whose\n // drafts were removed after the draft ids were resolved\n const existingDraftIds = await client.fetch<string[]>(\n '*[_id in $draftIds]._id',\n {draftIds},\n {perspective: 'raw', tag: 'release.discard-drafts'},\n )\n\n if (existingDraftIds.length === 0) return undefined\n\n const discardDraftActions: DiscardVersionAction[] = existingDraftIds.map((draftId) => ({\n actionType: 'sanity.action.document.version.discard',\n versionId: draftId,\n }))\n\n return client.action(discardDraftActions, {tag: 'release.discard-drafts', ...opts})\n }\n\n const handleScheduleRelease = (releaseId: string, publishAt: Date, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.schedule(\n {\n releaseId: getReleaseIdFromReleaseDocumentId(releaseId),\n publishAt: publishAt.toISOString(),\n },\n opts,\n ),\n opts,\n )\n\n const handleUnscheduleRelease = (releaseId: string, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.unschedule({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts),\n opts,\n )\n\n const handleArchiveRelease = (releaseId: string, opts?: BaseActionOptions) =>\n client.releases.archive({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts)\n\n const handleUnarchiveRelease = (releaseId: string, opts?: BaseActionOptions) =>\n handleReleaseLimitError(\n client.releases.unarchive({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts),\n opts,\n )\n\n const handleDeleteRelease = (releaseId: string, opts?: BaseActionOptions) =>\n client.releases.delete({releaseId: getReleaseIdFromReleaseDocumentId(releaseId)}, opts)\n\n const handleCreateVersion = async (\n releaseId: string,\n documentId: string,\n opts?: BaseActionOptions,\n ) => {\n // fetch original document to get the revision id\n const document = await client.getDocument(documentId)\n\n if (!document) {\n throw new Error(`Document with id ${documentId} not found`)\n }\n\n return client.createVersion(\n {\n baseId: documentId,\n ifBaseRevisionId: document?._rev,\n publishedId: getPublishedId(documentId),\n releaseId,\n },\n opts,\n )\n }\n\n const handleDiscardVersion = (releaseId: string, documentId: string, opts?: BaseActionOptions) =>\n client.discardVersion({releaseId, publishedId: getPublishedId(documentId)}, false, opts)\n\n const handleUnpublishVersion = (documentId: string, opts?: BaseActionOptions) => {\n const releaseId = getVersionFromId(documentId)\n // in cases where the document is not part of a release, or document is `drafts.`\n // the releaseId will be undefined\n // cannot unpublish in this case\n if (!releaseId) {\n throw new Error(`Release ID not found for document ${documentId}`)\n }\n\n return client.unpublishVersion({releaseId, publishedId: getPublishedId(documentId)}, opts)\n }\n\n const handleRevertRelease = async (\n revertReleaseId: string,\n releaseDocuments: RevertDocument[],\n releaseMetadata: ReleaseDocument['metadata'],\n revertType: 'staged' | 'immediate',\n ) => {\n await handleCreateRelease({\n _id: revertReleaseId,\n metadata: {\n title: releaseMetadata.title,\n description: releaseMetadata.description,\n releaseType: 'asap',\n cardinality: 'many',\n },\n })\n const versionId = getReleaseIdFromReleaseDocumentId(revertReleaseId)\n const newVersionDocumentActions: CreateVersionAction[] = releaseDocuments.map(\n (releaseDocument) => ({\n actionType: 'sanity.action.document.version.create',\n document: {...releaseDocument, _id: getVersionId(releaseDocument._id, versionId)},\n publishedId: getPublishedId(releaseDocument._id),\n }),\n )\n await client.action(newVersionDocumentActions)\n\n if (revertType === 'immediate') {\n await handlePublishRelease(revertReleaseId)\n }\n }\n\n const handleDuplicateRelease = async (\n releaseDocumentId: string,\n releaseMetadata: ReleaseDocument['metadata'],\n releaseDocuments?: IdentifiedSanityDocumentStub[],\n ) => {\n await handleCreateRelease({\n _id: releaseDocumentId,\n metadata: releaseMetadata,\n })\n\n if (releaseDocuments) {\n const versionId = getReleaseIdFromReleaseDocumentId(releaseDocumentId)\n const duplicateVersionDocumentActions: CreateVersionAction[] = releaseDocuments.map(\n (releaseDocument) => ({\n actionType: 'sanity.action.document.version.create',\n baseId: releaseDocument._id,\n publishedId: getPublishedId(releaseDocument._id),\n versionId: getVersionId(releaseDocument._id, versionId),\n }),\n )\n await client.action(duplicateVersionDocumentActions, {\n tag: 'duplicate-release.create-members',\n })\n }\n }\n\n const handleRevertUnpublishVersion = async (documentId: string, opts?: BaseActionOptions) => {\n return await client.action(\n {\n actionType: 'sanity.action.document.edit',\n draftId: documentId,\n publishedId: getPublishedId(documentId),\n patch: {\n unset: ['_system.delete'],\n },\n },\n opts,\n )\n }\n\n return {\n archive: handleArchiveRelease,\n unarchive: handleUnarchiveRelease,\n schedule: handleScheduleRelease,\n unschedule: handleUnscheduleRelease,\n createRelease: handleCreateRelease,\n updateRelease: handleUpdateRelease,\n publishRelease: handlePublishRelease,\n discardDrafts: handleDiscardDrafts,\n deleteRelease: handleDeleteRelease,\n revertRelease: handleRevertRelease,\n duplicateRelease: handleDuplicateRelease,\n createVersion: handleCreateVersion,\n discardVersion: handleDiscardVersion,\n unpublishVersion: handleUnpublishVersion,\n revertUnpublishVersion: handleRevertUnpublishVersion,\n }\n}\n","import {useMemo} from 'react'\n\nimport {useClient} from '../../hooks/useClient'\nimport {useReleasesUpsell} from '../contexts/upsell/useReleasesUpsell'\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../util/releasesClient'\nimport {createReleaseOperationsStore} from './createReleaseOperationStore'\n\n/**\n * @internal\n */\nexport function useReleaseOperations() {\n const studioClient = useClient(RELEASES_STUDIO_CLIENT_OPTIONS)\n const {onReleaseLimitReached} = useReleasesUpsell()\n return useMemo(\n () =>\n createReleaseOperationsStore({\n client: studioClient,\n onReleaseLimitReached,\n }),\n [onReleaseLimitReached, studioClient],\n )\n}\n","import {type ReleaseDocument} from '@sanity/client'\nimport {useMemo} from 'react'\nimport {useSyncObservable} from 'react-rx'\n\nimport {sortReleases} from '../hooks/utils'\nimport {useReleasesStore} from './useReleasesStore'\n\n/**\n * Gets all releases including archived and published releases\n * @internal\n */\nexport function useAllReleases(): {\n data: ReleaseDocument[]\n error?: Error\n loading: boolean\n map: Map<string, ReleaseDocument>\n} {\n const {state$} = useReleasesStore()\n // Kept synchronous: release lists feed perspective/version identity\n // resolution alongside live perspective state, so a deferred snapshot could\n // pair a stale release list with the current selection — or disagree with\n // the synchronous `useActiveReleases` read of the same store. Executable\n // proof: perspective/__tests__/deferralSafety.test.tsx.\n const {releases, error, state} = useSyncObservable(state$)!\n\n return useMemo(\n () => ({\n data: sortReleases(Array.from(releases.values())),\n map: releases,\n error: error,\n loading: ['loading', 'initialising'].includes(state),\n }),\n [error, releases, state],\n )\n}\n","/**\n * Schedule the provided callback using `scheduler.yield`, if it's available.\n * This allows long-running work to be broken up so the browser stays responsive.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Scheduler/yield\n * Otherwise, call it immediately.\n */\nexport function schedulerYield<Result>(\n promise: () => Promise<Result>,\n): Promise<Result> | Promise<void> {\n if ('scheduler' in window && typeof window.scheduler?.yield === 'function') {\n return window.scheduler.yield()\n }\n return promise()\n}\n","import {\n type CurrentUser,\n isValidationErrorMarker,\n type SanityDocument,\n type Schema,\n} from '@sanity/types'\nimport {uuid} from '@sanity/uuid'\nimport {useMemo} from 'react'\nimport {useObservable} from 'react-rx'\nimport {combineLatest, from, type Observable, of} from 'rxjs'\nimport {mergeMapArray} from 'rxjs-mergemap-array'\nimport {catchError, delay, filter, finalize, map, shareReplay, switchMap} from 'rxjs/operators'\n\nimport {useSchema} from '../../../hooks/useSchema'\nimport {type LocaleSource} from '../../../i18n/types'\nimport {type DocumentPreviewStore} from '../../../preview/documentPreviewStore'\nimport {useDocumentPreviewStore} from '../../../store/datastores'\nimport {useSource} from '../../../studio/source'\nimport {schedulerYield} from '../../../util/schedulerYield'\nimport {validateDocumentWithReferences, type ValidationStatus} from '../../../validation'\nimport {RELEASES_STUDIO_CLIENT_OPTIONS} from '../../util/releasesClient'\n\nconst bundleDocumentsCache: Record<string, BundleDocumentsObservableResult> = Object.create(null)\n\n/** @internal */\nexport function resetBundleDocumentsCacheForTests(): void {\n for (const key of Object.keys(bundleDocumentsCache)) {\n delete bundleDocumentsCache[key]\n }\n}\n\nexport interface DocumentValidationStatus extends ValidationStatus {\n hasError: boolean\n}\n\n/**\n * A document in a bundle (a set of documents resolved by a GROQ filter, e.g. a release or a\n * variant), along with its validation status. Shared by the release- and variant-specific types.\n *\n * @public\n */\nexport interface BundleDocument {\n memoKey: string\n isPending?: boolean\n document: SanityDocument & {publishedDocumentExists: boolean; draftDocumentExists?: boolean}\n validation: DocumentValidationStatus\n}\n\nexport type BundleDocumentsObservableResult = Observable<{\n loading: boolean\n results: BundleDocument[]\n error: Error | null\n}>\n\ninterface BundleDocumentsObservableOptions {\n schema: Schema\n documentPreviewStore: DocumentPreviewStore\n i18n: LocaleSource\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n getClient: ReturnType<typeof useSource>['getClient']\n currentUser?: Omit<CurrentUser, 'role'> | null\n /**\n * The GROQ filter used to resolve the set of documents to fetch,\n * e.g. `sanity::partOfRelease($releaseId)` or `sanity::partOfVariant($variantId)`.\n */\n groqFilter: string\n /**\n * The params referenced by `groqFilter`, e.g. `{releaseId}` or `{variantId}`.\n */\n params: Record<string, unknown>\n /**\n * Returns `true` for documents that should not be validated (validation is short-circuited).\n * Used, for example, to skip documents that are going to be unpublished in a release.\n */\n skipValidation?: (document: SanityDocument) => boolean\n}\n\nconst buildBundleDocumentsObservable = ({\n schema,\n documentPreviewStore,\n i18n,\n getClient,\n currentUser,\n groqFilter,\n params,\n skipValidation,\n}: Omit<BundleDocumentsObservableOptions, 'cacheKey'>): BundleDocumentsObservableResult => {\n // Helper function to create validation observable\n const createValidationObservable = (ctx: any, document: SanityDocument) => {\n if (skipValidation?.(document)) {\n return of({\n isValidating: false,\n validation: [],\n revision: document._rev,\n hasError: false,\n } satisfies DocumentValidationStatus)\n }\n\n // scheduledYield is used to provide some control over the main thread\n return from(schedulerYield(() => Promise.resolve())).pipe(\n switchMap(() =>\n validateDocumentWithReferences(ctx, of(document), false).pipe(\n map((validationStatus) => ({\n ...validationStatus,\n hasError: validationStatus.validation.some((marker) => isValidationErrorMarker(marker)),\n })),\n ),\n ),\n )\n }\n\n // Helper function to process a single document and set up the associated validation observable\n const processDocument = (id: string) => {\n const ctx = {\n observeDocument: documentPreviewStore.unstable_observeDocument,\n observeDocumentPairAvailability:\n documentPreviewStore.unstable_observeDocumentPairAvailability,\n i18n,\n getClient,\n schema,\n currentUser,\n }\n\n const document$ = documentPreviewStore\n .unstable_observeDocument(id, {\n apiVersion: RELEASES_STUDIO_CLIENT_OPTIONS.apiVersion,\n })\n .pipe(\n filter(Boolean),\n switchMap((doc) => {\n return documentPreviewStore.unstable_observeDocumentPairAvailability(id).pipe(\n map((availability) => ({\n ...doc,\n publishedDocumentExists: availability.published.available,\n draftDocumentExists: availability.draft.available,\n })),\n )\n }),\n )\n\n const validation$ = document$.pipe(\n switchMap((document) => createValidationObservable(ctx, document)),\n )\n\n return combineLatest([document$, validation$]).pipe(\n map(([document, validation]) => ({\n document,\n validation,\n memoKey: uuid(),\n })),\n )\n }\n\n // Helper function to process a group of document Ids\n // Used to process documents as to not overwhelm the main thread\n const processDocumentIdsGroup = (documentIdsGroup: string[], groupIndex: number) => {\n // On the first batch there is no delay\n const batchDelay = groupIndex === 0 ? 0 : 100\n\n return of(documentIdsGroup).pipe(\n delay(batchDelay),\n mergeMapArray((id: string) => processDocument(id)),\n )\n }\n\n return documentPreviewStore\n .unstable_observeDocumentIdSet(groqFilter, params, {\n apiVersion: RELEASES_STUDIO_CLIENT_OPTIONS.apiVersion,\n })\n .pipe(\n map((state) => state.documentIds || []),\n switchMap((documentIds) => {\n // If no documents, return empty results immediately\n if (documentIds.length === 0) {\n return of([])\n }\n\n // Process in smaller groups as to not overwhelm the main thread\n // depending on the browser it can handle a different number of calls at once, this felt like a good balance\n // given the tests done\n const batchSize = 5\n const documentIdsGroups = []\n for (let i = 0; i < documentIds.length; i += batchSize) {\n documentIdsGroups.push(documentIds.slice(i, i + batchSize))\n }\n\n // Process all batches and collect all results\n return combineLatest(\n documentIdsGroups.map((batch, batchIndex) =>\n // The delay is used to control the rate of the requests\n // It increases as it goes on as to allow for some space (in the miliseconds scale)\n // This means that technically one might expect it to take longer to get all the results, but\n // It makes the user experience better as it is not overwhelming the main thread\n // And it allows for the browser to more easily handle the requests\n processDocumentIdsGroup(batch, batchIndex).pipe(delay(batchIndex * 100)),\n ),\n ).pipe(\n // Flatten all batch results into a single array\n // This is done to avoid having to nest the results and keep the strutcture as it was before\n map((groupResults) => groupResults.flat()),\n )\n }),\n map((results) => ({loading: false, results, error: null})),\n catchError((error) => {\n return of({loading: false, results: [], error})\n }),\n )\n}\n\n/**\n * Generic document-fetching machinery shared across releases and variants.\n *\n * Resolves the set of documents matching `groqFilter`/`params`, then observes each document along\n * with its published availability and validation status. Results are batched to avoid overwhelming\n * the main thread, and shared across subscribers via a module-level cache keyed by `cacheKey`.\n *\n * @internal\n */\nexport const getBundleDocumentsObservable = ({\n cacheKey,\n ...options\n}: BundleDocumentsObservableOptions & {cacheKey: string}): BundleDocumentsObservableResult => {\n if (!bundleDocumentsCache[cacheKey]) {\n bundleDocumentsCache[cacheKey] = buildBundleDocumentsObservable(options).pipe(\n finalize(() => {\n delete bundleDocumentsCache[cacheKey]\n }),\n shareReplay(1),\n )\n }\n\n return bundleDocumentsCache[cacheKey]\n}\n\nconst BUNDLE_DOCUMENTS_EMPTY = {\n loading: false,\n results: [],\n error: null,\n}\n\nconst BUNDLE_DOCUMENTS_LOADING = {\n loading: true,\n results: [],\n error: null,\n}\n\n/**\n * Generic hook to fetch the documents matching a GROQ filter, along with their validation and\n * published availability. Used by release- and variant-specific hooks.\n *\n * @internal\n */\nexport function useBundleDocuments(options: {\n groqFilter: string\n params: Record<string, unknown>\n cacheKey: string\n skipValidation?: (document: SanityDocument) => boolean\n enabled?: boolean\n}): {\n loading: boolean\n results: BundleDocument[]\n error: null | Error\n} {\n const {groqFilter, params, cacheKey, skipValidation, enabled = true} = options\n const documentPreviewStore = useDocumentPreviewStore()\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const {getClient, i18n, currentUser} = useSource()\n const schema = useSchema()\n\n const bundleDocumentsObservable = useMemo(\n () =>\n enabled\n ? getBundleDocumentsObservable({\n schema,\n documentPreviewStore,\n getClient,\n i18n,\n currentUser,\n groqFilter,\n params,\n cacheKey,\n skipValidation,\n })\n : of(BUNDLE_DOCUMENTS_EMPTY),\n [\n enabled,\n schema,\n documentPreviewStore,\n getClient,\n i18n,\n currentUser,\n groqFilter,\n params,\n cacheKey,\n skipValidation,\n ],\n )\n\n return useObservable(\n bundleDocumentsObservable,\n enabled ? BUNDLE_DOCUMENTS_LOADING : BUNDLE_DOCUMENTS_EMPTY,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAaS,eAAe;CAAC;CAAQ;CAAa;AAAW;;;;AAK7D,SAAgBE,cAAcC,kBAA4D;CACxF,OACE,OAAOA,oBA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