sanity-plugin-dashboard-widget-document-list 0.1.0 → 1.0.1

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) 2022, 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,110 +1,112 @@
1
- # dashboard-widget-document-list
1
+ # sanity-plugin-dashboard-widget-document-list
2
2
 
3
- >This is a **Sanity Studio v2** plugin.
4
- > For the v3 version, please refer to the [v3-branch](https://github.com/sanity-io/dashboard-widget-document-list).
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).
5
5
 
6
- Dashboard widget for the Sanity Content Studio which displays a list of documents
6
+ ## What is it?
7
7
 
8
- ## Usage
9
- 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.
10
9
 
11
- 1. Install this widget in your Studio folder like so:
10
+ ## Install
12
11
 
13
- ```sh
14
- yarn add sanity-plugin-dashboard-widget-document-list@studio-v2
15
12
  ```
13
+ npm install --save sanity-plugin-dashboard-widget-document-list
14
+ ```
15
+
16
+ or
16
17
 
17
- Next, add `"dashboard-widget-document-list"` to `sanity.json` plugins array:
18
- ```json
19
- "plugins": [
20
- "dashboard-widget-document-list"
21
- ]
22
18
  ```
19
+ yarn add sanity-plugin-dashboard-widget-document-list
20
+ ```
21
+
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):
23
27
 
24
- 2. Update your `src/dashboardConfig.js` file by adding `{name: 'document-list'}` to the `widgets` array
25
- 3. Restart your Studio
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
+ ```
26
44
 
27
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.
28
46
 
29
- There are some options available:
47
+ ## Options
48
+
49
+ There are some options available, as specified by [DocumentListConfig](src/DocumentList.tsx):
30
50
 
31
51
  ### `title` (string)
32
52
  Widget title
33
53
 
34
54
  ```js
35
- {
36
- name: 'document-list',
37
- options: {
55
+ documentListWidget({
38
56
  title: 'Some documents'
39
- }
40
- }
57
+ })
41
58
  ```
42
59
 
43
60
  ### `order` (string)
44
61
  Field and direction to order by when docs are rendered
45
62
 
46
63
  ```js
47
- {
48
- name: 'document-list',
49
- options: {
64
+ documentListWidget({
50
65
  title: 'Last edited',
51
66
  order: '_updatedAt desc'
52
- }
53
- }
67
+ })
54
68
  ```
55
69
 
56
70
  ### `limit` (number)
57
71
  Number of docs rendered
58
72
 
59
73
  ```js
60
- {
61
- name: 'document-list',
62
- options: {
74
+ documentListWidget({
63
75
  title: 'Last edited',
64
76
  order: '_updatedAt desc',
65
77
  limit: 3
66
- }
67
- }
78
+ })
68
79
  ```
69
80
 
70
81
  ### `types` (array)
71
82
  Array of strings signifying which document (schema) types are fetched
72
83
 
73
84
  ```js
74
- {
75
- name: 'document-list',
76
- options: {
85
+ documentListWidget({
77
86
  title: 'Last edited',
78
87
  order: '_updatedAt desc',
79
88
  types: ['book', 'author']
80
- }
81
- }
89
+ })
82
90
  ```
83
91
 
84
92
  ### `query` (string) and `params` (object)
85
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.
86
94
 
87
95
  ```js
88
- {
89
- name: 'document-list',
90
- options: {
96
+ documentListWidget({
91
97
  title: 'Published books by title',
92
98
  query: '*[_type == "book" && published == true] | order(title asc) [0...10]'
93
- }
94
- }
99
+ })
95
100
  ```
96
101
 
97
102
  ```js
98
- {
99
- name: 'document-list',
100
- options: {
103
+ documentListWidget({
101
104
  title: 'My favorite documents',
102
105
  query: '*[_id in $ids]',
103
106
  params: {
104
107
  ids: ['ab2', 'c5z', '654']
105
108
  }
106
- }
107
- }
109
+ })
108
110
  ```
109
111
 
110
112
  ### `createButtonText` (string)
@@ -112,14 +114,11 @@ Customized GROQ query with params for maximum control. If you use the query opti
112
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.
113
115
 
114
116
  ```js
