refactor(editor): enable the noUncheckedIndexedAccess rule for the block-database package (#9691)

close: BS-2269
This commit is contained in:
zzj3720
2025-01-14 14:35:46 +00:00
parent aa2a8fbf9b
commit ff295f383f
24 changed files with 324 additions and 344 deletions
@@ -10,11 +10,11 @@ import {
type InlineHtmlAST,
TextUtils,
} from '@blocksuite/affine-shared/adapters';
import type { DeltaInsert } from '@blocksuite/inline';
import { type BlockSnapshot, nanoid } from '@blocksuite/store';
import { format } from 'date-fns/format';
import { nanoid } from '@blocksuite/store';
import type { Element } from 'hast';
import { processTable } from './utils';
const DATABASE_NODE_TYPES = new Set(['table', 'thead', 'tbody', 'th', 'tr']);
export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
@@ -53,8 +53,12 @@ export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
const rowId = nanoid();
cells[rowId] = Object.create(null);
(row as Element).children.forEach((cell, index) => {
cells[rowId][viewsColumns[index].id] = {
columnId: viewsColumns[index].id,
const column = viewsColumns[index];
if (!column) {
return;
}
cells[rowId][column.id] = {
columnId: column.id,
value: TextUtils.createText(
(cell as Element).children
.map(child => ('value' in child ? child.value : ''))
@@ -65,14 +69,18 @@ export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
});
// Build database columns from table header row
const columns = tableHeaderRow.children.map((_child, index) => {
const columns = tableHeaderRow.children.flatMap((_child, index) => {
const column = viewsColumns[index];
if (!column) {
return [];
}
return {
type: index === 0 ? 'title' : 'rich-text',
name: (_child as Element).children
.map(child => ('value' in child ? child.value : ''))
.join(''),
data: {},
id: viewsColumns[index].id,
id: column.id,
};
});
@@ -117,6 +125,10 @@ export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
// The first child of each table body row is the database title cell
if (o.node.tagName === 'tr') {
const { deltaConverter } = context;
const firstChild = o.node.children[0];
if (!firstChild) {
return;
}
walkerContext
.openNode({
type: 'block',
@@ -130,7 +142,7 @@ export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
props: {
text: {
'$blocksuite:internal:text$': true,
delta: deltaConverter.astToDelta(o.node.children[0]),
delta: deltaConverter.astToDelta(firstChild),
},
type: 'text',
},
@@ -156,7 +168,7 @@ export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
const columns = o.node.props.columns as Array<Column>;
const children = o.node.children;
const cells = o.node.props.cells as SerializedCells;
const table = processTable(columns, children, cells);
const createAstTableCell = (
children: InlineHtmlAST[]
): InlineHtmlAST => ({
@@ -183,94 +195,40 @@ export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
});
const { deltaConverter } = context;
const htmlAstRows = Array.prototype.map.call(
children,
(v: BlockSnapshot) => {
const rowCells = Array.prototype.map.call(columns, col => {
const cell = cells[v.id]?.[col.id];
if (!cell && col.type !== 'title') {
return createAstTableCell([{ type: 'text', value: '' }]);
}
switch (col.type) {
case 'rich-text':
return createAstTableCell(
deltaConverter.deltaToAST(
(cell.value as { delta: DeltaInsert[] }).delta
)
);
case 'title':
return createAstTableCell(
deltaConverter.deltaToAST(
(v.props.text as { delta: DeltaInsert[] }).delta
)
);
case 'date':
return createAstTableCell([
{
type: 'text',
value: format(new Date(cell.value as number), 'yyyy-MM-dd'),
},
]);
case 'select': {
const value =
(col.data.options.find(
(opt: Record<string, string>) => opt.id === cell.value
)?.value as string) ?? '';
return createAstTableCell([{ type: 'text', value }]);
}
case 'multi-select': {
const value = Array.prototype.map
.call(
cell.value,
val =>
col.data.options.find(
(opt: Record<string, string>) => val === opt.id
).value ?? ''
)
.filter(Boolean)
.join(',');
return createAstTableCell([{ type: 'text', value }]);
}
case 'checkbox': {
return createAstTableCell([
{ type: 'text', value: String(cell.value) },
]);
}
// eslint-disable-next-line sonarjs/no-duplicated-branches
default:
return createAstTableCell([
{ type: 'text', value: String(cell.value) },
]);
}
}) as InlineHtmlAST[];
return createAstTableRow(rowCells);
}
) as Element[];
// Handle first row (header).
const headerRow = createAstTableRow(
Array.prototype.map.call(columns, v =>
createAstTableHeaderCell([
{
type: 'text',
value: v.name ?? '',
},
])
) as Element[]
);
const tableHeaderAst: Element = {
type: 'element',
tagName: 'thead',
properties: Object.create(null),
children: [headerRow],
children: [
createAstTableRow(
table.headers.map(v =>
createAstTableHeaderCell([
{
type: 'text',
value: v.name ?? '',
},
])
)
),
],
};
const tableBodyAst: Element = {
type: 'element',
tagName: 'tbody',
properties: Object.create(null),
children: [...htmlAstRows],
children: table.rows.map(v => {
return createAstTableRow(
v.cells.map(cell => {
return createAstTableCell(
typeof cell.value === 'string'
? [{ type: 'text', value: cell.value }]
: deltaConverter.deltaToAST(cell.value.delta)
);
})
);
}),
};
walkerContext
@@ -9,11 +9,11 @@ import {
type MarkdownAST,
TextUtils,
} from '@blocksuite/affine-shared/adapters';
import type { DeltaInsert } from '@blocksuite/inline';
import { type BlockSnapshot, nanoid } from '@blocksuite/store';
import { format } from 'date-fns/format';
import { nanoid } from '@blocksuite/store';
import type { TableRow } from 'mdast';
import { processTable } from './utils';
const DATABASE_NODE_TYPES = new Set(['table', 'tableRow']);
const isDatabaseNode = (node: MarkdownAST) =>
@@ -28,7 +28,7 @@ export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
enter: (o, context) => {
const { walkerContext } = context;
if (o.node.type === 'table') {
const viewsColumns = o.node.children[0].children.map(() => {
const viewsColumns = o.node.children[0]?.children.map(() => {
return {
id: nanoid(),
hide: false,
@@ -40,8 +40,12 @@ export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
const rowId = nanoid();
cells[rowId] = Object.create(null);
row.children.slice(1).forEach((cell, index) => {
cells[rowId][viewsColumns[index + 1].id] = {
columnId: viewsColumns[index + 1].id,
const column = viewsColumns?.[index + 1];
if (!column) {
return;
}
cells[rowId][column.id] = {
columnId: column.id,
value: TextUtils.createText(
cell.children
.map(child => ('value' in child ? child.value : ''))
@@ -50,14 +54,14 @@ export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
};
});
});
const columns = o.node.children[0].children.map((_child, index) => {
const columns = o.node.children[0]?.children.map((_child, index) => {
return {
type: index === 0 ? 'title' : 'rich-text',
name: _child.children
.map(child => ('value' in child ? child.value : ''))
.join(''),
data: {},
id: viewsColumns[index].id,
id: viewsColumns?.[index]?.id,
};
});
walkerContext.openNode(
@@ -78,7 +82,7 @@ export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
conditions: [],
},
header: {
titleColumn: viewsColumns[0]?.id,
titleColumn: viewsColumns?.[0]?.id,
iconColumn: 'type',
},
},
@@ -103,6 +107,10 @@ export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
if (o.node.type === 'tableRow') {
const { deltaConverter } = context;
const firstChild = o.node.children[0];
if (!firstChild) {
return;
}
walkerContext
.openNode({
type: 'block',
@@ -116,7 +124,7 @@ export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
props: {
text: {
'$blocksuite:internal:text$': true,
delta: deltaConverter.astToDelta(o.node.children[0]),
delta: deltaConverter.astToDelta(firstChild),
},
type: 'text',
},
@@ -140,101 +148,25 @@ export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
const columns = o.node.props.columns as Array<Column>;
const children = o.node.children;
const cells = o.node.props.cells as SerializedCells;
const createAstCell = (children: MarkdownAST[]) => ({
type: 'tableCell',
children,
const table = processTable(columns, children, cells);
rows.push({
type: 'tableRow',
children: table.headers.map(v => ({
type: 'tableCell',
children: [{ type: 'text', value: v.name }],
})),
});
const mdAstCells = Array.prototype.map.call(
children,
(v: BlockSnapshot) =>
Array.prototype.map.call(columns, col => {
const cell = cells[v.id]?.[col.id];
if (!cell && col.type !== 'title') {
return createAstCell([{ type: 'text', value: '' }]);
}
switch (col.type) {
case 'link':
case 'progress':
case 'number':
return createAstCell([
{
type: 'text',
value: cell.value as string,
},
]);
case 'rich-text':
return createAstCell(
deltaConverter.deltaToAST(
(cell.value as { delta: DeltaInsert[] }).delta
)
);
case 'title':
return createAstCell(
deltaConverter.deltaToAST(
(v.props.text as { delta: DeltaInsert[] }).delta
)
);
case 'date':
return createAstCell([
{
type: 'text',
value: format(
new Date(cell.value as number),
'yyyy-MM-dd'
),
},
]);
case 'select': {
const value = col.data.options.find(
(opt: Record<string, string>) => opt.id === cell.value
)?.value;
return createAstCell([{ type: 'text', value }]);
}
case 'multi-select': {
const value = Array.prototype.map
.call(
cell.value,
val =>
col.data.options.find(
(opt: Record<string, string>) => val === opt.id
).value
)
.filter(Boolean)
.join(',');
return createAstCell([{ type: 'text', value }]);
}
case 'checkbox': {
return createAstCell([
{ type: 'text', value: cell.value as string },
]);
}
// eslint-disable-next-line sonarjs/no-duplicated-branches
default:
return createAstCell([
{ type: 'text', value: cell.value as string },
]);
}
})
);
// Handle first row.
if (Array.isArray(columns)) {
table.rows.forEach(v => {
rows.push({
type: 'tableRow',
children: Array.prototype.map.call(columns, v =>
createAstCell([
{
type: 'text',
value: v.name,
},
])
) as [],
children: v.cells.map(v => ({
type: 'tableCell',
children:
typeof v.value === 'string'
? [{ type: 'text', value: v.value }]
: deltaConverter.deltaToAST(v.value.delta),
})),
});
}
// Handle 2-... rows
Array.prototype.forEach.call(mdAstCells, children => {
rows.push({ type: 'tableRow', children });
});
walkerContext
@@ -61,7 +61,7 @@ export const databaseBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatche
const columnTypeClass = HastUtils.querySelector(o.node, 'svg')
?.properties?.className;
const columnType = Array.isArray(columnTypeClass)
? (ColumnClassMap[columnTypeClass[0]] ?? 'rich-text')
? (ColumnClassMap[columnTypeClass[0] ?? ''] ?? 'rich-text')
: 'rich-text';
walkerContext.pushGlobalContextStack<BlocksuiteTableColumn>(
'hast:table:column',
@@ -132,8 +132,12 @@ export const databaseBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatche
children: [],
}
);
row[columns[index].id] = {
columnId: columns[index].id,
const column = columns[index];
if (!column) {
return;
}
row[column.id] = {
columnId: column.id,
value: HastUtils.getTextContent(child),
};
} else if (HastUtils.querySelector(child, '.cell-title')) {
@@ -157,33 +161,35 @@ export const databaseBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatche
return;
}
const optionIds: string[] = [];
const column = columns[index];
if (!column) {
return;
}
if (HastUtils.querySelector(child, '.selected-value')) {
if (!('options' in columns[index].data)) {
columns[index].data.options = [];
if (!('options' in column.data)) {
column.data.options = [];
}
if (!['multi-select', 'select'].includes(column.type)) {
column.type = 'select';
}
if (
!['multi-select', 'select'].includes(columns[index].type)
) {
columns[index].type = 'select';
}
if (
columns[index].type === 'select' &&
column.type === 'select' &&
child.type === 'element' &&
child.children.length > 1
) {
columns[index].type = 'multi-select';
column.type = 'multi-select';
}
child.type === 'element' &&
child.children.forEach(span => {
const filteredArray = columns[index].data.options?.filter(
const filteredArray = column.data.options?.filter(
option =>
option.value === HastUtils.getTextContent(span)
);
const id = filteredArray?.length
? filteredArray[0].id
? (filteredArray[0]?.id ?? nanoid())
: nanoid();
if (!filteredArray?.length) {
columns[index].data.options?.push({
column.data.options?.push({
id,
value: HastUtils.getTextContent(span),
color: getTagColor(),
@@ -192,48 +198,48 @@ export const databaseBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatche
optionIds.push(id);
});
// Expand will be done when leaving the table
row[columns[index].id] = {
columnId: columns[index].id,
row[column.id] = {
columnId: column.id,
value: optionIds,
};
} else if (HastUtils.querySelector(child, '.checkbox')) {
if (columns[index].type !== 'checkbox') {
columns[index].type = 'checkbox';
if (column.type !== 'checkbox') {
column.type = 'checkbox';
}
row[columns[index].id] = {
columnId: columns[index].id,
row[column.id] = {
columnId: column.id,
value: HastUtils.querySelector(child, '.checkbox-on')
? true
: false,
};
} else if (columns[index].type === 'number') {
} else if (column.type === 'number') {
const text = HastUtils.getTextContent(child);
const number = Number(text);
if (Number.isNaN(number)) {
columns[index].type = 'rich-text';
row[columns[index].id] = {
columnId: columns[index].id,
column.type = 'rich-text';
row[column.id] = {
columnId: column.id,
value: TextUtils.createText(text),
};
} else {
row[columns[index].id] = {
columnId: columns[index].id,
row[column.id] = {
columnId: column.id,
value: number,
};
}
} else {
row[columns[index].id] = {
columnId: columns[index].id,
row[column.id] = {
columnId: column.id,
value: HastUtils.getTextContent(child),
};
}
if (
columns[index].type === 'rich-text' &&
!TextUtils.isText(row[columns[index].id].value)
column.type === 'rich-text' &&
!TextUtils.isText(row[column.id].value)
) {
row[columns[index].id] = {
columnId: columns[index].id,
value: TextUtils.createText(row[columns[index].id].value),
row[column.id] = {
columnId: column.id,
value: TextUtils.createText(row[column.id].value),
};
}
});
@@ -264,11 +270,15 @@ export const databaseBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatche
.getGlobalContextStack<BlocksuiteTableRow>('hast:table:rows')
.forEach((row, i) => {
Object.keys(row).forEach(columnId => {
const cell = row[columnId];
if (!cell) {
return;
}
if (
columns.find(column => column.id === columnId)?.type ===
'select'
) {
row[columnId].value = (row[columnId].value as string[])[0];
cell.value = (cell.value as string[])[0];
}
});
cells[children.at(i)?.id ?? nanoid()] = row;
@@ -7,11 +7,8 @@ import {
BlockPlainTextAdapterExtension,
type BlockPlainTextAdapterMatcher,
} from '@blocksuite/affine-shared/adapters';
import type { DeltaInsert } from '@blocksuite/inline';
import type { BlockSnapshot } from '@blocksuite/store';
import { format } from 'date-fns/format';
import { formatTable } from './utils.js';
import { formatTable, processTable } from './utils.js';
export const databaseBlockPlainTextAdapterMatcher: BlockPlainTextAdapterMatcher =
{
@@ -26,63 +23,22 @@ export const databaseBlockPlainTextAdapterMatcher: BlockPlainTextAdapterMatcher
const columns = o.node.props.columns as Array<Column>;
const children = o.node.children;
const cells = o.node.props.cells as SerializedCells;
const tableCells = children.map((v: BlockSnapshot) =>
columns.map(col => {
const cell = cells[v.id]?.[col.id];
if (!cell && col.type !== 'title') {
return '';
}
switch (col.type) {
case 'rich-text':
return deltaConverter
.deltaToAST((cell.value as { delta: DeltaInsert[] }).delta)
.join('');
case 'title':
return deltaConverter
.deltaToAST((v.props.text as { delta: DeltaInsert[] }).delta)
.join('');
case 'date':
return format(new Date(cell.value as number), 'yyyy-MM-dd');
case 'select': {
const value = (
col.data as { options: Array<Record<string, string>> }
).options.find(opt => opt.id === cell.value)?.value;
return value || '';
}
case 'multi-select': {
const value = (cell.value as string[])
.map(
val =>
(
col.data as { options: Array<Record<string, string>> }
).options.find(opt => val === opt.id)?.value
)
.filter(Boolean)
.join(',');
return value || '';
}
default:
return String(cell.value);
}
})
);
// Handle first row.
if (Array.isArray(columns)) {
rows.push(columns.map(col => col.name));
}
// Handle 2-... rows
tableCells.forEach(children => {
rows.push(children);
const table = processTable(columns, children, cells);
rows.push(table.headers.map(v => v.name));
table.rows.forEach(v => {
rows.push(
v.cells.map(v =>
typeof v.value === 'string'
? v.value
: deltaConverter.deltaToAST(v.value.delta).join('')
)
);
});
// Convert rows to table string
const tableString = formatTable(rows);
context.textBuffer.content += tableString;
context.textBuffer.content += '\n';
walkerContext.skipAllChildren();
},
},
@@ -1,6 +1,14 @@
import type { Column, SerializedCells } from '@blocksuite/affine-model';
import type { DeltaInsert } from '@blocksuite/inline';
import type { BlockSnapshot } from '@blocksuite/store';
import { databaseBlockModels } from '../properties/model';
function calculateColumnWidths(rows: string[][]): number[] {
return rows[0].map((_, colIndex) =>
Math.max(...rows.map(row => (row[colIndex] || '').length))
return (
rows[0]?.map((_, colIndex) =>
Math.max(...rows.map(row => (row[colIndex] || '').length))
) ?? []
);
}
@@ -10,7 +18,7 @@ function formatRow(
isHeader: boolean
): string {
const cells = row.map((cell, colIndex) =>
cell.padEnd(columnWidths[colIndex], ' ')
cell?.padEnd(columnWidths[colIndex] ?? 0, ' ')
);
const rowString = `| ${cells.join(' | ')} |`;
return isHeader
@@ -30,3 +38,73 @@ export function formatTable(rows: string[][]): string {
);
return formattedRows.join('\n');
}
export const isDelta = (value: unknown): value is { delta: DeltaInsert[] } => {
if (typeof value === 'object' && value !== null) {
return '$blocksuite:internal:text$' in value;
}
return false;
};
type Table = {
headers: Column[];
rows: Row[];
};
type Row = {
cells: Cell[];
};
type Cell = {
value: string | { delta: DeltaInsert[] };
};
export const processTable = (
columns: Column[],
children: BlockSnapshot[],
cells: SerializedCells
): Table => {
const table: Table = {
headers: columns,
rows: [],
};
children.forEach(v => {
const row: Row = {
cells: [],
};
const title = v.props.text;
if (isDelta(title)) {
row.cells.push({
value: title,
});
} else {
row.cells.push({
value: '',
});
}
columns.forEach(col => {
const property = databaseBlockModels[col.type];
const cell = cells[v.id]?.[col.id];
if (col.type === 'title') {
return;
}
if (!cell || !property) {
row.cells.push({
value: '',
});
return;
}
let value: string | { delta: DeltaInsert[] };
if (isDelta(cell.value)) {
value = cell.value;
} else {
value = property.config.cellToString({
value: cell.value,
data: col.data,
});
}
row.cells.push({
value,
});
});
table.rows.push(row);
});
return table;
};