Skip to content

Commit

Permalink
feat(Web patches): Diffing of strings
Browse files Browse the repository at this point in the history
  • Loading branch information
nokome committed Oct 10, 2021
1 parent 2002a96 commit ebf8e61
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 3 deletions.
11 changes: 11 additions & 0 deletions web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"@types/prosemirror-tables": "^0.9.1",
"@types/prosemirror-transform": "^1.1.4",
"@types/prosemirror-view": "^1.19.1",
"fast-array-diff": "^1.0.1",
"grapheme-splitter": "^1.0.4",
"lit": "^2.0.0",
"prosemirror-collab": "^1.2.2",
Expand Down
16 changes: 15 additions & 1 deletion web/src/patches/string/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
import { applyAdd, applyRemove, applyReplace } from '.'
import { applyAdd, applyRemove, applyReplace, diff } from '.'

test('diff', () => {
expect(diff('', '').ops).toEqual([])
expect(diff('', 'ab').ops).toEqual([
{ type: 'Add', address: [0], value: 'ab', length: 2 },
])
expect(diff('aa', 'a🏳️‍🌈b').ops).toEqual([
{ type: 'Remove', address: [1], items: 1 },
{ type: 'Add', address: [1], value: '🏳️‍🌈b', length: 2 },
])
expect(diff('a🏳️‍🌈bc', 'ac').ops).toEqual([
{ type: 'Remove', address: [1], items: 2 },
])
})

test('applyAdd', () => {
expect(applyAdd('', 0, 'a')).toEqual('a')
Expand Down
29 changes: 27 additions & 2 deletions web/src/patches/string/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,31 @@
import { DomOperation, Slot } from '@stencila/stencila'
import { assert, assertIndex, panic } from '../checks'
import { Operation, DomOperation, Patch, Slot } from '@stencila/stencila'
import { getPatch } from 'fast-array-diff'
import GraphemeSplitter from 'grapheme-splitter'
import { assert, assertIndex, panic } from '../checks'

/**
* Generate a `Patch` describing the difference between two strings
*/
export function diff(a: string, b: string): Patch {
const patch = getPatch(toGraphemes(a), toGraphemes(b))
const ops = patch.map((op): Operation => {
if (op.type === 'add') {
return {
type: 'Add',
address: [op.newPos],
value: op.items.join(''),
length: op.items.length,
}
} else {
return {
type: 'Remove',
address: [op.newPos],
items: op.items.length,
}
}
})
return { ops }
}

/**
* Apply a `DomOperation` to a string.
Expand Down

0 comments on commit ebf8e61

Please sign in to comment.