@sanity/scheduled-publishing
Version:
> [!IMPORTANT] > As of [v3.39.0](https://www.sanity.io/changelog/e6013ee5-8214-4e03-9593-f7b19124b8a3) of Sanity Studio, this plugin has been deprecated and the Scheduled Publishing functionality has been moved into the core studio package. > Read more an
1 lines • 75.3 kB
JavaScript
"use strict";const e=["onChange","onBlur","onKeyPress","value"],t=["onChange"],n=["selectTime","onFocusedDateChange","selectedDate","focusedDate","timeStep","onSelect","customValidation"],s=["value","onChange","customValidation"],i=["value","inputValue","customValidation","onInputChange","onChange","selectTime","timeStep"],l=["value","markers","title","description","placeholder","parseInputValue","formatInputValue","deserialize","serialize","selectTime","timeStep","readOnly","level","onChange","customValidation"],a=["type","onChange"],o=["focusedDate","onFocusedDateChange","onSelect","selectedDate"];var r,d,c,u,h,x;function p(e,t){if(null==e)return{};var n,s,i=function(e,t){if(null==e)return{};var n,s,i={},l=Object.keys(e);for(s=0;s<l.length;s++)n=l[s],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(s=0;s<l.length;s++)n=l[s],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,s)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?m(Object(n),!0).forEach((function(t){j(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function j(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var s=n.call(e,t||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}Object.defineProperty(exports,"__esModule",{value:!0});var b=require("@sanity/icons"),v=require("sanity"),y=require("sanity/router"),C=require("react/jsx-runtime"),k=require("@sanity/ui"),w=require("react"),S=require("styled-components"),M=require("@vvo/tzdb"),T=require("date-fns-tz"),D=require("debug"),L=require("date-fns"),I=require("react-focus-lock"),B=require("lodash/range"),A=require("lodash"),E=require("swr"),z=require("pluralize"),V=require("rxjs"),O=require("rxjs/operators"),F=require("@sanity/util/paths"),P=require("@sanity/color"),W=require("@tanstack/react-virtual");function R(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function N(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var U=R(w),H=R(S),Z=R(D),q=R(I),_=R(B),X=R(E),G=R(z),Y=N(F);const Q=e=>{const{buttonText:t="Action",disabled:n,icon:s,onAction:i,onComplete:l,tone:a="positive"}=e;return C.jsxs(k.Flex,{children:[C.jsx(k.Card,{flex:1,children:C.jsx(k.Button,{mode:"bleed",onClick:l,style:{width:"100%"},text:"Cancel"})}),i&&C.jsx(k.Card,{flex:1,marginLeft:3,children:C.jsx(k.Button,{disabled:n,icon:s,onClick:i,style:{width:"100%"},text:t,tone:a})})]})},J=e=>{const{body:t,title:n}=e;return C.jsxs(k.Stack,{paddingY:1,space:3,children:[C.jsxs(k.Inline,{space:2,children:[C.jsx(b.CalendarIcon,{}),n&&C.jsx(k.Text,{size:2,weight:"semibold",children:n})]}),t&&C.jsx(k.Text,{size:1,children:t})]})},K={publish:{actionName:"Publishing",badgeColor:"primary",badgeTone:"positive"},unpublish:{actionName:"Unpublishing",badgeColor:"danger",badgeTone:"critical"}},$={scheduled:{title:"Upcoming"},succeeded:{title:"Completed"},cancelled:{title:"Failed"}},ee=Object.keys($).filter((e=>!!e)),te="This document has validation errors that should be resolved before its publish date.",ne=C.jsxs(C.Fragment,{children:["Scheduled Publishing is only available on"," ",C.jsx("a",{href:"https://sanity.io/pricing",children:"Growth or higher plans"}),". Please upgrade to enable access."]}),se={SMALL:"d MMM yy',' p",MEDIUM:"d MMMM yyyy',' p",LARGE:"iiii',' d MMMM yyyy',' p"},ie={inputDateTimeFormat:"dd/MM/yyyy HH:mm"},le="scheduled-publishing:";function ae(e){const t="".concat(le).concat(e);return Z.default&&Z.default.enabled(t)?Z.default(t):Z.default(le)}function oe(e){let t;var n;return"object"==typeof(n=e)&&n&&"statusCode"in n&&"response"in n?t=403===e.response.statusCode?"Forbidden. Please check that your project has access to Scheduled Publishing.":e.message:(e instanceof Error&&(t=e.message),t=String(e)),t}Z.default(le);const re=ae("useScheduleOperation"),de=M.getTimeZones().map((e=>({abbreviation:e.abbreviation,alternativeName:e.alternativeName,mainCities:e.mainCities.join(", "),name:e.name,namePretty:e.name.replaceAll("_"," "),offset:e.currentTimeFormat.split(" ")[0],value:"".concat(e.currentTimeFormat," ").concat(e.abbreviation," ").concat(e.name)})));function ce(){return de.find((e=>e.name===Intl.DateTimeFormat().resolvedOptions().timeZone))||de.find((e=>"GMT"===e.abbreviation))||de[0]}function ue(){const e=localStorage.getItem("scheduled-publishing::time-zone");try{if(e)return JSON.parse(e)}catch(e){}return ce()}const he=()=>{const e=w.useMemo((()=>ue()),[]),[t,n]=w.useState(e),s=k.useToast();w.useEffect((()=>{const e=()=>{n(ue())};return window.addEventListener("timeZoneEventUpdate",e),()=>{window.removeEventListener("timeZoneEventUpdate",e)}}),[]);const i=w.useCallback((e=>{let{date:n,format:s=se.LARGE,includeTimeZone:i,prefix:l}=e,a=s;return l&&(a="'".concat(l,"'").concat(s)),i&&(a="".concat(s," (zzzz)")),T.formatInTimeZone(n,t.name,a)}),[t.name]),l=w.useCallback((()=>T.utcToZonedTime(new Date,t.name)),[t.name]),a=w.useCallback((e=>{re("handleNewValue:",e),n((t=>{try{t.name!==e.name&&(localStorage.setItem("scheduled-publishing::time-zone",JSON.stringify(e)),window.dispatchEvent(new Event("timeZoneEventUpdate"))),s.push({closable:!0,description:C.jsx(J,{body:"".concat(e.alternativeName," (").concat(e.namePretty,")"),title:"Time zone updated"}),duration:15e3,status:"info"})}catch(e){console.error(e),s.push({closable:!0,description:C.jsx(J,{body:oe(e),title:"Unable to update time zone"}),status:"error"})}return e}))}),[s]),o=w.useCallback((e=>T.utcToZonedTime(e,t.name)),[t.name]),r=w.useCallback((e=>T.zonedTimeToUtc(e,t.name)),[t.name]);return{formatDateTz:i,getCurrentZoneDate:l,setTimeZone:a,timeZone:t,utcToCurrentZoneDate:o,zoneDateToUtc:r}},xe=H.default.span((e=>{let{theme:t}=e;return S.css(r||(r=g(["\n color: ",";\n font-weight: 500;\n margin-left: 1em;\n "])),t.sanity.color.base.fg)})),pe=H.default.span((e=>{let{theme:t}=e;return S.css(d||(d=g(["\n color: ",";\n margin-left: 1em;\n "])),t.sanity.color.input.default.readOnly.fg)})),me=e=>{const{onClose:t}=e,{setTimeZone:n,timeZone:s}=he(),[i,l]=w.useState(s),a=(null==i?void 0:i.name)!==s.name,o=w.useMemo((()=>(null==i?void 0:i.name)===ce().name),[i]);return C.jsx(k.Dialog,{footer:C.jsx(k.Box,{paddingX:4,paddingY:3,children:C.jsx(Q,{buttonText:"Update time zone",disabled:!a||!i,onAction:()=>{i&&n(i),null==t||t()},onComplete:t,tone:"primary"})}),header:"Select time zone",id:"time-zone",onClose:t,width:1,children:C.jsxs(k.Stack,{padding:4,space:5,children:[C.jsx(k.Text,{size:1,children:"The selected time zone will change how dates are represented in schedules."}),C.jsxs(k.Stack,{space:3,children:[C.jsxs(k.Flex,{align:"center",justify:"space-between",children:[C.jsxs(k.Inline,{space:2,children:[C.jsx(k.Text,{size:1,weight:"semibold",children:"Time zone"}),o&&C.jsx(k.Text,{muted:!0,size:1,children:"local time"})]}),!o&&C.jsx(k.Text,{size:1,weight:"medium",children:C.jsx("a",{onClick:()=>{l(ce())},style:{cursor:"pointer"},children:"Select local time zone"})})]}),C.jsx(k.Autocomplete,{fontSize:2,icon:b.SearchIcon,id:"timezone",onChange:e=>{const t=de.find((t=>t.value===e));l(t)},openButton:!0,options:de,padding:4,placeholder:"Search for a city or time zone",popover:{boundaryElement:document.querySelector("body"),constrainSize:!0,placement:"bottom-start"},renderOption:e=>C.jsx(k.Card,{as:"button",padding:3,children:C.jsxs(k.Text,{size:1,textOverflow:"ellipsis",children:[C.jsxs("span",{children:["GMT",e.offset]}),C.jsx(xe,{children:e.alternativeName}),C.jsx(pe,{children:e.mainCities})]})}),renderValue:(e,t)=>t?"".concat(t.alternativeName," (").concat(t.namePretty,")"):"",tabIndex:-1,value:null==i?void 0:i.value})]})]})})};function fe(){const[e,t]=w.useState(!1),n=w.useCallback((()=>{t(!1)}),[]);return{visible:e,show:w.useCallback((()=>{t(!0)}),[]),hide:n}}function je(){const{visible:e,show:t,hide:n}=fe();return{DialogTimeZone:e?me:null,dialogProps:{onClose:n,visible:e},dialogTimeZoneShow:t,hide:n}}const ge=e=>{const{useElementQueries:t}=e,{timeZone:n}=he(),{DialogTimeZone:s,dialogProps:i,dialogTimeZoneShow:l}=je();return C.jsxs(C.Fragment,{children:[s&&C.jsx(s,f({},i)),C.jsx(k.Tooltip,{content:C.jsx(k.Box,{padding:2,children:C.jsxs(k.Text,{muted:!0,size:1,children:["Displaying schedules in ",n.alternativeName," (GMT",n.offset,")"]})}),portal:!0,children:C.jsx("div",{children:t?C.jsxs(C.Fragment,{children:[C.jsx(k.Box,{className:"button-small",children:C.jsx(k.Button,{fontSize:1,icon:b.EarthAmericasIcon,mode:"bleed",onClick:l,text:"".concat(n.abbreviation)})}),C.jsx(k.Box,{className:"button-large",children:C.jsx(k.Button,{fontSize:1,icon:b.EarthAmericasIcon,mode:"bleed",onClick:l,text:"".concat(n.alternativeName," (").concat(n.namePretty,")")})})]}):C.jsx(k.Button,{fontSize:1,icon:b.EarthAmericasIcon,mode:"bleed",onClick:l,text:"".concat(n.alternativeName," (").concat(n.namePretty,")")})})})]})},be=H.default(k.ElementQuery)(c||(c=g(["\n .button-small {\n display: block;\n }\n .button-large {\n display: none;\n }\n\n &[data-eq-min~='2'] {\n .button-small {\n display: none;\n }\n .button-large {\n display: block;\n }\n }\n"]))),ve=e=>{const{title:t}=e;return C.jsx(be,{children:C.jsxs(k.Flex,{align:"center",children:[t,C.jsx("input",{style:{opacity:0,position:"absolute",width:0},tabIndex:-1,type:"button"}),C.jsx(k.Box,{marginLeft:2,style:{marginTop:"-1em",marginBottom:"-1em"},children:C.jsx(ge,{useElementQueries:!0})})]})})};function ye(e){const{date:t,focused:n,isCurrentMonth:s,isToday:i,customValidation:l,onSelect:a,selected:o}=e,r=w.useMemo((()=>!l||l(L.endOfDay(t))),[t,l]),d=w.useCallback((()=>{r&&a(t)}),[t,r,a]);return C.jsx("div",{"aria-selected":o,"data-ui":"CalendarDay",children:C.jsx(k.Card,{"aria-label":t.toDateString(),"aria-pressed":o,as:"button",__unstable_focusRing:!0,"data-weekday":!0,"data-focused":n?"true":"",disabled:!r,role:"button",tabIndex:-1,onClick:d,padding:3,radius:2,selected:o,tone:i||o?"primary":"default",children:C.jsx(k.Text,{muted:!o&&!s,style:{textAlign:"center"},weight:s?"medium":"regular",children:t.getDate()})})})}const Ce=["January","February","March","April","May","June","July","August","September","October","November","December"],ke=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],we=A.range(0,24),Se=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Me=[1,2,3,4,5,6],Te=e=>{return(t=(e=>{const t=L.startOfMonth(e);return L.eachWeekOfInterval({start:t,end:L.lastDayOfMonth(t)})})(e),t.map((e=>[e,...Me.map((t=>L.addDays(e,t)))]))).map((e=>({number:L.getWeek(e[0]),days:e})));var t};function De(e){const{getCurrentZoneDate:t}=he(),{customValidation:n}=e;return C.jsx(k.Box,{"aria-hidden":e.hidden||!1,"data-ui":"CalendarMonth",children:C.jsxs(k.Grid,{gap:1,style:{gridTemplateColumns:"repeat(7, minmax(44px, 46px))"},children:[ke.map((e=>C.jsx(k.Box,{paddingY:2,children:C.jsx(k.Text,{size:1,weight:"medium",style:{textAlign:"center"},children:e})},e))),Te(e.date).map(((s,i)=>s.days.map(((s,l)=>{const a=e.focused&&L.isSameDay(s,e.focused),o=e.selected&&L.isSameDay(s,e.selected),r=L.isSameDay(s,t()),d=e.focused&&L.isSameMonth(s,e.focused);return C.jsx(ye,{date:s,focused:a,isCurrentMonth:d,isToday:r,customValidation:n,onSelect:e.onSelect,selected:o},"".concat(i,"-").concat(l))}))))]})})}const Le=!1,Ie=U.default.forwardRef((function(t,n){let{onChange:s,onBlur:i,onKeyPress:l,value:a}=t,o=p(t,e);const[r,d]=U.default.useState(),c=U.default.useCallback((e=>{d(e.currentTarget.value)}),[]),u=U.default.useCallback((e=>{e.currentTarget.value!=="".concat(a)&&s&&s(e),d(void 0)}),[s,a]),h=U.default.useCallback((e=>{u(e),i&&i(e)}),[u,i]),x=U.default.useCallback((e=>{"Enter"===e.key&&u(e),l&&l(e)}),[u,l]);return C.jsx(k.TextInput,f(f({},o),{},{"data-testid":"date-input",ref:n,value:void 0===r?a:r,onChange:c,onBlur:h,onKeyPress:x}))})),Be=e=>{let{onChange:n}=e,s=p(e,t);const i=U.default.useCallback((e=>{const t=parseInt(e.currentTarget.value,10);isNaN(t)||n(t)}),[n]);return C.jsx(Ie,f(f({},s),{},{onChange:i,inputMode:"numeric"}))},Ae=C.jsx("span",{"data-preserve-focus":!0,style:{overflow:"hidden",position:"absolute",outline:"none"},tabIndex:-1}),Ee=w.forwardRef((function(e,t){const{getCurrentZoneDate:s,zoneDateToUtc:i}=he(),{selectTime:l,onFocusedDateChange:a,selectedDate:o=s(),focusedDate:r=o,timeStep:d=1,onSelect:c,customValidation:u}=e,h=p(e,n),x=w.useCallback((e=>a(i(e))),[a,i]),m=w.useCallback((e=>x(L.setDate(L.setMonth(r,e),1))),[r,x]),j=w.useCallback((e=>m(Number(e.currentTarget.value))),[m]),g=w.useCallback((e=>x(L.addMonths(r,e))),[r,x]),b=w.useCallback((e=>x(L.setYear(r,e))),[r,x]),v=w.useCallback((e=>{c(i(L.setMinutes(L.setHours(e,o.getHours()),o.getMinutes())))}),[c,o,i]),y=w.useCallback((e=>{const t=Number(e.currentTarget.value);c(i(L.setMinutes(o,t)))}),[c,o,i]),S=w.useCallback((e=>{const t=Number(e.currentTarget.value);c(i(L.setHours(o,t)))}),[c,o,i]);w.useCallback(((e,t)=>{c(i(L.setHours(L.setMinutes(o,t),e)))}),[c,o,i]);const M=k.useForwardedRef(t),T=w.useCallback((()=>{var e,t;null==(t=null==(e=M.current)?void 0:e.querySelector('[data-focused="true"]'))||t.focus()}),[M]),D=w.useCallback((e=>{var t,n;Se.includes(e.key)&&(e.preventDefault(),e.currentTarget.hasAttribute("data-calendar-grid")?T():("ArrowUp"===e.key&&a(i(L.addDays(r,-7))),"ArrowDown"===e.key&&a(i(L.addDays(r,7))),"ArrowLeft"===e.key&&a(i(L.addDays(r,-1))),"ArrowRight"===e.key&&a(i(L.addDays(r,1))),null==(n=null==(t=M.current)?void 0:t.querySelector("[data-preserve-focus]"))||n.focus()))}),[i,M,T,a,r]);w.useEffect((()=>{T()}),[T]),w.useEffect((()=>{var e;(null==(e=document.activeElement)?void 0:e.matches("[data-calendar-grid], [data-calendar-grid] [data-preserve-focus]"))&&T()}),[M,T,r]);const I=w.useCallback((()=>c(new Date)),[c]);return C.jsxs(k.Box,f(f({"data-ui":"Calendar"},h),{},{ref:M,children:[C.jsxs(k.Box,{padding:2,children:[C.jsxs(k.Flex,{children:[C.jsx(k.Box,{flex:1,children:C.jsx(ze,{moveFocusedDate:g,onChange:j,value:null==r?void 0:r.getMonth()})}),C.jsx(k.Box,{marginLeft:2,children:C.jsx(Ve,{moveFocusedDate:g,onChange:b,value:r.getFullYear()})})]}),C.jsxs(k.Box,{"data-calendar-grid":!0,onKeyDown:D,marginTop:2,overflow:"hidden",tabIndex:0,children:[C.jsx(De,{date:r,focused:r,customValidation:u,onSelect:v,selected:o}),Ae]})]}),l&&C.jsxs(k.Box,{padding:2,style:{borderTop:"1px solid var(--card-border-color)"},children:[C.jsxs(k.Flex,{align:"center",children:[C.jsxs(k.Flex,{align:"center",flex:1,children:[C.jsx(k.Box,{children:C.jsx(k.Select,{"aria-label":"Select hour",value:null==o?void 0:o.getHours(),onChange:S,children:we.map((e=>C.jsx("option",{value:e,children:"".concat(e).padStart(2,"0")},e)))})}),C.jsx(k.Box,{paddingX:1,children:C.jsx(k.Text,{children:":"})}),C.jsx(k.Box,{children:C.jsx(k.Select,{"aria-label":"Select minutes",value:null==o?void 0:o.getMinutes(),onChange:y,children:_.default(0,60,d).map((e=>C.jsx("option",{value:e,children:"".concat(e).padStart(2,"0")},e)))})})]}),C.jsx(k.Box,{marginLeft:2,children:C.jsx(k.Button,{text:"Set to current time",mode:"bleed",onClick:I})})]}),Le]})]}))}));function ze(e){const{moveFocusedDate:t,onChange:n,value:s}=e,i=w.useCallback((()=>t(-1)),[t]),l=w.useCallback((()=>t(1)),[t]);return C.jsxs(k.Flex,{flex:1,children:[C.jsx(k.Button,{"aria-label":"Go to previous month",onClick:i,mode:"bleed",icon:b.ChevronLeftIcon,paddingX:2,radius:0}),C.jsx(k.Box,{flex:1,children:C.jsx(k.Select,{radius:0,value:s,onChange:n,children:Ce.map(((e,t)=>C.jsx("option",{value:t,children:e},t)))})}),C.jsx(k.Button,{"aria-label":"Go to next month",mode:"bleed",icon:b.ChevronRightIcon,onClick:l,paddingX:2,radius:0})]})}function Ve(e){const{moveFocusedDate:t,onChange:n,value:s}=e,i=w.useCallback((()=>t(-12)),[t]),l=w.useCallback((()=>t(12)),[t]);return C.jsxs(k.Flex,{children:[C.jsx(k.Button,{"aria-label":"Previous year",onClick:i,mode:"bleed",icon:b.ChevronLeftIcon,paddingX:2,radius:0}),C.jsx(Be,{value:s,onChange:n,radius:0,style:{width:65}}),C.jsx(k.Button,{"aria-label":"Next year",onClick:l,mode:"bleed",icon:b.ChevronRightIcon,paddingX:2,radius:0})]})}const Oe=U.default.forwardRef((function(e,t){const{utcToCurrentZoneDate:n}=he(),{value:i=new Date,onChange:l,customValidation:a}=e,o=p(e,s),[r,d]=U.default.useState(),c=U.default.useCallback((e=>{l(e),d(void 0)}),[l]);return C.jsx(Ee,f(f({},o),{},{ref:t,selectedDate:n(i),onSelect:c,focusedDate:n(r||i),onFocusedDateChange:d,customValidation:a}))})),Fe=U.default.forwardRef((function(e,t){const{value:n,inputValue:s,customValidation:l,onInputChange:a,onChange:o,selectTime:r,timeStep:d}=e,c=p(e,i),[u,h]=U.default.useState(null),x=k.useForwardedRef(t),m=U.default.useRef(null),[j,g]=U.default.useState(!1),v=k.usePortal();k.useClickOutside((()=>g(!1)),[u]);const y=w.useCallback((()=>{var e,t;null==(e=x.current)||e.focus(),null==(t=x.current)||t.select()}),[x]),S=w.useCallback((e=>{"Escape"===e.key&&g(!1)}),[]),M=w.useCallback((()=>g(!0)),[]),T=C.jsx(k.Box,{padding:1,children:C.jsx(k.Button,{ref:m,icon:b.CalendarIcon,mode:"bleed",padding:2,onClick:M,style:{display:"block"},"data-testid":"select-date-button"})});return C.jsx(Ie,f(f({ref:x},c),{},{value:s,onChange:a,suffix:j?C.jsx(k.LayerProvider,{zOffset:1e3,children:C.jsx(k.Popover,{constrainSize:!0,content:C.jsx(k.Box,{overflow:"auto",children:C.jsx(q.default,{onDeactivation:y,children:C.jsx(Oe,{selectTime:r,timeStep:d,onKeyUp:S,value:n,onChange:o,customValidation:l})})}),"data-testid":"date-input-dialog",fallbackPlacements:["bottom","bottom-start","top-end","top","top-start"],floatingBoundary:v.element,open:!0,placement:"bottom-end",portal:!0,radius:2,ref:h,children:T})}):T}))})),Pe=U.default.forwardRef((function(e,t){const{value:n,markers:s,title:i,description:a,placeholder:o,parseInputValue:r,formatInputValue:d,deserialize:c,serialize:u,selectTime:h,timeStep:x,readOnly:m,level:j,onChange:g,customValidation:b}=e,y=p(e,l),[S,M]=U.default.useState(null);w.useEffect((()=>{M(null)}),[n]);const{zoneDateToUtc:T}=he(),D=void 0===n,L=U.default.useCallback((e=>{const t=e.currentTarget.value,n=""===t?null:r(t);null===n?(g(null),D&&S&&M(null)):n.isValid?g(u(T(n.date))):M(t)}),[D,T,S,u,g,r]),I=U.default.useCallback((e=>{g(e?u(e):null)}),[u,g]),B=k.useForwardedRef(t),A=w.useId(),E=S?r(S):n?c(n):null,z=S||((null==E?void 0:E.isValid)?d(E.date):n),V=w.useMemo((()=>s.map((e=>({level:e.level,path:e.path,message:e.item.message})))),[s]);return C.jsx(v.FormField,{validation:(null==E?void 0:E.error)?[...V,{level:"error",message:E.error,path:[]}]:V,title:i,level:j,description:a,inputId:A,children:m?C.jsx(k.TextInput,{value:z,readOnly:!0}):C.jsx(Fe,f(f({},y),{},{id:A,selectTime:h,timeStep:x,placeholder:o||"e.g. ".concat(d(new Date)),ref:B,value:null==E?void 0:E.date,inputValue:z||"",readOnly:Boolean(m),onInputChange:L,onChange:I,customValidity:null==E?void 0:E.error,customValidation:b}))})}));function We(e){return e.toISOString()}function Re(e){const t=new Date(e);return(n=t)instanceof Date&&!isNaN(n.valueOf())?{isValid:!0,date:t}:{isValid:!1,error:'Invalid date value: "'.concat(e,'"')};var n}const Ne=U.default.forwardRef((function(e,t){const{type:n,onChange:s}=e,i=p(e,a),{title:l,description:o,placeholder:r}=n,{inputDateTimeFormat:d}=function(){const e=v.useTools().find((e=>"schedules"===e.name));return(null==e?void 0:e.options)||(console.warn("[scheduled-publishing] Unable to find tool options and reverting to default values - please ensure that the tool is available in the current studio."),ie)}(),{getCurrentZoneDate:c,timeZone:u}=he(),{customValidation:h,customValidationMessage:x,timeStep:m}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{customValidation:e.customValidation||function(){return!0},customValidationMessage:e.customValidationMessage||"Invalid date.",calendarTodayLabel:e.calendarTodayLabel||"Today",timeStep:"timeStep"in e&&Number(e.timeStep)||1}}(n.options),j=w.useCallback((e=>{let t=e;null!==t&&m>1&&(t=function(e,t){if(!t||1===t)return e;const n=L.parseISO(e),s=L.getMinutes(n),i=s%t;return We(0!==i?L.setMinutes(n,s-i):n)}(t,m)),s(t)}),[s,m]),g=U.default.useCallback((e=>T.formatInTimeZone(e,u.name,"".concat(d))),[d,u.name]),b=U.default.useCallback((e=>{const t=L.parse(e,"".concat(d),c());return L.isValid(t)?h(t)?{isValid:!0,date:t}:{isValid:!1,error:x}:{isValid:!1,error:'Invalid date. Must be in the format "'.concat(d,'"')}}),[h,x,c,d]);return C.jsx(Pe,f(f({},i),{},{onChange:j,ref:t,selectTime:!0,timeStep:m,title:l,description:o,placeholder:r,serialize:We,deserialize:Re,formatInputValue:g,customValidation:h,parseInputValue:b}))})),Ue=e=>{const{onChange:t,value:n}=e,{getCurrentZoneDate:s}=he(),[i,l]=w.useState();return C.jsx(k.Stack,{space:4,children:C.jsx(k.Card,{children:C.jsx(Ne,{level:0,markers:[],onChange:e=>{e&&t&&(t({date:e}),l(e))},type:{name:"date",options:{customValidation:e=>e>s(),customValidationMessage:"Date cannot be in the past."},title:"Date and time"},value:void 0===i?null==n?void 0:n.date:i})})})};function He(e){const{onChange:t,value:n}=e;return C.jsxs(k.Stack,{space:4,children:[e.children,C.jsx(Ue,{onChange:t,value:n})]})}const Ze=e=>{const{description:t,title:n}=e;return C.jsx(k.Card,{overflow:"hidden",padding:4,radius:2,shadow:1,tone:"critical",children:C.jsxs(k.Flex,{align:"center",gap:4,children:[C.jsx(k.Text,{size:2,children:C.jsx(b.ErrorOutlineIcon,{})}),C.jsxs(k.Inline,{space:2,children:[C.jsx(k.Text,{size:1,weight:"semibold",children:n}),t&&C.jsx(k.Text,{size:1,children:t})]})]})})},qe=w.createContext(void 0);function _e(e){let{children:t,value:n}=e;return C.jsx(qe.Provider,{value:n,children:t})}const Xe={refreshWhenHidden:!1,refreshWhenOffline:!1,revalidateIfStale:!1,revalidateOnFocus:!1,revalidateOnReconnect:!1,shouldRetryOnError:!1};function Ge(){const e=v.useClient({apiVersion:"2022-09-01"}),t="/projects/".concat(e.config().projectId,"/features/scheduledPublishing"),n=w.useCallback((()=>e.request({method:"GET",uri:t})),[e,t]),{data:s}=X.default(t,n,Xe);return s}function Ye(e){return(null==e?void 0:e.executedAt)||(null==e?void 0:e.executeAt)}function Qe(){let{reverseOrder:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{reverseOrder:!1};return function(t,n){const s=Ye(t),i=Ye(n);return s===i?0:null===s?1:null===i?-1:(s>i?1:-1)*(e?-1:1)}}const Je=ae("useScheduleOperation");function Ke(){const e=v.useClient({apiVersion:"2022-09-01"});return w.useMemo((()=>function(e){const{dataset:t,projectId:n}=e.config();function s(s){let{date:i,documentId:l}=s;Je("_create:",l);const a=new Date(i);return a.setSeconds(0),a.setMilliseconds(0),e.request({body:{documents:[{documentId:l}],executeAt:a,name:a},method:"POST",uri:"/schedules/".concat(n,"/").concat(t)})}function i(s){let{scheduleId:i}=s;return Je("_delete:",i),e.request({method:"DELETE",uri:"/schedules/".concat(n,"/").concat(t,"/").concat(i)})}function l(e){let{scheduleIds:t}=e;Je("_deleteMultiple:",t);const n=t.map((e=>i({scheduleId:e})));return Promise.allSettled(n)}function a(s){let{scheduleId:i}=s;return Je("_publish:",i),e.request({method:"POST",uri:"/schedules/".concat(n,"/").concat(t,"/").concat(i,"/publish")})}function o(s){let{documentSchedule:i,scheduleId:l}=s;return Je("_update:",l,i),e.request({body:i,method:"PATCH",uri:"/schedules/".concat(n,"/").concat(t,"/").concat(l)})}return{create:s,delete:i,deleteMultiple:l,publish:a,update:o}}(e)),[e])}var $e=(e=>(e.create="scheduleCreate",e.delete="scheduleDelete",e.deleteMultiple="scheduleDeleteMultiple",e.publish="schedulePublish",e.update="scheduleUpdate",e))($e||{});const et=(e,t)=>new CustomEvent(e,t);function tt(){const e=k.useToast(),{formatDateTz:t}=he(),n=Ke();return{createSchedule:async function(s){let{date:i,displayToast:l=!0,documentId:a}=s;try{const s=await n.create({date:i,documentId:a});window.dispatchEvent(et("scheduleCreate",{detail:{date:i,documentId:a}})),l&&(null==s?void 0:s.executeAt)&&e.push({closable:!0,description:C.jsx(J,{body:t({date:new Date(s.executeAt),includeTimeZone:!0,prefix:"Publishing on "}),title:"Schedule created"}),duration:15e3,status:"success"})}catch(t){l&&e.push({closable:!0,description:C.jsx(J,{body:oe(t),title:"Unable to create schedule"}),duration:15e3,status:"error"})}},deleteSchedule:async function(t){let{displayToast:s=!0,schedule:i}=t;try{await n.delete({scheduleId:null==i?void 0:i.id}),window.dispatchEvent(et("scheduleDelete",{detail:{scheduleId:null==i?void 0:i.id}})),s&&e.push({closable:!0,description:C.jsx(J,{title:"Schedule deleted"}),status:"success"})}catch(t){s&&e.push({closable:!0,description:C.jsx(J,{body:oe(t),title:"Unable to delete schedule"}),duration:15e3,status:"error"})}},deleteSchedules:async function(t){let{displayToast:s=!0,schedules:i}=t;try{const t=i.map((e=>e.id)),l=await n.deleteMultiple({scheduleIds:t}),{fulfilledIds:a,rejectedReasons:o}=l.reduce(((e,t,n)=>("fulfilled"===t.status&&e.fulfilledIds.push(i[n].id),"rejected"===t.status&&e.rejectedReasons.push("[".concat(i[n].id,"]: ").concat(t.reason)),e)),{fulfilledIds:[],rejectedReasons:[]}),r=a.length,d=o.length;(null==a?void 0:a.length)>0&&window.dispatchEvent(et("scheduleDeleteMultiple",{detail:{scheduleIds:a}})),s&&((null==a?void 0:a.length)>0&&e.push({closable:!0,description:C.jsx(J,{title:"".concat(G.default("schedule",r,!0)," deleted")}),status:"success"}),(null==o?void 0:o.length)>0&&e.push({closable:!0,description:C.jsx(J,{body:null==o?void 0:o.toString(),title:"Unable to delete ".concat(G.default("schedule",d,!0))}),duration:15e3,status:"error"}))}catch(t){s&&e.push({closable:!0,description:C.jsx(J,{body:oe(t),title:"Unable to delete schedules"}),duration:15e3,status:"error"})}},publishSchedule:async function(t){let{displayToast:s=!0,schedule:i}=t;try{const t=i.id;await n.publish({scheduleId:t}),window.dispatchEvent(et("schedulePublish",{detail:{scheduleId:t}})),s&&e.push({closable:!0,description:C.jsx(J,{title:"Document published"}),status:"success"})}catch(t){s&&e.push({closable:!0,description:C.jsx(J,{body:oe(t),title:"Unable to publish schedule"}),duration:15e3,status:"error"})}},updateSchedule:async function(s){let{date:i,displayToast:l=!0,scheduleId:a}=s;try{await n.update({documentSchedule:{executeAt:i},scheduleId:a}),window.dispatchEvent(et("scheduleUpdate",{detail:{date:i,scheduleId:a}})),l&&e.push({closable:!0,description:C.jsx(J,{body:t({date:new Date(i),includeTimeZone:!0,prefix:"Publishing on "}),title:"Schedule updated"}),duration:15e3,status:"success"})}catch(t){l&&e.push({closable:!0,description:C.jsx(J,{body:oe(t),title:"Unable to update schedule"}),duration:15e3,status:"error"})}}}}function nt(){const e=v.useClient({apiVersion:"2022-09-01"}),{dataset:t,projectId:n}=e.config();return"/schedules/".concat(n,"/").concat(t)}function st(e){const t=v.useClient({apiVersion:"2022-09-01"});return w.useCallback((()=>t.request({query:e.params,method:"GET",uri:e.url})),[t,e])}const it={refreshInterval:1e4,refreshWhenHidden:!1,refreshWhenOffline:!1,revalidateOnFocus:!1,revalidateOnReconnect:!0,shouldRetryOnError:!1},lt=[];function at(){let{documentId:e,state:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=nt(),s=w.useMemo((()=>({params:{documentIds:e,state:t},url:n})),[n,e,t]),i=st(s),{data:l,error:a,mutate:o}=X.default(s,i,it),r=w.useCallback((e=>{o((t=>{var n;return{schedules:null==(n=null==t?void 0:t.schedules)?void 0:n.filter((t=>t.id!==e.detail.scheduleId))}}),!0)}),[o]),d=w.useCallback((e=>{o((t=>{var n;return{schedules:null==(n=null==t?void 0:t.schedules)?void 0:n.filter((t=>!e.detail.scheduleIds.includes(t.id)))}}),!0)}),[o]),c=w.useCallback((e=>{o((t=>{const n=(null==t?void 0:t.schedules)||[],s=n.findIndex((t=>t.id===e.detail.scheduleId));return{schedules:[...null==n?void 0:n.slice(0,s),f(f({},n[s]),{},{executeAt:(new Date).toISOString(),state:"succeeded"}),...null==n?void 0:n.slice(s+1)]}}),!0)}),[o]),u=w.useCallback((e=>{o((t=>{const n=(null==t?void 0:t.schedules)||[],s=n.findIndex((t=>t.id===e.detail.scheduleId));return{schedules:[...null==n?void 0:n.slice(0,s),f(f({},n[s]),{},{executeAt:e.detail.date}),...null==n?void 0:n.slice(s+1)]}}),!0)}),[o]);w.useEffect((()=>(window.addEventListener($e.delete,r),window.addEventListener($e.deleteMultiple,d),window.addEventListener($e.publish,c),window.addEventListener($e.update,u),()=>{window.removeEventListener($e.delete,r),window.removeEventListener($e.deleteMultiple,d),window.removeEventListener($e.publish,c),window.removeEventListener($e.update,u)})),[r,d,c,u]);const h=w.useMemo((()=>{var e;return null==(e=null==l?void 0:l.schedules)?void 0:e.sort(Qe())}),[null==l?void 0:l.schedules]);return{error:a,isInitialLoading:!a&&!l,schedules:h||lt}}function ot(e){const[t,n]=w.useState(!1),[s,i]=w.useState(e&&(null==e?void 0:e.executeAt)?{date:e.executeAt}:null);return{formData:s,isDirty:t,onFormChange:w.useCallback((t=>{const s=(null==e?void 0:e.executeAt)&&new Date(e.executeAt).getTime()===new Date(null==t?void 0:t.date).getTime();i(t),n(!s)}),[null==e?void 0:e.executeAt])}}function rt(e){return w.useMemo((()=>e?e.replaceAll("drafts.",""):void 0),[e])}function dt(e){var t;return null==(t=e.documents)?void 0:t[0]}function ct(e){var t;return null==(t=dt(e))?void 0:t.documentId.replaceAll("drafts.","")}function ut(e){const t=dt(e),n=v.useSchema(),s=t.documentType;return w.useMemo((()=>{if(s)return n.get(s)}),[s,n])}const ht={validation:[],isValidating:!1};function xt(e){return w.useMemo((()=>function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ht.validation;const t=e.filter(v.isValidationErrorMarker).length>0,n=e.filter(v.isValidationWarningMarker).length>0;let s="default";return n&&(s="default"),t&&(s="critical"),{markers:e,validationTone:s,hasError:t,hasWarning:n}}(e)),[e])}const pt=H.default(k.Text)(u||(u=g(["\n white-space: initial;\n"]))),mt={error:"critical",warning:"caution",info:"primary"};function ft(e){const{marker:t,onClick:n,path:s,truncate:i}=e,l=w.useCallback((()=>{n&&n(t.path)}),[t.path,n]),a=mt[null==t?void 0:t.level]||void 0,o=C.jsxs(k.Flex,{children:[C.jsx(k.Box,{children:C.jsxs(k.Text,{size:1,children:["error"===t.level&&C.jsx(b.ErrorOutlineIcon,{}),"warning"===t.level&&C.jsx(b.WarningOutlineIcon,{}),"info"===t.level&&C.jsx(b.InfoOutlineIcon,{})]})}),C.jsxs(k.Stack,{space:2,flex:1,paddingLeft:3,children:[s&&C.jsx(pt,{size:1,weight:"semibold",children:s}),t.item.message&&C.jsx(pt,{muted:!0,size:1,textOverflow:i?"ellipsis":void 0,children:t.item.message})]})]});return C.jsx(k.MenuItem,{padding:1,onClick:l,radius:2,tone:a,children:C.jsx(k.Box,{padding:2,children:o})})}function jt(e){const{documentType:t,kind:n,validation:s,onFocus:i,onClose:l,truncate:a}=e,o=s.filter(v.isValidationErrorMarker),r=s.filter(v.isValidationWarningMarker),d=s.filter(v.isValidationInfoMarker),c=w.useCallback((function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];i&&i(e),l&&l()}),[i,l]),u=e=>{const n=t&&t.fields,s=n&&n.find((t=>t.name===e[0]));return s&&s.type.title||""},h=o.length>0,x=r.length>0,p=d.length>0;return h||x||p?C.jsxs(k.Container,{width:0,"data-kind":n,"data-testid":"validation-list",children:[h&&o.map(((e,t)=>C.jsx(ft,{truncate:a,path:u(e.path),marker:e,onClick:c},t))),x&&r.map(((e,t)=>C.jsx(ft,{truncate:a,path:u(e.path),marker:e,onClick:c},t))),p&&d.map(((e,t)=>C.jsx(ft,{truncate:a,path:u(e.path),marker:e,onClick:c},t)))]}):null}const gt={portal:!0,constrainSize:!0,preventOverflow:!0,tone:"default",width:0};function bt(e){const{type:t,markers:n,menuHeader:s,documentId:i}=e,l=y.useRouter(),{hasError:a,hasWarning:o}=xt(n),r=a||o?"visible":"hidden",d=w.useId()||"",c=rt(i),u=w.useCallback((e=>{c&&l.navigateIntent("edit",{id:c,path:encodeURIComponent(Y.toString(e))})}),[l,c]);return C.jsx(k.MenuButton,{id:d||"",button:C.jsx(k.Button,{title:"Show validation issues",mode:"bleed","data-testid":"schedule-validation-list-button",icon:a?b.ErrorOutlineIcon:b.WarningOutlineIcon,style:{visibility:r},tone:a?"critical":"default"}),menu:C.jsx(k.Menu,{padding:1,children:C.jsx(k.Container,{width:0,children:C.jsxs(k.Stack,{space:1,children:[null!=s?s:null,C.jsx(jt,{documentType:t,validation:n,onFocus:u})]})})}),popover:gt,placement:"bottom-end"})}function vt(e){let{id:t,schemaType:n}=e;return C.jsxs(k.Stack,{space:4,children:[C.jsxs(k.Text,{size:1,children:["Schedule this document to be published at any time in the future.",C.jsx("br",{}),"Any edits in the meantime will be added to the scheduled document."]}),C.jsx(k.Text,{size:1,children:"Visit the Schedules page to get an overview of all schedules."}),C.jsx(yt,{id:t,type:n})]})}function yt(e){let{id:t,type:n}=e;const s=rt(t),i=function(e){const t=v.useSchema();return w.useMemo((()=>t.get(e)),[e,t])}(n),l=v.useValidationStatus(s,n),{hasError:a}=xt(l.validation);return a?C.jsx(k.Card,{padding:2,radius:1,shadow:1,tone:"critical",children:C.jsxs(k.Flex,{gap:1,align:"center",children:[C.jsx(bt,{markers:l.validation,type:i,documentId:s}),C.jsx(k.Text,{size:1,children:te})]})}):null}function Ct(e,t){const n=v.useDocumentPreviewStore(),[s,i]=w.useState({});return w.useEffect((()=>{if(!t)return;const s=function(e,t,n,s){const i=(e=>!0===e.liveEdit)(t)?V.of({snapshot:null}):e.observeForPreview({_type:"reference",_ref:v.getDraftId(n)},t),l=e.observeForPreview({_type:"reference",_ref:v.getPublishedId(n)},t);return V.combineLatest([i,l]).pipe(O.map((e=>{let[t,n]=e;return{draft:t.snapshot?f({title:s},t.snapshot||{}):null,isLoading:!1,published:n.snapshot?f({title:s},n.snapshot||{}):null}})),O.startWith({draft:null,isLoading:!0,published:null}))}(n,t,e,"").subscribe((e=>{i(e)}));return()=>{null==s||s.unsubscribe()}}),[n,t,e]),s}const kt=H.default(k.ElementQuery)(h||(h=g(["\n .date-small {\n display: inline;\n }\n .date-medium {\n display: none;\n }\n .date-large {\n display: none;\n }\n\n &[data-eq-min~='1'] {\n .date-small {\n display: none;\n }\n .date-medium {\n display: inline;\n }\n .date-large {\n display: none;\n }\n }\n\n &[data-eq-min~='2'] {\n .date-small {\n display: none;\n }\n .date-medium {\n display: none;\n }\n .date-large {\n display: inline;\n }\n }\n"]))),wt=e=>{const{onClose:t,schedule:n}=e,{updateSchedule:s}=tt(),{formData:i,isDirty:l,onFormChange:a}=ot(n),o=w.useCallback((()=>{(null==i?void 0:i.date)&&s({date:i.date,scheduleId:n.id}).then(t)}),[n.id,s,t,null==i?void 0:i.date]);return C.jsx(k.Dialog,{footer:C.jsx(k.Box,{paddingX:4,paddingY:3,children:C.jsx(Q,{buttonText:"Update",disabled:!l,onAction:o,onComplete:t,tone:"primary"})}),header:C.jsx(ve,{title:"Edit schedule"}),id:"time-zone",onClose:t,width:1,children:C.jsx(k.Box,{padding:4,children:C.jsx(He,{onChange:a,value:i})})})};function St(e){const{visible:t,show:n,hide:s}=fe();return{DialogScheduleEdit:t?wt:null,dialogProps:{onClose:s,schedule:e,visible:t},dialogScheduleEditShow:n,hide:s}}const Mt=e=>{const{currentUser:t,hasPermission:n,icon:s,onClick:i,permissionsOperationLabel:l,title:a,tone:o}=e;return C.jsx(k.Tooltip,{content:C.jsx(k.Box,{paddingX:2,paddingY:1,children:C.jsx(v.InsufficientPermissionsMessage,{currentUser:t,operationLabel:l})}),disabled:n,placement:"left",portal:!0,children:C.jsx("div",{children:C.jsx(k.MenuItem,{disabled:!n,icon:s,onClick:i,text:a,tone:o})})})},Tt=e=>{const{actions:t,onDelete:n,onEdit:s,schedule:i,schemaType:l}=e,a=dt(i),o=v.useCurrentUser(),[r,d]=v.useDocumentPairPermissions({id:a.documentId,type:null==l?void 0:l.name,permission:"publish"}),{deleteSchedule:c,publishSchedule:u}=tt(),h=!d&&!(null==r?void 0:r.granted),x=()=>{c({schedule:i}).then((()=>null==n?void 0:n()))};return o?C.jsxs(C.Fragment,{children:[(null==t?void 0:t.edit)&&C.jsx(Mt,{currentUser:o,hasPermission:!h,icon:b.CalendarIcon,onClick:()=>{null==s||s()},permissionsOperationLabel:"edit schedules",title:"Edit schedule"}),(null==t?void 0:t.execute)&&C.jsx(Mt,{currentUser:o,hasPermission:!h,icon:b.PublishIcon,onClick:()=>{u({schedule:i})},permissionsOperationLabel:"execute schedules",title:"Publish now"}),(null==t?void 0:t.delete)&&C.jsx(Mt,{currentUser:o,hasPermission:!h,icon:b.TrashIcon,onClick:x,permissionsOperationLabel:"delete schedules",title:"Delete schedule",tone:"critical"}),(null==t?void 0:t.clear)&&C.jsx(Mt,{currentUser:o,hasPermission:!h,icon:b.CheckmarkCircleIcon,onClick:x,permissionsOperationLabel:"delete schedules",title:"Clear completed schedule"})]}):null},Dt=e=>{const{actions:t,onDelete:n,onEdit:s,schedule:i,schemaType:l}=e;return C.jsx(k.MenuButton,{button:C.jsx(k.Button,{icon:b.EllipsisVerticalIcon,mode:"bleed",paddingX:2,paddingY:3,tone:"default"}),id:"contextMenu",menu:C.jsx(k.Menu,{children:C.jsx(Tt,{actions:t,onDelete:n,onEdit:s,schedule:i,schemaType:l})}),placement:"left",popover:{portal:!0,tone:"default"}})};function Lt(e){let{schedule:t,updateValidation:n}=e;const s=ut(t),i=ct(t);return i&&(null==s?void 0:s.name)?C.jsx(It,{id:i,schemaName:s.name,updateValidation:n}):null}function It(e){let{id:t,schemaName:n,updateValidation:s}=e;const[i,l]=w.useState(!1);return w.useEffect((()=>{const e=setTimeout((()=>{l(!0)}),1500);return()=>{clearTimeout(e)}}),[]),i?C.jsx(Bt,{id:t,schemaName:n,updateValidation:s}):null}function Bt(e){let{id:t,schemaName:n,updateValidation:s}=e;const i=v.useValidationStatus(t,n);return w.useEffect((()=>{i.isValidating||s(i)}),[s,i]),null}const At=e=>{const{date:t,useElementQueries:n}=e,{formatDateTz:s}=he(),i=L.formatDistance(t,new Date,{addSuffix:!0}),l=s({date:t,format:se.LARGE}),a=s({date:t,format:se.MEDIUM}),o=s({date:t,format:se.SMALL});return C.jsx(k.Text,{size:1,textOverflow:"ellipsis",children:C.jsx(k.Tooltip,{content:C.jsx(k.Box,{padding:2,children:C.jsx(k.Text,{muted:!0,size:1,children:i})}),portal:!0,children:C.jsx("span",{children:n?C.jsxs(C.Fragment,{children:[C.jsx("span",{className:"date-small",children:o}),C.jsx("span",{className:"date-medium",children:a}),C.jsx("span",{className:"date-large",children:l})]}):l})})})};function Et(e){let{time:t}=e;const n=v.useTimeAgo(t);return C.jsxs("span",{title:n,children:[n," ago"]})}const zt=e=>{let{document:t}=e;return C.jsx(k.Tooltip,{content:C.jsx(k.Box,{padding:2,children:C.jsx(k.Text,{size:1,children:t?C.jsxs(C.Fragment,{children:["Edited ",(null==t?void 0:t._updatedAt)&&C.jsx(Et,{time:null==t?void 0:t._updatedAt})]}):C.jsx(C.Fragment,{children:"No unpublished edits"})})}),portal:!0,children:C.jsx(v.TextWithTone,{tone:"caution",dimmed:!t,muted:!t,size:1,children:C.jsx(b.EditIcon,{})})})},Vt=e=>{let{document:t}=e;return C.jsx(k.Tooltip,{content:C.jsx(k.Box,{padding:2,children:C.jsx(k.Text,{size:1,children:t?C.jsxs(C.Fragment,{children:["Published ",t._updatedAt&&C.jsx(Et,{time:t._updatedAt})]}):C.jsx(C.Fragment,{children:"Not published"})})}),portal:!0,children:C.jsx(v.TextWithTone,{tone:"positive",dimmed:!t,muted:!t,size:1,children:C.jsx(b.PublishIcon,{})})})},Ot={portal:!0,constrainSize:!0,preventOverflow:!0,tone:"default",width:0},Ft=e=>{const{stateReason:t}=e;return C.jsx(k.MenuButton,{id:"stateReason",button:C.jsx(k.Button,{title:"Schedule failed",mode:"bleed","data-testid":"schedule-validation-list-button",icon:b.ErrorOutlineIcon,tone:"critical"}),menu:C.jsx(k.Menu,{padding:1,children:C.jsxs(k.Container,{padding:2,width:0,children:[C.jsx(k.Text,{size:1,children:"This schedule failed to run."}),C.jsxs(k.Flex,{gap:3,marginTop:4,padding:1,children:[C.jsx(k.Text,{size:1,style:{color:P.red[700].hex},children:C.jsx(b.ErrorOutlineIcon,{})}),C.jsx(k.Text,{size:1,style:{color:P.red[700].hex},weight:"medium",children:t})]})]})}),placement:"bottom-end",popover:Ot})},Pt=e=>{const{id:t}=e;return C.jsx(v.UserAvatar,{user:t,withTooltip:!0})},Wt=e=>{const{children:t,contextMenu:n,linkComponent:s,onClick:i,previewState:l,publishedDocumentId:a,schedule:o,schemaType:r,useElementQueries:d}=e,[c,u]=w.useState(ht),{validation:h}=c,{hasError:x,validationTone:p}=xt(h),{formatDateTz:m}=he(),f=Ye(o),j=f?new Date(f):null;return C.jsx(k.Card,{padding:1,radius:2,shadow:1,tone:p,children:C.jsxs(k.Flex,{align:"center",gap:1,justify:"space-between",children:[C.jsx(k.Card,{__unstable_focusRing:!0,as:s||void 0,"data-as":i||s?"a":void 0,flex:1,onClick:i,padding:1,radius:2,tabIndex:0,tone:p,children:C.jsxs(k.Flex,{align:"center",gap:3,justify:"flex-start",paddingLeft:t?0:[1,2],children:[t&&C.jsx(k.Box,{style:{flexBasis:"auto",flexGrow:1},children:t}),"unpublish"===o.action&&C.jsx(k.Flex,{style:{flexShrink:0},children:C.jsx(k.Badge,{fontSize:0,mode:"outline",tone:K[o.action].badgeTone,children:o.action})}),C.jsx(k.Box,{display:["block","none"],style:{flexShrink:0,width:"90px"},children:C.jsx(k.Stack,{space:2,children:j?C.jsxs(C.Fragment,{children:[C.jsx(k.Text,{size:1,children:m({date:j,format:"dd/MM/yyyy"})}),C.jsx(k.Text,{size:1,children:m({date:j,format:"p"})})]}):C.jsx(k.Text,{muted:!0,size:1,children:C.jsx("em",{children:"No date specified"})})})}),C.jsx(k.Box,{display:["none","block"],style:{flexShrink:0,maxWidth:"250px",width:t?"35%":"auto"},children:j?C.jsx(At,{date:j,useElementQueries:d}):C.jsx(k.Text,{muted:!0,size:1,children:C.jsx("em",{children:"No date specified"})})}),!t&&C.jsx(k.Box,{style:{visibility:"hidden"},children:C.jsx(v.SanityDefaultPreview,{isPlaceholder:!0})}),C.jsxs(k.Flex,{align:"center",style:{flexShrink:0,marginLeft:"auto"},children:[C.jsx(k.Box,{display:["none","none","block"],marginX:3,style:{flexShrink:0},children:C.jsx(Pt,{id:null==o?void 0:o.author})}),C.jsx(k.Box,{display:["none","block"],marginX:[2,2,3],style:{flexShrink:0},children:C.jsxs(k.Inline,{space:4,children:[C.jsx(Vt,{document:null==l?void 0:l.published}),C.jsx(zt,{document:null==l?void 0:l.draft})]})})]})]})}),C.jsxs(k.Flex,{justify:"center",style:{width:"38px"},children:["scheduled"===o.state&&C.jsxs(k.Box,{children:[C.jsx(Lt,{schedule:o,updateValidation:u}),C.jsx(bt,{markers:h,type:r,documentId:a,menuHeader:C.jsx(k.Box,{padding:2,children:C.jsx(k.Text,{size:1,children:x?te:"This document has validation warnings."})})})]}),"cancelled"===o.state&&C.jsx(Ft,{stateReason:o.stateReason})]}),"cancelled"===o.state&&C.jsx(Ft,{stateReason:o.stateReason}),n&&C.jsx(k.Box,{style:{flexShrink:0},children:n})]})})},Rt=e=>{const{schedule:t,schemaType:n}=e,{DialogScheduleEdit:s,dialogProps:i,dialogScheduleEditShow:l}=St(t),{onComplete:a}=function(){const e=w.useContext(qe);if(void 0===e)throw new Error("useDocumentActionProps must be used within a DocumentActionPropsProvider");return e}(),o=w.useMemo((()=>ct(t)),[t]);return C.jsxs(C.Fragment,{children:[s&&C.jsx(s,f({},i)),C.jsx(Wt,{contextMenu:C.jsx(Dt,{actions:{delete:!0,edit:!0},onDelete:a,onEdit:l,schedule:t,schemaType:n}),onClick:l,publishedDocumentId:o,schedule:t,schemaType:n})]})},Nt=e=>{const{onDelete:t,schedule:n}=e,{deleteSchedule:s}=tt();return C.jsx(k.MenuButton,{button:C.jsx(k.Button,{icon:b.EllipsisVerticalIcon,mode:"bleed",paddingX:2,paddingY:3,tone:"default"}),id:"contextMenu",menu:C.jsx(k.Menu,{children:C.jsx(k.MenuItem,{icon:b.TrashIcon,onClick:()=>{s({schedule:n}).then((()=>null==t?void 0:t()))},text:"Delete schedule",tone:"critical"})}),placement:"left",popover:{portal:!0,tone:"default"}})},Ut=e=>{let{schedule:t}=e;return C.jsx(Wt,{contextMenu:C.jsx(Nt,{schedule:t}),schedule:t,useElementQueries:!0,children:C.jsx(v.SanityDefaultPreview,{icon:b.UnknownIcon,layout:"default",subtitle:C.jsx("em",{children:"It may have been deleted"}),title:C.jsx("em",{style:{color:P.red[600].hex},children:"Document not found"})})})},Ht=e=>{const{previewState:t,schedule:n,schemaType:s}=e,i=t.draft||t.published,l="succeeded"===n.state,a="scheduled"===n.state,{DialogScheduleEdit:o,dialogProps:r,dialogScheduleEditShow:d}=St(n),c=rt(null==i?void 0:i._id),u=w.useMemo((()=>w.forwardRef(((e,t)=>C.jsx(y.IntentLink,f(f({},e),{},{intent:"edit",params:{type:s.name,id:i&&v.getPublishedId(null==i?void 0:i._id)},ref:t}))))),[s,i]);return C.jsxs(C.Fragment,{children:[o&&C.jsx(o,f({},r)),C.jsx(Wt,{contextMenu:C.jsx(Dt,{actions:{clear:l,delete:!l,edit:a,execute:a},onEdit:d,schedule:n,schemaType:s}),linkComponent:u,previewState:t,publishedDocumentId:c,schedule:n,schemaType:s,useElementQueries:!0,children:t.isLoading?C.jsx(v.SanityDefaultPreview,{icon:null==s?void 0:s.icon,isPlaceholder:t.isLoading,layout:"default"}):C.jsx(v.Preview,{layout:"default",schemaType:s,value:i})})]})},Zt=e=>{const{schedule:t,type:n}=e,s=dt(t),i=ut(t),l=Ct(null==s?void 0:s.documentId,i),a=!(l.draft||l.published)&&!l.isLoading,o=w.useMemo((()=>!i||a?C.jsx(Ut,{schedule:t}):"document"===n?C.jsx(Rt,{schedule:t,schemaType:i}):"tool"===n?C.jsx(Ht,{previewState:l,schedule:t,schemaType:i}):null),[a,n,l,t,i]);return C.jsx(kt,{children:o})},qt=e=>{const{schedules:t}=e;return C.jsx(k.Stack,{space:4,children:0===t.length?C.jsx(k.Box,{children:C.jsx(k.Text,{size:1,children:"No schedules"})}):C.jsx(k.Stack,{space:2,children:t.map((e=>C.jsx(Zt,{schedule:e,type:"document"},e.id)))})})},_t=ae("ScheduleAction"),Xt=e=>{const{draft:t,id:n,liveEdit:s,onComplete:i,published:l,type:a}=e,o=v.useCurrentUser(),[r,d]=v.useDocumentPairPermissions({id:n,type:a,permission:"publish"}),{createSchedule:c}=tt(),u=Ge(),[h,x]=w.useState(!1),{formData:p,onFormChange:m}=ot(),{error:f,isInitialLoading:j,schedules:g}=at({documentId:n,state:"scheduled"});_t("schedules",g);const y=g&&g.length>0,S=null!==t||null!==l,M=!d&&!(null==r?void 0:r.granted),T=w.useCallback((()=>{x(!0)}),[]),D=w.useCallback((()=>{(null==p?void 0:p.date)&&c({date:p.date,documentId:n}).then(i)}),[i,c,n,null==p?void 0:p.date]),L=y?"Edit Schedule":"Schedule";if(M)return{disabled:!0,icon:b.CalendarIcon,label:L,title:C.jsx(v.InsufficientPermissionsMessage,{currentUser:o,operationLabel:"edit schedules"})};let I,B="This document doesn't exist yet";return S&&(B=null),j&&(B="Loading schedules"),s&&(B="Live Edit is enabled for this content type and publishing happens automatically as you make changes"),I=!1===u?{content:C.jsx(k.Text,{size:1,children:ne}),header:"Feature not available",onClose:i,type:"dialog"}:{content:f?C.jsx(Ze,{description:"More information in the developer console.",title:"Something went wrong, unable to retrieve schedules."}):C.jsx(_e,{value:e,children:y?C.jsx(qt,{schedules:g}):C.jsx(He,{onChange:m,value:p,children:C.jsx(vt,{id:n,schemaType:a})})}),footer:!y&&C.jsx(Q,{buttonText:"Schedule",disabled:!(null==p?void 0:p.date),icon:b.ClockIcon,onAction:D,onComplete:i,tone:"primary"}),header:C.jsx(ve,{title:L}),onClose:i,type:"dialog"},{dialog:h&&I,disabled:j||!S||s,label:L,icon:b.CalendarIcon,onHandle:T,title:B&&C.jsx(k.Box,{style:{maxWidth:"315px"},children:B})}};function Gt(e){const t=e.findIndex((e=>"publish"===e.action));return t<0?[Xt,...e]:[...e.slice(0,t+1),Xt,...e.slice(t+1)]}const Yt=ae("ScheduledBadge"),Qt=e=>{const{schedules:t}=at({documentId:e.id,state:"scheduled"});Yt("schedules",t);const n=null==t?void 0:t[0];if(!n||!n.executeAt)return null;const s=L.format(new Date(n.executeAt),se.LARGE);return{color:K[n.action].badgeColor,label:"Scheduled",title:"".concat(K[n.action].actionName," on ").concat(s," (local time)")}};function Jt(e){return[...e,Qt]}const Kt=w.createContext(void 0),$t=[];function en(e){let{children:t,value:n}=e;const[s,i]=w.useState(n.sortBy||"executeAt"),{utcToCurrentZoneDate:l}=he(),a=w.useCallback((e=>function(t){const n=Ye(t);if(!n)return!1;const s=new Date(n),i=l(s);return L.isSameDay(i,e)}),[l]),o=w.useCallback((e=>function(t){return t.state===e}),[]),r=w.useMemo((()=>n.schedules.filter((e=>n.selectedDate?a(n.selectedDate)(e):o(n.scheduleState)(e))).sort(((e,t)=>{if("createdAt"===s)return e[s]<t[s]?1:-1;if("executeAt"===s){return Qe({reverseOrder:!("scheduled"===n.scheduleState||n.selectedDate)})(e,t)}return 1}))||[]),[o,n.schedules,n.scheduleState,n.selectedDate,s,a]),d=w.useCallback((e=>n.schedules.filter(a(e)).sort(Qe())),[n.schedules,a]);return C.jsx(Kt.Provider,{value:{activeSchedules:r,schedules:n.schedules||$t,schedulesByDate:d,scheduleState:n.scheduleState,selectedDate:n.selectedDate,setSortBy:i,sortBy:s},children:t})}function tn(){const e=w.useContext(Kt);if(void 0===e)throw new Error("useSchedules must be used within a SchedulesProvider");return e}const nn=()=>!1===Ge()?C.jsx(k.Card,{padding:4,tone:"caution",children:C.jsxs(k.Flex,{align:"center",gap:3,children:[C.jsx(k.Text,{size:2,children:C.jsx(b.InfoOutlineIcon,{})}),C.jsx(k.Text,{size:1,children:ne})]})}):null;function sn(e,t){return w.useMemo((()=>e.filter((e=>e.state===t))),[e,t])}const ln=e=>{const{selected:t,schedules:n,state:s}=e,i=sn(n,s).length,l=i>0,a="cancelled"===s,{href:o,onClick:r}=y.useStateLink({state:{state:s}});return C.jsx(k.Button,{as:"a",href:o,mode:"bleed",onClick:r,selected:t,tone:a?"critical":"default",children:C.jsxs(k.Inline,{space:2,children:[C.jsx(k.Text,{size:2,weight:"medium",children:$[s].title}),l&&C.jsx(k.Text,{size:1,children:i})]})})},an=e=>{const{onClearDate:t,selectedDate:n}=e,{navigate:s}=y.useRouter(),{schedules:i,scheduleState:l}=tn(),a=e=>{s(e)},o=sn(i,l);return C.jsxs(C.Fragment,{children:[C.jsxs(k.Box,{display:["block","block","none"],children:[n&&C.jsx(k.Button,{fontSize:2,iconRight:b.CloseIcon,onClick:t,text:L.format(n,"d MMMM yyyy"),tone:"primary"}),l&&C.jsx(k.MenuButton,{button:C.jsx(k.Button,{fontSize:2,iconRight:b.SelectIcon,mode:"ghost",text:"