Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 41 additions & 9 deletions src/generate/dateFns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,51 @@ const getLocale = (locale: string): Locale => {
);
};

const dateFnsTokens: Record<string, string> = {
Y: 'y',
D: 'd',
gggg: 'yyyy',
g: 'G',
Wo: 'wo',
wo: 'wo',
A: 'a',
};

// date-fns reads a pair of quotes outside a literal as one apostrophe.
const quoteLiteral = (literal: string) => {
const escaped = literal.replace(/'/g, "''");
return /[^']/.test(literal) ? `'${escaped}'` : escaped;
};

const localeParse = (format: string) => {
return format
.replace(/Y/g, 'y')
.replace(/D/g, 'd')
.replace(/gggg/, 'yyyy')
.replace(/g/g, 'G')
.replace(/([Ww])o/g, 'wo')
.replace(/A/g, 'a');
const tokens = /\[([^\]]*)\]|''|'((?:''|[^'])*)(?:'|$)|gggg|[Ww]o|[\s\S]/g;
let result = '';
let literal = '';

for (const [token, bracketed, quoted] of format.matchAll(tokens)) {
if (bracketed !== undefined) {
literal += bracketed;
} else if (token === "''") {
literal += "'";
} else if (quoted !== undefined) {
literal += quoted.replace(/''/g, "'");
} else {
if (literal) {
result += quoteLiteral(literal);
literal = '';
}
result += dateFnsTokens[token] ?? token;
}
}

const pattern = result + quoteLiteral(literal);
// date-fns uses a lone quote to match empty literal text.
return format && !pattern ? "'" : pattern;
};

const parse = (text: string, format: string, locale: string) => {
return parseDate(text, localeParse(format), new Date(), { locale: getLocale(locale) });
}
return parseDate(text, format, new Date(), { locale: getLocale(locale) });
};

/**
* Check if the text is a valid date considering the format and locale
Expand Down
37 changes: 37 additions & 0 deletions tests/generate.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,43 @@ describe('Picker.Generate', () => {
MockDate.reset();
});

it('round-trips bracketed literals with the date-fns adapter', () => {
const { format, parse } = dateFnsGenerateConfig.locale;
const date = new Date(2020, 9, 23, 14, 5);
for (const pattern of [
"YYYY-MM-DD [TODAY at o'clock] HH:mm",
"YYYY-MM-DD [TODAY][ at o'clock] HH:mm",
"yyyy-MM-dd 'TODAY at o''clock' HH:mm",
]) {
const text = "2020-10-23 TODAY at o'clock 14:05";
expect(format('en_US', date, pattern)).toBe(text);
expect(parse('en_US', text, [pattern])).toEqual(date);
}
});

it.each([
["[foo]'bar'", 'foobar'],
["'foo'[bar]", 'foobar'],
["'[HH]", '[HH]'],
["[']''[o'clock]", "''o'clock"],
["[']", "'"],
])('round-trips date-fns literal suffix %s', (suffix, expected) => {
const { format, parse } = dateFnsGenerateConfig.locale;
const date = new Date(2020, 9, 23, 14, 5);
const pattern = `yyyy-MM-dd HH:mm ${suffix}`;
const text = `2020-10-23 14:05 ${expected}`;
expect(format('en_US', date, pattern)).toBe(text);
expect(parse('en_US', text, [pattern])).toEqual(date);
});

it.each(["'", '[]', '[][]'])('round-trips an empty date-fns literal %s', (pattern) => {
const { format, parse } = dateFnsGenerateConfig.locale;
const date = new Date();
expect(format('en_US', date, pattern)).toBe('');
expect(parse('en_US', '', [pattern])).toEqual(date);
expect(parse('en_US', 'x', [pattern])).toBeNull();
});

const list: { name: string; generateConfig: GenerateConfig<any> }[] = [
{ name: 'moment', generateConfig: momentGenerateConfig },
{ name: 'dayjs', generateConfig: dayjsGenerateConfig },
Expand Down