@helpwave/hightide
Version:
helpwave's component and theming library
247 lines (238 loc) • 9.06 kB
JavaScript
// src/components/date/YearMonthPicker.tsx
import { useEffect as useEffect3, useRef, useState as useState4 } from "react";
import { Scrollbars } from "react-custom-scrollbars-2";
// src/util/noop.ts
var noop = () => void 0;
// src/util/array.ts
var equalSizeGroups = (array, groupSize) => {
if (groupSize <= 0) {
console.warn(`group size should be greater than 0: groupSize = ${groupSize}`);
return [[...array]];
}
const groups = [];
for (let i = 0; i < array.length; i += groupSize) {
groups.push(array.slice(i, Math.min(i + groupSize, array.length)));
}
return groups;
};
var range = (start, end, allowEmptyRange = false) => {
if (end < start) {
if (!allowEmptyRange) {
console.warn(`range: end (${end}) < start (${start}) should be allowed explicitly, set allowEmptyRange to true`);
}
return [];
}
return Array.from({ length: end - start + 1 }, (_, index) => index + start);
};
// src/components/date/YearMonthPicker.tsx
import clsx2 from "clsx";
// src/components/Expandable.tsx
import { forwardRef, useState } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import clsx from "clsx";
import { jsx, jsxs } from "react/jsx-runtime";
var DefaultIcon = (expanded) => expanded ? /* @__PURE__ */ jsx(ChevronUp, { size: 16, className: "min-w-[16px]" }) : /* @__PURE__ */ jsx(ChevronDown, { size: 16, className: "min-w-[16px]" });
var Expandable = forwardRef(({
children,
label,
icon,
initialExpansion = false,
clickOnlyOnHeader = true,
className = "",
headerClassName = ""
}, ref) => {
const [isExpanded, setIsExpanded] = useState(initialExpansion);
icon ??= DefaultIcon;
return /* @__PURE__ */ jsxs(
"div",
{
ref,
className: clsx("col bg-surface text-on-surface group rounded-lg shadow-sm", { "cursor-pointer": !clickOnlyOnHeader }, className),
onClick: () => !clickOnlyOnHeader && setIsExpanded(!isExpanded),
children: [
/* @__PURE__ */ jsxs(
"button",
{
className: clsx("btn-md rounded-lg justify-between items-center bg-surface text-on-surface", { "group-hover:brightness-95": !isExpanded }, headerClassName),
onClick: () => clickOnlyOnHeader && setIsExpanded(!isExpanded),
children: [
label,
icon(isExpanded)
]
}
),
isExpanded && /* @__PURE__ */ jsx("div", { className: "col", children })
]
}
);
});
Expandable.displayName = "Expandable";
// src/util/date.ts
var monthsList = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var changeDuration = (date, duration, isAdding) => {
const {
years = 0,
months = 0,
days = 0,
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0
} = duration;
if (years < 0) {
console.error(`Range error years must be greater than 0: received ${years}`);
return new Date(date);
}
if (months < 0 || months > 11) {
console.error(`Range error month must be 0 <= month <= 11: received ${months}`);
return new Date(date);
}
if (days < 0) {
console.error(`Range error days must be greater than 0: received ${days}`);
return new Date(date);
}
if (hours < 0 || hours > 23) {
console.error(`Range error hours must be 0 <= hours <= 23: received ${hours}`);
return new Date(date);
}
if (minutes < 0 || minutes > 59) {
console.error(`Range error minutes must be 0 <= minutes <= 59: received ${minutes}`);
return new Date(date);
}
if (seconds < 0 || seconds > 59) {
console.error(`Range error seconds must be 0 <= seconds <= 59: received ${seconds}`);
return new Date(date);
}
if (milliseconds < 0) {
console.error(`Range error seconds must be greater than 0: received ${milliseconds}`);
return new Date(date);
}
const multiplier = isAdding ? 1 : -1;
const newDate = new Date(date);
newDate.setFullYear(newDate.getFullYear() + multiplier * years);
newDate.setMonth(newDate.getMonth() + multiplier * months);
newDate.setDate(newDate.getDate() + multiplier * days);
newDate.setHours(newDate.getHours() + multiplier * hours);
newDate.setMinutes(newDate.getMinutes() + multiplier * minutes);
newDate.setSeconds(newDate.getSeconds() + multiplier * seconds);
newDate.setMilliseconds(newDate.getMilliseconds() + multiplier * milliseconds);
return newDate;
};
var addDuration = (date, duration) => {
return changeDuration(date, duration, true);
};
var subtractDuration = (date, duration) => {
return changeDuration(date, duration, false);
};
// src/hooks/useLanguage.tsx
import { createContext, useContext, useEffect as useEffect2, useState as useState3 } from "react";
// src/hooks/useLocalStorage.tsx
import { useCallback, useEffect, useState as useState2 } from "react";
// src/hooks/useLanguage.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var DEFAULT_LANGUAGE = "en";
var LanguageContext = createContext({ language: DEFAULT_LANGUAGE, setLanguage: (v) => v });
var useLanguage = () => useContext(LanguageContext);
var useLocale = (overWriteLanguage) => {
const { language } = useLanguage();
const mapping = {
en: "en-US",
de: "de-DE"
};
return mapping[overWriteLanguage ?? language];
};
// src/components/date/YearMonthPicker.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var YearMonthPicker = ({
displayedYearMonth = /* @__PURE__ */ new Date(),
start = subtractDuration(/* @__PURE__ */ new Date(), { years: 50 }),
end = addDuration(/* @__PURE__ */ new Date(), { years: 50 }),
onChange = noop,
className = "",
maxHeight = 300,
showValueOpen = true
}) => {
const locale = useLocale();
const ref = useRef(null);
useEffect3(() => {
const scrollToItem = () => {
if (ref.current) {
ref.current.scrollIntoView({
behavior: "instant",
block: "center"
});
}
};
scrollToItem();
}, [ref]);
if (end < start) {
console.error(`startYear: (${start}) less than endYear: (${end})`);
return null;
}
const years = range(start.getFullYear(), end.getFullYear());
return /* @__PURE__ */ jsx3("div", { className: clsx2("col select-none", className), children: /* @__PURE__ */ jsx3(Scrollbars, { autoHeight: true, autoHeightMax: maxHeight, style: { height: "100%" }, children: /* @__PURE__ */ jsx3("div", { className: "col gap-y-1 mr-3", children: years.map((year) => {
const selectedYear = displayedYearMonth.getFullYear() === year;
return /* @__PURE__ */ jsx3(
Expandable,
{
ref: (displayedYearMonth.getFullYear() ?? (/* @__PURE__ */ new Date()).getFullYear()) === year ? ref : void 0,
label: /* @__PURE__ */ jsx3("span", { className: clsx2({ "text-primary font-bold": selectedYear }), children: year }),
initialExpansion: showValueOpen && selectedYear,
children: /* @__PURE__ */ jsx3("div", { className: "col gap-y-1 px-2 pb-2", children: equalSizeGroups([...monthsList], 3).map((monthList, index) => /* @__PURE__ */ jsx3("div", { className: "row", children: monthList.map((month) => {
const monthIndex = monthsList.indexOf(month);
const newDate = new Date(year, monthIndex);
const selectedMonth = selectedYear && monthIndex === displayedYearMonth.getMonth();
const firstOfMonth = new Date(year, monthIndex, 1);
const lastOfMonth = new Date(year, monthIndex, 1);
const isAfterStart = start === void 0 || start <= addDuration(subtractDuration(lastOfMonth, { days: 1 }), { months: 1 });
const isBeforeEnd = end === void 0 || firstOfMonth <= end;
const isValid = isAfterStart && isBeforeEnd;
return /* @__PURE__ */ jsx3(
"button",
{
disabled: !isValid,
className: clsx2(
"chip hover:brightness-95 flex-1",
{
"bg-gray-50 text-black": !selectedMonth && isValid,
"bg-primary text-on-primary": selectedMonth && isValid,
"bg-disabled-background text-disabled-text": !isValid
}
),
onClick: () => {
onChange(newDate);
},
children: new Intl.DateTimeFormat(locale, { month: "short" }).format(newDate)
},
month
);
}) }, index)) })
},
year
);
}) }) }) });
};
var ControlledYearMonthPicker = ({
displayedYearMonth = /* @__PURE__ */ new Date(),
onChange = noop,
...props
}) => {
const [yearMonth, setYearMonth] = useState4(displayedYearMonth);
useEffect3(() => setYearMonth(displayedYearMonth), [displayedYearMonth]);
return /* @__PURE__ */ jsx3(
YearMonthPicker,
{
displayedYearMonth: yearMonth,
onChange: (date) => {
setYearMonth(date);
onChange(date);
},
...props
}
);
};
export {
ControlledYearMonthPicker,
YearMonthPicker
};
//# sourceMappingURL=YearMonthPicker.mjs.map