@jupyterlab/apputils#ReactWidget TypeScript Examples

The following examples show how to use @jupyterlab/apputils#ReactWidget. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: comments_widget.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
export class CommentsWidget extends ReactWidget {
  constructor(private context: Context) {
    super();
    this.addClass('comments-widget');
  }

  render() {
    return (
      <div className={localStyles.root}>
        <CommentsComponent context={this.context} />
      </div>
    );
  }
}
Example #2
Source File: new_comment_dialog.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
export class NewCommentDialogWidget extends ReactWidget {
  context: Context;
  selection: object;

  constructor(selection: object, context: Context) {
    super();
    this.selection = selection;
    this.context = context;
  }
  render() {
    const serverRoot = getServerRoot();
    const currWidget = this.context.labShell.currentWidget;
    const filePath = this.context.docManager.contextForWidget(currWidget).path;
    return (
      <DialogComponent
        selection={this.selection}
        serverRoot={serverRoot}
        commentType="detached"
        currFilePath={filePath}
      />
    );
  }
}
Example #3
Source File: panel.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
/** Widget to be registered in the left-side panel. */
export class GitSyncWidget extends ReactWidget {
  id = 'gitsync';
  private visibleSignal = new Signal<GitSyncWidget, boolean>(this);

  constructor(private readonly service: GitSyncService) {
    super();
    this.title.iconClass = 'jp-Icon jp-Icon-20 jp-git-icon';
    this.title.caption = 'Git Sync Widget';
  }

  onAfterHide() {
    this.visibleSignal.emit(false);
  }

  onAfterShow() {
    this.visibleSignal.emit(true);
  }

  render() {
    return (
      <UseSignal signal={this.visibleSignal}>
        {isVisible => <Panel service={this.service} />}
      </UseSignal>
    );
  }
}
Example #4
Source File: widget_manager.ts    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
launchWidgetForId(
    widgetType: new (...args: any[]) => ReactWidget,
    id: string,
    ...args: any[]
  ) {
    // Get the widget associated with a dataset/resource id, or create one
    // if it doesn't exist yet and activate it
    let widget = this.widgets[id];
    if (!widget || widget.isDisposed) {
      const content = new widgetType(...args);
      widget = new MainAreaWidget({ content });
      widget.disposed.connect(() => {
        if (this.widgets[id] === widget) {
          delete this.widgets[id];
        }
      });
      this.widgets[id] = widget;
    }
    if (!widget.isAttached) {
      this.app.shell.add(widget, 'main');
    }
    this.app.shell.activateById(widget.id);
  }
Example #5
Source File: logStatus.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export class LogStatus extends ReactWidget {

  private connected: boolean = false;
  private ros: ROSLIB.Ros = null;
  private url: string;
  
  constructor(ros: ROSLIB.Ros, url: string) {
    super();
    this.addClass('jp-LogConsole-toolbarLogLevel');
    this.ros = ros;
    this.url = url;
  }

  private connect = (): void => this.ros?.connect(this.url);
  private disconnect = (): void => this.ros?.close();

  public setConnected = (connected: boolean) => {
    this.connected = connected;
    this.update();
  }

  render(): JSX.Element {
    return (
      <div className="main">
        {
          this.connected ?
          <div onClick={this.disconnect} className="ok"/> :
          <div onClick={this.connect} className="ko"/>
        }
      </div>
    );
  }
}
Example #6
Source File: settings.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * A SettingsWidget Lumino Widget that wraps a SettingsComponent.
 */
export default class SettingsWidget extends ReactWidget {
  private settings: ISettingRegistry;
  private idSettings: string;
  /**
   * Constructs a new Settings.
   */
  constructor(settings: ISettingRegistry, idSettings: string) {
    super();
    this.settings = settings;
    this.idSettings = idSettings;
    this.addClass('jp-ReactWidget');
  }

