root.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 nodes = super.normalize(child)
  12. if (sample) {
  13. if (type === 'prepend') {
  14. if (this.nodes.length > 1) {
  15. sample.raws.before = this.nodes[1].raws.before
  16. } else {
  17. delete sample.raws.before
  18. }
  19. } else if (this.first !== sample) {
  20. for (let node of nodes) {
  21. node.raws.before = sample.raws.before
  22. }
  23. }
  24. }
  25. return nodes
  26. }
  27. removeChild(child, ignore) {
  28. let index = this.index(child)
  29. if (!ignore && index === 0 && this.nodes.length > 1) {
  30. this.nodes[1].raws.before = this.nodes[index].raws.before
  31. }
  32. return super.removeChild(child)
  33. }
  34. toResult(opts = {}) {
  35. let lazy = new LazyResult(new Processor(), this, opts)
  36. return lazy.stringify()
  37. }
  38. }
  39. Root.registerLazyResult = dependant => {
  40. LazyResult = dependant
  41. }
  42. Root.registerProcessor = dependant => {
  43. Processor = dependant
  44. }
  45. module.exports = Root
  46. Root.default = Root
  47. Container.registerRoot(Root)