@event-calendar/react 0.0.0-stage → 5.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # EventCalendar for React
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The React component of [EventCalendar](https://github.com/vkurko/calendar), a full-sized drag & drop JavaScript event calendar with resource & timeline views.
4
+
5
+ See the [demo](https://vkurko.github.io/calendar/) and the [documentation](https://github.com/vkurko/calendar#readme) of all options and methods.
6
+
7
+ ## Usage
8
+ The first step is to install the EventCalendar `react` package:
9
+ ```bash
10
+ npm install --save-dev @event-calendar/react
11
+ ```
12
+ This package provides the `EventCalendar` component, as well as plugins for various views. You must use at least one plugin that provides a view. The following plugins are currently available:
13
+
14
+ * `DayGrid`
15
+ * `List`
16
+ * `ResourceTimeline`
17
+ * `ResourceTimeGrid`
18
+ * `TimeGrid`
19
+ * `Interaction` (doesn't provide a view)
20
+
21
+ Then in your React component, use the calendar like this:
22
+ ```jsx
23
+ import {useState} from 'react';
24
+ import {EventCalendar, TimeGrid} from '@event-calendar/react';
25
+ import '@event-calendar/react/index.css';
26
+
27
+ const plugins = [TimeGrid];
28
+
29
+ export default function App() {
30
+ const [events, setEvents] = useState([
31
+ // your list of events
32
+ ]);
33
+
34
+ return (
35
+ <EventCalendar
36
+ plugins={plugins}
37
+ view="timeGridWeek"
38
+ events={events}
39
+ eventClick={({event}) => console.log(event.id)}
40
+ />
41
+ );
42
+ }
43
+ ```
44
+ All [options](https://github.com/vkurko/calendar#options) are passed as props, and the calendar is updated when they change. Objects, arrays and callbacks can be written right in JSX, there is no need for `useMemo` and `useCallback`. The `className`, `style` and `id` props are set on the element that wraps the calendar.
45
+
46
+ The calendar is destroyed gracefully when the component containing it is destroyed.
47
+
48
+ ### Rendering content with React
49
+ The following options accept JSX or a function that returns JSX:
50
+
51
+ * [allDayContent](https://github.com/vkurko/calendar#alldaycontent)
52
+ * [dayCellContent](https://github.com/vkurko/calendar#daycellcontent)
53
+ * [eventContent](https://github.com/vkurko/calendar#eventcontent)
54
+ * [moreLinkContent](https://github.com/vkurko/calendar#morelinkcontent)
55
+ * [noEventsContent](https://github.com/vkurko/calendar#noeventscontent)
56
+ * [resourceLabelContent](https://github.com/vkurko/calendar#resourcelabelcontent)
57
+ * [weekNumberContent](https://github.com/vkurko/calendar#weeknumbercontent)
58
+ * the `content` property of [customButtons](https://github.com/vkurko/calendar#custombuttons)
59
+
60
+ ```jsx
61
+ <EventCalendar
62
+ plugins={plugins}
63
+ eventContent={({event, timeText}) => <EventBody event={event} time={timeText}/>}
64
+ noEventsContent={<i>No events</i>}
65
+ headerToolbar={{start: 'title', center: '', end: 'filter today prev,next'}}
66
+ customButtons={{filter: {content: <input value={query} onChange={e => setQuery(e.target.value)}/>}}}
67
+ />
68
+ ```
69
+ The argument of the function is described in the documentation of each option. If the function returns `null` or `undefined`, the default content is shown.
70
+
71
+ ### Calling methods in React
72
+ The [methods](https://github.com/vkurko/calendar#methods) of the calendar are available through the `ref`:
73
+ ```jsx
74
+ const calendar = useRef(null);
75
+
76
+ <EventCalendar ref={calendar} plugins={plugins}/>
77
+ <button onClick={() => calendar.current.next()}>Next</button>
78
+ ```
79
+
80
+ ## License
81
+ MIT
package/index.css ADDED
@@ -0,0 +1 @@
1
+ @import '@event-calendar/core/index.css';
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@event-calendar/react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "5.22.0",
4
+ "title": "Event Calendar React component",
5
+ "description": "React component of the full-sized drag & drop event calendar with resource & timeline views",
6
+ "keywords": [
7
+ "calendar",
8
+ "event",
9
+ "resource",
10
+ "timeline",
11
+ "full-sized",
12
+ "react"
13
+ ],
14
+ "homepage": "https://vkurko.github.io/calendar/",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/vkurko/calendar.git",
18
+ "directory": "packages/react"
19
+ },
20
+ "license": "MIT",
21
+ "files": [
22
+ "src",
23
+ "types",
24
+ "index.css"
25
+ ],
26
+ "type": "module",
27
+ "sideEffects": [
28
+ "*.css"
29
+ ],
30
+ "types": "./types/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./types/index.d.ts",
34
+ "default": "./src/index.js"
35
+ },
36
+ "./index.css": "./index.css",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "dependencies": {
40
+ "@event-calendar/core": "~5.22.0"
41
+ },
42
+ "peerDependencies": {
43
+ "react": ">=18",
44
+ "react-dom": ">=18"
45
+ }
6
46
  }
package/src/index.js ADDED
@@ -0,0 +1,211 @@
1
+ import {
2
+ createElement, forwardRef, memo, useEffect, useImperativeHandle, useLayoutEffect, useReducer, useRef
3
+ } from 'react';
4
+ import {createPortal, flushSync} from 'react-dom';
5
+ import {createCalendar, destroyCalendar} from '@event-calendar/core';
6
+
7
+ export * from '@event-calendar/core';
8
+
9
+ // Options whose content is rendered by React
10
+ const CONTENT = (
11
+ 'allDayContent dayCellContent eventContent moreLinkContent noEventsContent resourceLabelContent weekNumberContent'
12
+ ).split(' ');
13
+
14
+ // Callbacks that the calendar only calls, so they can be replaced without the calendar knowing it
15
+ const CALLBACKS = (
16
+ 'dateClick datesSet dragConstraint eventAllUpdated eventClick eventDidMount eventDragStart eventDragStop ' +
17
+ 'eventDrop eventMouseEnter eventMouseLeave eventResize eventResizeStart eventResizeStop loading noEventsClick ' +
18
+ 'resizeConstraint resourceExpand resourceLabelDidMount select selectConstraint unselect viewDidMount'
19
+ ).split(' ');
20
+
21
+ const useIsomorphicLayoutEffect = typeof document == 'undefined' ? useEffect : useLayoutEffect;
22
+
23
+ let uid = 0;
24
+
25
+ export const EventCalendar = forwardRef(function EventCalendar({plugins, options, className, style, id, ...rest}, ref) {
26
+ let props = {...options};
27
+ let attrs = {ref: useRef(null), className, style, id};
28
+ for (let name in rest) {
29
+ // Data and ARIA attributes are passed to the element, everything else is the options of the calendar
30
+ (name.includes('-') ? attrs : props)[name] = rest[name];
31
+ }
32
+
33
+ let update = useReducer(n => n + 1, 0)[1];
34
+ let self = useRef(null);
35
+ let s = self.current ??= {slots: new Map(), stable: {}, update};
36
+
37
+ useIsomorphicLayoutEffect(() => {
38
+ s.props = props;
39
+ if (s.calendar) {
40
+ // Set the options that did change
41
+ let prev = s.options;
42
+ let next = s.options = toOptions(s);
43
+ for (let name in {...prev, ...next}) {
44
+ if (!same(prev[name], next[name])) {
45
+ s.calendar.setOption(name, next[name]);
46
+ }
47
+ }
48
+ }
49
+ });
50
+
51
+ useIsomorphicLayoutEffect(() => {
52
+ let calendar = s.calendar = createCalendar(attrs.ref.current, plugins, s.options = toOptions(s));
53
+
54
+ return () => {
55
+ s.calendar = null;
56
+ destroyCalendar(calendar);
57
+ };
58
+ }, []);
59
+
60
+ useImperativeHandle(ref, () => s.calendar, []);
61
+
62
+ let portals = [];
63
+ for (let [el, slot] of s.slots) {
64
+ portals.push(createElement(Slot, {key: slot.key, el, arg: slot.arg, render: slot.read(props)}));
65
+ }
66
+
67
+ return createElement('div', attrs, portals);
68
+ });
69
+
70
+ const Slot = memo(function Slot({el, arg, render}) {
71
+ return createPortal(isFunction(render) ? render(arg) : render, el);
72
+ });
73
+
74
+ /**
75
+ * Create the options for the calendar. The functions given to the calendar stay the same between the renders,
76
+ * so that a new function passed as a prop does not make the calendar update.
77
+ */
78
+ function toOptions(s) {
79
+ let options = {};
80
+ for (let name in s.props) {
81
+ let value = s.props[name];
82
+ if (value !== undefined) {
83
+ if (CONTENT.includes(name)) {
84
+ value = stableContent(s, name, value, props => props[name]);
85
+ } else if (isFunction(value)) {
86
+ if (CALLBACKS.includes(name)) {
87
+ value = s.stable[name] ??= (...args) => s.props[name]?.(...args);
88
+ }
89
+ } else if (name == 'customButtons') {
90
+ value = customButtons(s, value);
91
+ }
92
+ options[name] = value;
93
+ }
94
+ }
95
+ return options;
96
+ }
97
+
98
+ function customButtons(s, buttons) {
99
+ let result = {};
100
+ for (let name in buttons) {
101
+ let button = result[name] = {...buttons[name]};
102
+ if (button.content != null) {
103
+ button.content = stableContent(
104
+ s, 'content:' + name, button.content, props => props.customButtons?.[name]?.content
105
+ );
106
+ }
107
+ if (isFunction(button.click)) {
108
+ button.click = s.stable['click:' + name] ??= (...args) => s.props.customButtons?.[name]?.click?.(...args);
109
+ }
110
+ }
111
+ return result;
112
+ }
113
+
114
+ /**
115
+ * Get the content function for the calendar. It stays the same when a new value is passed as a prop, because React
116
+ * renders the content with the new value by itself. The exception is the value that did return nothing for some
117
+ * content: the calendar shows its default content then, so it has to ask again to learn where the new value does it.
118
+ */
119
+ function stableContent(s, key, value, read) {
120
+ let fn = s.stable[key];
121
+ if (!fn || fn.sparse && fn.value !== value) {
122
+ fn = s.stable[key] = content(s, read);
123
+ }
124
+ fn.value = value;
125
+ return fn;
126
+ }
127
+
128
+ /**
129
+ * Create the content function for the calendar, which returns the function that receives the element to render into.
130
+ * `read` returns what has to be rendered from the given props: a React node or a function that returns it.
131
+ */
132
+ function content(s, read) {
133
+ return function fn(arg) {
134
+ let render = read(s.props);
135
+ if ((isFunction(render) ? render(arg) : render) == null) {
136
+ fn.sparse = true;
137
+ } else {
138
+ return el => {
139
+ let slot = s.slots.get(el);
140
+ if (!slot) {
141
+ // The element can still hold the content rendered by the calendar
142
+ el.textContent = '';
143
+ s.slots.set(el, slot = {key: ++uid});
144
+ }
145
+ slot.read = read;
146
+ slot.arg = arg;
147
+ slot.live = true;
148
+ schedule(s);
149
+
150
+ return () => {
151
+ slot.live = false;
152
+ schedule(s);
153
+ };
154
+ };
155
+ }
156
+ };
157
+ }
158
+
159
+ function schedule(s) {
160
+ if (!s.scheduled) {
161
+ s.scheduled = true;
162
+ queueMicrotask(() => {
163
+ s.scheduled = false;
164
+ let reused = [];
165
+ for (let [el, slot] of s.slots) {
166
+ if (!slot.live) {
167
+ s.slots.delete(el);
168
+ if (el.isConnected) {
169
+ // The calendar has already replaced the content of the element, so React will not find its nodes
170
+ el.removeChild = removeChild;
171
+ reused.push(el);
172
+ }
173
+ }
174
+ }
175
+ if (s.calendar) {
176
+ // Render right away, so that the content is in place before the browser paints the calendar
177
+ flushSync(s.update);
178
+ }
179
+ for (let el of reused) {
180
+ delete el.removeChild;
181
+ }
182
+ });
183
+ }
184
+ }
185
+
186
+ function removeChild(child) {
187
+ return child.parentNode == this ? Node.prototype.removeChild.call(this, child) : child;
188
+ }
189
+
190
+ /** Compare the values of an option, so that an equal object or array created on each render is not set again */
191
+ function same(a, b, depth = 0) {
192
+ if (a === b) {
193
+ return true;
194
+ }
195
+ if (!a || !b || typeof a != 'object' || typeof b != 'object' || depth > 9) {
196
+ return false;
197
+ }
198
+ if (a instanceof Date) {
199
+ return b instanceof Date && +a == +b;
200
+ }
201
+ let proto = Object.getPrototypeOf(a);
202
+ if (proto != Object.getPrototypeOf(b) || proto != Object.prototype && proto != Array.prototype) {
203
+ return false;
204
+ }
205
+ let keys = Object.keys(a);
206
+ return keys.length == Object.keys(b).length && keys.every(key => same(a[key], b[key], depth + 1));
207
+ }
208
+
209
+ function isFunction(value) {
210
+ return typeof value == 'function';
211
+ }
@@ -0,0 +1,53 @@
1
+ /// <reference lib="es6" />
2
+ /// <reference lib="dom" />
3
+ import type { CSSProperties, ForwardRefExoticComponent, ReactNode, RefAttributes } from "react";
4
+ import type { Calendar } from "@event-calendar/core";
5
+
6
+ export * from "@event-calendar/core";
7
+
8
+ type ContentOption =
9
+ | "allDayContent"
10
+ | "dayCellContent"
11
+ | "eventContent"
12
+ | "moreLinkContent"
13
+ | "noEventsContent"
14
+ | "resourceLabelContent"
15
+ | "weekNumberContent";
16
+
17
+ /**
18
+ * A React node or a function that returns it. The function receives the same argument as the function form of
19
+ * the option. If nothing is returned (`null` or `undefined`), the default content is shown.
20
+ */
21
+ type ReactContent<T> =
22
+ | ReactNode
23
+ | (Extract<T, (...args: any[]) => any> extends (...args: infer A) => any ? (...args: A) => ReactNode : never);
24
+
25
+ /** An arbitrary widget placed in the toolbar instead of a button */
26
+ export interface CustomItem {
27
+ content: ReactNode | (() => ReactNode);
28
+ }
29
+
30
+ export interface CustomButtons {
31
+ [key: string]: Calendar.CustomButton | CustomItem;
32
+ }
33
+
34
+ /** The options of the calendar, where the content is defined with React */
35
+ export type EventCalendarOptions =
36
+ & Omit<Calendar.Options, ContentOption | "customButtons">
37
+ & { [K in ContentOption]?: ReactContent<Calendar.Options[K]> }
38
+ & { customButtons?: CustomButtons | ((customButtons: Calendar.CustomButtons) => Calendar.CustomButtons) };
39
+
40
+ export type EventCalendarProps = EventCalendarOptions & {
41
+ plugins: Calendar.Plugin[];
42
+ /** The options as an object, the options passed as separate props take precedence */
43
+ options?: EventCalendarOptions;
44
+ /** `className`, `style`, `id`, `data-*` and `aria-*` are set on the element that contains the calendar */
45
+ className?: string;
46
+ style?: CSSProperties;
47
+ id?: string;
48
+ [key: `data-${string}`]: unknown;
49
+ [key: `aria-${string}`]: unknown;
50
+ };
51
+
52
+ /** The calendar. Its methods are available through the `ref`. */
53
+ export const EventCalendar: ForwardRefExoticComponent<EventCalendarProps & RefAttributes<Calendar>>;