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

Preserve external history option #22

Merged
merged 3 commits into from Jul 1, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -31,6 +31,7 @@ Check [detailed example](https://github.com/cudr/slate-collaborative/blob/master
onConnect?: () => void // connect callback
onDisconnect?: () => void // disconnect callback
onError?: (reason: string) => void // error callback
preserveExternalHistory?: boolean // preserve slate-history operations form other clients
}
```

Expand Down
8 changes: 6 additions & 2 deletions packages/bridge/src/apply/text.ts
Expand Up @@ -9,7 +9,9 @@ export const insertText = (
): SyncValue => {
const node = getTarget(doc, op.path)

node.text.insertAt(op.offset, ...op.text.split(''))
const offset = Math.min(node.text.length, op.offset)

node.text.insertAt(offset, ...op.text.split(''))

return doc
}
Expand All @@ -20,7 +22,9 @@ export const removeText = (
): SyncValue => {
const node = getTarget(doc, op.path)

node.text.deleteAt(op.offset, op.text.length)
const offset = Math.min(node.text.length, op.offset)

node.text.deleteAt(offset, op.text.length)

return doc
}
Expand Down
6 changes: 2 additions & 4 deletions packages/bridge/src/convert/convert.spec.ts
Expand Up @@ -54,15 +54,13 @@ describe('convert operations to slatejs model', () => {
{
type: 'remove_node',
path: [1],
node: {
text: '*'
}
node: createNode('paragraph', 'hello twice!')
},
{
type: 'remove_node',
path: [0, 0],
node: {
text: '*'
children: []
}
}
]
Expand Down
2 changes: 1 addition & 1 deletion packages/bridge/src/convert/create.ts
@@ -1,6 +1,6 @@
import * as Automerge from 'automerge'

const createByType = (type: any) =>
const createByType = (type: Automerge.CollectionType) =>
type === 'map' ? {} : type === 'list' ? [] : ''

const opCreate = ({ obj, type }: Automerge.Diff, [map, ops]: any) => {
Expand Down
6 changes: 5 additions & 1 deletion packages/bridge/src/convert/index.ts
Expand Up @@ -5,6 +5,8 @@ import opRemove from './remove'
import opSet from './set'
import opCreate from './create'

import { toJS } from '../utils'

import { SyncDoc } from '../model'

const byAction = {
Expand Down Expand Up @@ -32,7 +34,9 @@ const toSlateOp = (ops: Automerge.Diff[], doc: SyncDoc) => {
[]
])

return defer.flatMap(op => op(tempTree, doc)).filter(op => op)
const tempDoc = toJS(doc)

return defer.flatMap(op => op(tempTree, tempDoc)).filter(op => op)
}

export { toSlateOp }
49 changes: 36 additions & 13 deletions packages/bridge/src/convert/remove.ts
@@ -1,33 +1,56 @@
import * as Automerge from 'automerge'
import { Element } from 'slate'

import { toSlatePath, toJS } from '../utils'
import { getTarget } from '../path'

const removeTextOp = ({ index, path }: Automerge.Diff) => () => ({
type: 'remove_text',
path: toSlatePath(path).slice(0, path?.length),
offset: index,
text: '*',
marks: []
})
const removeTextOp = (op: Automerge.Diff) => (map: any, doc: Element) => {
const { index, path, obj } = op

const slatePath = toSlatePath(path).slice(0, path?.length)

let node

try {
node = getTarget(doc, slatePath) || map[obj]
} catch (e) {
console.error(e, op, doc)
}

if (typeof index !== 'number') return

const text = node?.text[index] || '*'

if (node) {
node.text = node.text?.slice(0, index) + node.text?.slice(index + 1)
}

return {
type: 'remove_text',
path: slatePath,
offset: index,
text,
marks: []
}
}

const removeNodeOp = ({ index, obj, path }: Automerge.Diff) => (
map: any,
doc: any
doc: Element
) => {
const slatePath = toSlatePath(path)
if (!map.hasOwnProperty(obj)) {
const target = getTarget(doc, [...slatePath, index] as any)

const parent = getTarget(doc, slatePath)
const target = parent?.children[index as number] || { children: [] }

if (!map.hasOwnProperty(obj)) {
map[obj] = target
}

return {
type: 'remove_node',
path: slatePath.length ? slatePath.concat(index) : [index],
node: {
text: '*'
}
node: target
}
}

Expand Down
6 changes: 3 additions & 3 deletions packages/bridge/src/path/index.ts
@@ -1,10 +1,10 @@
import { Node, Path } from 'slate'
import { Element, Node, Path } from 'slate'

import { SyncValue } from '../model'

export const isTree = (node: Node): boolean => Boolean(node?.children)

export const getTarget = (doc: SyncValue, path: Path) => {
export const getTarget = (doc: SyncValue | Element, path: Path) => {
const iterate = (current: any, idx: number) => {
if (!(isTree(current) || current[idx])) {
throw new TypeError(
Expand All @@ -30,7 +30,7 @@ export const getParentPath = (
}

export const getParent = (
doc: SyncValue,
doc: SyncValue | Element,
path: Path,
level = 1
): [any, number] => {
Expand Down
1 change: 1 addition & 0 deletions packages/client/package.json
Expand Up @@ -29,6 +29,7 @@
"@slate-collaborative/bridge": "^0.6.7",
"automerge": "0.14.0",
"slate": "0.58.3",
"slate-history": "0.58.3",
"socket.io-client": "^2.3.0",
"typescript": "^3.8.3"
},
Expand Down
18 changes: 12 additions & 6 deletions packages/client/src/automerge-editor.ts
@@ -1,6 +1,7 @@
import Automerge from 'automerge'

import { Editor, Operation } from 'slate'
import { HistoryEditor } from 'slate-history'

import {
toJS,
Expand Down Expand Up @@ -111,7 +112,8 @@ export const AutomergeEditor = {
applyOperation: (
e: AutomergeEditor,
docId: string,
data: Automerge.Message
data: Automerge.Message,
preserveExternalHistory?: boolean
) => {
try {
const current: any = e.docSet.getDoc(docId)
Expand All @@ -126,13 +128,17 @@ export const AutomergeEditor = {
e.isRemote = true

Editor.withoutNormalizing(e, () => {
slateOps.forEach((o: Operation) => {
e.apply(o)
})
if (HistoryEditor.isHistoryEditor(e) && !preserveExternalHistory) {
HistoryEditor.withoutSaving(e, () => {
slateOps.forEach((o: Operation) => e.apply(o))
})
} else {
slateOps.forEach((o: Operation) => e.apply(o))
}

e.onCursor && e.onCursor(updated.cursors)
})

e.onCursor && e.onCursor(updated.cursors)

Promise.resolve().then(_ => (e.isRemote = false))
}
} catch (e) {
Expand Down
11 changes: 5 additions & 6 deletions packages/client/src/withAutomerge.ts
Expand Up @@ -9,6 +9,7 @@ import { CursorData, CollabAction } from '@slate-collaborative/bridge'
export interface AutomergeOptions {
docId: string
cursorData?: CursorData
preserveExternalHistory?: boolean
}

/**
Expand All @@ -23,7 +24,7 @@ const withAutomerge = <T extends Editor>(

const { onChange } = e

const { docId, cursorData } = options || {}
const { docId, cursorData, preserveExternalHistory } = options || {}

e.docSet = new Automerge.DocSet()

Expand Down Expand Up @@ -73,11 +74,9 @@ const withAutomerge = <T extends Editor>(

if (!e.isRemote) {
AutomergeEditor.applySlateOps(e, docId, operations, cursorData)
}

onChange()

// console.log('e', e.children)
onChange()
}
}

/**
Expand All @@ -97,7 +96,7 @@ const withAutomerge = <T extends Editor>(
e.receiveOperation = data => {
if (docId !== data.docId) return

AutomergeEditor.applyOperation(e, docId, data)
AutomergeEditor.applyOperation(e, docId, data, preserveExternalHistory)
}

return e
Expand Down