sanity-plugin-dashboard-widget-document-list 0.0.13 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License
1
+ MIT License
2
2
 
3
- Copyright (c) 2019, Sanity.io <hello@sanity.io>
3
+ Copyright (c) 2022 Sanity.io
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to
7
- deal in the Software without restriction, including without limitation the
8
- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9
- sell copies of the Software, and to permit persons to whom the Software is
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
10
  furnished to do so, subject to the following conditions:
11
11
 
12
- * The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
14
 
15
15
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
16
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
17
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21
- IN THE SOFTWARE.
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,101 +1,112 @@
1
- # dashboard-widget-document-list
2
- Dashboard widget for the Sanity Content Studio which displays a list of documents
1
+ # sanity-plugin-dashboard-widget-document-list
3
2
 
3
+ >This is a **Sanity Studio v3** plugin.
4
+ > For the v2 version, please refer to the [v2-branch](https://github.com/sanity-io/dashboard-widget-document-list/tree/studio-v2).
4
5
 
6
+ ## What is it?
5
7
 
6
- ## Usage
7
- Assuming you already have a functional Dashboard in your Sanity Content Studio.
8
+ Dashboard widget for the Sanity Content Studio which displays a list of documents.
9
+
10
+ ## Install
11
+
12
+ ```
13
+ npm install --save sanity-plugin-dashboard-widget-document-list
14
+ ```
8
15
 
9
- 1. Install this widget in your Studio folder like so:
16
+ or
10
17
 
11
18
  ```
12
- sanity install dashboard-widget-document-list
19
+ yarn add sanity-plugin-dashboard-widget-document-list
13
20
  ```
14
21
 
15
- 2. Update your `src/dashboardConfig.js` file by adding `{name: 'document-list'}` to the `widgets` array
16
- 3. Restart your Studio
22
+ Ensure that you have followed install and usage instructions for @sanity/dashboard.
23
+
24
+ ## Usage
25
+
26
+ Add dashboard-widget-document-list as a widget to @sanity/dashboard plugin in sanity.config.ts (or .js):
27
+
28
+ ```js
29
+ import { dashboardTool } from "@sanity/dashboard";
30
+ import { documentListWidget } from "sanity-plugin-dashboard-widget-document-list";
31
+
32
+ export default defineConfig({
33
+ // ...
34
+ plugins: [
35
+ dashboardTool({
36
+ widgets: [
37
+ documentListWidget(),
38
+ ],
39
+ }
40
+ ),
41
+ ]
42
+ })
43
+ ```
17
44
 
18
45
  *Note*: If a document in the result (as returned by the backend) has a draft, that draft is rendered instead of the published document.
19
46
 
20
- There are some options available:
47
+ ## Options
48
+
49
+ There are some options available, as specified by [DocumentListConfig](src/DocumentList.tsx):
21
50
 
22
51
  ### `title` (string)
23
52
  Widget title
24
53
 
25
54
  ```js
26
- {
27
- name: 'document-list',
28
- options: {
55
+ documentListWidget({
29
56
  title: 'Some documents'
30
- }
31
- }
57
+ })
32
58
  ```
33
59
 
34
60
  ### `order` (string)
35
61
  Field and direction to order by when docs are rendered
36
62
 
37
63
  ```js
38
- {
39
- name: 'document-list',
40
- options: {
64
+ documentListWidget({
41
65
  title: 'Last edited',
42
66
  order: '_updatedAt desc'
43
- }
44
- }
67
+ })
45
68
  ```
46
69
 
47
70
  ### `limit` (number)
48
71
  Number of docs rendered
49
72
 
50
73
  ```js
51
- {
52
- name: 'document-list',
53
- options: {
74
+ documentListWidget({
54
75
  title: 'Last edited',
55
76
  order: '_updatedAt desc',
56
77
  limit: 3
57
- }
58
- }
78
+ })
59
79
  ```
60
80
 
61
81
  ### `types` (array)
62
82
  Array of strings signifying which document (schema) types are fetched
63
83
 
64
84
  ```js
65
- {
66
- name: 'document-list',
67
- options: {
85
+ documentListWidget({
68
86
  title: 'Last edited',
69
87
  order: '_updatedAt desc',
70
88
  types: ['book', 'author']
71
- }
72
- }
89
+ })
73
90
  ```
74
91
 
75
92
  ### `query` (string) and `params` (object)
76
93
  Customized GROQ query with params for maximum control. If you use the query option, the `types`, `order`, and `limit` options will cease to function. You're on your own.
77
94
 
78
95
  ```js
79
- {
80
- name: 'document-list',
81
- options: {
96
+ documentListWidget({
82
97
  title: 'Published books by title',
83
98
  query: '*[_type == "book" && published == true] | order(title asc) [0...10]'
84
- }
85
- }
99
+ })
86
100
  ```
87
101
 
88
102
  ```js
89
- {
90
- name: 'document-list',
91
- options: {
103
+ documentListWidget({
92
104
  title: 'My favorite documents',
93
105
  query: '*[_id in $ids]',
94
106
  params: {
95
107
  ids: ['ab2', 'c5z', '654']
96
108
  }
97
- }
98
- }
109
+ })
99
110
  ```
100
111
 
101
112
  ### `createButtonText` (string)
@@ -103,14 +114,11 @@ Customized GROQ query with params for maximum control. If you use the query opti
103
114
  You can override the button default button text (`Create new ${types[0]}`) by setting `createButtonText` to a string of your choice. This doesn't support dynamic variables.
104
115
 
105
116
  ```js
106
- {
107
- name: 'document-list',
108
- options: {
117
+ documentListWidget({
109
118
  title: 'Blog posts',
110
119
  query: '*[_type == "post"]',
111
120
  createButtonText: 'Create new blog post'
112
- }
113
- }
121
+ })
114
122
  ```
115
123
 
116
124
  ### `showCreateButton` (boolean)
@@ -118,10 +126,35 @@ You can override the button default button text (`Create new ${types[0]}`) by se
118
126
  You can disable the create button altogether by passing a `showCreateButton` boolean:
119
127
 
120
128
  ```js
121
- {
122
- name: 'document-list',
123
- options: {
129
+ documentListWidget({
124
130
  showCreateButton: false
125
- }
126
- }
131
+ })
127
132
  ```
133
+
134
+ ### Widget size
135
+
136
+ You can change the width of the plugin using `layout.width`:
137
+ ```js
138
+ documentListWidget({
139
+ layout: { width: "small" }
140
+ })
141
+ ```
142
+
143
+ ## License
144
+
145
+ MIT-licensed. See LICENSE.
146
+
147
+ ## Develop & test
148
+
149
+ This plugin uses [@sanity/plugin-kit](https://github.com/sanity-io/plugin-kit)
150
+ with default configuration for build & watch scripts.
151
+
152
+ See [Testing a plugin in Sanity Studio](https://github.com/sanity-io/plugin-kit#testing-a-plugin-in-sanity-studio)
153
+ on how to run this plugin with hotreload in the studio.
154
+
155
+ ### Release new version
156
+
157
+ Run ["CI & Release" workflow](https://github.com/sanity-io/dashboard-widget-document-list/actions/workflows/main.yml).
158
+ Make sure to select the main branch and check "Release new version".
159
+
160
+ Semantic release will only release on configured branches, so it is safe to run release on any branch.
@@ -0,0 +1,2 @@
1
+ function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}import{jsx as n,jsxs as i}from"react/jsx-runtime";import{useState as o,useMemo as c,useEffect as a}from"react";import{useClient as s,useSchema as d,IntentButton as u,getPublishedId as p,SanityPreview as l}from"sanity";import{intersection as m}from"lodash";import{of as y}from"rxjs";import{switchMap as f,tap as h,delay as b,mergeMap as g}from"rxjs/operators";import w from"lodash/uniqBy";import{Card as O,Flex as j,Spinner as v,Stack as P}from"@sanity/ui";import{DashboardWidgetContainer as _}from"@sanity/dashboard";const x=e=>"drafts.".concat(e._id);function E(e,t,r){return r.listen(e,t,{events:["welcome","mutation"],includeResult:!1,visibility:"query"}).pipe(f((n=>y(1).pipe("welcome"===n.type?h():b(1e3),g((()=>r.fetch(e,t).then((e=>function(e,t){if(!e)return Promise.resolve([]);const r=Array.isArray(e)?e:[e],n=r.filter((e=>!e._id.startsWith("drafts."))).map(x);return t.fetch("*[_id in $ids]",{ids:n}).then((e=>{const t=r.map((t=>e.find((e=>e._id===x(t)))||t));return w(t,"_id")})).catch((e=>{throw new Error("Problems fetching docs ".concat(n,". Error: ").concat(e.message))}))}(e,r))).catch((r=>{if(r.message.startsWith("Problems fetching docs"))throw r;throw new Error("Query failed ".concat(e," and ").concat(JSON.stringify(t),". Error: ").concat(r.message))}))))))))}const q={title:"Last created",order:"_createdAt desc",limit:10,queryParams:{},showCreateButton:!0,apiVersion:"v1"};function B(e){const{query:r,limit:p,apiVersion:l,queryParams:y,types:f,order:h,title:b,showCreateButton:g,createButtonText:w}=t(t({},q),e),[x,B]=o(),[D,Q]=o(!0),[S,A]=o(),T=s({apiVersion:l}),V=d(),{assembledQuery:N,params:W}=c((()=>{if(r)return{assembledQuery:r,params:y};const e=V.getTypeNames().filter((e=>{var t;const r=V.get(e);return"document"===(null==(t=null==r?void 0:r.type)?void 0:t.name)}));return{assembledQuery:"*[_type in $types] | order(".concat(h,") [0...").concat(2*p,"]"),params:{types:f?m(f,e):e}}}),[V,r,y,h,p,f]);return a((()=>{if(!N)return;const e=E(N,W,T).subscribe({next:e=>{B(e.slice(0,p)),Q(!1)},error:e=>{A(e),Q(!1)}});return()=>{e.unsubscribe()}}),[p,T,N,W]),n(_,{header:b,footer:f&&1===f.length&&g&&n(u,{mode:"bleed",style:{width:"100%"},paddingX:2,paddingY:4,tone:"primary",type:"button",intent:"create",params:{type:f[0]},text:w||"Create new ".concat(f[0])}),children:i(O,{children:[S&&n("div",{children:S.message}),!S&&D&&n(O,{padding:4,children:n(j,{justify:"center",children:n(v,{muted:!0})})}),!S&&!x&&!D&&n("div",{children:"Could not locate any documents :/"}),n(P,{space:2,children:x&&x.map((e=>n(C,{doc:e},e._id)))})]})})}function C(e){let{doc:t}=e;const r=d().get(t._type);return n(O,{flex:1,children:n(u,{intent:"edit",mode:"bleed",padding:1,radius:0,params:{type:t._type,id:p(t._id)},style:{width:"100%"},children:r?n(l,{layout:"default",schemaType:r,value:t},t._id):"Schema-type missing"})})}function D(e){return{name:"document-list-widget",component:function(){return n(B,t({},e))},layout:e.layout}}export{D as documentListWidget};
2
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":["../src/sanityConnector.ts","../src/DocumentList.tsx","../src/plugin.tsx"],"sourcesContent":["import {Observable, of as observableOf} from 'rxjs'\nimport {delay, mergeMap, switchMap, tap} from 'rxjs/operators'\nimport uniqBy from 'lodash/uniqBy'\nimport {SanityClient} from '@sanity/client'\nimport {SanityDocument} from 'sanity'\n\nconst draftId = (nonDraftDoc: SanityDocument) => `drafts.${nonDraftDoc._id}`\n\nfunction prepareDocumentList(\n incoming: SanityDocument | SanityDocument[],\n client: SanityClient\n): Promise<SanityDocument[]> {\n if (!incoming) {\n return Promise.resolve([])\n }\n const documents = Array.isArray(incoming) ? incoming : [incoming]\n\n const ids = documents.filter((doc) => !doc._id.startsWith('drafts.')).map(draftId)\n\n return client\n .fetch<SanityDocument[]>('*[_id in $ids]', {ids})\n .then((drafts) => {\n const outgoing = documents.map((doc) => {\n const foundDraft = drafts.find((draft) => draft._id === draftId(doc))\n return foundDraft || doc\n })\n return uniqBy(outgoing, '_id')\n })\n .catch((error) => {\n throw new Error(`Problems fetching docs ${ids}. Error: ${error.message}`)\n })\n}\n\nexport function getSubscription(\n query: string,\n params: Record<string, any>,\n client: SanityClient\n): Observable<SanityDocument[]> {\n return client\n .listen(query, params, {\n events: ['welcome', 'mutation'],\n includeResult: false,\n visibility: 'query',\n })\n .pipe(\n switchMap((event) => {\n return observableOf(1).pipe(\n event.type === 'welcome' ? tap() : delay(1000),\n mergeMap(() =>\n client\n .fetch(query, params)\n .then((incoming) => {\n return prepareDocumentList(incoming, client)\n })\n .catch((error) => {\n if (error.message.startsWith('Problems fetching docs')) {\n throw error\n }\n throw new Error(\n `Query failed ${query} and ${JSON.stringify(params)}. Error: ${error.message}`\n )\n })\n )\n )\n })\n )\n}\n","import React, {useEffect, useMemo, useState} from 'react'\nimport {getPublishedId, useClient, useSchema} from 'sanity'\nimport {intersection} from 'lodash'\nimport {getSubscription} from './sanityConnector'\nimport {SanityDocument, IntentButton, SanityPreview} from 'sanity'\nimport {Card, Flex, Spinner, Stack} from '@sanity/ui'\nimport {DashboardWidgetContainer} from '@sanity/dashboard'\n\nexport interface DocumentListConfig {\n title?: string\n types?: string[]\n query?: string\n queryParams?: Record<string, any>\n order?: string\n limit?: number\n showCreateButton?: boolean\n createButtonText?: string\n apiVersion?: string\n}\n\nconst defaultProps = {\n title: 'Last created',\n order: '_createdAt desc',\n limit: 10,\n queryParams: {},\n showCreateButton: true,\n apiVersion: 'v1',\n}\n\nexport function DocumentList(props: DocumentListConfig) {\n const {\n query,\n limit,\n apiVersion,\n queryParams,\n types,\n order,\n title,\n showCreateButton,\n createButtonText,\n } = {\n ...defaultProps,\n ...props,\n }\n\n const [documents, setDocuments] = useState<SanityDocument[] | undefined>()\n const [loading, setLoading] = useState<boolean>(true)\n const [error, setError] = useState<Error | undefined>()\n\n const versionedClient = useClient({apiVersion})\n const schema = useSchema()\n\n const {assembledQuery, params} = useMemo(() => {\n if (query) {\n return {assembledQuery: query, params: queryParams}\n }\n\n const documentTypes = schema.getTypeNames().filter((typeName) => {\n const schemaType = schema.get(typeName)\n return schemaType?.type?.name === 'document'\n })\n\n return {\n assembledQuery: `*[_type in $types] | order(${order}) [0...${limit * 2}]`,\n params: {types: types ? intersection(types, documentTypes) : documentTypes},\n }\n }, [schema, query, queryParams, order, limit, types])\n\n useEffect(() => {\n if (!assembledQuery) {\n return\n }\n\n const subscription = getSubscription(assembledQuery, params, versionedClient).subscribe({\n next: (d) => {\n setDocuments(d.slice(0, limit))\n setLoading(false)\n },\n error: (e) => {\n setError(e)\n setLoading(false)\n },\n })\n // eslint-disable-next-line consistent-return\n return () => {\n subscription.unsubscribe()\n }\n }, [limit, versionedClient, assembledQuery, params])\n\n return (\n <DashboardWidgetContainer\n header={title}\n footer={\n types &&\n types.length === 1 &&\n showCreateButton && (\n <IntentButton\n mode=\"bleed\"\n style={{width: '100%'}}\n paddingX={2}\n paddingY={4}\n tone=\"primary\"\n type=\"button\"\n intent=\"create\"\n params={{type: types[0]}}\n text={createButtonText || `Create new ${types[0]}`}\n />\n )\n }\n >\n <Card>\n {error && <div>{error.message}</div>}\n {!error && loading && (\n <Card padding={4}>\n <Flex justify=\"center\">\n <Spinner muted />\n </Flex>\n </Card>\n )}\n {!error && !documents && !loading && <div>Could not locate any documents :/</div>}\n <Stack space={2}>\n {documents && documents.map((doc) => <MenuEntry key={doc._id} doc={doc} />)}\n </Stack>\n </Card>\n </DashboardWidgetContainer>\n )\n}\n\nfunction MenuEntry({doc}: {doc: SanityDocument}) {\n const schema = useSchema()\n const type = schema.get(doc._type)\n return (\n <Card flex={1}>\n <IntentButton\n intent=\"edit\"\n mode=\"bleed\"\n padding={1}\n radius={0}\n params={{\n type: doc._type,\n id: getPublishedId(doc._id),\n }}\n style={{width: '100%'}}\n >\n {type ? (\n <SanityPreview layout=\"default\" schemaType={type} value={doc} key={doc._id} />\n ) : (\n 'Schema-type missing'\n )}\n </IntentButton>\n </Card>\n )\n}\n\nexport default DocumentList\n","import DocumentList, {DocumentListConfig} from './DocumentList'\nimport React from 'react'\nimport {LayoutConfig, DashboardWidget} from '@sanity/dashboard'\n\nexport interface DocumentListWidgetConfig extends DocumentListConfig {\n layout?: LayoutConfig\n}\n\nexport function documentListWidget(config: DocumentListWidgetConfig): DashboardWidget {\n return {\n name: 'document-list-widget',\n component: function component() {\n return <DocumentList {...config} />\n },\n layout: config.layout,\n }\n}\n"],"names":["draftId","nonDraftDoc","_id","getSubscription","query","params","client","listen","events","includeResult","visibility","pipe","switchMap","event","observableOf","type","tap","delay","mergeMap","fetch","then","incoming","Promise","resolve","documents","Array","isArray","ids","filter","doc","startsWith","map","drafts","outgoing","find","draft","uniqBy","catch","error","Error","message","prepareDocumentList","JSON","stringify","defaultProps","title","order","limit","queryParams","showCreateButton","apiVersion","DocumentList","props","types","createButtonText","setDocuments","useState","loading","setLoading","setError","versionedClient","useClient","schema","useSchema","assembledQuery","useMemo","documentTypes","getTypeNames","typeName","_a","schemaType","get","name","concat","intersection","useEffect","subscription","subscribe","next","d","slice","e","unsubscribe","jsx","DashboardWidgetContainer","header","footer","length","IntentButton","mode","style","width","paddingX","paddingY","tone","intent","text","children","jsxs","Card","padding","Flex","justify","Spinner","muted","Stack","space","MenuEntry","_ref","_type","flex","radius","id","getPublishedId","SanityPreview","layout","value","documentListWidget","config","component","_objectSpread"],"mappings":"4rCAMA,MAAMA,EAAWC,oBAA0CA,EAAYC,KA2BvD,SAAAC,EACdC,EACAC,EACAC,GAEO,OAAAA,EACJC,OAAOH,EAAOC,EAAQ,CACrBG,OAAQ,CAAC,UAAW,YACpBC,eAAe,EACfC,WAAY,UAEbC,KACCC,GAAWC,GACFC,EAAa,GAAGH,KACN,YAAfE,EAAME,KAAqBC,IAAQC,EAAM,KACzCC,GAAS,IACPZ,EACGa,MAAMf,EAAOC,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O,EACXT,SAAazE,GAAAA,EAAUO,KAAKF,GAASsD,EAAAwB,EAAA,CAAwB9E,OAATA,EAAI3B,aAKnE,CAEA,SAASyG,EAAwCC,GAAA,IAA9B/E,IAACA,GAA6B+E,EAC/C,MACM7F,EADSgD,IACKQ,IAAI1C,EAAIgF,OAC5B,OACG1B,EAAAgB,EAAA,CAAKW,KAAM,EACVb,SAACd,EAAAK,EAAA,CACCO,OAAO,OACPN,KAAK,QACLW,QAAS,EACTW,OAAQ,EACR1G,OAAQ,CACNU,KAAMc,EAAIgF,MACVG,GAAIC,EAAepF,EAAI3B,MAEzBwF,MAAO,CAACC,MAAO,QAEdM,WACEd,EAAA+B,EAAA,CAAcC,OAAO,UAAU7C,WAAYvD,EAAMqG,MAAOvF,GAAUA,EAAI3B,KAEvE,yBAKV,CChJO,SAASmH,EAAmBC,GAC1B,MAAA,CACL9C,KAAM,uBACN+C,UAAW,WACT,OAAQpC,EAAAhC,EAAAqE,EAAA,CAAA,EAAiBF,GAC3B,EACAH,OAAQG,EAAOH,OAEnB"}
package/lib/index.js CHANGED
@@ -1,17 +1,2 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- var _DocumentList = _interopRequireDefault(require("./DocumentList"));
9
-
10
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
-
12
- var _default = {
13
- name: 'document-list',
14
- component: _DocumentList.default
15
- };
16
- exports.default = _default;
17
- //# sourceMappingURL=index.js.map
1
+ "use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(exports,"__esModule",{value:!0});var n=require("react/jsx-runtime"),i=require("react"),s=require("sanity"),a=require("lodash"),o=require("rxjs"),c=require("rxjs/operators"),u=require("lodash/uniqBy"),d=require("@sanity/ui"),l=require("@sanity/dashboard");function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var y=p(u);const f=e=>"drafts.".concat(e._id);function m(e,t,r){return r.listen(e,t,{events:["welcome","mutation"],includeResult:!1,visibility:"query"}).pipe(c.switchMap((n=>o.of(1).pipe("welcome"===n.type?c.tap():c.delay(1e3),c.mergeMap((()=>r.fetch(e,t).then((e=>function(e,t){if(!e)return Promise.resolve([]);const r=Array.isArray(e)?e:[e],n=r.filter((e=>!e._id.startsWith("drafts."))).map(f);return t.fetch("*[_id in $ids]",{ids:n}).then((e=>{const t=r.map((t=>e.find((e=>e._id===f(t)))||t));return y.default(t,"_id")})).catch((e=>{throw new Error("Problems fetching docs ".concat(n,". Error: ").concat(e.message))}))}(e,r))).catch((r=>{if(r.message.startsWith("Problems fetching docs"))throw r;throw new Error("Query failed ".concat(e," and ").concat(JSON.stringify(t),". Error: ").concat(r.message))}))))))))}const h={title:"Last created",order:"_createdAt desc",limit:10,queryParams:{},showCreateButton:!0,apiVersion:"v1"};function b(e){const{query:r,limit:o,apiVersion:c,queryParams:u,types:p,order:y,title:f,showCreateButton:b,createButtonText:g}=t(t({},h),e),[x,w]=i.useState(),[O,v]=i.useState(!0),[P,q]=i.useState(),_=s.useClient({apiVersion:c}),S=s.useSchema(),{assembledQuery:C,params:E}=i.useMemo((()=>{if(r)return{assembledQuery:r,params:u};const e=S.getTypeNames().filter((e=>{var t;const r=S.get(e);return"document"===(null==(t=null==r?void 0:r.type)?void 0:t.name)}));return{assembledQuery:"*[_type in $types] | order(".concat(y,") [0...").concat(2*o,"]"),params:{types:p?a.intersection(p,e):e}}}),[S,r,u,y,o,p]);return i.useEffect((()=>{if(!C)return;const e=m(C,E,_).subscribe({next:e=>{w(e.slice(0,o)),v(!1)},error:e=>{q(e),v(!1)}});return()=>{e.unsubscribe()}}),[o,_,C,E]),n.jsx(l.DashboardWidgetContainer,{header:f,footer:p&&1===p.length&&b&&n.jsx(s.IntentButton,{mode:"bleed",style:{width:"100%"},paddingX:2,paddingY:4,tone:"primary",type:"button",intent:"create",params:{type:p[0]},text:g||"Create new ".concat(p[0])}),children:n.jsxs(d.Card,{children:[P&&n.jsx("div",{children:P.message}),!P&&O&&n.jsx(d.Card,{padding:4,children:n.jsx(d.Flex,{justify:"center",children:n.jsx(d.Spinner,{muted:!0})})}),!P&&!x&&!O&&n.jsx("div",{children:"Could not locate any documents :/"}),n.jsx(d.Stack,{space:2,children:x&&x.map((e=>n.jsx(j,{doc:e},e._id)))})]})})}function j(e){let{doc:t}=e;const r=s.useSchema().get(t._type);return n.jsx(d.Card,{flex:1,children:n.jsx(s.IntentButton,{intent:"edit",mode:"bleed",padding:1,radius:0,params:{type:t._type,id:s.getPublishedId(t._id)},style:{width:"100%"},children:r?n.jsx(s.SanityPreview,{layout:"default",schemaType:r,value:t},t._id):"Schema-type missing"})})}exports.documentListWidget=function(e){return{name:"document-list-widget",component:function(){return n.jsx(b,t({},e))},layout:e.layout}};
2
+ //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.js"],"names":["name","component","DocumentList"],"mappings":";;;;;;;AAAA;;;;eAEe;AACbA,EAAAA,IAAI,EAAE,eADO;AAEbC,EAAAA,SAAS,EAAEC;AAFE,C","sourcesContent":["import DocumentList from './DocumentList'\n\nexport default {\n name: 'document-list',\n component: DocumentList\n}\n"],"file":"index.js"}
1
+ {"version":3,"file":"index.js","sources":["../src/sanityConnector.ts","../src/DocumentList.tsx","../src/plugin.tsx"],"sourcesContent":["import {Observable, of as observableOf} from 'rxjs'\nimport {delay, mergeMap, switchMap, tap} from 'rxjs/operators'\nimport uniqBy from 'lodash/uniqBy'\nimport {SanityClient} from '@sanity/client'\nimport {SanityDocument} from 'sanity'\n\nconst draftId = (nonDraftDoc: SanityDocument) => `drafts.${nonDraftDoc._id}`\n\nfunction prepareDocumentList(\n incoming: SanityDocument | SanityDocument[],\n client: SanityClient\n): Promise<SanityDocument[]> {\n if (!incoming) {\n return Promise.resolve([])\n }\n const documents = Array.isArray(incoming) ? incoming : [incoming]\n\n const ids = documents.filter((doc) => !doc._id.startsWith('drafts.')).map(draftId)\n\n return client\n .fetch<SanityDocument[]>('*[_id in $ids]', {ids})\n .then((drafts) => {\n const outgoing = documents.map((doc) => {\n const foundDraft = drafts.find((draft) => draft._id === draftId(doc))\n return foundDraft || doc\n })\n return uniqBy(outgoing, '_id')\n })\n .catch((error) => {\n throw new Error(`Problems fetching docs ${ids}. Error: ${error.message}`)\n })\n}\n\nexport function getSubscription(\n query: string,\n params: Record<string, any>,\n client: SanityClient\n): Observable<SanityDocument[]> {\n return client\n .listen(query, params, {\n events: ['welcome', 'mutation'],\n includeResult: false,\n visibility: 'query',\n })\n .pipe(\n switchMap((event) => {\n return observableOf(1).pipe(\n event.type === 'welcome' ? tap() : delay(1000),\n mergeMap(() =>\n client\n .fetch(query, params)\n .then((incoming) => {\n return prepareDocumentList(incoming, client)\n })\n .catch((error) => {\n if (error.message.startsWith('Problems fetching docs')) {\n throw error\n }\n throw new Error(\n `Query failed ${query} and ${JSON.stringify(params)}. Error: ${error.message}`\n )\n })\n )\n )\n })\n )\n}\n","import React, {useEffect, useMemo, useState} from 'react'\nimport {getPublishedId, useClient, useSchema} from 'sanity'\nimport {intersection} from 'lodash'\nimport {getSubscription} from './sanityConnector'\nimport {SanityDocument, IntentButton, SanityPreview} from 'sanity'\nimport {Card, Flex, Spinner, Stack} from '@sanity/ui'\nimport {DashboardWidgetContainer} from '@sanity/dashboard'\n\nexport interface DocumentListConfig {\n title?: string\n types?: string[]\n query?: string\n queryParams?: Record<string, any>\n order?: string\n limit?: number\n showCreateButton?: boolean\n createButtonText?: string\n apiVersion?: string\n}\n\nconst defaultProps = {\n title: 'Last created',\n order: '_createdAt desc',\n limit: 10,\n queryParams: {},\n showCreateButton: true,\n apiVersion: 'v1',\n}\n\nexport function DocumentList(props: DocumentListConfig) {\n const {\n query,\n limit,\n apiVersion,\n queryParams,\n types,\n order,\n title,\n showCreateButton,\n createButtonText,\n } = {\n ...defaultProps,\n ...props,\n }\n\n const [documents, setDocuments] = useState<SanityDocument[] | undefined>()\n const [loading, setLoading] = useState<boolean>(true)\n const [error, setError] = useState<Error | undefined>()\n\n const versionedClient = useClient({apiVersion})\n const schema = useSchema()\n\n const {assembledQuery, params} = useMemo(() => {\n if (query) {\n return {assembledQuery: query, params: queryParams}\n }\n\n const documentTypes = schema.getTypeNames().filter((typeName) => {\n const schemaType = schema.get(typeName)\n return schemaType?.type?.name === 'document'\n })\n\n return {\n assembledQuery: `*[_type in $types] | order(${order}) [0...${limit * 2}]`,\n params: {types: types ? intersection(types, documentTypes) : documentTypes},\n }\n }, [schema, query, queryParams, order, limit, types])\n\n useEffect(() => {\n if (!assembledQuery) {\n return\n }\n\n const subscription = getSubscription(assembledQuery, params, versionedClient).subscribe({\n next: (d) => {\n setDocuments(d.slice(0, limit))\n setLoading(false)\n },\n error: (e) => {\n setError(e)\n setLoading(false)\n },\n })\n // eslint-disable-next-line consistent-return\n return () => {\n subscription.unsubscribe()\n }\n }, [limit, versionedClient, assembledQuery, params])\n\n return (\n <DashboardWidgetContainer\n header={title}\n footer={\n types &&\n types.length === 1 &&\n showCreateButton && (\n <IntentButton\n mode=\"bleed\"\n style={{width: '100%'}}\n paddingX={2}\n paddingY={4}\n tone=\"primary\"\n type=\"button\"\n intent=\"create\"\n params={{type: types[0]}}\n text={createButtonText || `Create new ${types[0]}`}\n />\n )\n }\n >\n <Card>\n {error && <div>{error.message}</div>}\n {!error && loading && (\n <Card padding={4}>\n <Flex justify=\"center\">\n <Spinner muted />\n </Flex>\n </Card>\n )}\n {!error && !documents && !loading && <div>Could not locate any documents :/</div>}\n <Stack space={2}>\n {documents && documents.map((doc) => <MenuEntry key={doc._id} doc={doc} />)}\n </Stack>\n </Card>\n </DashboardWidgetContainer>\n )\n}\n\nfunction MenuEntry({doc}: {doc: SanityDocument}) {\n const schema = useSchema()\n const type = schema.get(doc._type)\n return (\n <Card flex={1}>\n <IntentButton\n intent=\"edit\"\n mode=\"bleed\"\n padding={1}\n radius={0}\n params={{\n type: doc._type,\n id: getPublishedId(doc._id),\n }}\n style={{width: '100%'}}\n >\n {type ? (\n <SanityPreview layout=\"default\" schemaType={type} value={doc} key={doc._id} />\n ) : (\n 'Schema-type missing'\n )}\n </IntentButton>\n </Card>\n )\n}\n\nexport default DocumentList\n","import DocumentList, {DocumentListConfig} from './DocumentList'\nimport React from 'react'\nimport {LayoutConfig, DashboardWidget} from '@sanity/dashboard'\n\nexport interface DocumentListWidgetConfig extends DocumentListConfig {\n layout?: LayoutConfig\n}\n\nexport function documentListWidget(config: DocumentListWidgetConfig): DashboardWidget {\n return {\n name: 'document-list-widget',\n component: function component() {\n return <DocumentList {...config} />\n },\n layout: config.layout,\n }\n}\n"],"names":["draftId","nonDraftDoc","_id","getSubscription","query","params","client","listen","events","includeResult","visibility","pipe","switchMap","event","observableOf","of","type","tap","delay","mergeMap","fetch","then","incoming","Promise","resolve","documents","Array","isArray","ids","filter","doc","startsWith","map","drafts","outgoing","find","draft","uniqBy","catch","error","Error","message","prepareDocumentList","JSON","stringify","defaultProps","title","order","limit","queryParams","showCreateButton","apiVersion","DocumentList","props","types","createButtonText","setDocuments","useState","loading","setLoading","setError","versionedClient","useClient","schema","useSchema","assembledQuery","useMemo","documentTypes","getTypeNames","typeName","_a","schemaType","get","name","concat","intersection","useEffect","subscription","subscribe","next","d","slice","e","unsubscribe","jsx","DashboardWidgetContainer","header","footer","length","IntentButton","mode","style","width","paddingX","paddingY","tone","intent","text","children","jsxs","Card","padding","Flex","justify","Spinner","muted","Stack","space","MenuEntry","_ref","_type","flex","radius","id","getPublishedId","SanityPreview","layout","value","config","component","_objectSpread"],"mappings":"4iCAMA,MAAMA,EAAWC,oBAA0CA,EAAYC,KA2BvD,SAAAC,EACdC,EACAC,EACAC,GAEO,OAAAA,EACJC,OAAOH,EAAOC,EAAQ,CACrBG,OAAQ,CAAC,UAAW,YACpBC,eAAe,EACfC,WAAY,UAEbC,KACCC,EAAAA,WAAWC,GACFC,EAAAC,GAAa,GAAGJ,KACN,YAAfE,EAAMG,KAAqBC,EAAIA,MAAIC,EAAAA,MAAM,KACzCC,EAAAA,UAAS,IACPb,EACGc,MAAMhB,EAAOC,GACbgB,MAAMC,GA3CrB,SACEA,EACAhB,GAEA,IAAKgB,EACI,OAAAC,QAAQC,QAAQ,IAEzB,MAAMC,EAAYC,MAAMC,QAAQL,GAAYA,EAAW,CAACA,GAElDM,EAAMH,EAAUI,QAAQC,IAASA,EAAI5B,IAAI6B,WAAW,aAAYC,IAAIhC,GAEnE,OAAAM,EACJc,MAAwB,iBAAkB,CAACQ,QAC3CP,MAAMY,IACL,MAAMC,EAAWT,EAAUO,KAAKF,GACXG,EAAOE,MAAMC,GAAUA,EAAMlC,MAAQF,EAAQ8B,MAC3CA,IAEhB,OAAAO,EAAA,QAAOH,EAAU,MAAK,IAE9BI,OAAOC,IACN,MAAM,IAAIC,MAAgCZ,0BAAAA,OAAAA,sBAAeW,EAAME,SAAS,GAE9E,CAqBuBC,CAAoBpB,EAAUhB,KAEtCgC,OAAOC,IACN,GAAIA,EAAME,QAAQV,WAAW,0BACrB,MAAAQ,EAER,MAAM,IAAIC,MACQpC,gBAAAA,OAAAA,kBAAauC,KAAKC,UAAUvC,uBAAmBkC,EAAME,SACvE,SAMhB,CC9CA,MAAMI,EAAe,CACnBC,MAAO,eACPC,MAAO,kBACPC,MAAO,GACPC,YAAa,CAAC,EACd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C,EAAAA,IAAAhC,EAAAoE,EAAA,CAAA,EAAiBF,GAC3B,EACAF,OAAQE,EAAOF,OAEnB"}
@@ -0,0 +1,24 @@
1
+ /// <reference types="react" />
2
+
3
+ import {DashboardWidget} from '@sanity/dashboard'
4
+ import {LayoutConfig} from '@sanity/dashboard'
5
+
6
+ declare interface DocumentListConfig {
7
+ title?: string
8
+ types?: string[]
9
+ query?: string
10
+ queryParams?: Record<string, any>
11
+ order?: string
12
+ limit?: number
13
+ showCreateButton?: boolean
14
+ createButtonText?: string
15
+ apiVersion?: string
16
+ }
17
+
18
+ export declare function documentListWidget(config: DocumentListWidgetConfig): DashboardWidget
19
+
20
+ export declare interface DocumentListWidgetConfig extends DocumentListConfig {
21
+ layout?: LayoutConfig
22
+ }
23
+
24
+ export {}
package/package.json CHANGED
@@ -1,10 +1,7 @@
1
1
  {
2
- "public": true,
3
2
  "name": "sanity-plugin-dashboard-widget-document-list",
4
- "version": "0.0.13",
5
- "author": "Sanity.io <hello@sanity.io>",
6
- "description": "Example dashboard widget for Sanity Content Studio",
7
- "homepage": "https://github.com/sanity-io/dashboard-widget-document-list#readme",
3
+ "version": "1.0.0",
4
+ "description": "> **NOTE**",
8
5
  "keywords": [
9
6
  "sanity",
10
7
  "plugin",
@@ -13,37 +10,86 @@
13
10
  "widget",
14
11
  "documents"
15
12
  ],
16
- "main": "lib/index.js",
17
- "license": "MIT",
13
+ "homepage": "https://github.com/sanity-io/dashboard-widget-document-list#readme",
18
14
  "bugs": {
19
15
  "url": "https://github.com/sanity-io/dashboard-widget-document-list/issues"
20
16
  },
21
- "scripts": {
22
- "build": "sanipack build",
23
- "test": "sanipack verify",
24
- "clean": "rimraf lib",
25
- "prebuild": "npm run clean",
26
- "prepublishOnly": "npm run build && npm test"
27
- },
28
17
  "repository": {
29
18
  "type": "git",
30
- "url": "git+https://github.com/sanity-io/dashboard-widget-document-list.git"
19
+ "url": "git@github.com:sanity-io/dashboard-widget-document-list.git"
31
20
  },
32
- "devDependencies": {
33
- "babel-eslint": "^7.2.3",
34
- "eslint": "^4.3.0",
35
- "eslint-config-sanity": "^2.1.4",
36
- "eslint-plugin-react": "^7.1.0",
37
- "rimraf": "^2.7.1",
38
- "sanipack": "^1.0.8"
21
+ "license": "MIT",
22
+ "author": "Sanity.io <hello@sanity.io>",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./lib/src/index.d.ts",
26
+ "source": "./src/index.ts",
27
+ "import": "./lib/index.esm.js",
28
+ "require": "./lib/index.js",
29
+ "default": "./lib/index.esm.js"
30
+ },
31
+ "./package.json": "./package.json"
39
32
  },
40
- "peerDependencies": {
41
- "@sanity/base": ">=1",
42
- "react": "^16 || ^17"
33
+ "main": "./lib/index.js",
34
+ "module": "./lib/index.esm.js",
35
+ "source": "./src/index.ts",
36
+ "types": "./lib/src/index.d.ts",
37
+ "files": [
38
+ "src",
39
+ "lib",
40
+ "v2-incompatible.js",
41
+ "sanity.json"
42
+ ],
43
+ "scripts": {
44
+ "prebuild": "npm run clean && plugin-kit verify-package --silent && pkg-utils",
45
+ "build": "pkg-utils build --strict",
46
+ "clean": "rimraf lib",
47
+ "compile": "tsc --noEmit",
48
+ "link-watch": "plugin-kit link-watch",
49
+ "lint": "eslint .",
50
+ "prepare": "husky install",
51
+ "prepublishOnly": "npm run build",
52
+ "watch": "pkg-utils watch"
43
53
  },
44
54
  "dependencies": {
55
+ "@sanity/incompatible-plugin": "^1.0.4",
56
+ "@sanity/ui": "1.0.0-beta.32",
45
57
  "lodash": "^4.17.15",
46
- "prop-types": "^15.7.2",
47
58
  "rxjs": "^6.0.0"
48
- }
59
+ },
60
+ "devDependencies": {
61
+ "@commitlint/cli": "^17.2.0",
62
+ "@commitlint/config-conventional": "^17.2.0",
63
+ "@sanity/dashboard": "^3.0.0-v3-studio.8",
64
+ "@sanity/pkg-utils": "^1.17.2",
65
+ "@sanity/plugin-kit": "^2.1.5",
66
+ "@sanity/semantic-release-preset": "^2.0.2",
67
+ "@types/react": "^18",
68
+ "@typescript-eslint/eslint-plugin": "^5.42.0",
69
+ "@typescript-eslint/parser": "^5.42.0",
70
+ "eslint": "^8.26.0",
71
+ "eslint-config-prettier": "^8.5.0",
72
+ "eslint-config-sanity": "^6.0.0",
73
+ "eslint-plugin-prettier": "^4.2.1",
74
+ "eslint-plugin-react": "^7.31.10",
75
+ "eslint-plugin-react-hooks": "^4.6.0",
76
+ "husky": "^8.0.1",
77
+ "lint-staged": "^13.0.3",
78
+ "prettier": "^2.7.1",
79
+ "prettier-plugin-packagejson": "^2.3.0",
80
+ "react": "^18",
81
+ "rimraf": "^3.0.2",
82
+ "sanity": "3.0.0-rc.2",
83
+ "typescript": "^4.8.4"
84
+ },
85
+ "peerDependencies": {
86
+ "@sanity/dashboard": "^3.0.0-v3-studio.8",
87
+ "react": "^18",
88
+ "sanity": "dev-preview || 3.0.0-rc.2"
89
+ },
90
+ "engines": {
91
+ "node": ">=14"
92
+ },
93
+ "public": true,
94
+ "sanityExchangeUrl": "https://www.sanity.io/plugins/sanity-plugin-dashboard-widget-document-list"
49
95
  }
package/sanity.json CHANGED
@@ -1,12 +1,8 @@
1
1
  {
2
- "paths": {
3
- "source": "./src",
4
- "compiled": "./lib"
5
- },
6
2
  "parts": [
7
3
  {
8
- "implements": "part:@sanity/dashboard/widget",
9
- "path": "index.js"
4
+ "implements": "part:@sanity/base/sanity-root",
5
+ "path": "./v2-incompatible.js"
10
6
  }
11
7
  ]
12
8
  }
@@ -0,0 +1,155 @@
1
+ import React, {useEffect, useMemo, useState} from 'react'
2
+ import {getPublishedId, useClient, useSchema} from 'sanity'
3
+ import {intersection} from 'lodash'
4
+ import {getSubscription} from './sanityConnector'
5
+ import {SanityDocument, IntentButton, SanityPreview} from 'sanity'
6
+ import {Card, Flex, Spinner, Stack} from '@sanity/ui'
7
+ import {DashboardWidgetContainer} from '@sanity/dashboard'
8
+
9
+ export interface DocumentListConfig {
10
+ title?: string
11
+ types?: string[]
12
+ query?: string
13
+ queryParams?: Record<string, any>
14
+ order?: string
15
+ limit?: number
16
+ showCreateButton?: boolean
17
+ createButtonText?: string
18
+ apiVersion?: string
19
+ }
20
+
21
+ const defaultProps = {
22
+ title: 'Last created',
23
+ order: '_createdAt desc',
24
+ limit: 10,
25
+ queryParams: {},
26
+ showCreateButton: true,
27
+ apiVersion: 'v1',
28
+ }
29
+
30
+ export function DocumentList(props: DocumentListConfig) {
31
+ const {
32
+ query,
33
+ limit,
34
+ apiVersion,
35
+ queryParams,
36
+ types,
37
+ order,
38
+ title,
39
+ showCreateButton,
40
+ createButtonText,
41
+ } = {
42
+ ...defaultProps,
43
+ ...props,
44
+ }
45
+
46
+ const [documents, setDocuments] = useState<SanityDocument[] | undefined>()
47
+ const [loading, setLoading] = useState<boolean>(true)
48
+ const [error, setError] = useState<Error | undefined>()
49
+
50
+ const versionedClient = useClient({apiVersion})
51
+ const schema = useSchema()
52
+
53
+ const {assembledQuery, params} = useMemo(() => {
54
+ if (query) {
55
+ return {assembledQuery: query, params: queryParams}
56
+ }
57
+
58
+ const documentTypes = schema.getTypeNames().filter((typeName) => {
59
+ const schemaType = schema.get(typeName)
60
+ return schemaType?.type?.name === 'document'
61
+ })
62
+
63
+ return {
64
+ assembledQuery: `*[_type in $types] | order(${order}) [0...${limit * 2}]`,
65
+ params: {types: types ? intersection(types, documentTypes) : documentTypes},
66
+ }
67
+ }, [schema, query, queryParams, order, limit, types])
68
+
69
+ useEffect(() => {
70
+ if (!assembledQuery) {
71
+ return
72
+ }
73
+
74
+ const subscription = getSubscription(assembledQuery, params, versionedClient).subscribe({
75
+ next: (d) => {
76
+ setDocuments(d.slice(0, limit))
77
+ setLoading(false)
78
+ },
79
+ error: (e) => {
80
+ setError(e)
81
+ setLoading(false)
82
+ },
83
+ })
84
+ // eslint-disable-next-line consistent-return
85
+ return () => {
86
+ subscription.unsubscribe()
87
+ }
88
+ }, [limit, versionedClient, assembledQuery, params])
89
+
90
+ return (
91
+ <DashboardWidgetContainer
92
+ header={title}
93
+ footer={
94
+ types &&
95
+ types.length === 1 &&
96
+ showCreateButton && (
97
+ <IntentButton
98
+ mode="bleed"
99
+ style={{width: '100%'}}
100
+ paddingX={2}
101
+ paddingY={4}
102
+ tone="primary"
103
+ type="button"
104
+ intent="create"
105
+ params={{type: types[0]}}
106
+ text={createButtonText || `Create new ${types[0]}`}
107
+ />
108
+ )
109
+ }
110
+ >
111
+ <Card>
112
+ {error && <div>{error.message}</div>}
113
+ {!error && loading && (
114
+ <Card padding={4}>
115
+ <Flex justify="center">
116
+ <Spinner muted />
117
+ </Flex>
118
+ </Card>
119
+ )}
120
+ {!error && !documents && !loading && <div>Could not locate any documents :/</div>}
121
+ <Stack space={2}>
122
+ {documents && documents.map((doc) => <MenuEntry key={doc._id} doc={doc} />)}
123
+ </Stack>
124
+ </Card>
125
+ </DashboardWidgetContainer>
126
+ )
127
+ }
128
+
129
+ function MenuEntry({doc}: {doc: SanityDocument}) {
130
+ const schema = useSchema()
131
+ const type = schema.get(doc._type)
132
+ return (
133
+ <Card flex={1}>
134
+ <IntentButton
135
+ intent="edit"
136
+ mode="bleed"
137
+ padding={1}
138
+ radius={0}
139
+ params={{
140
+ type: doc._type,
141
+ id: getPublishedId(doc._id),
142
+ }}
143
+ style={{width: '100%'}}
144
+ >
145
+ {type ? (
146
+ <SanityPreview layout="default" schemaType={type} value={doc} key={doc._id} />
147
+ ) : (
148
+ 'Schema-type missing'
149
+ )}
150
+ </IntentButton>
151
+ </Card>
152
+ )
153
+ }
154
+
155
+ export default DocumentList
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export {documentListWidget, type DocumentListWidgetConfig} from './plugin'
package/src/plugin.tsx ADDED
@@ -0,0 +1,17 @@
1
+ import DocumentList, {DocumentListConfig} from './DocumentList'
2
+ import React from 'react'
3
+ import {LayoutConfig, DashboardWidget} from '@sanity/dashboard'
4
+
5
+ export interface DocumentListWidgetConfig extends DocumentListConfig {
6
+ layout?: LayoutConfig
7
+ }
8
+
9
+ export function documentListWidget(config: DocumentListWidgetConfig): DashboardWidget {
10
+ return {
11
+ name: 'document-list-widget',
12
+ component: function component() {
13
+ return <DocumentList {...config} />
14
+ },
15
+ layout: config.layout,
16
+ }
17
+ }
@@ -0,0 +1,67 @@
1
+ import {Observable, of as observableOf} from 'rxjs'
2
+ import {delay, mergeMap, switchMap, tap} from 'rxjs/operators'
3
+ import uniqBy from 'lodash/uniqBy'
4
+ import {SanityClient} from '@sanity/client'
5
+ import {SanityDocument} from 'sanity'
6
+
7
+ const draftId = (nonDraftDoc: SanityDocument) => `drafts.${nonDraftDoc._id}`
8
+
9
+ function prepareDocumentList(
10
+ incoming: SanityDocument | SanityDocument[],
11
+ client: SanityClient
12
+ ): Promise<SanityDocument[]> {
13
+ if (!incoming) {
14
+ return Promise.resolve([])
15
+ }
16
+ const documents = Array.isArray(incoming) ? incoming : [incoming]
17
+
18
+ const ids = documents.filter((doc) => !doc._id.startsWith('drafts.')).map(draftId)
19
+
20
+ return client
21
+ .fetch<SanityDocument[]>('*[_id in $ids]', {ids})
22
+ .then((drafts) => {
23
+ const outgoing = documents.map((doc) => {
24
+ const foundDraft = drafts.find((draft) => draft._id === draftId(doc))
25
+ return foundDraft || doc
26
+ })
27
+ return uniqBy(outgoing, '_id')
28
+ })
29
+ .catch((error) => {
30
+ throw new Error(`Problems fetching docs ${ids}. Error: ${error.message}`)
31
+ })
32
+ }
33
+
34
+ export function getSubscription(
35
+ query: string,
36
+ params: Record<string, any>,
37
+ client: SanityClient
38
+ ): Observable<SanityDocument[]> {
39
+ return client
40
+ .listen(query, params, {
41
+ events: ['welcome', 'mutation'],
42
+ includeResult: false,
43
+ visibility: 'query',
44
+ })
45
+ .pipe(
46
+ switchMap((event) => {
47
+ return observableOf(1).pipe(
48
+ event.type === 'welcome' ? tap() : delay(1000),
49
+ mergeMap(() =>
50
+ client
51
+ .fetch(query, params)
52
+ .then((incoming) => {
53
+ return prepareDocumentList(incoming, client)
54
+ })
55
+ .catch((error) => {
56
+ if (error.message.startsWith('Problems fetching docs')) {
57
+ throw error
58
+ }
59
+ throw new Error(
60
+ `Query failed ${query} and ${JSON.stringify(params)}. Error: ${error.message}`
61
+ )
62
+ })
63
+ )
64
+ )
65
+ })
66
+ )
67
+ }
@@ -0,0 +1,11 @@
1
+ const {showIncompatiblePluginDialog} = require('@sanity/incompatible-plugin')
2
+ const {name, version, sanityExchangeUrl} = require('./package.json')
3
+
4
+ export default showIncompatiblePluginDialog({
5
+ name: name,
6
+ versions: {
7
+ v3: version,
8
+ v2: '^0.0.13',
9
+ },
10
+ sanityExchangeUrl,
11
+ })
@@ -1,34 +0,0 @@
1
- @import 'part:@sanity/base/theme/variables-style';
2
-
3
- .container {
4
- composes: container from "part:@sanity/dashboard/widget-styles";
5
- }
6
-
7
- .header {
8
- composes: header from "part:@sanity/dashboard/widget-styles";
9
- }
10
-
11
- .title {
12
- composes: title from "part:@sanity/dashboard/widget-styles";
13
- }
14
-
15
- .content {
16
- composes: content from 'part:@sanity/dashboard/widget-styles';
17
- border-top: 1px solid var(--hairline-color);
18
- padding: var(--small-padding) 0;
19
- }
20
-
21
- .link {
22
- composes: item from 'part:@sanity/base/theme/layout/selectable-style';
23
- display: block;
24
- color: inherit;
25
- text-decoration: inherit;
26
- outline: none;
27
- padding: var(--small-padding) var(--medium-padding);
28
- height: 100%;
29
- }
30
-
31
- .footer {
32
- composes: footer from 'part:@sanity/dashboard/widget-styles';
33
- border-top: 1px solid var(--hairline-color);
34
- }
@@ -1,196 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
-
8
- var _react = _interopRequireDefault(require("react"));
9
-
10
- var _propTypes = _interopRequireDefault(require("prop-types"));
11
-
12
- var _router = require("part:@sanity/base/router");
13
-
14
- var _preview = _interopRequireDefault(require("part:@sanity/base/preview"));
15
-
16
- var _spinner = _interopRequireDefault(require("part:@sanity/components/loading/spinner"));
17
-
18
- var _schema = _interopRequireDefault(require("part:@sanity/base/schema"));
19
-
20
- var _intent = _interopRequireDefault(require("part:@sanity/components/buttons/intent"));
21
-
22
- var _default2 = require("part:@sanity/components/lists/default");
23
-
24
- var _draftUtils = require("part:@sanity/base/util/draft-utils");
25
-
26
- var _lodash = require("lodash");
27
-
28
- var _sanityConnector = require("./sanityConnector");
29
-
30
- var _DocumentList = _interopRequireDefault(require("./DocumentList.css"));
31
-
32
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
33
-
34
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
35
-
36
- var schemaTypeNames = _schema.default.getTypeNames();
37
-
38
- class DocumentList extends _react.default.Component {
39
- constructor() {
40
- super(...arguments);
41
-
42
- _defineProperty(this, "state", {
43
- documents: null,
44
- loading: true,
45
- error: null
46
- });
47
-
48
- _defineProperty(this, "componentDidMount", () => {
49
- var _this$props = this.props,
50
- query = _this$props.query,
51
- limit = _this$props.limit,
52
- apiVersion = _this$props.apiVersion;
53
-
54
- var _this$assembleQuery = this.assembleQuery(),
55
- assembledQuery = _this$assembleQuery.assembledQuery,
56
- params = _this$assembleQuery.params;
57
-
58
- if (!assembledQuery) {
59
- return;
60
- }
61
-
62
- this.unsubscribe();
63
- this.subscription = (0, _sanityConnector.getSubscription)(assembledQuery, params, apiVersion).subscribe({
64
- next: documents => this.setState({
65
- documents: documents.slice(0, limit),
66
- loading: false
67
- }),
68
- error: _error => this.setState({
69
- error: _error,
70
- query,
71
- loading: false
72
- })
73
- });
74
- });
75
-
76
- _defineProperty(this, "assembleQuery", () => {
77
- var _this$props2 = this.props,
78
- query = _this$props2.query,
79
- queryParams = _this$props2.queryParams,
80
- types = _this$props2.types,
81
- order = _this$props2.order,
82
- limit = _this$props2.limit;
83
-
84
- if (query) {
85
- return {
86
- assembledQuery: query,
87
- params: queryParams
88
- };
89
- }
90
-
91
- var documentTypes = schemaTypeNames.filter(typeName => {
92
- var schemaType = _schema.default.get(typeName);
93
-
94
- return schemaType.type && schemaType.type.name === 'document';
95
- });
96
- return {
97
- assembledQuery: "*[_type in $types] | order(".concat(order, ") [0...").concat(limit * 2, "]"),
98
- params: {
99
- types: types ? (0, _lodash.intersection)(types, documentTypes) : documentTypes
100
- }
101
- };
102
- });
103
- }
104
-
105
- componentWillUnmount() {
106
- this.unsubscribe();
107
- }
108
-
109
- unsubscribe() {
110
- if (this.subscription) {
111
- this.subscription.unsubscribe();
112
- }
113
- }
114
-
115
- render() {
116
- var _this$props3 = this.props,
117
- title = _this$props3.title,
118
- types = _this$props3.types,
119
- showCreateButton = _this$props3.showCreateButton,
120
- createButtonText = _this$props3.createButtonText;
121
- var _this$state = this.state,
122
- documents = _this$state.documents,
123
- loading = _this$state.loading,
124
- error = _this$state.error;
125
- return /*#__PURE__*/_react.default.createElement("div", {
126
- className: _DocumentList.default.container
127
- }, /*#__PURE__*/_react.default.createElement("header", {
128
- className: _DocumentList.default.header
129
- }, /*#__PURE__*/_react.default.createElement("h2", {
130
- className: _DocumentList.default.title
131
- }, title)), /*#__PURE__*/_react.default.createElement("div", {
132
- className: _DocumentList.default.content
133
- }, error && /*#__PURE__*/_react.default.createElement("div", null, error.message), !error && loading && /*#__PURE__*/_react.default.createElement(_spinner.default, {
134
- center: true,
135
- message: "Loading..."
136
- }), !error && !documents && !loading && /*#__PURE__*/_react.default.createElement("div", null, "Could not locate any documents :/"), /*#__PURE__*/_react.default.createElement(_default2.List, null, documents && documents.map(doc => {
137
- var type = _schema.default.get(doc._type);
138
-
139
- return /*#__PURE__*/_react.default.createElement(_default2.Item, {
140
- key: doc._id
141
- }, /*#__PURE__*/_react.default.createElement(_router.IntentLink, {
142
- intent: "edit",
143
- params: {
144
- type: doc._type,
145
- id: (0, _draftUtils.getPublishedId)(doc._id)
146
- },
147
- className: _DocumentList.default.link
148
- }, /*#__PURE__*/_react.default.createElement(_preview.default, {
149
- layout: "default",
150
- type: type,
151
- value: doc,
152
- key: doc._id
153
- })));
154
- }))), types && types.length === 1 && showCreateButton && /*#__PURE__*/_react.default.createElement("div", {
155
- className: _DocumentList.default.footer
156
- }, /*#__PURE__*/_react.default.createElement(_intent.default, {
157
- bleed: true,
158
- color: "primary",
159
- kind: "simple",
160
- intent: "create",
161
- params: {
162
- type: types[0]
163
- }
164
- }, createButtonText || "Create new ".concat(types[0]))));
165
- }
166
-
167
- }
168
-
169
- _defineProperty(DocumentList, "propTypes", {
170
- title: _propTypes.default.string,
171
- types: _propTypes.default.arrayOf(_propTypes.default.string),
172
- query: _propTypes.default.string,
173
- queryParams: _propTypes.default.object,
174
- // eslint-disable-line react/forbid-prop-types
175
- order: _propTypes.default.string,
176
- limit: _propTypes.default.number,
177
- showCreateButton: _propTypes.default.bool,
178
- createButtonText: _propTypes.default.string,
179
- apiVersion: _propTypes.default.string
180
- });
181
-
182
- _defineProperty(DocumentList, "defaultProps", {
183
- title: 'Last created',
184
- order: '_createdAt desc',
185
- limit: 10,
186
- types: null,
187
- query: null,
188
- queryParams: {},
189
- showCreateButton: true,
190
- createButtonText: null,
191
- apiVersion: 'v1'
192
- });
193
-
194
- var _default = DocumentList;
195
- exports.default = _default;
196
- //# sourceMappingURL=DocumentList.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/DocumentList.js"],"names":["schemaTypeNames","schema","getTypeNames","DocumentList","React","Component","documents","loading","error","props","query","limit","apiVersion","assembleQuery","assembledQuery","params","unsubscribe","subscription","subscribe","next","setState","slice","queryParams","types","order","documentTypes","filter","typeName","schemaType","get","type","name","componentWillUnmount","render","title","showCreateButton","createButtonText","state","styles","container","header","content","message","map","doc","_type","_id","id","link","length","footer","PropTypes","string","arrayOf","object","number","bool"],"mappings":";;;;;;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;AAEA,IAAMA,eAAe,GAAGC,gBAAOC,YAAP,EAAxB;;AAEA,MAAMC,YAAN,SAA2BC,eAAMC,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,CADnB,CADF,CA9BJ,CADF;AAuCD;;AAxHwC;;gBAArCpB,Y,eAQe;AACjB+B,EAAAA,KAAK,EAAEiB,mBAAUC,MADA;AAEjB7B,EAAAA,KAAK,EAAE4B,mBAAUE,OAAV,CAAkBF,mBAAUC,MAA5B,CAFU;AAGjB1C,EAAAA,KAAK,EAAEyC,mBAAUC,MAHA;AAIjB9B,EAAAA,WAAW,EAAE6B,mBAAUG,MAJN;AAIc;AAC/B9B,EAAAA,KAAK,EAAE2B,mBAAUC,MALA;AAMjBzC,EAAAA,KAAK,EAAEwC,mBAAUI,MANA;AAOjBpB,EAAAA,gBAAgB,EAAEgB,mBAAUK,IAPX;AAQjBpB,EAAAA,gBAAgB,EAAEe,mBAAUC,MARX;AASjBxC,EAAAA,UAAU,EAAEuC,mBAAUC;AATL,C;;gBARfjD,Y,kBAoBkB;AACpB+B,EAAAA,KAAK,EAAE,cADa;AAEpBV,EAAAA,KAAK,EAAE,iBAFa;AAGpBb,EAAAA,KAAK,EAAE,EAHa;AAIpBY,EAAAA,KAAK,EAAE,IAJa;AAKpBb,EAAAA,KAAK,EAAE,IALa;AAMpBY,EAAAA,WAAW,EAAE,EANO;AAOpBa,EAAAA,gBAAgB,EAAE,IAPE;AAQpBC,EAAAA,gBAAgB,EAAE,IARE;AASpBxB,EAAAA,UAAU,EAAE;AATQ,C;;eAuGTT,Y","sourcesContent":["/* eslint-disable complexity */\nimport React from 'react'\nimport PropTypes from 'prop-types'\nimport {IntentLink} from 'part:@sanity/base/router'\nimport SanityPreview from 'part:@sanity/base/preview'\nimport Spinner from 'part:@sanity/components/loading/spinner'\nimport schema from 'part:@sanity/base/schema'\nimport IntentButton from 'part:@sanity/components/buttons/intent'\nimport {List, Item} from 'part:@sanity/components/lists/default'\nimport {getPublishedId} from 'part:@sanity/base/util/draft-utils'\nimport {intersection} from 'lodash'\nimport {getSubscription} from './sanityConnector'\nimport styles from './DocumentList.css'\n\nconst schemaTypeNames = schema.getTypeNames()\n\nclass DocumentList extends React.Component {\n\n state = {\n documents: null,\n loading: true,\n error: null\n }\n\n static propTypes = {\n title: PropTypes.string,\n types: PropTypes.arrayOf(PropTypes.string),\n query: PropTypes.string,\n queryParams: PropTypes.object, // eslint-disable-line react/forbid-prop-types\n order: PropTypes.string,\n limit: PropTypes.number,\n showCreateButton: PropTypes.bool,\n createButtonText: PropTypes.string,\n apiVersion: PropTypes.string\n }\n\n static defaultProps = {\n title: 'Last created',\n order: '_createdAt desc',\n limit: 10,\n types: null,\n query: null,\n queryParams: {},\n showCreateButton: true,\n createButtonText: null,\n apiVersion: 'v1'\n }\n\n componentDidMount = () => {\n const {query, limit, apiVersion} = this.props\n const {assembledQuery, params} = this.assembleQuery()\n if (!assembledQuery) {\n return\n }\n\n this.unsubscribe()\n this.subscription = getSubscription(assembledQuery, params, apiVersion)\n .subscribe({\n next: documents =>\n this.setState({documents: documents.slice(0, limit), loading: false}),\n error: error =>\n this.setState({error, query, loading: false})\n })\n }\n\n componentWillUnmount() {\n this.unsubscribe()\n }\n\n unsubscribe() {\n if (this.subscription) {\n this.subscription.unsubscribe()\n }\n }\n\n assembleQuery = () => {\n const {query, queryParams, types, order, limit} = this.props\n if (query) {\n return {assembledQuery: query, params: queryParams}\n }\n\n const documentTypes = schemaTypeNames.filter(typeName => {\n const schemaType = schema.get(typeName)\n return schemaType.type && schemaType.type.name === 'document'\n })\n\n return {\n assembledQuery: `*[_type in $types] | order(${order}) [0...${limit * 2}]`,\n params: {types: types ? intersection(types, documentTypes) : documentTypes}\n }\n }\n\n\n render() {\n const {title, types, showCreateButton, createButtonText} = this.props\n const {documents, loading, error} = this.state\n\n return (\n <div className={styles.container}>\n <header className={styles.header}>\n <h2 className={styles.title}>{title}</h2>\n </header>\n <div className={styles.content}>\n {error && <div>{error.message}</div>}\n {!error && loading && <Spinner center message=\"Loading...\" />}\n {(!error && !documents && !loading) && <div>Could not locate any documents :/</div>}\n <List>\n {documents && documents.map(doc => {\n const type = schema.get(doc._type)\n return (\n <Item key={doc._id}>\n <IntentLink\n intent=\"edit\"\n params={{\n type: doc._type,\n id: getPublishedId(doc._id)\n }}\n className={styles.link}\n >\n <SanityPreview layout=\"default\" type={type} value={doc} key={doc._id} />\n </IntentLink>\n </Item>\n )\n\n })}\n </List>\n </div>\n {types && types.length === 1 && showCreateButton && (\n <div className={styles.footer}>\n <IntentButton bleed color=\"primary\" kind=\"simple\" intent=\"create\" params={{type: types[0]}}>\n {createButtonText || `Create new ${types[0]}`}\n </IntentButton>\n </div>\n )}\n </div>\n )\n }\n}\n\nexport default DocumentList\n"],"file":"DocumentList.js"}
@@ -1,64 +0,0 @@
1
- "use strict";
2
-
3
- var _rxjs = require("rxjs");
4
-
5
- var _operators = require("rxjs/operators");
6
-
7
- var _lodash = require("lodash");
8
-
9
- var _client = _interopRequireDefault(require("part:@sanity/base/client"));
10
-
11
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
-
13
- var withConfig = config => {
14
- return typeof _client.default.withConfig === 'function' ? _client.default.withConfig(config) : _client.default;
15
- };
16
-
17
- var draftId = nonDraftDoc => "drafts.".concat(nonDraftDoc._id);
18
-
19
- var prepareDocumentList = (incoming, apiVersion) => {
20
- if (!incoming) {
21
- return Promise.resolve([]);
22
- }
23
-
24
- var documents = Array.isArray(incoming) ? incoming : [incoming];
25
- var ids = documents.filter(doc => !doc._id.startsWith('drafts.')).map(draftId);
26
- return withConfig({
27
- apiVersion
28
- }).fetch('*[_id in $ids]', {
29
- ids
30
- }).then(drafts => {
31
- var outgoing = documents.map(doc => {
32
- var foundDraft = drafts.find(draft => draft._id === draftId(doc));
33
- return foundDraft || doc;
34
- });
35
- return (0, _lodash.uniqBy)(outgoing, '_id');
36
- }).catch(error => {
37
- throw new Error("Problems fetching docs ".concat(ids, ". Error: ").concat(error.message));
38
- });
39
- };
40
-
41
- var getSubscription = (query, params, apiVersion) => withConfig({
42
- apiVersion
43
- }).listen(query, params, {
44
- events: ['welcome', 'mutation'],
45
- includeResult: false,
46
- visibility: 'query'
47
- }).pipe((0, _operators.switchMap)(event => {
48
- return (0, _rxjs.of)(1).pipe(event.type === 'welcome' ? (0, _operators.tap)() : (0, _operators.delay)(1000), (0, _operators.mergeMap)(() => withConfig({
49
- apiVersion
50
- }).fetch(query, params).then(incoming => {
51
- return prepareDocumentList(incoming, apiVersion);
52
- }).catch(error => {
53
- if (error.message.startsWith('Problems fetching docs')) {
54
- throw error;
55
- }
56
-
57
- throw new Error("Query failed ".concat(query, " and ").concat(JSON.stringify(params), ". Error: ").concat(error.message));
58
- })));
59
- }));
60
-
61
- module.exports = {
62
- getSubscription
63
- };
64
- //# sourceMappingURL=sanityConnector.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sanityConnector.js"],"names":["withConfig","config","sanityClient","draftId","nonDraftDoc","_id","prepareDocumentList","incoming","apiVersion","Promise","resolve","documents","Array","isArray","ids","filter","doc","startsWith","map","fetch","then","drafts","outgoing","foundDraft","find","draft","catch","error","Error","message","getSubscription","query","params","listen","events","includeResult","visibility","pipe","event","type","JSON","stringify","module","exports"],"mappings":";;AAAA;;AACA;;AACA;;AACA;;;;AAEA,IAAMA,UAAU,GAAGC,MAAM,IAAI;AAC3B,SAAO,OAAOC,gBAAaF,UAApB,KAAmC,UAAnC,GACHE,gBAAaF,UAAb,CAAwBC,MAAxB,CADG,GAEHC,eAFJ;AAGD,CAJD;;AAMA,IAAMC,OAAO,GAAGC,WAAW,qBAAcA,WAAW,CAACC,GAA1B,CAA3B;;AAEA,IAAMC,mBAAmB,GAAG,CAACC,QAAD,EAAWC,UAAX,KAA0B;AACpD,MAAI,CAACD,QAAL,EAAe;AACb,WAAOE,OAAO,CAACC,OAAR,CAAgB,EAAhB,CAAP;AACD;;AACD,MAAMC,SAAS,GAAGC,KAAK,CAACC,OAAN,CAAcN,QAAd,IAA0BA,QAA1B,GAAqC,CAACA,QAAD,CAAvD;AAEA,MAAMO,GAAG,GAAGH,SAAS,CAClBI,MADS,CACFC,G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/B,EAAsCC,MAAtC,EACZZ,IADY,CACPb,QAAQ,IAAI;AAChB,WAAOD,mBAAmB,CAACC,QAAD,EAAWC,UAAX,CAA1B;AACD,GAHY,EAIZkB,KAJY,CAINC,KAAK,IAAI;AACd,QAAIA,KAAK,CAACE,OAAN,CAAcZ,UAAd,CAAyB,wBAAzB,CAAJ,EAAwD;AACtD,YAAMU,KAAN;AACD;;AACD,UAAM,IAAIC,KAAJ,wBAA0BG,KAA1B,kBAAuCS,IAAI,CAACC,SAAL,CAAeT,MAAf,CAAvC,sBAAyEL,KAAK,CAACE,OAA/E,EAAN;AACD,GATY,CAAf,CAFK,CAAP;AAaD,CAdK,CAFR,CADF;;AAoBAa,MAAM,CAACC,OAAP,GAAiB;AACfb,EAAAA;AADe,CAAjB","sourcesContent":["import {of as observableOf} from 'rxjs'\nimport {switchMap, delay, tap, mergeMap} from 'rxjs/operators'\nimport {uniqBy} from 'lodash'\nimport sanityClient from 'part:@sanity/base/client'\n\nconst withConfig = config => {\n return typeof sanityClient.withConfig === 'function'\n ? sanityClient.withConfig(config)\n : sanityClient\n}\n\nconst draftId = nonDraftDoc => `drafts.${nonDraftDoc._id}`\n\nconst prepareDocumentList = (incoming, apiVersion) => {\n if (!incoming) {\n return Promise.resolve([])\n }\n const documents = Array.isArray(incoming) ? incoming : [incoming]\n\n const ids = documents\n .filter(doc => !doc._id.startsWith('drafts.'))\n .map(draftId)\n\n return withConfig({apiVersion}).fetch('*[_id in $ids]', {ids})\n .then(drafts => {\n const outgoing = documents.map(doc => {\n const foundDraft = drafts.find(draft => draft._id === draftId(doc))\n return foundDraft || doc\n })\n return uniqBy(outgoing, '_id')\n })\n .catch(error => {\n throw new Error(`Problems fetching docs ${ids}. Error: ${error.message}`)\n })\n}\n\nconst getSubscription = (query, params, apiVersion) =>\n withConfig({apiVersion})\n .listen(query, params, {events: ['welcome', 'mutation'], includeResult: false, visibility: 'query'})\n .pipe(switchMap(event => {\n return observableOf(1).pipe(\n event.type === 'welcome' ? tap() : delay(1000),\n mergeMap(() => withConfig({apiVersion}).fetch(query, params)\n .then(incoming => {\n return prepareDocumentList(incoming, apiVersion)\n })\n .catch(error => {\n if (error.message.startsWith('Problems fetching docs')) {\n throw error\n }\n throw new Error(`Query failed ${query} and ${JSON.stringify(params)}. Error: ${error.message}`)\n }))\n )\n }))\n\n\nmodule.exports = {\n getSubscription\n}\n"],"file":"sanityConnector.js"}