Clock calendar: left click slides out a month calendar
CI / test (push) Failing after 17s

Left-clicking the Digital Clock (or the Binary Clock) opens a calendar flyout that
slides up out of the panel; Escape, a click elsewhere or another click on the clock
slides it back in.

- lib/clock/calendar.mbt: month maths (leap years, weekday, ISO week numbers), a
  six-week grid, the flyout's state, drawing and hit testing. Header with the time
  (in the clock's own 12/24-hour format) and the long date; month and year with
  previous / Today / next buttons; weekday names; today circled in the accent colour,
  other months' days muted. Keys: Escape closes, t today, p/n previous/next month.
- Module settings (right click): "Week starts on" Sunday/Monday and "Show week
  numbers", for both clocks (saved per module like the other settings).
- compositor/shell/slide.mbt: popups of the clock modules slide (200 ms, ease-out in,
  ease-in out), clipped to their final place so they come out of the panel edge; the
  popup takes input at its final place at once. A popup below the panel would slide
  the other way. Theme comes from the module's tokens, so dark/light follow.
- CPU: has_timed_work() is true only while a slide runs, so the main loop only keeps
  the frame pace for those 200 ms; an open calendar redraws only when its minute or
  month changes.
- Tests: lib/clock calendar tests (wasm), compositor/host/calendar_test.mbt (open,
  slide finishes, month buttons, Escape / click outside / toggle, settings, binary
  clock). Host failures are the 5 known input_test ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjahaLE5XqnCWoEwKv
This commit is contained in:
Claude committed 2026-11-25 20:47:06 +00:00
1 parent 10659e7655
commit a215dd6bf7
9 files changed
+893 -18

No files matched your search

@@ -18,12 +18,18 @@ pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.render_binary(size, @theme.get_tokens(), @clock.now(), seconds=@logic.binary_config.seconds)
}
///|
///| The calendar flyout (left click opens it; the shell slides it out of the panel).
pub fn popup() -> PopupSurface? {
None
let cal = @logic.binary_config.cal
if !cal.open {
return None
}
let (w, h) = cal.size()
let ops = cal.render(@theme.get_tokens(), @clock.now())
Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops })
}
///|
pub fn on_event(_target : Surface, _event : @types.InputEvent) -> Bool {
false
pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool {
@logic.binary_config.cal.handle(target is POPUP, event, @clock.now())
}
@@ -19,12 +19,18 @@ pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
@logic.render_digital(size, @theme.get_tokens(), @clock.now(), hour12=c.hour12, show_date=c.show_date, ampm=c.ampm)
}
///|
///| The calendar flyout (left click opens it; the shell slides it out of the panel).
pub fn popup() -> PopupSurface? {
None
let c = @logic.digital_config
if !c.cal.open {
return None
}
let (w, h) = c.cal.size()
let ops = c.cal.render(@theme.get_tokens(), @clock.now(), hour12=c.hour12, ampm=c.ampm)
Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops })
}
///|
pub fn on_event(_target : Surface, _event : @types.InputEvent) -> Bool {
false
pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool {
@logic.digital_config.cal.handle(target is POPUP, event, @clock.now())
}
+96
View File
@@ -0,0 +1,96 @@
///| The clocks' calendar flyout driven through the shell: a left click on the clock slides it
/// out of the panel, its buttons change the month, and Escape, a click elsewhere or another click
/// on the clock slide it away. Needs the modules: run scripts/build-modules.sh.
///|
fn cal_texts(comp : @host.ChandraCompositor, id : String) -> Array[String] {
comp.shell.slot_popup_texts(comp.shell.slot_of(id)).map(t => t.0)
}
///| Wait out the slide, drawing frames like the main loop does while one runs.
fn finish_slide(comp : @host.ChandraCompositor) -> Unit {
let mut n = 0
while comp.has_timed_work() && n < 200 {
@sys.sleep_ms(5)
ignore(comp.compose_frame())
n = n + 1
}
}
///|
test "left click on the clock slides out a calendar; Escape, a click elsewhere or the clock close it" {
let comp = new_comp("calendar")
let slot = comp.shell.slot_of("clock-digital")
let clock = rect_of(comp, "clock-digital")
assert_true(clock.w > 0)
assert_false(comp.has_timed_work()) // an idle desktop doesn't animate
click_module(comp, "clock-digital", 1U)
let pr = comp.shell.slot_popup_rect(slot)
assert_true(pr.w > 0)
assert_true(pr.y + pr.h <= clock.y) // above the panel
assert_true(pr.x + pr.w <= 1280)
// It is sliding: frames keep coming until it sits in place.
assert_true(comp.has_timed_work())
assert_true(comp.shell.slot_slide_offset(slot) > 0)
@sys.sleep_ms(60)
ignore(@sys.write_file_bytes("_build/calendar_sliding.png", @renderer.encode_png(comp.compose_frame())))
finish_slide(comp)
assert_false(comp.has_timed_work())
assert_eq(comp.shell.slot_slide_offset(slot), 0)
ignore(@sys.write_file_bytes("_build/calendar_open.png", @renderer.encode_png(comp.compose_frame())))
// The header, the month and the buttons.
let month = cal_texts(comp, "clock-digital")[2] // e.g. "November 2026"
assert_true(month.contains(" 20"))
assert_true(cal_texts(comp, "clock-digital").contains("Today"))
// The buttons sit right-aligned in the month row: next, Today, previous.
let row_y = pr.y + 80 + 14
click_at(comp, pr.x + pr.w - 12 - 14, row_y, 10U) // next month
assert_true(cal_texts(comp, "clock-digital")[2] != month)
click_at(comp, pr.x + pr.w - 12 - 28 - 4 - 28, row_y, 20U) // Today
assert_eq(cal_texts(comp, "clock-digital")[2], month)
assert_false(comp.has_timed_work()) // changing month doesn't slide
// Escape slides it away; input passes through at once.
comp.handle_input(@nested.InputEvent::Key(1U, true), 30U)
ignore(comp.compose_frame())
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
assert_true(comp.has_timed_work())
finish_slide(comp)
assert_false(comp.has_timed_work())
// Clicking the clock again toggles it.
click_module(comp, "clock-digital", 40U)
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
click_module(comp, "clock-digital", 50U)
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
// A click on the desktop closes it too.
click_module(comp, "clock-digital", 60U)
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
click_at(comp, 600, 200, 70U)
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
finish_slide(comp)
assert_false(comp.has_timed_work())
}
///|
test "the calendar's week start and week numbers are the clock's module settings" {
let comp = new_comp("calendar-cfg")
let slot = comp.shell.slot_of("clock-digital")
comp.shell.set_module_setting(slot, "week-start", "Monday")
comp.shell.set_module_setting(slot, "week-numbers", "on")
assert_eq(comp.shell.module_setting("clock-digital", "week-start"), Some("Monday"))
click_module(comp, "clock-digital", 1U)
comp.shell.dark_mode = false
comp.apply_theme()
finish_slide(comp)
ignore(@sys.write_file_bytes("_build/calendar_light.png", @renderer.encode_png(comp.compose_frame())))
let texts = cal_texts(comp, "clock-digital")
assert_true(texts.contains("Wk"))
let names = texts.filter(s => s == "Mo" || s == "Su")
assert_eq(names, ["Mo", "Su"])
// The binary clock has the calendar too.
assert_true(comp.shell.unload_slot(slot))
assert_true(comp.shell.load_module("clock-binary"))
ignore(comp.compose_frame())
click_module(comp, "clock-binary", 10U)
assert_true(comp.shell.slot_popup_rect(comp.shell.slot_of("clock-binary")).w > 0)
assert_true(cal_texts(comp, "clock-binary").contains("Today"))
}
+2 -1
View File
@@ -581,7 +581,8 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
self.rec is Some(_) ||
self.shot_request is Some(_) ||
self.rec_request is Some(_) ||
self.shot_toast is Some(_)
self.shot_toast is Some(_) ||
self.shell.animating()
}
///|
+8 -4
View File
@@ -179,6 +179,12 @@ pub(all) struct Widget {
mut popup_rect : @scene.Rect
mut popup_ops : Array[@types.DrawOp]
mut popup_hot : Bool
/// Popup slide (slide.mbt): when the running slide began (monotonic ms, 0: none), whether it
/// slides in or out, and while sliding out, where the popup was and what it showed.
mut slide_t0 : UInt64
mut slide_in : Bool
mut ghost_rect : @scene.Rect
mut ghost_ops : Array[@types.DrawOp]
}
///| A wasm module file found on the module path.
@@ -941,12 +947,10 @@ pub fn DesktopShell::render(
}
}
}
// Popups sit above the panel, left-aligned with their widget.
// Popups sit above the panel, left-aligned with their widget; some slide in and out.
for wd in self.widgets {
self.refresh_popup(wd)
if wd.popup_rect.w > 0 {
translate(wd.popup_ops, wd.popup_rect.x, wd.popup_rect.y, panel_ops)
}
self.draw_popup(wd, panel_ops)
}
if self.menu_open {
self.render_menu(w, tokens, panel_ops)
+147
View File
@@ -0,0 +1,147 @@
///| Popups that slide out of the panel when they open and back into it when they close (the
/// clocks' calendar). The popup keeps its final place for input from the first frame; only the
/// drawing moves, clipped to that place, so it looks like it comes out of the panel's edge.
/// Frames are only drawn at the frame pace while a slide runs (`animating`, which the
/// compositor's main loop checks); otherwise nothing is redrawn for it.
///| Modules whose popups slide.
let slide_modules : Array[String] = ["clock-digital", "clock-binary"]
///| How long a slide takes, in ms.
pub let slide_ms : UInt64 = 200
///|
fn Widget::slides(self : Widget) -> Bool {
slide_modules.contains(self.module_id)
}
///| How far into the running slide we are, 0.0 .. 1.0.
fn Widget::slide_progress(self : Widget, now : UInt64) -> Double {
if self.slide_t0 == 0 || now <= self.slide_t0 {
return 0.0
}
let p = (now - self.slide_t0).to_double() / slide_ms.to_double()
if p > 1.0 {
1.0
} else {
p
}
}
///| Start (or turn around) a slide, `slide_in` or out. A slide that is turned around midway
/// carries on from where it got to.
fn Widget::start_slide(self : Widget, slide_in : Bool) -> Unit {
let now = @sys.monotonic_ms()
let left = if self.slide_t0 != 0 {
let p = self.slide_progress(now)
if p < 1.0 {
((1.0 - p) * slide_ms.to_double()).to_uint64()
} else {
0UL
}
} else {
0UL
}
// Turning around at progress p starts the other way at progress 1 - p.
self.slide_t0 = if now > left { now - left } else { 1UL }
self.slide_in = slide_in
}
///| The widget's popup just opened.
fn DesktopShell::slide_in(self : DesktopShell, w : Widget) -> Unit {
ignore(self)
if w.slides() {
w.ghost_ops = []
w.ghost_rect = { x: 0, y: 0, w: 0, h: 0 }
w.start_slide(true)
}
}
///| The widget's popup just closed: it was at `rect` showing `ops`; slide that back in.
fn DesktopShell::slide_out(
self : DesktopShell,
w : Widget,
rect : @scene.Rect,
ops : Array[@types.DrawOp],
) -> Unit {
ignore(self)
if w.slides() {
w.ghost_rect = rect
w.ghost_ops = ops
w.start_slide(false)
}
}
///| True while a popup is sliding: the compositor then keeps drawing frames.
pub fn DesktopShell::animating(self : DesktopShell) -> Bool {
self.widgets.iter().any(w => w.slide_t0 != 0)
}
///| How far (pixels) a popup of height `h` is pushed back into the panel at slide progress `p`:
/// sliding in eases out (fast, then settling), sliding out eases in.
pub fn slide_offset(h : Int, p : Double, slide_in : Bool) -> Int {
let shown = if slide_in {
let q = 1.0 - p
1.0 - q * q * q
} else {
1.0 - p * p
}
((1.0 - shown) * h.to_double()).to_int()
}
///| Draw `w`'s popup (or the one sliding away) into `out`.
fn DesktopShell::draw_popup(self : DesktopShell, w : Widget, out : Array[@scene.DrawOp]) -> Unit {
let (rect, ops) = if w.popup_rect.w > 0 {
(w.popup_rect, w.popup_ops)
} else {
(w.ghost_rect, w.ghost_ops)
}
if rect.w <= 0 {
w.slide_t0 = 0
return
}
if w.slide_t0 == 0 {
if w.popup_rect.w > 0 {
translate(ops, rect.x, rect.y, out)
}
return
}
let p = w.slide_progress(@sys.monotonic_ms())
if p >= 1.0 {
// Done: drawn in place (or gone).
w.slide_t0 = 0
w.ghost_ops = []
w.ghost_rect = { x: 0, y: 0, w: 0, h: 0 }
if w.popup_rect.w > 0 {
translate(ops, rect.x, rect.y, out)
}
return
}
// A popup above the panel slides down into it; one below a top panel slides up.
let dir = if rect.y < self.panel_rect.y { 1 } else { -1 }
let dy = dir * slide_offset(rect.h, p, w.slide_in)
out.push(@scene.DrawOp::PushClip(rect))
translate(ops, rect.x, rect.y + dy, out)
out.push(@scene.DrawOp::PopClip)
}
///| The popup's drawn vertical offset from its place right now (0 when not sliding); for tests.
pub fn DesktopShell::slot_slide_offset(self : DesktopShell, slot : String) -> Int {
match self.widget_by_slot(slot) {
Some(w) if w.slide_t0 != 0 => {
let rect = if w.popup_rect.w > 0 { w.popup_rect } else { w.ghost_rect }
slide_offset(rect.h, w.slide_progress(@sys.monotonic_ms()), w.slide_in)
}
_ => 0
}
}
///|
test "slide offsets run from the panel to the popup's place and back" {
assert_eq(slide_offset(300, 0.0, true), 300)
assert_eq(slide_offset(300, 1.0, true), 0)
assert_true(slide_offset(300, 0.5, true) < 150) // eases out: most of the way after half the time
assert_eq(slide_offset(300, 0.0, false), 0)
assert_eq(slide_offset(300, 1.0, false), 300)
assert_true(slide_offset(300, 0.5, false) < 150) // eases in
}
+13
View File
@@ -309,6 +309,10 @@ pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? {
popup_rect: { x: 0, y: 0, w: 0, h: 0 },
popup_ops: [],
popup_hot: false,
slide_t0: 0,
slide_in: false,
ghost_rect: { x: 0, y: 0, w: 0, h: 0 },
ghost_ops: [],
}
self.next_slot = self.next_slot + 1
self.apply_module_cfg(w)
@@ -695,8 +699,14 @@ fn DesktopShell::refresh_popup(self : DesktopShell, w : Widget) -> Unit {
if self.widget_by_slot(w.slot) is None {
return
}
let was_open = w.popup_rect.w > 0
let old_rect = w.popup_rect
let old_ops = w.popup_ops
match w.pl.popup() {
None => {
if was_open {
self.slide_out(w, old_rect, old_ops)
}
w.popup_rect = { x: 0, y: 0, w: 0, h: 0 }
w.popup_ops = []
w.popup_hot = false
@@ -705,6 +715,9 @@ fn DesktopShell::refresh_popup(self : DesktopShell, w : Widget) -> Unit {
let (px, py) = @panel.popup_position(self.screen_w, self.screen_h - self.panel_h, w.rect.x, ps.w, ps.h, 6)
w.popup_rect = { x: px, y: py, w: ps.w, h: ps.h }
w.popup_ops = ps.ops
if !was_open {
self.slide_in(w)
}
}
}
}
+597
View File
@@ -0,0 +1,597 @@
///| The clocks' calendar flyout: left-click a clock and a month calendar slides out of the panel
/// (the shell does the slide). Pure logic: the month maths, the layout, drawing, hit testing and
/// the flyout's state; the clock modules only forward events and hand back `render`'s ops.
///|
pub fn is_leap(year : Int) -> Bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
///| Days in `month` (1-12) of `year`.
pub fn days_in_month(year : Int, month : Int) -> Int {
match month {
2 => if is_leap(year) { 29 } else { 28 }
4 | 6 | 9 | 11 => 30
_ => 31
}
}
///| Day of the week of a date, 0 = Sunday .. 6 = Saturday (Sakamoto's method).
pub fn weekday_of(year : Int, month : Int, day : Int) -> Int {
let t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
let y = if month < 3 { year - 1 } else { year }
(y + y / 4 - y / 100 + y / 400 + t[month - 1] + day) % 7
}
///| Day of the year, 1-366.
fn day_of_year(year : Int, month : Int, day : Int) -> Int {
let mut n = day
for m = 1; m < month; m = m + 1 {
n = n + days_in_month(year, m)
}
n
}
///| Weeks (52 or 53) in ISO year `year`.
fn iso_weeks_in_year(year : Int) -> Int {
// A year has 53 ISO weeks when it starts on a Thursday, or is a leap year starting on a Wednesday.
let jan1 = weekday_of(year, 1, 1)
if jan1 == 4 || (is_leap(year) && jan1 == 3) {
53
} else {
52
}
}
///| ISO 8601 week number (weeks start on Monday; week 1 holds the year's first Thursday).
pub fn iso_week(year : Int, month : Int, day : Int) -> Int {
let wd = (weekday_of(year, month, day) + 6) % 7 + 1 // Monday 1 .. Sunday 7
let w = (day_of_year(year, month, day) - wd + 10) / 7
if w < 1 {
iso_weeks_in_year(year - 1)
} else if w > iso_weeks_in_year(year) {
1
} else {
w
}
}
///|
let month_long : Array[String] = [
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December",
]
///|
let weekday_long : Array[String] = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
]
///|
let weekday_two : Array[String] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
///| One cell of the month grid: a date, and whether it belongs to the month shown.
#derive(Eq, Debug)
pub(all) struct DayCell {
year : Int
month : Int
day : Int
in_month : Bool
}
///| The 42 days (six weeks) shown for `month` of `year`, starting on Monday or Sunday: the
/// month's days plus the end of the month before and the start of the month after. Always six
/// rows, so the flyout keeps its size from month to month.
pub fn month_grid(year : Int, month : Int, monday_first : Bool) -> Array[DayCell] {
let first = weekday_of(year, month, 1)
let lead = if monday_first { (first + 6) % 7 } else { first }
let (py, pm) = if month == 1 { (year - 1, 12) } else { (year, month - 1) }
let (ny, nm) = if month == 12 { (year + 1, 1) } else { (year, month + 1) }
let prev_days = days_in_month(py, pm)
let days = days_in_month(year, month)
let out : Array[DayCell] = []
for i = 0; i < lead; i = i + 1 {
out.push({ year: py, month: pm, day: prev_days - lead + 1 + i, in_month: false })
}
for d = 1; d <= days; d = d + 1 {
out.push({ year, month, day: d, in_month: true })
}
let mut d = 1
while out.length() < 42 {
out.push({ year: ny, month: nm, day: d, in_month: false })
d = d + 1
}
out
}
// ---------------------------------------------------------------- the flyout
///| What a point in the flyout is over.
#derive(Eq, Debug)
pub(all) enum CalendarHit {
Prev
Next
Today
Nothing
}
///| The calendar flyout of one clock module: whether it is open, which month it shows, the
/// "Module settings" choices (week start, week numbers) and the button under the pointer.
pub(all) struct Calendar {
mut open : Bool
mut year : Int
mut month : Int
mut monday_first : Bool
mut week_numbers : Bool
mut hover : CalendarHit
}
///|
pub fn Calendar::new() -> Calendar {
{ open: false, year: 2026, month: 1, monday_first: false, week_numbers: false, hover: Nothing }
}
// Layout (popup-local pixels).
///|
let cal_margin : Int = 12
///|
let cal_cell_w : Int = 38
///|
let cal_cell_h : Int = 30
///|
let cal_weeknum_w : Int = 30
///| Top of the month/navigation row, of the weekday names and of the day grid.
let cal_nav_y : Int = 80
///|
let cal_nav_h : Int = 28
///|
let cal_names_y : Int = 114
///|
let cal_grid_y : Int = 140
///|
let cal_btn_w : Int = 28
///|
let cal_today_w : Int = 56
///| Left edge of the day grid (after the week-number column when it shows).
fn Calendar::grid_x(self : Calendar) -> Int {
cal_margin + (if self.week_numbers { cal_weeknum_w } else { 0 })
}
///| The flyout's size: (w, h).
pub fn Calendar::size(self : Calendar) -> (Int, Int) {
(self.grid_x() + 7 * cal_cell_w + cal_margin, cal_grid_y + 6 * cal_cell_h + cal_margin)
}
///| The previous-month, Today and next-month buttons, right-aligned in the navigation row:
/// (hit, x, w).
fn Calendar::buttons(self : Calendar) -> Array[(CalendarHit, Int, Int)] {
let (w, _) = self.size()
let next_x = w - cal_margin - cal_btn_w
let today_x = next_x - 4 - cal_today_w
let prev_x = today_x - 4 - cal_btn_w
[(Prev, prev_x, cal_btn_w), (Today, today_x, cal_today_w), (Next, next_x, cal_btn_w)]
}
///| What popup-local (x, y) is over.
pub fn Calendar::hit(self : Calendar, x : Int, y : Int) -> CalendarHit {
if y < cal_nav_y || y >= cal_nav_y + cal_nav_h {
return Nothing
}
for b in self.buttons() {
let (h, bx, bw) = b
if x >= bx && x < bx + bw {
return h
}
}
Nothing
}
///| Show the month holding `now`.
pub fn Calendar::go_today(self : Calendar, now : @types.Datetime) -> Unit {
self.year = now.year.reinterpret_as_int()
self.month = now.month.to_int()
}
///| Move the month shown by `delta` months.
pub fn Calendar::shift(self : Calendar, delta : Int) -> Unit {
let m = self.year * 12 + (self.month - 1) + delta
self.year = m / 12
self.month = m % 12 + 1
}
///| Open (on the current month) or close the flyout.
pub fn Calendar::toggle(self : Calendar, now : @types.Datetime) -> Unit {
if self.open {
self.open = false
} else {
self.open = true
self.go_today(now)
}
self.hover = Nothing
}
///| A clock module's input, as the plasmoid contract hands it over (`popup`: the event is for
/// the flyout rather than the clock itself). A click on the clock toggles the flyout; a click
/// elsewhere (focus-lost) or Escape closes it. True when it should be redrawn.
pub fn Calendar::handle(
self : Calendar,
popup : Bool,
ev : @types.InputEvent,
now : @types.Datetime,
) -> Bool {
match (popup, ev) {
(false, PointerDown(_)) => {
self.toggle(now)
true
}
(_, FocusLost) =>
if self.open {
self.open = false
self.hover = Nothing
true
} else {
false
}
(true, KeyDown(k)) =>
match k {
"Escape" => {
self.open = false
self.hover = Nothing
true
}
"t" | "T" => {
self.go_today(now)
true
}
"Left" | "p" => {
self.shift(-1)
true
}
"Right" | "n" => {
self.shift(1)
true
}
_ => false
}
(true, PointerDown(p)) =>
match self.hit(p.x, p.y) {
Prev => {
self.shift(-1)
true
}
Next => {
self.shift(1)
true
}
Today => {
self.go_today(now)
true
}
Nothing => false
}
(true, PointerMove(p)) => {
let h = self.hit(p.x, p.y)
if h != self.hover {
self.hover = h
true
} else {
false
}
}
(true, PointerLeave) =>
if self.hover != Nothing {
self.hover = Nothing
true
} else {
false
}
_ => false
}
}
///| The header's date line, e.g. "Wednesday, 25 November 2026".
pub fn long_date(now : @types.Datetime) -> String {
let wd = now.weekday.to_int()
let m = now.month.to_int()
weekday_long[wd % 7] +
", " +
now.day.to_int().to_string() +
" " +
month_long[(m + 11) % 12] +
" " +
now.year.to_string()
}
///| Draw the flyout: the time and date, the month with its buttons, the weekday names and the
/// day grid (today circled in the accent colour; other months' days muted), optionally with ISO
/// week numbers on the left. `hour12`/`ampm` follow the clock's own time format.
pub fn Calendar::render(
self : Calendar,
t : @theme.Tokens,
now : @types.Datetime,
hour12? : Bool = false,
ampm? : Bool = true,
) -> Array[@types.DrawOp] {
let (w, h) = self.size()
let p = t.palette
let fs = t.font_size.reinterpret_as_int()
let r = t.radius.reinterpret_as_int()
let ops : Array[@types.DrawOp] = [
@ui.fill_rect(@ui.rect(0, 0, w, h), p.surface_popup, radius=r),
@ui.stroke_rect(@ui.rect(0, 0, w, h), p.border, width=1, radius=r),
]
// Header: the time, large, and today's date under it.
let time = if hour12 {
let t12 = @timefmt.hhmm12(now.hour.to_int(), now.minute.to_int())
if ampm { t12 } else { t12[:t12.length() - 3].to_owned() }
} else {
@timefmt.hhmm(now.hour.to_int(), now.minute.to_int())
}
ops.push(@ui.text(cal_margin + 4, 30, time, fs + 14, p.foreground, bold=true))
ops.push(@ui.text(cal_margin + 4, 58, long_date(now), fs - 1, p.foreground_muted))
ops.push(@ui.fill_rect(@ui.rect(cal_margin, 72, w - 2 * cal_margin, 1), p.border))
// Month and year, then the previous / Today / next buttons.
let nav_mid = cal_nav_y + cal_nav_h / 2
ops.push(
@ui.text(
cal_margin + 4,
nav_mid,
month_long[self.month - 1] + " " + self.year.to_string(),
fs,
p.foreground,
bold=true,
),
)
for b in self.buttons() {
let (kind, bx, bw) = b
let rect = @ui.rect(bx, cal_nav_y, bw, cal_nav_h)
if self.hover == kind {
ops.push(@ui.fill_rect(rect, p.surface_hover, radius=r))
}
let cx = bx + bw / 2
match kind {
Prev => {
ops.push(@ui.line(cx + 3, nav_mid - 6, cx - 3, nav_mid, p.foreground, width=2))
ops.push(@ui.line(cx - 3, nav_mid, cx + 3, nav_mid + 6, p.foreground, width=2))
}
Next => {
ops.push(@ui.line(cx - 3, nav_mid - 6, cx + 3, nav_mid, p.foreground, width=2))
ops.push(@ui.line(cx + 3, nav_mid, cx - 3, nav_mid + 6, p.foreground, width=2))
}
Today => {
ops.push(@ui.stroke_rect(rect, p.border, width=1, radius=r))
ops.push(@ui.text(cx, nav_mid, "Today", fs - 3, p.foreground, align=CENTER))
}
Nothing => ()
}
}
// Weekday names.
let gx = self.grid_x()
let names_mid = cal_names_y + 11
if self.week_numbers {
ops.push(@ui.text(cal_margin + cal_weeknum_w / 2 - 2, names_mid, "Wk", fs - 4, p.foreground_muted, align=CENTER))
}
for c = 0; c < 7; c = c + 1 {
let wd = if self.monday_first { (c + 1) % 7 } else { c }
ops.push(
@ui.text(gx + c * cal_cell_w + cal_cell_w / 2, names_mid, weekday_two[wd], fs - 4, p.foreground_muted, align=CENTER, bold=true),
)
}
// The days.
let cells = month_grid(self.year, self.month, self.monday_first)
let ty = now.year.reinterpret_as_int()
let tm = now.month.to_int()
let td = now.day.to_int()
for i = 0; i < cells.length(); i = i + 1 {
let cell = cells[i]
let row = i / 7
let col = i % 7
let cx = gx + col * cal_cell_w + cal_cell_w / 2
let cy = cal_grid_y + row * cal_cell_h + cal_cell_h / 2
if col == 0 && self.week_numbers {
// The ISO week of the row's Thursday (Monday-first rows) or Monday (Sunday-first rows).
let k = if self.monday_first { i + 3 } else { i + 1 }
let ref_ = cells[k]
ops.push(
@ui.text(cal_margin + cal_weeknum_w / 2 - 2, cy, iso_week(ref_.year, ref_.month, ref_.day).to_string(), fs - 4, @ui.with_alpha(p.foreground_muted, 170), align=CENTER),
)
}
let is_today = cell.year == ty && cell.month == tm && cell.day == td
let colr = if is_today {
ops.push(@ui.circle(cx, cy, cal_cell_h / 2 - 2, p.accent))
p.accent_foreground
} else if cell.in_month {
p.foreground
} else {
@ui.with_alpha(p.foreground_muted, 130)
}
ops.push(@ui.text(cx, cy, cell.day.to_string(), fs - 2, colr, align=CENTER, bold=is_today))
}
ops
}
///| The flyout's two "Module settings" items, appended to a clock's own.
fn Calendar::config_items(self : Calendar) -> Array[ConfigEntry] {
[
{
key: "week-start",
label: "Week starts on",
choices: ["Sunday", "Monday"],
value: if self.monday_first { "Monday" } else { "Sunday" },
},
{ key: "week-numbers", label: "Show week numbers", choices: [], value: on_off(self.week_numbers) },
]
}
///| Apply a calendar setting; true when it changed something.
fn Calendar::set(self : Calendar, key : String, value : String) -> Bool {
match (key, value) {
("week-start", "Monday") if !self.monday_first => { self.monday_first = true; true }
("week-start", "Sunday") if self.monday_first => { self.monday_first = false; true }
("week-numbers", "on") if !self.week_numbers => { self.week_numbers = true; true }
("week-numbers", "off") if self.week_numbers => { self.week_numbers = false; true }
_ => false
}
}
// ---------------------------------------------------------------- tests
///|
fn cal_time(y : Int, m : Int, d : Int) -> @types.Datetime {
{
year: y.reinterpret_as_uint(),
month: m.to_byte(),
day: d.to_byte(),
hour: b'\x0E',
minute: b'\x07',
second: b'\x00',
weekday: weekday_of(y, m, d).to_byte(),
}
}
///|
test "month maths" {
assert_eq(weekday_of(2026, 11, 25), 3) // a Wednesday
assert_eq(weekday_of(2000, 1, 1), 6)
assert_eq(days_in_month(2024, 2), 29)
assert_eq(days_in_month(2100, 2), 28)
assert_eq(days_in_month(2000, 2), 29)
assert_eq(days_in_month(2026, 4), 30)
// ISO weeks, including the edges of the year.
assert_eq(iso_week(2026, 11, 25), 48)
assert_eq(iso_week(2021, 1, 1), 53) // belongs to 2020's week 53
assert_eq(iso_week(2024, 12, 30), 1) // belongs to 2025's week 1
assert_eq(iso_week(2026, 1, 1), 1)
assert_eq(iso_week(2027, 1, 3), 53)
}
///|
test "the month grid is six weeks from the chosen first weekday" {
// November 2026 starts on a Sunday.
let sun = month_grid(2026, 11, false)
assert_eq(sun.length(), 42)
assert_eq(sun[0], { year: 2026, month: 11, day: 1, in_month: true })
assert_eq(sun[29].day, 30)
assert_eq(sun[30], { year: 2026, month: 12, day: 1, in_month: false })
let mon = month_grid(2026, 11, true)
assert_eq(mon[0], { year: 2026, month: 10, day: 26, in_month: false })
assert_eq(mon[6], { year: 2026, month: 11, day: 1, in_month: true })
// January wraps to the December before.
let jan = month_grid(2027, 1, true)
assert_eq(jan[0], { year: 2026, month: 12, day: 28, in_month: false })
}
///|
test "clicks open and close the flyout; its buttons change the month" {
let now = cal_time(2026, 11, 25)
let c = Calendar::new()
assert_true(c.handle(false, PointerDown({ x: 3, y: 3 }), now))
assert_true(c.open)
assert_eq((c.year, c.month), (2026, 11))
let click = fn(h : CalendarHit) {
for b in c.buttons() {
let (k, x, w) = b
if k == h {
return c.handle(true, PointerDown({ x: x + w / 2, y: cal_nav_y + 5 }), now)
}
}
false
}
assert_true(click(Next))
assert_true(click(Next))
assert_eq((c.year, c.month), (2027, 1))
assert_true(click(Prev))
assert_true(click(Prev))
assert_true(click(Prev))
assert_eq((c.year, c.month), (2026, 10))
assert_true(click(Today))
assert_eq((c.year, c.month), (2026, 11))
// A click on a day does nothing; hovering a button highlights it.
assert_false(c.handle(true, PointerDown({ x: 40, y: cal_grid_y + 10 }), now))
let (bx, bw) = match c.buttons()[0] { (_, x, w) => (x, w) }
assert_true(c.handle(true, PointerMove({ x: bx + bw / 2, y: cal_nav_y + 5 }), now))
assert_eq(c.hover, Prev)
assert_true(c.handle(true, PointerLeave, now))
// Escape closes; clicking the clock again toggles; a click elsewhere closes.
assert_true(c.handle(true, KeyDown("Escape"), now))
assert_false(c.open)
c.shift(5)
assert_true(c.handle(false, PointerDown({ x: 0, y: 0 }), now))
assert_eq((c.year, c.month), (2026, 11)) // reopens on the current month
assert_true(c.handle(false, PointerDown({ x: 0, y: 0 }), now))
assert_false(c.open)
assert_true(c.handle(false, PointerDown({ x: 0, y: 0 }), now))
assert_true(c.handle(false, FocusLost, now))
assert_false(c.open)
assert_false(c.handle(false, FocusLost, now))
}
///|
test "the flyout draws the header, the month and today" {
let now = cal_time(2026, 11, 25)
let c = Calendar::new()
c.toggle(now)
let texts = fn(ops : Array[@types.DrawOp]) {
let out : Array[String] = []
for op in ops {
match op {
Text(t) => out.push(t.text)
_ => ()
}
}
out
}
let tk = test_tokens()
let ops = c.render(tk, now, hour12=true)
let ts = texts(ops)
assert_eq(ts[0], "2:07 PM")
assert_eq(ts[1], "Wednesday, 25 November 2026")
assert_eq(ts[2], "November 2026")
assert_true(ts.contains("Today"))
assert_eq(ts.filter(s => s == "Su" || s == "Mo").length(), 2)
// Today is circled.
let circles = ops.filter(op => op is Circle(_))
assert_eq(circles.length(), 1)
// Not on another month.
c.shift(1)
assert_eq(c.render(tk, now).filter(op => op is Circle(_)).length(), 0)
// Week numbers widen it and add one number per row; Monday-first puts "Mo" first.
let (w0, h0) = c.size()
c.shift(-1)
assert_true(c.set("week-numbers", "on"))
assert_true(c.set("week-start", "Monday"))
assert_false(c.set("week-start", "Monday"))
let (w1, h1) = c.size()
assert_eq(h1, h0)
assert_eq(w1, w0 + cal_weeknum_w)
let ts = texts(c.render(tk, now))
assert_true(ts.contains("Wk"))
let names = ts.filter(s => s.length() == 2 && s[0] >= 'A' && s[0] <= 'Z' && s != "Wk")
assert_eq(names[0], "Mo")
assert_true(ts.contains("44") && ts.contains("48") && ts.contains("49"))
}
///|
test "the clocks' module settings include the calendar's" {
let c = ClockConfig::new()
let items = c.binary_items()
assert_eq(items.map(i => i.key), ["seconds", "week-start", "week-numbers"])
assert_eq(items[1].value, "Sunday")
assert_true(c.set("week-start", "Monday"))
assert_true(c.cal.monday_first)
assert_eq(c.digital_items().filter(i => i.key == "week-start")[0].value, "Monday")
assert_true(c.set("week-numbers", "on"))
assert_eq(c.binary_items()[2].value, "on")
assert_false(c.set("week-start", "Tuesday"))
}
+10 -5
View File
@@ -189,11 +189,13 @@ pub(all) struct ClockConfig {
mut show_date : Bool
mut seconds : Bool
mut ampm : Bool
/// The clock's calendar flyout (left click), with its week-start and week-number settings.
cal : Calendar
}
///|
pub fn ClockConfig::new(hour12? : Bool = false) -> ClockConfig {
{ hour12, show_date: true, seconds: true, ampm: true }
{ hour12, show_date: true, seconds: true, ampm: true, cal: Calendar::new() }
}
///|
@@ -215,12 +217,15 @@ pub fn ClockConfig::digital_items(self : ClockConfig) -> Array[ConfigEntry] {
items.push({ key: "ampm", label: "Show AM/PM", choices: [], value: on_off(self.ampm) })
}
items.push({ key: "date", label: "Show date", choices: [], value: on_off(self.show_date) })
items.append(self.cal.config_items())
items
}
///| The binary clock's settings: whether the seconds columns show.
pub fn ClockConfig::binary_items(self : ClockConfig) -> Array[ConfigEntry] {
[{ key: "seconds", label: "Show seconds", choices: [], value: on_off(self.seconds) }]
let items = [{ key: "seconds", label: "Show seconds", choices: [], value: on_off(self.seconds) }]
items.append(self.cal.config_items())
items
}
///| Apply one setting; true when it changed something. Unknown keys and values are ignored.
@@ -242,7 +247,7 @@ pub fn ClockConfig::set(self : ClockConfig, key : String, value : String) -> Boo
"date" => flag(self.show_date, fn(b) { self.show_date = b })
"ampm" => flag(self.ampm, fn(b) { self.ampm = b })
"seconds" => flag(self.seconds, fn(b) { self.seconds = b })
_ => false
_ => self.cal.set(key, value)
}
}
@@ -276,7 +281,7 @@ pub let binary_config : ClockConfig = ClockConfig::new()
test "12-hour clock shows AM/PM, and it can be switched off" {
let c = ClockConfig::new(hour12=true)
let items = c.digital_items()
assert_eq(items.map(i => i.key), ["format", "ampm", "date"])
assert_eq(items.map(i => i.key), ["format", "ampm", "date", "week-start", "week-numbers"])
assert_eq(items[1].value, "on")
let ops = render_digital(@ui.size(120, 36), test_tokens(), test_time(), hour12=true)
match ops[0] {
@@ -296,5 +301,5 @@ test "12-hour clock shows AM/PM, and it can be switched off" {
}
// AM/PM is only offered in 12-hour mode
assert_true(c.set("format", "24-hour"))
assert_eq(c.digital_items().map(i => i.key), ["format", "date"])
assert_eq(c.digital_items().map(i => i.key), ["format", "date", "week-start", "week-numbers"])
}