@wordpress/components
Version:
UI components for WordPress.
301 lines (300 loc) • 15.2 kB
JavaScript
import { addDays, addMonths, addWeeks, isEqual, isSameDay, isSameMonth, subDays, subMonths, subWeeks } from "date-fns";
import clsx from "clsx";
import { __, _n, isRTL, sprintf } from "@wordpress/i18n";
import { arrowLeft, arrowRight } from "@wordpress/icons";
import { date, dateI18n, getSettings } from "@wordpress/date";
import { useEffect, useRef, useState } from "@wordpress/element";
import { useLilius } from "./use-lilius/index.mjs";
import Button from "../../button/index.mjs";
import { HStack } from "../../h-stack/index.mjs";
import { Heading } from "../../heading/index.mjs";
import { inputToDate, setInConfiguredTimezone, startOfDayInConfiguredTimezone } from "../utils.mjs";
import { TIMEZONELESS_FORMAT } from "../constants.mjs";
import { jsx, jsxs } from "react/jsx-runtime";
// packages/style-runtime/src/index.ts
const STYLE_HASH_ATTRIBUTE = "data-wp-hash";
/**
* Returns the shared style runtime registry.
*
* The registry is stored on `globalThis` so separately bundled copies of this
* package can coordinate through the same document and style maps.
*
* @return The shared runtime registry.
*/
function getRuntime() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) return globalScope.__wpStyleRuntime;
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") registerDocument(document);
return globalScope.__wpStyleRuntime;
}
/**
* Checks whether a document already contains a style tag for a hash.
*
* @param targetDocument Document to inspect.
* @param hash Stable hash for the transformed CSS.
*
* @return Whether the style hash already exists in the document.
*/
function documentContainsStyleHash(targetDocument, hash) {
if (!targetDocument.head) return false;
for (const style of targetDocument.head.querySelectorAll(`style[${STYLE_HASH_ATTRIBUTE}]`)) if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) return true;
return false;
}
/**
* Injects a registered style into a document, unless that document already
* contains a style tag for the same hash.
*
* @param targetDocument Document to inject the style into.
* @param hash Stable hash for the transformed CSS.
* @param css CSS text to inject.
*/
function injectStyle(targetDocument, hash, css) {
if (!targetDocument.head) return;
const runtime = getRuntime();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) return;
if (documentContainsStyleHash(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
/**
* Registers a document as a style injection target.
*
* Existing registered styles are replayed into the document immediately.
* Documents are reference-counted so multiple providers can safely register the
* same document without one cleanup removing it while another registration is
* still active.
*
* @param targetDocument Document to receive registered styles.
* @return Cleanup function that unregisters this document registration.
*/
function registerDocument(targetDocument) {
const runtime = getRuntime();
runtime.documents.set(targetDocument, (runtime.documents.get(targetDocument) ?? 0) + 1);
for (const [hash, css] of runtime.styles) injectStyle(targetDocument, hash, css);
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) return;
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
/**
* Registers a style and injects it into all registered documents.
*
* The hash is used as the deduplication key, so calling this repeatedly with
* the same hash will not add duplicate style tags to a document.
* Registered styles are retained for the lifetime of the page so they can be
* replayed into documents that are registered later.
*
* @param hash Stable hash for the transformed CSS.
* @param css CSS text to inject.
*/
function registerStyle(hash, css) {
const runtime = getRuntime();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) injectStyle(targetDocument, hash, css);
}
// packages/components/src/date-time/date-picker/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("9ccda9ca28", "._4133ce7f8f5171a6__wrapper{box-sizing:border-box}._4133ce7f8f5171a6__wrapper *,._4133ce7f8f5171a6__wrapper :after,._4133ce7f8f5171a6__wrapper :before{box-sizing:inherit}._5d71bd33c79ccd8a__navigator{grid-template-columns:.5fr repeat(5,1fr) .5fr;justify-items:center;margin-bottom:var(--wpds-dimension-gap-lg,16px)}._5d71bd33c79ccd8a__navigator._5d71bd33c79ccd8a__navigator{display:grid}._84049a4038b5abaa__previous-month{grid-column:1/2}._2ed0fb8188d62fd2__next-month{grid-column:7/8}._640229ee401af16b__heading{grid-column:2/7}._640229ee401af16b__heading strong{font-weight:var(--wpds-typography-font-weight-emphasis,600)}._640229ee401af16b__heading._640229ee401af16b__heading{font-size:var(--wpds-typography-font-size-md,13px);font-weight:var(--wpds-typography-font-weight-default,400)}.a6fafdc57e4ec7ef__calendar{column-gap:var(--wpds-dimension-gap-sm,8px);display:grid;grid-template-columns:.5fr repeat(5,1fr) .5fr;justify-items:center;row-gap:var(--wpds-dimension-gap-sm,8px)}._8ea229147ce1d280__day-of-week{color:var(--wpds-color-foreground-content-neutral-weak,#6e6e6e);font-size:var(--wpds-typography-font-size-md,13px);line-height:1.4}._15b622d97c3ea916__day{grid-column:var(--_wp-components-date-picker-column);justify-content:center;padding:0;position:relative}._15b622d97c3ea916__day:where(:disabled){pointer-events:none}._15b622d97c3ea916__day:where(.f4c4764286fd7b88__has-events):before{border:var(--wpds-border-width-sm,2px) solid var(--wpds-color-stroke-interactive-brand,var(--wp-admin-theme-color,#3858e9));border-radius:50%;content:\" \";left:50%;position:absolute;transform:translate(-50%,9px)}._15b622d97c3ea916__day:where(.f4c4764286fd7b88__has-events.ddd970c7f061156e__is-selected):before{border-color:var(--wpds-color-foreground-interactive-brand-strong,#fff)}._15b622d97c3ea916__day._15b622d97c3ea916__day._15b622d97c3ea916__day{border-radius:50%;font-size:var(--wpds-typography-font-size-md,13px);font-weight:var(--wpds-typography-font-weight-default,400);height:28px;width:28px}._15b622d97c3ea916__day._15b622d97c3ea916__day._15b622d97c3ea916__day:where(.ddd970c7f061156e__is-selected){background:var(--wpds-color-background-interactive-brand-strong,var(--wp-admin-theme-color,#3858e9))}._15b622d97c3ea916__day._15b622d97c3ea916__day._15b622d97c3ea916__day:where(.ddd970c7f061156e__is-selected),._15b622d97c3ea916__day._15b622d97c3ea916__day._15b622d97c3ea916__day:where(.ddd970c7f061156e__is-selected):hover:not(:disabled,[aria-disabled=true]){color:var(--wpds-color-foreground-interactive-brand-strong,#fff)}._15b622d97c3ea916__day._15b622d97c3ea916__day._15b622d97c3ea916__day:where(.ddd970c7f061156e__is-selected):focus:not(:disabled){border:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid}._15b622d97c3ea916__day._15b622d97c3ea916__day._15b622d97c3ea916__day:where(.ddd970c7f061156e__is-selected):after{border:var(--wpds-border-width-xs,1px) solid transparent;border-radius:inherit;content:\"\";inset:0;pointer-events:none;position:absolute}._15b622d97c3ea916__day._15b622d97c3ea916__day._15b622d97c3ea916__day:where(._9af06b51a4cb7f3d__is-today){background:var(--wpds-color-background-surface-neutral-weak,#f3f3f3)}");
var style_module_default = {
"wrapper": "_4133ce7f8f5171a6__wrapper",
"navigator": "_5d71bd33c79ccd8a__navigator",
"previous-month": "_84049a4038b5abaa__previous-month",
"next-month": "_2ed0fb8188d62fd2__next-month",
"heading": "_640229ee401af16b__heading",
"calendar": "a6fafdc57e4ec7ef__calendar",
"day-of-week": "_8ea229147ce1d280__day-of-week",
"day": "_15b622d97c3ea916__day",
"has-events": "f4c4764286fd7b88__has-events",
"is-selected": "ddd970c7f061156e__is-selected",
"is-today": "_9af06b51a4cb7f3d__is-today"
};
// packages/components/src/date-time/date-picker/index.tsx
/**
* DatePicker is a React component that renders a calendar for date selection.
*
* ```jsx
* import { DatePicker } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyDatePicker = () => {
* const [ date, setDate ] = useState( new Date() );
*
* return (
* <DatePicker
* currentDate={ date }
* onChange={ ( newDate ) => setDate( newDate ) }
* />
* );
* };
* ```
*/
function DatePicker({ currentDate, onChange, events = [], isInvalidDate, onMonthPreviewed, startOfWeek: weekStartsOn = 0 }) {
const date$1 = inputToDate(currentDate ?? /* @__PURE__ */ new Date());
const { calendar, viewing, setSelected, setViewing, isSelected, viewPreviousMonth, viewNextMonth } = useLilius({
selected: [startOfDayInConfiguredTimezone(date$1)],
viewing: startOfDayInConfiguredTimezone(date$1),
weekStartsOn
});
const [focusable, setFocusable] = useState(startOfDayInConfiguredTimezone(date$1));
const [isFocusWithinCalendar, setIsFocusWithinCalendar] = useState(false);
const [prevCurrentDate, setPrevCurrentDate] = useState(currentDate);
if (currentDate !== prevCurrentDate) {
setPrevCurrentDate(currentDate);
setSelected([startOfDayInConfiguredTimezone(date$1)]);
setViewing(startOfDayInConfiguredTimezone(date$1));
setFocusable(startOfDayInConfiguredTimezone(date$1));
}
return /* @__PURE__ */ jsxs("div", {
className: clsx("components-datetime__date", style_module_default.wrapper),
role: "application",
"aria-label": __("Calendar"),
children: [/* @__PURE__ */ jsxs(HStack, {
className: style_module_default.navigator,
children: [
/* @__PURE__ */ jsx(Button, {
className: style_module_default["previous-month"],
icon: isRTL() ? arrowRight : arrowLeft,
variant: "tertiary",
"aria-label": __("View previous month"),
onClick: () => {
viewPreviousMonth();
setFocusable(subMonths(focusable, 1));
const prevMonth = subMonths(viewing, 1);
onMonthPreviewed?.(dateI18n(TIMEZONELESS_FORMAT, prevMonth, -prevMonth.getTimezoneOffset()));
},
size: "compact"
}),
/* @__PURE__ */ jsxs(Heading, {
level: 3,
className: style_module_default.heading,
children: [
/* @__PURE__ */ jsx("strong", { children: dateI18n("F", viewing, -viewing.getTimezoneOffset()) }),
" ",
dateI18n("Y", viewing, -viewing.getTimezoneOffset())
]
}),
/* @__PURE__ */ jsx(Button, {
className: style_module_default["next-month"],
icon: isRTL() ? arrowLeft : arrowRight,
variant: "tertiary",
"aria-label": __("View next month"),
onClick: () => {
viewNextMonth();
setFocusable(addMonths(focusable, 1));
const nextMonth = addMonths(viewing, 1);
onMonthPreviewed?.(dateI18n(TIMEZONELESS_FORMAT, nextMonth, -nextMonth.getTimezoneOffset()));
},
size: "compact"
})
]
}), /* @__PURE__ */ jsxs("div", {
className: style_module_default.calendar,
onFocus: () => setIsFocusWithinCalendar(true),
onBlur: () => setIsFocusWithinCalendar(false),
children: [calendar[0][0].map((day) => /* @__PURE__ */ jsx("div", {
className: style_module_default["day-of-week"],
children: dateI18n("D", day, -day.getTimezoneOffset())
}, day.toString())), calendar[0].map((week) => week.map((day, index) => {
if (!isSameMonth(day, viewing)) return null;
return /* @__PURE__ */ jsx(Day, {
day,
column: index + 1,
isSelected: isSelected(day),
isFocusable: isEqual(day, focusable),
isFocusAllowed: isFocusWithinCalendar,
isToday: isSameDay(day, startOfDayInConfiguredTimezone(/* @__PURE__ */ new Date())),
isInvalid: isInvalidDate ? isInvalidDate(day) : false,
numEvents: events.filter((event) => isSameDay(event.date, day)).length,
onClick: () => {
setSelected([day]);
setFocusable(day);
const newDate = setInConfiguredTimezone(date$1, {
year: day.getFullYear(),
month: day.getMonth(),
date: day.getDate()
});
onChange?.(date(TIMEZONELESS_FORMAT, newDate));
},
onKeyDown: (event) => {
let nextFocusable;
if (event.key === "ArrowLeft") nextFocusable = addDays(day, isRTL() ? 1 : -1);
if (event.key === "ArrowRight") nextFocusable = addDays(day, isRTL() ? -1 : 1);
if (event.key === "ArrowUp") nextFocusable = subWeeks(day, 1);
if (event.key === "ArrowDown") nextFocusable = addWeeks(day, 1);
if (event.key === "PageUp") nextFocusable = subMonths(day, 1);
if (event.key === "PageDown") nextFocusable = addMonths(day, 1);
if (event.key === "Home") {
const daysToSubtract = (day.getDay() - weekStartsOn + 7) % 7;
nextFocusable = subDays(day, daysToSubtract);
}
if (event.key === "End") {
const dayOfWeek = day.getDay();
const daysToAdd = (weekStartsOn + 6 - dayOfWeek) % 7;
nextFocusable = addDays(day, daysToAdd);
}
if (nextFocusable) {
event.preventDefault();
setFocusable(nextFocusable);
if (!isSameMonth(nextFocusable, viewing)) {
setViewing(nextFocusable);
onMonthPreviewed?.(dateI18n(TIMEZONELESS_FORMAT, nextFocusable, -nextFocusable.getTimezoneOffset()));
}
}
}
}, day.toString());
}))]
})]
});
}
function Day({ day, column, isSelected, isFocusable, isFocusAllowed, isToday, isInvalid, numEvents, onClick, onKeyDown }) {
const ref = useRef(null);
useEffect(() => {
if (ref.current && isFocusable && isFocusAllowed) ref.current.focus();
}, [isFocusable]);
return /* @__PURE__ */ jsx(Button, {
__next40pxDefaultSize: true,
ref,
className: clsx("components-datetime__date__day", style_module_default.day, {
[style_module_default["is-selected"]]: isSelected,
[style_module_default["is-today"]]: !isSelected && isToday,
[style_module_default["has-events"]]: numEvents > 0
}),
style: { "--_wp-components-date-picker-column": column },
disabled: isInvalid,
tabIndex: isFocusable ? 0 : -1,
"aria-label": getDayLabel(day, isSelected, isToday, numEvents),
onClick,
onKeyDown,
children: dateI18n("j", day, -day.getTimezoneOffset())
});
}
function getDayLabel(date, isSelected, isToday, numEvents) {
const { formats } = getSettings();
const parts = [dateI18n(formats.date, date, -date.getTimezoneOffset())];
if (isSelected) parts.push(__("Selected"));
if (isToday) parts.push(__("Today"));
if (numEvents > 0) parts.push(sprintf(_n("There is %d event", "There are %d events", numEvents), numEvents));
return parts.join(". ");
}
export { DatePicker, DatePicker as default };
//# sourceMappingURL=index.mjs.map