position.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. CKEDITOR.define( function() {
  7. /**
  8. * Position is always before of after a node.
  9. * See {@link #position} property for more information.
  10. *
  11. * @class document.Position
  12. */
  13. class Position {
  14. /**
  15. * Create a position.
  16. *
  17. * @param {document.node} node Node the position is next to.
  18. * @param {Number} position Possible options: Position.BEFORE or Position.AFTER
  19. */
  20. constructor( node, position ) {
  21. /**
  22. * Position of the node it the tree. For example:
  23. *
  24. * root Before: [] After: []
  25. * |- p Before: [ 0 ] After: [ 1 ]
  26. * |- ul Before: [ 1 ] After: [ 2 ]
  27. * |- li Before: [ 1, 0 ] After: [ 1, 1 ]
  28. * | |- f Before: [ 1, 0, 0 ] After: [ 1, 0, 1 ]
  29. * | |- o Before: [ 1, 0, 1 ] After: [ 1, 0, 2 ]
  30. * | |- o Before: [ 1, 0, 2 ] After: [ 1, 0, 3 ]
  31. * |- li Before: [ 1, 1 ] After: [ 1, 2 ]
  32. * |- b Before: [ 1, 1, 0 ] After: [ 1, 1, 1 ]
  33. * |- a Before: [ 1, 1, 1 ] After: [ 1, 1, 2 ]
  34. * |- r Before: [ 1, 1, 2 ] After: [ 1, 1, 3 ]
  35. *
  36. * @type {Array}
  37. */
  38. this.position = [];
  39. var parent = node.parent;
  40. while ( parent && parent.parent ) {
  41. this.position.unshift( parent.positionInParent );
  42. parent = parent.parent;
  43. }
  44. // Root have position [].
  45. if ( node.parent ) {
  46. if ( position === Position.BEFORE ) {
  47. this.position.push( node.positionInParent );
  48. } else {
  49. this.position.push( node.positionInParent + 1 );
  50. }
  51. }
  52. }
  53. }
  54. Position.BEFORE = -1;
  55. Position.AFTER = 1;
  56. return Position;
  57. } );