115
- {
116
- name: 'document-list',
117
- options: {
117
+ documentListWidget({
118
118
  title: 'Blog posts',
119
119
  query: '*[_type == "post"]',
120
120
  createButtonText: 'Create new blog post'
121
- }
122
- }
121
+ })
123
122
  ```
124
123
 
125
124
  ### `showCreateButton` (boolean)
@@ -127,10 +126,35 @@ You can override the button default button text (`Create new ${types[0]}`) by se
127
126
  You can disable the create button altogether by passing a `showCreateButton` boolean:
128
127
 
129
128
  ```js
130
- {
131
- name: 'document-list',
132
- options: {
129
+ documentListWidget({
133
130
  showCreateButton: false
134
- }
135
- }
131
+ })
136
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,Preview 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, Preview} 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 <Preview 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","Preview","layout","value","documentListWidget","config","component","_objectSpread"],"mappings":"srCAMA,MAAMA,EAAWC,oBAA0CA,EAAYC,KA2BvD,SAAAC,EACdC,EACAC,EACAC,GAEO,OAAAA,EACJC,OAA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AAA,CAAKC,QAAS,EACbH,SAACd,EAAAkB,EAAA,CAAKC,QAAQ,SACZL,SAACd,EAAAoB,EAAA,CAAQC,OAAK,SAIlBlE,IAAUd,IAAciC,GAAY0B,EAAA,MAAA,CAAIc,SAAA,sCACzCd,EAAAsB,EAAA,CAAMC,MAAO,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,CAAQC,OAAO,UAAU7C,WAAYvD,EAAMqG,MAAOvF,GAAUA,EAAI3B,KAEjE,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.Preview,{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, Preview} 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 <Preview 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","Preview","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,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,WACEd,EAAAA,IAAA+B,UAAA,CAAQC,OAAO,UAAU7C,WAAYvD,EAAMqG,MAAOvF,GAAUA,EAAI5B,KAEjE,yBAKV,4BChJO,SAA4BoH,GAC1B,MAAA,CACL7C,KAAM,uBACN8C,UAAW,WACT,OAAQnC,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,7 +1,7 @@
1
1
  {
2
2
  "name": "sanity-plugin-dashboard-widget-document-list",
3
- "version": "0.1.0",
4
- "description": "Example dashboard widget for Sanity Content Studio",
3
+ "version": "1.0.1",
4
+ "description": "> **NOTE**",
5
5
  "keywords": [
6
6
  "sanity",
7
7
  "plugin",
@@ -20,33 +20,76 @@
20
20
  },
21
21
  "license": "MIT",
22
22
  "author": "Sanity.io <hello@sanity.io>",
23
- "main": "lib/index.js",
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"
32
+ },
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
+ ],
24
43
  "scripts": {
25
- "prebuild": "npm run clean",
26
- "build": "sanipack build",
44
+ "prebuild": "npm run clean && plugin-kit verify-package --silent && pkg-utils",
45
+ "build": "pkg-utils build --strict",
27
46
  "clean": "rimraf lib",
28
- "prepublishOnly": "npm run build && npm test",
29
- "test": "sanipack verify"
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"
30
53
  },
31
54
  "dependencies": {
55
+ "@sanity/incompatible-plugin": "^1.0.4",
56
+ "@sanity/ui": "^1.0.0",
32
57
  "lodash": "^4.17.15",
33
- "prop-types": "^15.7.2",
34
58
  "rxjs": "^6.0.0"
35
59
  },
36
60
  "devDependencies": {
37
- "@commitlint/cli": "^17.1.2",
38
- "@commitlint/config-conventional": "^17.1.0",
39
- "@sanity/semantic-release-preset": "^2.0.1",
40
- "babel-eslint": "^7.2.3",
41
- "eslint": "^4.3.0",
42
- "eslint-config-sanity": "^2.1.4",
43
- "eslint-plugin-react": "^7.1.0",
44
- "rimraf": "^2.7.1",
45
- "sanipack": "^1.0.8"
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",
83
+ "typescript": "^4.8.4"
46
84
  },
