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;
}

Build a clock · Part 6 of 6

A timer

A knob that moves along the rim sets a countdown of up to 60 seconds.

01

The knob

canvas.handles.disk creates a point that can be dragged. It starts at 12. Reactive.do runs the given function whenever the knob moves.

The function first puts the knob back onto the rim: Circles.closestPoint writes the closest point on the face into the knob. A function that changes its own sender does not run again because of that change, so this does not loop.

Then Vectors.angleTo measures the angle from the direction of 12 to the direction of the knob, clockwise. A full turn is 60 seconds. % 60 turns 60 into 0, so the knob at 12 means no time is set.

02

The arc

Arcs.arcAt builds an arc from a center, a radius, a start angle and a sweep. It expects the start as an angle from the x-axis; Vectors.angle computes it from the direction of twelve. The sweep is the angle of the knob.

The arc is created before the ticks and hands, so it is drawn below them.

03

The readout

A label below the center shows the seconds. It is empty when no time is set.

04

Counting down

Each second, the countdown animates the knob one second back with Animate.point.eased. The knob's reaction then updates the arc and the readout, the same way as when the knob is dragged.

knob.active is true while the user holds the knob. The countdown waits until it is released, so it does not pull the knob away while it is being set.

The animation uses easeOutCubic, which does not overshoot. An overshoot on the last step would carry the knob past 12, and the timer would read 59 seconds again.