WebDev Bites: ViewCode Component Demo

resizable code viewer with shadow DOM encapsulation

Figure 1. CSS Example
:root {
  --dark:  #333;
  --light: #f8f8f8;
}

body {
  font-family: 'Segoe UI', sans-serif;
  padding: 1rem 2rem;
  margin: 0;
}

t-b {
  display: block;
  margin: 0.75rem 0;
  max-width: 50em;
}
This is a view-code component. Clicking on the code body makes it wider. Clicking on the title makes it narrower. ViewCode supports two rendering modes: a plain text path and a Prism syntax-highlighting path. The highlight="prism" attribute switches to Prism mode, which expects a <pre slot="code"><code> structure in the light DOM.
This is the first in a sequence of pages that explore the design of a W3C web component for displaying code with optional syntax highlighting. The next page explains the design of the component. The final page shows how an application uses the viewer and lists its public interface.

Component Parts

The primary parts of a web component are:
  1. Class derived from HTMLElement
    Each application of the component's tag creates an instance of this class when the code is parsed at load time.
  2. Shadow DOM, a tree of encapsulated HTML elements
    ViewCode separates its shadow DOM into two module-level template strings: VC_STYLE for the CSS and VC_TEMPLATE for the HTML structure.
    The shadow DOM contains an internal <pre><code> pair for the plain-text path and a named slot (slot="code") for the Prism path. CSS attribute selectors on :host([highlight="prism"]) toggle which one is visible.
  3. Event listeners
    Associates user events with parts of the component. ViewCode listens for clicks on the code body (widen) and title (narrow), plus slotchange to react when slotted content is assigned or replaced.
  4. Helper functions
    ViewCode uses _renderDefault(), _maybeSetupPrism(), _resolveDisplayEl(), _harmonizeBox(), _applyBoxColors(), _applySizing(), _applyTypography(), and _stripCommonIndent().
  5. Hyphenated tag name associated with the component class.
    The tag name view-code is associated with the class ViewCode.