47
85
  "peerDependencies": {
48
- "@sanity/base": ">=1",
49
- "react": "^16 || ^17"
86
+ "@sanity/dashboard": "^3.0.0-v3-studio.8",
87
+ "react": "^18",
88
+ "sanity": "^3.0.0"
89
+ },
90
+ "engines": {
91
+ "node": ">=14"
50
92
  },
51
- "public": true
93
+ "public": true,
94
+ "sanityExchangeUrl": "https://www.sanity.io/plugins/sanity-plugin-dashboard-widget-document-list"
52
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, Preview} 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
+ <Preview 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,133 +0,0 @@
1
- ---
2
- name: CI & Release
3
-
4
- # Workflow name based on selected inputs. Fallback to default Github naming when expression evaluates to empty string
5
- run-name: >-
6
- ${{
7
- inputs.release && inputs.test && format('Build {0} ➤ Test ➤ Publish to NPM', github.ref_name) ||
8
- inputs.release && !inputs.test && format('Build {0} ➤ Skip Tests ➤ Publish to NPM', github.ref_name) ||
9
- github.event_name == 'workflow_dispatch' && inputs.test && format('Build {0} ➤ Test', github.ref_name) ||
10
- github.event_name == 'workflow_dispatch' && !inputs.test && format('Build {0} ➤ Skip Tests', github.ref_name) ||
11
- ''
12
- }}
13
-
14
- on:
15
- # Build on pushes branches that have a PR (including drafts)
16
- pull_request:
17
- # Build on commits pushed to branches without a PR if it's in the allowlist
18
- push:
19
- branches: [main,studio-v2]
20
- # https://docs.github.com/en/actions/managing-workflow-runs/manually-running-a-workflow
21
- workflow_dispatch:
22
- inputs:
23
- test:
24
- description: Run tests
25
- required: true
26
- default: true
27
- type: boolean
28
- release:
29
- description: Release new version
30
- required: true
31
- default: false
32
- type: boolean
33
-
34
- concurrency:
35
- # On PRs builds will cancel if new pushes happen before the CI completes, as it defines `github.head_ref` and gives it the name of the branch the PR wants to merge into
36
- # Otherwise `github.run_id` ensures that you can quickly merge a queue of PRs without causing tests to auto cancel on any of the commits pushed to main.
37
- group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
38
- cancel-in-progress: true
39
-
40
- jobs:
41
- log-the-inputs:
42
- name: Log inputs
43
- runs-on: ubuntu-latest
44
- steps:
45
- - run: |
46
- echo "Inputs: $INPUTS"
47
- env:
48
- INPUTS: ${{ toJSON(inputs) }}
49
-
50
- build:
51
- runs-on: ubuntu-latest
52
- name: Lint & Build
53
- steps:
54
- - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag=v3
55
- - uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516 # tag=v3
56
- with:
57
- cache: npm
58
- node-version: lts/*
59
- - run: npm ci
60
- # Linting can be skipped
61
- - run: npm run lint --if-present
62
- if: github.event.inputs.test != 'false'
63
- # But not the build script, as semantic-release will crash if this command fails so it makes sense to test it early
64
- - run: npm run prepublishOnly --if-present
65
-
66
- # test:
67
- # needs: build
68
- # # The test matrix can be skipped, in case a new release needs to be fast-tracked and tests are already passing on main
69
- # if: github.event.inputs.test != 'false'
70
- # runs-on: ${{ matrix.os }}
71
- # name: Node.js ${{ matrix.node }} / ${{ matrix.os }}
72
- # strategy:
73
- # # A test failing on windows doesn't mean it'll fail on macos. It's useful to let all tests run to its completion to get the full picture
74
- # fail-fast: false
75
- # matrix:
76
- # # Run the testing suite on each major OS with the latest LTS release of Node.js
77
- # os: [macos-latest, ubuntu-latest, windows-latest]
78
- # node: [lts/*]
79
- # # It makes sense to also test the oldest, and latest, versions of Node.js, on ubuntu-only since it's the fastest CI runner
80
- # include:
81
- # - os: ubuntu-latest
82
- # # Test the oldest LTS release of Node that's still receiving bugfixes and security patches, versions older than that have reached End-of-Life
83
- # node: lts/-2
84
- # - os: ubuntu-latest
85
- # # Test the actively developed version that will become the latest LTS release next October
86
- # node: current
87
- # steps:
88
- # # It's only necessary to do this for windows, as mac and ubuntu are sane OS's that already use LF
89
- # - name: Set git to use LF
90
- # if: matrix.os == 'windows-latest'
91
- # run: |
92
- # git config --global core.autocrlf false
93
- # git config --global core.eol lf
94
- # - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag=v3
95
- # - uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516 # tag=v3
96
- # with:
97
- # cache: npm
98
- # node-version: ${{ matrix.node }}
99
- # - run: npm i
100
- # - run: npm test --if-present
101
-
102
- release:
103
- # needs: [build, test]
104
- needs: [build]
105
- # only run if opt-in during workflow_dispatch
106
- if: always() && github.event.inputs.release == 'true' && needs.build.result != 'failure' && needs.test.result != 'failure' && needs.test.result != 'cancelled'
107
- runs-on: ubuntu-latest
108
- name: Semantic release
109
- steps:
110
- - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag=v3
111
- with:
112
- # Need to fetch entire commit history to
113
- # analyze every commit since last release
114
- fetch-depth: 0
115
- - uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516 # tag=v3
116
- with:
117
- cache: npm
118
- node-version: lts/*
119
- - run: npm ci
120
- # Branches that will release new versions are defined in .releaserc.json
121
- - run: npx semantic-release
122
- # Don't allow interrupting the release step if the job is cancelled, as it can lead to an inconsistent state
123
- # e.g. git tags were pushed but it exited before `npm publish`
124
- if: always()
125
- env:
126
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
127
- NPM_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
128
- # Re-run semantic release with rich logs if it failed to publish for easier debugging
129
- - run: npx semantic-release --dry-run --debug
130
- if: failure()
131
- env:
132
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
133
- NPM_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
package/.releaserc.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "extends": "@sanity/semantic-release-preset",
3
- "branches": [
4
- "main",
5
- { "name": "studio-v2", "channel": "studio-v2", "range": "0.1.x" }
6
- ]
7
- }
package/CHANGELOG.md DELETED
@@ -1,18 +0,0 @@
1
- <!-- markdownlint-disable --><!-- textlint-disable -->
2
-
3
- # 📓 Changelog
4
-
5
- All notable changes to this project will be documented in this file. See
6
- [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
7
-
8
- ## [0.1.0](https://github.com/sanity-io/dashboard-widget-document-list/compare/v0.0.13...v0.1.0) (2022-11-22)
9
-
10
- ### Features
11
-
12
- - make semantic-release happy (not really a feat) ([afe6342](https://github.com/sanity-io/dashboard-widget-document-list/commit/afe634251827e4651422ea82e4841954447d2e35))
13
-
14
- ### Bug Fixes
15
-
16
- - added workflow so it can be triggered from v3 ([1fcacd7](https://github.com/sanity-io/dashboard-widget-document-list/commit/1fcacd76267754c7a8c8480ceb04d10c3fda981b))
17
- - **ci:** publish using semantic-release ([8f5b196](https://github.com/sanity-io/dashboard-widget-document-list/commit/8f5b1964c484552bc712d88c962c94f9cf150004))
18
- - typo ([3929617](https://github.com/sanity-io/dashboard-widget-document-list/commit/39296177e02b56c4748eff1fcaabcd275e746c06))
@@ -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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D,CAAvB,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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+BY,KAA/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"}