Files
yjs/structs/ItemJSON.js

83 lines
2.0 KiB
JavaScript
Raw Normal View History

/**
2018-11-25 03:17:00 +01:00
* @module structs
*/
2017-10-11 03:41:54 +02:00
2018-11-27 14:59:12 +01:00
import { Item, splitHelper } from './Item.js'
import { logItemHelper } from '../protocols/syncProtocol.js'
import * as encoding from '../lib/encoding.js'
import * as decoding from '../lib/decoding.js'
import { Y } from '../utils/Y.js' // eslint-disable-line
2018-11-25 03:17:00 +01:00
export class ItemJSON extends Item {
2017-10-11 03:41:54 +02:00
constructor () {
super()
this._content = null
}
2018-02-15 17:58:14 +01:00
_copy () {
let struct = super._copy()
2017-10-30 11:33:00 +01:00
struct._content = this._content
return struct
}
2017-10-11 03:41:54 +02:00
get _length () {
return this._content.length
}
/**
* @param {Y} y
* @param {decoding.Decoder} decoder
*/
2017-10-11 03:41:54 +02:00
_fromBinary (y, decoder) {
let missing = super._fromBinary(y, decoder)
let len = decoding.readVarUint(decoder)
2017-10-11 03:41:54 +02:00
this._content = new Array(len)
for (let i = 0; i < len; i++) {
const ctnt = decoding.readVarString(decoder)
let parsed
if (ctnt === 'undefined') {
parsed = undefined
} else {
parsed = JSON.parse(ctnt)
}
this._content[i] = parsed
2017-10-11 03:41:54 +02:00
}
return missing
}
/**
* @param {encoding.Encoder} encoder
*/
2017-10-16 04:53:12 +02:00
_toBinary (encoder) {
super._toBinary(encoder)
2017-10-11 03:41:54 +02:00
let len = this._content.length
encoding.writeVarUint(encoder, len)
2017-10-11 03:41:54 +02:00
for (let i = 0; i < len; i++) {
let encoded
let content = this._content[i]
if (content === undefined) {
encoded = 'undefined'
} else {
encoded = JSON.stringify(content)
}
encoding.writeVarString(encoder, encoded)
2017-10-11 03:41:54 +02:00
}
}
2018-03-29 11:58:02 +02:00
/**
* Transform this YXml Type to a readable format.
* Useful for logging as all Items and Delete implement this method.
*
* @private
*/
2017-10-11 03:41:54 +02:00
_logString () {
2018-03-29 11:58:02 +02:00
return logItemHelper('ItemJSON', this, `content:${JSON.stringify(this._content)}`)
2017-10-11 03:41:54 +02:00
}
2017-10-16 04:53:12 +02:00
_splitAt (y, diff) {
if (diff === 0) {
return this
} else if (diff >= this._length) {
return this._right
}
let item = new ItemJSON()
item._content = this._content.splice(diff)
splitHelper(y, this, item, diff)
return item
}
2017-10-11 03:41:54 +02:00
}