mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-02-15 05:37:32 +00:00
refactor(editor): move menu context to components (#9302)
This commit is contained in:
@@ -4,3 +4,5 @@ export * from './doc.js';
|
||||
export * from './get-content-block.js';
|
||||
export * from './getter.js';
|
||||
export * from './list.js';
|
||||
export * from './merge-to-code-model.js';
|
||||
export * from './transform-model.js';
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { BlockModel } from '@blocksuite/store';
|
||||
import { Text } from '@blocksuite/store';
|
||||
|
||||
export function mergeToCodeModel(models: BlockModel[]) {
|
||||
if (models.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const doc = models[0].doc;
|
||||
|
||||
const parent = doc.getParent(models[0]);
|
||||
if (!parent) {
|
||||
return null;
|
||||
}
|
||||
const index = parent.children.indexOf(models[0]);
|
||||
const text = models
|
||||
.map(model => {
|
||||
if (model.text instanceof Text) {
|
||||
return model.text.toString();
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
models.forEach(model => doc.deleteBlock(model));
|
||||
|
||||
const id = doc.addBlock(
|
||||
'affine:code',
|
||||
{ text: new Text(text) },
|
||||
parent,
|
||||
index
|
||||
);
|
||||
return id;
|
||||
}
|
||||
31
blocksuite/affine/shared/src/utils/model/transform-model.ts
Normal file
31
blocksuite/affine/shared/src/utils/model/transform-model.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { BlockModel, Doc, Text } from '@blocksuite/store';
|
||||
|
||||
export function transformModel(
|
||||
model: BlockModel,
|
||||
flavour: BlockSuite.Flavour,
|
||||
props?: Parameters<Doc['addBlock']>[1]
|
||||
) {
|
||||
const doc = model.doc;
|
||||
const parent = doc.getParent(model);
|
||||
if (!parent) {
|
||||
return null;
|
||||
}
|
||||
const blockProps: {
|
||||
type?: string;
|
||||
text?: Text;
|
||||
children?: BlockModel[];
|
||||
} = {
|
||||
text: model?.text?.clone(), // should clone before `deleteBlock`
|
||||
children: model.children,
|
||||
...props,
|
||||
};
|
||||
const index = parent.children.indexOf(model);
|
||||
|
||||
// Sometimes the new block can not be added due to some reason, e.g. invalid schema check.
|
||||
// So we need to try to add the new block first, and if it fails, we will not delete the old block.
|
||||
const id = doc.addBlock(flavour, blockProps, parent, index);
|
||||
doc.deleteBlock(model, {
|
||||
deleteChildren: false,
|
||||
});
|
||||
return id;
|
||||
}
|
||||
Reference in New Issue
Block a user