Skip to content

Commit

Permalink
Allow objects to appear as elements in Automerge.Text
Browse files Browse the repository at this point in the history
Fixes #194
  • Loading branch information
ept committed Sep 10, 2019
1 parent 66bb6b5 commit 2ff0009
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
5 changes: 3 additions & 2 deletions frontend/apply_patch.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,8 @@ function updateTextObject(diffs, startIndex, endIndex, cache, updated) {
insertions = []
}
maxElem = Math.max(maxElem, parseElemId(diff.elemId).counter)
insertions.push({elemId: diff.elemId, value: diff.value, conflicts: diff.conflicts})
const value = getValue(diff, cache, updated)
insertions.push({elemId: diff.elemId, value, conflicts: diff.conflicts})

if (startIndex === endIndex || diffs[startIndex + 1].action !== 'insert' ||
diffs[startIndex + 1].index !== diff.index + 1) {
Expand All @@ -352,7 +353,7 @@ function updateTextObject(diffs, startIndex, endIndex, cache, updated) {
} else if (diff.action === 'set') {
elems[diff.index] = {
elemId: elems[diff.index].elemId,
value: diff.value,
value: getValue(diff, cache, updated),
conflicts: diff.conflicts
}

Expand Down
13 changes: 11 additions & 2 deletions frontend/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ class Text {
return this.elems[index].elemId
}

/**
* Iterates over the text elements character by character, including any
* inline objects.
*/
[Symbol.iterator] () {
let elems = this.elems, index = -1
return {
Expand All @@ -45,14 +49,19 @@ class Text {
* Returns the content of the Text object as a simple string.
*/
toString() {
return this.join('')
let chars = []
for (let elem of this.elems) {
if (typeof elem.value === 'string') chars.push(elem.value)
}
return chars.join('')
}

/**
* Returns the content of the Text object as a simple string, so that the
* JSON serialization of an Automerge document represents text nicely.
*/
toJSON() {
return this.join('')
return this.toString()
}

/**
Expand Down
8 changes: 5 additions & 3 deletions test/text_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,15 +160,17 @@ describe('Automerge.Text', () => {
assert.strictEqual(s1.text.toString(), 'Init')
})
})

describe('non-textual control characters', () => {
let s1
beforeEach(() => {
s1 = Automerge.change(Automerge.init(), doc => {
doc.text = new Automerge.Text()
doc.text.insertAt(0, 'a')
doc.text.insertAt(1, { attribute: 'bold' })
doc.text = new Automerge.Text()
doc.text.insertAt(0, 'a')
doc.text.insertAt(1, { attribute: 'bold' })
})
})

it('should allow fetching non-textual characters', () => {
assert.deepEqual(s1.text.get(1), { attribute: 'bold' })
})
Expand Down

0 comments on commit 2ff0009

Please sign in to comment.