2
0

(dateInput) Add format option and improve parsing

Use date-fns for custom format and make sure dates are timezone independants

Closes #533, closes #592
This commit is contained in:
Baptiste Arnaud
2023-09-05 10:34:56 +02:00
parent 111fb323b1
commit 9e8fa124b5
14 changed files with 100 additions and 86 deletions

View File

@@ -1,6 +1,7 @@
import { ParsedReply } from '@/features/chat/types'
import { DateInputBlock } from '@typebot.io/schemas'
import { parse as chronoParse } from 'chrono-node'
import { format } from 'date-fns'
export const parseDateReply = (
reply: string,
@@ -8,21 +9,29 @@ export const parseDateReply = (
): ParsedReply => {
const parsedDate = chronoParse(reply)
if (parsedDate.length === 0) return { status: 'fail' }
const formatOptions: Intl.DateTimeFormatOptions = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: block.options.hasTime ? '2-digit' : undefined,
minute: block.options.hasTime ? '2-digit' : undefined,
}
const startDate = parsedDate[0].start
.date()
.toLocaleString(undefined, formatOptions)
const endDate = parsedDate[0].end
?.date()
.toLocaleString(undefined, formatOptions)
const formatString =
block.options.format ??
(block.options.hasTime ? 'dd/MM/yyyy HH:mm' : 'dd/MM/yyyy')
const detectedStartDate = parseDateWithNeutralTimezone(
parsedDate[0].start.date()
)
const startDate = format(detectedStartDate, formatString)
const detectedEndDate = parsedDate[0].end?.date()
? parseDateWithNeutralTimezone(parsedDate[0].end?.date())
: undefined
const endDate = detectedEndDate
? format(detectedEndDate, formatString)
: undefined
if (block.options.isRange && !endDate) return { status: 'fail' }
return {
status: 'success',
reply: block.options.isRange ? `${startDate} to ${endDate}` : startDate,
}
}
const parseDateWithNeutralTimezone = (date: Date) =>
new Date(date.valueOf() + date.getTimezoneOffset() * 60 * 1000)

View File

@@ -142,7 +142,6 @@ test('API chat execution should work on published bot', async ({ request }) => {
data: { message: '8', sessionId: chatSessionId },
})
).json()
console.log(messages, input)
expect(messages[0].content.richText).toStrictEqual([
{
children: [{ text: "I'm gonna shoot multiple inputs now..." }],