1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 | 1× 725× 725× 507× 507× 1× 507× 507× 507× 507× 507× 507× 507× 507× 507× 22× 22× 480× 712× 22200× 638× 2× 2× 2× 2× 2× 2× 2630× 5× 2630× 2630× 2630× 2630× 2630× 83× 83× 83× 83× 83× 83× 15× 15× 15× 15× 15× 15× 1021× 1021× 1021× 1021× 1021× 1727× 4228× 834× 834× 831× 831× 710× 576× 710× 707× 710× 710× 710× 710× 710× 82× 82× 82× 82× 82× 82× 82× 82× 82× 78× 82× 82× 39× 39× 831× 831× 831× 6× 89× 89× 87× 87× 87× 23× 87× 161× 1246× 1246× 161× 3910× 3910× 3910× 3910× 218× 218× 218× 218× 218× 961× 51× 910× 236× 674× 961× 1160× 2630× 2630× 83× 83× 1021× 1021× 15× 15× 6× 6× 6× 3× 3× 3× 164× 10× 10× 10× 154× 1× 1× 1× | import { isEqual, isNil, isPlainObject, forEach, last, uuid, EventEmitter } from '../util' import PropertyIndex from './PropertyIndex' import AnnotationIndex from './AnnotationIndex' import ContainerAnnotationIndex from './ContainerAnnotationIndex' import DocumentChange from './DocumentChange' import PathEventProxy from './PathEventProxy' import IncrementalData from './IncrementalData' import DocumentNodeFactory from './DocumentNodeFactory' import Selection from './Selection' import PropertySelection from './PropertySelection' import ContainerSelection from './ContainerSelection' import NodeSelection from './NodeSelection' import CustomSelection from './CustomSelection' import Coordinate from './Coordinate' import { createNodeSelection } from './selectionHelpers' import JSONConverter from './JSONConverter' import ParentNodeHook from './ParentNodeHook' const converter = new JSONConverter() /** Basic implementation of a Document. @example ```js import { Document } from 'substance' class MyArticle extends Document { constructor(...args) { super(...args) this.addIndex('foo', FooIndex) } } ``` */ class Document extends EventEmitter { /** @param {DocumentSchema} schema The document schema. */ constructor(schema) { super() // HACK: to be able to inherit but not execute this ctor if (arguments[0] === 'SKIP') return this.__id__ = uuid() /* istanbul ignore next */ Iif (!schema) { throw new Error('A document needs a schema for reflection.') } this.schema = schema this.nodeFactory = new DocumentNodeFactory(this) this.data = new IncrementalData(schema, this.nodeFactory) // all by type this.addIndex('type', new PropertyIndex('type')) // special index for (property-scoped) annotations this.addIndex('annotations', new AnnotationIndex()) // TODO: these are only necessary if there is a container annotation // in the schema // special index for (container-scoped) annotations this.addIndex('container-annotations', new ContainerAnnotationIndex()) // change event proxies are triggered after a document change has been applied // before the regular document:changed event is fired. // They serve the purpose of making the event notification more efficient // In earlier days all observers such as node views where listening on the same event 'operation:applied'. // This did not scale with increasing number of nodes, as on every operation all listeners where notified. // The proxies filter the document change by interest and then only notify a small set of observers. // Example: NotifyByPath notifies only observers which are interested in changes to a certain path. this.eventProxies = { 'path': new PathEventProxy(this), } this.on('document:changed', this._updateEventProxies, this) // TODO: maybe we want to have a generalized concept for such low-level hooks // e.g. indexes are similar ParentNodeHook.register(this) } dispose() { this.off() this.data.off() } get id() { return this.__id__ } /** @returns {model/DocumentSchema} the document's schema. */ getSchema() { return this.schema } /** Check if this storage contains a node with given id. @returns {Boolean} `true` if a node with id exists, `false` otherwise. */ contains(id) { return this.data.contains(id) } /** Get a node or value via path. @param {String|String[]} path node id or path to property. @returns {DocumentNode|any|undefined} a Node instance, a value or undefined if not found. */ get(path, strict) { return this.data.get(path, strict) } /** @return {Object} A hash of {@link model/DocumentNode} instances. */ getNodes() { return this.data.getNodes() } /** Creates a context like a transaction for importing nodes. This is important in presence of cyclic dependencies. Indexes will not be updated during the import but will afterwards when all nodes are have been created. @private @param {Function} importer a `function(doc)`, where with `doc` is a `model/AbstractDocument` @example Consider the following example from our documentation generator: We want to have a member index, which keeps track of members of namespaces, modules, and classes. grouped by type, and in the case of classes, also grouped by 'instance' and 'class'. ``` ui - class - ui/Component ui/Component - class - method - mount - instance - method - render ``` To decide which grouping to apply, the parent type of a member needs to be considered. Using an incremental approach, this leads to the problem, that the parent must exist before the child. At the same time, e.g. when deserializing, the parent has already a field with all children ids. This cyclic dependency is best address, by turning off all listeners (such as indexes) until the data is consistent. */ import(importer) { try { this.data._stopIndexing() importer(this) this.data._startIndexing() } finally { this.data.queue = [] this.data._startIndexing() } } /** Create a node from the given data. @param {Object} plain node data. @return {DocumentNode} The created node. @example ```js doc.transaction(function(tx) { tx.create({ id: 'p1', type: 'paragraph', content: 'Hi I am a Substance paragraph.' }) }) ``` */ create(nodeData) { if (!nodeData.id) { nodeData.id = uuid(nodeData.type) } var op = this._create(nodeData) var change = new DocumentChange([op], {}, {}) change._extractInformation(this) this._notifyChangeListeners(change, { hidden: true }) return this.data.get(nodeData.id) } /** Delete the node with given id. @param {String} nodeId @returns {DocumentNode} The deleted node. @example ```js doc.transaction(function(tx) { tx.delete('p1') }) ``` */ delete(nodeId) { var node = this.get(nodeId) var op = this._delete(nodeId) var change = new DocumentChange([op], {}, {}) change._extractInformation(this) this._notifyChangeListeners(change, { hidden: true }) return node } /** Set a property to a new value. @param {String[]} property path @param {any} newValue @returns {DocumentNode} The deleted node. @example ```js doc.transaction(function(tx) { tx.set(['p1', 'content'], "Hello there! I'm a new paragraph.") }) ``` */ set(path, value) { var oldValue = this.get(path) var op = this._set(path, value) var change = new DocumentChange([op], {}, {}) change._extractInformation(this) this._notifyChangeListeners(change, { hidden: true }) return oldValue } /** Update a property incrementally. @param {Array} property path @param {Object} diff @returns {any} The value before applying the update. @example Inserting text into a string property: ``` doc.update(['p1', 'content'], { insert: {offset: 3, value: "fee"} }) ``` would turn "Foobar" into "Foofeebar". Deleting text from a string property: ``` doc.update(['p1', 'content'], { delete: {start: 0, end: 3} }) ``` would turn "Foobar" into "bar". Inserting into an array: ``` doc.update(['p1', 'content'], { insert: {offset: 2, value: 0} }) ``` would turn `[1,2,3,4]` into `[1,2,0,3,4]`. Deleting from an array: ``` doc.update(['body', 'nodes'], { delete: 2 }) ``` would turn `[1,2,3,4]` into `[1,2,4]`. */ update(path, diff) { var op = this._update(path, diff) var change = new DocumentChange([op], {}, {}) change._extractInformation(this) this._notifyChangeListeners(change, { hidden: true }) return op } /** Add a document index. @param {String} name @param {DocumentIndex} index */ addIndex(name, index) { return this.data.addIndex(name, index) } /** @param {String} name @returns {DocumentIndex} the node index with given name. */ getIndex(name) { return this.data.getIndex(name) } /** Creates a selection which is attached to this document. Every selection implementation provides its own parameter format which is basically a JSON representation. @param {model/Selection} sel An object describing the selection. @example Creating a PropertySelection: ```js doc.createSelection({ type: 'property', path: [ 'text1', 'content'], startOffset: 10, endOffset: 20, containerId: 'body' }) ``` Creating a ContainerSelection: ```js doc.createSelection({ type: 'container', containerId: 'body', startPath: [ 'p1', 'content'], startOffset: 10, endPath: [ 'p2', 'content'], endOffset: 20 }) ``` Creating a NullSelection: ```js doc.createSelection(null) ``` */ createSelection(data) { let sel if (isNil(data)) return Selection.nullSelection Iif (arguments.length !== 1 || !isPlainObject(data)) { throw new Error('Illegal argument: call createSelection({ type: ... }') } else { switch (data.type) { case 'property': { if (isNil(data.endOffset)) { data.endOffset = data.startOffset } if (!data.hasOwnProperty('reverse')) { Iif (data.startOffset>data.endOffset) { [data.startOffset, data.endOffset] = [data.endOffset, data.startOffset] data.reverse = !data.reverse } } // integrity checks: let text = this.get(data.path, 'strict') Iif (data.startOffset < 0 || data.startOffset > text.length) { throw new Error('Invalid startOffset: target property has length '+text.length+', given startOffset is ' + data.startOffset) } Iif (data.endOffset < 0 || data.endOffset > text.length) { throw new Error('Invalid startOffset: target property has length '+text.length+', given endOffset is ' + data.endOffset) } sel = new PropertySelection(data) break } case 'container': { let container = this.get(data.containerId, 'strict') Iif (!container) throw new Error('Can not create ContainerSelection: container "'+data.containerId+'" does not exist.') let start = this._normalizeCoor({ path: data.startPath, offset: data.startOffset}) let end = this._normalizeCoor({ path: data.endPath, offset: data.endOffset}) let startAddress = container.getAddress(start) let endAddress = container.getAddress(end) Iif (!startAddress) { throw new Error('Invalid arguments for ContainerSelection: ', start.toString()) } Iif (!endAddress) { throw new Error('Invalid arguments for ContainerSelection: ', end.toString()) } if (!data.hasOwnProperty('reverse')) { Iif (endAddress.isBefore(startAddress, 'strict')) { [start, end] = [end, start] data.reverse = true } } sel = new ContainerSelection(container.id, start.path, start.offset, end.path, end.offset, data.reverse, data.surfaceId) break } case 'node': { sel = createNodeSelection({ doc: this, nodeId: data.nodeId, mode: data.mode, containerId: data.containerId, reverse: data.reverse, surfaceId: data.surfaceId }) break } case 'custom': { sel = CustomSelection.fromJSON(data) break } default: throw new Error('Illegal selection type', data) } } Eif (!sel.isNull()) { sel.attach(this) } return sel } getEventProxy(name) { return this.eventProxies[name] } newInstance() { var DocumentClass = this.constructor return new DocumentClass(this.schema) } // useful in combination with paste transformation createSnippet() { var snippet = this.newInstance() var snippetContainer = snippet.create({ type: 'container', id: Document.SNIPPET_ID }) snippet.getContainer = function() { return snippetContainer } return snippet } _apply(documentChange) { forEach(documentChange.ops, function(op) { this.data.apply(op) this.emit('operation:applied', op) }.bind(this)) // extract aggregated information, such as which property has been affected etc. documentChange._extractInformation(this) } _notifyChangeListeners(change, info) { info = info || {} this.emit('document:changed', change, info, this) } _updateEventProxies(change, info) { forEach(this.eventProxies, function(proxy) { proxy.onDocumentChanged(change, info, this) }.bind(this)) } createFromDocument(doc) { let nodes = doc.getNodes() let annotations = [] let contentNodes = [] let containers = [] forEach(nodes, (node) => { if (node._isAnnotation) { annotations.push(node) } else if (node._isContainer) { containers.push(node) } else { contentNodes.push(node) } }) contentNodes.concat(annotations).concat(containers).forEach(n=>this.create(n)) } /** Convert to JSON. @returns {Object} Plain content. */ toJSON() { return converter.exportDocument(this) } getAnnotations(path) { return this.getIndex('annotations').get(path) } _create(nodeData) { var op = this.data.create(nodeData) return op } _delete(nodeId) { var op = this.data.delete(nodeId) return op } _update(path, diff) { var op = this.data.update(path, diff) return op } _set(path, value) { var op = this.data.set(path, value) return op } // NOTE: this is still here because DOMSelection is using it _createSelectionFromRange(range) { Iif (!range) return Selection.nullSelection let inOneNode = isEqual(range.start.path, range.end.path) if (inOneNode) { Iif (range.start.isNodeCoordinate()) { // ATTENTION: we only create full NodeSelections // when mapping from the DOM to Model return new NodeSelection(range.containerId, range.start.getNodeId(), mode, range.reverse, range.surfaceId) return new NodeSelection(range.containerId, range.start.getNodeId(), 'full', range.reverse, range.surfaceId) } else { return this.createSelection({ type: 'property', path: range.start.path, startOffset: range.start.offset, endOffset: range.end.offset, reverse: range.reverse, containerId: range.containerId, surfaceId: range.surfaceId }) } } else { return this.createSelection({ type: 'container', startPath: range.start.path, startOffset: range.start.offset, endPath: range.end.path, endOffset: range.end.offset, reverse: range.reverse, containerId: range.containerId, surfaceId: range.surfaceId }) } } _normalizeCoor({ path, offset }) { // NOTE: normalizing so that a node coordinate is used only for 'isolated nodes' if (path.length === 1) { let node = this.get(path[0]).getRoot() Eif (node.isText()) { // console.warn("DEPRECATED: don't use node coordinates for TextNodes. Use selectionHelpers instead to set cursor at first or last position conveniently.") return new Coordinate(node.getTextPath(), offset === 0 ? 0 : node.getLength()) } else if (node.isList()) { // console.warn("DEPRECATED: don't use node coordinates for ListNodes. Use selectionHelpers instead to set cursor at first or last position conveniently.") if (offset === 0) { let item = node.getItemAt(0) return new Coordinate(item.getTextPath(), 0) } else { let item = this.get(last(node.items)) return new Coordinate(item.getTextPath(), item.getLength()) } } } return new Coordinate(path, offset) } } Document.prototype._isDocument = true // used by transforms copy, paste // and by ClipboardImporter/Exporter Document.SNIPPET_ID = "snippet" Document.TEXT_SNIPPET_ID = "text-snippet" export default Document |