add createTable

This commit is contained in:
Hans Pagel
2021-01-22 22:37:43 +01:00
parent d3fcbc91c3
commit d1bbc8f24d
5 changed files with 81 additions and 25 deletions

View File

@@ -0,0 +1,13 @@
import {
NodeType, Fragment,
Node as ProsemirrorNode,
Schema,
} from 'prosemirror-model'
export function createCell(cellType: NodeType, cellContent?: Fragment<Schema> | ProsemirrorNode<Schema> | Array<ProsemirrorNode<Schema>>) {
if (cellContent) {
return cellType.createChecked(null, cellContent)
}
return cellType.createAndFill()
}

View File

@@ -0,0 +1,31 @@
import {
Schema,
Fragment,
Node as ProsemirrorNode,
} from 'prosemirror-model'
import { createCell } from './createCell'
import { getTableNodeTypes } from './getTableNodeTypes'
export function createTable(schema: Schema, rowsCount: 3, colsCount: 3, withHeaderRow: true, cellContent?: Fragment<Schema> | ProsemirrorNode<Schema> | Array<ProsemirrorNode<Schema>>) {
const types = getTableNodeTypes(schema)
const headerCells = []
const cells = []
for (let index = 0; index < colsCount; index += 1) {
cells.push(createCell(types.cell, cellContent))
if (withHeaderRow) {
headerCells.push(createCell(types.header_cell, cellContent))
}
}
const rows = []
for (let index = 0; index < rowsCount; index += 1) {
rows.push(types.row.createChecked(null, withHeaderRow && index === 0 ? headerCells : cells))
}
return types.table.createChecked(null, rows)
}

View File

@@ -0,0 +1,22 @@
import { Schema } from 'prosemirror-model'
export function getTableNodeTypes(schema: Schema) {
if (schema.cached.tableNodeTypes) {
return schema.cached.tableNodeTypes
}
const roles = {}
Object.keys(schema.nodes).forEach(type => {
const nodeType = schema.nodes[type]
if (nodeType.spec.tableRole) {
// @ts-ignore
roles[nodeType.spec.tableRole] = nodeType
}
})
schema.cached.tableNodeTypes = roles
return roles
}