  render(): JSX.Element {
    return <SettingsComponent settings={this.settings} idSettings={this.idSettings}/>;
  }
}
Example #7
Source File: jupyterlab-sparkmonitor.ts    From sparkmonitor with Apache License 2.0 6 votes vote down vote up
createCellReactElements() {
        const createElementIfNotExists = (cellModel: ICellModel) => {
            if (cellModel.type === 'code') {
                const codeCell = this.notebookPanel.content.widgets.find((widget) => widget.model === cellModel);
                if (codeCell && !codeCell.node.querySelector('.sparkMonitorCellRoot')) {
                    const widget = ReactWidget.create(
                        React.createElement(CellWidget, {
                            notebookId: this.notebookPanel.id,
                            cellId: cellModel.id,
                        }),
                    );
                    widget.addClass('SparkMonitorCellWidget');

                    (codeCell.layout as PanelLayout).insertWidget(
                        2, // Insert the element below the input area based on position/index
                        widget,
                    );
                    codeCell.update();
                }
            }
        };

        const cells = this.notebookPanel.context.model.cells;

        // Ensure new cells created have a monitoring display
        cells.changed.connect((cells, changed) => {
            for (let i = 0; i < cells.length; i += 1) {
                createElementIfNotExists(cells.get(i));
            }
        });

        // Do it the first time
        for (let i = 0; i < cells.length; i += 1) {
            createElementIfNotExists(cells.get(i));
        }
    }
Example #8
Source File: widget.tsx    From ipyflex with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
class ReactWidgetWrapper extends ReactWidget {
  constructor(
    send_msg: any,
    model: any,
    style: any = {},
    editable = true,
    header = false
  ) {
    super();
    this._send_msg = send_msg;
    this._model = model;
    this._style = style;
    this._editable = editable;
    this._header = header;
  }

  onResize = (msg: any) => {
    window.dispatchEvent(new Event('resize'));
  };

  render() {
    return (
      <FlexWidget
        style={this._style}
        send_msg={this._send_msg}
        model={this._model}
        editable={this._editable}
        header={this._header}
      />
    );
  }
  private _send_msg: any;
  private _model: any;
  private _style: any;
  private _editable: boolean;
  private _header: boolean | IDict;
}
Example #9
Source File: logConsolePanel.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export class LogConsolePanel extends ReactWidget {
  
  private level: number;
  private topic: string;
  private logs: RosLog[];

  constructor() {
    super();
    this.addClass('jp-LogConsolePanel');

    this.level = 1;
    this.topic = '/all';
    this.logs = [];
  }

  public setLevel = (level: number): void => {
    this.level = level;
    this.update();
  }

  public setTopic = (topic: string): void => {
    this.topic = topic;
    this.update();
  }

  public setLogs = (logs: RosLog[]): void => {
    this.logs = logs;
    this.update();
  }

  render(): JSX.Element {
    const logsLevel: JSX.Element[] = [];

    for(let i=0; i<this.logs.length; i++) {
      if (this.topic == '/all' || this.logs[i].name == this.topic) {
        
        if (this.logs[i].level == 0) {
          logsLevel.push(<Checkpoint key={UUID.uuid4()} log={this.logs[i]}/>);
        
        } else if (this.logs[i].level >= this.level) {
          logsLevel.push(<Log key={UUID.uuid4()} log={this.logs[i]}/>);
        }
      }
    }

    return (
      <div className="lm-Widget p-Widget jp-Scrolling lm-StackedPanel-child p-StackedPanel-child">
        <div className="lm-Widget p-Widget jp-OutputArea">
          { logsLevel }
        </div>
      </div>
    );
  }
}
Example #10
Source File: logLevelSwitcher.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export class LogLevelSwitcher extends ReactWidget {
  
  private logConsolePanel: LogConsolePanel;
  private level: number;

  constructor(logConsolePanel: LogConsolePanel) {
    super();
    this.addClass('jp-LogConsole-toolbarLogLevel');
    this.logConsolePanel = logConsolePanel;
    this.level = 1;
  }

  /**
   * Handle `change` events for the HTMLSelect component.
   */
  handleChange = (event: React.ChangeEvent<HTMLSelectElement>): void => {
    this.level = event.target.value as any;
    this.logConsolePanel.setLevel(this.level);
    this.update();
  };

  /**
   * Handle `keydown` events for the HTMLSelect component.
   */
  handleKeyDown = (event: React.KeyboardEvent): void => {
    if (event.keyCode === 13) this.logConsolePanel.activate();
    this.update();
  };

  render(): JSX.Element {
    return (
      <>
        <label>Level:</label>
        <HTMLSelect
          className="jp-LogConsole-toolbarLogLevelDropdown"
          onChange={this.handleChange}
          onKeyDown={this.handleKeyDown}
          value={this.level}
          aria-label="Log level"
          options={[
            { label: "Debug", value: 1 },
            { label: "Info", value: 2 },
            { label: "Warning", value: 4 },
            { label: "Error", value: 8 },
            { label: "Critical", value: 16 }
          ]}
        />
      </>
    );
  }
}
Example #11
Source File: logNodeSwitcher.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export class LogNodeSwitcher extends ReactWidget {
  
  private logConsolePanel: LogConsolePanel = null;
  private topic: string;
  private topics: string[];

  constructor(logConsolePanel: LogConsolePanel) {
    super();
    this.addClass('jp-LogConsole-toolbarLogLevel');
    this.logConsolePanel = logConsolePanel;
    this.topic = '/all';
    this.topics = ['/all'];
  }

  private handleChange = (event: React.ChangeEvent<HTMLSelectElement>): void => {
    this.topic = event.target.value;
    this.logConsolePanel.setTopic(this.topic);
    this.update();
  };

  private handleKeyDown = (event: React.KeyboardEvent): void => {
    if (event.keyCode === 13) this.logConsolePanel.activate();
  };

  public refreshNodes = (nodes: string[]): void => {
    this.topics = nodes;
    this.topics.unshift('/all');
    this.update();
  }

  public setNode = (node: string): void => {
    if (!this.topics.includes(node)) this.topics.push(node);
    this.update();
  }

  render(): JSX.Element {
    const topics = this.topics.map(value => { return {label: value.substring(1), value}; });

    return (
      <>
        <label>Node:</label>
        <HTMLSelect
          className="jp-LogConsole-toolbarLogLevelDropdown"
          onChange={this.handleChange}
          onKeyDown={this.handleKeyDown}
          value={this.topic}
          aria-label="Log level"
          options={topics}
        />
      </>
    );
  }
}
Example #12
Source File: dashboard.tsx    From jupyterlab-interactive-dashboard-editor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
export class DashboardModeSwitcher extends ReactWidget {
    constructor(dashboard: Dashboard) {
      super();
      this.addClass(TOOLBAR_MODE_SWITCHER_CLASS);
      this._dashboard = dashboard;

      if (dashboard.model) {
        this.update();
      }

      dashboard.model.stateChanged.connect((_sender, change) => {
        if (change.name === 'mode') {
          this.update();
        }
      }, this);
    }

