-
Notifications
You must be signed in to change notification settings - Fork 6
/
vwc-calendar.ts
254 lines (226 loc) · 7.25 KB
/
vwc-calendar.ts
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
import '@vonage/vvd-core';
import {
customElement,
html,
LitElement,
property,
TemplateResult
} from 'lit-element';
import type { DirectiveFn } from 'lit-html';
import { repeat } from 'lit-html/directives/repeat.js';
import { style } from './vwc-calendar.css.js';
import {
assertIsValidDateStringRepresentation,
getValidDateString,
getFirstDateOfTheWeek
} from './vwc-calendar-date-functions.js';
import type { VWCCalendarEvent } from './vwc-calendar-event.js';
import {
ARROW_DOWN,
ARROW_LEFT,
ARROW_RIGHT,
ARROW_UP,
getHeaderDescendantGridCell,
isCellOrHeader,
getNextFocusableGridElement,
} from './vwc-calendar-keyboard-interactions.js';
import { getEventContext } from './vwc-calendar-event-context.js';
export const TotalHours = 24;
declare global {
interface HTMLElementTagNameMap {
'vwc-calendar': VWCCalendar;
}
}
/**
* Represents a calendar custom element.
*
* @cssprop [--vvd-calendar-shape=6px] defines the calendar and its events shape (border radius)
*
* @alpha
*/
@customElement('vwc-calendar')
export class VWCCalendar extends LitElement {
/**
* assign styles
* @internal
* */
static override styles = [style];
/**
* The date within a week of choice.
* Accepts any valid date string representation e.g. _2021-01-01_
* @public
* */
@property({
reflect: true,
converter: {
toAttribute(v) {
// throw if not a valid date string representation
assertIsValidDateStringRepresentation(v);
return v;
},
fromAttribute(v) {
// throw if not a valid date string representation
assertIsValidDateStringRepresentation(v);
return new Date(v);
}
}
})
datetime?: Date;
/**
* A locale string or array of locale strings that contain one or more language or locale tags.
* If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale.
* If you omit this parameter, the default locale of the JavaScript runtime is used.
* This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* e.g. en-US | en-US, he-IL
*
* @public
* */
@property({
reflect: true,
type: String
})
locales?: string | string[] | undefined;
/**
* The convention of displayed time in which the day runs from midnight to midnight and is divided into 24 or 12 hours.
* Unless provided, choice will be set according to local time preference (e.g. US = 12, IL = 24)
*
* @public
* */
@property({
reflect: true,
type: Boolean
})
hour12?: boolean;
#daysLength = 7;
#hours = (Array.from({ length: TotalHours - 1 }) as Date[])
.fill(new Date(new Date().setHours(0, 0, 0)))
.map((d, i) => new Date(d.setHours(++i)));
/**
* Fire an event
* @param {string} event - event name
* @param {Object} [detail={}] - optional event detail object
* @returns {boolean} - return true
*/
getEventContext = getEventContext.bind(this);
private getDaysArr(dateArr: Date[]): Date[] {
if (dateArr.length == this.#daysLength) { return dateArr; }
const lastDate = new Date(dateArr[dateArr.length - 1]);
lastDate.setDate(lastDate.getDate() + 1);
const concatenatedDateArr = [...dateArr, lastDate];
return this.getDaysArr(concatenatedDateArr);
}
private get focusedCalendarEvent(): VWCCalendarEvent | null {
return (document.activeElement?.matches('vwc-calendar-event') && document.activeElement as VWCCalendarEvent) || null;
}
private getCalendarEventContainingCell(calendarEvent: VWCCalendarEvent) {
const daySlot = calendarEvent.getAttribute('slot');
const slot = this.shadowRoot?.querySelector(`slot[name="${daySlot}"i]`);
return slot?.parentElement;
}
private arrowKeysInteractions(event: KeyboardEvent) {
const activeElement = this.shadowRoot?.activeElement;
let focusNext: Element | null | undefined;
if (isCellOrHeader(activeElement)) {
focusNext = getNextFocusableGridElement.call(this, event.key, activeElement);
} else if (this.focusedCalendarEvent) {
focusNext = this.getCalendarEventContainingCell(this.focusedCalendarEvent);
} else if (activeElement?.matches('em[role="button"i]')) {
focusNext = getHeaderDescendantGridCell.call(this, event.key, activeElement as HTMLElement);
} else {
// default selectable element (first header)
focusNext = this.shadowRoot?.querySelector('[role="columnheader"i]');
}
this.moveTo(focusNext as HTMLElement);
event.preventDefault();
}
private moveTo(el: HTMLElement | null | undefined) {
const onBlur = ({ target }: FocusEvent) => (target as HTMLElement)?.setAttribute('tabindex', '-1');
el?.addEventListener('blur', onBlur, { once: true });
el?.setAttribute('tabindex', '0');
el?.focus();
}
private onKeydown(event: KeyboardEvent) {
const isArrow = [ARROW_UP, ARROW_RIGHT, ARROW_DOWN, ARROW_LEFT].includes(event.key);
isArrow && this.arrowKeysInteractions(event);
}
protected renderTimeRows(): DirectiveFn {
const length = this.#hours.length + 1;
return repeat(
Array.from({ length }),
() => html`<div role="listitem"></div>`
);
}
protected renderColumns(): DirectiveFn {
const length = this.#daysLength;
return repeat(
Array.from({ length }),
(_, i) => html`
<div role="gridcell" tabindex="-1">
<slot name="day-${i}"></slot>
</div>
`
);
}
/**
* The html days markup
* @internal
* */
protected renderDays(): TemplateResult {
return html`
<div class="column-headers" role="row">
${this.getDaysArr([getFirstDateOfTheWeek(this.datetime)]).map(date => html`
<div role="columnheader" tabindex="-1">
<time datetime=${getValidDateString(date)} aria-readonly="true">
<h2>
<!-- TODO add to column aria-labelledby or describedby to count events and related day e.g. "3 events, Sunday, March 8" -->
<em tabindex="0" role="button" aria-label=${new Intl.DateTimeFormat(this.locales, { weekday: 'long', month: 'long', day: 'numeric' }).format(date)}>
${new Intl.DateTimeFormat(this.locales, { day: '2-digit' }).format(date)}
</em>
<small aria-hidden="true">
${new Intl.DateTimeFormat(this.locales, { weekday: 'short' }).format(date)}
</small>
</h2>
</time>
</div>`)}
</div>`;
}
/**
* the html days markup
* @internal
* */
protected renderHours(): TemplateResult {
const displayedFormatOptions: Intl.DateTimeFormatOptions = { hour: 'numeric', hour12: this.hour12 };
console.log(displayedFormatOptions);
return html`
<div class="row-headers" role="presentation">
${this.#hours.map(h => html`<span role="rowheader">
<time datetime="${new Intl.DateTimeFormat(this.locales, { hour: 'numeric', minute: 'numeric', hour12: false }).format(h)}">
${new Intl.DateTimeFormat(this.locales, displayedFormatOptions).format(h)}
</time>
</span>`)}
</div>`;
}
/**
* the html markup
* @internal
* */
protected override render(): TemplateResult {
return html`
<div role="grid" @keydown=${this.onKeydown}>
${this.renderDays()}
<div class="calendar-row" role="row">
${this.renderHours()}
<div class="calendar-grid-presentation" role="presentation">
<div class="hours" role="list">
${this.renderTimeRows()}
</div>
<div class="columns" role="presentation">
${this.renderColumns()}
</div>
<slot></slot>
</div>
</div>
</div>
`;
}
}