Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(calendar-heatmap): add calendar heatmap component
Timothy Yin2f56f3558a23
diff --git a/app/assets/css/heatmap.css b/app/assets/css/heatmap.cssnew file mode 100644index 00000000..d5c03425--- /dev/null+++ b/app/assets/css/heatmap.css@@ -0,0 +1,164 @@+.tippy-box[data-animation='fade'][data-state='hidden'] {+ opacity: 0;+}+[data-tippy-root] {+ max-width: calc(100vw - 10px);+}+.tippy-box {+ position: relative;+ background-color: #333;+ color: #fff;+ border-radius: 4px;+ font-size: 14px;+ line-height: 1.4;+ white-space: normal;+ outline: 0;+ transition-property: transform, visibility, opacity;+}+.tippy-box[data-placement^='top'] > .tippy-arrow {+ bottom: 0;+}+.tippy-box[data-placement^='top'] > .tippy-arrow:before {+ bottom: -7px;+ left: 0;+ border-width: 8px 8px 0;+ border-top-color: initial;+ transform-origin: center top;+}+.tippy-box[data-placement^='bottom'] > .tippy-arrow {+ top: 0;+}+.tippy-box[data-placement^='bottom'] > .tippy-arrow:before {+ top: -7px;+ left: 0;+ border-width: 0 8px 8px;+ border-bottom-color: initial;+ transform-origin: center bottom;+}+.tippy-box[data-placement^='left'] > .tippy-arrow {+ right: 0;+}+.tippy-box[data-placement^='left'] > .tippy-arrow:before {+ border-width: 8px 0 8px 8px;+ border-left-color: initial;+ right: -7px;+ transform-origin: center left;+}+.tippy-box[data-placement^='right'] > .tippy-arrow {+ left: 0;+}+.tippy-box[data-placement^='right'] > .tippy-arrow:before {+ left: -7px;+ border-width: 8px 8px 8px 0;+ border-right-color: initial;+ transform-origin: center right;+}+.tippy-box[data-inertia][data-state='visible'] {+ transition-timing-function: cubic-bezier(0.54, 1.5, 0.38, 1.11);+}+.tippy-arrow {+ width: 16px;+ height: 16px;+ color: #333;+}+.tippy-arrow:before {+ content: '';+ position: absolute;+ border-color: transparent;+ border-style: solid;+}+.tippy-content {+ position: relative;+ padding: 5px 9px;+ z-index: 1;+}+.tippy-box[data-placement^='top'] > .tippy-svg-arrow {+ bottom: 0;+}+.tippy-box[data-placement^='top'] > .tippy-svg-arrow:after,+.tippy-box[data-placement^='top'] > .tippy-svg-arrow > svg {+ top: 16px;+ transform: rotate(180deg);+}+.tippy-box[data-placement^='bottom'] > .tippy-svg-arrow {+ top: 0;+}+.tippy-box[data-placement^='bottom'] > .tippy-svg-arrow > svg {+ bottom: 16px;+}+.tippy-box[data-placement^='left'] > .tippy-svg-arrow {+ right: 0;+}+.tippy-box[data-placement^='left'] > .tippy-svg-arrow:after,+.tippy-box[data-placement^='left'] > .tippy-svg-arrow > svg {+ transform: rotate(90deg);+ top: calc(50% - 3px);+ left: 11px;+}+.tippy-box[data-placement^='right'] > .tippy-svg-arrow {+ left: 0;+}+.tippy-box[data-placement^='right'] > .tippy-svg-arrow:after,+.tippy-box[data-placement^='right'] > .tippy-svg-arrow > svg {+ transform: rotate(-90deg);+ top: calc(50% - 3px);+ right: 11px;+}+.tippy-svg-arrow {+ width: 16px;+ height: 16px;+ fill: #333;+ text-align: initial;+}+.tippy-svg-arrow,+.tippy-svg-arrow > svg {+ position: absolute;+}+.vch__container .vch__legend {+ display: flex;+ justify-content: space-between;+ align-items: center;+}+.vch__container .vch__external-legend-wrapper {+ margin: 0 8px;+}+svg.vch__wrapper {+ font-family:+ -apple-system,+ BlinkMacSystemFont,+ Segoe UI,+ Roboto,+ Oxygen,+ Ubuntu,+ Cantarell,+ Open Sans,+ Helvetica Neue,+ sans-serif;+ line-height: 10px;+ width: 100%;+}+svg.vch__wrapper .vch__months__labels__wrapper text.vch__month__label {+ font-size: 10px;+}+svg.vch__wrapper .vch__days__labels__wrapper text.vch__day__label,+svg.vch__wrapper .vch__legend__wrapper text {+ font-size: 9px;+}+svg.vch__wrapper text.vch__month__label,+svg.vch__wrapper text.vch__day__label,+svg.vch__wrapper .vch__legend__wrapper text {+ fill: #767676;+}+svg.vch__wrapper rect.vch__day__square:hover {+ stroke: #555;+ stroke-width: 2px;+ paint-order: stroke;+}+svg.vch__wrapper rect.vch__day__square:focus {+ outline: none;+}+svg.vch__wrapper.dark-mode text.vch__month__label,+svg.vch__wrapper.dark-mode text.vch__day__label,+svg.vch__wrapper.dark-mode .vch__legend__wrapper text {+ fill: #fff;+}diff --git a/app/components/ui/CalendarHeatmap/CalendarHeatmap.vue b/app/components/ui/CalendarHeatmap/CalendarHeatmap.vuenew file mode 100644index 00000000..b892d281--- /dev/null+++ b/app/components/ui/CalendarHeatmap/CalendarHeatmap.vue@@ -0,0 +1,538 @@+<script setup lang="ts">+import type { CreateSingletonInstance, Instance } from 'tippy.js'+import tippy, { createSingleton } from 'tippy.js'+import 'tippy.js/dist/tippy.css'+import 'tippy.js/dist/svg-arrow.css'+import {+ Heatmap,+ COLOR_THEMES,+ type CalendarItem,+ type Locale,+ type Month,+ type TooltipFormatter,+ type Value,+} from './Heatmap'++interface Props {+ endDate: Date | string+ values: Value[]+ max?: number+ rangeColor?: string[]+ locale?: Partial<Locale>+ tooltip?: boolean+ tooltipUnit?: string+ tooltipFormatter?: TooltipFormatter+ vertical?: boolean+ tooltipNoDataFormatter?: (date: Date) => string+ round?: number+ darkMode?: boolean+ startDate?: Date | string+ theme?: keyof typeof COLOR_THEMES+}++const props = withDefaults(defineProps<Props>(), {+ max: undefined,+ rangeColor: undefined,+ locale: undefined,+ tooltip: true,+ tooltipUnit: 'contributions',+ tooltipFormatter: undefined,+ vertical: false,+ tooltipNoDataFormatter: undefined,+ round: 0,+ darkMode: false,+ startDate: undefined,+ theme: 'blue',+})++// Emits 定义+interface Emits {+ dayClick: [day: CalendarItem]+}++const emit = defineEmits<Emits>()++const DEFAULT_LOCALE: Locale = {+ months: [+ 'Jan',+ 'Feb',+ 'Mar',+ 'Apr',+ 'May',+ 'Jun',+ 'Jul',+ 'Aug',+ 'Sep',+ 'Oct',+ 'Nov',+ 'Dec',+ ],+ days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],+ on: 'on',+ less: 'Less',+ more: 'More',+}+const BASE_SQUARE_SIZE = 10+const DAYS_IN_WEEK = 7++// 常量定义+const SQUARE_BORDER_SIZE = BASE_SQUARE_SIZE / 5+const SQUARE_SIZE = BASE_SQUARE_SIZE + SQUARE_BORDER_SIZE+const LEFT_SECTION_WIDTH = Math.ceil(BASE_SQUARE_SIZE * 2.5)+const RIGHT_SECTION_WIDTH = SQUARE_SIZE * 3+const TOP_SECTION_HEIGHT = BASE_SQUARE_SIZE + BASE_SQUARE_SIZE / 2+const BOTTOM_SECTION_HEIGHT = BASE_SQUARE_SIZE + BASE_SQUARE_SIZE / 2+const yearWrapperTransform = `translate(${LEFT_SECTION_WIDTH}, ${TOP_SECTION_HEIGHT})`++const svg = ref<SVGElement | null>(null)+const now = ref(new Date())+const heatmap = ref(+ new Heatmap(+ props.endDate as Date,+ props.values,+ props.max,+ props.startDate as Date,+ ),+)+const width = ref(0)+const height = ref(0)+const viewbox = ref('0 0 0 0')+const legendViewbox = ref('0 0 0 0')+const daysLabelWrapperTransform = ref('')+const monthsLabelWrapperTransform = ref('')+const legendWrapperTransform = ref('')+const lo = ref<Locale>(DEFAULT_LOCALE)++const rangeColor = ref<string[]>(+ props.rangeColor || [+ ...(props.darkMode+ ? COLOR_THEMES[props.theme].dark+ : COLOR_THEMES[props.theme].light),+ ],+)++const tippyInstances = new Map<HTMLElement, Instance>()+let tippySingleton: CreateSingletonInstance++function initTippy() {+ tippyInstances.clear()+ if (tippySingleton) {+ tippySingleton.setInstances(Array.from(tippyInstances.values()))+ } else {+ tippySingleton = createSingleton(Array.from(tippyInstances.values()), {+ overrides: [],+ moveTransition: 'transform 0.1s ease-out',+ allowHTML: true,+ })+ }+}++function tooltipOptions(day: CalendarItem): string | undefined {+ if (props.tooltip) {+ if (day.count !== undefined) {+ if (props.tooltipFormatter) {+ return props.tooltipFormatter(day, props.tooltipUnit)+ }+ return `<b>${day.count} ${props.tooltipUnit}</b> ${lo.value.on} ${lo.value.months[day.date.getMonth()]} ${day.date.getDate()}, ${day.date.getFullYear()}`+ } else if (props.tooltipNoDataFormatter) {+ return props.tooltipNoDataFormatter(day.date)+ } else {+ return `<b>No ${props.tooltipUnit}</b> ${lo.value.on} ${lo.value.months[day.date.getMonth()]} ${day.date.getDate()}, ${day.date.getFullYear()}`+ }+ }+ return undefined+}++function getWeekPosition(index: number): string {+ if (props.vertical) {+ return `translate(0, ${SQUARE_SIZE * heatmap.value.weekCount - (index + 1) * SQUARE_SIZE})`+ }+ return `translate(${index * SQUARE_SIZE}, 0)`+}++function getDayPosition(index: number): string {+ if (props.vertical) {+ return `translate(${index * SQUARE_SIZE}, 0)`+ }+ return `translate(0, ${index * SQUARE_SIZE})`+}++function getMonthLabelPosition(month: Month): { x: number; y: number } {+ // Find the exact position of the 1st day in the calendar+ const calendar = heatmap.value.calendar+ let exactPosition = month.index * SQUARE_SIZE++ // Look for the 1st day of this month in the calendar+ const week = calendar[month.index]+ if (week && week.length > 0) {+ for (let dayIndex = 0; dayIndex < week.length; dayIndex++) {+ const day = week[dayIndex]+ if (+ day &&+ day.date.getTime() > 0 &&+ day.date.getDate() === 1 &&+ day.date.getMonth() === month.value+ ) {+ if (props.vertical) {+ exactPosition =+ SQUARE_SIZE * heatmap.value.weekCount -+ SQUARE_SIZE * month.index -+ SQUARE_SIZE / 4+ } else {+ exactPosition = month.index * SQUARE_SIZE+ }+ break+ }+ }+ }++ if (props.vertical) {+ return {+ x: 3,+ y: exactPosition,+ }+ }+ return {+ x: exactPosition,+ y: SQUARE_SIZE - SQUARE_BORDER_SIZE,+ }+}++function initTippyLazy(e: MouseEvent): void {+ if (+ tippySingleton &&+ e.target &&+ (e.target as HTMLElement).classList.contains('vch__day__square') &&+ (e.target as HTMLElement).dataset.weekIndex !== undefined &&+ (e.target as HTMLElement).dataset.dayIndex !== undefined+ ) {+ const weekIndex = Number((e.target as HTMLElement).dataset.weekIndex)+ const dayIndex = Number((e.target as HTMLElement).dataset.dayIndex)++ if (!isNaN(weekIndex) && !isNaN(dayIndex)) {+ const dayData = heatmap.value.calendar[weekIndex]?.[dayIndex]+ if (dayData) {+ const tooltip = tooltipOptions(dayData)+ if (tooltip) {+ const instance = tippyInstances.get(e.target as HTMLElement)++ if (instance) {+ instance.setContent(tooltip)+ } else {+ tippyInstances.set(+ e.target as HTMLElement,+ tippy(e.target as HTMLElement, { content: tooltip }),+ )+ tippySingleton.setInstances(Array.from(tippyInstances.values()))+ }+ }+ }+ }+ }+}++watch(+ [() => props.rangeColor, () => props.darkMode, () => props.theme],+ ([rc, dm, theme]) => {+ rangeColor.value = rc || [+ ...(dm ? COLOR_THEMES[theme].dark : COLOR_THEMES[theme].light),+ ]+ },+)++watch(+ () => props.vertical,+ (v) => {+ if (v) {+ width.value =+ LEFT_SECTION_WIDTH + SQUARE_SIZE * DAYS_IN_WEEK + RIGHT_SECTION_WIDTH+ height.value =+ TOP_SECTION_HEIGHT ++ SQUARE_SIZE * heatmap.value.weekCount ++ SQUARE_BORDER_SIZE+ daysLabelWrapperTransform.value = `translate(${LEFT_SECTION_WIDTH}, 0)`+ monthsLabelWrapperTransform.value = `translate(0, ${TOP_SECTION_HEIGHT})`+ } else {+ width.value =+ LEFT_SECTION_WIDTH ++ SQUARE_SIZE * heatmap.value.weekCount ++ SQUARE_BORDER_SIZE+ height.value = TOP_SECTION_HEIGHT + SQUARE_SIZE * DAYS_IN_WEEK+ daysLabelWrapperTransform.value = `translate(0, ${TOP_SECTION_HEIGHT})`+ monthsLabelWrapperTransform.value = `translate(${LEFT_SECTION_WIDTH}, 0)`+ }+ },+ { immediate: true },+)++watch([width, height], ([w, h]) => (viewbox.value = `0 0 ${w} ${h}`), {+ immediate: true,+})++watch(+ [width, height, rangeColor],+ ([w, h, rc]) => {+ legendWrapperTransform.value = props.vertical+ ? `translate(${LEFT_SECTION_WIDTH + SQUARE_SIZE * DAYS_IN_WEEK}, ${TOP_SECTION_HEIGHT})`+ : `translate(${w - SQUARE_SIZE * rc.length - 30}, ${h - BOTTOM_SECTION_HEIGHT})`+ },+ { immediate: true },+)++watch(+ () => props.locale,+ (l) => {+ lo.value = l ? { ...DEFAULT_LOCALE, ...l } : DEFAULT_LOCALE+ },+ { immediate: true },+)++watch(+ rangeColor,+ (rc) => {+ legendViewbox.value = `0 0 ${BASE_SQUARE_SIZE * (rc.length + 1)} ${BASE_SQUARE_SIZE}`+ },+ { immediate: true },+)++watch(+ [+ () => props.values,+ () => props.tooltipUnit,+ () => props.tooltipFormatter,+ () => props.tooltipNoDataFormatter,+ () => props.max,+ () => props.startDate,+ () => props.endDate,+ rangeColor,+ ],+ () => {+ heatmap.value = new Heatmap(+ props.endDate as Date,+ props.values,+ props.max,+ props.startDate as Date,+ )+ tippyInstances.forEach((item) => item.destroy())+ nextTick(initTippy)+ },+)++onMounted(initTippy)+onBeforeUnmount(() => {+ tippySingleton?.destroy()+ tippyInstances.forEach((item) => item.destroy())+})++const curRangeColor = rangeColor++function handleDayClick(day: CalendarItem): void {+ emit('dayClick', day)+}+</script>++<template>+ <div :class="{ vch__container: true, 'dark-mode': darkMode }">+ <svg+ ref="svg"+ class="vch__wrapper"+ :viewBox="viewbox"+ >+ <g+ class="vch__months__labels__wrapper"+ :transform="monthsLabelWrapperTransform"+ >+ <text+ v-for="(month, index) in heatmap.firstFullWeekOfMonths"+ :key="index"+ class="vch__month__label"+ :x="getMonthLabelPosition(month).x"+ :y="getMonthLabelPosition(month).y"+ >+ {{ lo.months[month.value] }}+ </text>+ </g>++ <g+ class="vch__days__labels__wrapper"+ :transform="daysLabelWrapperTransform"+ >+ <text+ class="vch__day__label"+ :x="vertical ? SQUARE_SIZE : 0"+ :y="vertical ? SQUARE_SIZE - SQUARE_BORDER_SIZE : 20"+ >+ {{ lo.days[1] }}+ </text>+ <text+ class="vch__day__label"+ :x="vertical ? SQUARE_SIZE * 3 : 0"+ :y="vertical ? SQUARE_SIZE - SQUARE_BORDER_SIZE : 44"+ >+ {{ lo.days[3] }}+ </text>+ <text+ class="vch__day__label"+ :x="vertical ? SQUARE_SIZE * 5 : 0"+ :y="vertical ? SQUARE_SIZE - SQUARE_BORDER_SIZE : 69"+ >+ {{ lo.days[5] }}+ </text>+ </g>++ <g+ v-if="vertical"+ class="vch__legend__wrapper"+ :transform="legendWrapperTransform"+ >+ <text+ :x="SQUARE_SIZE * 1.25"+ y="8"+ >+ {{ lo.less }}+ </text>+ <rect+ v-for="(color, index) in curRangeColor"+ :key="index"+ :rx="round"+ :ry="round"+ :style="{ fill: color }"+ :width="SQUARE_SIZE - SQUARE_BORDER_SIZE"+ :height="SQUARE_SIZE - SQUARE_BORDER_SIZE"+ :x="SQUARE_SIZE * 1.75"+ :y="SQUARE_SIZE * (index + 1)"+ />+ <text+ :x="SQUARE_SIZE * 1.25"+ :y="SQUARE_SIZE * (curRangeColor.length + 2) - SQUARE_BORDER_SIZE"+ >+ {{ lo.more }}+ </text>+ </g>++ <g+ class="vch__year__wrapper"+ :transform="yearWrapperTransform"+ @mouseover="initTippyLazy"+ >+ <g+ v-for="(week, weekIndex) in heatmap.calendar"+ :key="weekIndex"+ class="vch__month__wrapper"+ :transform="getWeekPosition(weekIndex)"+ >+ <template+ v-for="(day, dayIndex) in week"+ :key="dayIndex"+ >+ <rect+ v-if="+ day.date.getTime() > 0 &&+ (day.date <= now || heatmap.isExactYearRange())+ "+ class="vch__day__square"+ :rx="round"+ :ry="round"+ :transform="getDayPosition(dayIndex)"+ :width="SQUARE_SIZE - SQUARE_BORDER_SIZE"+ :height="SQUARE_SIZE - SQUARE_BORDER_SIZE"+ :style="{ fill: curRangeColor[day.colorIndex] }"+ :data-week-index="weekIndex"+ :data-day-index="dayIndex"+ @click="handleDayClick(day)"+ />+ </template>+ </g>+ </g>+ </svg>+ <div class="vch__legend">+ <slot name="legend">+ <div class="vch__legend-left">+ <slot name="vch__legend-left" />+ </div>+ <div class="vch__legend-right">+ <slot name="legend-right">+ <div class="vch__legend">+ <div>{{ lo.less }}</div>+ <svg+ v-if="!vertical"+ class="vch__external-legend-wrapper"+ :viewBox="legendViewbox"+ :height="SQUARE_SIZE - SQUARE_BORDER_SIZE"+ >+ <g class="vch__legend__wrapper">+ <rect+ v-for="(color, index) in curRangeColor"+ :key="index"+ :rx="round"+ :ry="round"+ :style="{ fill: color }"+ :width="SQUARE_SIZE - SQUARE_BORDER_SIZE"+ :height="SQUARE_SIZE - SQUARE_BORDER_SIZE"+ :x="SQUARE_SIZE * index"+ />+ </g>+ </svg>+ <div>{{ lo.more }}</div>+ </div>+ </slot>+ </div>+ </slot>+ </div>+ </div>+</template>++<style lang="scss">+.vch__container {+ .vch__legend {+ display: flex;+ justify-content: space-between;+ align-items: center;+ }++ .vch__external-legend-wrapper {+ margin: 0 8px;+ }+}++svg.vch__wrapper {+ font-family:+ -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,+ Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;+ line-height: 10px;+ width: 100%;++ .vch__months__labels__wrapper text.vch__month__label {+ font-size: 10px;+ }++ .vch__days__labels__wrapper text.vch__day__label,+ .vch__legend__wrapper text {+ font-size: 9px;+ }++ text.vch__month__label,+ text.vch__day__label,+ .vch__legend__wrapper text {+ fill: #767676;+ }++ rect.vch__day__square:hover {+ stroke: #555;+ stroke-width: 2px;+ paint-order: stroke;+ }++ rect.vch__day__square:focus {+ outline: none;+ }++ &.dark-mode {+ text.vch__month__label,+ text.vch__day__label,+ .vch__legend__wrapper text {+ fill: #fff;+ }+ }+}+</style>diff --git a/app/components/ui/CalendarHeatmap/Heatmap.ts b/app/components/ui/CalendarHeatmap/Heatmap.tsnew file mode 100644index 00000000..0192ad54--- /dev/null+++ b/app/components/ui/CalendarHeatmap/Heatmap.ts@@ -0,0 +1,318 @@+export interface Value {+ date: Date | string+ count: number+}++export interface Activity {+ count: number+ colorIndex: number+}++export type Activities = Map<string, Activity>++export interface CalendarItem {+ date: Date+ count?: number+ colorIndex: number+}++export type Calendar = CalendarItem[][]++export interface Month {+ value: number+ index: number+}++export interface Locale {+ months: string[]+ days: string[]+ on: string+ less: string+ more: string+}++export type TooltipFormatter = (item: CalendarItem, unit: string) => string++// 颜色主题配置+export const COLOR_THEMES = {+ // 默认蓝色主题+ blue: {+ light: ['#ebedf0', '#dae2ef', '#c0ddf9', '#73b3f3', '#3886e1', '#17459e'],+ dark: ['#1f1f22', '#1e334a', '#1d466c', '#1d5689', '#1d69ac', '#1B95D1'],+ },+ // 绿色主题+ green: {+ light: ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127', '#0d2818'],+ dark: ['#1f1f22', '#0e4429', '#006d32', '#26a641', '#39d353', '#57e86a'],+ },+ // 红色主题+ red: {+ light: ['#ebedf0', '#f9d3d3', '#f2a7a7', '#ec6b6b', '#d63a3a', '#800f0f'],+ dark: ['#1f1f22', '#4a1e1e', '#6c1d1d', '#892121', '#ac2626', '#d13b3b'],+ },+ // 紫色主题+ purple: {+ light: ['#ebedf0', '#e2d6f9', '#c9a9f2', '#a26be5', '#6a35c9', '#2f0b73'],+ dark: ['#1f1f22', '#2c1e4a', '#412d6c', '#583d92', '#764eb8', '#9b6edb'],+ },+ // 橙色主题+ orange: {+ light: ['#ebedf0', '#ffe0c2', '#ffbb80', '#ff944d', '#e66a00', '#803900'],+ dark: ['#1f1f22', '#4a2e1e', '#6c3f1d', '#8c4f1d', '#b05d14', '#e67826'],+ },+ // 青色主题+ teal: {+ light: ['#ebedf0', '#c2f0ed', '#80dfd9', '#4ac6c0', '#229a96', '#0d4c4a'],+ dark: ['#1f1f22', '#1e3a3a', '#1d5656', '#1d6f6c', '#1d8f8c', '#26b3af'],+ },+ // 金色主题+ gold: {+ light: ['#ebedf0', '#fff6c2', '#ffe680', '#ffda4d', '#e6b800', '#7f6a00'],+ dark: ['#1f1f22', '#4a421e', '#6c5e1d', '#8c781d', '#b08f14', '#e6b825'],+ },+} as const++export class Heatmap {+ static readonly DAYS_IN_ONE_YEAR = 365+ static readonly DAYS_IN_WEEK = 7++ startDate: Date+ endDate: Date+ max: number+ private _values: Value[]+ private _firstFullWeekOfMonths?: Month[]+ private _activities?: Activities+ private _calendar?: Calendar++ constructor(+ endDate: Date | string,+ values: Value[],+ max?: number,+ startDate?: Date | string,+ ) {+ this.endDate = this.parseDate(endDate)+ if (startDate) {+ this.startDate = this.parseDate(startDate)+ } else {+ this.startDate = this.shiftDate(this.endDate, -Heatmap.DAYS_IN_ONE_YEAR)+ }+ this._values = values || []+ this.max = max || Math.max(...this._values.map((v) => v.count))+ this._activities = undefined+ this._calendar = undefined+ this._firstFullWeekOfMonths = undefined+ }++ set values(v: Value[]) {+ this._values = v+ this.max = Math.max(...v.map((item) => item.count))+ this._activities = undefined+ this._calendar = undefined+ this._firstFullWeekOfMonths = undefined+ }++ get values(): Value[] {+ return this._values+ }++ get activities(): Activities {+ if (!this._activities) {+ this._activities = new Map()+ for (const value of this._values) {+ const date = this.parseDate(value.date)+ const key = this.keyDayParser(date)+ this._activities.set(key, {+ count: value.count,+ colorIndex: this.getColorIndex(value.count),+ })+ }+ }+ return this._activities+ }++ get weekCount(): number {+ return Math.ceil(this.getDaysCount() / Heatmap.DAYS_IN_WEEK)+ }++ get calendar(): Calendar {+ if (!this._calendar) {+ const calendar: Calendar = []+ let week: CalendarItem[] = []++ // Check if this is a specific year (exactly 365/366 days from Jan 1 to Dec 31)+ const isSpecificYear = this.isExactYearRange()++ if (isSpecificYear) {+ // For specific year, start with empty slots only for days before the first day of the year+ const emptyDaysAtStart = this.getCountEmptyDaysAtStart()++ // Add empty days at the start of the first week+ for (let i = 0; i < emptyDaysAtStart; i++) {+ week.push({+ date: new Date(0), // Use epoch as placeholder for empty days+ colorIndex: 0,+ count: undefined,+ })+ }+ } else {+ // For non-specific year ranges (like "recent year"), add padding to align to week start+ const emptyDaysAtStart = this.getCountEmptyDaysAtStart()++ // Add empty days at the start of the first week+ for (let i = 0; i < emptyDaysAtStart; i++) {+ week.push({+ date: new Date(0), // Use epoch as placeholder for empty days+ colorIndex: 0,+ count: undefined,+ })+ }+ }++ // Fill actual days+ const currentDate = new Date(this.startDate)+ while (currentDate <= this.endDate) {+ const key = this.keyDayParser(currentDate)+ const activity = this.activities.get(key)++ week.push({+ date: new Date(currentDate),+ count: activity?.count,+ colorIndex: activity?.colorIndex || 0,+ })++ if (week.length === Heatmap.DAYS_IN_WEEK) {+ calendar.push(week)+ week = []+ }++ currentDate.setDate(currentDate.getDate() + 1)+ }++ if (isSpecificYear) {+ // For specific year, add empty slots only for days after the last day of the year+ const emptyDaysAtEnd = this.getCountEmptyDaysAtEnd()+ for (let i = 0; i < emptyDaysAtEnd; i++) {+ week.push({+ date: new Date(0), // Use epoch as placeholder for empty days+ colorIndex: 0,+ count: undefined,+ })+ }+ } else {+ // For other ranges (like "recent year"), use the original logic+ const emptyDaysAtEnd = this.getCountEmptyDaysAtEnd()+ const nextDate = new Date(currentDate)+ for (let i = 0; i < emptyDaysAtEnd; i++) {+ week.push({+ date: new Date(nextDate),+ colorIndex: 0,+ })+ nextDate.setDate(nextDate.getDate() + 1)+ }+ }++ if (week.length > 0) {+ calendar.push(week)+ }++ this._calendar = calendar+ }+ return this._calendar+ }++ get firstFullWeekOfMonths(): Month[] {+ if (!this._firstFullWeekOfMonths) {+ const months: Month[] = []+ const calendar = this.calendar++ for (let weekIndex = 0; weekIndex < calendar.length; weekIndex++) {+ const week = calendar[weekIndex]+ if (week && week.length > 0) {+ // Check each day in the week to find the 1st day of any month+ for (const day of week) {+ if (day.date.getTime() > 0 && day.date.getDate() === 1) {+ const month = day.date.getMonth()++ // Check if this month is not already in our list+ const existingMonth = months.find((m) => m.value === month)+ if (!existingMonth) {+ months.push({+ value: month,+ index: weekIndex,+ })+ }+ }+ }+ }+ }++ // Sort by month value to ensure proper order+ months.sort((a, b) => a.value - b.value)+ this._firstFullWeekOfMonths = months+ }+ return this._firstFullWeekOfMonths+ }++ getColorIndex(count?: number): number {+ if (!count || count === 0) return 0+ if (count >= this.max) return 4++ const step = this.max / 4+ if (count <= step) return 1+ if (count <= step * 2) return 2+ if (count <= step * 3) return 3+ return 4+ }++ getCountEmptyDaysAtStart(): number {+ return this.startDate.getDay()+ }++ getCountEmptyDaysAtEnd(): number {+ const remainingDays = this.getDaysCount() % Heatmap.DAYS_IN_WEEK+ return remainingDays === 0 ? 0 : Heatmap.DAYS_IN_WEEK - remainingDays+ }++ getDaysCount(): number {+ return (+ Math.ceil(+ (this.endDate.getTime() - this.startDate.getTime()) /+ (1000 * 60 * 60 * 24),+ ) + 1+ )+ }++ isExactYearRange(): boolean {+ // Check if this represents an exact year (Jan 1 to Dec 31)+ const startYear = this.startDate.getFullYear()+ const endYear = this.endDate.getFullYear()++ return (+ startYear === endYear &&+ this.startDate.getMonth() === 0 && // January+ this.startDate.getDate() === 1 && // 1st day+ this.endDate.getMonth() === 11 && // December+ this.endDate.getDate() === 31 // 31st day+ )+ }++ private shiftDate(date: Date, numDays: number): Date {+ const newDate = new Date(date)+ newDate.setDate(newDate.getDate() + numDays)+ return newDate+ }++ private parseDate(date: Date | string): Date {+ if (typeof date === 'string') {+ return new Date(date)+ }+ return new Date(date)+ }++ private keyDayParser(date: Date): string {+ const year = date.getFullYear()+ const month = String(date.getMonth() + 1).padStart(2, '0')+ const day = String(date.getDate()).padStart(2, '0')+ return `${year}-${month}-${day}`+ }+}