deltafactory.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/delta/deltafactory
  7. */
  8. import CKEditorError from '../../../utils/ckeditorerror.js';
  9. import OperationFactory from '../operation/operationfactory.js';
  10. const deserializers = new Map();
  11. /**
  12. * A factory class for creating operations.
  13. *
  14. * Delta is a single, from the user action point of view, change in the editable document, like insert, split or
  15. * rename element. Delta is composed of operations, which are unit changes needed to be done to execute user action.
  16. *
  17. * Multiple deltas are grouped into a single {@link module:engine/model/batch~Batch}.
  18. */
  19. export default class DeltaFactory {
  20. /**
  21. * Creates InsertDelta from deserialized object, i.e. from parsed JSON string.
  22. *
  23. * @param {Object} json
  24. * @param {module:engine/model/document~Document} doc Document on which this delta will be applied.
  25. * @returns {module:engine/model/delta/insertdelta~InsertDelta}
  26. */
  27. static fromJSON( json, doc ) {
  28. if ( !deserializers.has( json.__className ) ) {
  29. /**
  30. * This delta has no defined deserializer.
  31. *
  32. * @error delta-fromjson-no-deserializer
  33. * @param {String} name
  34. */
  35. throw new CKEditorError(
  36. 'delta-fromjson-no-deserializer: This delta has no defined deserializer',
  37. { name: json.__className }
  38. );
  39. }
  40. let Delta = deserializers.get( json.__className );
  41. let delta = new Delta();
  42. for ( let operation of json.operations ) {
  43. delta.addOperation( OperationFactory.fromJSON( operation, doc ) );
  44. }
  45. return delta;
  46. }
  47. /**
  48. * Registers a class for delta factory.
  49. *
  50. * @param {Function} Delta A delta class to register.
  51. */
  52. static register( Delta ) {
  53. deserializers.set( Delta.className, Delta );
  54. }
  55. }