Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                // See <https://groups.google.com/g/comp.lang.javascript/c/CEhrlUfL-d4>

// Converts a property into a "field"
// A "field" is a 'private' property + getter/setter pair
function field(target: any, key: string) {
  if (delete target[key]) {
    // Create new property with getter and setter
    Object.defineProperty(target, key, {
      get() {
        return this[`_${key}`];
      },
      set(newVal) {
        this[`_${key}`] = newVal;
      },
      enumerable: true,
      configurable: true
    });
  }
}

// converts a property into a "field" that
// raises a custom MODEL_CHANGE event when updated
function bindable(target: any, key: string) {
  if (delete target[key]) {
    // Create new property with getter and setter
    Object.defineProperty(target, key, {
      get() {
        return this[`_${key}`];
      },
      set(newVal) {
        if (!(this instanceof Observable))
          throw new TypeError("Only an Observable class can use @bindable");
        Reflect.set(this, `_${key}`, newVal);
        this.notify(
          new CustomEvent("MODEL_CHANGE", {
            detail: { [key]: newVal }
          })
        );
      },
      enumerable: true,
      configurable: true
    });
  }
}

abstract class Observer {
  update(event?: Event) {}
}

abstract class Observable {
  protected _observers: Observer[] = [];

  observe(observer: Observer) {
    if (this._observers.indexOf(observer) > -1)
      throw new Error("Observer already added");
    this._observers.push(observer);
  }

  unobserve(observer: Observer) {
    if (this._observers.indexOf(observer) == -1)
      throw new Error("Observer does not exist");
    this._observers = this._observers.filter((o) => o === observer);
  }

  notify(event: Event) {
    [...this._observers].forEach((o) => o.update(event));
  }
}

abstract class Model extends Observable {}

abstract class View<M extends Model> extends Observer {
  @field model: M;
  rootType!: HTMLElement;
  @field rootElement: this["rootType"];
  @field elContainer: HTMLElement;

  constructor(elContainer: HTMLElement, model: M) {
    super();
    this.elContainer = elContainer;
    this.rootElement = this.initRoot();
    this.model = model;
    this.model.observe(this);
  }

  initRoot(): this["rootType"] {
    return document.createElement("div");
  }

  render() {
    this.elContainer.appendChild(this.rootElement);
  }
}

abstract class Controller<M extends Model> extends Observer {
  @field model;
  constructor(model: M) {
    super();
    this.model = model;
  }
}

//////////////////////////////
/////////// Usage ////////////
/////////////////////////////

class ClockModel extends Model {
  @bindable time;
  #intervalId?: number;
  constructor() {
    super();
    this.time = new Date();
    this.isRunning = true;
  }

  get isRunning() {
    return this.#intervalId != undefined;
  }

  set isRunning(value) {
    if (!value) {
      clearInterval(this.#intervalId);
      this.#intervalId = undefined;
    } else {
      this.#intervalId = setInterval(() => {
        this.time = new Date();
      }, 1000);
    }
  }
}

abstract class AbstractClockView<M extends ClockModel> extends View<M> {
  initRoot() {
    return document.createElement("article");
  }
}

class AnalogClockView<M extends ClockModel> extends AbstractClockView<M> {
  #elTitle;
  #elCanvas;
  #ctx;
  #radius = 110;