    private _handleChange(
      that: DashboardModeSwitcher
    ): (event: React.ChangeEvent<HTMLSelectElement>) => void {
      return (event: React.ChangeEvent<HTMLSelectElement>): void => {
        that.dashboard.model.mode = event.target.value as Dashboard.Mode;
      };
    }

    render(): JSX.Element {
      const value = this._dashboard.model.mode;
      return (
        <HTMLSelect
          className={TOOLBAR_SELECT_CLASS}
          onChange={this._handleChange(this)}
          value={value}
          aria-label={'Mode'}
        >
          <option value="present">Present</option>
          {/* <option value="free-edit">Free Layout</option> */}
          <option value="grid-edit">Edit</option>
        </HTMLSelect>
      );
    }

    get dashboard(): Dashboard {
      return this._dashboard;
    }

    private _dashboard: Dashboard;
  }
Example #13
Source File: bagPanel.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
export default class BagPanel extends ReactWidget {
  private _model: BagModel = null;

  private _isLoading = true;
  private _isTypesVisible = false;
  private _isTopicsVisible = false;
  
  constructor(model: BagModel){
    super();
    this._model = model;

    this._model.stateChanged.connect(this._modelChanged, this);
    this._model.statusChanged.connect(this._statusChanged, this);

    this._model.info();
  }

  dispose() {
    this._model.session?.dispose();
    Signal.clearData(this);
    super.dispose();
  }

  get model(): BagModel { return this._model; }

  private _modelChanged(): void {
    this._isLoading = false;
    this.update();
  }

  private _statusChanged(sender: BagModel, status: string): void {
    if (status == "loading") {
      this._isLoading = true;
    }

    this.update();
  }

  private _showTypes(hide: boolean): void {
    if (hide) this._isTypesVisible = !this._isTypesVisible;
    else this._isTypesVisible = false;
    this.update();
  }

