-
Notifications
You must be signed in to change notification settings - Fork 394
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[desk-tool] Move undo changes logic to separate file
- Loading branch information
Showing
2 changed files
with
34 additions
and
31 deletions.
There are no files selected for viewing
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
31 changes: 31 additions & 0 deletions
31
packages/@sanity/desk-tool/src/panes/documentPane/changesPanel/undoChange.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import {diffItem} from 'sanity-diff-patch' | ||
import {Diff, Path} from '@sanity/diff' | ||
import {toString as pathToString} from '@sanity/util/paths' | ||
import {InsertPatch, UnsetPatch, SetPatch, OperationsAPI} from './types' | ||
|
||
export function undoChange(diff: Diff, path: Path, documentOperations: OperationsAPI) { | ||
const patches = diffItem(diff.toValue, diff.fromValue, {diffMatchPatch: {enabled: false}}, path) | ||
|
||
const inserts = patches | ||
.filter((patch): patch is InsertPatch => patch.op === 'insert') | ||
.map(({after, items}) => ({insert: {after, items}})) | ||
|
||
const unsets = patches | ||
.filter((patch): patch is UnsetPatch => patch.op === 'unset') | ||
.reduce((acc, patch) => acc.concat(pathToString(patch.path)), [] as string[]) | ||
|
||
let hasSets = false | ||
const sets = patches | ||
.filter((patch): patch is SetPatch => patch.op === 'set') | ||
.reduce((acc, patch) => { | ||
hasSets = true | ||
acc[pathToString(patch.path)] = patch.value | ||
return acc | ||
}, {} as Record<string, unknown>) | ||
|
||
return documentOperations.patch.execute([ | ||
...inserts, | ||
...(unsets.length > 0 ? [{unset: unsets}] : []), | ||
...(hasSets ? [{set: sets}] : []) | ||
]) | ||
} |