feat: calendar core #10
Openbart-krakowski(GitHub profile, opens in a new tab)wants to merge 176 commits into
v0 fromrefs/pull/10/headopened bart-krakowski(GitHub profile, opens in a new tab) changed the title
- packages/time/src/calendar/generateDateRange.ts line 4OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,4 @@1+import { Temporal } from '@js-temporal/polyfill'2+3+export const generateDateRange = (4+ start: Temporal.PlainDate,packages/time/src/calendar/getEventProps.ts line 13OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,13 @@1+import { Temporal } from "@js-temporal/polyfill";2+import type { Properties as CSSProperties } from "csstype";3+import type { CalendarState, Event } from "./types";4+5+export const getEventProps = (6+ eventMap: Map<string, Event[]>,7+ id: Event['id'],8+ state: CalendarState9+): { style: CSSProperties } | null => {10+ const event = [...eventMap.values()].flat().find((currEvent) => currEvent.id === id);11+ if (!event) return null;12+13+ const eventStartDate = Temporal.PlainDateTime.from(event.startDate);packages/time/src/calendar/getEventProps.ts line 25OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+export const getEventProps = (6+ eventMap: Map<string, Event[]>,7+ id: Event['id'],8+ state: CalendarState9+): { style: CSSProperties } | null => {10+ const event = [...eventMap.values()].flat().find((currEvent) => currEvent.id === id);11+ if (!event) return null;12+13+ const eventStartDate = Temporal.PlainDateTime.from(event.startDate);14+ const eventEndDate = Temporal.PlainDateTime.from(event.endDate);15+ const isSplitEvent = Temporal.PlainDate.compare(eventStartDate.toPlainDate(), eventEndDate.toPlainDate()) !== 0;16+17+ let percentageOfDay;18+ let eventHeightInMinutes;19+20+ if (isSplitEvent) {21+ const isStartPart = eventStartDate.hour !== 0 || eventStartDate.minute !== 0;22+ if (isStartPart) {23+ const eventTimeInMinutes = eventStartDate.hour * 60 + eventStartDate.minute;24+ percentageOfDay = (eventTimeInMinutes / (24 * 60)) * 100;25+ eventHeightInMinutes = 24 * 60 - eventTimeInMinutes;packages/time/src/calendar/getEventProps.ts line 37OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +17,21 @@17+ let percentageOfDay;18+ let eventHeightInMinutes;19+20+ if (isSplitEvent) {21+ const isStartPart = eventStartDate.hour !== 0 || eventStartDate.minute !== 0;22+ if (isStartPart) {23+ const eventTimeInMinutes = eventStartDate.hour * 60 + eventStartDate.minute;24+ percentageOfDay = (eventTimeInMinutes / (24 * 60)) * 100;25+ eventHeightInMinutes = 24 * 60 - eventTimeInMinutes;26+ } else {27+ percentageOfDay = 0;28+ eventHeightInMinutes = eventEndDate.hour * 60 + eventEndDate.minute;29+ }30+ } else {31+ const eventTimeInMinutes = eventStartDate.hour * 60 + eventStartDate.minute;32+ percentageOfDay = (eventTimeInMinutes / (24 * 60)) * 100;33+ const endTimeInMinutes = eventEndDate.hour * 60 + eventEndDate.minute;34+ eventHeightInMinutes = endTimeInMinutes - eventTimeInMinutes;35+ }36+37+ const eventHeight = Math.min((eventHeightInMinutes / (24 * 60)) * 100, 20);packages/time/src/calendar/getEventProps.ts line 39Resolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +45,21 @@45+ Temporal.PlainDateTime.compare(eventStartDate, eEndDate) <= 0) ||46+ (Temporal.PlainDateTime.compare(eventEndDate, eStartDate) >= 0 &&47+ Temporal.PlainDateTime.compare(eventEndDate, eEndDate) <= 0) ||48+ (Temporal.PlainDateTime.compare(eStartDate, eventStartDate) >= 0 &&49+ Temporal.PlainDateTime.compare(eStartDate, eventEndDate) <= 0) ||50+ (Temporal.PlainDateTime.compare(eEndDate, eventStartDate) >= 0 &&51+ Temporal.PlainDateTime.compare(eEndDate, eventEndDate) <= 0)52+ );53+ });54+55+ const eventIndex = overlappingEvents.findIndex((e) => e.id === id);56+ const totalOverlaps = overlappingEvents.length;57+ const sidePadding = 2;58+ const innerPadding = 2;59+ const totalInnerPadding = (totalOverlaps - 1) * innerPadding;60+ const availableWidth = 100 - totalInnerPadding - 2 * sidePadding;61+ const eventWidth = totalOverlaps > 0 ? availableWidth / totalOverlaps : 100 - 2 * sidePadding;62+ const eventLeft = sidePadding + eventIndex * (eventWidth + innerPadding);63+64+ if (state.viewMode.unit === 'week' || state.viewMode.unit === 'day') {65+ return {@@ -0,0 +1,21 @@1+import { Temporal } from "@js-temporal/polyfill";2+import type { Day, Event } from "./types";3+4+interface GroupDaysByBaseProps<TEvent extends Event = Event> {5+ days: (Day<TEvent> | null)[];6+ weekStartsOn: number;7+}8+9+type GroupDaysByMonthProps<TEvent extends Event = Event> = GroupDaysByBaseProps<TEvent> & {10+ unit: 'month';11+ fillMissingDays?: never;12+};13+14+type GroupDaysByWeekProps<TEvent extends Event = Event> = GroupDaysByBaseProps<TEvent> & {15+ unit: 'week';16+ fillMissingDays?: boolean;17+};18+19+export type GroupDaysByProps<TEvent extends Event = Event> = GroupDaysByMonthProps<TEvent> | GroupDaysByWeekProps<TEvent>;20+21+export const groupDaysBy = <TEvent extends Event>({packages/time/src/calendar/splitMultiDayEvents.ts line 11OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,11 @@1+import { Temporal } from '@js-temporal/polyfill';2+import type { Event } from './types';3+4+export const splitMultiDayEvents = <TEvent extends Event>(event: TEvent, timeZone: Temporal.TimeZoneLike): TEvent[] => {5+ const startDate = event.startDate instanceof Temporal.PlainDateTime ? event.startDate.toZonedDateTime(timeZone) : event.startDate;6+ const endDate = event.endDate instanceof Temporal.PlainDateTime ? event.endDate.toZonedDateTime(timeZone) : event.endDate;7+ const events: TEvent[] = [];8+9+ let currentDay = startDate;10+ while (Temporal.ZonedDateTime.compare(currentDay, endDate) < 0) {11+ const startOfCurrentDay = currentDay.with({ hour: 0, minute: 0, second: 0, millisecond: 0 });packages/time/src/calendar/types.ts line 5OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,5 @@1+import type { Temporal } from "@js-temporal/polyfill"2+3+export interface Event {4+ id: string;5+ startDate: Temporal.PlainDateTime | Temporal.ZonedDateTime;packages/time/src/calendar/types.ts line 3OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,3 @@1+import type { Temporal } from "@js-temporal/polyfill"2+3+export interface Event {packages/time/src/core/calendar.ts line 25OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+import { splitMultiDayEvents } from '../calendar/splitMultiDayEvents'6+import { getEventProps } from '../calendar/getEventProps'7+import { groupDaysBy } from '../calendar/groupDaysBy'8+import { getDateDefaults } from '../utils/dateDefaults'9+import type { Properties as CSSProperties } from 'csstype'10+import type { GroupDaysByProps } from '../calendar/groupDaysBy'11+import type { CalendarStore, Day, Event } from '../calendar/types'12+13+import './weekInfoPolyfill'14+15+export type { CalendarStore, Event, Day } from '../calendar/types'16+17+/**18+ * Represents the configuration for the current viewing mode of a calendar,19+ * specifying the scale and unit of time.20+ */21+export interface ViewMode {22+ /** The number of units for the view mode. */23+ value: number24+ /** The unit of time that the calendar view should display (month, week, or day). */25+ unit: 'month' | 'week' | 'day'packages/time/src/core/calendar.ts line 33OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +13,21 @@13+import './weekInfoPolyfill'14+15+export type { CalendarStore, Event, Day } from '../calendar/types'16+17+/**18+ * Represents the configuration for the current viewing mode of a calendar,19+ * specifying the scale and unit of time.20+ */21+export interface ViewMode {22+ /** The number of units for the view mode. */23+ value: number24+ /** The unit of time that the calendar view should display (month, week, or day). */25+ unit: 'month' | 'week' | 'day'26+}27+28+/**29+ * Configuration options for initializing a CalendarCore instance, allowing customization30+ * of events, locale, time zone, and the calendar system.31+ * @template TEvent - Specifies the event type, extending a base Event type.32+ */33+export interface CalendarCoreOptions<TEvent extends Event = Event> {packages/time/src/core/calendar.ts line 81OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +61,21 @@61+ changeViewMode: (newViewMode: CalendarStore['viewMode']) => void62+ /** Retrieves styling properties for a specific event, identified by ID. */63+ getEventProps: (id: Event['id']) => { style: CSSProperties } | null64+ /** Provides properties for the marker indicating the current time. */65+ getCurrentTimeMarkerProps: () => {66+ style: CSSProperties67+ currentTime: string | undefined68+ }69+ /** Groups days by a specified unit. */70+ groupDaysBy: (71+ props: Omit<GroupDaysByProps<TEvent>, 'weekStartsOn'>,72+ ) => (Day<TEvent> | null)[][]73+}74+75+interface CalendarState<TEvent extends Event> {76+ /** The currently focused date period in the calendar. */77+ currentPeriod: CalendarStore['currentPeriod']78+ /** The current view mode of the calendar. */79+ viewMode: CalendarStore['viewMode']80+ /** The current date and time according to the calendar's time zone. */81+ currentTime: CalendarStore['currentTime']@@ -0,0 +118,21 @@118+ currentTime: Temporal.Now.plainDateTimeISO(this.options.timeZone),119+ })120+ }121+122+ private getFirstDayOfMonth() {123+ return getFirstDayOfMonth(124+ this.store.state.currentPeriod125+ .toString({ calendarName: 'auto' })126+ .substring(0, 7),127+ )128+ }129+130+ private getFirstDayOfWeek() {131+ return getFirstDayOfWeek(132+ this.store.state.currentPeriod.toString(),133+ this.options.locale,134+ )135+ }136+137+ private getCalendarDays() {138+ const start =@@ -0,0 +132,21 @@132+ this.store.state.currentPeriod.toString(),133+ this.options.locale,134+ )135+ }136+137+ private getCalendarDays() {138+ const start =139+ this.store.state.viewMode.unit === 'month'140+ ? this.getFirstDayOfMonth().subtract({141+ days:142+ (this.getFirstDayOfMonth().dayOfWeek -143+ (this.getFirstDayOfWeek().dayOfWeek + 1) +144+ 7) %145+ 7,146+ })147+ : this.store.state.currentPeriod148+149+ let end150+ switch (this.store.state.viewMode.unit) {151+ case 'month': {152+ const lastDayOfMonth = this.getFirstDayOfMonth()packages/time/src/core/calendar.ts line 183OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +163,21 @@163+ case 'week': {164+ end = this.getFirstDayOfWeek().add({165+ days: 7 * this.store.state.viewMode.value - 1,166+ })167+ break168+ }169+ case 'day': {170+ end = this.store.state.currentPeriod.add({171+ days: this.store.state.viewMode.value - 1,172+ })173+ break174+ }175+ }176+177+ const allDays = generateDateRange(start, end)178+ const startMonth = this.store.state.currentPeriod.month179+ const endMonth = this.store.state.currentPeriod.add({180+ months: this.store.state.viewMode.value - 1,181+ }).month182+183+ return allDays.filter(packages/time/src/core/calendar.ts line 205OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +185,21 @@185+ )186+ }187+188+ private getEventMap() {189+ const map = new Map<string, TEvent[]>()190+ this.options.events?.forEach((event) => {191+ const eventStartDate =192+ event.startDate instanceof Temporal.PlainDateTime193+ ? event.startDate.toZonedDateTime(this.options.timeZone)194+ : event.startDate195+ const eventEndDate =196+ event.endDate instanceof Temporal.PlainDateTime197+ ? event.endDate.toZonedDateTime(this.options.timeZone)198+ : event.endDate199+ if (Temporal.ZonedDateTime.compare(eventStartDate, eventEndDate) !== 0) {200+ const splitEvents = splitMultiDayEvents<TEvent>(201+ event,202+ this.options.timeZone,203+ )204+ splitEvents.forEach((splitEvent) => {205+ const splitKey = splitEvent.startDate.toString().split('T')[0]packages/time/src/core/calendar.ts line 212OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +192,21 @@192+ event.startDate instanceof Temporal.PlainDateTime193+ ? event.startDate.toZonedDateTime(this.options.timeZone)194+ : event.startDate195+ const eventEndDate =196+ event.endDate instanceof Temporal.PlainDateTime197+ ? event.endDate.toZonedDateTime(this.options.timeZone)198+ : event.endDate199+ if (Temporal.ZonedDateTime.compare(eventStartDate, eventEndDate) !== 0) {200+ const splitEvents = splitMultiDayEvents<TEvent>(201+ event,202+ this.options.timeZone,203+ )204+ splitEvents.forEach((splitEvent) => {205+ const splitKey = splitEvent.startDate.toString().split('T')[0]206+ if (splitKey) {207+ if (!map.has(splitKey)) map.set(splitKey, [])208+ map.get(splitKey)?.push(splitEvent)209+ }210+ })211+ } else {212+ const eventKey = event.startDate.toString().split('T')[0]packages/time/src/core/calendar.ts line 49Resolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +14,21 @@14+15+export type { CalendarStore, Event, Day } from '../calendar/types'16+17+/**18+ * Represents the configuration for the current viewing mode of a calendar,19+ * specifying the scale and unit of time.20+ */21+export interface ViewMode {22+ /** The number of units for the view mode. */23+ value: number24+ /** The unit of time that the calendar view should display (month, week, or day). */25+ unit: 'month' | 'week' | 'day'26+}27+28+/**29+ * Configuration options for initializing a CalendarCore instance, allowing customization30+ * of events, locale, time zone, and the calendar system.31+ * @template TEvent - Specifies the event type, extending a base Event type.32+ */33+export interface CalendarCoreOptions<TEvent extends Event = Event> {34+ /** An optional array of events to be handled by the calendar. */packages/time/src/core/calendar.ts line 300OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +280,21 @@280+ ...prev,281+ currentPeriod: firstDayOfPrevWeek,282+ }))283+ break284+ }285+286+ case 'day': {287+ const prevCustomStart = this.store.state.currentPeriod.subtract({288+ days: this.store.state.viewMode.value,289+ })290+ this.store.setState((prev) => ({291+ ...prev,292+ currentPeriod: prevCustomStart,293+ }))294+ break295+ }296+ }297+ }298+299+ goToNextPeriod() {300+ const firstDayOfMonth = this.getFirstDayOfMonth()packages/time/src/core/calendar.ts line 422Resolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +320,21 @@320+ ...prev,321+ currentPeriod: firstDayOfNextWeek,322+ }))323+ break324+ }325+326+ case 'day': {327+ const nextCustomStart = this.store.state.currentPeriod.add({328+ days: this.store.state.viewMode.value,329+ })330+ this.store.setState((prev) => ({331+ ...prev,332+ currentPeriod: nextCustomStart,333+ }))334+ break335+ }336+ }337+ }338+339+ goToCurrentPeriod() {340+ this.store.setState((prev) => ({packages/time/src/core/calendar.ts line 437Resolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +327,21 @@327+ const nextCustomStart = this.store.state.currentPeriod.add({328+ days: this.store.state.viewMode.value,329+ })330+ this.store.setState((prev) => ({331+ ...prev,332+ currentPeriod: nextCustomStart,333+ }))334+ break335+ }336+ }337+ }338+339+ goToCurrentPeriod() {340+ this.store.setState((prev) => ({341+ ...prev,342+ currentPeriod: Temporal.Now.plainDateISO(),343+ }))344+ }345+346+ goToSpecificPeriod(date: Temporal.PlainDate) {347+ this.store.setState((prev) => ({packages/time/src/core/calendar.ts line 372OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +352,21 @@352+353+ updateCurrentTime() {354+ this.store.setState((prev) => ({355+ ...prev,356+ currentTime: Temporal.Now.plainDateTimeISO(),357+ }))358+ }359+360+ getEventProps(id: Event['id']) {361+ return getEventProps(this.getEventMap(), id, this.store.state)362+ }363+364+ getCurrentTimeMarkerProps(): {365+ style: CSSProperties366+ currentTime: string | undefined367+ } {368+ const { hour, minute } = this.store.state.currentTime369+ const currentTimeInMinutes = hour * 60 + minute370+ const percentageOfDay = (currentTimeInMinutes / (24 * 60)) * 100371+372+ return {packages/time/src/core/weekInfoPolyfill.ts line 16OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,16 @@1+interface WeekInfo {2+ firstDay: number3+ weekend: number[]4+ minimalDays: number5+}6+7+// eslint-disable-next-line @typescript-eslint/no-namespace8+declare namespace Intl {9+ interface Locale {10+ getWeekInfo: () => WeekInfo11+ weekInfo?: WeekInfo12+ }13+}14+15+;(function () {16+ if (typeof (Intl as any).Locale.prototype.getWeekInfo !== 'function') {packages/time/src/utils/getFirstDayOfWeek.ts line 6OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+import { Temporal } from '@js-temporal/polyfill'2+3+export const getFirstDayOfWeek = (currWeek: string, locale: Intl.UnicodeBCP47LocaleIdentifier | Intl.Locale = 'en-US') => {4+ const date = Temporal.PlainDate.from(currWeek);5+ const loc = new Intl.Locale(locale);6+ const { firstDay } = loc.weekInfo || loc.getWeekInfo();
cutterbl(GitHub profile, opens in a new tab) requested changes
packages/time/src/core/weekInfoPolyfill/weekInfoPolyfill.ts line 16OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,16 @@1+interface WeekInfo {2+ firstDay: number3+ weekend: number[]4+ minimalDays: number5+}6+7+// eslint-disable-next-line @typescript-eslint/no-namespace8+declare namespace Intl {9+ interface Locale {10+ getWeekInfo: () => WeekInfo11+ weekInfo?: WeekInfo12+ }13+}14+15+;(function () {16+ // Chrome & Safaripackages/time/src/core/weekInfoPolyfill/weekInfoPolyfill.ts line 28OutdatedResolvedby cutterbl(GitHub profile, opens in a new tab)@@ -0,0 +8,21 @@8+declare namespace Intl {9+ interface Locale {10+ getWeekInfo: () => WeekInfo11+ weekInfo?: WeekInfo12+ }13+}14+15+;(function () {16+ // Chrome & Safari17+ if ('weekInfo' in Intl.Locale.prototype && typeof Intl.Locale.prototype.getWeekInfo !== 'function') {18+ Intl.Locale.prototype.getWeekInfo = function () {19+ return this.weekInfo20+ }21+ }22+ // Firefox23+ if (typeof Intl.Locale.prototype.getWeekInfo !== 'function') {24+ import('./weekInfoData').then(({ weekInfoData }) => {25+ Intl.Locale.prototype.getWeekInfo = function () {26+ const locale = this.toString().toLowerCase()27+28+ const match =packages/time/src/utils/endOf.ts line 6OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+import type { Temporal } from '@js-temporal/polyfill'2+3+/**4+ * Helper function to get the end of a given day.5+ * @param date - The date for which the end of the day is needed.6+ * @returns The end of the given day.packages/time/src/utils/startOf.ts line 6OutdatedResolvedby bart-krakowski(GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+import type { Temporal } from '@js-temporal/polyfill'2+3+/**4+ * Helper function to get the start of a given day.5+ * @param date - The date for which the start of the day is needed.6+ * @returns The start of the given day.- @@ -1,9 +1,18 @@11 import type { Temporal } from '@js-temporal/polyfill'223+type ViewUnit = 'month' | 'week' | 'day' | 'workWeek' | 'decade' | 'year'4+5+interface EndOfParams {6+ date: Temporal.ZonedDateTime7+ unit: ViewUnit8+ viewModeValue?: number9+ firstDayOfWeek?: number10+}11+312 /**413 * Helper function to get the end of a given temporal unit.5- * @param date {Temporal.ZonedDateTime} - The date for which the end of the unit is needed.6- * @param unit {Unit} - The unit for which to find the end ('day', 'week', 'month', 'year', 'workWeek', 'decade').14+ * @param {EndOfParams} params - The parameters for the endOf function.715 * @returns {Temporal.ZonedDateTime} The end of the given unit.816 */9-export const endOf = (date: Temporal.ZonedDateTime, unit: 'day' | 'week' | 'month' | 'year' | 'workWeek' | 'decade'): Temporal.ZonedDateTime => {17+export function endOf({18+ date,
Sign in to join this conversation.
cutterbl(GitHub profile, opens in a new tab) requested changes
Still figuring out nx and TS, so having trouble visualizing some of this. I've put down some notes on things, and hopefully they make sense. There is a lot here, so I'm sure I missed some stuff.
A big thing is to consider the core idea laid out in the intro wiki entry as well as the core idea around TanStack projects where we deal in data and state, and let the developer decide how they render the UI. Not to say that we won't provide any UI type props at all, but that we have to carefully think through what those things might be (likely ARIA type props and event handlers).
Please take all of this feedback only as constructive criticism. I really appreciate any assistance with this project. While I'm new to nx and TS, I've been a JS developer for 25+ years now, and have been working on scheduling applications for the better part of 20 years, so I'm speaking to you from years of experience in this area.
If you have questions on anything, please reach out.