@kahi-ui/framework
Version:
Straight-forward Svelte UI for the Web
79 lines (78 loc) • 3.14 kB
JavaScript
import { Temporal } from "../../vendor/js-temporal-polyfill";
import { DEFAULT_LOCALE, DEFAULT_MONTH, DEFAULT_YEAR } from "../locale";
import { from_datestamp, to_datestamp } from "./datestamps";
const DEFAULT_FORMAT_OPTIONS = {
month: DEFAULT_MONTH,
year: DEFAULT_YEAR,
};
const RESET_UNITS = {
day: 1,
};
export function add_months(datestamp, months) {
const date = from_datestamp(datestamp).add({ months });
return to_datestamp(date);
}
export function clamp_month(datestamp, minimum, maximum, inclusive = false) {
// NOTE: Yeah a bit long-winded handling the comparison logic and day manipulation, but
// we want to preserve the input day instead of resetting it all the time
const source_date = from_datestamp(datestamp);
const month_date = source_date.with(RESET_UNITS);
if (maximum) {
const maximum_date = from_datestamp(maximum, RESET_UNITS);
if (Temporal.PlainDate.compare(maximum_date, month_date) < (inclusive ? 0 : 1)) {
return to_datestamp(maximum_date, { day: source_date.day });
}
}
if (minimum) {
const minimum_date = from_datestamp(minimum, RESET_UNITS);
if (Temporal.PlainDate.compare(minimum_date, month_date) > (inclusive ? 0 : -1)) {
return to_datestamp(minimum_date, { day: source_date.day });
}
}
return to_datestamp(source_date);
}
export function format_month(datestamp, locale = DEFAULT_LOCALE, options = DEFAULT_FORMAT_OPTIONS) {
const date = from_datestamp(datestamp);
return date.toLocaleString(locale, options);
}
export function get_month(datestamp) {
return from_datestamp(datestamp).month;
}
export function includes_month(datestamp, targets) {
const source_date = from_datestamp(datestamp, RESET_UNITS);
return !!targets.find((target, index) => {
const target_date = from_datestamp(target, RESET_UNITS);
return source_date.equals(target_date);
});
}
export function is_month(datestamp, target) {
const source_date = from_datestamp(datestamp, RESET_UNITS);
const target_date = from_datestamp(target, RESET_UNITS);
return source_date.equals(target_date);
}
export function is_month_in_range(datestamp, minimum, maximum, inclusive = false) {
const date = from_datestamp(datestamp, RESET_UNITS);
if (maximum) {
const maximum_date = from_datestamp(maximum, RESET_UNITS);
if (Temporal.PlainDate.compare(maximum_date, date) < (inclusive ? 0 : 1))
return false;
}
if (minimum) {
const minimum_date = from_datestamp(minimum, RESET_UNITS);
if (Temporal.PlainDate.compare(minimum_date, date) > (inclusive ? 0 : -1))
return false;
}
return true;
}
export function now_month() {
const date = Temporal.Now.plainDateISO();
return to_datestamp(date, RESET_UNITS);
}
export function set_month(datestamp, month) {
const date = from_datestamp(datestamp).with({ month });
return to_datestamp(date);
}
export function subtract_months(datestamp, months) {
const date = from_datestamp(datestamp).subtract({ months });
return to_datestamp(date);
}