Compare commits

..

14 Commits

Author SHA1 Message Date
Kevin Jahns
b1192fbb46 v13.0.0-32 -- distribution files 2017-11-14 21:31:19 -08:00
Kevin Jahns
2e3240b379 13.0.0-32 2017-11-14 21:31:11 -08:00
Kevin Jahns
2558652356 fix attribute filter (it used to filter everything) 2017-11-14 21:19:39 -08:00
Kevin Jahns
783cbd63fc 13.0.0-31 2017-11-14 20:44:12 -08:00
Kevin Jahns
41be80e751 fix y-xml server environment 2017-11-14 20:43:30 -08:00
Kevin Jahns
3d6050d8a2 13.0.0-30 2017-11-12 13:37:37 -08:00
Kevin Jahns
3d5ba7b4cc fix the case that a new transaction starts in an event listener (afterTransaction, observe, observeDeep) 2017-11-12 13:37:06 -08:00
Kevin Jahns
415b66607c fixed filtering 2017-11-10 19:04:00 -08:00
Kevin Jahns
05cd1d0575 13.0.0-29 2017-11-10 18:46:10 -08:00
Kevin Jahns
4edc22bedb remove prematurely commited dom-filter update 2017-11-10 18:45:41 -08:00
Kevin Jahns
16f84c67d5 13.0.0-28 2017-11-10 18:41:39 -08:00
Kevin Jahns
290d3c8ffe support undefined as an attribute value 2017-11-10 18:41:10 -08:00
Kevin Jahns
c51e8b46c2 13.0.0-27 2017-11-10 12:55:05 -08:00
Kevin Jahns
0cda1630d2 fix path bugs 2017-11-10 12:54:33 -08:00
26 changed files with 819 additions and 618 deletions

View File

@@ -1,4 +1,15 @@
/* global Y */
/* global Y, HTMLElement, customElements */
class MagicTable extends HTMLElement {
constructor () {
super()
var shadow = this.attachShadow({mode: 'open'})
setTimeout(() => {
shadow.append(this.childNodes[0])
}, 1000)
}
}
customElements.define('magic-table', MagicTable)
// initialize a shared object. This function call returns a promise!
let y = new Y({
@@ -17,17 +28,14 @@ window.onload = function () {
window.yXmlType.bindToDom(document.body)
}
window.undoManager = new Y.utils.UndoManager(window.yXmlType, {
captureTimeout: 0
captureTimeout: 500
})
document.onkeydown = function interceptUndoRedo (e) {
if (e.keyCode === 90 && e.metaKey) {
console.log('uidtaren')
if (!e.shiftKey) {
console.info('Undo!')
window.undoManager.undo()
} else {
console.info('Redo!')
window.undoManager.redo()
}
e.preventDefault()

36
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "yjs",
"version": "13.0.0-25",
"version": "13.0.0-32",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -2808,14 +2808,6 @@
}
}
},
"string_decoder": {
"version": "1.0.1",
"bundled": true,
"dev": true,
"requires": {
"safe-buffer": "5.0.1"
}
},
"string-width": {
"version": "1.0.2",
"bundled": true,
@@ -2826,6 +2818,14 @@
"strip-ansi": "3.0.1"
}
},
"string_decoder": {
"version": "1.0.1",
"bundled": true,
"dev": true,
"requires": {
"safe-buffer": "5.0.1"
}
},
"stringstream": {
"version": "0.0.5",
"bundled": true,
@@ -4868,15 +4868,6 @@
"duplexer": "0.1.1"
}
},
"string_decoder": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz",
"integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==",
"dev": true,
"requires": {
"safe-buffer": "5.1.1"
}
},
"string-width": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
@@ -4898,6 +4889,15 @@
"resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.0.tgz",
"integrity": "sha1-aybpvTr8qnvjtCabUm3huCAArHg="
},
"string_decoder": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz",
"integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==",
"dev": true,
"requires": {
"safe-buffer": "5.1.1"
}
},
"strip-ansi": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "yjs",
"version": "13.0.0-26",
"version": "13.0.0-32",
"description": "A framework for real-time p2p shared editing on any data",
"main": "./y.node.js",
"browser": "./y.js",

View File

