refactor(editor): unify directories naming (#11516)

**Directory Structure Changes**

- Renamed multiple block-related directories by removing the "block-" prefix:
  - `block-attachment` → `attachment`
  - `block-bookmark` → `bookmark`
  - `block-callout` → `callout`
  - `block-code` → `code`
  - `block-data-view` → `data-view`
  - `block-database` → `database`
  - `block-divider` → `divider`
  - `block-edgeless-text` → `edgeless-text`
  - `block-embed` → `embed`
This commit is contained in:
Saul-Mirone
2025-04-07 12:34:40 +00:00
parent e1bd2047c4
commit 1f45cc5dec
893 changed files with 439 additions and 460 deletions
@@ -0,0 +1,13 @@
import type { ExtensionType } from '@blocksuite/store';
import { DatabaseBlockHtmlAdapterExtension } from './html.js';
import { DatabaseBlockMarkdownAdapterExtension } from './markdown.js';
import { DatabaseBlockNotionHtmlAdapterExtension } from './notion-html.js';
import { DatabaseBlockPlainTextAdapterExtension } from './plain-text.js';
export const DatabaseBlockAdapterExtensions: ExtensionType[] = [
DatabaseBlockHtmlAdapterExtension,
DatabaseBlockMarkdownAdapterExtension,
DatabaseBlockNotionHtmlAdapterExtension,
DatabaseBlockPlainTextAdapterExtension,
];
@@ -0,0 +1,105 @@
import {
type ColumnDataType,
DatabaseBlockSchema,
type SerializedCells,
} from '@blocksuite/affine-model';
import {
BlockHtmlAdapterExtension,
type BlockHtmlAdapterMatcher,
type InlineHtmlAST,
} from '@blocksuite/affine-shared/adapters';
import type { Element } from 'hast';
import { processTable } from './utils';
export const databaseBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
flavour: DatabaseBlockSchema.model.flavour,
toMatch: () => false,
fromMatch: o => o.node.flavour === DatabaseBlockSchema.model.flavour,
toBlockSnapshot: {},
fromBlockSnapshot: {
enter: (o, context) => {
const { walkerContext } = context;
const columns = o.node.props.columns as Array<ColumnDataType>;
const children = o.node.children;
const cells = o.node.props.cells as SerializedCells;
const table = processTable(columns, children, cells);
const createAstTableCell = (
children: InlineHtmlAST[]
): InlineHtmlAST => ({
type: 'element',
tagName: 'td',
properties: Object.create(null),
children,
});
const createAstTableHeaderCell = (
children: InlineHtmlAST[]
): InlineHtmlAST => ({
type: 'element',
tagName: 'th',
properties: Object.create(null),
children,
});
const createAstTableRow = (cells: InlineHtmlAST[]): Element => ({
type: 'element',
tagName: 'tr',
properties: Object.create(null),
children: cells,
});
const { deltaConverter } = context;
const tableHeaderAst: Element = {
type: 'element',
tagName: 'thead',
properties: Object.create(null),
children: [
createAstTableRow(
table.headers.map(v =>
createAstTableHeaderCell([
{
type: 'text',
value: v.name ?? '',
},
])
)
),
],
};
const tableBodyAst: Element = {
type: 'element',
tagName: 'tbody',
properties: Object.create(null),
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
.openNode({
type: 'element',
tagName: 'table',
properties: Object.create(null),
children: [tableHeaderAst, tableBodyAst],
})
.closeNode();
walkerContext.skipAllChildren();
},
},
};
export const DatabaseBlockHtmlAdapterExtension = BlockHtmlAdapterExtension(
databaseBlockHtmlAdapterMatcher
);
@@ -0,0 +1,4 @@
export * from './html';
export * from './markdown';
export * from './notion-html';
export * from './plain-text';
@@ -0,0 +1,67 @@
import {
type ColumnDataType,
DatabaseBlockSchema,
type SerializedCells,
} from '@blocksuite/affine-model';
import {
BlockMarkdownAdapterExtension,
type BlockMarkdownAdapterMatcher,
type MarkdownAST,
} from '@blocksuite/affine-shared/adapters';
import type { TableRow } from 'mdast';
import { processTable } from './utils';
const DATABASE_NODE_TYPES = new Set(['table', 'tableRow']);
const isDatabaseNode = (node: MarkdownAST) =>
DATABASE_NODE_TYPES.has(node.type);
export const databaseBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
{
flavour: DatabaseBlockSchema.model.flavour,
toMatch: o => isDatabaseNode(o.node),
fromMatch: o => o.node.flavour === DatabaseBlockSchema.model.flavour,
toBlockSnapshot: {},
fromBlockSnapshot: {
enter: (o, context) => {
const { walkerContext, deltaConverter } = context;
const rows: TableRow[] = [];
const columns = o.node.props.columns as Array<ColumnDataType>;
const children = o.node.children;
const cells = o.node.props.cells as SerializedCells;
const table = processTable(columns, children, cells);
rows.push({
type: 'tableRow',
children: table.headers.map(v => ({
type: 'tableCell',
children: [{ type: 'text', value: v.name }],
})),
});
table.rows.forEach(v => {
rows.push({
type: 'tableRow',
children: v.cells.map(v => ({
type: 'tableCell',
children:
typeof v.value === 'string'
? [{ type: 'text', value: v.value }]
: deltaConverter.deltaToAST(v.value.delta),
})),
});
});
walkerContext
.openNode({
type: 'table',
children: rows,
})
.closeNode();
walkerContext.skipAllChildren();
},
},
};
export const DatabaseBlockMarkdownAdapterExtension =
BlockMarkdownAdapterExtension(databaseBlockMarkdownAdapterMatcher);
@@ -0,0 +1,358 @@
import { DatabaseBlockSchema } from '@blocksuite/affine-model';
import {
AdapterTextUtils,
BlockNotionHtmlAdapterExtension,
type BlockNotionHtmlAdapterMatcher,
HastUtils,
} from '@blocksuite/affine-shared/adapters';
import { getTagColor } from '@blocksuite/data-view';
import { type BlockSnapshot, nanoid } from '@blocksuite/store';
const ColumnClassMap: Record<string, string> = {
typesSelect: 'select',
typesMultipleSelect: 'multi-select',
typesNumber: 'number',
typesCheckbox: 'checkbox',
typesText: 'rich-text',
typesTitle: 'title',
};
const NotionDatabaseToken = '.collection-content';
const NotionDatabaseTitleToken = '.collection-title';
type BlocksuiteTableColumn = {
type: string;
name: string;
data: {
options?: {
id: string;
value: string;
color: string;
}[];
};
id: string;
};
type BlocksuiteTableRow = Record<
string,
{
columnId: string;
value: unknown;
}
>;
const DATABASE_NODE_TYPES = new Set(['table', 'th', 'tr']);
export const databaseBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatcher =
{
flavour: DatabaseBlockSchema.model.flavour,
toMatch: o =>
HastUtils.isElement(o.node) && DATABASE_NODE_TYPES.has(o.node.tagName),
fromMatch: () => false,
toBlockSnapshot: {
enter: (o, context) => {
if (!HastUtils.isElement(o.node)) {
return;
}
const { walkerContext, deltaConverter, pageMap } = context;
switch (o.node.tagName) {
case 'th': {
const columnId = nanoid();
const columnTypeClass = HastUtils.querySelector(o.node, 'svg')
?.properties?.className;
const columnType = Array.isArray(columnTypeClass)
? (ColumnClassMap[columnTypeClass[0] ?? ''] ?? 'rich-text')
: 'rich-text';
walkerContext.pushGlobalContextStack<BlocksuiteTableColumn>(
'hast:table:column',
{
type: columnType,
name: HastUtils.getTextContent(
HastUtils.getTextChildrenOnlyAst(o.node)
),
data: Object.create(null),
id: columnId,
}
);
// disable icon img in th
walkerContext.setGlobalContext('hast:disableimg', true);
break;
}
case 'tr': {
if (
o.parent?.node.type === 'element' &&
o.parent.node.tagName === 'tbody'
) {
const columns =
walkerContext.getGlobalContextStack<BlocksuiteTableColumn>(
'hast:table:column'
);
const row = Object.create(null);
let plainTable = false;
HastUtils.getElementChildren(o.node).forEach((child, index) => {
if (plainTable || columns[index] === undefined) {
plainTable = true;
if (columns[index] === undefined) {
columns.push({
type: 'rich-text',
name: '',
data: Object.create(null),
id: nanoid(),
});
walkerContext.pushGlobalContextStack<BlockSnapshot>(
'hast:table:children',
{
type: 'block',
id: nanoid(),
flavour: 'affine:paragraph',
props: {
text: {
'$blocksuite:internal:text$': true,
delta: deltaConverter.astToDelta(child),
},
type: 'text',
},
children: [],
}
);
}
walkerContext.pushGlobalContextStack<BlockSnapshot>(
'hast:table:children',
{
type: 'block',
id: nanoid(),
flavour: 'affine:paragraph',
props: {
text: {
'$blocksuite:internal:text$': true,
delta: deltaConverter.astToDelta(child),
},
type: 'text',
},
children: [],
}
);
const column = columns[index];
if (!column) {
return;
}
row[column.id] = {
columnId: column.id,
value: HastUtils.getTextContent(child),
};
} else if (HastUtils.querySelector(child, '.cell-title')) {
walkerContext.pushGlobalContextStack<BlockSnapshot>(
'hast:table:children',
{
type: 'block',
id: nanoid(),
flavour: 'affine:paragraph',
props: {
text: {
'$blocksuite:internal:text$': true,
delta: deltaConverter.astToDelta(child, { pageMap }),
},
type: 'text',
},
children: [],
}
);
columns[index].type = 'title';
return;
}
const optionIds: string[] = [];
const column = columns[index];
if (!column) {
return;
}
if (HastUtils.querySelector(child, '.selected-value')) {
if (!('options' in column.data)) {
column.data.options = [];
}
if (!['multi-select', 'select'].includes(column.type)) {
column.type = 'select';
}
if (
column.type === 'select' &&
child.type === 'element' &&
child.children.length > 1
) {
column.type = 'multi-select';
}
child.type === 'element' &&
child.children.forEach(span => {
const filteredArray = column.data.options?.filter(
option =>
option.value === HastUtils.getTextContent(span)
);
const id = filteredArray?.length
? (filteredArray[0]?.id ?? nanoid())
: nanoid();
if (!filteredArray?.length) {
column.data.options?.push({
id,
value: HastUtils.getTextContent(span),
color: getTagColor(),
});
}
optionIds.push(id);
});
// Expand will be done when leaving the table
row[column.id] = {
columnId: column.id,
value: optionIds,
};
} else if (HastUtils.querySelector(child, '.checkbox')) {
if (column.type !== 'checkbox') {
column.type = 'checkbox';
}
row[column.id] = {
columnId: column.id,
value: HastUtils.querySelector(child, '.checkbox-on')
? true
: false,
};
} else if (column.type === 'number') {
const text = HastUtils.getTextContent(child);
const number = Number(text);
if (Number.isNaN(number)) {
column.type = 'rich-text';
row[column.id] = {
columnId: column.id,
value: AdapterTextUtils.createText(text),
};
} else {
row[column.id] = {
columnId: column.id,
value: number,
};
}
} else {
row[column.id] = {
columnId: column.id,
value: HastUtils.getTextContent(child),
};
}
if (
column.type === 'rich-text' &&
!AdapterTextUtils.isText(row[column.id].value)
) {
row[column.id] = {
columnId: column.id,
value: AdapterTextUtils.createText(row[column.id].value),
};
}
});
walkerContext.setGlobalContextStack('hast:table:column', columns);
walkerContext.pushGlobalContextStack('hast:table:rows', row);
}
}
}
},
leave: (o, context) => {
if (!HastUtils.isElement(o.node)) {
return;
}
const { walkerContext } = context;
switch (o.node.tagName) {
case 'table': {
const columns =
walkerContext.getGlobalContextStack<BlocksuiteTableColumn>(
'hast:table:column'
);
walkerContext.setGlobalContextStack('hast:table:column', []);
const children = walkerContext.getGlobalContextStack<BlockSnapshot>(
'hast:table:children'
);
walkerContext.setGlobalContextStack('hast:table:children', []);
const cells = Object.create(null);
walkerContext
.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'
) {
cell.value = (cell.value as string[])[0];
}
});
cells[children.at(i)?.id ?? nanoid()] = row;
});
walkerContext.setGlobalContextStack('hast:table:cells', []);
let databaseTitle = '';
if (
o.parent?.node.type === 'element' &&
HastUtils.querySelector(o.parent.node, NotionDatabaseToken)
) {
databaseTitle = HastUtils.getTextContent(
HastUtils.querySelector(o.parent.node, NotionDatabaseTitleToken)
);
}
walkerContext.openNode(
{
type: 'block',
id: nanoid(),
flavour: DatabaseBlockSchema.model.flavour,
props: {
views: [
{
id: nanoid(),
name: 'Table View',
mode: 'table',
columns: [],
filter: {
type: 'group',
op: 'and',
conditions: [],
},
header: {
titleColumn:
columns.find(column => column.type === 'title')?.id ??
'',
iconColumn: 'type',
},
},
],
title: {
'$blocksuite:internal:text$': true,
delta: databaseTitle
? [
{
insert: databaseTitle,
},
]
: [],
},
columns,
cells,
},
children: [],
},
'children'
);
children.forEach(child => {
walkerContext.openNode(child, 'children').closeNode();
});
walkerContext.closeNode();
walkerContext.cleanGlobalContextStack('hast:table:column');
walkerContext.cleanGlobalContextStack('hast:table:rows');
walkerContext.cleanGlobalContextStack('hast:table:children');
break;
}
case 'th': {
walkerContext.setGlobalContext('hast:disableimg', false);
break;
}
}
},
},
fromBlockSnapshot: {},
};
export const DatabaseBlockNotionHtmlAdapterExtension =
BlockNotionHtmlAdapterExtension(databaseBlockNotionHtmlAdapterMatcher);
@@ -0,0 +1,48 @@
import {
type ColumnDataType,
DatabaseBlockSchema,
type SerializedCells,
} from '@blocksuite/affine-model';
import {
BlockPlainTextAdapterExtension,
type BlockPlainTextAdapterMatcher,
} from '@blocksuite/affine-shared/adapters';
import { formatTable, processTable } from './utils.js';
export const databaseBlockPlainTextAdapterMatcher: BlockPlainTextAdapterMatcher =
{
flavour: DatabaseBlockSchema.model.flavour,
toMatch: () => false,
fromMatch: o => o.node.flavour === DatabaseBlockSchema.model.flavour,
toBlockSnapshot: {},
fromBlockSnapshot: {
enter: (o, context) => {
const { walkerContext, deltaConverter } = context;
const rows: string[][] = [];
const columns = o.node.props.columns as Array<ColumnDataType>;
const children = o.node.children;
const cells = o.node.props.cells as SerializedCells;
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('')
)
);
});
const tableString = formatTable(rows);
context.textBuffer.content += tableString;
context.textBuffer.content += '\n';
walkerContext.skipAllChildren();
},
},
};
export const DatabaseBlockPlainTextAdapterExtension =
BlockPlainTextAdapterExtension(databaseBlockPlainTextAdapterMatcher);
@@ -0,0 +1,109 @@
import type { ColumnDataType, SerializedCells } from '@blocksuite/affine-model';
import type { BlockSnapshot, DeltaInsert } 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))
) ?? []
);
}
function formatRow(
row: string[],
columnWidths: number[],
isHeader: boolean
): string {
const cells = row.map((cell, colIndex) =>
cell?.padEnd(columnWidths[colIndex] ?? 0, ' ')
);
const rowString = `| ${cells.join(' | ')} |`;
return isHeader
? `${rowString}\n${formatSeparator(columnWidths)}`
: rowString;
}
function formatSeparator(columnWidths: number[]): string {
const separator = columnWidths.map(width => '-'.repeat(width)).join(' | ');
return `| ${separator} |`;
}
export function formatTable(rows: string[][]): string {
const columnWidths = calculateColumnWidths(rows);
const formattedRows = rows.map((row, index) =>
formatRow(row, columnWidths, index === 0)
);
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: ColumnDataType[];
rows: Row[];
};
type Row = {
cells: Cell[];
};
type Cell = {
value: string | { delta: DeltaInsert[] };
};
export const processTable = (
columns: ColumnDataType[],
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.rawValue.toString({
value: cell.value,
data: col.data,
});
}
row.cells.push({
value,
});
});
table.rows.push(row);
});
return table;
};