summaryrefslogtreecommitdiff
path: root/templates/stats.html
blob: efb952ce68caf304bea1bb6959fcf1f91597a42c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
{% extends "base.html" %}

{% block title %}Stats · Lumière{% endblock %}

{% block content %}
  <section class="stats-hero">
    <div class="stats-hero-copy">
      <p class="eyebrow">Stats</p>
      <h1>Watching patterns</h1>
      <p class="stats-hero-text">A research spread for your diary: the geography of what you watch, the people and genres that recur, and the rhythms that define a year of logging.</p>
    </div>
    <div class="stats-hero-actions">
      <a class="button-link" href="/stats/year-in-review">Year in review</a>
    </div>
  </section>

  <section class="stats-summary">
    <article class="stats-summary-card">
      <span class="summary-label">Films watched</span>
      <strong id="stats-total-films">—</strong>
    </article>
    <article class="stats-summary-card">
      <span class="summary-label">Total runtime</span>
      <strong id="stats-total-runtime">—</strong>
    </article>
    <article class="stats-summary-card">
      <span class="summary-label">Average stars</span>
      <strong><span id="stats-average-stars">—</span><span class="stats-average-mark" aria-hidden="true">✦</span></strong>
    </article>
    <article class="stats-summary-card">
      <span class="summary-label">Rewatch rate</span>
      <strong id="stats-rewatch-rate">—</strong>
    </article>
  </section>

  <section class="stats-context-strip">
    <article class="stats-context-card">
      <span class="summary-label">Top director</span>
      <strong id="stats-top-director">—</strong>
      <p id="stats-top-director-meta" class="stats-context-meta">No repeat viewings yet.</p>
    </article>
    <article class="stats-context-card">
      <span class="summary-label">Most active month</span>
      <strong id="stats-top-month">—</strong>
      <p id="stats-top-month-meta" class="stats-context-meta">No monthly cluster yet.</p>
    </article>
    <article class="stats-context-card">
      <span class="summary-label">Countries logged</span>
      <strong id="stats-country-count">—</strong>
      <p class="stats-context-meta">Based on films with country metadata.</p>
    </article>
  </section>

  <section class="stats-research">
    <section class="stats-panel stats-panel-feature">
      <div class="stats-panel-header">
        <div>
          <p class="eyebrow">World map</p>
          <h2>Films by country</h2>
        </div>
        <p class="stats-panel-note">The map functions as a reading aid. Hover to inspect where your diary clusters geographically.</p>
      </div>
      <div class="stats-map-shell">
        <div id="world-map" class="stats-map" aria-label="World map of watched films"></div>
        <div id="map-readout" class="map-readout" aria-live="polite">
          <strong>Hover a country</strong>
          <span>Film count will appear here.</span>
        </div>
      </div>
      <div id="map-tooltip" class="stats-tooltip" hidden></div>
    </section>

    <section class="stats-panel stats-panel-feature">
      <div class="stats-panel-header">
        <div>
          <p class="eyebrow">Calendar</p>
          <h2>Past 365 days</h2>
        </div>
        <p class="stats-panel-note">A density view of your diary cadence over the trailing year.</p>
      </div>
      <div id="watch-heatmap" class="heatmap-shell" aria-label="Daily watch heatmap"></div>
    </section>

    <section class="stats-column">
      <section class="stats-panel">
        <div class="stats-panel-header">
          <div>
            <p class="eyebrow">Directors</p>
            <h2>Most watched</h2>
          </div>
        </div>
        <ol id="top-directors" class="stats-list"></ol>
      </section>

      <section class="stats-panel">
        <div class="stats-panel-header">
          <div>
            <p class="eyebrow">Genres</p>
            <h2>Most watched</h2>
          </div>
        </div>
        <ol id="top-genres" class="stats-list"></ol>
      </section>

      <section class="stats-panel">
        <div class="stats-panel-header">
          <div>
            <p class="eyebrow">Companions</p>
            <h2>Watched with</h2>
          </div>
        </div>
        <ol id="watched-with" class="stats-list"></ol>
      </section>
    </section>

    <section class="stats-column">
      <section class="stats-panel">
        <div class="stats-panel-header">
          <div>
            <p class="eyebrow">Stars</p>
            <h2>Distribution</h2>
          </div>
        </div>
        <div id="star-distribution" class="stats-bars"></div>
      </section>

      <section class="stats-panel">
        <div class="stats-panel-header">
          <div>
            <p class="eyebrow">Films</p>
            <h2>Rewatches</h2>
          </div>
        </div>
        <div id="rewatch-patterns-list" class="stats-list"></div>
      </section>

      <section class="stats-panel">
        <div class="stats-panel-header">
          <div>
            <p class="eyebrow">Decades</p>
            <h2>By era</h2>
          </div>
        </div>
        <ol id="film-decades" class="stats-list"></ol>
      </section>
    </section>
  </section>
{% endblock %}

