~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
213 lines · 8.7 KB Raw History
const std = @import("std");
const store = @import("../../storage/store.zig");

pub const Signal = struct {
    /// Rules for the page's per-request `<style>` element.
    style: []const u8,
    html: []const u8,
};

pub fn fromState(
    allocator: std.mem.Allocator,
    residents: []const store.Resident,
    collections: []const store.CollectionSummary,
    activity: store.Activity,
    range: store.ActivityRange,
    /// `&resident=…` or empty, carried by the range links.
    scope_query: []const u8,
) !Signal {
    var hash = std.hash.Wyhash.init(0x7a_64_73);
    for (residents) |resident| {
        hash.update(resident.did);
        hash.update(resident.handle);
        var buf: [16]u8 = undefined;
        hash.update(try std.fmt.bufPrint(&buf, "{d}", .{resident.record_count}));
    }
    for (collections) |collection| {
        hash.update(collection.collection);
        var buf: [16]u8 = undefined;
        hash.update(try std.fmt.bufPrint(&buf, "{d}", .{collection.count}));
    }
    for (activity.buckets) |bucket| {
        var buf: [32]u8 = undefined;
        hash.update(try std.fmt.bufPrint(&buf, "{d}", .{bucket.count}));
    }
    const seed = hash.final();
    const hue_a: u16 = @intCast(seed % 360);
    const hue_b: u16 = @intCast((seed >> 11) % 360);
    const hue_c: u16 = @intCast((seed >> 23) % 360);
    var style: std.Io.Writer.Allocating = .init(allocator);
    defer style.deinit();
    try style.writer.print(
        "body{{--signal-a:hsl({d} 76% 62%);--signal-b:hsl({d} 84% 66%);--signal-c:hsl({d} 78% 65%)}}",
        .{ hue_a, hue_b, hue_c },
    );

    var html: std.Io.Writer.Allocating = .init(allocator);
    defer html.deinit();
    const w = &html.writer;
    const buckets = activity.buckets;

    var max_count: u64 = 1;
    var total_count: u64 = 0;
    for (buckets) |bucket| {
        max_count = @max(max_count, bucket.count);
        total_count += bucket.count;
    }

    try w.writeAll("<div class=\"entropy\" data-activity><div class=\"entropy-top\"><span class=\"entropy-label\">");
    const span = try spanLabel(allocator, range, buckets);
    if (total_count == 0) {
        try w.print("no records written {s}", .{span});
    } else {
        try w.print("<b>{f}</b> record{s} written {s}", .{ grouped(total_count), if (total_count == 1) "" else "s", span });
    }
    try w.writeAll("</span><div class=\"ranges\" role=\"group\" aria-label=\"time range\">");
    for (std.enums.values(store.ActivityRange)) |option| {
        const current = if (option == range) " aria-current=\"page\"" else "";
        try w.print("<a href=\"/?range={s}{s}\"{s}>{s}</a>", .{ option.label(), scope_query, current, option.label() });
    }
    try w.writeAll("</div></div>");

    if (buckets.len == 0) {
        try w.writeAll("<span class=\"signal-empty\">waiting for writes</span></div>");
        return .{ .style = try style.toOwnedSlice(), .html = try html.toOwnedSlice() };
    }

    try w.writeAll("<span class=\"entropy-bars\" tabindex=\"0\" role=\"group\" aria-label=\"records written per bar; use the arrow keys to read each\">");
    for (buckets, 1..) |bucket, position| {
        const label = try bucketLabel(allocator, range, activity.monthly, bucket);
        try style.writer.print(".entropy-bars i:nth-child({d}){{--h:{d}px}}", .{ position, scaledHeight(bucket.count, max_count) });
        try w.print("<i data-label=\"{s} · {f} record{s}\"></i>", .{ label, grouped(bucket.count), if (bucket.count == 1) "" else "s" });
    }
    try w.writeAll("</span><span class=\"entropy-axis\">");
    const middle = buckets[buckets.len / 2];
    for ([_]u64{ buckets[0].start_us, middle.start_us, buckets[buckets.len - 1].start_us }) |time| {
        try w.print("<span>{s}</span>", .{try axisLabel(allocator, range, time)});
    }
    const last = buckets[buckets.len - 1];
    try w.print("</span><p class=\"entropy-read\" aria-live=\"polite\">{s} · {f} record{s}</p></div>", .{
        try bucketLabel(allocator, range, activity.monthly, last), grouped(last.count), if (last.count == 1) "" else "s",
    });
    return .{ .style = try style.toOwnedSlice(), .html = try html.toOwnedSlice() };
}

fn scaledHeight(count: u64, max_count: u64) u64 {
    if (count == 0) return 4;
    const count_root = std.math.sqrt(@as(f64, @floatFromInt(count)));
    const max_root = std.math.sqrt(@as(f64, @floatFromInt(@max(max_count, 1))));
    return 8 + @as(u64, @intFromFloat(@round(count_root * 48.0 / max_root)));
}