  private _showTopics(hide: boolean): void {
    if (hide) this._isTopicsVisible = !this._isTopicsVisible;
    else this._isTopicsVisible = false;
    this.update();
  }

  render(): JSX.Element {
    if (this._model?.error) {
      const body = document.createElement('div');
      renderText({host: body, sanitizer: defaultSanitizer, source: this._model?.error });

      showDialog({
        title: "ERROR Bag: " + this._model.session.name,
        body: <div className=".jp-RenderedText" dangerouslySetInnerHTML={{ __html: body.innerHTML }} />,
        buttons: [ Dialog.okButton() ]
      });
    }

    return (
      <div className="bagPanel">
        { this._isLoading ?
            <div className="loader"> <div className="lds-ring"><div></div><div></div><div></div><div></div></div> </div>
          :
            <div className="bag">
              <div>Path: {this._model.bag?.path}</div>
              <div>Version: {this._model.bag?.version}</div>
              <div>Duration: {this._model.bag?.duration}</div>
              <div>Start: {this._model.bag?.start}</div>
              <div>End: {this._model.bag?.end}</div>
              <div>Size: {this._model.bag?.size}</div>
              <div>Messages: {this._model.bag?.messages}</div>
              <div>Compresion: {this._model.bag?.compression}</div>
              
              <div onClick={()=>{ this._showTypes(true); }}>
                Types: { !this._isTypesVisible &&
                  <runIcon.react tag="span" top="5px" width="14px" height="14px" />
                }
              </div>
              { this._isTypesVisible && 
                <table onClick={() => {this._showTypes(false);}} style={{paddingLeft: "15px"}}>
                  <tbody>
                    {this._model.bag?.types.map( type => {
                      return (<tr key={type.type}><td>{type.type}</td><td>{type.hash}</td></tr>);
                    })}
                  </tbody>
                </table>
              }

              <div onClick={() => {this._showTopics(true);}}>
                Topics: { !this._isTopicsVisible &&
                  <runIcon.react tag="span" top="5px" width="14px" height="14px" />
                }
              </div>
              
              { this._isTopicsVisible &&
                <table onClick={() => {this._showTopics(false);}} style={{paddingLeft: "15px"}}>
                  <tbody>
                    <tr><th>Topic</th><th>Message type</th><th>Message count</th><th>Connections</th><th>Frequency</th></tr>
                    {this._model.bag?.topics?.map( topic => {
                      return (<tr key={topic.topic}><td>{topic.topic}</td><td>{topic.msg_type}</td><td>{topic.message_count}</td><td>{topic.connections}</td><td>{topic.frequency}</td></tr>);
                    })}
                  </tbody>
                </table>
              }
            </div>
        }
      </div>
    );
  }
}
Example #14
Source File: status.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
export default class StatusLaunch extends ReactWidget {
  private paths: string[] = null;
  private ws: WebSocket = null;

  constructor() {
    super();
    this.node.title = 'Launch status.';
    this.addClass('jp-ReactWidget');

    this.paths = [];
    const server = ServerConnection.makeSettings();
    const url = URLExt.join(server.wsUrl, 'ros/launch');
    this.ws = new WebSocket(url);
    this.ws.onopen = this.onOpen;
    this.ws.onmessage = this.onMessage;
    this.ws.onerror = this.onError;
    this.ws.onclose = this.onClose;
  }

  onOpen = (event) => { } // console.log(event); }
  onError = (event) => { console.error(event); }
  onClose = (event) => { } // console.log(event); }
  onMessage = (message) => {
    const msg = JSON.parse(message.data);
    const body = document.createElement('div');
    
    switch (msg.code) {
      case 0: this.paths = msg.paths; break;
      case 1: this.paths.push(msg.path); break;
      case 2:
        renderText({host: body, sanitizer: defaultSanitizer, source: msg.msg });
        showDialog({
          title: "WARNING: " + msg.path,
          body: <div className=".jp-RenderedText" dangerouslySetInnerHTML={{ __html: body.innerHTML }}></div>,
          buttons: [ Dialog.okButton() ]
        });
        break;
      case 3:
      case 4:
        var index = this.paths.indexOf(msg.path);
        if (index !== -1) this.paths.splice(index, 1);

        renderText({host: body, sanitizer: defaultSanitizer, source: msg.msg });
        showDialog({
          title: (msg.code == 3 ? "FINISHED: " : "ERROR: " ) + msg.path,
          body: <div className=".jp-RenderedText" dangerouslySetInnerHTML={{ __html: body.innerHTML }}></div>,
          buttons: [ Dialog.okButton() ]
        });
        break;
      
      default:
        break;
    }
    this.update();
  }

