observablejson.ts 2.0 KB

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