@@ -5,9 +5,13 @@ import commonjs from 'rollup-plugin-commonjs'
var pkg = require('./package.json')
export default {
entry: 'src/Y.js',
moduleName: 'Y',
format: 'umd',
input: 'src/Y.js',
name: 'Y',
sourcemap: true,
output: {
file: 'y.js',
format: 'umd'
},
plugins: [
nodeResolve({
main: true,
@@ -32,8 +36,6 @@ export default {
}
})
],
dest: 'y.js',
sourceMap: true,
banner: `
/**
* ${pkg.name} - ${pkg.description}

View File

@@ -3,9 +3,13 @@ import commonjs from 'rollup-plugin-commonjs'
var pkg = require('./package.json')
export default {
entry: 'src/y-dist.cjs.js',
moduleName: 'Y',
format: 'cjs',
input: 'src/y-dist.cjs.js',
nameame: 'Y',
sourcemap: true,
output: {
file: 'y.node.js',
format: 'cjs'
},
plugins: [
nodeResolve({
main: true,
@@ -14,8 +18,6 @@ export default {
}),
commonjs()
],
dest: 'y.node.js',
sourceMap: true,
banner: `
/**
* ${pkg.name} - ${pkg.description}

View File

@@ -3,9 +3,13 @@ import commonjs from 'rollup-plugin-commonjs'
import multiEntry from 'rollup-plugin-multi-entry'
export default {
entry: 'test/y-xml.tests.js',
moduleName: 'y-tests',
format: 'umd',
input: 'test/y-xml.tests.js',
name: 'y-tests',
sourcemap: true,
output: {
file: 'y.test.js',
format: 'umd'
},
plugins: [
nodeResolve({
main: true,
@@ -14,7 +18,5 @@ export default {
}),
commonjs(),
multiEntry()
],
dest: 'y.test.js',
sourceMap: true
]
}

View File

@@ -20,7 +20,13 @@ export default class ItemJSON extends Item {
this._content = new Array(len)
for (let i = 0; i < len; i++) {
const ctnt = decoder.readVarString()
this._content[i] = JSON.parse(ctnt)
let parsed
if (ctnt === 'undefined') {
parsed = undefined
} else {
parsed = JSON.parse(ctnt)
}
this._content[i] = parsed
}
return missing
}
@@ -29,7 +35,14 @@ export default class ItemJSON extends Item {
let len = this._content.length
encoder.writeVarUint(len)
for (let i = 0; i < len; i++) {
encoder.writeVarString(JSON.stringify(this._content[i]))
let encoded
let content = this._content[i]
if (content === undefined) {
encoded = 'undefined'
} else {
encoded = JSON.stringify(content)
}
encoder.writeVarString(encoded)
}
}
_logString () {

View File

@@ -65,9 +65,9 @@ export default class Type extends Item {
}
return path
}
_callEventHandler (event) {
const changedParentTypes = this._y._transaction.changedParentTypes
this._eventHandler.callEventListeners(event)
_callEventHandler (transaction, event) {
const changedParentTypes = transaction.changedParentTypes
this._eventHandler.callEventListeners(transaction, event)
let type = this
while (type !== this._y) {
let events = changedParentTypes.get(type)

View File

@@ -1,5 +1,6 @@
import Type from '../Struct/Type.js'
import ItemJSON from '../Struct/ItemJSON.js'
import ItemString from '../Struct/ItemString.js'
import { logID } from '../MessageHandler/messageToString.js'
import YEvent from '../Util/YEvent.js'
@@ -11,15 +12,19 @@ class YArrayEvent extends YEvent {
}
export default class YArray extends Type {
_callObserver (parentSubs, remote) {
this._callEventHandler(new YArrayEvent(this, remote))
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YArrayEvent(this, remote))
}
get (pos) {
let n = this._start
while (n !== null) {
if (!n._deleted) {
if (pos < n._length) {
return n._content[n._length - pos]
if (n.constructor === ItemJSON || n.constructor === ItemString) {
return n._content[pos]
} else {
return n
}
}
pos -= n._length
}

View File

@@ -13,8 +13,8 @@ class YMapEvent extends YEvent {
}
export default class YMap extends Type {
_callObserver (parentSubs, remote) {
this._callEventHandler(new YMapEvent(this, parentSubs, remote))
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YMapEvent(this, parentSubs, remote))
}
toJSON () {
const map = {}

View File

@@ -5,7 +5,7 @@ import YMap from '../YMap.js'
import YXmlFragment from './YXmlFragment.js'
export default class YXmlElement extends YXmlFragment {
constructor (arg1, arg2) {
constructor (arg1, arg2, _document) {
super()
this.nodeName = null
this._scrollElement = null
@@ -13,7 +13,7 @@ export default class YXmlElement extends YXmlFragment {
this.nodeName = arg1.toUpperCase()
} else if (arg1 != null && arg1.nodeType != null && arg1.nodeType === arg1.ELEMENT_NODE) {
this.nodeName = arg1.nodeName
this._setDom(arg1)
this._setDom(arg1, _document)
} else {
this.nodeName = 'UNDEFINED'
}
@@ -26,14 +26,12 @@ export default class YXmlElement extends YXmlFragment {
struct.nodeName = this.nodeName
return struct
}
_setDom (dom) {
_setDom (dom, _document) {
if (this._dom != null) {
throw new Error('Only call this method if you know what you are doing ;)')
} else if (dom._yxml != null) { // TODO do i need to check this? - no.. but for dev purps..
throw new Error('Already bound to an YXml type')
} else {
this._dom = dom
dom._yxml = this
// tag is already set in constructor
// set attributes
let attrNames = []
@@ -46,8 +44,8 @@ export default class YXmlElement extends YXmlFragment {
let attrValue = dom.getAttribute(attrName)
this.setAttribute(attrName, attrValue)
}
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes))
this._bindToDom(dom)
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes), _document)
this._bindToDom(dom, _document)
return dom
}
}
@@ -115,7 +113,6 @@ export default class YXmlElement extends YXmlFragment {
let dom = this._dom
if (dom == null) {
dom = _document.createElement(this.nodeName)
this._dom = dom
dom._yxml = this
let attrs = this.getAttributes()
for (let key in attrs) {
@@ -124,7 +121,7 @@ export default class YXmlElement extends YXmlFragment {
this.forEach(yxml => {
dom.appendChild(yxml.getDom(_document))
})
this._bindToDom(dom)
this._bindToDom(dom, _document)
}
return dom
}

View File

@@ -9,7 +9,7 @@ import YXmlEvent from './YXmlEvent.js'
import { logID } from '../../MessageHandler/messageToString.js'
import diff from 'fast-diff'
function domToYXml (parent, doms) {
function domToYXml (parent, doms, _document) {
const types = []
doms.forEach(d => {
if (d._yxml != null && d._yxml !== false) {
@@ -20,7 +20,7 @@ function domToYXml (parent, doms) {
if (d.nodeType === d.TEXT_NODE) {
type = new YXmlText(d)
} else if (d.nodeType === d.ELEMENT_NODE) {
type = new YXmlFragment._YXmlElement(d, parent._domFilter)
type = new YXmlFragment._YXmlElement(d, parent._domFilter, _document)
} else {
throw new Error('Unsupported node!')
}
@@ -98,7 +98,9 @@ export default class YXmlFragment extends YArray {
} catch (e) {
console.error(e)
}
this._domObserver.takeRecords()
if (this._domObserver !== null) {
this._domObserver.takeRecords()
}
token = true
}
}
@@ -142,8 +144,8 @@ export default class YXmlFragment extends YArray {
xml.setDomFilter(f)
})
}
_callObserver (parentSubs, remote) {
this._callEventHandler(new YXmlEvent(this, parentSubs, remote))
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YXmlEvent(this, parentSubs, remote))
}
toString () {
return this.map(xml => xml.toString()).join('')
@@ -162,113 +164,116 @@ export default class YXmlFragment extends YArray {
this._dom = null
}
}
insertDomElementsAfter (prev, doms) {
const types = domToYXml(this, doms)
insertDomElementsAfter (prev, doms, _document) {
const types = domToYXml(this, doms, _document)
this.insertAfter(prev, types)
return types
}
insertDomElements (pos, doms) {
const types = domToYXml(this, doms)
insertDomElements (pos, doms, _document) {
const types = domToYXml(this, doms, _document)
this.insert(pos, types)
return types
}
getDom () {
return this._dom
}
bindToDom (dom) {
bindToDom (dom, _document) {
if (this._dom != null) {
this._unbindFromDom()
}
if (dom._yxml != null) {
dom._yxml._unbindFromDom()
}
if (MutationObserver == null) {
throw new Error('Not able to bind to a DOM element, because MutationObserver is not available!')
}
dom.innerHTML = ''
this._dom = dom
dom._yxml = this
this.forEach(t => {
dom.insertBefore(t.getDom(), null)
dom.insertBefore(t.getDom(_document), null)
})
this._bindToDom(dom)
this._bindToDom(dom, _document)
}
// binds to a dom element
// Only call if dom and YXml are isomorph
_bindToDom (dom) {
if (this._parent === null || this._parent._dom != null || typeof MutationObserver === 'undefined') {
// only bind if parent did not already bind
_bindToDom (dom, _document) {
_document = _document || document
this._dom = dom
dom._yxml = this
// TODO: refine this..
if ((this.constructor !== YXmlFragment && this._parent !== this._y) || this._parent === null) {
// TODO: only top level YXmlFragment can bind. Also allow YXmlElements..
return
}
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords())
})
this._y.on('beforeTransaction', beforeTransactionSelectionFixer)
this._y.on('afterTransaction', afterTransactionSelectionFixer)
// Apply Y.Xml events to dom
this.observeDeep(reflectChangesOnDom.bind(this))
this.observeDeep(events => {
reflectChangesOnDom.call(this, events, _document)
})
// Apply Dom changes on Y.Xml
this._domObserverListener = mutations => {
this._mutualExclude(() => {
this._y.transact(() => {
let diffChildren = new Set()
mutations.forEach(mutation => {
const dom = mutation.target
const yxml = dom._yxml
if (yxml == null) {
// dom element is filtered
return
}
switch (mutation.type) {
case 'characterData':
var diffs = diff(yxml.toString(), dom.nodeValue)
var pos = 0
for (var i = 0; i < diffs.length; i++) {
var d = diffs[i]
if (d[0] === 0) { // EQUAL
pos += d[1].length
} else if (d[0] === -1) { // DELETE
yxml.delete(pos, d[1].length)
} else { // INSERT
yxml.insert(pos, d[1])
pos += d[1].length
}
}
break
case 'attributes':
let name = mutation.attributeName
// check if filter accepts attribute
if (this._domFilter(dom, [name]).length > 0 && this.constructor !== YXmlFragment) {
var val = dom.getAttribute(name)
if (yxml.getAttribute(name) !== val) {
if (val == null) {
yxml.removeAttribute(name)
} else {
yxml.setAttribute(name, val)
if (typeof MutationObserver !== 'undefined') {
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords())
})
this._domObserverListener = mutations => {
this._mutualExclude(() => {
this._y.transact(() => {
let diffChildren = new Set()
mutations.forEach(mutation => {
const dom = mutation.target
const yxml = dom._yxml
if (yxml == null) {
// dom element is filtered
return
}
switch (mutation.type) {
case 'characterData':
var diffs = diff(yxml.toString(), dom.nodeValue)
var pos = 0
for (var i = 0; i < diffs.length; i++) {
var d = diffs[i]
if (d[0] === 0) { // EQUAL
pos += d[1].length
} else if (d[0] === -1) { // DELETE
yxml.delete(pos, d[1].length)
} else { // INSERT
yxml.insert(pos, d[1])
pos += d[1].length
}
}
}
break
case 'childList':
diffChildren.add(mutation.target)
break
break
case 'attributes':
let name = mutation.attributeName
// check if filter accepts attribute
if (this._domFilter(dom, [name]).length > 0 && yxml.constructor !== YXmlFragment) {
var val = dom.getAttribute(name)
if (yxml.getAttribute(name) !== val) {
if (val == null) {
yxml.removeAttribute(name)
} else {
yxml.setAttribute(name, val)
}
}
}
break
case 'childList':
diffChildren.add(mutation.target)
break
}
})
for (let dom of diffChildren) {
if (dom._yxml != null && dom._yxml !== false) {
applyChangesFromDom(dom)
}
}
})
for (let dom of diffChildren) {
if (dom._yxml != null) {
applyChangesFromDom(dom)
}
}
})
}
this._domObserver = new MutationObserver(this._domObserverListener)
this._domObserver.observe(dom, {
childList: true,
attributes: true,
characterData: true,
subtree: true
})
}
this._domObserver = new MutationObserver(this._domObserverListener)
this._domObserver.observe(dom, {
childList: true,
attributes: true,
characterData: true,
subtree: true
})
return dom
}
_logString () {

View File

@@ -7,7 +7,7 @@ let relativeSelection = null
export let beforeTransactionSelectionFixer
if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, remote) {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, transaction, remote) {
if (!remote) {
return
}
@@ -30,7 +30,7 @@ if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _fakeBeforeTransactionSelectionFixer () {}
}
export function afterTransactionSelectionFixer (y, remote) {
export function afterTransactionSelectionFixer (y, transaction, remote) {
if (relativeSelection === null || !remote) {
return
}

View File

@@ -135,7 +135,33 @@ export function applyChangesFromDom (dom) {
}
}
export function reflectChangesOnDom (events) {
export function reflectChangesOnDom (events, _document) {
// Make sure that no filtered attributes are applied to the structure
// if they were, delete them
/*
events.forEach(event => {
const target = event.target
if (event.attributesChanged === undefined) {
// event.target is Y.XmlText
return
}
const keys = this._domFilter(target.nodeName, Array.from(event.attributesChanged))
if (keys === null) {
target._delete()
} else {
const removeKeys = new Set() // is a copy of event.attributesChanged
event.attributesChanged.forEach(key => { removeKeys.add(key) })
keys.forEach(key => {
// remove all accepted keys from removeKeys
removeKeys.delete(key)
})
// remove the filtered attribute
removeKeys.forEach(key => {
target.removeAttribute(key)
})
}
})
*/
this._mutualExclude(() => {
events.forEach(event => {
const yxml = event.target
@@ -157,9 +183,9 @@ export function reflectChangesOnDom (events) {
})
if (event.childListChanged) {
// create fragment of undeleted nodes
const fragment = document.createDocumentFragment()
const fragment = _document.createDocumentFragment()
yxml.forEach(function (t) {
fragment.append(t.getDom())
fragment.appendChild(t.getDom(_document))
})
// remove remainding nodes
let lastChild = dom.lastChild
@@ -168,7 +194,7 @@ export function reflectChangesOnDom (events) {
lastChild = dom.lastChild
}
// insert fragment of undeleted nodes
dom.append(fragment)
dom.appendChild(fragment)
}
}
/* TODO: smartscrolling

View File

@@ -17,7 +17,7 @@ export default class EventHandler {
removeAllEventListeners () {
this.eventListeners = []
}
callEventListeners (event) {
callEventListeners (transaction, event) {
for (var i = 0; i < this.eventListeners.length; i++) {
try {
const f = this.eventListeners[i]

View File

@@ -1,16 +1,16 @@
import ID from './ID.js'
class ReverseOperation {
constructor (y) {
constructor (y, transaction) {
this.created = new Date()
const beforeState = y._transaction.beforeState
const beforeState = transaction.beforeState
this.toState = new ID(y.userID, y.ss.getState(y.userID) - 1)
if (beforeState.has(y.userID)) {
this.fromState = new ID(y.userID, beforeState.get(y.userID))
} else {
this.fromState = this.toState
}
this.deletedStructs = y._transaction.deletedStructs
this.deletedStructs = transaction.deletedStructs
}
}
@@ -70,13 +70,12 @@ export default class UndoManager {
this._redoing = false
const y = scope._y
this.y = y
y.on('afterTransaction', (y, remote) => {
if (!remote && y._transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y)
y.on('afterTransaction', (y, transaction, remote) => {
if (!remote && transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y, transaction)
if (!this._undoing) {
let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null
if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) {
console.log('appending', lastUndoOp, reverseOperation)
lastUndoOp.created = reverseOperation.created
lastUndoOp.toState = reverseOperation.toState
reverseOperation.deletedStructs.forEach(lastUndoOp.deletedStructs.add, lastUndoOp.deletedStructs)
@@ -93,7 +92,6 @@ export default class UndoManager {
})
}
undo () {
console.log('undoing')
this._undoing = true
const performedUndo = applyReverseOperation(this.y, this._scope, this._undoBuffer)
this._undoing = false

View File

@@ -8,15 +8,15 @@ export default class YEvent {
const path = []
let type = this.target
const y = type._y
while (type._parent !== this._currentTarget && type._parent !== y) {
while (type !== this.currentTarget && type !== y) {
let parent = type._parent
if (type._parentSub !== null) {
path.push(type._parentSub)
path.unshift(type._parentSub)
} else {
// parent is array-ish
for (let [i, child] of parent) {
if (child === type) {
path.push(i)
path.unshift(i)
break
}
}

View File

@@ -15,6 +15,7 @@ import YMap from './Type/YMap.js'
import YText from './Type/YText.js'
import { YXmlFragment, YXmlElement, YXmlText } from './Type/y-xml/y-xml.js'
import BinaryDecoder from './Binary/Decoder.js'
import { getRelativePosition, fromRelativePosition } from './Util/relativePosition.js'
import debug from 'debug'
import Transaction from './Transaction.js'
@@ -44,8 +45,8 @@ export default class Y extends NamedEventHandler {
transact (f, remote = false) {
let initialCall = this._transaction === null
if (initialCall) {
this.emit('beforeTransaction', this, remote)
this._transaction = new Transaction(this)
this.emit('beforeTransaction', this, this._transaction, remote)
}
try {
f(this)
@@ -53,13 +54,15 @@ export default class Y extends NamedEventHandler {
console.error(e)
}
if (initialCall) {
const transaction = this._transaction
this._transaction = null
// emit change events on changed types
this._transaction.changedTypes.forEach(function (subs, type) {
transaction.changedTypes.forEach(function (subs, type) {
if (!type._deleted) {
type._callObserver(subs, remote)
type._callObserver(transaction, subs, remote)
}
})
this._transaction.changedParentTypes.forEach(function (events, type) {
transaction.changedParentTypes.forEach(function (events, type) {
if (!type._deleted) {
events = events
.filter(event =>
@@ -71,12 +74,11 @@ export default class Y extends NamedEventHandler {
})
// we don't have to check for events.length
// because there is no way events is empty..
type._deepEventHandler.callEventListeners(events)
type._deepEventHandler.callEventListeners(transaction, events)
}
})
// when all changes & events are processed, emit afterTransaction event
this.emit('afterTransaction', this, remote)
this._transaction = null
this.emit('afterTransaction', this, transaction, remote)
}
}
// fake _start for root properties (y.set('name', type))
@@ -168,7 +170,9 @@ Y.XmlText = YXmlText
Y.utils = {
BinaryDecoder,
UndoManager
UndoManager,
getRelativePosition,
fromRelativePosition
}
Y.debug = debug

View File

@@ -41,6 +41,8 @@ test('basic map tests', async function map0 (t) {
test('Basic get&set of Map property (converge via sync)', async function map1 (t) {
let { users, map0 } = await initArrays(t, { users: 2 })
map0.set('stuff', 'stuffy')
map0.set('undefined', undefined)
map0.set('null', null)
t.compare(map0.get('stuff'), 'stuffy')
await flushAll(t, users)
@@ -48,6 +50,8 @@ test('Basic get&set of Map property (converge via sync)', async function map1 (t
for (let user of users) {
var u = user.get('map', Y.Map)
t.compare(u.get('stuff'), 'stuffy')
t.assert(u.get('undefined') === undefined, 'undefined')
t.compare(u.get('null'), null, 'null')
}
await compareUsers(t, users)
})
@@ -172,31 +176,36 @@ test('observePath properties', async function map10 (t) {
})
*/
/* TODO: reimplement observeDeep
test('observe deep properties', async function map11 (t) {
let { users, map1, map2, map3 } = await initArrays(t, { users: 4 })
var _map1 = map1.set('map', new Y.Map())
var calls = 0
var dmapid
_map1.observe(function (event) {
calls++
t.compare(event.name, 'deepmap')
dmapid = event.target.opContents.deepmap
map1.observeDeep(function (events) {
events.forEach(event => {
calls++
t.assert(event.keysChanged.has('deepmap'))
t.assert(event.path.length === 1)
t.assert(event.path[0] === 'map')
dmapid = event.target.get('deepmap')._id
})
})
await flushAll(t, users)
await flushAll(t, users)
var _map3 = map3.get('map')
_map3.set('deepmap', new Y.Map())
await flushAll(t, users)
var _map2 = map2.get('map')
_map2.set('deepmap', new Y.Map())
await flushAll(t, users)
await flushAll(t, users)
var dmap1 = _map1.get('deepmap')
var dmap2 = _map2.get('deepmap')
var dmap3 = _map3.get('deepmap')
t.assert(calls > 0)
t.compare(dmap1._model, dmap2._model)
t.compare(dmap1._model, dmap3._model)
t.compare(dmap1._model, dmapid)
t.assert(dmap1._id.equals(dmap2._id))
t.assert(dmap1._id.equals(dmap3._id))
t.assert(dmap1._id.equals(dmapid))
await compareUsers(t, users)
})
@@ -204,8 +213,10 @@ test('observes using observeDeep', async function map12 (t) {
let { users, map0 } = await initArrays(t, { users: 2 })
var pathes = []
var calls = 0
map0.observeDeep(function (event) {
pathes.push(event.path)
map0.observeDeep(function (events) {
events.forEach(event => {
pathes.push(event.path)
})
calls++
})
map0.set('map', new Y.Map())
@@ -215,7 +226,6 @@ test('observes using observeDeep', async function map12 (t) {
t.compare(pathes, [[], ['map'], ['map', 'array']])
await compareUsers(t, users)
})
*/
/* TODO: Test events in Y.Map
function compareEvent (t, is, should) {

View File

@@ -153,7 +153,7 @@ export async function initArrays (t, opts) {
result['array' + i] = y.define('array', Y.Array)
result['map' + i] = y.define('map', Y.Map)
result['xml' + i] = y.define('xml', Y.XmlElement)
y.get('xml', Y.Xml).setDomFilter(function (d, attrs) {
y.get('xml').setDomFilter(function (d, attrs) {
if (d.nodeName === 'HIDDEN') {
return null
} else {
@@ -187,7 +187,7 @@ export async function flushAll (t, users) {
if (users.length === 0) {
return
}
await wait(0)
await wait(10)
if (users[0].connector.testRoom != null) {
// use flushAll method specified in Test Connector
await users[0].connector.testRoom.flushAll(users)

8
y.js

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

396
y.node.js
View File

@@ -1,7 +1,7 @@
/**
* yjs - A framework for real-time p2p shared editing on any data
* @version v13.0.0-26
* @version v13.0.0-32
* @license MIT
*/
@@ -687,7 +687,6 @@ if (!String.fromCodePoint) {
/*! http://mths.be/codepointat v0.2.0 by @mathias */
if (!String.prototype.codePointAt) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
@@ -1900,7 +1899,7 @@ class EventHandler {
removeAllEventListeners () {
this.eventListeners = [];
}
callEventListeners (event) {
callEventListeners (transaction, event) {
for (var i = 0; i < this.eventListeners.length; i++) {
try {
const f = this.eventListeners[i];
@@ -1967,9 +1966,9 @@ class Type extends Item {
}
return path
}
_callEventHandler (event) {
const changedParentTypes = this._y._transaction.changedParentTypes;
this._eventHandler.callEventListeners(event);
_callEventHandler (transaction, event) {
const changedParentTypes = transaction.changedParentTypes;
this._eventHandler.callEventListeners(transaction, event);
let type = this;
while (type !== this._y) {
let events = changedParentTypes.get(type);
@@ -2092,7 +2091,13 @@ class ItemJSON extends Item {
this._content = new Array(len);
for (let i = 0; i < len; i++) {
const ctnt = decoder.readVarString();
this._content[i] = JSON.parse(ctnt);
let parsed;
if (ctnt === 'undefined') {
parsed = undefined;
} else {
parsed = JSON.parse(ctnt);
}
this._content[i] = parsed;
}
return missing
}
@@ -2101,7 +2106,14 @@ class ItemJSON extends Item {
let len = this._content.length;
encoder.writeVarUint(len);
for (let i = 0; i < len; i++) {
encoder.writeVarString(JSON.stringify(this._content[i]));
let encoded;
let content = this._content[i];
if (content === undefined) {
encoded = 'undefined';
} else {
encoded = JSON.stringify(content);
}
encoder.writeVarString(encoded);
}
}
_logString () {
@@ -2122,6 +2134,47 @@ class ItemJSON extends Item {
}
}
class ItemString extends Item {
constructor () {
super();
this._content = null;
}
_copy () {
let struct = super._copy();
struct._content = this._content;
return struct
}
get _length () {
return this._content.length
}
_fromBinary (y, decoder) {
let missing = super._fromBinary(y, decoder);
this._content = decoder.readVarString();
return missing
}
_toBinary (encoder) {
super._toBinary(encoder);
encoder.writeVarString(this._content);
}
_logString () {
const left = this._left !== null ? this._left._lastId : null;
const origin = this._origin !== null ? this._origin._lastId : null;
return `ItemJSON(id:${logID(this._id)},content:${JSON.stringify(this._content)},left:${logID(left)},origin:${logID(origin)},right:${logID(this._right)},parent:${logID(this._parent)},parentSub:${this._parentSub})`
}
_splitAt (y, diff) {
if (diff === 0) {
return this
} else if (diff >= this._length) {
return this._right
}
let item = new ItemString();
item._content = this._content.slice(diff);
this._content = this._content.slice(0, diff);
splitHelper(y, this, item, diff);
return item
}
}
class YEvent {
constructor (target) {
this.target = target;
@@ -2131,15 +2184,15 @@ class YEvent {
const path = [];
let type = this.target;
const y = type._y;
while (type._parent !== this._currentTarget && type._parent !== y) {
while (type !== this.currentTarget && type !== y) {
let parent = type._parent;
if (type._parentSub !== null) {
path.push(type._parentSub);
path.unshift(type._parentSub);
} else {
// parent is array-ish
for (let [i, child] of parent) {
if (child === type) {
path.push(i);
path.unshift(i);
break
}
}
@@ -2158,15 +2211,19 @@ class YArrayEvent extends YEvent {
}
class YArray extends Type {
_callObserver (parentSubs, remote) {
this._callEventHandler(new YArrayEvent(this, remote));
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YArrayEvent(this, remote));
}
get (pos) {
let n = this._start;
while (n !== null) {
if (!n._deleted) {
if (pos < n._length) {
return n._content[n._length - pos]
if (n.constructor === ItemJSON || n.constructor === ItemString) {
return n._content[pos]
} else {
return n
}
}
pos -= n._length;
}
@@ -2372,8 +2429,8 @@ class YMapEvent extends YEvent {
}
class YMap extends Type {
_callObserver (parentSubs, remote) {
this._callEventHandler(new YMapEvent(this, parentSubs, remote));
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YMapEvent(this, parentSubs, remote));
}
toJSON () {
const map = {};
@@ -2472,47 +2529,6 @@ class YMap extends Type {
}
}
class ItemString extends Item {
constructor () {
super();
this._content = null;
}
_copy () {
let struct = super._copy();
struct._content = this._content;
return struct
}
get _length () {
return this._content.length
}
_fromBinary (y, decoder) {
let missing = super._fromBinary(y, decoder);
this._content = decoder.readVarString();
return missing
}
_toBinary (encoder) {
super._toBinary(encoder);
encoder.writeVarString(this._content);
}
_logString () {
const left = this._left !== null ? this._left._lastId : null;
const origin = this._origin !== null ? this._origin._lastId : null;
return `ItemJSON(id:${logID(this._id)},content:${JSON.stringify(this._content)},left:${logID(left)},origin:${logID(origin)},right:${logID(this._right)},parent:${logID(this._parent)},parentSub:${this._parentSub})`
}
_splitAt (y, diff) {
if (diff === 0) {
return this
} else if (diff >= this._length) {
return this._right
}
let item = new ItemString();
item._content = this._content.slice(diff);
this._content = this._content.slice(0, diff);
splitHelper(y, this, item, diff);
return item
}
}
class YText extends YArray {
constructor (string) {
super();
@@ -2760,7 +2776,33 @@ function applyChangesFromDom (dom) {
}
}
function reflectChangesOnDom (events) {
function reflectChangesOnDom (events, _document) {
// Make sure that no filtered attributes are applied to the structure
// if they were, delete them
/*
events.forEach(event => {
const target = event.target
if (event.attributesChanged === undefined) {
// event.target is Y.XmlText
return
}
const keys = this._domFilter(target.nodeName, Array.from(event.attributesChanged))
if (keys === null) {
target._delete()
} else {
const removeKeys = new Set() // is a copy of event.attributesChanged
event.attributesChanged.forEach(key => { removeKeys.add(key) })
keys.forEach(key => {
// remove all accepted keys from removeKeys
removeKeys.delete(key)
})
// remove the filtered attribute
removeKeys.forEach(key => {
target.removeAttribute(key)
})
}
})
*/
this._mutualExclude(() => {
events.forEach(event => {
const yxml = event.target;
@@ -2782,9 +2824,9 @@ function reflectChangesOnDom (events) {
});
if (event.childListChanged) {
// create fragment of undeleted nodes
const fragment = document.createDocumentFragment();
const fragment = _document.createDocumentFragment();
yxml.forEach(function (t) {
fragment.append(t.getDom());
fragment.appendChild(t.getDom(_document));
});
// remove remainding nodes
let lastChild = dom.lastChild;
@@ -2793,7 +2835,7 @@ function reflectChangesOnDom (events) {
lastChild = dom.lastChild;
}
// insert fragment of undeleted nodes
dom.append(fragment);
dom.appendChild(fragment);
}
}
/* TODO: smartscrolling
@@ -2914,7 +2956,7 @@ let relativeSelection = null;
let beforeTransactionSelectionFixer;
if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, remote) {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, transaction, remote) {
if (!remote) {
return
}
@@ -2937,7 +2979,7 @@ if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _fakeBeforeTransactionSelectionFixer () {};
}
function afterTransactionSelectionFixer (y, remote) {
function afterTransactionSelectionFixer (y, transaction, remote) {
if (relativeSelection === null || !remote) {
return
}
@@ -3736,7 +3778,7 @@ function merge_tuples (diffs, start, length) {
/* global MutationObserver */
function domToYXml (parent, doms) {
function domToYXml (parent, doms, _document) {
const types = [];
doms.forEach(d => {
if (d._yxml != null && d._yxml !== false) {
@@ -3747,7 +3789,7 @@ function domToYXml (parent, doms) {
if (d.nodeType === d.TEXT_NODE) {
type = new YXmlText(d);
} else if (d.nodeType === d.ELEMENT_NODE) {
type = new YXmlFragment._YXmlElement(d, parent._domFilter);
type = new YXmlFragment._YXmlElement(d, parent._domFilter, _document);
} else {
throw new Error('Unsupported node!')
}
@@ -3825,7 +3867,9 @@ class YXmlFragment extends YArray {
} catch (e) {
console.error(e);
}
this._domObserver.takeRecords();
if (this._domObserver !== null) {
this._domObserver.takeRecords();
}
token = true;
}
};
@@ -3869,8 +3913,8 @@ class YXmlFragment extends YArray {
xml.setDomFilter(f);
});
}
_callObserver (parentSubs, remote) {
this._callEventHandler(new YXmlEvent(this, parentSubs, remote));
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YXmlEvent(this, parentSubs, remote));
}
toString () {
return this.map(xml => xml.toString()).join('')
@@ -3889,113 +3933,116 @@ class YXmlFragment extends YArray {
this._dom = null;
}
}
insertDomElementsAfter (prev, doms) {
const types = domToYXml(this, doms);
insertDomElementsAfter (prev, doms, _document) {
const types = domToYXml(this, doms, _document);
this.insertAfter(prev, types);
return types
}
insertDomElements (pos, doms) {
const types = domToYXml(this, doms);
insertDomElements (pos, doms, _document) {
const types = domToYXml(this, doms, _document);
this.insert(pos, types);
return types
}
getDom () {
return this._dom
}
bindToDom (dom) {
bindToDom (dom, _document) {
if (this._dom != null) {
this._unbindFromDom();
}
if (dom._yxml != null) {
dom._yxml._unbindFromDom();
}
if (MutationObserver == null) {
throw new Error('Not able to bind to a DOM element, because MutationObserver is not available!')
}
dom.innerHTML = '';
this._dom = dom;
dom._yxml = this;
this.forEach(t => {
dom.insertBefore(t.getDom(), null);
dom.insertBefore(t.getDom(_document), null);
});
this._bindToDom(dom);
this._bindToDom(dom, _document);
}
// binds to a dom element
// Only call if dom and YXml are isomorph
_bindToDom (dom) {
if (this._parent === null || this._parent._dom != null || typeof MutationObserver === 'undefined') {
// only bind if parent did not already bind
_bindToDom (dom, _document) {
_document = _document || document;
this._dom = dom;
dom._yxml = this;
// TODO: refine this..
if ((this.constructor !== YXmlFragment && this._parent !== this._y) || this._parent === null) {
// TODO: only top level YXmlFragment can bind. Also allow YXmlElements..
return
}
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords());
});
this._y.on('beforeTransaction', beforeTransactionSelectionFixer);
this._y.on('afterTransaction', afterTransactionSelectionFixer);
// Apply Y.Xml events to dom
this.observeDeep(reflectChangesOnDom.bind(this));
this.observeDeep(events => {
reflectChangesOnDom.call(this, events, _document);
});
// Apply Dom changes on Y.Xml
this._domObserverListener = mutations => {
this._mutualExclude(() => {
this._y.transact(() => {
let diffChildren = new Set();
mutations.forEach(mutation => {
const dom = mutation.target;
const yxml = dom._yxml;
if (yxml == null) {
// dom element is filtered
return
}
switch (mutation.type) {
case 'characterData':
var diffs = diff_1(yxml.toString(), dom.nodeValue);
var pos = 0;
for (var i = 0; i < diffs.length; i++) {
var d = diffs[i];
if (d[0] === 0) { // EQUAL
pos += d[1].length;
} else if (d[0] === -1) { // DELETE
yxml.delete(pos, d[1].length);
} else { // INSERT
yxml.insert(pos, d[1]);
pos += d[1].length;
}
}
break
case 'attributes':
let name = mutation.attributeName;
// check if filter accepts attribute
if (this._domFilter(dom, [name]).length > 0 && this.constructor !== YXmlFragment) {
var val = dom.getAttribute(name);
if (yxml.getAttribute(name) !== val) {
if (val == null) {
yxml.removeAttribute(name);
} else {
yxml.setAttribute(name, val);
if (typeof MutationObserver !== 'undefined') {
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords());
});
this._domObserverListener = mutations => {
this._mutualExclude(() => {
this._y.transact(() => {
let diffChildren = new Set();
mutations.forEach(mutation => {
const dom = mutation.target;
const yxml = dom._yxml;
if (yxml == null) {
// dom element is filtered
return
}
switch (mutation.type) {
case 'characterData':
var diffs = diff_1(yxml.toString(), dom.nodeValue);
var pos = 0;
for (var i = 0; i < diffs.length; i++) {
var d = diffs[i];
if (d[0] === 0) { // EQUAL
pos += d[1].length;
} else if (d[0] === -1) { // DELETE
yxml.delete(pos, d[1].length);
} else { // INSERT
yxml.insert(pos, d[1]);
pos += d[1].length;
}
}
}
break
case 'childList':
diffChildren.add(mutation.target);
break
break
case 'attributes':
let name = mutation.attributeName;
// check if filter accepts attribute
if (this._domFilter(dom, [name]).length > 0 && yxml.constructor !== YXmlFragment) {
var val = dom.getAttribute(name);
if (yxml.getAttribute(name) !== val) {
if (val == null) {
yxml.removeAttribute(name);
} else {
yxml.setAttribute(name, val);
}
}
}
break
case 'childList':
diffChildren.add(mutation.target);
break
}
});
for (let dom of diffChildren) {
if (dom._yxml != null && dom._yxml !== false) {
applyChangesFromDom(dom);
}
}
});
for (let dom of diffChildren) {
if (dom._yxml != null) {
applyChangesFromDom(dom);
}
}
});
};
this._domObserver = new MutationObserver(this._domObserverListener);
this._domObserver.observe(dom, {
childList: true,
attributes: true,
characterData: true,
subtree: true
});
};
this._domObserver = new MutationObserver(this._domObserverListener);
this._domObserver.observe(dom, {
childList: true,
attributes: true,
characterData: true,
subtree: true
});
}
return dom
}
_logString () {
@@ -4007,7 +4054,7 @@ class YXmlFragment extends YArray {
// import diff from 'fast-diff'
class YXmlElement extends YXmlFragment {
constructor (arg1, arg2) {
constructor (arg1, arg2, _document) {
super();
this.nodeName = null;
this._scrollElement = null;
@@ -4015,7 +4062,7 @@ class YXmlElement extends YXmlFragment {
this.nodeName = arg1.toUpperCase();
} else if (arg1 != null && arg1.nodeType != null && arg1.nodeType === arg1.ELEMENT_NODE) {
this.nodeName = arg1.nodeName;
this._setDom(arg1);
this._setDom(arg1, _document);
} else {
this.nodeName = 'UNDEFINED';
}
@@ -4028,14 +4075,12 @@ class YXmlElement extends YXmlFragment {
struct.nodeName = this.nodeName;
return struct
}
_setDom (dom) {
_setDom (dom, _document) {
if (this._dom != null) {
throw new Error('Only call this method if you know what you are doing ;)')
} else if (dom._yxml != null) { // TODO do i need to check this? - no.. but for dev purps..
throw new Error('Already bound to an YXml type')
} else {
this._dom = dom;
dom._yxml = this;
// tag is already set in constructor
// set attributes
let attrNames = [];
@@ -4048,8 +4093,8 @@ class YXmlElement extends YXmlFragment {
let attrValue = dom.getAttribute(attrName);
this.setAttribute(attrName, attrValue);
}
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes));
this._bindToDom(dom);
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes), _document);
this._bindToDom(dom, _document);
return dom
}
}
@@ -4117,7 +4162,6 @@ class YXmlElement extends YXmlFragment {
let dom = this._dom;
if (dom == null) {
dom = _document.createElement(this.nodeName);
this._dom = dom;
dom._yxml = this;
let attrs = this.getAttributes();
for (let key in attrs) {
@@ -4126,7 +4170,7 @@ class YXmlElement extends YXmlFragment {
this.forEach(yxml => {
dom.appendChild(yxml.getDom(_document));
});
this._bindToDom(dom);
this._bindToDom(dom, _document);
}
return dom
}
@@ -4367,16 +4411,16 @@ class NamedEventHandler {
}
class ReverseOperation {
constructor (y) {
constructor (y, transaction) {
this.created = new Date();
const beforeState = y._transaction.beforeState;
const beforeState = transaction.beforeState;
this.toState = new ID(y.userID, y.ss.getState(y.userID) - 1);
if (beforeState.has(y.userID)) {
this.fromState = new ID(y.userID, beforeState.get(y.userID));
} else {
this.fromState = this.toState;
}
this.deletedStructs = y._transaction.deletedStructs;
this.deletedStructs = transaction.deletedStructs;
}
}
@@ -4436,13 +4480,12 @@ class UndoManager {
this._redoing = false;
const y = scope._y;
this.y = y;
y.on('afterTransaction', (y, remote) => {
if (!remote && y._transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y);
y.on('afterTransaction', (y, transaction, remote) => {
if (!remote && transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y, transaction);
if (!this._undoing) {
let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null;
if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) {
console.log('appending', lastUndoOp, reverseOperation);
lastUndoOp.created = reverseOperation.created;
lastUndoOp.toState = reverseOperation.toState;
reverseOperation.deletedStructs.forEach(lastUndoOp.deletedStructs.add, lastUndoOp.deletedStructs);
@@ -4459,7 +4502,6 @@ class UndoManager {
});
}
undo () {
console.log('undoing');
this._undoing = true;
const performedUndo = applyReverseOperation(this.y, this._scope, this._undoBuffer);
this._undoing = false;
@@ -4830,6 +4872,15 @@ function coerce(val) {
}
});
var debug_1 = debug$1.coerce;
var debug_2 = debug$1.disable;
var debug_3 = debug$1.enable;
var debug_4 = debug$1.enabled;
var debug_5 = debug$1.humanize;
var debug_6 = debug$1.names;
var debug_7 = debug$1.skips;
var debug_8 = debug$1.formatters;
var browser = createCommonjsModule(function (module, exports) {
/**
* This is the web browser implementation of `debug()`.
@@ -5018,6 +5069,14 @@ function localstorage() {
}
});
var browser_1 = browser.log;
var browser_2 = browser.formatArgs;
var browser_3 = browser.save;
var browser_4 = browser.load;
var browser_5 = browser.useColors;
var browser_6 = browser.storage;
var browser_7 = browser.colors;
class AbstractConnector {
constructor (y, opts) {
this.y = y;
@@ -5379,8 +5438,8 @@ class Y$1 extends NamedEventHandler {
transact (f, remote = false) {
let initialCall = this._transaction === null;
if (initialCall) {
this.emit('beforeTransaction', this, remote);
this._transaction = new Transaction(this);
this.emit('beforeTransaction', this, this._transaction, remote);
}
try {
f(this);
@@ -5388,13 +5447,15 @@ class Y$1 extends NamedEventHandler {
console.error(e);
}
if (initialCall) {
const transaction = this._transaction;
this._transaction = null;
// emit change events on changed types
this._transaction.changedTypes.forEach(function (subs, type) {
transaction.changedTypes.forEach(function (subs, type) {
if (!type._deleted) {
type._callObserver(subs, remote);
type._callObserver(transaction, subs, remote);
}
});
this._transaction.changedParentTypes.forEach(function (events, type) {
transaction.changedParentTypes.forEach(function (events, type) {
if (!type._deleted) {
events = events
.filter(event =>
@@ -5406,12 +5467,11 @@ class Y$1 extends NamedEventHandler {
});
// we don't have to check for events.length
// because there is no way events is empty..
type._deepEventHandler.callEventListeners(events);
type._deepEventHandler.callEventListeners(transaction, events);
}
});
// when all changes & events are processed, emit afterTransaction event
this.emit('afterTransaction', this, remote);
this._transaction = null;
this.emit('afterTransaction', this, transaction, remote);
}
}
// fake _start for root properties (y.set('name', type))
@@ -5503,7 +5563,9 @@ Y$1.XmlText = YXmlText;
Y$1.utils = {
BinaryDecoder,
UndoManager
UndoManager,
getRelativePosition,
fromRelativePosition
};
Y$1.debug = browser;

File diff suppressed because one or more lines are too long

603
y.test.js
View File

@@ -1,8 +1,8 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global['y-tests'] = global['y-tests'] || {})));
}(this, (function (exports) { 'use strict';
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(factory) :
(factory());
}(this, (function () { 'use strict';
class N {
// A created node is always red!
@@ -684,7 +684,6 @@ if (!String.fromCodePoint) {
/*! http://mths.be/codepointat v0.2.0 by @mathias */
if (!String.prototype.codePointAt) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
@@ -1886,7 +1885,7 @@ class EventHandler {
removeAllEventListeners () {
this.eventListeners = [];
}
callEventListeners (event) {
callEventListeners (transaction, event) {
for (var i = 0; i < this.eventListeners.length; i++) {
try {
const f = this.eventListeners[i];
@@ -1926,9 +1925,35 @@ class Type extends Item {
this._eventHandler = new EventHandler();
this._deepEventHandler = new EventHandler();
}
_callEventHandler (event) {
const changedParentTypes = this._y._transaction.changedParentTypes;
this._eventHandler.callEventListeners(event);
getPathTo (type) {
if (type === this) {
return []
}
const path = [];
const y = this._y;
while (type._parent !== this && this._parent !== y) {
let parent = type._parent;
if (type._parentSub !== null) {
path.push(type._parentSub);
} else {
// parent is array-ish
for (let [i, child] of parent) {
if (child === type) {
path.push(i);
break
}
}
}
type = parent;
}
if (this._parent !== this) {
throw new Error('The type is not a child of this node')
}
return path
}
_callEventHandler (transaction, event) {
const changedParentTypes = transaction.changedParentTypes;
this._eventHandler.callEventListeners(transaction, event);
let type = this;
while (type !== this._y) {
let events = changedParentTypes.get(type);
@@ -2051,7 +2076,13 @@ class ItemJSON extends Item {
this._content = new Array(len);
for (let i = 0; i < len; i++) {
const ctnt = decoder.readVarString();
this._content[i] = JSON.parse(ctnt);
let parsed;
if (ctnt === 'undefined') {
parsed = undefined;
} else {
parsed = JSON.parse(ctnt);
}
this._content[i] = parsed;
}
return missing
}
@@ -2060,7 +2091,14 @@ class ItemJSON extends Item {
let len = this._content.length;
encoder.writeVarUint(len);
for (let i = 0; i < len; i++) {
encoder.writeVarString(JSON.stringify(this._content[i]));
let encoded;
let content = this._content[i];
if (content === undefined) {
encoded = 'undefined';
} else {
encoded = JSON.stringify(content);
}
encoder.writeVarString(encoded);
}
}
_logString () {
@@ -2081,36 +2119,72 @@ class ItemJSON extends Item {
}
}
class ItemString extends Item {
constructor () {
super();
this._content = null;
}
_copy () {
let struct = super._copy();
struct._content = this._content;
return struct
}
get _length () {
return this._content.length
}
_fromBinary (y, decoder) {
let missing = super._fromBinary(y, decoder);
this._content = decoder.readVarString();
return missing
}
_toBinary (encoder) {
super._toBinary(encoder);
encoder.writeVarString(this._content);
}
_logString () {
const left = this._left !== null ? this._left._lastId : null;
const origin = this._origin !== null ? this._origin._lastId : null;
return `ItemJSON(id:${logID(this._id)},content:${JSON.stringify(this._content)},left:${logID(left)},origin:${logID(origin)},right:${logID(this._right)},parent:${logID(this._parent)},parentSub:${this._parentSub})`
}
_splitAt (y, diff) {
if (diff === 0) {
return this
} else if (diff >= this._length) {
return this._right
}
let item = new ItemString();
item._content = this._content.slice(diff);
this._content = this._content.slice(0, diff);
splitHelper(y, this, item, diff);
return item
}
}
class YEvent {
constructor (target) {
this.target = target;
this._path = null;
this.currentTarget = target;
}
get path () {
if (this._path !== null) {
return this._path
} else {
const path = [];
let type = this.target;
const y = type._y;
while (type._parent !== y) {
let parent = type._parent;
if (type._parentSub !== null) {
path.push(type._parentSub);
} else {
// parent is array-ish
for (let [i, child] of parent) {
if (child === type) {
path.push(i);
break
}
const path = [];
let type = this.target;
const y = type._y;
while (type !== this.currentTarget && type !== y) {
let parent = type._parent;
if (type._parentSub !== null) {
path.unshift(type._parentSub);
} else {
// parent is array-ish
for (let [i, child] of parent) {
if (child === type) {
path.unshift(i);
break
}
}
type = parent;
}
this._path = path;
return path
type = parent;
}
return path
}
}
@@ -2122,15 +2196,19 @@ class YArrayEvent extends YEvent {
}
class YArray extends Type {
_callObserver (parentSubs, remote) {
this._callEventHandler(new YArrayEvent(this, remote));
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YArrayEvent(this, remote));
}
get (pos) {
let n = this._start;
while (n !== null) {
if (!n._deleted) {
if (pos < n._length) {
return n._content[n._length - pos]
if (n.constructor === ItemJSON || n.constructor === ItemString) {
return n._content[pos]
} else {
return n
}
}
pos -= n._length;
}
@@ -2336,8 +2414,8 @@ class YMapEvent extends YEvent {
}
class YMap extends Type {
_callObserver (parentSubs, remote) {
this._callEventHandler(new YMapEvent(this, parentSubs, remote));
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YMapEvent(this, parentSubs, remote));
}
toJSON () {
const map = {};
@@ -2436,47 +2514,6 @@ class YMap extends Type {
}
}
class ItemString extends Item {
constructor () {
super();
this._content = null;
}
_copy () {
let struct = super._copy();
struct._content = this._content;
return struct
}
get _length () {
return this._content.length
}
_fromBinary (y, decoder) {
let missing = super._fromBinary(y, decoder);
this._content = decoder.readVarString();
return missing
}
_toBinary (encoder) {
super._toBinary(encoder);
encoder.writeVarString(this._content);
}
_logString () {
const left = this._left !== null ? this._left._lastId : null;
const origin = this._origin !== null ? this._origin._lastId : null;
return `ItemJSON(id:${logID(this._id)},content:${JSON.stringify(this._content)},left:${logID(left)},origin:${logID(origin)},right:${logID(this._right)},parent:${logID(this._parent)},parentSub:${this._parentSub})`
}
_splitAt (y, diff) {
if (diff === 0) {
return this
} else if (diff >= this._length) {
return this._right
}
let item = new ItemString();
item._content = this._content.slice(diff);
this._content = this._content.slice(0, diff);
splitHelper(y, this, item, diff);
return item
}
}
class YText extends YArray {
constructor (string) {
super();
@@ -2724,7 +2761,33 @@ function applyChangesFromDom (dom) {
}
}
function reflectChangesOnDom (events) {
function reflectChangesOnDom (events, _document) {
// Make sure that no filtered attributes are applied to the structure
// if they were, delete them
/*
events.forEach(event => {
const target = event.target
if (event.attributesChanged === undefined) {
// event.target is Y.XmlText
return
}
const keys = this._domFilter(target.nodeName, Array.from(event.attributesChanged))
if (keys === null) {
target._delete()
} else {
const removeKeys = new Set() // is a copy of event.attributesChanged
event.attributesChanged.forEach(key => { removeKeys.add(key) })
keys.forEach(key => {
// remove all accepted keys from removeKeys
removeKeys.delete(key)
})
// remove the filtered attribute
removeKeys.forEach(key => {
target.removeAttribute(key)
})
}
})
*/
this._mutualExclude(() => {
events.forEach(event => {
const yxml = event.target;
@@ -2746,9 +2809,9 @@ function reflectChangesOnDom (events) {
});
if (event.childListChanged) {
// create fragment of undeleted nodes
const fragment = document.createDocumentFragment();
const fragment = _document.createDocumentFragment();
yxml.forEach(function (t) {
fragment.append(t.getDom());
fragment.appendChild(t.getDom(_document));
});
// remove remainding nodes
let lastChild = dom.lastChild;
@@ -2757,7 +2820,7 @@ function reflectChangesOnDom (events) {
lastChild = dom.lastChild;
}
// insert fragment of undeleted nodes
dom.append(fragment);
dom.appendChild(fragment);
}
}
/* TODO: smartscrolling
@@ -2878,7 +2941,7 @@ let relativeSelection = null;
let beforeTransactionSelectionFixer;
if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, remote) {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, transaction, remote) {
if (!remote) {
return
}
@@ -2901,7 +2964,7 @@ if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _fakeBeforeTransactionSelectionFixer () {};
}
function afterTransactionSelectionFixer (y, remote) {
function afterTransactionSelectionFixer (y, transaction, remote) {
if (relativeSelection === null || !remote) {
return
}
@@ -3700,7 +3763,7 @@ function merge_tuples (diffs, start, length) {
/* global MutationObserver */
function domToYXml (parent, doms) {
function domToYXml (parent, doms, _document) {
const types = [];
doms.forEach(d => {
if (d._yxml != null && d._yxml !== false) {
@@ -3711,7 +3774,7 @@ function domToYXml (parent, doms) {
if (d.nodeType === d.TEXT_NODE) {
type = new YXmlText(d);
} else if (d.nodeType === d.ELEMENT_NODE) {
type = new YXmlFragment._YXmlElement(d, parent._domFilter);
type = new YXmlFragment._YXmlElement(d, parent._domFilter, _document);
} else {
throw new Error('Unsupported node!')
}
@@ -3789,7 +3852,9 @@ class YXmlFragment extends YArray {
} catch (e) {
console.error(e);
}
this._domObserver.takeRecords();
if (this._domObserver !== null) {
this._domObserver.takeRecords();
}
token = true;
}
};
@@ -3833,8 +3898,8 @@ class YXmlFragment extends YArray {
xml.setDomFilter(f);
});
}
_callObserver (parentSubs, remote) {
this._callEventHandler(new YXmlEvent(this, parentSubs, remote));
_callObserver (transaction, parentSubs, remote) {
this._callEventHandler(transaction, new YXmlEvent(this, parentSubs, remote));
}
toString () {
return this.map(xml => xml.toString()).join('')
@@ -3853,113 +3918,116 @@ class YXmlFragment extends YArray {
this._dom = null;
}
}
insertDomElementsAfter (prev, doms) {
const types = domToYXml(this, doms);
insertDomElementsAfter (prev, doms, _document) {
const types = domToYXml(this, doms, _document);
this.insertAfter(prev, types);
return types
}
insertDomElements (pos, doms) {
const types = domToYXml(this, doms);
insertDomElements (pos, doms, _document) {
const types = domToYXml(this, doms, _document);
this.insert(pos, types);
return types
}
getDom () {
return this._dom
}
bindToDom (dom) {
bindToDom (dom, _document) {
if (this._dom != null) {
this._unbindFromDom();
}
if (dom._yxml != null) {
dom._yxml._unbindFromDom();
}
if (MutationObserver == null) {
throw new Error('Not able to bind to a DOM element, because MutationObserver is not available!')
}
dom.innerHTML = '';
this._dom = dom;
dom._yxml = this;
this.forEach(t => {
dom.insertBefore(t.getDom(), null);
dom.insertBefore(t.getDom(_document), null);
});
this._bindToDom(dom);
this._bindToDom(dom, _document);
}
// binds to a dom element
// Only call if dom and YXml are isomorph
_bindToDom (dom) {
if (this._parent === null || this._parent._dom != null || typeof MutationObserver === 'undefined') {
// only bind if parent did not already bind
_bindToDom (dom, _document) {
_document = _document || document;
this._dom = dom;
dom._yxml = this;
// TODO: refine this..
if ((this.constructor !== YXmlFragment && this._parent !== this._y) || this._parent === null) {
// TODO: only top level YXmlFragment can bind. Also allow YXmlElements..
return
}
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords());
});
this._y.on('beforeTransaction', beforeTransactionSelectionFixer);
this._y.on('afterTransaction', afterTransactionSelectionFixer);
// Apply Y.Xml events to dom
this.observeDeep(reflectChangesOnDom.bind(this));
this.observeDeep(events => {
reflectChangesOnDom.call(this, events, _document);
});
// Apply Dom changes on Y.Xml
this._domObserverListener = mutations => {
this._mutualExclude(() => {
this._y.transact(() => {
let diffChildren = new Set();
mutations.forEach(mutation => {
const dom = mutation.target;
const yxml = dom._yxml;
if (yxml == null) {
// dom element is filtered
return
}
switch (mutation.type) {
case 'characterData':
var diffs = diff_1(yxml.toString(), dom.nodeValue);
var pos = 0;
for (var i = 0; i < diffs.length; i++) {
var d = diffs[i];
if (d[0] === 0) { // EQUAL
pos += d[1].length;
} else if (d[0] === -1) { // DELETE
yxml.delete(pos, d[1].length);
} else { // INSERT
yxml.insert(pos, d[1]);
pos += d[1].length;
}
}
break
case 'attributes':
let name = mutation.attributeName;
// check if filter accepts attribute
if (this._domFilter(dom, [name]).length > 0 && this.constructor !== YXmlFragment) {
var val = dom.getAttribute(name);
if (yxml.getAttribute(name) !== val) {
if (val == null) {
yxml.removeAttribute(name);
} else {
yxml.setAttribute(name, val);
if (typeof MutationObserver !== 'undefined') {
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords());
});
this._domObserverListener = mutations => {
this._mutualExclude(() => {
this._y.transact(() => {
let diffChildren = new Set();
mutations.forEach(mutation => {
const dom = mutation.target;
const yxml = dom._yxml;
if (yxml == null) {
// dom element is filtered
return
}
switch (mutation.type) {
case 'characterData':
var diffs = diff_1(yxml.toString(), dom.nodeValue);
var pos = 0;
for (var i = 0; i < diffs.length; i++) {
var d = diffs[i];
if (d[0] === 0) { // EQUAL
pos += d[1].length;
} else if (d[0] === -1) { // DELETE
yxml.delete(pos, d[1].length);
} else { // INSERT
yxml.insert(pos, d[1]);
pos += d[1].length;
}
}
}
break
case 'childList':
diffChildren.add(mutation.target);
break
break
case 'attributes':
let name = mutation.attributeName;
// check if filter accepts attribute
if (this._domFilter(dom, [name]).length > 0 && this.constructor !== YXmlFragment) {
var val = dom.getAttribute(name);
if (yxml.getAttribute(name) !== val) {
if (val == null) {
yxml.removeAttribute(name);
} else {
yxml.setAttribute(name, val);
}
}
}
break
case 'childList':
diffChildren.add(mutation.target);
break
}
});
for (let dom of diffChildren) {
if (dom._yxml != null && dom._yxml !== false) {
applyChangesFromDom(dom);
}
}
});
for (let dom of diffChildren) {
if (dom._yxml != null) {
applyChangesFromDom(dom);
}
}
});
};
this._domObserver = new MutationObserver(this._domObserverListener);
this._domObserver.observe(dom, {
childList: true,
attributes: true,
characterData: true,
subtree: true
});
};
this._domObserver = new MutationObserver(this._domObserverListener);
this._domObserver.observe(dom, {
childList: true,
attributes: true,
characterData: true,
subtree: true
});
}
return dom
}
_logString () {
@@ -3971,7 +4039,7 @@ class YXmlFragment extends YArray {
// import diff from 'fast-diff'
class YXmlElement extends YXmlFragment {
constructor (arg1, arg2) {
constructor (arg1, arg2, _document) {
super();
this.nodeName = null;
this._scrollElement = null;
@@ -3979,7 +4047,7 @@ class YXmlElement extends YXmlFragment {
this.nodeName = arg1.toUpperCase();
} else if (arg1 != null && arg1.nodeType != null && arg1.nodeType === arg1.ELEMENT_NODE) {
this.nodeName = arg1.nodeName;
this._setDom(arg1);
this._setDom(arg1, _document);
} else {
this.nodeName = 'UNDEFINED';
}
@@ -3992,14 +4060,12 @@ class YXmlElement extends YXmlFragment {
struct.nodeName = this.nodeName;
return struct
}
_setDom (dom) {
_setDom (dom, _document) {
if (this._dom != null) {
throw new Error('Only call this method if you know what you are doing ;)')
} else if (dom._yxml != null) { // TODO do i need to check this? - no.. but for dev purps..
throw new Error('Already bound to an YXml type')
} else {
this._dom = dom;
dom._yxml = this;
// tag is already set in constructor
// set attributes
let attrNames = [];
@@ -4012,8 +4078,8 @@ class YXmlElement extends YXmlFragment {
let attrValue = dom.getAttribute(attrName);
this.setAttribute(attrName, attrValue);
}
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes));
this._bindToDom(dom);
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes), _document);
this._bindToDom(dom, _document);
return dom
}
}
@@ -4081,7 +4147,6 @@ class YXmlElement extends YXmlFragment {
let dom = this._dom;
if (dom == null) {
dom = _document.createElement(this.nodeName);
this._dom = dom;
dom._yxml = this;
let attrs = this.getAttributes();
for (let key in attrs) {
@@ -4090,7 +4155,7 @@ class YXmlElement extends YXmlFragment {
this.forEach(yxml => {
dom.appendChild(yxml.getDom(_document));
});
this._bindToDom(dom);
this._bindToDom(dom, _document);
}
return dom
}
@@ -4331,15 +4396,16 @@ class NamedEventHandler {
}
class ReverseOperation {
constructor (y) {
const beforeState = y._transaction.beforeState;
constructor (y, transaction) {
this.created = new Date();
const beforeState = transaction.beforeState;
this.toState = new ID(y.userID, y.ss.getState(y.userID) - 1);
if (beforeState.has(y.userID)) {
this.fromState = new ID(y.userID, beforeState.get(y.userID));
} else {
this.fromState = this.toState;
}
this.deletedStructs = y._transaction.deletedStructs;
this.deletedStructs = transaction.deletedStructs;
}
}
@@ -4353,8 +4419,45 @@ function isStructInScope (y, struct, scope) {
return false
}
function applyReverseOperation (y, scope, reverseBuffer) {
let performedUndo = false;
y.transact(() => {
while (!performedUndo && reverseBuffer.length > 0) {
let undoOp = reverseBuffer.pop();
// make sure that it is possible to iterate {from}-{to}
y.os.getItemCleanStart(undoOp.fromState);
y.os.getItemCleanEnd(undoOp.toState);
y.os.iterate(undoOp.fromState, undoOp.toState, op => {
if (!op._deleted && isStructInScope(y, op, scope)) {
performedUndo = true;
op._delete(y);
}
});
for (let op of undoOp.deletedStructs) {
if (
isStructInScope(y, op, scope) &&
op._parent !== y &&
!op._parent._deleted &&
(
op._parent._id.user !== y.userID ||
op._parent._id.clock < undoOp.fromState.clock ||
op._parent._id.clock > undoOp.fromState.clock
)
) {
performedUndo = true;
op = op._copy(undoOp.deletedStructs);
op._integrate(y);
}
}
}
});
return performedUndo
}
class UndoManager {
constructor (scope) {
constructor (scope, options = {}) {
this.options = options;
options.captureTimeout = options.captureTimeout == null ? 500 : options.captureTimeout;
this._undoBuffer = [];
this._redoBuffer = [];
this._scope = scope;
@@ -4362,11 +4465,18 @@ class UndoManager {
this._redoing = false;
const y = scope._y;
this.y = y;
y.on('afterTransaction', (y, remote) => {
if (!remote && (y._transaction.beforeState.has(y.userID) || y._transaction.deletedStructs.size > 0)) {
let reverseOperation = new ReverseOperation(y);
y.on('afterTransaction', (y, transaction, remote) => {
if (!remote && transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y, transaction);
if (!this._undoing) {
this._undoBuffer.push(reverseOperation);
let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null;
if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) {
lastUndoOp.created = reverseOperation.created;
lastUndoOp.toState = reverseOperation.toState;
reverseOperation.deletedStructs.forEach(lastUndoOp.deletedStructs.add, lastUndoOp.deletedStructs);
} else {
this._undoBuffer.push(reverseOperation);
}
if (!this._redoing) {
this._redoBuffer = [];
}
@@ -4378,46 +4488,15 @@ class UndoManager {
}
undo () {
this._undoing = true;
this._applyReverseOperation(this._undoBuffer);
const performedUndo = applyReverseOperation(this.y, this._scope, this._undoBuffer);
this._undoing = false;
return performedUndo
}
redo () {
this._redoing = true;
this._applyReverseOperation(this._redoBuffer);
const performedRedo = applyReverseOperation(this.y, this._scope, this._redoBuffer);
this._redoing = false;
}
_applyReverseOperation (reverseBuffer) {
this.y.transact(() => {
let performedUndo = false;
while (!performedUndo && reverseBuffer.length > 0) {
let undoOp = reverseBuffer.pop();
// make sure that it is possible to iterate {from}-{to}
this.y.os.getItemCleanStart(undoOp.fromState);
this.y.os.getItemCleanEnd(undoOp.toState);
this.y.os.iterate(undoOp.fromState, undoOp.toState, op => {
if (!op._deleted && isStructInScope(this.y, op, this._scope)) {
performedUndo = true;
op._delete(this.y);
}
});
for (let op of undoOp.deletedStructs) {
if (
isStructInScope(this.y, op, this._scope) &&
op._parent !== this.y &&
!op._parent._deleted &&
(
op._parent._id.user !== this.y.userID ||
op._parent._id.clock < undoOp.fromState.clock ||
op._parent._id.clock > undoOp.fromState.clock
)
) {
performedUndo = true;
op = op._copy(undoOp.deletedStructs);
op._integrate(this.y);
}
}
}
});
return performedRedo
}
}
@@ -4778,6 +4857,15 @@ function coerce(val) {
}
});
var debug_1 = debug$1.coerce;
var debug_2 = debug$1.disable;
var debug_3 = debug$1.enable;
var debug_4 = debug$1.enabled;
var debug_5 = debug$1.humanize;
var debug_6 = debug$1.names;
var debug_7 = debug$1.skips;
var debug_8 = debug$1.formatters;
var browser = createCommonjsModule(function (module, exports) {
/**
* This is the web browser implementation of `debug()`.
@@ -4966,6 +5054,14 @@ function localstorage() {
}
});
var browser_1 = browser.log;
var browser_2 = browser.formatArgs;
var browser_3 = browser.save;
var browser_4 = browser.load;
var browser_5 = browser.useColors;
var browser_6 = browser.storage;
var browser_7 = browser.colors;
class AbstractConnector {
constructor (y, opts) {
this.y = y;
@@ -5327,8 +5423,8 @@ class Y$2 extends NamedEventHandler {
transact (f, remote = false) {
let initialCall = this._transaction === null;
if (initialCall) {
this.emit('beforeTransaction', this, remote);
this._transaction = new Transaction(this);
this.emit('beforeTransaction', this, this._transaction, remote);
}
try {
f(this);
@@ -5336,25 +5432,31 @@ class Y$2 extends NamedEventHandler {
console.error(e);
}
if (initialCall) {
const transaction = this._transaction;
this._transaction = null;
// emit change events on changed types
this._transaction.changedTypes.forEach(function (subs, type) {
transaction.changedTypes.forEach(function (subs, type) {
if (!type._deleted) {
type._callObserver(subs, remote);
type._callObserver(transaction, subs, remote);
}
});
this._transaction.changedParentTypes.forEach(function (events, type) {
transaction.changedParentTypes.forEach(function (events, type) {
if (!type._deleted) {
events = events.filter(event =>
!event.target._deleted
);
events = events
.filter(event =>
!event.target._deleted
);
events
.forEach(event => {
event.currentTarget = type;
});
// we don't have to check for events.length
// because there is no way events is empty..
type._deepEventHandler.callEventListeners(events);
type._deepEventHandler.callEventListeners(transaction, events);
}
});
// when all changes & events are processed, emit afterTransaction event
this.emit('afterTransaction', this, remote);
this._transaction = null;
this.emit('afterTransaction', this, transaction, remote);
}
}
// fake _start for root properties (y.set('name', type))
@@ -5446,7 +5548,9 @@ Y$2.XmlText = YXmlText;
Y$2.utils = {
BinaryDecoder,
UndoManager
UndoManager,
getRelativePosition,
fromRelativePosition
};
Y$2.debug = browser;
@@ -12879,6 +12983,8 @@ var chance_1 = createCommonjsModule(function (module, exports) {
})();
});
var chance_2 = chance_1.Chance;
function defragmentItemContent (y) {
const os = y.os;
if (os.length < 2) {
@@ -13036,7 +13142,7 @@ async function initArrays (t, opts) {
result['array' + i] = y.define('array', Y$1.Array);
result['map' + i] = y.define('map', Y$1.Map);
result['xml' + i] = y.define('xml', Y$1.XmlElement);
y.get('xml', Y$1.Xml).setDomFilter(function (d, attrs) {
y.get('xml').setDomFilter(function (d, attrs) {
if (d.nodeName === 'HIDDEN') {
return null
} else {
@@ -13070,7 +13176,7 @@ async function flushAll (t, users) {
if (users.length === 0) {
return
}
await wait(0);
await wait(10);
if (users[0].connector.testRoom != null) {
// use flushAll method specified in Test Connector
await users[0].connector.testRoom.flushAll(users);
@@ -14890,7 +14996,7 @@ patchFilter$3.filterName = 'texts';
var textDeltaReverse = function(delta) {
var i, l, lines, line, lineTmp, header = null,
headerRegex = /^@@ +\-(\d+),(\d+) +\+(\d+),(\d+) +@@$/,
lineHeader, lineAdd, lineRemove;
lineHeader;
lines = delta.split('\n');
for (i = 0, l = lines.length; i < l; i++) {
line = lines[i];
@@ -14898,13 +15004,8 @@ var textDeltaReverse = function(delta) {
if (lineStart === '@') {
header = headerRegex.exec(line);
lineHeader = i;
lineAdd = null;
lineRemove = null;
// fix header
lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@';
} else if (lineStart === '+') {
lineAdd = i;
lines[i] = '-' + lines[i].slice(1);
if (lines[i - 1].slice(0, 1) === '+') {
// swap lines to keep default order (-+)
@@ -14913,7 +15014,6 @@ var textDeltaReverse = function(delta) {
lines[i - 1] = lineTmp;
}
} else if (lineStart === '-') {
lineRemove = i;
lines[i] = '+' + lines[i].slice(1);
}
}
@@ -15748,17 +15848,12 @@ class TestCase extends Logger {
var stackframe = createCommonjsModule$1(function (module, exports) {
(function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof undefined === 'function' && undefined.amd) {
undefined('stackframe', [], factory);
} else {
module.exports = factory();
}
}(commonjsGlobal$1, function() {
'use strict';
function _isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
@@ -15860,18 +15955,12 @@ var stackframe = createCommonjsModule$1(function (module, exports) {
var errorStackParser = createCommonjsModule$1(function (module, exports) {
(function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof undefined === 'function' && undefined.amd) {
undefined('error-stack-parser', ['stackframe'], factory);
} else {
module.exports = factory(stackframe);
}
}(commonjsGlobal$1, function ErrorStackParser(StackFrame) {
'use strict';
var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+\:\d+/;
var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+\:\d+|\(native\))/m;
var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code\])?$/;
@@ -16052,10 +16141,6 @@ var errorStackParser = createCommonjsModule$1(function (module, exports) {
var stackGenerator = createCommonjsModule$1(function (module, exports) {
(function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof undefined === 'function' && undefined.amd) {
undefined('stack-generator', ['stackframe'], factory);
} else {
@@ -18168,24 +18253,12 @@ var sourceMapConsumer = {
var stacktraceGps = createCommonjsModule$1(function (module, exports) {
(function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof undefined === 'function' && undefined.amd) {
undefined('stacktrace-gps', ['source-map', 'stackframe'], factory);
} else {
module.exports = factory(sourceMapConsumer, stackframe);
}
}(commonjsGlobal$1, function(SourceMap, StackFrame) {
'use strict';
/**
* Make a X-Domain request to url and callback.
*
* @param {String} url
* @returns {Promise} with response text if fulfilled
*/
function _xdr(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
@@ -18503,10 +18576,6 @@ var stacktraceGps = createCommonjsModule$1(function (module, exports) {
var stacktrace = createCommonjsModule$1(function (module, exports) {
(function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof undefined === 'function' && undefined.amd) {
undefined('stacktrace', ['error-stack-parser', 'stack-generator', 'stacktrace-gps'], factory);
} else {
@@ -19145,7 +19214,5 @@ test('y-xml: Random tests (1000)', async function xmlRandom1000 (t) {
await applyRandomTests(t, xmlTransactions, 1000);
});
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=y.test.js.map

File diff suppressed because one or more lines are too long