@atlaskit/editor-plugin-date
Version:
Date plugin for @atlaskit/editor-core
207 lines (198 loc) • 8.16 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
import addDays from 'date-fns/addDays';
import addMonths from 'date-fns/addMonths';
import addYears from 'date-fns/addYears';
// eslint-disable-next-line import/no-namespace
import * as locales from 'date-fns/locale';
import { dateToDateType, dateTypeToDate, formatDateType } from './formatParse';
function isDigit(c) {
if (c === undefined) {
return false;
}
return c >= '0' && c <= '9';
}
/**
* Check if cursor is in first segment of a date.
* @param cursorPos Cursor pos, with 0 referring to the left of first char
* @param date Date string in any locale
*/
function isCursorInFirstDateSegment(cursorPos, date) {
var posCounter = cursorPos - 1;
var isAdjacent = true;
// The date without any non-digit characters on the end
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
var strippedDate = date.replace(/[^0-9]+$/g, '');
while (posCounter >= 0 && isAdjacent) {
var c = strippedDate[posCounter];
if (!isDigit(c)) {
isAdjacent = false;
}
posCounter -= 1;
}
return isAdjacent;
}
/**
* Check if cursor is in last segment of a date.
* @param cursorPos Cursor pos, with 0 referring to the left of first char
* @param date Date string in any locale
*/
function isCursorInLastDateSegment(cursorPos, date) {
var posCounter = cursorPos;
var isAdjacent = true;
// The date without any non-digit characters on the end
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
var strippedDate = date.replace(/[^0-9]+$/g, '');
while (posCounter < strippedDate.length && isAdjacent) {
var c = strippedDate[posCounter];
if (!isDigit(c)) {
isAdjacent = false;
}
posCounter += 1;
}
return isAdjacent;
}
/**
* Inconclusively check if a date string is valid - a value of false means it is definitely
* invalid, a value of true means it might be valid.
* @param date Date string to be parsed
*/
export function isDatePossiblyValid(date) {
var _iterator = _createForOfIteratorHelper(date),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var c = _step.value;
var isNumber = c >= '0' && c <= '9';
var isValidPunctuation = '. ,/-'.indexOf(c) !== -1;
if (!(isNumber || isValidPunctuation)) {
return false;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return true;
}
/**
* Find the segment of a date a position refers to. Eg: pos 2 in 29/03/2020 is in
* the day segment.
* @param position Cursor position, with 0 referring to the left of the first char
* @param date The localised date string
* @param locale The language to interpret the date string in
*/
export function findDateSegmentByPosition(position, date, locale) {
if (position > date.length) {
return undefined;
}
var placeholder = getLocaleDatePlaceholder(locale);
if (!placeholder) {
return undefined;
}
// The placeholder without any non-digit characters on the end
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
var strippedPlaceholder = placeholder.replace(/[^ymd]+$/g, '');
var keyToSegment = {
d: 'day',
m: 'month',
y: 'year'
};
var firstSegment = keyToSegment[strippedPlaceholder[0]];
var lastSegment = keyToSegment[strippedPlaceholder[strippedPlaceholder.length - 1]];
var allPossibleSegments = ['day', 'month', 'year'];
var middleSegment = allPossibleSegments.filter(function (s) {
return s !== firstSegment && s !== lastSegment;
})[0];
if (isCursorInFirstDateSegment(position, date)) {
return firstSegment;
}
if (isCursorInLastDateSegment(position, date)) {
return lastSegment;
}
return middleSegment;
}
/**
* Generate a placeholder date string for a given locale
* eg: locale 'hu-HU' -> 'yyyy. mm. dd.'
* @param locale A locale string supported by Intl.DateTimeFormat
* @returns A placeholder string. d=1 or 2 digit day, dd=zero padded
* day, same for month but letter m, yyyy=year
*/
export function getLocaleDatePlaceholder(locale) {
var uniqueDateType = {
day: 7,
month: 1,
year: 1992
};
var localisedDateString = formatDateType(uniqueDateType, locale);
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
var shortDateFormat = localisedDateString.replace(/\d+/g, function (str) {
if (!str) {
return '';
}
// Ignored via go/ees005
// eslint-disable-next-line no-var
var num = parseInt(str);
switch (num % 100) {
case 92:
// Ignored via go/ees005
// eslint-disable-next-line require-unicode-regexp
return str.replace(/.{1}/g, 'y');
case 1:
return str.length === 1 ? 'm' : 'mm';
case 7:
return str.length === 1 ? 'd' : 'dd';
}
return '';
});
return shortDateFormat;
}
/**
* Adjust date segment up or down. Eg. If day is the active segment and adjustment is -1,
* reduce the day by one.
* @param date Valid datetype
* @param activeSegment which part of the date is selected/being adjusted
* @param adjustment how many units the segment is being adjusted (can be pos or neg, usually 1 or -1)
*/
export function adjustDate(date, activeSegment, adjustment) {
var originalDate = dateTypeToDate(date);
var newDate = activeSegment === 'day' ? addDays(originalDate, adjustment) : activeSegment === 'month' ? addMonths(originalDate, adjustment) : addYears(originalDate, adjustment);
return dateToDateType(newDate);
}
export function isToday(date) {
var today = new Date();
return date !== undefined && today.getDate() === date.day && date.month === today.getMonth() + 1 && date.year === today.getFullYear();
}
/**
* Get the corresponding date-fns locale for a given locale string. Ideally we could rely on Intl
* but firefox does not support getting the first day of the week from it. We have to handle silly
* use cases like 'nl-NL' where the language code is the same as the region code because someone
* decided to format them in this non-standard way
* @param localeString Locale string, eg. 'en-AU'
* @returns Locale or undefined if not found
* @example
* getDFLocale('en-AU') // returns enAU locale
*/
export function getDFLocale(localeString) {
var dfLocaleString = localeString;
var _localeString$split = localeString.split('-'),
_localeString$split2 = _slicedToArray(_localeString$split, 2),
lang = _localeString$split2[0],
region = _localeString$split2[1];
if (region) {
if (lang.toLocaleLowerCase() === region.toLocaleLowerCase()) {
dfLocaleString = lang;
} else {
dfLocaleString = "".concat(lang).concat(region);
}
}
return locales[dfLocaleString];
}