Node.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. var applyReviver = require('../doc/applyReviver.js');
  3. var identity = require('./identity.js');
  4. var toJS = require('./toJS.js');
  5. class NodeBase {
  6. constructor(type) {
  7. Object.defineProperty(this, identity.NODE_TYPE, { value: type });
  8. }
  9. /** Create a copy of this node. */
  10. clone() {
  11. const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
  12. if (this.range)
  13. copy.range = this.range.slice();
  14. return copy;
  15. }
  16. /** A plain JavaScript representation of this node. */
  17. toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
  18. if (!identity.isDocument(doc))
  19. throw new TypeError('A document argument is required');
  20. const ctx = {
  21. anchors: new Map(),
  22. doc,
  23. keep: true,
  24. mapAsMap: mapAsMap === true,
  25. mapKeyWarned: false,
  26. maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
  27. };
  28. const res = toJS.toJS(this, '', ctx);
  29. if (typeof onAnchor === 'function')
  30. for (const { count, res } of ctx.anchors.values())
  31. onAnchor(res, count);
  32. return typeof reviver === 'function'
  33. ? applyReviver.applyReviver(reviver, { '': res }, '', res)
  34. : res;
  35. }
  36. }
  37. exports.NodeBase = NodeBase;