11import { MapChange } from '@jupyter/ydoc' ;
2+ import { Kernel } from '@jupyterlab/services' ;
23import { JSONExt , JSONObject , PromiseDelegate } from '@lumino/coreutils' ;
34import { ISignal , Signal } from '@lumino/signaling' ;
45import * as Y from 'yjs' ;
56
67import type { Awareness } from 'y-protocols/awareness' ;
7- import { IJupyterYDoc , IJupyterYModel } from './types' ;
8+ import { IJupyterYDoc , IJupyterYModel , IYCommProvider } from './types' ;
89
910export class JupyterYModel implements IJupyterYModel {
1011 constructor ( commMetadata : { [ key : string ] : any } ) {
@@ -57,6 +58,41 @@ export class JupyterYModel implements IJupyterYModel {
5758 return undefined ;
5859 }
5960
61+ /**
62+ * The raw comm channel backing this model, available once the widget
63+ * manager has wired up the comm provider.
64+ */
65+ get comm ( ) : Kernel . IComm | undefined {
66+ return this . _commProvider ?. comm ;
67+ }
68+
69+ /**
70+ * Fires when a custom (non Y-protocol) message is received over the comm.
71+ */
72+ get messageReceived ( ) : ISignal < IJupyterYModel , JSONObject > {
73+ return this . _messageReceived ;
74+ }
75+
76+ /**
77+ * Send a custom message to the kernel over the comm.
78+ */
79+ sendMessage ( data : JSONObject ) : void {
80+ this . _commProvider ?. sendMessage ( data ) ;
81+ }
82+
83+ /**
84+ * Wire the model to its comm provider. Called by the widget manager once
85+ * the comm is open; relays custom comm messages through `messageReceived`.
86+ */
87+ setCommProvider ( provider : IYCommProvider ) : void {
88+ this . _commProvider = provider ;
89+ provider . messageReceived . connect ( this . _onCommMessage , this ) ;
90+ }
91+
92+ private _onCommMessage = ( _ : IYCommProvider , data : JSONObject ) : void => {
93+ this . _messageReceived . emit ( data ) ;
94+ } ;
95+
6096 protected async initialize ( commMetadata : { [ key : string ] : any } ) {
6197 this . ydoc = this . ydocFactory ( commMetadata ) ;
6298 this . sharedModel = new JupyterYDoc ( commMetadata , this . _ydoc ) ;
@@ -71,6 +107,8 @@ export class JupyterYModel implements IJupyterYModel {
71107 return ;
72108 }
73109 this . _isDisposed = true ;
110+ this . _commProvider ?. messageReceived . disconnect ( this . _onCommMessage , this ) ;
111+ this . _commProvider ?. dispose ( ) ;
74112 this . _sharedModel . dispose ( ) ;
75113 this . _disposed . emit ( ) ;
76114 Signal . clearData ( this ) ;
@@ -89,6 +127,9 @@ export class JupyterYModel implements IJupyterYModel {
89127 private _yModelName : string ;
90128 private _sharedModel : IJupyterYDoc ;
91129
130+ private _commProvider ?: IYCommProvider ;
131+ private _messageReceived = new Signal < IJupyterYModel , JSONObject > ( this ) ;
132+
92133 private _isDisposed = false ;
93134
94135 private _ready : PromiseDelegate < void > = new PromiseDelegate < void > ( ) ;
0 commit comments