{% block scripts %}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/3.0.2/topojson.min.js"></script>
  <script>
    const PANEL_COLOR = getComputedStyle(document.documentElement).getPropertyValue("--panel").trim();
    const PANEL_SOFT_COLOR = getComputedStyle(document.documentElement).getPropertyValue("--panel-soft").trim();
    const ACCENT_COLOR = getComputedStyle(document.documentElement).getPropertyValue("--accent").trim();

    function heatmapColor(count) {
      if (count <= 0) return PANEL_SOFT_COLOR;
      if (count === 1) return "rgba(240, 184, 77, 0.35)";
      if (count === 2) return "rgba(240, 184, 77, 0.65)";
      return ACCENT_COLOR;
    }

    function formatMonthLabel(dateString) {
      return new Date(`${dateString}T00:00:00`).toLocaleDateString(undefined, { month: "short" });
    }

    function formatStatsMonth(monthKey) {
      if (!monthKey) return "—";
      const [year, month] = monthKey.split("-");
      const date = new Date(Number(year), Number(month) - 1, 1);
      return date.toLocaleDateString(undefined, { month: "long", year: "numeric" });
    }

    function formatCountryCode(value) {
      return String(value).padStart(3, "0");
    }

    function formatRuntime(minutes) {
      if (!minutes) return "0h";
      const totalHours = Math.floor(minutes / 60);
      if (totalHours >= 24) {
        const days = Math.floor(totalHours / 24);
        const hours = totalHours % 24;
        return hours > 0 ? `${days}d ${hours}h` : `${days}d`;
      }
      const mins = minutes % 60;
      return mins > 0 ? `${totalHours}h ${mins}m` : `${totalHours}h`;
    }

    function renderLists(data) {
      const totalFilms = document.getElementById("stats-total-films");
      if (totalFilms) totalFilms.textContent = data.total_watched;

      const totalRuntime = document.getElementById("stats-total-runtime");
      if (totalRuntime) totalRuntime.textContent = formatRuntime(data.total_runtime_minutes);

      const averageStars = document.getElementById("stats-average-stars");
      if (averageStars) averageStars.textContent = data.average_stars ? data.average_stars.toFixed(1) : "—";

      const rewatchRate = document.getElementById("stats-rewatch-rate");
      if (rewatchRate) rewatchRate.textContent = data.rewatch_rate ? `${Math.round(data.rewatch_rate.rate * 100)}%` : "—";

      const topDirector = document.getElementById("stats-top-director");
      const topDirectorMeta = document.getElementById("stats-top-director-meta");
      if (topDirector) topDirector.textContent = data.top_director ? data.top_director.director : "—";
      if (topDirectorMeta) topDirectorMeta.textContent = data.top_director ? `${data.top_director.count} films logged` : "No repeat viewings yet.";

      const topMonth = document.getElementById("stats-top-month");
      const topMonthMeta = document.getElementById("stats-top-month-meta");
      if (topMonth) topMonth.textContent = data.top_month ? formatStatsMonth(data.top_month.month) : "—";
      if (topMonthMeta) topMonthMeta.textContent = data.top_month ? `${data.top_month.count} diary entries` : "No monthly cluster yet.";

      const countryCount = document.getElementById("stats-country-count");
      if (countryCount) countryCount.textContent = data.films_per_country.length;

      const topDirectors = document.getElementById("top-directors");
      topDirectors.innerHTML = data.most_watched_directors.slice(0, 8).map((item) => `
        <li><span>${item.director}</span><strong>${item.count}</strong></li>
      `).join("");

      const watchedWith = document.getElementById("watched-with");
      watchedWith.innerHTML = data.watched_with_breakdown
        .filter((item) => item.watched_with.toLowerCase() !== "solo")
        .slice(0, 8)
        .map((item) => `
        <li><span>${item.watched_with}</span><strong>${item.count}</strong></li>
      `).join("");

      const topGenres = document.getElementById("top-genres");
      topGenres.innerHTML = data.films_per_genre.slice(0, 8).map((item) => `
        <li><span>${item.genre}</span><strong>${item.count}</strong></li>
      `).join("");

      const filmDecades = document.getElementById("film-decades");
      filmDecades.innerHTML = data.films_per_decade.map((item) => `
        <li><span>${item.decade}</span><strong>${item.count}</strong></li>
      `).join("");

      const starDistribution = document.getElementById("star-distribution");
      const maxStars = Math.max(1, ...data.star_distribution.map((item) => item.count));
      starDistribution.innerHTML = data.star_distribution.map((item) => `
        <div class="stats-bar-row">
          <span>${item.stars} star</span>
          <div class="stats-bar-track"><div class="stats-bar-fill" style="width:${(item.count / maxStars) * 100}%"></div></div>
          <strong>${item.count}</strong>
        </div>
      `).join("");

      const rewatchPatterns = document.getElementById("rewatch-patterns-list");
      if (data.rewatch_patterns && data.rewatch_patterns.length > 0) {
        rewatchPatterns.innerHTML = data.rewatch_patterns.map((item) => {
          const stars = (n) => (n > 0 ? "✦".repeat(n) : "—");
          const ratingHistory = item.ratings.map(stars).join(" → ");
          const drift = item.rating_changed
            ? `<span style="color:var(--accent)">${ratingHistory}</span>`
            : `<span style="color:var(--muted)">${ratingHistory}</span>`;
          const gap = item.days_between != null
            ? `<span style="color:var(--subtle);font-size:13px">${item.days_between}d apart</span>`
            : "";
          return `<div class="stats-list-row stats-list-row-rewatch">
            <span>${item.title}</span>
            <span style="display:flex;gap:12px;align-items:center">${gap}${drift}<strong>${item.watches}×</strong></span>
          </div>`;
        }).join("");
      } else {
        rewatchPatterns.innerHTML = "<p style=\"color:var(--muted);font-size:14px;margin:0\">No rewatches yet.</p>";
      }
    }

    function renderHeatmap(days) {
      const container = document.getElementById("watch-heatmap");
      const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
      const parsedDays = days.map((item) => {
        const date = new Date(`${item.date}T00:00:00`);
        return { ...item, dateObj: date };
      });

      const containerWidth = container.clientWidth || 720;
      const maxCell = 13;
      const minCell = 8;
      const weekdayWidth = containerWidth < 640 ? 20 : 34;
      const gap = containerWidth < 640 ? 2 : 4;
      const availableWidth = Math.max(53 * minCell, containerWidth - weekdayWidth - 8);
      const computedCell = Math.floor((availableWidth - (52 * gap)) / 53);
      const cellSize = Math.max(minCell, Math.min(maxCell, computedCell));

      container.style.setProperty("--heatmap-cell", `${cellSize}px`);
      container.style.setProperty("--heatmap-gap", `${gap}px`);
      container.style.setProperty("--heatmap-weekday-width", `${weekdayWidth}px`);

      const firstWeekStart = new Date(parsedDays[0].dateObj);
      const mondayOffset = (firstWeekStart.getDay() + 6) % 7;
      firstWeekStart.setDate(firstWeekStart.getDate() - mondayOffset);

      const monthLabels = [];
      const seenMonths = new Set();
      const cells = parsedDays.map((item) => {
        const diffDays = Math.floor((item.dateObj - firstWeekStart) / 86400000);
        const week = Math.floor(diffDays / 7);
        const weekday = (item.dateObj.getDay() + 6) % 7;
        const monthKey = item.date.slice(0, 7);
        if (!seenMonths.has(monthKey)) {
          seenMonths.add(monthKey);
          monthLabels.push({ week, label: formatMonthLabel(item.date) });
        }
        return `
          <button
            class="heatmap-cell"
            style="grid-column:${week + 1};grid-row:${weekday + 1};background:${heatmapColor(item.count)}"
            title="${item.date}: ${item.count} film${item.count === 1 ? "" : "s"}"
            aria-label="${item.date}: ${item.count} film${item.count === 1 ? "" : "s"}"
            type="button"
          ></button>
        `;
      }).join("");

      container.innerHTML = `
        <div class="heatmap-months">
          ${monthLabels.map((item) => `<span style="grid-column:${item.week + 1}">${item.label}</span>`).join("")}
        </div>
        <div class="heatmap-body">
          <div class="heatmap-weekdays">
            ${weekdays.map((label) => `<span>${label}</span>`).join("")}
          </div>
          <div class="heatmap-grid">${cells}</div>
        </div>
      `;
    }

    async function renderMap(data) {
      const container = document.getElementById("world-map");
      const readout = document.getElementById("map-readout");
      const tooltip = document.getElementById("map-tooltip");
      const [worldResponse, namesResponse] = await Promise.all([
        fetch("https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json"),
        fetch("https://cdn.jsdelivr.net/gh/lukes/ISO-3166-Countries-with-Regional-Codes@master/all/all.json"),
      ]);
      const [world, countryRows] = await Promise.all([worldResponse.json(), namesResponse.json()]);
      const counts = new Map(data.films_per_country_codes.map((item) => [String(item.code), item.count]));
      const labels = data.country_labels_by_code || {};
      const names = countryRows.reduce((map, row) => {
        map.set(formatCountryCode(row["country-code"]), row.name);
        return map;
      }, new Map());
      const maxCount = Math.max(1, ...data.films_per_country_codes.map((item) => item.count));

      const width = container.clientWidth || 960;
      const height = Math.min(520, Math.max(320, Math.round(width * 0.55)));
      const projection = d3.geoNaturalEarth1().fitSize([width, height], topojson.feature(world, world.objects.countries));
      const path = d3.geoPath(projection);
      const color = d3.scaleLinear().domain([0, maxCount]).range([PANEL_COLOR, ACCENT_COLOR]);

      const svg = d3.create("svg")
        .attr("viewBox", `0 0 ${width} ${height}`)
        .attr("role", "img")
        .attr("aria-label", "World map shaded by films watched");
      let activeCountryPath = null;

      function updateReadout(name, count) {
        readout.innerHTML = `<strong>${name}</strong><span>${count} film${count === 1 ? "" : "s"}</span>`;
      }

      function resetMapHover() {
        if (activeCountryPath) {
          activeCountryPath.attr("stroke", "rgba(244, 239, 230, 0.18)").attr("stroke-width", 0.7);
          activeCountryPath = null;
        }
        readout.innerHTML = `<strong>Hover a country</strong><span>Film count will appear here.</span>`;
        tooltip.hidden = true;
      }

      svg.append("g")
        .selectAll("path")
        .data(topojson.feature(world, world.objects.countries).features)
        .join("path")
        .attr("d", path)
        .attr("fill", (feature) => color(counts.get(String(feature.id)) || 0))
        .attr("stroke", "rgba(244, 239, 230, 0.18)")
        .attr("stroke-width", 0.7)
        .style("cursor", "pointer")
        .on("pointerenter", function(event, feature) {
          const count = counts.get(String(feature.id)) || 0;
          const featureCode = formatCountryCode(feature.id);
          const name = names.get(featureCode) || labels[String(feature.id)] || `Country ${feature.id}`;
          if (activeCountryPath) {
            activeCountryPath.attr("stroke", "rgba(244, 239, 230, 0.18)").attr("stroke-width", 0.7);
          }
          activeCountryPath = d3.select(this);
          activeCountryPath.attr("stroke", ACCENT_COLOR).attr("stroke-width", 1.4);
          updateReadout(name, count);
          tooltip.hidden = false;
          tooltip.innerHTML = `<strong>${name}</strong><span>${count} film${count === 1 ? "" : "s"}</span>`;
          tooltip.style.left = `${event.pageX + 12}px`;
          tooltip.style.top = `${event.pageY + 12}px`;
        })
        .on("pointermove", function(event) {
          tooltip.style.left = `${event.pageX + 12}px`;
          tooltip.style.top = `${event.pageY + 12}px`;
        })
        .on("pointerleave", function() {
          resetMapHover();
        });

      container.innerHTML = "";
      container.appendChild(svg.node());
      svg.on("pointerleave", resetMapHover);
      container.addEventListener("mouseleave", resetMapHover);
    }

    async function bootStats() {
      const response = await fetch("/stats/data");
      const data = await response.json();
      renderLists(data);
      renderHeatmap(data.films_per_day_365);
      await renderMap(data);
      window.addEventListener("resize", () => renderHeatmap(data.films_per_day_365));
    }

    bootStats();
  </script>
{% endblock %}