Last active
March 4, 2022 15:43
-
-
Save SimeonGriggs/1bc07ed705eed4a748f19a0d5ea8258e to your computer and use it in GitHub Desktop.
A Structure Builder function for Parent/Child Document Relationships
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is all explained in a complete guide at: | |
// https://www.sanity.io/guides/parent-child-taxonomy | |
import S from '@sanity/desk-tool/structure-builder' | |
import documentStore from 'part:@sanity/base/datastore/document' | |
import {map} from 'rxjs/operators' | |
import {FiTag} from 'react-icons/fi' | |
/** | |
* This is an example of a Structure Builder list item that: | |
* | |
* 1. Provides a top level link to edit 'parent' 'category' documents | |
* 2. Queries the documentStore for those same documents to | |
* create a 'folder' for each 'parent', to show their 'children' | |
* 3. Calls for a 'category-child' template and pre-populates | |
* the 'parent' reference field with the 'parent' _id | |
*/ | |
const views = [S.view.form()] | |
export default function parentChild(schema = 'category') { | |
const categoryParents = `_type == "${schema}" && !defined(parent)` | |
return S.listItem(schema) | |
.title('Categories') | |
.icon(FiTag) | |
.child(() => | |
documentStore.listenQuery(`*[${categoryParents}]`).pipe( | |
map((parents) => | |
S.list() | |
.title('All Categories') | |
.items([ | |
S.listItem() | |
.title('Parent Categories') | |
.child(() => | |
S.documentList() | |
.title('Parent Categories') | |
.schemaType(schema) | |
.filter(categoryParents) | |
.child((id) => S.document().documentId(id).views(views)) | |
), | |
S.divider(), | |
...parents.map((parent) => | |
S.listItem() | |
.title(parent.title) | |
.icon(FiTag) | |
.child(() => | |
S.documentList() | |
.title('Child Categories') | |
.schemaType(schema) | |
.filter(`_type == "${schema}" && parent._ref == $parentId`) | |
.params({parentId: parent._id}) | |
.canHandleIntent(S.documentTypeList(schema).getCanHandleIntent()) | |
.initialValueTemplates([ | |
S.initialValueTemplateItem('category-child', { | |
parentId: parent._id, | |
}), | |
]) | |
.child((id) => S.document().documentId(id).views(views)) | |
) | |
), | |
]) | |
) | |
) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment