lit#render TypeScript Examples

The following examples show how to use lit#render. 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: opc-provider.ts    From one-platform with MIT License 6 votes vote down vote up
private injectMenuDrawer() {
    // check
    if (!this.opcMenuDrawer) {
      !this.isWarningHidden && console.warn("menu drawer not found");
      return;
    }
    this.opcMenuDrawer.menuTitle = this.userInfo?.fullName;

    this.opcMenuDrawer.addEventListener("opc-menu-drawer:close", () => {
      this.opcNavBar.activeButton = "";
    });

    // rendering avatar and footer for the drawer
    render(
      html`
        <opc-avatar slot="avatar">
          ${this.userInfo?.firstName.charAt(0)}
          ${this.userInfo?.lastName.charAt(0)}
        </opc-avatar>
        <button slot="menu" onclick="window.OpAuthHelper.logout()">
          Log Out
        </button>
      `,
      this.opcMenuDrawer
    );
  }
Example #2
Source File: opc-provider.ts    From one-platform with MIT License 6 votes vote down vote up
private addToastToList(newToast: TemplateResult<1>) {
    render(newToast, this.toastContainer, {
      renderBefore: this.toastContainer.firstChild,
    });
    const toasts = [
      ...this.toastContainer.querySelectorAll("opc-toast"),
    ] as OpcToast[];
    toasts.slice(5).map((toast) => (toast.toastRef as any).open());
  }
Example #3
Source File: htmlOutput.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
export function renderIfHtmlOutput(val: any, intoElement: HTMLElement) {
  let didRender = false;
  if (val instanceof HTMLElement) {
    intoElement.appendChild(val);
    didRender = true;
  } else if (isProbablyTemplateResult(val)) {
    render(html`${val}`, intoElement);
    didRender = true;
  }

  if (didRender) {
    intoElement.classList.add("cell-output-html");
  }

  return didRender;
}
Example #4
Source File: markdown.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
async run() {
    // this.editMode = "wysiwyg";
    // const topElement = this.elements.topElement;
    // topElement.innerHTML = "";
    // const outDiv = document.createElement("div");
    // outDiv.classList.add("markdown-body");
    // outDiv.innerHTML = md.render(this.cell.textContent);
    // // Re-render when katex becomes available
    // if (!(await isKatexAlreadyLoaded())) {
    //   // Possible improvement: we could detect if any latex is present before we load katex
    //   katexHookPromise.then(() => {
    //     outDiv.innerHTML = md.render(this.cell.textContent);
    //   });
    // }
    // topElement.appendChild(outDiv);
    // // This works around a weird situation in which more than one output is present when
    // // a cell is marked as run_on_load
    // if (topElement.children.length > 1) {
    //   // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    //   topElement.children.item(0)!.remove();
    // }
    render(this.getControls(), this.elements.topControlsElement);
  }
Example #5
Source File: markdown.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
enterEditMode(mode: EditMode) {
    if (this.editor) {
      this.editor.dispose();
    }

    this.editMode = mode;
    this.setupEditor();
    render(this.getControls(), this.elements.topControlsElement);
  }
Example #6
Source File: esm.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
attach(params: CellHandlerAttachParameters) {
    this.elements = params.elements;

    const topElement = this.elements.topElement;
    render(this.getControls(), this.elements.topControlsElement);
    this.editor = new StarboardTextEditor(this.cell, this.runtime, {
      language: "javascript",
    });
    topElement.appendChild(this.editor);
  }
Example #7
Source File: latex.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
async run() {
    const topElement = this.elements.topElement;

    if (this.editor !== undefined) {
      this.editor.dispose();
      delete this.editor;
    }

    (await katexLoader()).render(this.cell.textContent, topElement, {
      throwOnError: false,
      errorColor: "#cc0000",
      displayMode: true,
    });
    topElement.children[0].addEventListener("dblclick", (_event: any) => this.enterEditMode());
    this.isInEditMode = false;
    render(this.getControls(), this.elements.topControlsElement);
  }
Example #8
Source File: html.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
attach(params: CellHandlerAttachParameters) {
    this.elements = params.elements;

    render(this.getControls(), this.elements.topControlsElement);
    this.editor = new StarboardTextEditor(this.cell, this.runtime, {
      language: "html",
    });
    this.elements.topElement.appendChild(this.editor);
  }
Example #9
Source File: javascript.ts    From starboard-notebook with Mozilla Public License 2.0 6 votes vote down vote up
attach(params: CellHandlerAttachParameters) {
    this.elements = params.elements;

    const topElement = this.elements.topElement;
    topElement.classList.add("flush");
    render(this.getControls(), this.elements.topControlsElement);
    this.editor = new StarboardTextEditor(this.cell, this.runtime, {
      language: "javascript",
    });
    topElement.appendChild(this.editor);
  }
Example #10
Source File: textEditor.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
render() {
    return html`
      <div style="position: relative; width: 100%; height: 0">
        <div class="starboard-text-editor-controls">
          <div class="dropdown">
            <button
              data-bs-toggle="dropdown"
              class="btn btn-small transparent p-1 px-1 me-1"
              style="color: #00000066"
              title="Editor Actions"
            >
              <span class="bi bi-gear"></span>
            </button>
            <div class="dropdown-menu">
              <li>
                ${currentEditor === "monaco"
                  ? html`<button
                      class="dropdown-item"
                      @click=${() => this.switchToCodeMirrorEditor()}
                      title="Switch to CodeMirror based editor, simpler and smartphone friendly"
                    >
                      Switch to Simple Editor
                    </button>`
                  : html`<button
                      class="dropdown-item"
                      @click=${() => this.switchToMonacoEditor()}
                      title="Switch to Monaco based editor, a few MB in size, smartphone unfriendly"
                    >
                      Switch to Advanced Editor
                    </button>`}
              </li>
              <li>
                <button
                  class="dropdown-item"
                  @click=${() => this.copyCellText()}
                  title="Copy the text in this cell to clipboard"
                >
                  Copy Text
                </button>
              </li>
            </div>
          </div>
        </div>
      </div>
      <div class="starboard-text-editor"></div>
    `;
  }
Example #11
Source File: opc-provider.ts    From one-platform with MIT License 5 votes vote down vote up
private injectNav() {
    // check
    if (!this.opcNavBar) {
      !this.isWarningHidden && console.warn("nav bar not found");
      return;
    }
    // links in navbar
    this.opcNavBar.links = [
      {
        href: " /get-started/docs",
        name: "Documentation",
      },
      {
        href: " /get-started/blog",
        name: "Blog",
      },
    ];

    // adding event listeners to nav button clicks
    this.opcNavBar.addEventListener("opc-nav-btn-menu:click", () => {
      this.opcMenuDrawer.open();
      this.opcNavBar.activeButton = "menu";
    });
    this.opcNavBar.addEventListener("opc-nav-btn-notification:click", () => {
      this.opcNotificationDrawer.open();
      this.opcNavBar.activeButton = "notification";
    });

    render(
      html` <style>
          opc-nav {
            --opc-nav-container__z-index: var(--opc-app-layout__nav-zIndex);
          }
          opc-menu-drawer {
            --opc-menu-drawer__z-index: var(--opc-app-layout__drawer-zIndex);
          }
          opc-notification-drawer {
            --opc-notification-drawer__z-index: var(
              --opc-app-layout__drawer-zIndex
            );
          }
          opc-feedback {
            --op-feedback__z-index: var(--opc-app-layout__feedback-zIndex);
          }
        </style>
        <opc-nav-search
          slot="opc-nav-search"
          value=${this.searchValue}
          @opc-nav-search:change=${(evt: any) =>
            (this.searchValue = evt.detail.value)}
          @opc-nav-search:submit=${(evt: any) =>
            (window.location.href = `/search?query=${evt.detail.value}`)}
        ></opc-nav-search>
        <a slot="opc-nav-logo" href="/">
          <img slot="" src="${opLogo}" height="30px" alt="logo" />
        </a>`,
      this.opcNavBar
    );
  }
Example #12
Source File: textEditor.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
firstUpdated(changedProperties: any) {
    super.firstUpdated(changedProperties);
    [].slice.call(document.querySelectorAll(".dropdown-toggle")).map((e) => new Dropdown(e));

    if (currentEditor === "codemirror" || currentEditor === "monaco" || this.runtime.config.defaultTextEditor) {
      this.initEditor();
      // While it loads, render markdown
      const mdText = md.render("```" + `${this.opts.language}\n${this.cell.textContent}\n` + "```");
      render(
        html`<div class="cell-popover cell-select-editor-popover">
            Loading ${currentEditor || this.runtime.config.defaultTextEditor} editor..
          </div>
          ${unsafeHTML(mdText)}`,
        this.editorMountpoint
      );
    } else {
      this.editorMountpoint.addEventListener("dblclick", () => this.handleDblClick(), { once: true, passive: true });
      const mdText = md.render("```" + `${this.opts.language}\n${this.cell.textContent}\n` + "```");
      render(
        html`
          <div class="cell-popover cell-select-editor-popover">
            <div style="display: flex; align-items: center;">
              <b style="font-size: 1em; margin-right: 4px">Please select a text editor</b>
              <button
                @click=${() => this.switchToMonacoEditor()}
                title="Monaco Editor (advanced, desktop only)"
                class="cell-popover-icon-button"
              >
                Monaco
              </button>
              <button
                @click=${() => this.switchToCodeMirrorEditor()}
                title="CodeMirror Editor (simpler, touchscreen friendly)"
                class="cell-popover-icon-button"
              >
                CodeMirror
              </button>
            </div>
            <span style="font-size: 0.85em"
              ><b>Monaco</b> is more powerful, but is larger (4MB) and has poor touchscreen support.</span
            >
          </div>
          ${unsafeHTML(mdText)}
        `,
        this.editorMountpoint
      );
      notifyOnEditorChosen.push(() => this.initEditor());
    }
  }
Example #13
Source File: latex.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
enterEditMode() {
    this.isInEditMode = true;
    this.setupEditor();
    render(this.getControls(), this.elements.topControlsElement);
  }
Example #14
Source File: javascript.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
clear() {
    render(html``, this.elements.bottomElement);
  }
Example #15
Source File: javascript.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
async run() {
    this.lastRunId++;
    const currentRunId = this.lastRunId;
    this.isCurrentlyRunning = true;
    render(this.getControls(), this.elements.topControlsElement);

    this.outputElement = new ConsoleOutputElement();
    this.outputElement.hook(this.runtime.consoleCatcher);

    const htmlOutput = document.createElement("div");
    htmlOutput.classList.add("cell-output-html");
    render(html`${this.outputElement}${htmlOutput}`, this.elements.bottomElement);

    const outVal = await this.jsRunner.run(this.cell.textContent);

    // Not entirely sure this is necessary anymore, but we had to wait one tick with unhooking
    // as some console messages are delayed by one tick it seems.
    await this.outputElement.unhookAfterOneTick(this.runtime.consoleCatcher);

    const val = outVal.value;
    const htmlOutputRendered = renderIfHtmlOutput(val, htmlOutput);

    if (!htmlOutputRendered && val !== undefined) {
      // Don't show undefined output
      if (outVal.error) {
        if (val.stack !== undefined) {
          let stackToPrint: string = val.stack;
          const errMsg: string = val.toString();
          if (stackToPrint.startsWith(errMsg)) {
            // Prevent duplicate error msg in Chrome
            stackToPrint = stackToPrint.substr(errMsg.length);
          }
          this.outputElement.addEntry({
            method: "error",
            data: [errMsg, stackToPrint],
          });
        } else {
          this.outputElement.addEntry({
            method: "error",
            data: [val],
          });
        }
      } else {
        this.outputElement.addEntry({
          method: "result",
          data: [val],
        });
      }
    }

    if (this.lastRunId === currentRunId) {
      this.isCurrentlyRunning = false;
      render(this.getControls(), this.elements.topControlsElement);
    }

    if (outVal.error) {
      throw val;
    }
  }
Example #16
Source File: html.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
clear() {
    render(html``, this.elements.bottomElement);
  }
Example #17
Source File: html.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
async run() {
    const htmlContent = this.cell.textContent;
    render(html`${unsafeHTML(htmlContent)}`, this.elements.bottomElement);
  }
Example #18
Source File: esm.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
clear() {
    render(html``, this.elements.bottomElement);
  }
Example #19
Source File: esm.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
async run() {
    this.lastRunId++;
    const currentRunId = this.lastRunId;
    this.isCurrentlyRunning = true;
    render(this.getControls(), this.elements.topControlsElement);

    this.outputElement = new ConsoleOutputElement();
    this.outputElement.hook(this.runtime.consoleCatcher);

    const htmlOutput = document.createElement("div");
    render(html`${this.outputElement}${htmlOutput}`, this.elements.bottomElement);

    const esmCodeUrl = URL.createObjectURL(new Blob([this.cell.textContent], { type: "text/javascript" }));

    let out: any = {};
    let error: any = undefined;
    try {
      out = await import(/* webpackIgnore: true */ esmCodeUrl);
    } catch (e) {
      error = e;
    }

    await this.outputElement.unhookAfterOneTick(this.runtime.consoleCatcher);

    const val = out.default;

    if (out) {
      Object.assign(window, out);
    }

    if (error) {
      if (error.stack !== undefined) {
        let stackToPrint: string = error.stack;
        const errMsg: string = error.toString();
        if (stackToPrint.startsWith(errMsg)) {
          // Prevent duplicate error msg in Chrome
          stackToPrint = stackToPrint.substr(errMsg.length);
        }
        this.outputElement.addEntry({
          method: "error",
          data: [errMsg, stackToPrint],
        });
      } else {
        this.outputElement.addEntry({
          method: "error",
          data: [error],
        });
      }
    }

    const htmlOutputRendered = renderIfHtmlOutput(val, htmlOutput);
    if (!htmlOutputRendered) {
      if (val !== undefined) {
        // Don't show undefined output
        this.outputElement.addEntry({
          method: "result",
          data: [val],
        });
      }
    }

    if (this.lastRunId === currentRunId) {
      this.isCurrentlyRunning = false;
      render(this.getControls(), this.elements.topControlsElement);
    }

    if (error) {
      throw error;
    }
  }
