sanity-plugin-dashboard-widget-document-list
Version:
2 lines (1 loc) • 2.9 kB
JavaScript
import{jsx as e,jsxs as t}from"react/jsx-runtime";import{DashboardWidgetContainer as r}from"@sanity/dashboard";import{Card as i,Flex as n,Spinner as o,Stack as s}from"@sanity/ui";import a from"lodash/intersection.js";import{useState as d,useMemo as c,useEffect as m}from"react";import{useClient as u,useSchema as l,IntentButton as p,getPublishedId as y,Preview as f}from"sanity";import h from"lodash/uniqBy";import{of as g}from"rxjs";import{switchMap as b,tap as w,delay as _,mergeMap as $}from"rxjs/operators";const v=e=>`drafts.${e._id}`;function x(e,t,r){return r.listen(e,t,{events:["welcome","mutation"],includeResult:!1,visibility:"query"}).pipe(b((i=>g(1).pipe("welcome"===i.type?w():_(1e3),$((()=>r.fetch(e,t).then((e=>function(e,t){if(!e)return Promise.resolve([]);const r=Array.isArray(e)?e:[e],i=r.filter((e=>!e._id.startsWith("drafts."))).map(v);return t.fetch("*[_id in $ids]",{ids:i}).then((e=>{const t=r.map((t=>e.find((e=>e._id===v(t)))||t));return h(t,"_id")})).catch((e=>{throw new Error(`Problems fetching docs ${i}. Error: ${e.message}`)}))}(e,r))).catch((r=>{throw r.message.startsWith("Problems fetching docs")?r:new Error(`Query failed ${e} and ${JSON.stringify(t)}. Error: ${r.message}`)}))))))))}const P={title:"Last created",order:"_createdAt desc",limit:10,queryParams:{},showCreateButton:!0,apiVersion:"v1"};function j(y){const{query:f,limit:h,apiVersion:g,queryParams:b,types:w,order:_,title:$,showCreateButton:v,createButtonText:j}={...P,...y},[B,C]=d(),[E,Q]=d(!0),[A,T]=d(),V=u({apiVersion:g}),N=l(),{assembledQuery:S,params:W}=c((()=>{if(f)return{assembledQuery:f,params:b};const e=N.getTypeNames().filter((e=>{var t;const r=N.get(e);return"document"===(null==(t=null==r?void 0:r.type)?void 0:t.name)}));return{assembledQuery:`*[_type in $types] | order(${_}) [0...${2*h}]`,params:{types:w?a(w,e):e}}}),[N,f,b,_,h,w]);return m((()=>{if(!S)return;const e=x(S,W,V).subscribe({next:e=>{C(e.slice(0,h)),Q(!1)},error:e=>{T(e),Q(!1)}});return()=>{e.unsubscribe()}}),[h,V,S,W]),e(r,{header:$,footer:w&&1===w.length&&v&&e(p,{mode:"bleed",style:{width:"100%"},paddingY:4,tone:"primary",type:"button",intent:"create",params:{type:w[0]},text:j||`Create new ${w[0]}`}),children:t(i,{children:[A&&e("div",{children:A.message}),!A&&E&&e(i,{padding:4,children:e(n,{justify:"center",children:e(o,{muted:!0})})}),!A&&!B&&!E&&e("div",{children:"Could not locate any documents :/"}),e(s,{space:2,children:B&&B.map((t=>e(q,{doc:t},t._id)))})]})})}function q({doc:t}){const r=l().get(t._type);return e(i,{flex:1,children:e(p,{intent:"edit",mode:"bleed",tooltipProps:{},params:{type:t._type,id:y(t._id)},style:{width:"100%"},children:r?e(f,{layout:"default",schemaType:r,value:t},t._id):"Schema-type missing"})})}function B(t){return{name:"document-list-widget",component:function(){return e(j,{...t})},layout:t.layout}}export{B as documentListWidget};//# sourceMappingURL=index.js.map