import {
isTableContent,
TableContent,
} from "@prismicio/types-internal/lib/content"
import {
type Table,
TableCell,
} from "@prismicio/types-internal/lib/customtypes"
import {
DiffChange,
DiffOperation,
} from "@prismicio/types-internal/lib/customtypes/diff"
import { v4 as uuid } from "uuid"
import type { NestableMock, Patch } from "../../Mock"
import type { MockConfig } from "../../MockConfig"
import { RichTextMock } from "./RichText"
export type TableMockConfig = MockConfig
export const TableMock: NestableMock = {
generate(_def: Table, config?: TableMockConfig): TableContent {
/**
* We decided to keep a small table with a fixed size, and some opinionated
* content for the cells, so it looks good in the SM simulator.
*/
const columns = 2
return {
__TYPE__: "TableContent",
content: config?.value ?? [
{
key: uuid(),
type: "tableRow",
content: mockTableCells({ length: columns, type: "tableHeader" }),
},
{
key: uuid(),
type: "tableRow",
content: mockTableCells({ length: columns, type: "tableCell" }),
},
],
}
},
applyPatch(data: Patch):
| {
result: TableContent | undefined
}
| undefined {
if (data.diff.op === DiffOperation.Removed) return { result: undefined }
if (data.diff.value.type === "Table") {
const patched = this.patch(
data.diff,
isTableContent(data.content) ? data.content : undefined,
data.config?.type === "Table" ? data.config : undefined,
)
return { result: patched }
}
return
},
patch(
diff: DiffChange,
_content: TableContent,
config?: TableMockConfig,
): TableContent | undefined {
switch (diff.op) {
case DiffOperation.Removed:
return
case DiffOperation.Updated:
case DiffOperation.Added:
return this.generate(diff.value, config)
}
},
}
const pattern = {
tableHeader: "TABLE_HEADER",
tableCell: "TABLE_CELL",
} as const
const mockTableCells = ({
length,
type,
}: {
length: number
type: "tableHeader" | "tableCell"
}) =>
Array.from({ length }, () => ({
key: uuid(),
type,
content: RichTextMock.generate(TableCell, {
type: "StructuredText",
pattern: pattern[type],
}),
}))