forked from kuuote/denote
/
editor.tsx
296 lines (271 loc) · 8.37 KB
/
editor.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="dom" />
import React, {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "./deps/react.ts";
import { equal } from "./deps/std/asserts.ts";
import * as uuid from "./deps/std/uuidv1.ts";
import {
defaultPosition,
getCharDOM,
LineView,
positionFromElement,
} from "./line.tsx";
import {
defaultSelection,
defaultSelectionProps,
Selection,
} from "./selection.tsx";
import { getAbsoluteRect, Rect } from "./rect.ts";
import { Line, Position } from "./types.ts";
import { applyCommit, makeChanges, Revision } from "./commit.ts";
import { clamp, countIndent } from "./util.ts";
/* Editor logic */
export class Editor {
cursor = defaultPosition;
selection = defaultSelection;
// rendering callback
// must be set on view
callback = () => console.log("callback was not defined");
constructor(private revision: Revision) {}
getLines(): Line[] {
return this.revision.lines;
}
setCallback(callback: () => void) {
this.callback = callback;
}
setCursor(cursor: Position) {
this.cursor = cursor;
this.callback();
}
setSelection(selection: Selection) {
this.selection = selection;
this.callback();
}
/** 現在のカーソル位置に文字を流し込む */
input(str: string) {
const lines = this.getLines();
const currentCursorLine = lines.at(this.cursor.line);
if (!currentCursorLine) return;
const cursorLine = currentCursorLine;
const indentStr = cursorLine.text.slice(0, countIndent(cursorLine.text));
const a = cursorLine.text.slice(0, this.cursor.column);
const b = cursorLine.text.slice(this.cursor.column, cursorLine.text.length);
const newLines = (a +
str.split("\n").map((line, index) =>
index === 0 ? line : `${indentStr}${line}`
).join("\n") +
b).split("\n");
this.revision = applyCommit(this.revision, {
id: String(uuid.generate()),
parentID: this.revision.id,
changes: [
...makeChanges(lines, this.cursor.line, this.cursor.line, newLines),
],
});
this.cursor = {
line: this.cursor.line + newLines.length - 1,
column: newLines.at(-1)?.length ?? 0 - b.length,
};
this.callback();
}
}
export function EditorView(props: { editor: Editor }): JSX.Element {
const { editor } = props;
const { cursor, selection } = editor;
// いい方法があったら差し替える
const [, reRender] = useState(1);
useEffect(() => {
editor.setCallback(() => reRender(Math.random()));
}, []);
const lines = props.editor.getLines();
const [cursorView, setCursorView] = useState({
left: 0,
top: 0,
height: 0,
});
// 選択によってカーソルが移動するため選択範囲の始点を格納しておく
const selectionStart = useRef(defaultPosition);
const [selectionView, setSelectionView] = useState(defaultSelectionProps);
/** クリックした位置にカーソルを動かす
*
* 同時に選択範囲を消す
*/
const handleClick = useCallback((e: React.MouseEvent<Element>) => {
const pos = positionFromElement(e.target as Element, e.clientX, e.clientY);
editor.setCursor(pos);
// 選択範囲の保持とリセット
selectionStart.current = pos;
setSelectionView(defaultSelectionProps);
}, []);
// カーソルの描画
useLayoutEffect(() => {
const len = lines[cursor.line]?.text.length ?? -1;
// カーソル行が末尾にある際は該当する DOM が無いので len - 1 で丸める
// 単純に len - 1 するだけでは 空行の時に -1 になってしまうため 0 で丸める
const col = clamp(0, cursor.column, len - 1);
const char = getCharDOM(cursor.line, col);
if (char == null) {
console.log("cursorView: char == null");
setCursorView({
left: 0,
top: 0,
height: 0,
});
return;
}
const rect = getAbsoluteRect(char);
// 末尾の時は要素の幅を足すことで右端にカーソルが置かれているように見せる
const absoluteX = rect.left + (cursor.column === len ? rect.width : 0);
const absoluteY = rect.top;
setCursorView({
left: absoluteX,
top: absoluteY,
height: rect.height,
});
}, [cursor]);
/** カーソル移動で選択範囲を変更する */
const handleMouseMove = useCallback((e: React.MouseEvent<Element>) => {
if (e.buttons !== 1) {
return;
}
const pos = positionFromElement(
e.target as Element,
e.clientX,
e.clientY,
);
if (pos.line === -1) return;
const selection = [pos, selectionStart.current].sort((a, b) => {
if (a.line !== b.line) {
return a.line - b.line;
}
return a.column - b.column;
});
if (equal(selection[0], selection[1])) {
editor.setSelection(defaultSelection);
} else {
editor.setSelection({
start: selection[0],
end: selection[1],
});
}
editor.setCursor(pos);
}, []);
// 選択範囲の描画
useLayoutEffect(() => {
const startlen = lines[selection.start.line]?.text.length ?? -1;
const startcol = clamp(0, selection.start.column, startlen - 1);
const start = getCharDOM(selection.start.line, startcol);
const endlen = lines[selection.end.line]?.text.length ?? -1;
const endcol = clamp(0, selection.end.column, endlen - 1);
const end = getCharDOM(selection.end.line, endcol);
if (!start || !end) {
setSelectionView(defaultSelectionProps);
return;
}
const startRect = getAbsoluteRect(start);
const endRect = getAbsoluteRect(end);
// 要素のサイズ次第で微細な差があるため吸収
// これ、startRectとendRectが衝突してるみたいな条件でもいいかもしれん
// 単純な衝突判定じゃだめなので中間値を取るか
if (endRect.top < startRect.top + startRect.height / 2) {
const view = {
...startRect,
width: endRect.left + (selection.end.column === endlen
// 末尾にいる時は前の要素を参照しているためwidth分足す
? endRect.width
: 0) -
startRect.left,
};
setSelectionView({
...defaultSelectionProps,
center: view,
});
} else {
const lineView = document.getElementsByClassName("line").item(0)!;
const lineRect = getAbsoluteRect(lineView);
const topLeft = startRect.left +
(selection.start.column === startlen ? startRect.width : 0);
const top = {
...startRect,
left: topLeft,
width: lineRect.left + lineRect.width - (topLeft),
};
const center = {
...lineRect,
top: startRect.top + startRect.height,
height: endRect.top - (startRect.top + startRect.height),
};
const bottom = {
...endRect,
left: lineRect.left,
width: endRect.left - lineRect.left +
(selection.end.column === endlen ? endRect.width : 0),
};
setSelectionView({
top,
center,
bottom,
});
}
}, [selection]);
/* handling textarea */
const onChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
editor.input(e.currentTarget.value);
e.currentTarget.value = "";
}, []);
useLayoutEffect(() => {
const textarea = document.getElementsByTagName("textarea")[0];
if (textarea && cursorView.left > 0) {
setTimeout(() => textarea.focus(), 0);
}
}, [cursorView]);
return (
<span
className="editor"
onMouseDown={handleClick}
onMouseMove={handleMouseMove}
>
<span
className="cursor"
style={{
left: cursorView.left,
top: cursorView.top,
height: `${cursorView.height}px`,
}}
>
</span>
<Selection {...selectionView} />
<textarea
className="input"
style={{
position: "absolute",
left: cursorView.left,
top: cursorView.top,
width: 1,
height: cursorView.height,
lineHeight: cursorView.height,
opacity: 0,
}}
onChange={onChange}
spellCheck="false"
wrap="off"
>
</textarea>
<span>
{lines.map((line, index) => (
<LineView
key={line.id}
line={line}
lnum={index}
/>
))}
</span>
</span>
);
}