-
-
Notifications
You must be signed in to change notification settings - Fork 392
/
DateTimePlugin.tsx
103 lines (82 loc) · 3.05 KB
/
DateTimePlugin.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import {
COMMAND_PRIORITY_EDITOR,
$createTextNode,
$getSelection,
$isRangeSelection,
$createParagraphNode,
} from 'lexical'
import { useEffect } from 'react'
import { INSERT_DATETIME_COMMAND, INSERT_TIME_COMMAND, INSERT_DATE_COMMAND } from '../Commands'
import { mergeRegister } from '@lexical/utils'
import { $createHeadingNode } from '@lexical/rich-text'
import { formatDateAndTimeForNote, dateToHoursAndMinutesTimeString } from '@/Utils/DateUtils'
import { INSERT_HORIZONTAL_RULE_COMMAND } from '@lexical/react/LexicalHorizontalRuleNode'
export default function DatetimePlugin(): JSX.Element | null {
const [editor] = useLexicalComposerContext()
useEffect(() => {
return mergeRegister(
editor.registerCommand<string>(
INSERT_DATETIME_COMMAND,
() => {
const now = new Date()
const selection = $getSelection()
if (!$isRangeSelection(selection)) {
return false
}
const heading = $createHeadingNode('h1')
const dateString = $createTextNode(formatDateAndTimeForNote(now, false))
dateString.setFormat('italic')
heading.append(dateString)
const timeNode = $createTextNode(dateToHoursAndMinutesTimeString(now))
timeNode.toggleFormat('superscript')
timeNode.toggleFormat('italic')
heading.append(timeNode)
const newLineNode = $createParagraphNode()
selection.insertNodes([heading, newLineNode])
editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, undefined)
return true
},
COMMAND_PRIORITY_EDITOR,
),
editor.registerCommand<string>(
INSERT_DATE_COMMAND,
() => {
const now = new Date()
const selection = $getSelection()
if (!$isRangeSelection(selection)) {
return false
}
const heading = $createHeadingNode('h1')
const dateString = $createTextNode(formatDateAndTimeForNote(now, false))
dateString.setFormat('italic')
heading.append(dateString)
const newLineNode = $createParagraphNode()
selection.insertNodes([heading, newLineNode])
editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, undefined)
return true
},
COMMAND_PRIORITY_EDITOR,
),
editor.registerCommand<string>(
INSERT_TIME_COMMAND,
() => {
const now = new Date()
const selection = $getSelection()
if (!$isRangeSelection(selection)) {
return false
}
const heading = $createHeadingNode('h2')
const dateString = $createTextNode(dateToHoursAndMinutesTimeString(now))
dateString.setFormat('italic')
heading.append(dateString)
const newLineNode = $createParagraphNode()
selection.insertNodes([heading, newLineNode])
return true
},
COMMAND_PRIORITY_EDITOR,
),
)
}, [editor])
return null
}