  launch = (path) => {
    this.ws.send( JSON.stringify({ cmd: 'start', path }) );
  }

  toggle = (path) => {
    showDialog({
      title: path,
      body: <pre className=".jp-RenderedText">This execution will be stoped. Are you sure?</pre>,
      buttons: [ Dialog.okButton(), Dialog.cancelButton() ]
    }).then(res => {
      if (res.button.label != "OK") return;
      this.ws.send( JSON.stringify({ cmd: 'stop', path }) );

    }).catch( e => console.log(e) );
  }
  
  render(): JSX.Element {
    return (
      <a href="#" className="main">
        {
          this.paths.map( (path, i) => {
            return (
              <span key={i} style={{ margin: '3px' }} onClick={() => this.toggle(path)}>
                { path.split('/').pop() }
              </span>
            );
          })
        }
      </a>
    );
  }
}
Example #15
Source File: status.tsx    From jupyterlab-ros with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
export default class StatusMaster extends ReactWidget {
  private ws: WebSocket = null;
  private status: boolean = false;

  constructor() {
    super();
    this.node.title = "ROS Master";
    this.addClass('jp-ReactWidget');
    
    const server = ServerConnection.makeSettings();
    const url = URLExt.join(server.wsUrl, 'ros/master');
    this.ws = new WebSocket(url);
    this.ws.onopen = this.onOpen;
    this.ws.onmessage = this.onMessage;
    this.ws.onerror = this.onError;
    this.ws.onclose = this.onClose;
    this.status = false;
  }

  dispose = () => {
    console.log("disposed");
    this.ws.close();
    this.ws = null;
  }

  onOpen = (msg) => { this.ws.send(JSON.stringify({ cmd: "start" })); }
  onError = (msg) => console.error(msg);
  onClose = (msg) => {}
  onMessage = (message) => {
    const msg = JSON.parse(message.data);
    
    if (msg['error']) {
      const body = document.createElement('div');
      renderText({host: body, sanitizer: defaultSanitizer, source: msg['error'] });

      showDialog({
        title: "Master: WARNING",
        body: <div className=".jp-RenderedText" dangerouslySetInnerHTML={{ __html: body.innerHTML }} />,
        buttons: [ Dialog.okButton() ]
      });

    } else if (msg['output']) {
      const body = document.createElement('div');
      renderText({host: body, sanitizer: defaultSanitizer, source: msg['output'] });

      showDialog({
        title: "Master FINNISHED",
        body: <div className=".jp-RenderedText" dangerouslySetInnerHTML={{ __html: body.innerHTML }} />,
        buttons: [ Dialog.okButton() ]
      });
    }

    this.status = msg['status'];
    this.update();
  }

  start = () => {
    showDialog({
      title: "Master",
      body: <pre className=".jp-RenderedText">Do you want to START ROS Master?</pre>,
      buttons: [ Dialog.okButton(), Dialog.cancelButton() ]
    }).then(res => {
      if (res.button.label != "OK") return;
      this.ws.send(JSON.stringify({ cmd: "start" }));
    }).catch( e => console.log(e) );
  }

  stop = () => {
    showDialog({
      title: "Master",
      body: <pre className=".jp-RenderedText">Do you want to STOP ROS Master?</pre>,
      buttons: [ Dialog.okButton(), Dialog.cancelButton() ]
    }).then(res => {
      if (res.button.label != "OK") return;
      this.ws.send(JSON.stringify({ cmd: "stop" }));
    }).catch( e => console.log(e) );
  }

  toggle = () => {
    if (this.status == false ) this.start();
    else this.stop();
  }
  
  render(): JSX.Element {
    return (
      <a href="#" onClick={this.toggle} className="main">
        <div className="ros-logo"/>
        { this.status ?
            <div className="ok"/>
          :
            <div className="ko"/>
        }
      </a>
    );
  }
}