sanity-plugin-documents-pane 1.0.7 → 1.1.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/README.md CHANGED
@@ -12,7 +12,7 @@ sanity install documents-pane
12
12
 
13
13
  This plugin is designed to be used as a [Component inside of a View](https://www.sanity.io/docs/structure-builder-reference#c0c8284844b7).
14
14
 
15
- The example below illustrates using the current Document being used to query for all Documents that reference it.
15
+ The example below illustrates using the current Document being used to query for all published documents that reference it.
16
16
 
17
17
  ```js
18
18
  // ./src/deskStructure.js
@@ -25,18 +25,64 @@ S.view
25
25
  .options({
26
26
  query: `*[!(_id in path("drafts.**")) && references($id)]`,
27
27
  params: {id: `_id`},
28
- useDraft: false,
29
- debug: true,
30
28
  })
31
29
  .title('Incoming References')
32
30
  ```
33
31
 
34
32
  The `.options()` configuration works as follows:
35
33
 
36
- - `query` (string, required)
37
- - `params` (object, optional) A [dot-notated string](https://www.npmjs.com/package/dlv) from the document object to a field, to use as variables in the query.
38
- - `useDraft` (bool, optional, default: `false`) When populating the `params` values, it will use the `published` version of the document by default.
34
+ - `query` (string, required) A string defining the entire GROQ query that will select documents to list.
35
+ - `params` (object or function, optional)
36
+ - Object: a [dot-notated string](https://www.npmjs.com/package/dlv) from the document object to a field, to use as variables in the query.
37
+ - Function: a function that receives the various displayed, draft, and published versions of the document, and returns an object of query parameters. Return null if the parameters cannot be resolved.
38
+ - `useDraft` (bool, optional, default: `false`) When populating the `params` values, it will use the `published` version of the document by default. Not permitted if using a function for `params` as the function will determine which version of the document to use.
39
39
  - `debug` (bool, optional, default: `false`) In case of an error or the query returning no documents, setting to `true` will display the query and params that were used.
40
+ - `initialValueTemplates` (function, optional) A function that receives the various displayed, draft, and published versions of the document, and returns a list of initial value templates. These will be used to define buttons at the top of the list so users can create new related documents.
41
+
42
+
43
+ ## Resolving query parameters with a function and providing initial value templates
44
+ Providing a function for `params` allows us to modify values from the current document, for example to list references to a draft document. Providing a function for the `initialValueTemplates` option allows us to determine which buttons to show and what parameters will be used for the new document.
45
+ ```js
46
+ const options = {
47
+ query: `*[_type=="post" && author._ref == $id]`,
48
+ params: ({document}) => {
49
+ // references will never point to a draft ID, so extract the regular ID
50
+ const id = document.displayed._id?.replace('drafts.', '')
51
+
52
+ // we don't have to worry about undefined parameters,
53
+ // as the plugin will handle them and show an appropriate message
54
+ return {id}
55
+ },
56
+ initialValueTemplates: ({document}) => {
57
+ const templates = []
58
+
59
+ // references must point to a non-draft ID, so if using the ID in the template,
60
+ // be sure it doesn't start with `drafts.`
61
+ const id = document?.displayed?._id.replace('drafts.', '')
62
+ const name = document?.displayed?.name || 'author'
63
+
64
+ if (id) {
65
+ templates.push({
66
+ // the name of the schema type that should be created (required)
67
+ schemaType: 'post',
68
+ // the title that should appear on the button - we can customize it (required)
69
+ title: `New post by ${name}`,
70
+ // the name of the template that should be used (optional)
71
+ template: 'postWithAuthor',
72
+ // values for parameters that can be passed to the template referenced above (optional)
73
+ parameters: {
74
+ authorId: id,
75
+ },
76
+ })
77
+
78
+ // we could push more templates if needed.
79
+ }
80
+
81
+ // must always return a list, even if empty
82
+ return templates
83
+ },
84
+ }
85
+ ```
40
86
 
41
87
  ## Thanks!
42
88
 
package/lib/Debug.js CHANGED
@@ -16,7 +16,7 @@ function Debug(_ref) {
16
16
  params = _ref.params;
17
17
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ui.Stack, {
18
18
  space: 4
19
- }, /*#__PURE__*/_react.default.createElement(_ui.Box, null, /*#__PURE__*/_react.default.createElement(_ui.Label, null, "Query")), /*#__PURE__*/_react.default.createElement(_ui.Box, null, /*#__PURE__*/_react.default.createElement(_ui.Code, null, query))), /*#__PURE__*/_react.default.createElement(_ui.Stack, {
19
+ }, /*#__PURE__*/_react.default.createElement(_ui.Box, null, /*#__PURE__*/_react.default.createElement(_ui.Label, null, "Query")), /*#__PURE__*/_react.default.createElement(_ui.Box, null, /*#__PURE__*/_react.default.createElement(_ui.Code, null, query))), params && /*#__PURE__*/_react.default.createElement(_ui.Stack, {
20
20
  space: 4
21
21
  }, /*#__PURE__*/_react.default.createElement(_ui.Box, null, /*#__PURE__*/_react.default.createElement(_ui.Label, null, "Params")), /*#__PURE__*/_react.default.createElement(_ui.Box, null, /*#__PURE__*/_react.default.createElement(_ui.Code, null, JSON.stringify(params)))));
22
22
  }
package/lib/Debug.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Debug.tsx"],"names":["Debug","query","params","JSON","stringify"],"mappings":";;;;;;;AAAA;;AACA;;;;AAEe,SAASA,KAAT,OAAgC;AAAA,MAAhBC,KAAgB,QAAhBA,KAAgB;AAAA,MAATC,MAAS,QAATA,MAAS;AAC7C,sBACE,yEACE,6BAAC,SAAD;AAAO,IAAA,KAAK,EAAE;AAAd,kBACE,6BAAC,OAAD,qBAAK,6BAAC,SAAD,gBAAL,CADF,eAEE,6BAAC,OAAD,qBACE,6BAAC,QAAD,QAAOD,KAAP,CADF,CAFF,CADF,eAOE,6BAAC,SAAD;AAAO,IAAA,KAAK,EAAE;AAAd,kBACE,6BAAC,OAAD,qBAAK,6BAAC,SAAD,iBAAL,CADF,eAEE,6BAAC,OAAD,qBACE,6BAAC,QAAD,QAAOE,IAAI,CAACC,SAAL,CAAeF,MAAf,CAAP,CADF,CAFF,CAPF,CADF;AAgBD","sourcesContent":["import React from 'react'\nimport {Code, Box, Label, Stack} from '@sanity/ui'\n\nexport default function Debug({query, params}) {\n return (\n <>\n <Stack space={4}>\n <Box><Label>Query</Label></Box>\n <Box>\n <Code>{query}</Code>\n </Box>\n </Stack>\n <Stack space={4}>\n <Box><Label>Params</Label></Box>\n <Box>\n <Code>{JSON.stringify(params)}</Code>\n </Box>\n </Stack>\n </>\n )\n}\n"],"file":"Debug.js"}
1
+ {"version":3,"file":"Debug.js","names":["Debug","query","params","JSON","stringify"],"sources":["../src/Debug.tsx"],"sourcesContent":["import React from 'react'\nimport {Code, Box, Label, Stack} from '@sanity/ui'\n\nexport default function Debug({query, params}: {query: string; params?: {[key: string]: string}}) {\n return (\n <>\n <Stack space={4}>\n <Box>\n <Label>Query</Label>\n </Box>\n <Box>\n <Code>{query}</Code>\n </Box>\n </Stack>\n {params && (\n <Stack space={4}>\n <Box>\n <Label>Params</Label>\n </Box>\n <Box>\n <Code>{JSON.stringify(params)}</Code>\n </Box>\n </Stack>\n )}\n </>\n )\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;;;AAEe,SAASA,KAAT,OAAmF;EAAA,IAAnEC,KAAmE,QAAnEA,KAAmE;EAAA,IAA5DC,MAA4D,QAA5DA,MAA4D;EAChG,oBACE,yEACE,6BAAC,SAAD;IAAO,KAAK,EAAE;EAAd,gBACE,6BAAC,OAAD,qBACE,6BAAC,SAAD,gBADF,CADF,eAIE,6BAAC,OAAD,qBACE,6BAAC,QAAD,QAAOD,KAAP,CADF,CAJF,CADF,EASGC,MAAM,iBACL,6BAAC,SAAD;IAAO,KAAK,EAAE;EAAd,gBACE,6BAAC,OAAD,qBACE,6BAAC,SAAD,iBADF,CADF,eAIE,6BAAC,OAAD,qBACE,6BAAC,QAAD,QAAOC,IAAI,CAACC,SAAL,CAAeF,MAAf,CAAP,CADF,CAJF,CAVJ,CADF;AAsBD"}
package/lib/Documents.js CHANGED
@@ -5,76 +5,64 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = Documents;
7
7
 
8
- var _react = _interopRequireDefault(require("react"));
9
-
10
- var _reactQuery = require("react-query");
8
+ var _react = _interopRequireWildcard(require("react"));
11
9
 
12
10
  var _ui = require("@sanity/ui");
13
11
 
14
- var _deskTool = require("@sanity/desk-tool");
12
+ var _paths = require("@sanity/util/paths");
15
13
 
16
- var _RouterContext = require("@sanity/state-router/lib/RouterContext");
14
+ var _deskTool = require("@sanity/desk-tool");
17
15
 
18
16
  var _preview = _interopRequireDefault(require("part:@sanity/base/preview"));
19
17
 
20
18
  var _schema = _interopRequireDefault(require("part:@sanity/base/schema"));
21
19
 
22
- var _client = _interopRequireDefault(require("part:@sanity/base/client"));
23
-
24
20
  var _Debug = _interopRequireDefault(require("./Debug"));
25
21
 
26
22
  var _Feedback = _interopRequireDefault(require("./Feedback"));
27
23
 
24
+ var _useListeningQuery2 = _interopRequireDefault(require("./hooks/useListeningQuery"));
25
+
26
+ var _NewDocument = _interopRequireDefault(require("./NewDocument"));
27
+
28
28
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29
29
 
30
- var client = _client.default.withConfig({
31
- apiVersion: "2021-05-19"
32
- });
30
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
31
+
32
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
33
33
 
34
34
  function Documents(props) {
35
35
  var query = props.query,
36
36
  params = props.params,
37
37
  debug = props.debug,
38
- _rev = props._rev;
39
-
40
- var _useQuery = (0, _reactQuery.useQuery)(['useDocuments', {
41
- props
42
- }], () => client.fetch(query, params)),
43
- isLoading = _useQuery.isLoading,
44
- error = _useQuery.error,
45
- data = _useQuery.data;
46
-
47
- var routerContext = _react.default.useContext(_RouterContext.RouterContext);
38
+ initialValueTemplates = props.initialValueTemplates;
48
39
 
49
40
  var _usePaneRouter = (0, _deskTool.usePaneRouter)(),
50
41
  routerPanesState = _usePaneRouter.routerPanesState,
51
- groupIndex = _usePaneRouter.groupIndex;
52
-
53
- var openDocumentInSidePane = _react.default.useCallback((id, type) => {
54
- var newPane = [{
55
- id: id,
56
- params: {
57
- type
58
- }
59
- }];
60
- var panes = [routerPanesState[0], routerPanesState[1], newPane];
61
- var href = routerContext.resolvePathFromState({
62
- panes
42
+ groupIndex = _usePaneRouter.groupIndex,
43
+ handleEditReference = _usePaneRouter.handleEditReference;
44
+
45
+ var _useListeningQuery = (0, _useListeningQuery2.default)(query, params),
46
+ loading = _useListeningQuery.loading,
47
+ error = _useListeningQuery.error,
48
+ data = _useListeningQuery.data;
49
+
50
+ var handleClick = (0, _react.useCallback)((id, type) => {
51
+ var _routerPanesState;
52
+
53
+ var childParams = ((_routerPanesState = routerPanesState[groupIndex + 1]) === null || _routerPanesState === void 0 ? void 0 : _routerPanesState[0].params) || {};
54
+ var parentRefPath = childParams.parentRefPath;
55
+ handleEditReference({
56
+ id,
57
+ type,
58
+ // Uncertain that this works as intended
59
+ parentRefPath: parentRefPath ? (0, _paths.fromString)(parentRefPath) : [""],
60
+ // Added this to satisfy TS
61
+ template: type
63
62
  });
64
- routerContext.navigateUrl(href);
65
- }, [routerContext, routerPanesState, groupIndex]);
66
-
67
- if (!_rev) {
68
- return /*#__PURE__*/_react.default.createElement(_ui.Stack, {
69
- padding: 4,
70
- space: 5
71
- }, /*#__PURE__*/_react.default.createElement(_Feedback.default, null, "Document must be Published"), debug && /*#__PURE__*/_react.default.createElement(_Debug.default, {
72
- query: query,
73
- params: params
74
- }));
75
- }
63
+ }, [routerPanesState, groupIndex, handleEditReference]);
76
64
 
77
- if (isLoading) {
65
+ if (loading) {
78
66
  return /*#__PURE__*/_react.default.createElement(_ui.Box, {
79
67
  padding: 4
80
68
  }, /*#__PURE__*/_react.default.createElement(_ui.Flex, {
@@ -96,27 +84,30 @@ function Documents(props) {
96
84
  }
97
85
 
98
86
  if (!(data !== null && data !== void 0 && data.length)) {
99
- return /*#__PURE__*/_react.default.createElement(_ui.Stack, {
87
+ return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_NewDocument.default, {
88
+ initialValueTemplates: initialValueTemplates
89
+ }), /*#__PURE__*/_react.default.createElement(_ui.Stack, {
100
90
  padding: 4,
101
91
  space: 5
102
92
  }, /*#__PURE__*/_react.default.createElement(_Feedback.default, null, "No Documents found"), debug && /*#__PURE__*/_react.default.createElement(_Debug.default, {
103
93
  query: query,
104
94
  params: params
105
- }));
95
+ })));
106
96
  }
107
97
 
108
- return /*#__PURE__*/_react.default.createElement(_ui.Stack, {
98
+ return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_NewDocument.default, {
99
+ initialValueTemplates: initialValueTemplates
100
+ }), /*#__PURE__*/_react.default.createElement(_ui.Stack, {
109
101
  padding: 2,
110
- space: 2
102
+ space: 1
111
103
  }, data.map(doc => /*#__PURE__*/_react.default.createElement(_ui.Button, {
112
104
  key: doc._id,
113
- onClick: () => openDocumentInSidePane(doc._id, doc._type),
114
- mode: "bleed",
115
- radius: 2,
116
- padding: 2
105
+ onClick: () => handleClick(doc._id, doc._type),
106
+ padding: 2,
107
+ mode: "bleed"
117
108
  }, /*#__PURE__*/_react.default.createElement(_preview.default, {
118
109
  value: doc,
119
110
  type: _schema.default.get(doc._type)
120
- }))));
111
+ })))));
121
112
  }
122
113
  //# sourceMappingURL=Documents.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Documents.tsx"],"names":["client","sanityClient","withConfig","apiVersion","Documents","props","query","params","debug","_rev","fetch","isLoading","error","data","routerContext","React","useContext","RouterContext","routerPanesState","groupIndex","openDocumentInSidePane","useCallback","id","type","newPane","panes","href","resolvePathFromState","navigateUrl","length","map","doc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AD;AAAO,IAAA,OAAO,EAAE,CAAhB;AAAmB,IAAA,KAAK,EAAE;AAA1B,KACGM,IAAI,CAACiB,GAAL,CAAUC,GAAD,iBACR,6BAAC,UAAD;AACE,IAAA,GAAG,EAAEA,GAAG,CAACC,GADX;AAEE,IAAA,OAAO,EAAE,MAAMZ,sBAAsB,CAACW,GAAG,CAACC,GAAL,EAAUD,GAAG,CAACE,KAAd,CAFvC;AAGE,IAAA,IAAI,EAAC,OAHP;AAIE,IAAA,MAAM,EAAE,CAJV;AAKE,IAAA,OAAO,EAAE;AALX,kBAOE,6BAAC,gBAAD;AAAS,IAAA,KAAK,EAAEF,GAAhB;AAAqB,IAAA,IAAI,EAAEG,gBAAOC,GAAP,CAAWJ,GAAG,CAACE,KAAf;AAA3B,IAPF,CADD,CADH,CADF;AAeD","sourcesContent":["import React from 'react'\nimport {useQuery} from 'react-query'\nimport {Button, Box, Stack, Flex, Spinner} from '@sanity/ui'\nimport {usePaneRouter} from '@sanity/desk-tool'\nimport {RouterContext} from '@sanity/state-router/lib/RouterContext'\nimport Preview from 'part:@sanity/base/preview'\nimport schema from 'part:@sanity/base/schema'\nimport sanityClient from 'part:@sanity/base/client'\n\nimport Debug from './Debug'\nimport Feedback from './Feedback'\n\n const client = sanityClient.withConfig({apiVersion: `2021-05-19`})\n\nexport default function Documents(props) {\n const {query, params, debug, _rev} = props\n\n const {isLoading, error, data} = useQuery(['useDocuments', {props}], () =>\n client.fetch(query, params)\n )\n\n const routerContext = React.useContext(RouterContext)\n const {routerPanesState, groupIndex} = usePaneRouter()\n\n const openDocumentInSidePane = React.useCallback(\n (id: string, type: string) => {\n const newPane = [\n {\n id: id,\n params: {type},\n },\n ]\n let panes = [routerPanesState[0], routerPanesState[1], newPane]\n\n const href = routerContext.resolvePathFromState({panes})\n routerContext.navigateUrl(href)\n },\n [routerContext, routerPanesState, groupIndex]\n )\n\n if (!_rev) {\n return (\n <Stack padding={4} space={5}>\n <Feedback>Document must be Published</Feedback>\n {debug && <Debug query={query} params={params} />}\n </Stack>\n )\n }\n\n if (isLoading) {\n return (\n <Box padding={4}>\n <Flex justify=\"center\" align=\"center\">\n <Spinner muted />\n </Flex>\n </Box>\n )\n }\n\n if (error) {\n return (\n <Stack padding={4} space={5}>\n <Feedback>There was en error performing this query</Feedback>\n {debug && <Debug query={query} params={params} />}\n </Stack>\n )\n }\n\n if (!data?.length) {\n return (\n <Stack padding={4} space={5}>\n <Feedback>No Documents found</Feedback>\n {debug && <Debug query={query} params={params} />}\n </Stack>\n )\n }\n\n return (\n <Stack padding={2} space={2}>\n {data.map((doc) => (\n <Button\n key={doc._id}\n onClick={() => openDocumentInSidePane(doc._id, doc._type)}\n mode=\"bleed\"\n radius={2}\n padding={2}\n >\n <Preview value={doc} type={schema.get(doc._type)} />\n </Button>\n ))}\n </Stack>\n )\n}\n"],"file":"Documents.js"}
1
+ {"version":3,"file":"Documents.js","names":["Documents","props","query","params","debug","initialValueTemplates","usePaneRouter","routerPanesState","groupIndex","handleEditReference","useListeningQuery","loading","error","data","handleClick","useCallback","id","type","childParams","parentRefPath","pathFromString","template","length","map","doc","_id","_type","schema","get"],"sources":["../src/Documents.tsx"],"sourcesContent":["import React, {useCallback} from 'react'\nimport {Box, Button, Stack, Flex, Spinner} from '@sanity/ui'\nimport {fromString as pathFromString} from '@sanity/util/paths'\nimport {usePaneRouter} from '@sanity/desk-tool'\nimport Preview from 'part:@sanity/base/preview'\nimport schema from 'part:@sanity/base/schema'\n\nimport Debug from './Debug'\nimport Feedback from './Feedback'\nimport useListeningQuery from './hooks/useListeningQuery'\nimport {DocumentsPaneInitialValueTemplate} from './types'\nimport NewDocument from './NewDocument'\n\ntype DocumentsProps = {\n query: string\n params: {[key: string]: string}\n debug: boolean\n initialValueTemplates: DocumentsPaneInitialValueTemplate[]\n}\n\nexport default function Documents(props: DocumentsProps) {\n const {query, params, debug, initialValueTemplates} = props\n const {routerPanesState, groupIndex, handleEditReference} = usePaneRouter()\n\n const {loading, error, data} = useListeningQuery(query, params)\n\n const handleClick = useCallback(\n (id, type) => {\n const childParams = routerPanesState[groupIndex + 1]?.[0].params || {}\n const {parentRefPath} = childParams\n\n handleEditReference({\n id,\n type,\n // Uncertain that this works as intended\n parentRefPath: parentRefPath ? pathFromString(parentRefPath) : [``],\n // Added this to satisfy TS\n template: type,\n })\n },\n [routerPanesState, groupIndex, handleEditReference]\n )\n\n if (loading) {\n return (\n <Box padding={4}>\n <Flex justify=\"center\" align=\"center\">\n <Spinner muted />\n </Flex>\n </Box>\n )\n }\n\n if (error) {\n return (\n <Stack padding={4} space={5}>\n <Feedback>There was en error performing this query</Feedback>\n {debug && <Debug query={query} params={params} />}\n </Stack>\n )\n }\n\n if (!data?.length) {\n return (\n <>\n <NewDocument initialValueTemplates={initialValueTemplates} />\n <Stack padding={4} space={5}>\n <Feedback>No Documents found</Feedback>\n {debug && <Debug query={query} params={params} />}\n </Stack>\n </>\n )\n }\n\n return (\n <>\n <NewDocument initialValueTemplates={initialValueTemplates} />\n <Stack padding={2} space={1}>\n {data.map((doc) => (\n <Button\n key={doc._id}\n onClick={() => handleClick(doc._id, doc._type)}\n padding={2}\n mode=\"bleed\"\n >\n <Preview value={doc} type={schema.get(doc._type)} />\n </Button>\n ))}\n </Stack>\n </>\n )\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA;;AACA;;AACA;;AAEA;;;;;;;;AASe,SAASA,SAAT,CAAmBC,KAAnB,EAA0C;EACvD,IAAOC,KAAP,GAAsDD,KAAtD,CAAOC,KAAP;EAAA,IAAcC,MAAd,GAAsDF,KAAtD,CAAcE,MAAd;EAAA,IAAsBC,KAAtB,GAAsDH,KAAtD,CAAsBG,KAAtB;EAAA,IAA6BC,qBAA7B,GAAsDJ,KAAtD,CAA6BI,qBAA7B;;EACA,qBAA4D,IAAAC,uBAAA,GAA5D;EAAA,IAAOC,gBAAP,kBAAOA,gBAAP;EAAA,IAAyBC,UAAzB,kBAAyBA,UAAz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P,CAAJ,EAAmB;IACjB,oBACE,yEACE,6BAAC,oBAAD;MAAa,qBAAqB,EAAEjB;IAApC,EADF,eAEE,6BAAC,SAAD;MAAO,OAAO,EAAE,CAAhB;MAAmB,KAAK,EAAE;IAA1B,gBACE,6BAAC,iBAAD,6BADF,EAEGD,KAAK,iBAAI,6BAAC,cAAD;MAAO,KAAK,EAAEF,KAAd;MAAqB,MAAM,EAAEC;IAA7B,EAFZ,CAFF,CADF;EASD;;EAED,oBACE,yEACE,6BAAC,oBAAD;IAAa,qBAAqB,EAAEE;EAApC,EADF,eAEE,6BAAC,SAAD;IAAO,OAAO,EAAE,CAAhB;IAAmB,KAAK,EAAE;EAA1B,GACGQ,IAAI,CAACU,GAAL,CAAUC,GAAD,iBACR,6BAAC,UAAD;IACE,GAAG,EAAEA,GAAG,CAACC,GADX;IAEE,OAAO,EAAE,MAAMX,WAAW,CAACU,GAAG,CAACC,GAAL,EAAUD,GAAG,CAACE,KAAd,CAF5B;IAGE,OAAO,EAAE,CAHX;IAIE,IAAI,EAAC;EAJP,gBAME,6BAAC,gBAAD;IAAS,KAAK,EAAEF,GAAhB;IAAqB,IAAI,EAAEG,eAAA,CAAOC,GAAP,CAAWJ,GAAG,CAACE,KAAf;EAA3B,EANF,CADD,CADH,CAFF,CADF;AAiBD"}
@@ -7,45 +7,64 @@ exports.default = DocumentsPane;
7
7
 
8
8
  var _react = _interopRequireDefault(require("react"));
9
9
 
10
- var _dlv = _interopRequireDefault(require("dlv"));
11
-
12
- var _reactQuery = require("react-query");
10
+ var _ui = require("@sanity/ui");
13
11
 
14
12
  var _Documents = _interopRequireDefault(require("./Documents"));
15
13
 
16
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
+ var _Feedback = _interopRequireDefault(require("./Feedback"));
17
15
 
18
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
16
+ var _Debug = _interopRequireDefault(require("./Debug"));
19
17
 
20
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
18
+ var _resolveParams = _interopRequireDefault(require("./resolveParams"));
21
19
 
22
- 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; }
20
+ var _resolveInitialValueTemplates = _interopRequireDefault(require("./resolveInitialValueTemplates"));
23
21
 
24
- var queryClient = new _reactQuery.QueryClient();
22
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25
23
 
26
- function DocumentsPane(_ref) {
27
- var sanityDocument = _ref.document,
28
- options = _ref.options;
24
+ function DocumentsPane(props) {
25
+ var document = props.document,
26
+ options = props.options;
29
27
  var query = options.query,
30
28
  params = options.params,
31
- useDraft = options.useDraft,
32
- debug = options.debug;
33
- var doc = useDraft ? sanityDocument.displayed : sanityDocument.published;
34
-
35
- var _ref2 = doc !== null && doc !== void 0 ? doc : {},
36
- _id = _ref2._id,
37
- _rev = _ref2._rev;
38
-
39
- var paramValues = Object.keys(params).reduce((acc, key) => _objectSpread(_objectSpread({}, acc), {}, {
40
- [key]: (0, _dlv.default)(doc, params[key])
41
- }), {});
42
- return /*#__PURE__*/_react.default.createElement(_reactQuery.QueryClientProvider, {
43
- client: queryClient
44
- }, /*#__PURE__*/_react.default.createElement(_Documents.default, {
45
- _rev: _rev,
29
+ _options$useDraft = options.useDraft,
30
+ useDraft = _options$useDraft === void 0 ? false : _options$useDraft,
31
+ _options$debug = options.debug,
32
+ debug = _options$debug === void 0 ? false : _options$debug,
33
+ initialValueTemplatesResolver = options.initialValueTemplates;
34
+
35
+ if (useDraft && typeof params === 'function') {
36
+ return /*#__PURE__*/_react.default.createElement(_ui.Stack, {
37
+ padding: 4,
38
+ space: 5
39
+ }, /*#__PURE__*/_react.default.createElement(_Feedback.default, null, /*#__PURE__*/_react.default.createElement("code", null, "useDraft"), " should not be ", /*#__PURE__*/_react.default.createElement("code", null, "true"), " when supplying a function for", /*#__PURE__*/_react.default.createElement("code", null, "params")), debug && /*#__PURE__*/_react.default.createElement(_Debug.default, {
40
+ query: query
41
+ }));
42
+ }
43
+
44
+ var paramValues = (0, _resolveParams.default)({
45
+ document,
46
+ params,
47
+ useDraft
48
+ });
49
+ var initialValueTemplates = (0, _resolveInitialValueTemplates.default)({
50
+ resolver: initialValueTemplatesResolver,
51
+ document
52
+ });
53
+
54
+ if (!paramValues) {
55
+ return /*#__PURE__*/_react.default.createElement(_ui.Stack, {
56
+ padding: 4,
57
+ space: 5
58
+ }, /*#__PURE__*/_react.default.createElement(_Feedback.default, null, "Parameters for this query could not be resolved. This may mean the document does not yet exist or is incomplete."), debug && /*#__PURE__*/_react.default.createElement(_Debug.default, {
59
+ query: query
60
+ }));
61
+ }
62
+
63
+ return /*#__PURE__*/_react.default.createElement(_Documents.default, {
46
64
  query: query,
47
65
  params: paramValues,
48
- debug: debug
49
- }));
66
+ debug: debug,
67
+ initialValueTemplates: initialValueTemplates
68
+ });
50
69
  }
51
70
  //# sourceMappingURL=DocumentsPane.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/DocumentsPane.tsx"],"names":["queryClient","QueryClient","DocumentsPane","sanityDocument","document","options","query","params","useDraft","debug","doc","displayed","published","_id","_rev","paramValues","Object","keys","reduce","acc","key"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AAEA;;;;;;;;;;AAEA,IAAMA,WAAW,GAAG,IAAIC,uBAAJ,EAApB;;AAEe,SAASC,aAAT,OAA4D;AAAA,MAA1BC,cAA0B,QAApCC,QAAoC;AAAA,MAAVC,OAAU,QAAVA,OAAU;AACzE,MAAOC,KAAP,GAAyCD,OAAzC,CAAOC,KAAP;AAAA,MAAcC,MAAd,GAAyCF,OAAzC,CAAcE,MAAd;AAAA,MAAsBC,QAAtB,GAAyCH,OAAzC,CAAsBG,QAAtB;AAAA,MAAgCC,KAAhC,GAAyCJ,OAAzC,CAAgCI,KAAhC;AAEA,MAAMC,GAAG,GAAGF,QAAQ,GAAGL,cAAc,CAACQ,SAAlB,GAA8BR,cAAc,CAACS,SAAjE;;AACA,cAAoBF,GAApB,aAAoBA,GAApB,cAAoBA,GAApB,GAA2B,EAA3B;AAAA,MAAOG,GAAP,SAAOA,GAAP;AAAA,MAAYC,IAAZ,SAAYA,IAAZ;;AAEA,MAAMC,WAAW,GAAGC,MAAM,CAACC,IAAP,CAAYV,MAAZ,EAAoBW,MAApB,CAClB,CAACC,GAAD,EAAMC,GAAN,qCAAmBD,GAAnB;AAAwB,KAACC,GAAD,GAAO,kBAAMV,GAAN,EAAWH,MAAM,CAACa,GAAD,CAAjB;AAA/B,IADkB,EAElB,EAFkB,CAApB;AAKA,sBACE,6BAAC,+BAAD;AAAqB,IAAA,MAAM,EAAEpB;AAA7B,kBACE,6BAAC,kBAAD;AAAW,IAAA,IAAI,EAAEc,IAAjB;AAAuB,IAAA,KAAK,EAAER,KAA9B;AAAqC,IAAA,MAAM,EAAES,WAA7C;AAA0D,IAAA,KAAK,EAAEN;AAAjE,IADF,CADF;AAKD","sourcesContent":["import React from 'react'\nimport delve from 'dlv'\nimport {QueryClient, QueryClientProvider} from 'react-query'\n\nimport Documents from './Documents'\n\nconst queryClient = new QueryClient()\n\nexport default function DocumentsPane({document: sanityDocument, options}) {\n const {query, params, useDraft, debug} = options\n\n const doc = useDraft ? sanityDocument.displayed : sanityDocument.published\n const {_id, _rev} = doc ?? {}\n\n const paramValues = Object.keys(params).reduce(\n (acc, key) => ({...acc, [key]: delve(doc, params[key])}),\n {}\n )\n\n return (\n <QueryClientProvider client={queryClient}>\n <Documents _rev={_rev} query={query} params={paramValues} debug={debug} />\n </QueryClientProvider>\n )\n}\n"],"file":"DocumentsPane.js"}
1
+ {"version":3,"file":"DocumentsPane.js","names":["DocumentsPane","props","document","options","query","params","useDraft","debug","initialValueTemplatesResolver","initialValueTemplates","paramValues","resolveParams","resolveInitialValueTemplates","resolver"],"sources":["../src/DocumentsPane.tsx"],"sourcesContent":["import React from 'react'\nimport {Stack} from '@sanity/ui'\n\nimport Documents from './Documents'\nimport Feedback from './Feedback'\nimport Debug from './Debug'\nimport {DocumentsPaneProps} from './types'\nimport resolveParams from './resolveParams'\nimport resolveInitialValueTemplates from './resolveInitialValueTemplates'\n\nexport default function DocumentsPane(props: DocumentsPaneProps) {\n const {document, options} = props\n const {\n query,\n params,\n useDraft = false,\n debug = false,\n initialValueTemplates: initialValueTemplatesResolver,\n } = options\n\n if (useDraft && typeof params === 'function') {\n return (\n <Stack padding={4} space={5}>\n <Feedback>\n <code>useDraft</code> should not be <code>true</code> when supplying a function for\n <code>params</code>\n </Feedback>\n {debug && <Debug query={query} />}\n </Stack>\n )\n }\n\n const paramValues = resolveParams({document, params, useDraft})\n\n const initialValueTemplates = resolveInitialValueTemplates({\n resolver: initialValueTemplatesResolver,\n document,\n })\n\n if (!paramValues) {\n return (\n <Stack padding={4} space={5}>\n <Feedback>\n Parameters for this query could not be resolved. This may mean the document does not yet\n exist or is incomplete.\n </Feedback>\n {debug && <Debug query={query} />}\n </Stack>\n )\n }\n\n return (\n <Documents\n query={query}\n params={paramValues}\n debug={debug}\n initialValueTemplates={initialValueTemplates}\n />\n )\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;AAEA;;AACA;;AACA;;AAEA;;AACA;;;;AAEe,SAASA,aAAT,CAAuBC,KAAvB,EAAkD;EAC/D,IAAOC,QAAP,GAA4BD,KAA5B,CAAOC,QAAP;EAAA,IAA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;AAAA;;AACA;;;;AAQe,SAASA,QAAT,CAAkBC,KAAlB,EAAwC;AACrD,MAAOC,QAAP,GAAqCD,KAArC,CAAOC,QAAP;AAAA,oBAAqCD,KAArC,CAAiBE,IAAjB;AAAA,MAAiBA,IAAjB;AAEA,sBACE,6BAAC,QAAD;AAAM,IAAA,OAAO,EAAE,CAAf;AAAkB,IAAA,MAAM,EAAE,CAA1B;AAA6B,IAAA,MAAM,EAAE,CAArC;AAAwC,IAAA,IAAI,EAAEA;AAA9C,kBACE,6BAAC,QAAD;AAAM,IAAA,IAAI,EAAE;AAAZ,KAAgBD,QAAhB,CADF,CADF;AAKD","sourcesContent":["import React from 'react'\nimport {Card, Text} from '@sanity/ui'\nimport type {BadgeTone} from '@sanity/ui'\n\ntype FeedbackProps = {\n children?: React.ReactNode\n tone?: BadgeTone\n}\n\nexport default function Feedback(props: FeedbackProps) {\n const {children, tone = `caution`} = props\n\n return (\n <Card padding={3} radius={2} shadow={1} tone={tone}>\n <Text size={1}>{children}</Text>\n </Card>\n )\n}\n"],"file":"Feedback.js"}
1
+ {"version":3,"file":"Feedback.js","names":["Feedback","props","children","tone"],"sources":["../src/Feedback.tsx"],"sourcesContent":["import React from 'react'\nimport {Card, Text} from '@sanity/ui'\nimport type {BadgeTone} from '@sanity/ui'\n\ntype FeedbackProps = {\n children?: React.ReactNode\n tone?: BadgeTone\n}\n\nexport default function Feedback(props: FeedbackProps) {\n const {children, tone = `caution`} = props\n\n return (\n <Card padding={3} radius={2} shadow={1} tone={tone}>\n <Text size={1}>{children}</Text>\n </Card>\n )\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;;;AAQe,SAASA,QAAT,CAAkBC,KAAlB,EAAwC;EACrD,IAAOC,QAAP,GAAqCD,KAArC,CAAOC,QAAP;EAAA,kBAAqCD,KAArC,CAAiBE,IAAjB;EAAA,IAAiBA,IAAjB;EAEA,oBACE,6BAAC,QAAD;IAAM,OAAO,EAAE,CAAf;IAAkB,MAAM,EAAE,CAA1B;IAA6B,MAAM,EAAE,CAArC;IAAwC,IAAI,EAAEA;EAA9C,gBACE,6BAAC,QAAD;IAAM,IAAI,EAAE;EAAZ,GAAgBD,QAAhB,CADF,CADF;AAKD"}
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = NewDocument;
7
+
8
+ var _ui = require("@sanity/ui");
9
+
10
+ var _react = _interopRequireDefault(require("react"));
11
+
12
+ var _icons = require("@sanity/icons");
13
+
14
+ var _deskTool = require("@sanity/desk-tool");
15
+
16
+ var _uuid = require("@sanity/uuid");
17
+
18
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
+
20
+ function NewDocument(props) {
21
+ var _props$initialValueTe = props.initialValueTemplates,
22
+ initialValueTemplates = _props$initialValueTe === void 0 ? [] : _props$initialValueTe;
23
+
24
+ var _usePaneRouter = (0, _deskTool.usePaneRouter)(),
25
+ ReferenceChildLink = _usePaneRouter.ReferenceChildLink;
26
+
27
+ if (!initialValueTemplates.length) return null;
28
+ return /*#__PURE__*/_react.default.createElement(_ui.Card, {
29
+ borderBottom: true,
30
+ padding: 2
31
+ }, /*#__PURE__*/_react.default.createElement(_ui.Flex, {
32
+ justify: "flex-end",
33
+ gap: 1
34
+ }, initialValueTemplates.map(template => {
35
+ return /*#__PURE__*/_react.default.createElement(ReferenceChildLink, {
36
+ documentId: (0, _uuid.uuid)(),
37
+ documentType: template.schemaType,
38
+ template: {
39
+ id: template.template,
40
+ params: template.parameters
41
+ },
42
+ parentRefPath: [],
43
+ key: "".concat(template.schemaType, "-").concat(template.template),
44
+ style: {
45
+ textDecoration: 'none'
46
+ }
47
+ }, /*#__PURE__*/_react.default.createElement(_ui.Button, {
48
+ icon: /*#__PURE__*/_react.default.createElement(_icons.ComposeIcon, null),
49
+ text: template.title,
50
+ mode: "bleed",
51
+ as: "span"
52
+ }));
53
+ })));
54
+ }
55
+ //# sourceMappingURL=NewDocument.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NewDocument.js","names":["NewDocument","props","initialValueTemplates","usePaneRouter","ReferenceChildLink","length","map","template","uuid","schemaType","id","params","parameters","textDecoration","title"],"sources":["../src/NewDocument.tsx"],"sourcesContent":["import {Button, Card, Flex} from '@sanity/ui'\nimport React from 'react'\nimport {DocumentsPaneInitialValueTemplate} from './types'\nimport {ComposeIcon} from '@sanity/icons'\nimport {usePaneRouter} from '@sanity/desk-tool'\nimport {uuid} from \"@sanity/uuid\"\n\ninterface NewDocumentProps {\n initialValueTemplates: DocumentsPaneInitialValueTemplate[]\n}\n\nexport default function NewDocument(props: NewDocumentProps) {\n const {initialValueTemplates = []} = props\n const {ReferenceChildLink} = usePaneRouter()\n\n if (!initialValueTemplates.length) return null\n\n return (\n <Card borderBottom={true} padding={2}>\n <Flex justify=\"flex-end\" gap={1}>\n {initialValueTemplates.map((template) => {\n return (\n <ReferenceChildLink\n documentId={uuid()}\n documentType={template.schemaType}\n template={{id: template.template, params: template.parameters}}\n parentRefPath={[]}\n key={`${template.schemaType}-${template.template}`}\n style={{textDecoration: 'none'}}\n >\n <Button icon={<ComposeIcon />} text={template.title} mode=\"bleed\" as=\"span\" />\n </ReferenceChildLink>\n )\n })}\n </Flex>\n </Card>\n )\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;AAEA;;AACA;;AACA;;;;AAMe,SAASA,WAAT,CAAqBC,KAArB,EAA8C;EAC3D,4BAAqCA,KAArC,CAAOC,qBAAP;EAAA,IAAOA,qBAAP,sCAA+B,EAA/B;;EACA,qBAA6B,IAAAC,uBAAA,GAA7B;EAAA,IAAOC,kBAAP,kBAAOA,kBAAP;;EAEA,IAAI,CAACF,qBAAqB,CAACG,MAA3B,EAAmC,OAAO,IAAP;EAEnC,oBACE,6BAAC,QAAD;IAAM,YAAY,EAAE,IAApB;IAA0B,OAAO,EAAE;EAAnC,gBACE,6BAAC,QAAD;IAAM,OAAO,EAAC,UAAd;IAAyB,GAAG,EAAE;EAA9B,GACGH,qBAAqB,CAACI,GAAtB,CAA2BC,QAAD,IAAc;IACvC,oBACE,6BAAC,kBAAD;MACE,UAAU,EAAE,IAAAC,UAAA,GADd;MAEE,YAAY,EAAED,QAAQ,CAACE,UAFzB;MAGE,QAAQ,EAAE;QAACC,EAAE,EAAEH,QAAQ,CAACA,QAAd;QAAwBI,MAAM,EAAEJ,QAAQ,CAACK;MAAzC,CAHZ;MAIE,aAAa,EAAE,EAJjB;MAKE,GAAG,YAAKL,QAAQ,CAACE,UAAd,cAA4BF,QAAQ,CAACA,QAArC,CALL;MAME,KAAK,EAAE;QAACM,cAAc,EAAE;MAAjB;IANT,gBAQE,6BAAC,UAAD;MAAQ,IAAI,eAAE,6BAAC,kBAAD,OAAd;MAA+B,IAAI,EAAEN,QAAQ,CAACO,KAA9C;MAAqD,IAAI,EAAC,OAA1D;MAAkE,EAAE,EAAC;IAArE,EARF,CADF;EAYD,CAbA,CADH,CADF,CADF;AAoBD"}
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = useListeningQuery;
7
+
8
+ var _react = require("react");
9
+
10
+ var _document = _interopRequireDefault(require("part:@sanity/base/datastore/document"));
11
+
12
+ var _operators = require("rxjs/operators");
13
+
14
+ var _reactFastCompare = _interopRequireDefault(require("react-fast-compare"));
15
+
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+
18
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
19
+
20
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
21
+
22
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
23
+
24
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
25
+
26
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
27
+
28
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
29
+
30
+ var DEFAULT_PARAMS = {};
31
+ var DEFAULT_OPTIONS = {
32
+ apiVersion: "v2022-05-09"
33
+ };
34
+
35
+ function useListeningQuery(query) {
36
+ var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_PARAMS;
37
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_OPTIONS;
38
+
39
+ var _useState = (0, _react.useState)(true),
40
+ _useState2 = _slicedToArray(_useState, 2),
41
+ loading = _useState2[0],
42
+ setLoading = _useState2[1];
43
+
44
+ var _useState3 = (0, _react.useState)(false),
45
+ _useState4 = _slicedToArray(_useState3, 2),
46
+ error = _useState4[0],
47
+ setError = _useState4[1];
48
+
49
+ var _useState5 = (0, _react.useState)(null),
50
+ _useState6 = _slicedToArray(_useState5, 2),
51
+ data = _useState6[0],
52
+ setData = _useState6[1];
53
+
54
+ var subscription = (0, _react.useRef)(null);
55
+ (0, _react.useEffect)(() => {
56
+ if (query) {
57
+ subscription.current = _document.default.listenQuery(query, params, options).pipe((0, _operators.distinctUntilChanged)(_reactFastCompare.default), (0, _operators.catchError)(err => {
58
+ console.error(err);
59
+ setError(err);
60
+ setLoading(false);
61
+ setData(null);
62
+ return err;
63
+ })).subscribe(documents => {
64
+ setData(current => (0, _reactFastCompare.default)(current, documents) ? current : documents);
65
+ setLoading(false);
66
+ setError(false);
67
+ });
68
+ }
69
+
70
+ return () => {
71
+ return subscription.current ? subscription.current.unsubscribe() : undefined;
72
+ };
73
+ }, [query, params, options]);
74
+ return {
75
+ loading,
76
+ error,
77
+ data
78
+ };
79
+ }
80
+ //# sourceMappingURL=useListeningQuery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useListeningQuery.js","names":["DEFAULT_PARAMS","DEFAULT_OPTIONS","apiVersion","useListeningQuery","query","params","options","useState","loading","setLoading","error","setError","data","setData","subscription","useRef","useEffect","current","documentStore","listenQuery","pipe","distinctUntilChanged","isEqual","catchError","err","console","subscribe","documents","unsubscribe","undefined"],"sources":["../../src/hooks/useListeningQuery.ts"],"sourcesContent":["import React, {useEffect, useState, useRef} from 'react'\nimport documentStore from 'part:@sanity/base/datastore/document'\nimport {catchError, distinctUntilChanged} from 'rxjs/operators'\nimport isEqual from 'react-fast-compare'\n\ntype Params = Record<string, string | number | boolean | string[]>\n\ninterface ListenQueryOptions {\n tag?: string\n apiVersion?: string\n}\n\ntype ReturnShape = {\n loading: boolean\n error: boolean\n data: any\n}\n\ntype Observable = {\n unsubscribe: () => void\n}\n\nconst DEFAULT_PARAMS = {}\nconst DEFAULT_OPTIONS = {apiVersion: `v2022-05-09`}\n\nexport default function useListeningQuery(\n query: string,\n params: Params = DEFAULT_PARAMS,\n options: ListenQueryOptions = DEFAULT_OPTIONS\n): ReturnShape {\n const [loading, setLoading] = useState(true)\n const [error, setError] = useState(false)\n const [data, setData] = useState(null)\n const subscription = useRef<null | Observable>(null)\n\n useEffect(() => {\n if (query) {\n subscription.current = documentStore\n .listenQuery(query, params, options)\n .pipe(\n distinctUntilChanged(isEqual),\n catchError((err) => {\n console.error(err)\n setError(err)\n setLoading(false)\n setData(null)\n\n return err\n })\n )\n .subscribe((documents) => {\n setData((current) => (isEqual(current, documents) ? current : documents))\n setLoading(false)\n setError(false)\n })\n }\n\n return () => {\n return subscription.current ? subscription.current.unsubscribe() : undefined\n }\n }, [query, params, options])\n\n return {loading, error, data}\n}\n"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;;;;;;;;;;;;;;;AAmBA,IAAMA,cAAc,GAAG,EAAvB;AACA,IAAMC,eAAe,GAAG;EAACC,UAAU;AAAX,CAAxB;;AAEe,SAASC,iBAAT,CACbC,KADa,EAIA;EAAA,IAFbC,MAEa,uEAFIL,cAEJ;EAAA,IADbM,OACa,uEADiBL,eACjB;;EACb,gBAA8B,IAAAM,eAAA,EAAS,IAAT,CAA9B;EAAA;EAAA,IAAOC,OAAP;EAAA,IAAgBC,UAAhB;;EACA,iBAA0B,IAAAF,eAAA,EAAS,KAAT,CAA1B;EAAA;EAAA,IAAOG,KAAP;EAAA,IAAcC,QAAd;;EACA,iBAAwB,IAAAJ,eAAA,EAAS,IAAT,CAAxB;EAAA;EAAA,IAAOK,IAAP;EAAA,IAAaC,OAAb;;EACA,IAAMC,YAAY,GAAG,IAAAC,aAAA,EAA0B,IAA1B,CAArB;EAEA,IAAAC,gBAAA,EAAU,MAAM;IACd,IAAIZ,KAAJ,EAAW;MACTU,YAAY,CAACG,OAAb,GAAuBC,iBAAA,CACpBC,WADoB,CACRf,KADQ,EACDC,MADC,EACOC,OADP,EAEpBc,IAFoB,CAGnB,IAAAC,+BAAA,EAAqBC,yBAArB,CAHmB,EAInB,IAAAC,qBAAA,EAAYC,GAAD,IAAS;QAClBC,OAAO,CAACf,KAAR,CAAcc,GAAd;QACAb,QAAQ,CAACa,GAAD,CAAR;QACAf,UAAU,CAAC,KAAD,CAAV;QACAI,OAAO,CAAC,IAAD,CAAP;QAEA,OAAOW,GAAP;MACD,CAPD,CAJmB,EAapBE,SAboB,CAaTC,SAAD,IAAe;QACxBd,OAAO,CAAEI,OAAD,IAAc,IAAAK,yBAAA,EAAQL,OAAR,EAAiBU,SAAjB,IAA8BV,OAA9B,GAAwCU,SAAvD,CAAP;QACAlB,UAAU,CAAC,KAAD,CAAV;QACAE,QAAQ,CAAC,KAAD,CAAR;MACD,CAjBoB,CAAvB;IAkBD;;IAED,OAAO,MAAM;MACX,OAAOG,YAAY,CAACG,OAAb,GAAuBH,YAAY,CAACG,OAAb,CAAqBW,WAArB,EAAvB,GAA4DC,SAAnE;IACD,CAFD;EAGD,CAzBD,EAyBG,CAACzB,KAAD,EAAQC,MAAR,EAAgBC,OAAhB,CAzBH;EA2BA,OAAO;IAACE,OAAD;IAAUE,KAAV;IAAiBE;EAAjB,CAAP;AACD"}
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.js"],"names":["DocumentsPane"],"mappings":";;;;;;;AACA;;;;eAEeA,sB","sourcesContent":["\nimport DocumentsPane from \"./DocumentsPane\";\n\nexport default DocumentsPane\n"],"file":"index.js"}
1
+ {"version":3,"file":"index.js","names":["DocumentsPane"],"sources":["../src/index.ts"],"sourcesContent":["import DocumentsPane from './DocumentsPane'\n\nexport default DocumentsPane\n"],"mappings":";;;;;;;AAAA;;;;eAEeA,sB"}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = resolveInitialValueTemplates;
7
+
8
+ function resolveInitialValueTemplates(options) {
9
+ var _ref = options || {},
10
+ resolver = _ref.resolver,
11
+ document = _ref.document;
12
+
13
+ if (!resolver) return [];
14
+ return resolver({
15
+ document
16
+ });
17
+ }
18
+ //# sourceMappingURL=resolveInitialValueTemplates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveInitialValueTemplates.js","names":["resolveInitialValueTemplates","options","resolver","document"],"sources":["../src/resolveInitialValueTemplates.ts"],"sourcesContent":["import {\n DocumentsPaneInitialValueTemplate,\n DocumentsPaneInitialValueTemplateResolver,\n DocumentVersionsCollection,\n} from './types'\n\ninterface ResolveInitialValueTemplatesOptions {\n resolver: DocumentsPaneInitialValueTemplateResolver | undefined\n document: DocumentVersionsCollection\n}\n\nexport default function resolveInitialValueTemplates(\n options: ResolveInitialValueTemplatesOptions\n): DocumentsPaneInitialValueTemplate[] {\n const {resolver, document} = options || {}\n\n if (!resolver) return []\n\n return resolver({document})\n}\n"],"mappings":";;;;;;;AAWe,SAASA,4BAAT,CACbC,OADa,EAEwB;EACrC,WAA6BA,OAAO,IAAI,EAAxC;EAAA,IAAOC,QAAP,QAAOA,QAAP;EAAA,IAAiBC,QAAjB,QAAiBA,QAAjB;;EAEA,IAAI,CAACD,QAAL,EAAe,OAAO,EAAP;EAEf,OAAOA,QAAQ,CAAC;IAACC;EAAD,CAAD,CAAf;AACD"}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = resolveParams;
7
+
8
+ var _dlv = _interopRequireDefault(require("dlv"));
9
+
10
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
+
12
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
13
+
14
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
15
+
16
+ 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; }
17
+
18
+ function defaultResolver(options) {
19
+ var params = options.params,
20
+ document = options.document,
21
+ useDraft = options.useDraft; // params is optional
22
+
23
+ if (!params) return {}; // legacy useDraft behaviour
24
+
25
+ var doc = useDraft ? document.displayed : document.published;
26
+ return Object.keys(params).reduce((acc, key) => _objectSpread(_objectSpread({}, acc), {}, {
27
+ [key]: (0, _dlv.default)(doc, params[key])
28
+ }), {});
29
+ }
30
+
31
+ function resolveParams(options) {
32
+ var params = options.params,
33
+ document = options.document;
34
+ var resolvedParams = typeof params == 'function' ? params({
35
+ document
36
+ }) : defaultResolver(options); // if any of the parameters are undefined, the query will error
37
+ // so return undefined so the UI can show a more appropriate message
38
+
39
+ if (Object.values(resolvedParams).includes(undefined)) return undefined; // Typescript can't tell that we've guarded against any value being undefined,
40
+ // so forcing the type
41
+
42
+ return resolvedParams;
43
+ }
44
+ //# sourceMappingURL=resolveParams.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveParams.js","names":["defaultResolver","options","params","document","useDraft","doc","displayed","published","Object","keys","reduce","acc","key","delve","resolveParams","resolvedParams","values","includes","undefined"],"sources":["../src/resolveParams.ts"],"sourcesContent":["import {DocumentsPaneQueryParams, DocumentVersionsCollection} from './types'\nimport delve from 'dlv'\n\ninterface ResolveParamsOptions {\n params?: DocumentsPaneQueryParams\n document: DocumentVersionsCollection\n useDraft: boolean\n}\n\ntype ResolveParamsReturn = undefined | {[key: string]: string}\n\nfunction defaultResolver(options: ResolveParamsOptions): {[key: string]: string | undefined} {\n const {params, document, useDraft} = options\n\n // params is optional\n if (!params) return {}\n\n // legacy useDraft behaviour\n const doc = useDraft ? document.displayed : document.published\n\n return Object.keys(params).reduce((acc, key) => ({...acc, [key]: delve(doc, params[key])}), {})\n}\n\nexport default function resolveParams(options: ResolveParamsOptions): ResolveParamsReturn {\n const {params, document} = options\n\n const resolvedParams = typeof params == 'function' ? params({document}) : defaultResolver(options)\n\n // if any of the parameters are undefined, the query will error\n // so return undefined so the UI can show a more appropriate message\n if (Object.values(resolvedParams).includes(undefined)) return undefined\n\n // Typescript can't tell that we've guarded against any value being undefined,\n // so forcing the type\n return resolvedParams as {[key: string]: string}\n}\n"],"mappings":";;;;;;;AACA;;;;;;;;;;AAUA,SAASA,eAAT,CAAyBC,OAAzB,EAA6F;EAC3F,IAAOC,MAAP,GAAqCD,OAArC,CAAOC,MAAP;EAAA,IAAeC,QAAf,GAAqCF,OAArC,CAAeE,QAAf;EAAA,IAAyBC,QAAzB,GAAqCH,OAArC,CAAyBG,QAAzB,CAD2F,CAG3F;;EACA,IAAI,CAACF,MAAL,EAAa,OAAO,EAAP,CAJ8E,CAM3F;;EACA,IAAMG,GAAG,GAAGD,QAAQ,GAAGD,QAAQ,CAACG,SAAZ,GAAwBH,QAAQ,CAACI,SAArD;EAEA,OAAOC,MAAM,CAACC,IAAP,CAAYP,MAAZ,EAAoBQ,MAApB,CAA2B,CAACC,GAAD,EAAMC,GAAN,qCAAmBD,GAAnB;IAAwB,CAACC,GAAD,GAAO,IAAAC,YAAA,EAAMR,GAAN,EAAWH,MAAM,CAACU,GAAD,CAAjB;EAA/B,EAA3B,EAAqF,EAArF,CAAP;AACD;;AAEc,SAASE,aAAT,CAAuBb,OAAvB,EAA2E;EACxF,IAAOC,MAAP,GAA2BD,OAA3B,CAAOC,MAAP;EAAA,IAAeC,QAAf,GAA2BF,OAA3B,CAAeE,QAAf;EAEA,IAAMY,cAAc,GAAG,OAAOb,MAAP,IAAiB,UAAjB,GAA8BA,MAAM,CAAC;IAACC;EAAD,CAAD,CAApC,GAAmDH,eAAe,CAACC,OAAD,CAAzF,CAHwF,CAKxF;EACA;;EACA,IAAIO,MAAM,CAACQ,MAAP,CAAcD,cAAd,EAA8BE,QAA9B,CAAuCC,SAAvC,CAAJ,EAAuD,OAAOA,SAAP,CAPiC,CASxF;EACA;;EACA,OAAOH,cAAP;AACD"}
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import {SanityDocument} from '@sanity/client'\n\nexport interface DocumentVersionsCollection {\n displayed: SanityDocument\n published: SanityDocument\n draft: SanityDocument\n historical: SanityDocument\n}\n\n// eslint-disable-next-line prettier/prettier\nexport type DocumentsPaneQueryParams = (params: {document: DocumentVersionsCollection}) => ({[key: string]: string}) | {[key: string]: string}\n\nexport interface DocumentsPaneInitialValueTemplate {\n schemaType: string\n template?: string\n parameters?: {[key: string]: any}\n title: string\n}\n\n// eslint-disable-next-line prettier/prettier\nexport type DocumentsPaneInitialValueTemplateResolver = (params: {document: DocumentVersionsCollection}) => DocumentsPaneInitialValueTemplate[]\n\nexport type DocumentsPaneOptions = {\n query: string\n params?: DocumentsPaneQueryParams\n debug?: boolean\n useDraft?: boolean\n initialValueTemplates?: DocumentsPaneInitialValueTemplateResolver\n}\n\nexport type DocumentsPaneProps = {\n document: DocumentVersionsCollection\n options: DocumentsPaneOptions\n}\n"],"mappings":""}
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "sanity-plugin-documents-pane",
3
- "version": "1.0.7",
3
+ "version": "1.1.0",
4
4
  "description": "Displays the results of a GROQ query in a View Pane",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {
7
7
  "build": "sanipack build",
8
+ "verify": "sanipack verify",
8
9
  "watch": "sanipack build --watch",
9
10
  "_postinstall": "husky install",
10
11
  "prepublishOnly": "pinst --disable && sanipack build && sanipack verify",
@@ -28,42 +29,34 @@
28
29
  "author": "Sanity.io <hello@sanity.io>",
29
30
  "license": "MIT",
30
31
  "dependencies": {
31
- "@sanity/base": "^2.29.5",
32
- "@sanity/desk-tool": "^2.29.5",
33
- "@sanity/state-router": "^2.29.3",
34
- "@sanity/ui": "^0.34.6",
32
+ "@sanity/icons": "^1.3.4",
33
+ "@sanity/ui": "^0.38.0",
35
34
  "dlv": "^1.1.3",
36
- "react-query": "^3.19.1",
37
- "husky": "^7.0.1"
38
- },
39
- "devDependencies": {
40
- "eslint": "7.31.0",
41
- "eslint-config-prettier": "^8.3.0",
42
- "eslint-config-sanity": "5.1.0",
43
- "eslint-plugin-react": "^7.24.0",
44
- "pinst": "^2.1.6",
45
- "prettier": "^2.3.2",
46
- "sanipack": "^2.1.0"
35
+ "react-fast-compare": "^3.2.0",
36
+ "rxjs": "^6.5.6"
47
37
  },
48
38
  "peerDependencies": {
49
- "react": "^17.0.0"
39
+ "@sanity/base": "^2.30.1",
40
+ "@sanity/desk-tool": "^2.30.1",
41
+ "@sanity/uuid": "^3.0.1",
42
+ "@sanity/util": "^2.29.5",
43
+ "react": "^16.0.0 || ^17.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@sanity/eslint-config-studio": "^2.0.0",
47
+ "eslint": "8.19.0",
48
+ "eslint-config-prettier": "^8.5.0",
49
+ "eslint-config-sanity": "6.0.0",
50
+ "eslint-plugin-prettier": "^4.2.1",
51
+ "eslint-plugin-react": "^7.30.1",
52
+ "husky": "^8.0.1",
53
+ "pinst": "^3.0.0",
54
+ "prettier": "^2.7.1",
55
+ "sanipack": "^2.1.0",
56
+ "typescript": "^4.7.4"
50
57
  },
51
58
  "bugs": {
52
59
  "url": "https://github.com/sanity-io/sanity-plugin-document-pane/issues"
53
60
  },
54
- "homepage": "https://github.com/sanity-io/sanity-plugin-document-pane#readme",
55
- "prettier": {
56
- "semi": false,
57
- "printWidth": 100,
58
- "bracketSpacing": false,
59
- "singleQuote": true
60
- },
61
- "eslintConfig": {
62
- "parser": "sanipack/babel/eslint-parser",
63
- "extends": [
64
- "sanity",
65
- "sanity/react",
66
- "prettier"
67
- ]
68
- }
61
+ "homepage": "https://github.com/sanity-io/sanity-plugin-document-pane#readme"
69
62
  }
package/src/Debug.tsx CHANGED
@@ -1,21 +1,27 @@
1
1
  import React from 'react'
2
2
  import {Code, Box, Label, Stack} from '@sanity/ui'
3
3
 
4
- export default function Debug({query, params}) {
4
+ export default function Debug({query, params}: {query: string; params?: {[key: string]: string}}) {
5
5
  return (
6
6
  <>
7
7
  <Stack space={4}>
8
- <Box><Label>Query</Label></Box>
9
8
  <Box>
10
- <Code>{query}</Code>
9
+ <Label>Query</Label>
11
10
  </Box>
12
- </Stack>
13
- <Stack space={4}>
14
- <Box><Label>Params</Label></Box>
15
11
  <Box>
16
- <Code>{JSON.stringify(params)}</Code>
12
+ <Code>{query}</Code>
17
13
  </Box>
18
14
  </Stack>
15
+ {params && (
16
+ <Stack space={4}>
17
+ <Box>
18
+ <Label>Params</Label>
19
+ </Box>
20
+ <Box>
21
+ <Code>{JSON.stringify(params)}</Code>
22
+ </Box>
23
+ </Stack>
24
+ )}
19
25
  </>
20
26
  )
21
27
  }
package/src/Documents.tsx CHANGED
@@ -1,53 +1,47 @@
1
- import React from 'react'
2
- import {useQuery} from 'react-query'
3
- import {Button, Box, Stack, Flex, Spinner} from '@sanity/ui'
1
+ import React, {useCallback} from 'react'
2
+ import {Box, Button, Stack, Flex, Spinner} from '@sanity/ui'
3
+ import {fromString as pathFromString} from '@sanity/util/paths'
4
4
  import {usePaneRouter} from '@sanity/desk-tool'
5
- import {RouterContext} from '@sanity/state-router/lib/RouterContext'
6
5
  import Preview from 'part:@sanity/base/preview'
7
6
  import schema from 'part:@sanity/base/schema'
8
- import sanityClient from 'part:@sanity/base/client'
9
7
 
10
8
  import Debug from './Debug'
11
9
  import Feedback from './Feedback'
10
+ import useListeningQuery from './hooks/useListeningQuery'
11
+ import {DocumentsPaneInitialValueTemplate} from './types'
12
+ import NewDocument from './NewDocument'
12
13
 
13
- const client = sanityClient.withConfig({apiVersion: `2021-05-19`})
14
-
15
- export default function Documents(props) {
16
- const {query, params, debug, _rev} = props
14
+ type DocumentsProps = {
15
+ query: string
16
+ params: {[key: string]: string}
17
+ debug: boolean
18
+ initialValueTemplates: DocumentsPaneInitialValueTemplate[]
19
+ }
17
20
 
18
- const {isLoading, error, data} = useQuery(['useDocuments', {props}], () =>
19
- client.fetch(query, params)
20
- )
21
+ export default function Documents(props: DocumentsProps) {
22
+ const {query, params, debug, initialValueTemplates} = props
23
+ const {routerPanesState, groupIndex, handleEditReference} = usePaneRouter()
21
24
 
22
- const routerContext = React.useContext(RouterContext)
23
- const {routerPanesState, groupIndex} = usePaneRouter()
25
+ const {loading, error, data} = useListeningQuery(query, params)
24
26
 
25
- const openDocumentInSidePane = React.useCallback(
26
- (id: string, type: string) => {
27
- const newPane = [
28
- {
29
- id: id,
30
- params: {type},
31
- },
32
- ]
33
- let panes = [routerPanesState[0], routerPanesState[1], newPane]
27
+ const handleClick = useCallback(
28
+ (id, type) => {
29
+ const childParams = routerPanesState[groupIndex + 1]?.[0].params || {}
30
+ const {parentRefPath} = childParams
34
31
 
35
- const href = routerContext.resolvePathFromState({panes})
36
- routerContext.navigateUrl(href)
32
+ handleEditReference({
33
+ id,
34
+ type,
35
+ // Uncertain that this works as intended
36
+ parentRefPath: parentRefPath ? pathFromString(parentRefPath) : [``],
37
+ // Added this to satisfy TS
38
+ template: type,
39
+ })
37
40
  },
38
- [routerContext, routerPanesState, groupIndex]
41
+ [routerPanesState, groupIndex, handleEditReference]
39
42
  )
40
43
 
41
- if (!_rev) {
42
- return (
43
- <Stack padding={4} space={5}>
44
- <Feedback>Document must be Published</Feedback>
45
- {debug && <Debug query={query} params={params} />}
46
- </Stack>
47
- )
48
- }
49
-
50
- if (isLoading) {
44
+ if (loading) {
51
45
  return (
52
46
  <Box padding={4}>
53
47
  <Flex justify="center" align="center">
@@ -68,26 +62,31 @@ export default function Documents(props) {
68
62
 
69
63
  if (!data?.length) {
70
64
  return (
71
- <Stack padding={4} space={5}>
72
- <Feedback>No Documents found</Feedback>
73
- {debug && <Debug query={query} params={params} />}
74
- </Stack>
65
+ <>
66
+ <NewDocument initialValueTemplates={initialValueTemplates} />
67
+ <Stack padding={4} space={5}>
68
+ <Feedback>No Documents found</Feedback>
69
+ {debug && <Debug query={query} params={params} />}
70
+ </Stack>
71
+ </>
75
72
  )
76
73
  }
77
74
 
78
75
  return (
79
- <Stack padding={2} space={2}>
80
- {data.map((doc) => (
81
- <Button
82
- key={doc._id}
83
- onClick={() => openDocumentInSidePane(doc._id, doc._type)}
84
- mode="bleed"
85
- radius={2}
86
- padding={2}
87
- >
88
- <Preview value={doc} type={schema.get(doc._type)} />
89
- </Button>
90
- ))}
91
- </Stack>
76
+ <>
77
+ <NewDocument initialValueTemplates={initialValueTemplates} />
78
+ <Stack padding={2} space={1}>
79
+ {data.map((doc) => (
80
+ <Button
81
+ key={doc._id}
82
+ onClick={() => handleClick(doc._id, doc._type)}
83
+ padding={2}
84
+ mode="bleed"
85
+ >
86
+ <Preview value={doc} type={schema.get(doc._type)} />
87
+ </Button>
88
+ ))}
89
+ </Stack>
90
+ </>
92
91
  )
93
92
  }
@@ -1,25 +1,60 @@
1
1
  import React from 'react'
2
- import delve from 'dlv'
3
- import {QueryClient, QueryClientProvider} from 'react-query'
2
+ import {Stack} from '@sanity/ui'
4
3
 
5
4
  import Documents from './Documents'
5
+ import Feedback from './Feedback'
6
+ import Debug from './Debug'
7
+ import {DocumentsPaneProps} from './types'
8
+ import resolveParams from './resolveParams'
9
+ import resolveInitialValueTemplates from './resolveInitialValueTemplates'
6
10
 
7
- const queryClient = new QueryClient()
11
+ export default function DocumentsPane(props: DocumentsPaneProps) {
12
+ const {document, options} = props
13
+ const {
14
+ query,
15
+ params,
16
+ useDraft = false,
17
+ debug = false,
18
+ initialValueTemplates: initialValueTemplatesResolver,
19
+ } = options
8
20
 
9
- export default function DocumentsPane({document: sanityDocument, options}) {
10
- const {query, params, useDraft, debug} = options
21
+ if (useDraft && typeof params === 'function') {
22
+ return (
23
+ <Stack padding={4} space={5}>
24
+ <Feedback>
25
+ <code>useDraft</code> should not be <code>true</code> when supplying a function for
26
+ <code>params</code>
27
+ </Feedback>
28
+ {debug && <Debug query={query} />}
29
+ </Stack>
30
+ )
31
+ }
11
32
 
12
- const doc = useDraft ? sanityDocument.displayed : sanityDocument.published
13
- const {_id, _rev} = doc ?? {}
33
+ const paramValues = resolveParams({document, params, useDraft})
14
34
 
15
- const paramValues = Object.keys(params).reduce(
16
- (acc, key) => ({...acc, [key]: delve(doc, params[key])}),
17
- {}
18
- )
35
+ const initialValueTemplates = resolveInitialValueTemplates({
36
+ resolver: initialValueTemplatesResolver,
37
+ document,
38
+ })
39
+
40
+ if (!paramValues) {
41
+ return (
42
+ <Stack padding={4} space={5}>
43
+ <Feedback>
44
+ Parameters for this query could not be resolved. This may mean the document does not yet
45
+ exist or is incomplete.
46
+ </Feedback>
47
+ {debug && <Debug query={query} />}
48
+ </Stack>
49
+ )
50
+ }
19
51
 
20
52
  return (
21
- <QueryClientProvider client={queryClient}>
22
- <Documents _rev={_rev} query={query} params={paramValues} debug={debug} />
23
- </QueryClientProvider>
53
+ <Documents
54
+ query={query}
55
+ params={paramValues}
56
+ debug={debug}
57
+ initialValueTemplates={initialValueTemplates}
58
+ />
24
59
  )
25
60
  }
@@ -0,0 +1,38 @@
1
+ import {Button, Card, Flex} from '@sanity/ui'
2
+ import React from 'react'
3
+ import {DocumentsPaneInitialValueTemplate} from './types'
4
+ import {ComposeIcon} from '@sanity/icons'
5
+ import {usePaneRouter} from '@sanity/desk-tool'
6
+ import {uuid} from "@sanity/uuid"
7
+
8
+ interface NewDocumentProps {
9
+ initialValueTemplates: DocumentsPaneInitialValueTemplate[]
10
+ }
11
+
12
+ export default function NewDocument(props: NewDocumentProps) {
13
+ const {initialValueTemplates = []} = props
14
+ const {ReferenceChildLink} = usePaneRouter()
15
+
16
+ if (!initialValueTemplates.length) return null
17
+
18
+ return (
19
+ <Card borderBottom={true} padding={2}>
20
+ <Flex justify="flex-end" gap={1}>
21
+ {initialValueTemplates.map((template) => {
22
+ return (
23
+ <ReferenceChildLink
24
+ documentId={uuid()}
25
+ documentType={template.schemaType}
26
+ template={{id: template.template, params: template.parameters}}
27
+ parentRefPath={[]}
28
+ key={`${template.schemaType}-${template.template}`}
29
+ style={{textDecoration: 'none'}}
30
+ >
31
+ <Button icon={<ComposeIcon />} text={template.title} mode="bleed" as="span" />
32
+ </ReferenceChildLink>
33
+ )
34
+ })}
35
+ </Flex>
36
+ </Card>
37
+ )
38
+ }
@@ -0,0 +1,64 @@
1
+ import React, {useEffect, useState, useRef} from 'react'
2
+ import documentStore from 'part:@sanity/base/datastore/document'
3
+ import {catchError, distinctUntilChanged} from 'rxjs/operators'
4
+ import isEqual from 'react-fast-compare'
5
+
6
+ type Params = Record<string, string | number | boolean | string[]>
7
+
8
+ interface ListenQueryOptions {
9
+ tag?: string
10
+ apiVersion?: string
11
+ }
12
+
13
+ type ReturnShape = {
14
+ loading: boolean
15
+ error: boolean
16
+ data: any
17
+ }
18
+
19
+ type Observable = {
20
+ unsubscribe: () => void
21
+ }
22
+
23
+ const DEFAULT_PARAMS = {}
24
+ const DEFAULT_OPTIONS = {apiVersion: `v2022-05-09`}
25
+
26
+ export default function useListeningQuery(
27
+ query: string,
28
+ params: Params = DEFAULT_PARAMS,
29
+ options: ListenQueryOptions = DEFAULT_OPTIONS
30
+ ): ReturnShape {
31
+ const [loading, setLoading] = useState(true)
32
+ const [error, setError] = useState(false)
33
+ const [data, setData] = useState(null)
34
+ const subscription = useRef<null | Observable>(null)
35
+
36
+ useEffect(() => {
37
+ if (query) {
38
+ subscription.current = documentStore
39
+ .listenQuery(query, params, options)
40
+ .pipe(
41
+ distinctUntilChanged(isEqual),
42
+ catchError((err) => {
43
+ console.error(err)
44
+ setError(err)
45
+ setLoading(false)
46
+ setData(null)
47
+
48
+ return err
49
+ })
50
+ )
51
+ .subscribe((documents) => {
52
+ setData((current) => (isEqual(current, documents) ? current : documents))
53
+ setLoading(false)
54
+ setError(false)
55
+ })
56
+ }
57
+
58
+ return () => {
59
+ return subscription.current ? subscription.current.unsubscribe() : undefined
60
+ }
61
+ }, [query, params, options])
62
+
63
+ return {loading, error, data}
64
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ import DocumentsPane from './DocumentsPane'
2
+
3
+ export default DocumentsPane
@@ -0,0 +1,20 @@
1
+ import {
2
+ DocumentsPaneInitialValueTemplate,
3
+ DocumentsPaneInitialValueTemplateResolver,
4
+ DocumentVersionsCollection,
5
+ } from './types'
6
+
7
+ interface ResolveInitialValueTemplatesOptions {
8
+ resolver: DocumentsPaneInitialValueTemplateResolver | undefined
9
+ document: DocumentVersionsCollection
10
+ }
11
+
12
+ export default function resolveInitialValueTemplates(
13
+ options: ResolveInitialValueTemplatesOptions
14
+ ): DocumentsPaneInitialValueTemplate[] {
15
+ const {resolver, document} = options || {}
16
+
17
+ if (!resolver) return []
18
+
19
+ return resolver({document})
20
+ }
@@ -0,0 +1,36 @@
1
+ import {DocumentsPaneQueryParams, DocumentVersionsCollection} from './types'
2
+ import delve from 'dlv'
3
+
4
+ interface ResolveParamsOptions {
5
+ params?: DocumentsPaneQueryParams
6
+ document: DocumentVersionsCollection
7
+ useDraft: boolean
8
+ }
9
+
10
+ type ResolveParamsReturn = undefined | {[key: string]: string}
11
+
12
+ function defaultResolver(options: ResolveParamsOptions): {[key: string]: string | undefined} {
13
+ const {params, document, useDraft} = options
14
+
15
+ // params is optional
16
+ if (!params) return {}
17
+
18
+ // legacy useDraft behaviour
19
+ const doc = useDraft ? document.displayed : document.published
20
+
21
+ return Object.keys(params).reduce((acc, key) => ({...acc, [key]: delve(doc, params[key])}), {})
22
+ }
23
+
24
+ export default function resolveParams(options: ResolveParamsOptions): ResolveParamsReturn {
25
+ const {params, document} = options
26
+
27
+ const resolvedParams = typeof params == 'function' ? params({document}) : defaultResolver(options)
28
+
29
+ // if any of the parameters are undefined, the query will error
30
+ // so return undefined so the UI can show a more appropriate message
31
+ if (Object.values(resolvedParams).includes(undefined)) return undefined
32
+
33
+ // Typescript can't tell that we've guarded against any value being undefined,
34
+ // so forcing the type
35
+ return resolvedParams as {[key: string]: string}
36
+ }
package/src/types.ts ADDED
@@ -0,0 +1,34 @@
1
+ import {SanityDocument} from '@sanity/client'
2
+
3
+ export interface DocumentVersionsCollection {
4
+ displayed: SanityDocument
5
+ published: SanityDocument
6
+ draft: SanityDocument
7
+ historical: SanityDocument
8
+ }
9
+
10
+ // eslint-disable-next-line prettier/prettier
11
+ export type DocumentsPaneQueryParams = (params: {document: DocumentVersionsCollection}) => ({[key: string]: string}) | {[key: string]: string}
12
+
13
+ export interface DocumentsPaneInitialValueTemplate {
14
+ schemaType: string
15
+ template?: string
16
+ parameters?: {[key: string]: any}
17
+ title: string
18
+ }
19
+
20
+ // eslint-disable-next-line prettier/prettier
21
+ export type DocumentsPaneInitialValueTemplateResolver = (params: {document: DocumentVersionsCollection}) => DocumentsPaneInitialValueTemplate[]
22
+
23
+ export type DocumentsPaneOptions = {
24
+ query: string
25
+ params?: DocumentsPaneQueryParams
26
+ debug?: boolean
27
+ useDraft?: boolean
28
+ initialValueTemplates?: DocumentsPaneInitialValueTemplateResolver
29
+ }
30
+
31
+ export type DocumentsPaneProps = {
32
+ document: DocumentVersionsCollection
33
+ options: DocumentsPaneOptions
34
+ }
package/.babelrc DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "sanipack/babel"
3
- }
package/.eslintignore DELETED
@@ -1 +0,0 @@
1
- lib
package/src/index.js DELETED
@@ -1,4 +0,0 @@
1
-
2
- import DocumentsPane from "./DocumentsPane";
3
-
4
- export default DocumentsPane