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
|
import {createElement, useLayoutEffect, useRef, useState} from 'react';
import './entry.css';
function TextField({ item, onEnter, onSelect, onRemove, ref }) {
const onKeyDown = e => {
if (e.keyCode === 38) { // up
onSelect(-1);
e.preventDefault();
return;
} else if (e.keyCode === 40) { // down
onSelect(+1);
e.preventDefault();
return;
} else if (e.keyCode === 8 && e.target.innerText.length === 0) { // backspace
onRemove();
e.preventDefault();
return;
}
if (e.keyCode !== 13) {
return;
} else if (e.shiftKey) {
return;
}
e.preventDefault();
onEnter(e.ctrlKey ? 'todo' : 'plain');
};
useLayoutEffect(() => {
if (ref.current == null) {
return;
}
ref.current.innerText = item.text;
}, [item.text]);
return <div ref={ref} className='text' contentEditable="true" onKeyDown={onKeyDown} onClick={() => onSelect(0)}></div>;
}
function Plain({ item, onEnter, onSelect, onRemove, ref }) {
return <TextField item={item} onEnter={onEnter} onSelect={onSelect} onRemove={onRemove} ref={ref} />;
}
function Todo({ item, onEnter, onSelect, onRemove, ref }) {
return <>
<input type="checkbox" />
<TextField item={item} onEnter={onEnter} onSelect={onSelect} onRemove={onRemove} ref={ref} />
</>;
}
export default function Entry({ item, onEnter, onSelect, onRemove, isFocused }) {
const ref = useRef(null);
useLayoutEffect(() => {
if (isFocused && ref.current != null && document.activeElement !== ref.current) {
ref.current.focus();
document.execCommand('selectAll', false, null);
document.getSelection().collapseToEnd();
}
}, [isFocused]);
const child = createElement(item.type === 'plain' ? Plain : Todo, {
ref,
item,
onEnter,
onSelect,
onRemove: () => onRemove(true),
});
return <div className={`entry ${isFocused ? 'focus' : ''}`}>
<button onClick={() => onRemove(false)}>X</button>
{child}
</div>
}
|