forked from ant-design/md-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.tsx
446 lines (431 loc) · 13.3 KB
/
table.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import { Popover, Typography } from 'antd';
import classNames from 'classnames';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Editor, Node, NodeEntry, Path } from 'slate';
import { ReactEditor } from 'slate-react';
import { RenderElementProps } from 'slate-react/dist/components/editable';
import stringWidth from 'string-width';
import { TableCellNode, TableNode } from '../../el';
import { useSelStatus } from '../../hooks/editor';
import { useEditorStore } from '../store';
import { DragHandle } from '../tools/DragHandle';
import { TableAttr } from '../tools/TableAttr';
import { ColSideDiv, IntersectionPointDiv, RowSideDiv } from './renderSideDiv';
import './table.css';
const numberValidationRegex = /^[+-]?(\d|([1-9]\d+))(\.\d+)?$/;
/**
* TableCell 组件用于渲染表格单元格,根据元素的 title 属性决定渲染 <th> 或 <td>。
*
* @param {RenderElementProps} props - 传递给组件的属性。
* @returns {JSX.Element} 渲染的表格单元格。
*
* @example
* ```tsx
* <TableCell element={element} attributes={attributes} children={children} />
* ```
*
* @remarks
* - 使用 `useEditorStore` 获取编辑器的 store。
* - 使用 `useSelStatus` 获取选择状态。
* - 使用 `useCallback` 创建上下文菜单的回调函数。
* - 使用 `React.useMemo` 优化渲染性能。
*
* @internal
* - `minWidth` 根据元素内容的字符串宽度计算,最小值为 20,最大值为 200。
* - `textWrap` 设置为 'wrap',`maxWidth` 设置为 '200px'。
* - `onContextMenu` 事件处理函数根据元素是否有 title 属性传递不同的参数。
*/
export function TableCell(props: RenderElementProps) {
const { store, readonly } = useEditorStore();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_] = useSelStatus(props.element);
return React.useMemo(() => {
const domWidth = stringWidth(Node.string(props.element)) * 8 + 20;
const minWidth = Math.min(domWidth, 200);
const text = Node.string(props.element);
return props.element.title ? (
<th {...props.attributes} data-be={'th'}>
<div
style={{
minWidth: minWidth,
textWrap: 'wrap',
maxWidth: '200px',
}}
>
{props.children}
</div>
</th>
) : (
<td {...props.attributes} data-be={'td'} className={classNames('group')}>
{readonly && domWidth > 200 ? (
<Popover
title={
<div
style={{
maxWidth: 400,
maxHeight: 400,
fontWeight: 400,
fontSize: '1em',
overflow: 'auto',
}}
>
<Typography.Text copyable={{ text: text }}>
{text}
</Typography.Text>
</div>
}
>
<div
style={{
minWidth: minWidth,
maxWidth: 200,
overflow: 'hidden',
textOverflow: 'ellipsis',
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 2,
maxHeight: 40,
}}
>
{text}
</div>
</Popover>
) : (
<div
style={{
minWidth: minWidth,
textWrap: 'wrap',
maxWidth: '200px',
display: 'flex',
justifyContent: numberValidationRegex.test(
text?.replaceAll(',', ''),
)
? 'end'
: 'start',
}}
>
{props.children}
</div>
)}
</td>
);
}, [props.element, props.element.children, store.refreshHighlight]);
}
/**
* 表格组件,使用 `observer` 包装以响应状态变化。
*
* @param {RenderElementProps} props - 渲染元素的属性。
*
* @returns {JSX.Element} 表格组件的 JSX 元素。
*
* @component
*
* @example
* ```tsx
* <Table {...props} />
* ```
*
* @remarks
* 该组件使用了多个 React 钩子函数,包括 `useState`、`useEffect`、`useCallback` 和 `useRef`。
*
* - `useState` 用于管理组件的状态。
* - `useEffect` 用于处理组件挂载和卸载时的副作用。
* - `useCallback` 用于优化回调函数的性能。
* - `useRef` 用于获取 DOM 元素的引用。
*
* 组件还使用了 `IntersectionObserver` 来检测表格是否溢出,并相应地添加或移除 CSS 类。
*
* @see https://reactjs.org/docs/hooks-intro.html React Hooks
*/
export const Table = observer((props: RenderElementProps) => {
const { store } = useEditorStore();
const [tableAttrVisible, setTableAttrVisible] = useState(false);
const [isShowBar, setIsShowBar] = useState(false);
const [state, setState] = useState({
top: 0,
left: 0,
width: 0,
scaleOpen: false,
enterScale: false,
align: '' as string | undefined,
rows: 0,
cols: 0,
selectCols: 0,
selectRows: 0,
});
const [selected, path] = useSelStatus(props.element);
const tableRef = React.useRef<NodeEntry<TableNode>>();
const overflowShadowContainerRef = React.useRef<HTMLTableElement>(null);
const tableCellRef = useRef<NodeEntry<TableCellNode>>();
useEffect(() => {
if (store.floatBarOpen) {
setTableAttrVisible(false);
}
}, [store.floatBarOpen]);
const isSel = useMemo(() => {
if (selected) return true;
if (!store.selectTablePath?.length) return false;
return store.selectTablePath.join('') === path.join('');
}, [store.editor, selected, store.selectTablePath, props.element]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (!tableRef.current) return;
if (tableAttrVisible && tableRef.current) {
if (!store.editor.hasPath(tableRef.current[1])) return;
try {
const dom = ReactEditor.toDOMNode(
store.editor,
Node.get(store.editor, tableRef.current[1]),
) as HTMLElement;
if (dom && !dom.contains(event.target as Node)) {
setTableAttrVisible(false);
}
} catch (error) {}
}
const isInsideScrollbar = () => {
if (!overflowShadowContainerRef.current) return false;
return overflowShadowContainerRef.current.contains(
event.target as Node,
);
};
if (isInsideScrollbar()) {
return;
}
setIsShowBar(false);
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [tableAttrVisible, tableRef, store.editor, isShowBar]);
const resize = useCallback(() => {
const table = tableRef.current;
if (!table) return;
setTimeout(() => {
try {
const dom = ReactEditor.toDOMNode(
store.editor,
table[0],
) as HTMLElement;
if (dom) {
setState((prev) => ({
...prev,
rows: table[0].children.length,
cols: table[0].children[0].children.length,
}));
}
} catch (e) {}
}, 16);
}, [setState, store.editor]);
const handleClickTable = useCallback(() => {
if (store.floatBarOpen) return;
const el = store.tableCellNode;
if (el) {
tableCellRef.current = el;
try {
const dom = ReactEditor.toDOMNode(store.editor, el[0]) as HTMLElement;
const overflowShadowContainer = overflowShadowContainerRef.current!;
const tableTop = overflowShadowContainer.offsetTop;
let left = dom.getBoundingClientRect().left;
setState((prev) => ({
...prev,
top: tableTop - 48 + 3,
left,
}));
setTableAttrVisible(true);
} catch (error) {
console.log(error);
}
setState((prev) => ({
...prev,
align: el[0].align,
}));
const table = Editor.node(store.editor, Path.parent(Path.parent(el[1])));
if (table && table[0] !== tableRef.current?.[0]) {
tableRef.current = table;
resize();
}
}
setIsShowBar(true);
}, [store.tableCellNode, store.editor, setState, isShowBar]);
const tableTargetRef = useRef<HTMLTableElement>(null);
useEffect(() => {
if (!tableTargetRef.current) {
return;
}
if (typeof IntersectionObserver === 'undefined') {
return;
}
const observerRoot = (tableTargetRef as any).current?.parentNode;
const observerTarget = (tableTargetRef as any).current;
const overflowShadowContainer = overflowShadowContainerRef.current!;
overflowShadowContainer.classList.add('overflow-shadow-container');
overflowShadowContainer.classList.add('card-table-wrap');
const options = {
root: observerRoot,
threshold: 1,
};
new IntersectionObserver(([entry]) => {
if (entry.intersectionRatio !== 1) {
overflowShadowContainer.classList.add(
'is-overflowing',
'is-scrolled-left',
);
} else {
overflowShadowContainer.classList.remove('is-overflowing');
}
}, options).observe(observerTarget);
let handleScrollX = (e: any) => {
if (e.target.scrollLeft < 1) {
overflowShadowContainer.classList.add('is-scrolled-left');
} else {
overflowShadowContainer.classList.remove('is-scrolled-left');
}
if (
Math.abs(
e.target.scrollLeft +
e.target.offsetWidth -
observerTarget.offsetWidth,
) <= 1
) {
overflowShadowContainer.classList.add('is-scrolled-right');
} else {
overflowShadowContainer.classList.remove('is-scrolled-right');
}
};
observerRoot.addEventListener('scroll', handleScrollX);
return () => {
observerRoot.removeEventListener('scroll', handleScrollX);
};
}, []);
const getTableNode = () => {
return props.element;
};
const [selCells, setSelCells] = useState<NodeEntry<TableCellNode>[]>([]);
useEffect(() => {
if (!store.editor) return;
const cachedSelCells = store.CACHED_SEL_CELLS?.get(store.editor);
cachedSelCells?.forEach((cell) => {
const [cellNode] = cell;
const cellDom = ReactEditor.toDOMNode(store.editor, cellNode);
if (cellDom) {
cellDom.classList.remove('selected-cell-td');
}
});
selCells?.forEach((cell) => {
const [cellNode] = cell;
const cellDom = ReactEditor.toDOMNode(store.editor, cellNode);
if (cellDom) {
cellDom.classList.add('selected-cell-td');
}
});
store.CACHED_SEL_CELLS.set(store.editor, selCells);
}, [JSON.stringify(selCells)]);
return useMemo(() => {
return (
<div
{...props.attributes}
data-be={'table'}
onDragStart={store.dragStart}
ref={overflowShadowContainerRef}
style={{
display: 'flex',
gap: 1,
maxWidth: '100%',
minWidth: 0,
marginBottom: 12,
}}
>
<div className="ant-md-editor-drag-el">
{tableAttrVisible && (
<TableAttr
state={state}
setState={setState}
tableRef={tableRef}
tableCellRef={tableCellRef}
/>
)}
<DragHandle />
</div>
<div
className={`ant-md-editor-table ant-md-editor-content-table ${
isShowBar ? 'show-bar' : ''
}`}
onMouseUp={handleClickTable}
onClick={() => {
runInAction(() => {
if (isSel) {
store.selectTablePath = [];
return;
}
store.selectTablePath = path;
});
}}
style={{
width: '100%',
maxWidth: '100%',
overflow: 'auto',
flex: 1,
minWidth: 0,
marginLeft: 20,
marginTop: 4,
marginRight: 6,
}}
>
<div
style={{
visibility: isShowBar ? 'visible' : 'hidden',
overflow: 'hidden',
}}
data-slate-editor="false"
>
<IntersectionPointDiv
getTableNode={getTableNode}
selCells={selCells}
setSelCells={setSelCells}
/>
<RowSideDiv
tableRef={tableTargetRef}
getTableNode={getTableNode}
selCells={selCells}
setSelCells={setSelCells}
/>
<ColSideDiv
tableRef={tableTargetRef}
getTableNode={getTableNode}
selCells={selCells}
setSelCells={setSelCells}
/>
</div>
<table
className="md-editor-table"
style={{
borderCollapse: 'separate',
borderSpacing: 0,
}}
ref={tableTargetRef}
>
<tbody data-slate-node="element">{props.children}</tbody>
</table>
</div>
</div>
);
}, [
props.element.children,
state,
setState,
store.dragStart,
store.editor?.children?.length === 1,
handleClickTable,
tableAttrVisible,
isSel,
]);
});