fn spanLabel(allocator: std.mem.Allocator, range: store.ActivityRange, buckets: []const store.ActivityBucket) ![]const u8 {
    return switch (range) {
        .day => "in the past 24 hours",
        .week => "in the past 7 days",
        .month => "in the past 30 days",
        .year => "in the past year",
        .all => if (buckets.len == 0) "yet" else blk: {
            const first = civilFromMicros(buckets[0].start_us);
            break :blk try std.fmt.allocPrint(allocator, "since {s} {d}", .{ monthName(first.month), first.year });
        },
    };
}

fn axisLabel(allocator: std.mem.Allocator, range: store.ActivityRange, time: u64) ![]const u8 {
    const civil = civilFromMicros(time);
    return switch (range) {
        .day => std.fmt.allocPrint(allocator, "{d:0>2}:00", .{civil.hour}),
        .week, .month, .year => std.fmt.allocPrint(allocator, "{s} {d}", .{ monthName(civil.month), civil.day }),
        .all => std.fmt.allocPrint(allocator, "{s} {d}", .{ monthName(civil.month), civil.year }),
    };
}

fn bucketLabel(allocator: std.mem.Allocator, range: store.ActivityRange, monthly: bool, bucket: store.ActivityBucket) ![]const u8 {
    const start = civilFromMicros(bucket.start_us);
    const end = civilFromMicros(bucket.end_us - 1);
    if (monthly) {
        if (start.year == end.year and start.month == end.month) {
            return std.fmt.allocPrint(allocator, "{s} {d}", .{ monthName(start.month), start.year });
        }
        return std.fmt.allocPrint(allocator, "{s} {d}–{s} {d}", .{ monthName(start.month), start.year, monthName(end.month), end.year });
    }
    return switch (range) {
        .day, .week => std.fmt.allocPrint(allocator, "{s} {d}, {d:0>2}:00–{d:0>2}:00 UTC", .{
            monthName(start.month), start.day, start.hour, (@as(u16, end.hour) + 1) % 24,
        }),
        .month => std.fmt.allocPrint(allocator, "{s} {d}", .{ monthName(start.month), start.day }),
        .year, .all => std.fmt.allocPrint(allocator, "{s} {d}–{s} {d}", .{ monthName(start.month), start.day, monthName(end.month), end.day }),
    };
}

/// A count with thousands separators: 37,446.
pub fn grouped(value: u64) Grouped {
    return .{ .value = value };
}

pub const Grouped = struct {
    value: u64,

    pub fn format(self: Grouped, w: *std.Io.Writer) std.Io.Writer.Error!void {
        var buf: [24]u8 = undefined;
        const digits = std.fmt.bufPrint(&buf, "{d}", .{self.value}) catch unreachable;
        for (digits, 0..) |c, i| {
            if (i > 0 and (digits.len - i) % 3 == 0) try w.writeByte(',');
            try w.writeByte(c);
        }
    }
};

const Civil = struct {
    year: i64,
    month: u8,
    day: u8,
    hour: u8,
    minute: u8,
};

fn civilFromMicros(timestamp_us: u64) Civil {
    const timestamp_s: i64 = @intCast(timestamp_us / std.time.us_per_s);
    const days = @divFloor(timestamp_s, std.time.s_per_day);
    const seconds_of_day = @mod(timestamp_s, std.time.s_per_day);
    const date = civilFromDays(days);
    return .{
        .year = date.year,
        .month = date.month,
        .day = date.day,
        .hour = @intCast(@divFloor(seconds_of_day, std.time.s_per_hour)),
        .minute = @intCast(@divFloor(@mod(seconds_of_day, std.time.s_per_hour), std.time.s_per_min)),
    };
}

fn civilFromDays(days_since_epoch: i64) struct { year: i64, month: u8, day: u8 } {
    const z = days_since_epoch + 719468;
    const era = if (z >= 0) @divFloor(z, 146097) else @divFloor(z - 146096, 146097);
    const doe: u64 = @intCast(z - era * 146097);
    const yoe = @divFloor(doe - @divFloor(doe, 1460) + @divFloor(doe, 36524) - @divFloor(doe, 146096), 365);
    var year: i64 = @intCast(yoe);
    year += era * 400;
    const doy = doe - (365 * yoe + @divFloor(yoe, 4) - @divFloor(yoe, 100));
    const mp = @divFloor(5 * doy + 2, 153);
    const day = doy - @divFloor(153 * mp + 2, 5) + 1;
    const month = if (mp < 10) mp + 3 else mp - 9;
    year += if (month <= 2) 1 else 0;
    return .{ .year = year, .month = @intCast(month), .day = @intCast(day) };
}

fn monthName(month: u8) []const u8 {
    return switch (month) {
        1 => "Jan",
        2 => "Feb",
        3 => "Mar",
        4 => "Apr",
        5 => "May",
        6 => "Jun",
        7 => "Jul",
        8 => "Aug",
        9 => "Sep",
        10 => "Oct",
        11 => "Nov",
        12 => "Dec",
        else => "?",
    };
}