Example #20
Source File: default.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
attach(params: CellHandlerAttachParameters) {
    render(html`${this.editor}`, params.elements.topElement);
  }
Example #21
Source File: css.ts    From starboard-notebook with Mozilla Public License 2.0 5 votes vote down vote up
async run() {
    const content = this.cell.textContent;
    if (content) {
      render(html`${unsafeHTML("<style>\n" + content + "\n</style>")}`, this.elements.bottomElement);
    }
  }
Example #22
Source File: opc-provider.ts    From one-platform with MIT License 5 votes vote down vote up
render() {
    return html`
      <opc-loader ?hidden=${!this.isLoading}></opc-loader>
      <slot></slot>
      <div class="opc-toast-container"></div>
    `;
  }
Example #23
Source File: opc-provider.ts    From one-platform with MIT License 5 votes vote down vote up
/**
   * Will update is used for derived propery calculation
   * notification -> app count is recomputed on notification state change
   */
  willUpdate(changedProperties: any): void {
    // only need to check changed properties for an expensive computation.
    if (
      changedProperties.has("notifications") ||
      changedProperties.has("selectedAppsForNotificationFilter")
    ) {
      this.notificationAppCount = getNotificationAppCount(this.notifications);
      const chipContainer: any = this.querySelector(
        ".opc-notification-drawer__header-chip-group"
      );
      const headerContainer: any = this.querySelector(".opc-notification-item");
      if (chipContainer) {
        render(
          html`
            ${Object.entries(this.notificationAppCount).map(([app, count]) => {
              if (!count) {
                return null;
              }
              const isChipActive =
                this.selectedAppsForNotificationFilter.includes(
                  app.toLowerCase()
                );
              return html`<opc-filter-chip
                @click=${() => this.handleFilterChipSelect(app.toLowerCase())}
                ?isChipActive=${isChipActive}
              >
                ${app} +${count}
              </button>`;
            })}
          `,
          chipContainer
        );
      }
      // to render the chips for filtering in notification drawer
      if (headerContainer) {
        render(
          html`${this.notifications
            .filter(({ app = "others" }) => {
              if (this.selectedAppsForNotificationFilter.length === 0) {
                return true;
              }
              return this.selectedAppsForNotificationFilter.includes(
                app.toLowerCase()
              );
            })
            .map(
              (notification) =>
                html` <opc-notification-item
                  title=${notification.subject}
                  variant=${notification.variant}
                  key=${notification.id}
                  @opc-notification-item:close=${() => {
                    this.handleNotificationClose(notification.id!);
                  }}
                >
                  <span>
                    ${notification.body}.
                    ${notification.link
                      ? html`<a href=${notification.link}>This is the link.</a>`
                      : ""}
                  </span>
                </opc-notification-item>`
            )}`,
          this.opcNotificationDrawer,
          { renderBefore: headerContainer }
        );
      }
    }
  }
Example #24
Source File: opc-provider.ts    From one-platform with MIT License 5 votes vote down vote up
private injectNotificationDrawer() {
    // check
    if (!this.opcNotificationDrawer) {
      !this.isWarningHidden && console.warn("notification drawer not found");
      return;
    }

    this.opcNotificationDrawer.addEventListener(
      "opc-notification-drawer:close",
      () => {
        this.opcNavBar.activeButton = "";
      }
    );

    // rendering drawer header for filter operations and footer
    render(
      html`
        <style>
          .p-4 {
            padding: 1rem;
          }
          .opc-notification-drawer__header-chip-group {
            margin-top: 0.5rem;
            display: flex;
            flex-wrap: wrap;
          }
          .opc-notification-drawer__header-chip-group
            opc-filter-chip:not(:last-child) {
            margin-right: 4px;
          }
        </style>
        <div
          slot="header-body"
          class="opc-notification-drawer__header-chip-group"
        ></div>
        <div class="opc-notification-item"></div>
        <div class="p-4" slot="footer">
          <opc-drawer-footer></opc-drawer-footer>
        </div>
      `,
      this.opcNotificationDrawer
    );
  }