import { VisQuill, Animate, Arcs, Circles, EasingFunctions, Pins, Points, Reactive, Vectors, type Pin, type Real, type RvgGroup } from "@visquill/visquill-gdk";
import "./styles.css";

// The current local time in seconds, counted from 1970.
function now(): number {
  const date = new Date();
  return date.getTime() / 1000 - date.getTimezoneOffset() * 60;
}

// A hand: a layer that turns with its angle.
function hand(canvas: RvgGroup, twelve: Pin, style: string, length: number, angle: Real) {
  const layer = canvas.layer();
  layer.visuals.segment(style, [0, 0], [length, 0]);
  Reactive.do([angle], () => {
    Pins.rotateBy(twelve, angle, layer.anchor);
  });
}

// Part 6: a timer for up to 60 seconds.
export function run(div: HTMLDivElement) {
  const rvg = VisQuill.create(div, "clock-");
  const canvas = rvg.canvas;
  canvas.handles.defaultZIndex = 1;

  const face = canvas.visuals.circle("face");
  Circles.circleAt([280, 170], 130, face);

  // A pin at the center that points to 12, and turned copies of it.
  const twelve = Pins.withOrientation([280, 170], [0, -1]);
  const at = (fraction: number) => Pins.rotateBy(twelve, fraction * 2 * Math.PI);

  // The timer's arc and readout. They are created before the ticks and
  // hands, so they are drawn below them.
  const arc = canvas.visuals.arc("timer-arc region-arc");
  const readout = canvas.text.label("", "readout region-readout");
  Points.copy([280, 225], readout);

  for (let i = 0; i < 60; i++) {
    const long = i % 5 === 0;
    const pin = at(i / 60);
    canvas.visuals.segment(long ? "tick long" : "tick", Pins.moveForward(pin, long ? 116 : 123), Pins.moveForward(pin, 130));
  }
  for (let h = 1; h <= 12; h++) {
    const label = canvas.text.label(String(h), "number");
    Points.copy(Pins.moveForward(at(h / 12), 100), label);
  }

  const t = now();
  const hourAngle = canvas.values.real((t / 43200) * 2 * Math.PI);
  const minuteAngle = canvas.values.real((t / 3600) * 2 * Math.PI);
  const secondAngle = canvas.values.real((t / 60) * 2 * Math.PI);

  hand(canvas, twelve, "hand hour", 65, hourAngle);
  hand(canvas, twelve, "hand minute", 100, minuteAngle);
  hand(canvas, twelve, "hand second", 112, secondAngle);
  canvas.visuals.point("cap", { x: 280, y: 170 });

  // The knob is a handle. It starts at 12, which means 0 seconds.
  const knob = canvas.handles.disk("knob region-knob", Pins.moveForward(twelve, 130));
  let seconds = 0;

  // The arc starts at 12. Arcs.arcAt takes the start as an angle measured
  // clockwise from the x-axis; Vectors.angle gives it for the 12 o'clock direction.
  const start = Vectors.angle(Pins.getOrientation(twelve), true);

  // When the knob moves, it is put back onto the rim. The angle from 12 to
  // the knob, clockwise, gives the seconds (a full turn is 60), the arc and
  // the readout.
  Reactive.do([knob], () => {
    Circles.closestPoint(face, knob, knob);
    const toKnob = Vectors.direction([280, 170], knob);
    const angle = Vectors.angleTo(Pins.getOrientation(twelve), toKnob, true).value;
    seconds = Math.round((angle / (2 * Math.PI)) * 60) % 60;
    Arcs.arcAt([280, 170], 122, start, seconds > 0 ? angle : 0, arc);
    readout.value = seconds > 0 ? `${seconds} s` : "";
  });

  const ticker = setInterval(() => {
    const t = Math.round(now());
    Animate.real.eased(secondAngle, (t / 60) * 2 * Math.PI, 300, {
      easing: EasingFunctions.easeOutBack,
    });
    Animate.real.eased(minuteAngle, (t / 3600) * 2 * Math.PI, 300);
    Animate.real.eased(hourAngle, (t / 43200) * 2 * Math.PI, 300);

    // The countdown moves the knob back by one second, but not while the
    // user holds it. The knob's reaction then updates the arc and the
    // readout, the same way as when it is dragged.
    if (seconds > 0 && !knob.active.value) {
      const target = Pins.moveForward(at((seconds - 1) / 60), 130);
      Animate.point.eased(knob, target, 300, { easing: EasingFunctions.easeOutCubic });
    }
  }, 1000);

  return () => clearInterval(ticker);
}
/* Each class is the prefix "clock-" plus the name used in demo.ts. */

.clock-face {
  fill: #faf6ef;
  stroke: #1c1a17;
  stroke-width: 3px;
}

/* All ticks are thin; the class "long" makes every fifth one thicker. */
.clock-tick { stroke: #1c1a17; stroke-width: 1px; }
.clock-long { stroke-width: 3px; }

.clock-number {
  fill: #1c1a17;
  font: 500 16px Inter, system-ui, sans-serif;
  text-anchor: middle;
  dominant-baseline: middle;
  user-select: none;
}

.clock-hand { stroke: #1c1a17; stroke-linecap: round; }
.clock-hour { stroke-width: 6px; }
.clock-minute { stroke-width: 4px; }
.clock-second { stroke: #c0503f; stroke-width: 2px; }
.clock-cap { r: 5px; fill: #1c1a17; }

/* Part 6: the timer. The arc is a thick, light line just inside the rim. */
.clock-timer-arc {
  fill: none;
  stroke: #e9c48f;
  stroke-width: 14px;
}

.clock-knob {
  r: 10px;
  fill: #d8913a;
  stroke: #faf6ef;
  stroke-width: 2px;
  cursor: grab;
}
.clock-knob:active { cursor: grabbing; }

.clock-readout {
  fill: #1c1a17;
  font: 500 14px "JetBrains Mono", ui-monospace, monospace;
  text-anchor: middle;
  dominant-baseline: middle;
  user-select: none;
}

Tutorial · 6 parts

Build a clock

A clock face with ticks, numbers and moving hands, and a timer you set by dragging a knob along the rim.

01

What you will build

A clock face with tick marks, numbers and three hands that show the current time and tick once a second. On top of it, a timer: drag the orange knob along the rim to set up to 60 seconds, and the clock counts them down.

This is the result of the last part. Try the knob.

02

What you will learn

  • Creating a graphic, drawing circles and segments, styling them with CSS.
  • Pins: a point with a direction. The whole clock is measured from one pin that points to 12, with turned copies of it (Pins.rotateBy, Pins.moveForward).
  • Layers and their anchors: a hand is a layer that turns.
  • Reactive values and Reactive.do.
  • Animation with Animate.real.eased and easing functions.
  • Handles: dragging, keeping a handle on a circle, and active.
  • Arcs, and stopping a timer when the demo is removed.

No previous knowledge of VisQuill is needed; some TypeScript helps.

03

How the parts work

Each part adds to the code of the part before it. On the right are the live demo and its code; as you scroll through a part, the code and the visuals the text is about are highlighted. Every part can be downloaded as a small Vite project that runs on its own.

Start with part 1: The face →