observablejson.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. JSONExt, JSONObject, JSONValue
  5. } from '@phosphor/coreutils';
  6. import {
  7. Message
  8. } from '@phosphor/messaging';
  9. import {
  10. IObservableMap, ObservableMap
  11. } from './observablemap';
  12. /**
  13. * An observable JSON value.
  14. */
  15. export
  16. interface IObservableJSON extends IObservableMap<JSONValue> {
  17. /**
  18. * Serialize the model to JSON.
  19. */
  20. toJSON(): JSONObject;
  21. }
  22. /**
  23. * The namespace for IObservableJSON related interfaces.
  24. */
  25. export
  26. namespace IObservableJSON {
  27. /**
  28. * A type alias for observable JSON changed args.
  29. */
  30. export
  31. type IChangedArgs = IObservableMap.IChangedArgs<JSONValue>;
  32. }
  33. /**
  34. * A concrete Observable map for JSON data.
  35. */
  36. export
  37. class ObservableJSON extends ObservableMap<JSONValue> {
  38. /**
  39. * Construct a new observable JSON object.
  40. */
  41. constructor(options: ObservableJSON.IOptions = {}) {
  42. super({
  43. itemCmp: JSONExt.deepEqual,
  44. values: options.values
  45. });
  46. }
  47. /**
  48. * Serialize the model to JSON.
  49. */
  50. toJSON(): JSONObject {
  51. let out: JSONObject = Object.create(null);
  52. for (let key of this.keys()) {
  53. let value = this.get(key);
  54. if (JSONExt.isPrimitive(value)) {
  55. out[key] = value;
  56. } else {
  57. out[key] = JSON.parse(JSON.stringify(value));
  58. }
  59. }
  60. return out;
  61. }
  62. }
  63. /**
  64. * The namespace for ObservableJSON static data.
  65. */
  66. export
  67. namespace ObservableJSON {
  68. /**
  69. * The options use to initialize an observable JSON object.
  70. */
  71. export
  72. interface IOptions {
  73. /**
  74. * The optional intitial value for the object.
  75. */
  76. values?: JSONObject;
  77. }
  78. /**
  79. * An observable JSON change message.
  80. */
  81. export
  82. class ChangeMessage extends Message {
  83. /**
  84. * Create a new metadata changed message.
  85. */
  86. constructor(args: IObservableJSON.IChangedArgs) {
  87. super('jsonvalue-changed');
  88. this.args = args;
  89. }
  90. /**
  91. * The arguments of the change.
  92. */
  93. readonly args: IObservableJSON.IChangedArgs;
  94. }
  95. }