Compare commits

..

8 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
23 changed files with 460 additions and 533 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! // initialize a shared object. This function call returns a promise!
let y = new Y({ let y = new Y({
@@ -17,17 +28,14 @@ window.onload = function () {
window.yXmlType.bindToDom(document.body) window.yXmlType.bindToDom(document.body)
} }
window.undoManager = new Y.utils.UndoManager(window.yXmlType, { window.undoManager = new Y.utils.UndoManager(window.yXmlType, {
captureTimeout: 0 captureTimeout: 500
}) })
document.onkeydown = function interceptUndoRedo (e) { document.onkeydown = function interceptUndoRedo (e) {
if (e.keyCode === 90 && e.metaKey) { if (e.keyCode === 90 && e.metaKey) {
console.log('uidtaren')
if (!e.shiftKey) { if (!e.shiftKey) {
console.info('Undo!')
window.undoManager.undo() window.undoManager.undo()
} else { } else {
console.info('Redo!')
window.undoManager.redo() window.undoManager.redo()
} }
e.preventDefault() e.preventDefault()

2
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{ {
"name": "yjs", "name": "yjs",
"version": "13.0.0-29", "version": "13.0.0-32",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,8 +12,8 @@ class YArrayEvent extends YEvent {
} }
export default class YArray extends Type { export default class YArray extends Type {
_callObserver (parentSubs, remote) { _callObserver (transaction, parentSubs, remote) {
this._callEventHandler(new YArrayEvent(this, remote)) this._callEventHandler(transaction, new YArrayEvent(this, remote))
} }
get (pos) { get (pos) {
let n = this._start let n = this._start

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,16 +1,16 @@
import ID from './ID.js' import ID from './ID.js'
class ReverseOperation { class ReverseOperation {
constructor (y) { constructor (y, transaction) {
this.created = new Date() 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) this.toState = new ID(y.userID, y.ss.getState(y.userID) - 1)
if (beforeState.has(y.userID)) { if (beforeState.has(y.userID)) {
this.fromState = new ID(y.userID, beforeState.get(y.userID)) this.fromState = new ID(y.userID, beforeState.get(y.userID))
} else { } else {
this.fromState = this.toState this.fromState = this.toState
} }
this.deletedStructs = y._transaction.deletedStructs this.deletedStructs = transaction.deletedStructs
} }
} }
@@ -70,9 +70,9 @@ export default class UndoManager {
this._redoing = false this._redoing = false
const y = scope._y const y = scope._y
this.y = y this.y = y
y.on('afterTransaction', (y, remote) => { y.on('afterTransaction', (y, transaction, remote) => {
if (!remote && y._transaction.changedParentTypes.has(scope)) { if (!remote && transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y) let reverseOperation = new ReverseOperation(y, transaction)
if (!this._undoing) { if (!this._undoing) {
let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null
if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) { if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) {

View File

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

View File

@@ -153,7 +153,7 @@ export async function initArrays (t, opts) {
result['array' + i] = y.define('array', Y.Array) result['array' + i] = y.define('array', Y.Array)
result['map' + i] = y.define('map', Y.Map) result['map' + i] = y.define('map', Y.Map)
result['xml' + i] = y.define('xml', Y.XmlElement) 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') { if (d.nodeName === 'HIDDEN') {
return null return null
} else { } else {

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

249
y.node.js
View File

@@ -1,7 +1,7 @@
/** /**
* yjs - A framework for real-time p2p shared editing on any data * yjs - A framework for real-time p2p shared editing on any data
* @version v13.0.0-29 * @version v13.0.0-32
* @license MIT * @license MIT
*/ */
@@ -1899,7 +1899,7 @@ class EventHandler {
removeAllEventListeners () { removeAllEventListeners () {
this.eventListeners = []; this.eventListeners = [];
} }
callEventListeners (event) { callEventListeners (transaction, event) {
for (var i = 0; i < this.eventListeners.length; i++) { for (var i = 0; i < this.eventListeners.length; i++) {
try { try {
const f = this.eventListeners[i]; const f = this.eventListeners[i];
@@ -1966,9 +1966,9 @@ class Type extends Item {
} }
return path return path
} }
_callEventHandler (event) { _callEventHandler (transaction, event) {
const changedParentTypes = this._y._transaction.changedParentTypes; const changedParentTypes = transaction.changedParentTypes;
this._eventHandler.callEventListeners(event); this._eventHandler.callEventListeners(transaction, event);
let type = this; let type = this;
while (type !== this._y) { while (type !== this._y) {
let events = changedParentTypes.get(type); let events = changedParentTypes.get(type);
@@ -2211,8 +2211,8 @@ class YArrayEvent extends YEvent {
} }
class YArray extends Type { class YArray extends Type {
_callObserver (parentSubs, remote) { _callObserver (transaction, parentSubs, remote) {
this._callEventHandler(new YArrayEvent(this, remote)); this._callEventHandler(transaction, new YArrayEvent(this, remote));
} }
get (pos) { get (pos) {
let n = this._start; let n = this._start;
@@ -2429,8 +2429,8 @@ class YMapEvent extends YEvent {
} }
class YMap extends Type { class YMap extends Type {
_callObserver (parentSubs, remote) { _callObserver (transaction, parentSubs, remote) {
this._callEventHandler(new YMapEvent(this, parentSubs, remote)); this._callEventHandler(transaction, new YMapEvent(this, parentSubs, remote));
} }
toJSON () { toJSON () {
const map = {}; const map = {};
@@ -2776,18 +2776,22 @@ function applyChangesFromDom (dom) {
} }
} }
function reflectChangesOnDom (events) { function reflectChangesOnDom (events, _document) {
// Make sure that no filtered attributes are applied to the structure // Make sure that no filtered attributes are applied to the structure
// if they were, delete them // if they were, delete them
/* /*
events.forEach(event => { events.forEach(event => {
const target = event.target const target = event.target
const keys = this._domFilter(target.nodeName, Array.from(event.keysChanged)) if (event.attributesChanged === undefined) {
// event.target is Y.XmlText
return
}
const keys = this._domFilter(target.nodeName, Array.from(event.attributesChanged))
if (keys === null) { if (keys === null) {
target._delete() target._delete()
} else { } else {
const removeKeys = new Set() // is a copy of event.keysChanged const removeKeys = new Set() // is a copy of event.attributesChanged
event.keysChanged.forEach(key => { removeKeys.add(key) }) event.attributesChanged.forEach(key => { removeKeys.add(key) })
keys.forEach(key => { keys.forEach(key => {
// remove all accepted keys from removeKeys // remove all accepted keys from removeKeys
removeKeys.delete(key) removeKeys.delete(key)
@@ -2820,9 +2824,9 @@ function reflectChangesOnDom (events) {
}); });
if (event.childListChanged) { if (event.childListChanged) {
// create fragment of undeleted nodes // create fragment of undeleted nodes
const fragment = document.createDocumentFragment(); const fragment = _document.createDocumentFragment();
yxml.forEach(function (t) { yxml.forEach(function (t) {
fragment.append(t.getDom()); fragment.appendChild(t.getDom(_document));
}); });
// remove remainding nodes // remove remainding nodes
let lastChild = dom.lastChild; let lastChild = dom.lastChild;
@@ -2831,7 +2835,7 @@ function reflectChangesOnDom (events) {
lastChild = dom.lastChild; lastChild = dom.lastChild;
} }
// insert fragment of undeleted nodes // insert fragment of undeleted nodes
dom.append(fragment); dom.appendChild(fragment);
} }
} }
/* TODO: smartscrolling /* TODO: smartscrolling
@@ -2952,7 +2956,7 @@ let relativeSelection = null;
let beforeTransactionSelectionFixer; let beforeTransactionSelectionFixer;
if (typeof getSelection !== 'undefined') { if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, remote) { beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, transaction, remote) {
if (!remote) { if (!remote) {
return return
} }
@@ -2975,7 +2979,7 @@ if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _fakeBeforeTransactionSelectionFixer () {}; beforeTransactionSelectionFixer = function _fakeBeforeTransactionSelectionFixer () {};
} }
function afterTransactionSelectionFixer (y, remote) { function afterTransactionSelectionFixer (y, transaction, remote) {
if (relativeSelection === null || !remote) { if (relativeSelection === null || !remote) {
return return
} }
@@ -3774,7 +3778,7 @@ function merge_tuples (diffs, start, length) {
/* global MutationObserver */ /* global MutationObserver */
function domToYXml (parent, doms) { function domToYXml (parent, doms, _document) {
const types = []; const types = [];
doms.forEach(d => { doms.forEach(d => {
if (d._yxml != null && d._yxml !== false) { if (d._yxml != null && d._yxml !== false) {
@@ -3785,7 +3789,7 @@ function domToYXml (parent, doms) {
if (d.nodeType === d.TEXT_NODE) { if (d.nodeType === d.TEXT_NODE) {
type = new YXmlText(d); type = new YXmlText(d);
} else if (d.nodeType === d.ELEMENT_NODE) { } else if (d.nodeType === d.ELEMENT_NODE) {
type = new YXmlFragment._YXmlElement(d, parent._domFilter); type = new YXmlFragment._YXmlElement(d, parent._domFilter, _document);
} else { } else {
throw new Error('Unsupported node!') throw new Error('Unsupported node!')
} }
@@ -3863,7 +3867,9 @@ class YXmlFragment extends YArray {
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }
this._domObserver.takeRecords(); if (this._domObserver !== null) {
this._domObserver.takeRecords();
}
token = true; token = true;
} }
}; };
@@ -3907,8 +3913,8 @@ class YXmlFragment extends YArray {
xml.setDomFilter(f); xml.setDomFilter(f);
}); });
} }
_callObserver (parentSubs, remote) { _callObserver (transaction, parentSubs, remote) {
this._callEventHandler(new YXmlEvent(this, parentSubs, remote)); this._callEventHandler(transaction, new YXmlEvent(this, parentSubs, remote));
} }
toString () { toString () {
return this.map(xml => xml.toString()).join('') return this.map(xml => xml.toString()).join('')
@@ -3927,113 +3933,116 @@ class YXmlFragment extends YArray {
this._dom = null; this._dom = null;
} }
} }
insertDomElementsAfter (prev, doms) { insertDomElementsAfter (prev, doms, _document) {
const types = domToYXml(this, doms); const types = domToYXml(this, doms, _document);
this.insertAfter(prev, types); this.insertAfter(prev, types);
return types return types
} }
insertDomElements (pos, doms) { insertDomElements (pos, doms, _document) {
const types = domToYXml(this, doms); const types = domToYXml(this, doms, _document);
this.insert(pos, types); this.insert(pos, types);
return types return types
} }
getDom () { getDom () {
return this._dom return this._dom
} }
bindToDom (dom) { bindToDom (dom, _document) {
if (this._dom != null) { if (this._dom != null) {
this._unbindFromDom(); this._unbindFromDom();
} }
if (dom._yxml != null) { if (dom._yxml != null) {
dom._yxml._unbindFromDom(); dom._yxml._unbindFromDom();
} }
if (MutationObserver == null) {
throw new Error('Not able to bind to a DOM element, because MutationObserver is not available!')
}
dom.innerHTML = ''; dom.innerHTML = '';
this._dom = dom;
dom._yxml = this;
this.forEach(t => { 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 // binds to a dom element
// Only call if dom and YXml are isomorph // Only call if dom and YXml are isomorph
_bindToDom (dom) { _bindToDom (dom, _document) {
if (this._parent === null || this._parent._dom != null || typeof MutationObserver === 'undefined') { _document = _document || document;
// only bind if parent did not already bind 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 return
} }
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords());
});
this._y.on('beforeTransaction', beforeTransactionSelectionFixer); this._y.on('beforeTransaction', beforeTransactionSelectionFixer);
this._y.on('afterTransaction', afterTransactionSelectionFixer); this._y.on('afterTransaction', afterTransactionSelectionFixer);
// Apply Y.Xml events to dom // 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 // Apply Dom changes on Y.Xml
this._domObserverListener = mutations => { if (typeof MutationObserver !== 'undefined') {
this._mutualExclude(() => { this._y.on('beforeTransaction', () => {
this._y.transact(() => { this._domObserverListener(this._domObserver.takeRecords());
let diffChildren = new Set(); });
mutations.forEach(mutation => { this._domObserverListener = mutations => {
const dom = mutation.target; this._mutualExclude(() => {
const yxml = dom._yxml; this._y.transact(() => {
if (yxml == null) { let diffChildren = new Set();
// dom element is filtered mutations.forEach(mutation => {
return const dom = mutation.target;
} const yxml = dom._yxml;
switch (mutation.type) { if (yxml == null) {
case 'characterData': // dom element is filtered
var diffs = diff_1(yxml.toString(), dom.nodeValue); return
var pos = 0; }
for (var i = 0; i < diffs.length; i++) { switch (mutation.type) {
var d = diffs[i]; case 'characterData':
if (d[0] === 0) { // EQUAL var diffs = diff_1(yxml.toString(), dom.nodeValue);
pos += d[1].length; var pos = 0;
} else if (d[0] === -1) { // DELETE for (var i = 0; i < diffs.length; i++) {
yxml.delete(pos, d[1].length); var d = diffs[i];
} else { // INSERT if (d[0] === 0) { // EQUAL
yxml.insert(pos, d[1]); pos += d[1].length;
pos += d[1].length; } else if (d[0] === -1) { // DELETE
} yxml.delete(pos, d[1].length);
} } else { // INSERT
break yxml.insert(pos, d[1]);
case 'attributes': pos += d[1].length;
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
break case 'attributes':
case 'childList': let name = mutation.attributeName;
diffChildren.add(mutation.target); // check if filter accepts attribute
break 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 && dom._yxml !== false) {
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 return dom
} }
_logString () { _logString () {
@@ -4045,7 +4054,7 @@ class YXmlFragment extends YArray {
// import diff from 'fast-diff' // import diff from 'fast-diff'
class YXmlElement extends YXmlFragment { class YXmlElement extends YXmlFragment {
constructor (arg1, arg2) { constructor (arg1, arg2, _document) {
super(); super();
this.nodeName = null; this.nodeName = null;
this._scrollElement = null; this._scrollElement = null;
@@ -4053,7 +4062,7 @@ class YXmlElement extends YXmlFragment {
this.nodeName = arg1.toUpperCase(); this.nodeName = arg1.toUpperCase();
} else if (arg1 != null && arg1.nodeType != null && arg1.nodeType === arg1.ELEMENT_NODE) { } else if (arg1 != null && arg1.nodeType != null && arg1.nodeType === arg1.ELEMENT_NODE) {
this.nodeName = arg1.nodeName; this.nodeName = arg1.nodeName;
this._setDom(arg1); this._setDom(arg1, _document);
} else { } else {
this.nodeName = 'UNDEFINED'; this.nodeName = 'UNDEFINED';
} }
@@ -4066,14 +4075,12 @@ class YXmlElement extends YXmlFragment {
struct.nodeName = this.nodeName; struct.nodeName = this.nodeName;
return struct return struct
} }
_setDom (dom) { _setDom (dom, _document) {
if (this._dom != null) { if (this._dom != null) {
throw new Error('Only call this method if you know what you are doing ;)') 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.. } 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') throw new Error('Already bound to an YXml type')
} else { } else {
this._dom = dom;
dom._yxml = this;
// tag is already set in constructor // tag is already set in constructor
// set attributes // set attributes
let attrNames = []; let attrNames = [];
@@ -4086,8 +4093,8 @@ class YXmlElement extends YXmlFragment {
let attrValue = dom.getAttribute(attrName); let attrValue = dom.getAttribute(attrName);
this.setAttribute(attrName, attrValue); this.setAttribute(attrName, attrValue);
} }
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes)); this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes), _document);
this._bindToDom(dom); this._bindToDom(dom, _document);
return dom return dom
} }
} }
@@ -4155,7 +4162,6 @@ class YXmlElement extends YXmlFragment {
let dom = this._dom; let dom = this._dom;
if (dom == null) { if (dom == null) {
dom = _document.createElement(this.nodeName); dom = _document.createElement(this.nodeName);
this._dom = dom;
dom._yxml = this; dom._yxml = this;
let attrs = this.getAttributes(); let attrs = this.getAttributes();
for (let key in attrs) { for (let key in attrs) {
@@ -4164,7 +4170,7 @@ class YXmlElement extends YXmlFragment {
this.forEach(yxml => { this.forEach(yxml => {
dom.appendChild(yxml.getDom(_document)); dom.appendChild(yxml.getDom(_document));
}); });
this._bindToDom(dom); this._bindToDom(dom, _document);
} }
return dom return dom
} }
@@ -4405,16 +4411,16 @@ class NamedEventHandler {
} }
class ReverseOperation { class ReverseOperation {
constructor (y) { constructor (y, transaction) {
this.created = new Date(); 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); this.toState = new ID(y.userID, y.ss.getState(y.userID) - 1);
if (beforeState.has(y.userID)) { if (beforeState.has(y.userID)) {
this.fromState = new ID(y.userID, beforeState.get(y.userID)); this.fromState = new ID(y.userID, beforeState.get(y.userID));
} else { } else {
this.fromState = this.toState; this.fromState = this.toState;
} }
this.deletedStructs = y._transaction.deletedStructs; this.deletedStructs = transaction.deletedStructs;
} }
} }
@@ -4474,9 +4480,9 @@ class UndoManager {
this._redoing = false; this._redoing = false;
const y = scope._y; const y = scope._y;
this.y = y; this.y = y;
y.on('afterTransaction', (y, remote) => { y.on('afterTransaction', (y, transaction, remote) => {
if (!remote && y._transaction.changedParentTypes.has(scope)) { if (!remote && transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y); let reverseOperation = new ReverseOperation(y, transaction);
if (!this._undoing) { if (!this._undoing) {
let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null; let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null;
if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) { if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) {
@@ -5432,8 +5438,8 @@ class Y$1 extends NamedEventHandler {
transact (f, remote = false) { transact (f, remote = false) {
let initialCall = this._transaction === null; let initialCall = this._transaction === null;
if (initialCall) { if (initialCall) {
this.emit('beforeTransaction', this, remote);
this._transaction = new Transaction(this); this._transaction = new Transaction(this);
this.emit('beforeTransaction', this, this._transaction, remote);
} }
try { try {
f(this); f(this);
@@ -5441,13 +5447,15 @@ class Y$1 extends NamedEventHandler {
console.error(e); console.error(e);
} }
if (initialCall) { if (initialCall) {
const transaction = this._transaction;
this._transaction = null;
// emit change events on changed types // emit change events on changed types
this._transaction.changedTypes.forEach(function (subs, type) { transaction.changedTypes.forEach(function (subs, type) {
if (!type._deleted) { 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) { if (!type._deleted) {
events = events events = events
.filter(event => .filter(event =>
@@ -5459,12 +5467,11 @@ class Y$1 extends NamedEventHandler {
}); });
// we don't have to check for events.length // we don't have to check for events.length
// because there is no way events is empty.. // 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 // when all changes & events are processed, emit afterTransaction event
this.emit('afterTransaction', this, remote); this.emit('afterTransaction', this, transaction, remote);
this._transaction = null;
} }
} }
// fake _start for root properties (y.set('name', type)) // fake _start for root properties (y.set('name', type))
@@ -5556,7 +5563,9 @@ Y$1.XmlText = YXmlText;
Y$1.utils = { Y$1.utils = {
BinaryDecoder, BinaryDecoder,
UndoManager UndoManager,
getRelativePosition,
fromRelativePosition
}; };
Y$1.debug = browser; Y$1.debug = browser;

File diff suppressed because one or more lines are too long

422
y.test.js
View File

@@ -1,8 +1,8 @@
(function (global, factory) { (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(['exports'], factory) : typeof define === 'function' && define.amd ? define(factory) :
(factory((global['y-tests'] = {}))); (factory());
}(this, (function (exports) { 'use strict'; }(this, (function () { 'use strict';
class N { class N {
// A created node is always red! // A created node is always red!
@@ -1448,10 +1448,6 @@ function logID (id) {
} }
} }
/**
* Delete all items in an ID-range
* TODO: implement getItemCleanStartNode for better performance (only one lookup)
*/
function deleteItemRange (y, user, clock, range) { function deleteItemRange (y, user, clock, range) {
const createDelete = y.connector._forwardAppliedStructs; const createDelete = y.connector._forwardAppliedStructs;
let item = y.os.getItemCleanStart(new ID(user, clock)); let item = y.os.getItemCleanStart(new ID(user, clock));
@@ -1556,13 +1552,6 @@ function transactionTypeChanged (y, type, sub) {
} }
} }
/**
* Helper utility to split an Item (see _splitAt)
* - copy all properties from a to b
* - connect a to b
* - assigns the correct _id
* - save b to os
*/
function splitHelper (y, a, b, diff) { function splitHelper (y, a, b, diff) {
const aID = a._id; const aID = a._id;
b._id = new ID(aID.user, aID.clock + diff); b._id = new ID(aID.user, aID.clock + diff);
@@ -1896,7 +1885,7 @@ class EventHandler {
removeAllEventListeners () { removeAllEventListeners () {
this.eventListeners = []; this.eventListeners = [];
} }
callEventListeners (event) { callEventListeners (transaction, event) {
for (var i = 0; i < this.eventListeners.length; i++) { for (var i = 0; i < this.eventListeners.length; i++) {
try { try {
const f = this.eventListeners[i]; const f = this.eventListeners[i];
@@ -1913,7 +1902,6 @@ class EventHandler {
} }
} }
// restructure children as if they were inserted one after another
function integrateChildren (y, start) { function integrateChildren (y, start) {
let right; let right;
do { do {
@@ -1963,9 +1951,9 @@ class Type extends Item {
} }
return path return path
} }
_callEventHandler (event) { _callEventHandler (transaction, event) {
const changedParentTypes = this._y._transaction.changedParentTypes; const changedParentTypes = transaction.changedParentTypes;
this._eventHandler.callEventListeners(event); this._eventHandler.callEventListeners(transaction, event);
let type = this; let type = this;
while (type !== this._y) { while (type !== this._y) {
let events = changedParentTypes.get(type); let events = changedParentTypes.get(type);
@@ -2208,8 +2196,8 @@ class YArrayEvent extends YEvent {
} }
class YArray extends Type { class YArray extends Type {
_callObserver (parentSubs, remote) { _callObserver (transaction, parentSubs, remote) {
this._callEventHandler(new YArrayEvent(this, remote)); this._callEventHandler(transaction, new YArrayEvent(this, remote));
} }
get (pos) { get (pos) {
let n = this._start; let n = this._start;
@@ -2426,8 +2414,8 @@ class YMapEvent extends YEvent {
} }
class YMap extends Type { class YMap extends Type {
_callObserver (parentSubs, remote) { _callObserver (transaction, parentSubs, remote) {
this._callEventHandler(new YMapEvent(this, parentSubs, remote)); this._callEventHandler(transaction, new YMapEvent(this, parentSubs, remote));
} }
toJSON () { toJSON () {
const map = {}; const map = {};
@@ -2773,18 +2761,22 @@ function applyChangesFromDom (dom) {
} }
} }
function reflectChangesOnDom (events) { function reflectChangesOnDom (events, _document) {
// Make sure that no filtered attributes are applied to the structure // Make sure that no filtered attributes are applied to the structure
// if they were, delete them // if they were, delete them
/* /*
events.forEach(event => { events.forEach(event => {
const target = event.target const target = event.target
const keys = this._domFilter(target.nodeName, Array.from(event.keysChanged)) if (event.attributesChanged === undefined) {
// event.target is Y.XmlText
return
}
const keys = this._domFilter(target.nodeName, Array.from(event.attributesChanged))
if (keys === null) { if (keys === null) {
target._delete() target._delete()
} else { } else {
const removeKeys = new Set() // is a copy of event.keysChanged const removeKeys = new Set() // is a copy of event.attributesChanged
event.keysChanged.forEach(key => { removeKeys.add(key) }) event.attributesChanged.forEach(key => { removeKeys.add(key) })
keys.forEach(key => { keys.forEach(key => {
// remove all accepted keys from removeKeys // remove all accepted keys from removeKeys
removeKeys.delete(key) removeKeys.delete(key)
@@ -2817,9 +2809,9 @@ function reflectChangesOnDom (events) {
}); });
if (event.childListChanged) { if (event.childListChanged) {
// create fragment of undeleted nodes // create fragment of undeleted nodes
const fragment = document.createDocumentFragment(); const fragment = _document.createDocumentFragment();
yxml.forEach(function (t) { yxml.forEach(function (t) {
fragment.append(t.getDom()); fragment.appendChild(t.getDom(_document));
}); });
// remove remainding nodes // remove remainding nodes
let lastChild = dom.lastChild; let lastChild = dom.lastChild;
@@ -2828,7 +2820,7 @@ function reflectChangesOnDom (events) {
lastChild = dom.lastChild; lastChild = dom.lastChild;
} }
// insert fragment of undeleted nodes // insert fragment of undeleted nodes
dom.append(fragment); dom.appendChild(fragment);
} }
} }
/* TODO: smartscrolling /* TODO: smartscrolling
@@ -2949,7 +2941,7 @@ let relativeSelection = null;
let beforeTransactionSelectionFixer; let beforeTransactionSelectionFixer;
if (typeof getSelection !== 'undefined') { if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, remote) { beforeTransactionSelectionFixer = function _beforeTransactionSelectionFixer (y, transaction, remote) {
if (!remote) { if (!remote) {
return return
} }
@@ -2972,7 +2964,7 @@ if (typeof getSelection !== 'undefined') {
beforeTransactionSelectionFixer = function _fakeBeforeTransactionSelectionFixer () {}; beforeTransactionSelectionFixer = function _fakeBeforeTransactionSelectionFixer () {};
} }
function afterTransactionSelectionFixer (y, remote) { function afterTransactionSelectionFixer (y, transaction, remote) {
if (relativeSelection === null || !remote) { if (relativeSelection === null || !remote) {
return return
} }
@@ -3771,7 +3763,7 @@ function merge_tuples (diffs, start, length) {
/* global MutationObserver */ /* global MutationObserver */
function domToYXml (parent, doms) { function domToYXml (parent, doms, _document) {
const types = []; const types = [];
doms.forEach(d => { doms.forEach(d => {
if (d._yxml != null && d._yxml !== false) { if (d._yxml != null && d._yxml !== false) {
@@ -3782,7 +3774,7 @@ function domToYXml (parent, doms) {
if (d.nodeType === d.TEXT_NODE) { if (d.nodeType === d.TEXT_NODE) {
type = new YXmlText(d); type = new YXmlText(d);
} else if (d.nodeType === d.ELEMENT_NODE) { } else if (d.nodeType === d.ELEMENT_NODE) {
type = new YXmlFragment._YXmlElement(d, parent._domFilter); type = new YXmlFragment._YXmlElement(d, parent._domFilter, _document);
} else { } else {
throw new Error('Unsupported node!') throw new Error('Unsupported node!')
} }
@@ -3860,7 +3852,9 @@ class YXmlFragment extends YArray {
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }
this._domObserver.takeRecords(); if (this._domObserver !== null) {
this._domObserver.takeRecords();
}
token = true; token = true;
} }
}; };
@@ -3904,8 +3898,8 @@ class YXmlFragment extends YArray {
xml.setDomFilter(f); xml.setDomFilter(f);
}); });
} }
_callObserver (parentSubs, remote) { _callObserver (transaction, parentSubs, remote) {
this._callEventHandler(new YXmlEvent(this, parentSubs, remote)); this._callEventHandler(transaction, new YXmlEvent(this, parentSubs, remote));
} }
toString () { toString () {
return this.map(xml => xml.toString()).join('') return this.map(xml => xml.toString()).join('')
@@ -3924,113 +3918,116 @@ class YXmlFragment extends YArray {
this._dom = null; this._dom = null;
} }
} }
insertDomElementsAfter (prev, doms) { insertDomElementsAfter (prev, doms, _document) {
const types = domToYXml(this, doms); const types = domToYXml(this, doms, _document);
this.insertAfter(prev, types); this.insertAfter(prev, types);
return types return types
} }
insertDomElements (pos, doms) { insertDomElements (pos, doms, _document) {
const types = domToYXml(this, doms); const types = domToYXml(this, doms, _document);
this.insert(pos, types); this.insert(pos, types);
return types return types
} }
getDom () { getDom () {
return this._dom return this._dom
} }
bindToDom (dom) { bindToDom (dom, _document) {
if (this._dom != null) { if (this._dom != null) {
this._unbindFromDom(); this._unbindFromDom();
} }
if (dom._yxml != null) { if (dom._yxml != null) {
dom._yxml._unbindFromDom(); dom._yxml._unbindFromDom();
} }
if (MutationObserver == null) {
throw new Error('Not able to bind to a DOM element, because MutationObserver is not available!')
}
dom.innerHTML = ''; dom.innerHTML = '';
this._dom = dom;
dom._yxml = this;
this.forEach(t => { 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 // binds to a dom element
// Only call if dom and YXml are isomorph // Only call if dom and YXml are isomorph
_bindToDom (dom) { _bindToDom (dom, _document) {
if (this._parent === null || this._parent._dom != null || typeof MutationObserver === 'undefined') { _document = _document || document;
// only bind if parent did not already bind 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 return
} }
this._y.on('beforeTransaction', () => {
this._domObserverListener(this._domObserver.takeRecords());
});
this._y.on('beforeTransaction', beforeTransactionSelectionFixer); this._y.on('beforeTransaction', beforeTransactionSelectionFixer);
this._y.on('afterTransaction', afterTransactionSelectionFixer); this._y.on('afterTransaction', afterTransactionSelectionFixer);
// Apply Y.Xml events to dom // 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 // Apply Dom changes on Y.Xml
this._domObserverListener = mutations => { if (typeof MutationObserver !== 'undefined') {
this._mutualExclude(() => { this._y.on('beforeTransaction', () => {
this._y.transact(() => { this._domObserverListener(this._domObserver.takeRecords());
let diffChildren = new Set(); });
mutations.forEach(mutation => { this._domObserverListener = mutations => {
const dom = mutation.target; this._mutualExclude(() => {
const yxml = dom._yxml; this._y.transact(() => {
if (yxml == null) { let diffChildren = new Set();
// dom element is filtered mutations.forEach(mutation => {
return const dom = mutation.target;
} const yxml = dom._yxml;
switch (mutation.type) { if (yxml == null) {
case 'characterData': // dom element is filtered
var diffs = diff_1(yxml.toString(), dom.nodeValue); return
var pos = 0; }
for (var i = 0; i < diffs.length; i++) { switch (mutation.type) {
var d = diffs[i]; case 'characterData':
if (d[0] === 0) { // EQUAL var diffs = diff_1(yxml.toString(), dom.nodeValue);
pos += d[1].length; var pos = 0;
} else if (d[0] === -1) { // DELETE for (var i = 0; i < diffs.length; i++) {
yxml.delete(pos, d[1].length); var d = diffs[i];
} else { // INSERT if (d[0] === 0) { // EQUAL
yxml.insert(pos, d[1]); pos += d[1].length;
pos += d[1].length; } else if (d[0] === -1) { // DELETE
} yxml.delete(pos, d[1].length);
} } else { // INSERT
break yxml.insert(pos, d[1]);
case 'attributes': pos += d[1].length;
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
break case 'attributes':
case 'childList': let name = mutation.attributeName;
diffChildren.add(mutation.target); // check if filter accepts attribute
break 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 && dom._yxml !== false) {
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 return dom
} }
_logString () { _logString () {
@@ -4042,7 +4039,7 @@ class YXmlFragment extends YArray {
// import diff from 'fast-diff' // import diff from 'fast-diff'
class YXmlElement extends YXmlFragment { class YXmlElement extends YXmlFragment {
constructor (arg1, arg2) { constructor (arg1, arg2, _document) {
super(); super();
this.nodeName = null; this.nodeName = null;
this._scrollElement = null; this._scrollElement = null;
@@ -4050,7 +4047,7 @@ class YXmlElement extends YXmlFragment {
this.nodeName = arg1.toUpperCase(); this.nodeName = arg1.toUpperCase();
} else if (arg1 != null && arg1.nodeType != null && arg1.nodeType === arg1.ELEMENT_NODE) { } else if (arg1 != null && arg1.nodeType != null && arg1.nodeType === arg1.ELEMENT_NODE) {
this.nodeName = arg1.nodeName; this.nodeName = arg1.nodeName;
this._setDom(arg1); this._setDom(arg1, _document);
} else { } else {
this.nodeName = 'UNDEFINED'; this.nodeName = 'UNDEFINED';
} }
@@ -4063,14 +4060,12 @@ class YXmlElement extends YXmlFragment {
struct.nodeName = this.nodeName; struct.nodeName = this.nodeName;
return struct return struct
} }
_setDom (dom) { _setDom (dom, _document) {
if (this._dom != null) { if (this._dom != null) {
throw new Error('Only call this method if you know what you are doing ;)') 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.. } 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') throw new Error('Already bound to an YXml type')
} else { } else {
this._dom = dom;
dom._yxml = this;
// tag is already set in constructor // tag is already set in constructor
// set attributes // set attributes
let attrNames = []; let attrNames = [];
@@ -4083,8 +4078,8 @@ class YXmlElement extends YXmlFragment {
let attrValue = dom.getAttribute(attrName); let attrValue = dom.getAttribute(attrName);
this.setAttribute(attrName, attrValue); this.setAttribute(attrName, attrValue);
} }
this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes)); this.insertDomElements(0, Array.prototype.slice.call(dom.childNodes), _document);
this._bindToDom(dom); this._bindToDom(dom, _document);
return dom return dom
} }
} }
@@ -4152,7 +4147,6 @@ class YXmlElement extends YXmlFragment {
let dom = this._dom; let dom = this._dom;
if (dom == null) { if (dom == null) {
dom = _document.createElement(this.nodeName); dom = _document.createElement(this.nodeName);
this._dom = dom;
dom._yxml = this; dom._yxml = this;
let attrs = this.getAttributes(); let attrs = this.getAttributes();
for (let key in attrs) { for (let key in attrs) {
@@ -4161,7 +4155,7 @@ class YXmlElement extends YXmlFragment {
this.forEach(yxml => { this.forEach(yxml => {
dom.appendChild(yxml.getDom(_document)); dom.appendChild(yxml.getDom(_document));
}); });
this._bindToDom(dom); this._bindToDom(dom, _document);
} }
return dom return dom
} }
@@ -4402,16 +4396,16 @@ class NamedEventHandler {
} }
class ReverseOperation { class ReverseOperation {
constructor (y) { constructor (y, transaction) {
this.created = new Date(); 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); this.toState = new ID(y.userID, y.ss.getState(y.userID) - 1);
if (beforeState.has(y.userID)) { if (beforeState.has(y.userID)) {
this.fromState = new ID(y.userID, beforeState.get(y.userID)); this.fromState = new ID(y.userID, beforeState.get(y.userID));
} else { } else {
this.fromState = this.toState; this.fromState = this.toState;
} }
this.deletedStructs = y._transaction.deletedStructs; this.deletedStructs = transaction.deletedStructs;
} }
} }
@@ -4471,9 +4465,9 @@ class UndoManager {
this._redoing = false; this._redoing = false;
const y = scope._y; const y = scope._y;
this.y = y; this.y = y;
y.on('afterTransaction', (y, remote) => { y.on('afterTransaction', (y, transaction, remote) => {
if (!remote && y._transaction.changedParentTypes.has(scope)) { if (!remote && transaction.changedParentTypes.has(scope)) {
let reverseOperation = new ReverseOperation(y); let reverseOperation = new ReverseOperation(y, transaction);
if (!this._undoing) { if (!this._undoing) {
let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null; let lastUndoOp = this._undoBuffer.length > 0 ? this._undoBuffer[this._undoBuffer.length - 1] : null;
if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) { if (lastUndoOp !== null && reverseOperation.created - lastUndoOp.created <= options.captureTimeout) {
@@ -4530,7 +4524,7 @@ var y = d * 365.25;
* @api public * @api public
*/ */
var ms = function(val, options) { var index = function(val, options) {
options = options || {}; options = options || {};
var type = typeof val; var type = typeof val;
if (type === 'string' && val.length > 0) { if (type === 'string' && val.length > 0) {
@@ -4672,7 +4666,7 @@ exports.coerce = coerce;
exports.disable = disable; exports.disable = disable;
exports.enable = enable; exports.enable = enable;
exports.enabled = enabled; exports.enabled = enabled;
exports.humanize = ms; exports.humanize = index;
/** /**
* The currently active debug mode names, and names to skip. * The currently active debug mode names, and names to skip.
@@ -4731,8 +4725,8 @@ function createDebug(namespace) {
// set `diff` timestamp // set `diff` timestamp
var curr = +new Date(); var curr = +new Date();
var ms$$1 = curr - (prevTime || curr); var ms = curr - (prevTime || curr);
self.diff = ms$$1; self.diff = ms;
self.prev = prevTime; self.prev = prevTime;
self.curr = curr; self.curr = curr;
prevTime = curr; prevTime = curr;
@@ -4751,19 +4745,19 @@ function createDebug(namespace) {
} }
// apply any `formatters` transformations // apply any `formatters` transformations
var index = 0; var index$$1 = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index // if we encounter an escaped % then don't increase the array index
if (match === '%%') return match; if (match === '%%') return match;
index++; index$$1++;
var formatter = exports.formatters[format]; var formatter = exports.formatters[format];
if ('function' === typeof formatter) { if ('function' === typeof formatter) {
var val = args[index]; var val = args[index$$1];
match = formatter.call(self, val); match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format` // now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1); args.splice(index$$1, 1);
index--; index$$1--;
} }
return match; return match;
}); });
@@ -5429,8 +5423,8 @@ class Y$2 extends NamedEventHandler {
transact (f, remote = false) { transact (f, remote = false) {
let initialCall = this._transaction === null; let initialCall = this._transaction === null;
if (initialCall) { if (initialCall) {
this.emit('beforeTransaction', this, remote);
this._transaction = new Transaction(this); this._transaction = new Transaction(this);
this.emit('beforeTransaction', this, this._transaction, remote);
} }
try { try {
f(this); f(this);
@@ -5438,13 +5432,15 @@ class Y$2 extends NamedEventHandler {
console.error(e); console.error(e);
} }
if (initialCall) { if (initialCall) {
const transaction = this._transaction;
this._transaction = null;
// emit change events on changed types // emit change events on changed types
this._transaction.changedTypes.forEach(function (subs, type) { transaction.changedTypes.forEach(function (subs, type) {
if (!type._deleted) { 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) { if (!type._deleted) {
events = events events = events
.filter(event => .filter(event =>
@@ -5456,12 +5452,11 @@ class Y$2 extends NamedEventHandler {
}); });
// we don't have to check for events.length // we don't have to check for events.length
// because there is no way events is empty.. // 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 // when all changes & events are processed, emit afterTransaction event
this.emit('afterTransaction', this, remote); this.emit('afterTransaction', this, transaction, remote);
this._transaction = null;
} }
} }
// fake _start for root properties (y.set('name', type)) // fake _start for root properties (y.set('name', type))
@@ -5553,7 +5548,9 @@ Y$2.XmlText = YXmlText;
Y$2.utils = { Y$2.utils = {
BinaryDecoder, BinaryDecoder,
UndoManager UndoManager,
getRelativePosition,
fromRelativePosition
}; };
Y$2.debug = browser; Y$2.debug = browser;
@@ -5729,7 +5726,7 @@ if (typeof Y !== 'undefined') {
} }
var chance_1 = createCommonjsModule(function (module, exports) { var chance_1 = createCommonjsModule(function (module, exports) {
// Chance.js 1.0.12 // Chance.js 1.0.10
// http://chancejs.com // http://chancejs.com
// (c) 2013 Victor Quinn // (c) 2013 Victor Quinn
// Chance may be freely distributed or modified under the MIT license. // Chance may be freely distributed or modified under the MIT license.
@@ -5794,7 +5791,7 @@ var chance_1 = createCommonjsModule(function (module, exports) {
return this; return this;
} }
Chance.prototype.VERSION = "1.0.12"; Chance.prototype.VERSION = "1.0.10";
// Random helper functions // Random helper functions
function initOptions(options, defaults) { function initOptions(options, defaults) {
@@ -6013,16 +6010,6 @@ var chance_1 = createCommonjsModule(function (module, exports) {
return integer.toString(16); return integer.toString(16);
}; };
Chance.prototype.letter = function(options) {
options = initOptions(options, {casing: 'lower'});
var pool = "abcdefghijklmnopqrstuvwxyz";
var letter = this.character({pool: pool});
if (options.casing === 'upper') {
letter = letter.toUpperCase();
}
return letter;
};
/** /**
* Return a random string * Return a random string
* *
@@ -6965,25 +6952,8 @@ var chance_1 = createCommonjsModule(function (module, exports) {
return this.word({length: options.length}) + '@' + (options.domain || this.domain()); return this.word({length: options.length}) + '@' + (options.domain || this.domain());
}; };
/**
* #Description:
* ===============================================
* Generate a random Facebook id, aka fbid.
*
* NOTE: At the moment (Sep 2017), Facebook ids are
* "numeric strings" of length 16.
* However, Facebook Graph API documentation states that
* "it is extremely likely to change over time".
* @see https://developers.facebook.com/docs/graph-api/overview/
*
* #Examples:
* ===============================================
* chance.fbid() => '1000035231661304'
*
* @return [string] facebook id
*/
Chance.prototype.fbid = function () { Chance.prototype.fbid = function () {
return '10000' + this.string({pool: "1234567890", length: 11}); return parseInt('10000' + this.natural({max: 100000000000}), 10);
}; };
Chance.prototype.google_analytics = function () { Chance.prototype.google_analytics = function () {
@@ -7824,72 +7794,8 @@ var chance_1 = createCommonjsModule(function (module, exports) {
// -- End Regional // -- End Regional
// -- Music --
Chance.prototype.note = function(options) {
// choices for 'notes' option:
// flatKey - chromatic scale with flat notes (default)
// sharpKey - chromatic scale with sharp notes
// flats - just flat notes
// sharps - just sharp notes
// naturals - just natural notes
// all - naturals, sharps and flats
options = initOptions(options, { notes : 'flatKey'});
var scales = {
naturals: ['C', 'D', 'E', 'F', 'G', 'A', 'B'],
flats: ['D♭', 'E♭', 'G♭', 'A♭', 'B♭'],
sharps: ['C♯', 'D♯', 'F♯', 'G♯', 'A♯']
};
scales.all = scales.naturals.concat(scales.flats.concat(scales.sharps));
scales.flatKey = scales.naturals.concat(scales.flats);
scales.sharpKey = scales.naturals.concat(scales.sharps);
return this.pickone(scales[options.notes]);
};
Chance.prototype.midi_note = function(options) {
var min = 0;
var max = 127;
options = initOptions(options, { min : min, max : max });
return this.integer({min: options.min, max: options.max});
};
Chance.prototype.chord_quality = function(options) {
options = initOptions(options, { jazz: true });
var chord_qualities = ['maj', 'min', 'aug', 'dim'];
if (options.jazz){
chord_qualities = [
'maj7',
'min7',
'7',
'sus',
'dim',
'ø'
];
}
return this.pickone(chord_qualities);
};
Chance.prototype.chord = function (options) {
options = initOptions(options);
return this.note(options) + this.chord_quality(options);
};
Chance.prototype.tempo = function (options) {
var min = 40;
var max = 320;
options = initOptions(options, {min: min, max: max});
return this.integer({min: options.min, max: options.max});
};
// -- End Music
// -- Miscellaneous -- // -- Miscellaneous --
// Coin - Flip, flip, flipadelphia
Chance.prototype.coin = function(options) {
return this.bool() ? "heads" : "tails";
};
// Dice - For all the board game geeks out there, myself included ;) // Dice - For all the board game geeks out there, myself included ;)
function diceFn (range) { function diceFn (range) {
return function () { return function () {
@@ -13079,19 +12985,6 @@ var chance_1 = createCommonjsModule(function (module, exports) {
var chance_2 = chance_1.Chance; var chance_2 = chance_1.Chance;
/**
* Try to merge all items in os with their successors.
*
* Some transformations (like delete) fragment items.
* Item(c: 'ab') + Delete(1,1) + Delete(0, 1) -> Item(c: 'a',deleted);Item(c: 'b',deleted)
*
* This functions merges the fragmented nodes together:
* Item(c: 'a',deleted);Item(c: 'b',deleted) -> Item(c: 'ab', deleted)
*
* TODO: The Tree implementation does not support deletions in-spot.
* This is why all deletions must be performed after the traversal.
*
*/
function defragmentItemContent (y) { function defragmentItemContent (y) {
const os = y.os; const os = y.os;
if (os.length < 2) { if (os.length < 2) {
@@ -13249,7 +13142,7 @@ async function initArrays (t, opts) {
result['array' + i] = y.define('array', Y$1.Array); result['array' + i] = y.define('array', Y$1.Array);
result['map' + i] = y.define('map', Y$1.Map); result['map' + i] = y.define('map', Y$1.Map);
result['xml' + i] = y.define('xml', Y$1.XmlElement); 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') { if (d.nodeName === 'HIDDEN') {
return null return null
} else { } else {
@@ -13370,7 +13263,7 @@ async function applyRandomTests (t, mods, iterations) {
return initInformation return initInformation
} }
var index$1 = function (str) { var index$1$1 = function (str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase(); return '%' + c.charCodeAt(0).toString(16).toUpperCase();
}); });
@@ -13556,7 +13449,7 @@ function parserForArrayFormat(opts) {
function encode(value, opts) { function encode(value, opts) {
if (opts.encode) { if (opts.encode) {
return opts.strict ? index$1(value) : encodeURIComponent(value); return opts.strict ? index$1$1(value) : encodeURIComponent(value);
} }
return value; return value;
@@ -13668,7 +13561,7 @@ var stringify = function (obj, opts) {
}).join('&') : ''; }).join('&') : '';
}; };
var index = { var index$2 = {
extract: extract, extract: extract,
parse: parse$1, parse: parse$1,
stringify: stringify stringify: stringify
@@ -13683,7 +13576,7 @@ const browserSupport =
function createTestLink (params) { function createTestLink (params) {
if (typeof location !== 'undefined') { if (typeof location !== 'undefined') {
var query = index.parse(location.search); var query = index$2.parse(location.search);
delete query.test; delete query.test;
delete query.seed; delete query.seed;
delete query.args; delete query.args;
@@ -13693,7 +13586,7 @@ function createTestLink (params) {
query[name] = params[name]; query[name] = params[name];
} }
} }
return location.protocol + '//' + location.host + location.pathname + '?' + index.stringify(query) + location.hash return location.protocol + '//' + location.host + location.pathname + '?' + index$2.stringify(query) + location.hash
} }
} }
@@ -13704,7 +13597,7 @@ class TestHandler {
this.repeatingRun = 0; this.repeatingRun = 0;
this.tests = {}; this.tests = {};
if (typeof location !== 'undefined') { if (typeof location !== 'undefined') {
this.opts = index.parse(location.search); this.opts = index$2.parse(location.search);
if (this.opts.case != null) { if (this.opts.case != null) {
this.opts.case = Number(this.opts.case); this.opts.case = Number(this.opts.case);
} }
@@ -13845,7 +13738,7 @@ function createCommonjsModule$1(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports; return module = { exports: {} }, fn(module, module.exports), module.exports;
} }
var isBrowser = typeof index !== 'undefined'; var isBrowser = typeof index$2 !== 'undefined';
var environment = { var environment = {
isBrowser: isBrowser isBrowser: isBrowser
@@ -18394,8 +18287,8 @@ var stacktraceGps = createCommonjsModule$1(function (module, exports) {
* @returns {String} original representation of the base64-encoded string. * @returns {String} original representation of the base64-encoded string.
*/ */
function _atob(b64str) { function _atob(b64str) {
if (typeof index !== 'undefined' && index.atob) { if (typeof index$2 !== 'undefined' && index$2.atob) {
return index.atob(b64str); return index$2.atob(b64str);
} else { } else {
throw new Error('You must supply a polyfill for window.atob in this environment'); throw new Error('You must supply a polyfill for window.atob in this environment');
} }
@@ -18905,7 +18798,7 @@ var stacktrace = createCommonjsModule$1(function (module, exports) {
})); }));
}); });
index.stacktrace = stacktrace; index$2.stacktrace = stacktrace;
function test (testDescription, ...args) { function test (testDescription, ...args) {
let location = stacktrace.getSync()[1]; let location = stacktrace.getSync()[1];
@@ -18914,6 +18807,9 @@ function test (testDescription, ...args) {
testHandler.register(testCase); testHandler.register(testCase);
} }
//# sourceMappingURL=cutest.mjs.map
test('set property', async function xml0 (t) { test('set property', async function xml0 (t) {
var { users, xml0, xml1 } = await initArrays(t, { users: 2 }); var { users, xml0, xml1 } = await initArrays(t, { users: 2 });
xml0.setAttribute('height', 10); xml0.setAttribute('height', 10);
@@ -19318,7 +19214,5 @@ test('y-xml: Random tests (1000)', async function xmlRandom1000 (t) {
await applyRandomTests(t, xmlTransactions, 1000); await applyRandomTests(t, xmlTransactions, 1000);
}); });
Object.defineProperty(exports, '__esModule', { value: true });
}))); })));
//# sourceMappingURL=y.test.js.map //# sourceMappingURL=y.test.js.map

File diff suppressed because one or more lines are too long