root.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict'
  2. let Container = require('./container')
  3. let LazyResult, Processor
  4. class Root extends Container {
  5. constructor(defaults) {
  6. super(defaults)
  7. this.type = 'root'
  8. if (!this.nodes) this.nodes = []
  9. }
  10. normalize(child, sample, type) {
  11. let keepBefore = new Set()
  12. for (let node of Array.isArray(child) ? child : [child]) {
  13. if (
  14. node &&
  15. typeof node === 'object' &&
  16. !node.parent &&
  17. node.raws &&
  18. typeof node.raws.before !== 'undefined'
  19. ) {
  20. keepBefore.add(node.raws)
  21. }
  22. }
  23. let nodes = super.normalize(child)
  24. if (sample) {
  25. if (type === 'prepend') {
  26. if (this.nodes.length > 1) {
  27. sample.raws.before = this.nodes[1].raws.before
  28. } else {
  29. delete sample.raws.before
  30. }
  31. } else if (this.first !== sample) {
  32. for (let node of nodes) {
  33. if (!keepBefore.has(node.raws)) {
  34. node.raws.before = sample.raws.before
  35. }
  36. }
  37. }
  38. }
  39. return nodes
  40. }
  41. removeChild(child, ignore) {
  42. let index = this.index(child)
  43. if (!ignore && index === 0 && this.nodes.length > 1) {
  44. this.nodes[1].raws.before = this.nodes[index].raws.before
  45. }
  46. return super.removeChild(child)
  47. }
  48. toResult(opts = {}) {
  49. let lazy = new LazyResult(new Processor(), this, opts)
  50. return lazy.stringify()
  51. }
  52. }
  53. Root.registerLazyResult = dependant => {
  54. LazyResult = dependant
  55. }
  56. Root.registerProcessor = dependant => {
  57. Processor = dependant
  58. }
  59. module.exports = Root
  60. Root.default = Root
  61. Container.registerRoot(Root)