Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | 101x 139x 101x 15x 15x 101x 12x 4x 33x 4x 4x 4x 101x 101x 126x 2x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 8x 8x 8x 8x 8x 8x 8x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 14x 14x 14x 14x 38x 1x 3x 1x 4x 16x 34x 101x 1x 1x 2x 1x 4x 14x 2x 12x 2x 5x 2x 5x 101x 165x 144x 11x 11x 11x 11x 11x 11x 11x 11x 101x 101x 101x 101x 6x 6x 6x 107x 107x 107x 107x 107x 107x 107x 3x 3x 3x 107x | import { Box, IconButton, InputBase, Stack } from "@mui/material";
import { PlusIcon, TableIcon, TrashIcon, XIcon } from "@phosphor-icons/react";
import GiveButton from "@shared/Button/GiveButton";
import { GiveInput } from "@shared/GiveInputs/GiveInput";
import { useAppTheme } from "@theme/v2/Provider";
import {
AtomicBlockUtils,
ContentBlock,
ContentState,
EditorState,
Modifier,
SelectionState,
} from "draft-js";
import { useCallback, useMemo, useRef } from "react";
import IconWrapper from "./IconWrapper";
import { WrapperActionComponent } from "./components/Wrapper";
// Draft.js has no native table block, so legal documents (the Merchant
// Agreement fee schedule — Aaron's "preserve the tables" requirement) encode
// tables as atomic blocks carrying an IMMUTABLE "TABLE" entity:
// data = { columns: string[], rows: string[][] } — columns is the header.
// This module is the whole contract:
// - tableBlockRenderFunc: renders the entity — editable cells inside the
// editor, a static table everywhere read-only (viewer, published pages).
// - insertTable / TableInsertControl: the toolbar "insert table" action.
// Cell values are rendered as text nodes (never markup), so table content
// needs no sanitization on public surfaces.
export type TableData = { columns: string[]; rows: string[][] };
const isStringArray = (value: unknown): value is string[] =>
Array.isArray(value) && value.every((cell) => typeof cell === "string");
export const isTableData = (value: unknown): value is TableData => {
const data = value as TableData;
return (
!!data &&
typeof data === "object" &&
isStringArray(data.columns) &&
Array.isArray(data.rows) &&
data.rows.every(isStringArray)
);
};
export const insertTable = (
editorState: EditorState,
columnCount: number,
rowCount: number,
): EditorState => {
const columns = Array.from({ length: columnCount }, () => "");
const rows = Array.from({ length: rowCount }, () =>
Array.from({ length: columnCount }, () => ""),
);
const contentWithEntity = editorState
.getCurrentContent()
.createEntity("TABLE", "IMMUTABLE", { columns, rows });
const entityKey = contentWithEntity.getLastCreatedEntityKey();
return AtomicBlockUtils.insertAtomicBlock(
EditorState.set(editorState, { currentContent: contentWithEntity }),
entityKey,
" ",
);
};
/**
* Table edits must go through the HOST editor's own change pipeline
* (HFRichInput's handleEditorChange → controlled prop), NEVER through
* react-draft-wysiwyg-next's internal `onChange`: that onChange silently
* DROPS every update while `readOnly` is true or while the selection sits
* collapsed on an atomic block — which is exactly where the selection lands
* after inserting or clicking a table, freezing the whole editor ("cannot
* type anywhere"). The host provides these handlers when building its render
* func (buildTableBlockRenderFunc); without them the table renders static.
*/
export type TableHost = {
getEditorState: () => EditorState;
onChange: (editorState: EditorState) => void;
};
type TableBlockProps = {
block: ContentBlock;
contentState: ContentState;
blockProps?: {
host?: TableHost;
};
};
// Stops an event from reaching Draft's handlers on the editor root. Applied
// to every input-related event of the editable table wrapper (see the "event
// island" note at the render site).
const stopEvent = (e: { stopPropagation: () => void }) => e.stopPropagation();
const isolationHandlers = {
onBeforeInput: stopEvent,
onInput: stopEvent,
onKeyDown: stopEvent,
onKeyPress: stopEvent,
onKeyUp: stopEvent,
onSelect: stopEvent,
onFocus: stopEvent,
onBlur: stopEvent,
onCompositionStart: stopEvent,
onCompositionUpdate: stopEvent,
onCompositionEnd: stopEvent,
onCopy: stopEvent,
onCut: stopEvent,
onPaste: stopEvent,
onMouseDown: stopEvent,
onMouseUp: stopEvent,
onClick: stopEvent,
onDragStart: stopEvent,
onDrop: stopEvent,
} as const;
/**
* Header/body cell in edit mode. Uncontrolled on purpose: committing on every
* keystroke would push a new EditorState (and re-render the whole block) per
* character; instead the DOM keeps the value and it is committed once on blur.
*/
function EditableCell({
value,
onCommit,
header,
}: {
value: string;
onCommit: (value: string) => void;
header?: boolean;
}) {
return (
<InputBase
defaultValue={value}
onBlur={(e) => {
Eif (e.target.value !== value) onCommit(e.target.value);
}}
multiline
fullWidth
sx={{
fontSize: "14px",
fontWeight: header ? 600 : 400,
padding: 0,
"& textarea": { padding: 0 },
}}
/>
);
}
export function DraftTableBlock({
block,
contentState,
blockProps,
}: TableBlockProps) {
const { palette } = useAppTheme();
const host = blockProps?.host;
const entityKey = useMemo(() => {
try {
return block.getEntityAt(0);
} catch {
return null;
}
}, [block]);
const data = useMemo<TableData | null>(() => {
try {
Iif (!entityKey) return null;
const entityData = contentState.getEntity(entityKey).getData();
return isTableData(entityData) ? entityData : null;
} catch {
return null;
}
}, [entityKey, contentState]);
// Editable only when the host editor wired its own change pipeline in
// (see TableHost); read-only surfaces (DocumentViewer, published pages)
// use the plain render func with no host and get the static table.
const editable = !!host && !!entityKey;
const updateData = (next: TableData) => {
Iif (!host || !entityKey) return;
const editorState = host.getEditorState();
// NOT mergeEntityData: it mutates Draft's global entity store and returns
// the SAME ContentState instance, which Draft's shouldComponentUpdate
// reads as "nothing changed" — structural edits (add/remove row/column)
// would update the data but never re-render. Creating a fresh entity and
// re-applying it over the block's range changes the blockMap, yielding a
// genuinely new ContentState. The orphaned old entity is dropped by
// convertToRaw on save (it only exports referenced entities).
let content = editorState
.getCurrentContent()
.createEntity("TABLE", "IMMUTABLE", next);
const nextEntityKey = content.getLastCreatedEntityKey();
const blockRange = SelectionState.createEmpty(block.getKey()).merge({
anchorOffset: 0,
focusOffset: block.getLength(),
});
content = Modifier.applyEntity(content, blockRange, nextEntityKey);
host.onChange(EditorState.push(editorState, content, "apply-entity"));
};
const removeTable = () => {
Iif (!host) return;
const editorState = host.getEditorState();
let content = editorState.getCurrentContent();
const blockKey = block.getKey();
// Standard atomic-block removal: delete from the block's start into the
// start of the following block (merging them), then reset the merged
// block's type so it does not stay "atomic".
const blockAfter = content.getBlockAfter(blockKey);
const target = SelectionState.createEmpty(blockKey).merge({
anchorOffset: 0,
focusKey: blockAfter ? blockAfter.getKey() : blockKey,
focusOffset: blockAfter ? 0 : block.getLength(),
});
content = Modifier.removeRange(content, target, "backward");
content = Modifier.setBlockType(
content,
content.getSelectionAfter(),
"unstyled",
);
host.onChange(EditorState.push(editorState, content, "remove-range"));
};
if (!data) return null;
const { columns, rows } = data;
const border = `1px solid ${palette.border?.primary}`;
const cellSx = {
border,
padding: "8px 12px",
textAlign: "left" as const,
verticalAlign: "top" as const,
// Cells may carry multi-paragraph text joined with \n.
whiteSpace: "pre-line" as const,
};
const table = (
<Box
component="table"
sx={{
borderCollapse: "collapse",
width: "100%",
fontSize: "14px",
"& th": {
...cellSx,
fontWeight: 600,
backgroundColor: palette.surface?.secondary,
},
"& td": cellSx,
}}
>
<thead>
<tr>
{columns.map((column, columnIndex) => (
<th key={`${columnIndex}-${columns.length}`}>
{editable ? (
<Stack direction="row" alignItems="flex-start">
<EditableCell
header
value={column}
onCommit={(value) =>
updateData({
columns: columns.map((c, i) =>
i === columnIndex ? value : c,
),
rows,
})
}
/>
{columns.length > 1 && (
<IconButton
size="small"
aria-label="Remove column"
onClick={() =>
updateData({
columns: columns.filter((_, i) => i !== columnIndex),
rows: rows.map((row) =>
row.filter((_, i) => i !== columnIndex),
),
})
}
>
<XIcon size={12} />
</IconButton>
)}
</Stack>
) : (
column
)}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, rowIndex) => (
<tr key={`${rowIndex}-${rows.length}-${columns.length}`}>
{row.map((cell, cellIndex) => (
<td key={cellIndex}>
{editable ? (
<Stack direction="row" alignItems="flex-start">
<EditableCell
value={cell}
onCommit={(value) =>
updateData({
columns,
rows: rows.map((r, ri) =>
ri === rowIndex
? r.map((c, ci) => (ci === cellIndex ? value : c))
: r,
),
})
}
/>
{cellIndex === row.length - 1 && rows.length > 1 && (
<IconButton
size="small"
aria-label="Remove row"
onClick={() =>
updateData({
columns,
rows: rows.filter((_, i) => i !== rowIndex),
})
}
>
<XIcon size={12} />
</IconButton>
)}
</Stack>
) : (
cell
)}
</td>
))}
</tr>
))}
</tbody>
</Box>
);
if (!editable) {
// Wide tables scroll inside their own container instead of widening the
// document column.
return <Box sx={{ overflowX: "auto", margin: "12px 0" }}>{table}</Box>;
}
return (
// The editable table is a complete EVENT ISLAND inside the Draft editor:
// every input-related event is stopped from bubbling to Draft's handlers
// on the editor root. Draft inserts characters via onBeforeInput (not
// keydown!) and force-restores its own DOM selection from onFocus/onSelect
// — letting any of these through means each typed character is ALSO
// inserted at Draft's stale caret in the document, and the cell loses
// focus after the first keystroke.
<Box
contentEditable={false}
data-testid="draft-table-block"
{...isolationHandlers}
sx={{ overflowX: "auto", margin: "12px 0" }}
>
{table}
<Stack direction="row" gap="8px" marginTop="8px" alignItems="center">
<GiveButton
label="Row"
variant="ghost"
size="small"
startIcon={<PlusIcon size={14} />}
onClick={() =>
updateData({
columns,
rows: [...rows, columns.map(() => "")],
})
}
/>
<GiveButton
label="Column"
variant="ghost"
size="small"
startIcon={<PlusIcon size={14} />}
onClick={() =>
updateData({
columns: [...columns, ""],
rows: rows.map((row) => [...row, ""]),
})
}
/>
<Box flex={1} />
<GiveButton
label="Delete table"
variant="ghost"
size="small"
startIcon={<TrashIcon size={14} />}
onClick={removeTable}
/>
</Stack>
</Box>
);
}
// Claim only TABLE atomics; returning undefined for anything else lets
// react-draft-wysiwyg-next's own atomic renderer keep handling IMAGE /
// EMBEDDED_LINK blocks. The library calls this with (block, config,
// getEditorState). The host editor builds its instance with its own change
// pipeline (see TableHost — rdw's internal onChange must be bypassed);
// read-only surfaces use the plain `tableBlockRenderFunc` below and render
// the static table.
export const buildTableBlockRenderFunc =
(host?: TableHost) =>
(
block: ContentBlock,
config?: { getEditorState?: () => EditorState },
getEditorState?: () => EditorState,
) => {
if (block.getType() !== "atomic") return undefined;
const resolveEditorState =
host?.getEditorState ?? getEditorState ?? config?.getEditorState;
Iif (!resolveEditorState) return undefined;
try {
const entityKey = block.getEntityAt(0);
Iif (!entityKey) return undefined;
const entity = resolveEditorState()
.getCurrentContent()
.getEntity(entityKey);
Iif (entity.getType() !== "TABLE") return undefined;
} catch {
return undefined;
}
return {
component: DraftTableBlock,
editable: false,
props: { host },
};
};
export const tableBlockRenderFunc = buildTableBlockRenderFunc();
const MAX_COLUMNS = 10;
const MAX_ROWS = 50;
const clamp = (raw: string, max: number, fallback: number) => {
const n = parseInt(raw, 10);
Iif (Number.isNaN(n)) return fallback;
return Math.min(Math.max(n, 1), max);
};
/**
* Toolbar "insert table" action (opt-in via the "table" option — legal
* documents only). Size inputs are uncontrolled and read through refs so the
* popover content keeps a stable identity across re-renders — see LinkModal
* for why an unstable `customContent` remounts the popover and drops focus.
*/
export function TableInsertControl({
hostEditorState,
onInsert,
}: {
/**
* Deliberately NOT named `editorState` / `onChange`: react-draft-wysiwyg
* clones every toolbar custom button injecting its own `editorState` and
* `onChange` props, which would override ours — and rdw's onChange drops
* updates whenever the selection sits on an atomic block (see TableHost).
* The insert must go through the host's change pipeline instead.
*/
hostEditorState: EditorState;
onInsert: (editorState: EditorState) => void;
}) {
const columnsRef = useRef("3");
const rowsRef = useRef("3");
// Read through refs so `renderContent` keeps a stable identity across
// editor re-renders (see the LinkModal note on popover remounts).
const editorStateRef = useRef(hostEditorState);
editorStateRef.current = hostEditorState;
const onChangeRef = useRef(onInsert);
onChangeRef.current = onInsert;
const renderContent = useCallback(
({ onClose }: { onClose: () => void }) => (
<Box
gap="16px"
display="flex"
flexDirection="column"
style={{ padding: "16px" }}
>
<GiveInput
label="Columns"
type="number"
defaultValue={3}
inputProps={{ min: 1, max: MAX_COLUMNS }}
onChange={(e) => (columnsRef.current = e.target.value)}
/>
<GiveInput
label="Rows"
type="number"
defaultValue={3}
inputProps={{ min: 1, max: MAX_ROWS }}
onChange={(e) => (rowsRef.current = e.target.value)}
/>
<Box display="flex" alignItems="center" justifyContent="flex-end">
<GiveButton
onClick={onClose}
variant="ghost"
size="large"
label="Cancel"
/>
<GiveButton
variant="filled"
size="large"
label="Insert"
onClick={() => {
onChangeRef.current(
insertTable(
editorStateRef.current,
clamp(columnsRef.current, MAX_COLUMNS, 3),
clamp(rowsRef.current, MAX_ROWS, 3),
),
);
onClose();
}}
/>
</Box>
</Box>
),
[],
);
return (
<WrapperActionComponent
value={""}
menuWidth={240}
activeIndex={-1}
customContent={renderContent}
anchor={
// The Box carries the wrapper-injected open handlers (and a testid);
// IconWrapper does not forward unknown props.
<Box display="inline-flex" data-testid="insert-table-button">
<IconWrapper
onClick={() => {
// onClick gets overridden by the wrapper (opens the popover)
return;
}}
icon={TableIcon}
/>
</Box>
}
/>
);
}
|