-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathdropdowns.tsx
93 lines (76 loc) · 2.29 KB
/
dropdowns.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
import React from 'react';
import type { ChangeEvent, FC, HTMLAttributes } from 'react';
import { EditorState, useEditorState } from '../editor/EditorContext';
export const BtnStyles = createDropdown('Styles', [
['Normal', 'formatBlock', 'DIV'],
['𝗛𝗲𝗮𝗱𝗲𝗿 𝟭', 'formatBlock', 'H1'],
['Header 2', 'formatBlock', 'H2'],
['𝙲𝚘𝚍𝚎', 'formatBlock', 'PRE'],
]);
export function createDropdown(
title: string,
items: DropDownItem[],
): FC<DropDownFactoryProps> {
DropdownFactory.displayName = title;
return DropdownFactory;
function DropdownFactory(props: DropDownFactoryProps) {
const editorState = useEditorState();
const { $el, $selection, htmlMode } = editorState;
if (htmlMode) {
return null;
}
const activeIndex = items.findIndex(
(item) => item[1] === 'formatBlock' && $selection?.nodeName === item[2],
);
return (
<Dropdown
{...props}
items={items}
onChange={onChange}
selected={activeIndex}
tabIndex={-1}
title={title}
/>
);
function onChange(e: ChangeEvent<HTMLSelectElement>) {
const target = e.target;
const selectedValue = target.value;
const selectedIndex = parseInt(selectedValue, 10);
const [, command, commandArgument] = items[selectedIndex] || [];
e.preventDefault();
if (document.activeElement !== $el) {
$el?.focus();
}
if (typeof command === 'function') {
command(editorState);
} else if (command) {
document.execCommand(command, false, commandArgument);
}
setTimeout(() => (target.value = selectedValue), 10);
}
}
}
export function Dropdown({ items, selected, ...inputProps }: DropdownProps) {
return (
<select {...inputProps} value={selected} className="rsw-dd">
<option hidden>{inputProps.title}</option>
{items.map((item, index) => (
<option key={item[2]} value={index}>
{item[0]}
</option>
))}
</select>
);
}
export type DropDownItem = [
string,
string | ((editorState: EditorState) => void),
string,
];
export interface DropDownFactoryProps
extends HTMLAttributes<HTMLSelectElement> {
selected?: number;
}
export interface DropdownProps extends DropDownFactoryProps {
items: DropDownItem[];
}