Node.js 1.3 KB

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