Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to add new documents on top #80

Merged
merged 1 commit into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ Additionally, pass in overrides for the field, such as making it visible by pass

You cannot override the `name`, `type` or `initialValue` attributes.

You can configure the placement of new documents by setting `newItemPosition` to `before` (defaults to `after`).

```js
// sanity.config.js
import {defineConfig} from "sanity";
Expand All @@ -136,8 +138,11 @@ export default defineConfig({
// Minimum required configuration
orderRankField({ type: "category" }),

// OR placing new documents on top
orderRankField({ type: "category", newItemPosition: "before" }),

// OR you can override _some_ of the field settings
orderRankField({ type: 'category', hidden: false }),
orderRankField({ type: "category", hidden: false }),

// ...all other fields
],
Expand All @@ -153,8 +158,8 @@ export default defineConfig({
On first load, your Document list will not have any Order. You can select "Reset Order" from the menu in the top right of the list.
You can also re-run this at any time.

The `orderRankField` will query the last Document to set an `initialValue` to come after it.
New Documents always start at the end of the Ordered list.
The `orderRankField` will query the last/first Document to set an `initialValue` to come after/before it.
The placement of new documents can be configured by `newItemPosition` on the `orderRankField` in the document.

## Querying Ordered Documents

Expand Down
3 changes: 2 additions & 1 deletion src/desk-structure/orderableDocumentListDeskItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {ConfigContext} from 'sanity'
import {ComponentType} from 'react'
import {StructureBuilder, type ListItem, type MenuItem} from 'sanity/desk'
import OrderableDocumentList from '../OrderableDocumentList'
import {API_VERSION} from '../helpers/constants'

export interface OrderableListConfig {
type: string
Expand All @@ -29,7 +30,7 @@ export function orderableDocumentListDeskItem(config: OrderableListConfig): List

const {type, filter, menuItems = [], createIntent, params, title, icon, id, context, S} = config
const {schema, getClient} = context
const client = getClient({apiVersion: '2021-09-01'})
const client = getClient({apiVersion: API_VERSION})

const listTitle = title ?? `Orderable ${type}`
const listId = id ?? `orderable-${type}`
Expand Down
14 changes: 9 additions & 5 deletions src/fields/orderRankField.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import {type ConfigContext, defineField} from 'sanity'
import {ORDER_FIELD_NAME} from '../helpers/constants'
import {API_VERSION, ORDER_FIELD_NAME} from '../helpers/constants'
import initialRank from '../helpers/initialRank'
import {NewItemPosition} from '../types'

export type SchemaContext = Omit<ConfigContext, 'schema' | 'currentUser' | 'client'>

export interface RankFieldConfig {
type: string
newItemPosition?: NewItemPosition
}

export const orderRankField = (config: RankFieldConfig) => {

Check warning on line 13 in src/fields/orderRankField.ts

View workflow job for this annotation

GitHub Actions / Lint & Build

Missing return type on function
if (!config?.type) {
throw new Error(
`
Expand All @@ -18,7 +20,7 @@
)
}

const {type} = config
const {type, newItemPosition = 'after'} = config
return defineField({
title: 'Order Rank',
readOnly: true,
Expand All @@ -27,11 +29,13 @@
name: ORDER_FIELD_NAME,
type: 'string',
initialValue: async (p, {getClient}) => {
const lastDocOrderRank = await getClient({apiVersion: '2021-09-01'}).fetch(
`*[_type == $type]|order(@[$order] desc)[0][$order]`,
const direction = newItemPosition === 'before' ? 'asc' : 'desc'

const lastDocOrderRank = await getClient({apiVersion: API_VERSION}).fetch(
`*[_type == $type]|order(@[$order] ${direction})[0][$order]`,
{type, order: ORDER_FIELD_NAME}
)
return initialRank(lastDocOrderRank)
return initialRank(lastDocOrderRank, newItemPosition)
},
})
}
3 changes: 2 additions & 1 deletion src/helpers/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {useClient} from 'sanity'
import {API_VERSION} from './constants'

export function useSanityClient() {

Check warning on line 4 in src/helpers/client.ts

View workflow job for this annotation

GitHub Actions / Lint & Build

Missing return type on function
return useClient({apiVersion: '2021-09-01'})
return useClient({apiVersion: API_VERSION})
}
2 changes: 2 additions & 0 deletions src/helpers/constants.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export const ORDER_FIELD_NAME = `orderRank` as const

export const API_VERSION = `2021-09-01` as const
13 changes: 9 additions & 4 deletions src/helpers/initialRank.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import {LexoRank} from 'lexorank'
import {NewItemPosition} from '../types'

// Use in initial value field by passing in the rank value of the last document
// If not value passed, generate a sensibly low rank
export default function initialRank(lastRankValue = ``): string {
const lastRank = lastRankValue ? LexoRank.parse(lastRankValue) : LexoRank.min()
const nextRank = lastRank.genNext().genNext()
export default function initialRank(
compareRankValue = ``,
newItemPosition: NewItemPosition = 'after'
): string {
const compareRank = compareRankValue ? LexoRank.parse(compareRankValue) : LexoRank.min()
const rank =
newItemPosition === 'before' ? compareRank.genPrev().genPrev() : compareRank.genNext().genNext()

return nextRank.toString()
return rank.toString()
}
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ export interface SanityDocumentWithOrder extends SanityDocument {
[ORDER_FIELD_NAME]?: string
hasPublished?: boolean
}

export type NewItemPosition = 'after' | 'before'
Loading