@kahi-ui/framework
Version:
Straight-forward Svelte UI for the Web
79 lines (78 loc) • 3.15 kB
JavaScript
import { Temporal } from "../../vendor/js-temporal-polyfill";
import { DEFAULT_LOCALE, DEFAULT_YEAR } from "../locale";
import { from_datestamp, to_datestamp } from "./datestamps";
const DEFAULT_FORMAT_OPTIONS = {
year: DEFAULT_YEAR,
};
const RESET_UNITS = {
day: 1,
month: 1,
};
export function add_years(datestamp, years) {
const date = from_datestamp(datestamp).add({ years });
return to_datestamp(date);
}
export function clamp_year(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 year_date = source_date.with(RESET_UNITS);
if (maximum) {
const maximum_date = from_datestamp(maximum, RESET_UNITS);
if (Temporal.PlainDate.compare(maximum_date, year_date) < (inclusive ? 0 : 1)) {
return to_datestamp(maximum_date, { day: source_date.day, month: source_date.month });
}
}
if (minimum) {
const minimum_date = from_datestamp(minimum, RESET_UNITS);
if (Temporal.PlainDate.compare(minimum_date, year_date) > (inclusive ? 0 : -1)) {
return to_datestamp(minimum_date, { day: source_date.day, month: source_date.month });
}
}
return to_datestamp(source_date);
}
export function format_year(datestamp, locale = DEFAULT_LOCALE, options = DEFAULT_FORMAT_OPTIONS) {
const date = from_datestamp(datestamp);
return date.toLocaleString(locale, options);
}
export function get_year(datestamp) {
return from_datestamp(datestamp).year;
}
export function includes_year(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_year(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_year_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_year() {
const date = Temporal.Now.plainDateISO();
return to_datestamp(date, RESET_UNITS);
}
export function set_year(datestamp, year) {
const date = from_datestamp(datestamp).with({ year });
return to_datestamp(date);
}
export function subtract_years(datestamp, years) {
const date = from_datestamp(datestamp).subtract({ years });
return to_datestamp(date);
}