  constructor(elContainer: HTMLElement, model: M) {
    super(elContainer, model);

    this.#elTitle = Object.assign(document.createElement("h2"), {
      textContent: "Analog Clock"
    });
    this.rootElement.appendChild(this.#elTitle);

    this.#elCanvas = Object.assign(document.createElement("canvas"), {
      height: this.#radius * 2,
      width: this.#radius * 2
    });
    this.rootElement.appendChild(this.#elCanvas);

    this.#ctx = this.#elCanvas.getContext("2d")!;
    this.#ctx.translate(this.#radius, this.#radius);
  }

  update() {
    this._clear();
    this._drawFace();
    this._drawTime();
  }

  protected _clear() {
    const canvas = this.#elCanvas;
    canvas.width = canvas.width;
    this.#ctx.translate(this.#radius, this.#radius);
  }

  protected _drawFace() {
    const r = this.#radius,
      ctx = this.#ctx;
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.arc(0, 0, r, 0, Math.PI * 2, true);
    ctx.stroke();
  }

  protected _drawHand(
    color: string,
    pos: number,
    length: number,
    width: number
  ) {
    const ctx = this.#ctx,
      oldStyle = ctx.strokeStyle;
    ctx.beginPath();
    ctx.strokeStyle = color;
    ctx.lineWidth = width;
    ctx.lineCap = "round";
    ctx.moveTo(0, 0);
    ctx.rotate(pos);
    ctx.lineTo(0, -length);
    ctx.stroke();
    ctx.rotate(-pos);
    ctx.strokeStyle = oldStyle;
  }

  protected _drawTime() {
    const r = this.#radius,
      { PI } = Math,
      { time } = this.model,
      [hour, minute, second] = [
        time.getHours(),
        time.getMinutes(),
        time.getSeconds()
      ];

    const hPos =
      ((hour % 12) * PI) / 6 +
      (minute * PI) / (6 * 60) +
      (second * PI) / (360 * 60);
    this._drawHand("black", hPos, r * 0.5, r * 0.07);

    const minPos = (minute * PI) / 30 + (second * PI) / (30 * 60);
    this._drawHand("blue", minPos, r * 0.8, r * 0.07);

    const secPos = (second * PI) / 30;
    this._drawHand("red", secPos, r * 0.9, r * 0.02);
  }
}

class DigitalClockView<M extends ClockModel> extends AbstractClockView<M> {
  #elTitle;
  #elHour;
  #elMinute;
  #elSecond;

  constructor(elContainer: HTMLElement, model: M) {
    super(elContainer, model);

    this.#elTitle = Object.assign(document.createElement("h2"), {
      textContent: "Digital Clock"
    });
    this.rootElement.appendChild(this.#elTitle);

    this.#elHour = document.createElement("span");
    this.rootElement.appendChild(this.#elHour);
    this.rootElement.appendChild(document.createTextNode(":"));

    this.#elMinute = document.createElement("span");
    this.rootElement.appendChild(this.#elMinute);
    this.rootElement.appendChild(document.createTextNode(":"));

    this.#elSecond = document.createElement("span");
    this.rootElement.appendChild(this.#elSecond);
  }

  update() {
    const { time } = this.model,
      [hour, minute, second] = [
        time.getHours(),
        time.getMinutes(),
        time.getSeconds()
      ];
    this.#elHour.textContent = `${hour}`.padStart(2, "0");
    this.#elMinute.textContent = `${minute}`.padStart(2, "0");
    this.#elSecond.textContent = `${second}`.padStart(2, "0");
  }
}

class Clock extends Controller<ClockModel> {
  #btnToggle;
  #analogClock;
  #digitalClock;
  constructor(elContainer: HTMLElement, model = new ClockModel()) {
    super(model);

    this.#analogClock = new AnalogClockView(elContainer, model);
    elContainer.appendChild(this.#analogClock.rootElement);
    this.#analogClock.render();

    this.#digitalClock = new DigitalClockView(elContainer, model);
    elContainer.appendChild(this.#digitalClock.rootElement);
    this.#digitalClock.render();

    this.#btnToggle = Object.assign(document.createElement("button"), {
      textContent: "Stop"
    });
    this.#btnToggle.addEventListener("click", (e) => this.onToggle(e));
    elContainer.appendChild(this.#btnToggle);
  }

  onToggle(_e: Event) {
    this.model.isRunning = !this.model.isRunning;
    this.#btnToggle.textContent = this.model.isRunning ? "Stop" : "Start";
  }
}

///////// Testing //////////
const clock = new Clock(document.body);

              
            
!
999px

Console