feat(editor): add inline packages (#11048)
This commit is contained in:
54
blocksuite/affine/inlines/preset/package.json
Normal file
54
blocksuite/affine/inlines/preset/package.json
Normal file
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@blocksuite/affine-inline-preset",
|
||||
"description": "Inline preset for BlockSuite.",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"keywords": [],
|
||||
"author": "toeverything",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@blocksuite/affine-components": "workspace:*",
|
||||
"@blocksuite/affine-inline-link": "workspace:*",
|
||||
"@blocksuite/affine-inline-reference": "workspace:*",
|
||||
"@blocksuite/affine-model": "workspace:*",
|
||||
"@blocksuite/affine-rich-text": "workspace:*",
|
||||
"@blocksuite/affine-shared": "workspace:*",
|
||||
"@blocksuite/block-std": "workspace:*",
|
||||
"@blocksuite/global": "workspace:*",
|
||||
"@blocksuite/icons": "^2.2.6",
|
||||
"@blocksuite/store": "workspace:*",
|
||||
"@floating-ui/dom": "^1.6.13",
|
||||
"@lit/context": "^1.1.2",
|
||||
"@preact/signals-core": "^1.8.0",
|
||||
"@toeverything/theme": "^1.1.12",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/katex": "^0.16.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/mdast": "^4.0.4",
|
||||
"collapse-white-space": "^2.1.0",
|
||||
"date-fns": "^4.0.0",
|
||||
"katex": "^0.16.11",
|
||||
"lit": "^3.2.0",
|
||||
"lit-html": "^3.2.1",
|
||||
"lodash-es": "^4.17.21",
|
||||
"remark-math": "^6.0.0",
|
||||
"rxjs": "^7.8.1",
|
||||
"shiki": "^3.0.0",
|
||||
"yjs": "^13.6.21",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./effects": "./src/effects.ts"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"dist",
|
||||
"!src/__tests__",
|
||||
"!dist/__tests__"
|
||||
],
|
||||
"version": "0.20.0"
|
||||
}
|
||||
24
blocksuite/affine/inlines/preset/src/adapters/extensions.ts
Normal file
24
blocksuite/affine/inlines/preset/src/adapters/extensions.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { ExtensionType } from '@blocksuite/store';
|
||||
|
||||
import { HtmlInlineToDeltaAdapterExtensions } from './html/html-inline';
|
||||
import { InlineDeltaToHtmlAdapterExtensions } from './html/inline-delta';
|
||||
import { InlineDeltaToMarkdownAdapterExtensions } from './markdown/inline-delta';
|
||||
import { MarkdownInlineToDeltaAdapterExtensions } from './markdown/markdown-inline';
|
||||
import { NotionHtmlInlineToDeltaAdapterExtensions } from './notion-html/html-inline';
|
||||
import { InlineDeltaToPlainTextAdapterExtensions } from './plain-text/inline-delta';
|
||||
|
||||
export const InlineAdapterExtensions: ExtensionType[] = [
|
||||
HtmlInlineToDeltaAdapterExtensions,
|
||||
InlineDeltaToHtmlAdapterExtensions,
|
||||
InlineDeltaToPlainTextAdapterExtensions,
|
||||
NotionHtmlInlineToDeltaAdapterExtensions,
|
||||
InlineDeltaToMarkdownAdapterExtensions,
|
||||
MarkdownInlineToDeltaAdapterExtensions,
|
||||
].flat();
|
||||
|
||||
export * from './html/html-inline';
|
||||
export * from './html/inline-delta';
|
||||
export * from './markdown/inline-delta';
|
||||
export * from './markdown/markdown-inline';
|
||||
export * from './notion-html/html-inline';
|
||||
export * from './plain-text/inline-delta';
|
||||
@@ -0,0 +1,175 @@
|
||||
import { htmlLinkElementToDeltaMatcher } from '@blocksuite/affine-inline-link';
|
||||
import {
|
||||
type HtmlAST,
|
||||
HtmlASTToDeltaExtension,
|
||||
} from '@blocksuite/affine-shared/adapters';
|
||||
import { collapseWhiteSpace } from 'collapse-white-space';
|
||||
import type { Element } from 'hast';
|
||||
|
||||
const isElement = (ast: HtmlAST): ast is Element => {
|
||||
return ast.type === 'element';
|
||||
};
|
||||
|
||||
const textLikeElementTags = new Set(['span', 'bdi', 'bdo', 'ins']);
|
||||
const listElementTags = new Set(['ol', 'ul']);
|
||||
const strongElementTags = new Set(['strong', 'b']);
|
||||
const italicElementTags = new Set(['i', 'em']);
|
||||
|
||||
export const htmlTextToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'text',
|
||||
match: ast => ast.type === 'text',
|
||||
toDelta: (ast, context) => {
|
||||
if (!('value' in ast)) {
|
||||
return [];
|
||||
}
|
||||
const { options } = context;
|
||||
options.trim ??= true;
|
||||
|
||||
if (options.pre) {
|
||||
return [{ insert: ast.value }];
|
||||
}
|
||||
|
||||
const value = options.trim
|
||||
? collapseWhiteSpace(ast.value, { trim: options.trim })
|
||||
: collapseWhiteSpace(ast.value);
|
||||
return value ? [{ insert: value }] : [];
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlTextLikeElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'text-like-element',
|
||||
match: ast => isElement(ast) && textLikeElementTags.has(ast.tagName),
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, { trim: false })
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlListToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'list-element',
|
||||
match: ast => isElement(ast) && listElementTags.has(ast.tagName),
|
||||
toDelta: () => {
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlStrongElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'strong-element',
|
||||
match: ast => isElement(ast) && strongElementTags.has(ast.tagName),
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, { trim: false }).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, bold: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlItalicElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'italic-element',
|
||||
match: ast => isElement(ast) && italicElementTags.has(ast.tagName),
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, { trim: false }).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, italic: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlCodeElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'code-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'code',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, { trim: false }).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, code: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlDelElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'del-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'del',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, { trim: false }).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, strike: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlUnderlineElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'underline-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'u',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, { trim: false }).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, underline: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlMarkElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'mark-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'mark',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, { trim: false }).map(delta => {
|
||||
delta.attributes = { ...delta.attributes };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const htmlBrElementToDeltaMatcher = HtmlASTToDeltaExtension({
|
||||
name: 'br-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'br',
|
||||
toDelta: () => {
|
||||
return [{ insert: '\n' }];
|
||||
},
|
||||
});
|
||||
|
||||
export const HtmlInlineToDeltaAdapterExtensions = [
|
||||
htmlTextToDeltaMatcher,
|
||||
htmlTextLikeElementToDeltaMatcher,
|
||||
htmlStrongElementToDeltaMatcher,
|
||||
htmlItalicElementToDeltaMatcher,
|
||||
htmlCodeElementToDeltaMatcher,
|
||||
htmlDelElementToDeltaMatcher,
|
||||
htmlUnderlineElementToDeltaMatcher,
|
||||
htmlLinkElementToDeltaMatcher,
|
||||
htmlMarkElementToDeltaMatcher,
|
||||
htmlBrElementToDeltaMatcher,
|
||||
];
|
||||
@@ -0,0 +1,158 @@
|
||||
import { linkDeltaToHtmlAdapterMatcher } from '@blocksuite/affine-inline-link';
|
||||
import { referenceDeltaToHtmlAdapterMatcher } from '@blocksuite/affine-inline-reference';
|
||||
import type { InlineHtmlAST } from '@blocksuite/affine-shared/adapters';
|
||||
import { InlineDeltaToHtmlAdapterExtension } from '@blocksuite/affine-shared/adapters';
|
||||
import { ThemeProvider } from '@blocksuite/affine-shared/services';
|
||||
|
||||
export const boldDeltaToHtmlAdapterMatcher = InlineDeltaToHtmlAdapterExtension({
|
||||
name: 'bold',
|
||||
match: delta => !!delta.attributes?.bold,
|
||||
toAST: (_, context) => {
|
||||
return {
|
||||
type: 'element',
|
||||
tagName: 'strong',
|
||||
properties: {},
|
||||
children: [context.current],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const italicDeltaToHtmlAdapterMatcher =
|
||||
InlineDeltaToHtmlAdapterExtension({
|
||||
name: 'italic',
|
||||
match: delta => !!delta.attributes?.italic,
|
||||
toAST: (_, context) => {
|
||||
return {
|
||||
type: 'element',
|
||||
tagName: 'em',
|
||||
properties: {},
|
||||
children: [context.current],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const strikeDeltaToHtmlAdapterMatcher =
|
||||
InlineDeltaToHtmlAdapterExtension({
|
||||
name: 'strike',
|
||||
match: delta => !!delta.attributes?.strike,
|
||||
toAST: (_, context) => {
|
||||
return {
|
||||
type: 'element',
|
||||
tagName: 'del',
|
||||
properties: {},
|
||||
children: [context.current],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const inlineCodeDeltaToHtmlAdapterMatcher =
|
||||
InlineDeltaToHtmlAdapterExtension({
|
||||
name: 'inlineCode',
|
||||
match: delta => !!delta.attributes?.code,
|
||||
toAST: (_, context) => {
|
||||
return {
|
||||
type: 'element',
|
||||
tagName: 'code',
|
||||
properties: {},
|
||||
children: [context.current],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const underlineDeltaToHtmlAdapterMatcher =
|
||||
InlineDeltaToHtmlAdapterExtension({
|
||||
name: 'underline',
|
||||
match: delta => !!delta.attributes?.underline,
|
||||
toAST: (_, context) => {
|
||||
return {
|
||||
type: 'element',
|
||||
tagName: 'u',
|
||||
properties: {},
|
||||
children: [context.current],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const highlightBackgroundDeltaToHtmlAdapterMatcher =
|
||||
InlineDeltaToHtmlAdapterExtension({
|
||||
name: 'highlight-background',
|
||||
match: delta => !!delta.attributes?.background,
|
||||
toAST: (delta, context, provider) => {
|
||||
const hast: InlineHtmlAST = {
|
||||
type: 'element',
|
||||
tagName: 'span',
|
||||
properties: {},
|
||||
children: [context.current],
|
||||
};
|
||||
if (!provider || !delta.attributes?.background) {
|
||||
return hast;
|
||||
}
|
||||
|
||||
const theme = provider.getOptional(ThemeProvider);
|
||||
if (!theme) {
|
||||
return hast;
|
||||
}
|
||||
|
||||
const backgroundVar = delta.attributes?.background.substring(
|
||||
'var('.length,
|
||||
delta.attributes?.background.indexOf(')')
|
||||
);
|
||||
const background = theme.getCssVariableColor(backgroundVar);
|
||||
return {
|
||||
type: 'element',
|
||||
tagName: 'mark',
|
||||
properties: {
|
||||
style: `background-color: ${background};`,
|
||||
},
|
||||
children: [context.current],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const highlightColorDeltaToHtmlAdapterMatcher =
|
||||
InlineDeltaToHtmlAdapterExtension({
|
||||
name: 'highlight-color',
|
||||
match: delta => !!delta.attributes?.color,
|
||||
toAST: (delta, context, provider) => {
|
||||
const hast: InlineHtmlAST = {
|
||||
type: 'element',
|
||||
tagName: 'span',
|
||||
properties: {},
|
||||
children: [context.current],
|
||||
};
|
||||
if (!provider || !delta.attributes?.color) {
|
||||
return hast;
|
||||
}
|
||||
|
||||
const theme = provider.getOptional(ThemeProvider);
|
||||
if (!theme) {
|
||||
return hast;
|
||||
}
|
||||
|
||||
const colorVar = delta.attributes?.color.substring(
|
||||
'var('.length,
|
||||
delta.attributes?.color.indexOf(')')
|
||||
);
|
||||
const color = theme.getCssVariableColor(colorVar);
|
||||
return {
|
||||
type: 'element',
|
||||
tagName: 'mark',
|
||||
properties: {
|
||||
style: `color: ${color};background-color: transparent`,
|
||||
},
|
||||
children: [context.current],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const InlineDeltaToHtmlAdapterExtensions = [
|
||||
boldDeltaToHtmlAdapterMatcher,
|
||||
italicDeltaToHtmlAdapterMatcher,
|
||||
strikeDeltaToHtmlAdapterMatcher,
|
||||
underlineDeltaToHtmlAdapterMatcher,
|
||||
highlightBackgroundDeltaToHtmlAdapterMatcher,
|
||||
highlightColorDeltaToHtmlAdapterMatcher,
|
||||
inlineCodeDeltaToHtmlAdapterMatcher,
|
||||
referenceDeltaToHtmlAdapterMatcher,
|
||||
linkDeltaToHtmlAdapterMatcher,
|
||||
];
|
||||
@@ -0,0 +1,129 @@
|
||||
import { linkDeltaToMarkdownAdapterMatcher } from '@blocksuite/affine-inline-link';
|
||||
import { referenceDeltaToMarkdownAdapterMatcher } from '@blocksuite/affine-inline-reference';
|
||||
import {
|
||||
FOOTNOTE_DEFINITION_PREFIX,
|
||||
InlineDeltaToMarkdownAdapterExtension,
|
||||
} from '@blocksuite/affine-shared/adapters';
|
||||
import type { PhrasingContent } from 'mdast';
|
||||
import type RemarkMath from 'remark-math';
|
||||
|
||||
declare type _GLOBAL_ = typeof RemarkMath;
|
||||
|
||||
export const boldDeltaToMarkdownAdapterMatcher =
|
||||
InlineDeltaToMarkdownAdapterExtension({
|
||||
name: 'bold',
|
||||
match: delta => !!delta.attributes?.bold,
|
||||
toAST: (_, context) => {
|
||||
const { current: currentMdast } = context;
|
||||
return {
|
||||
type: 'strong',
|
||||
children: [currentMdast],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const italicDeltaToMarkdownAdapterMatcher =
|
||||
InlineDeltaToMarkdownAdapterExtension({
|
||||
name: 'italic',
|
||||
match: delta => !!delta.attributes?.italic,
|
||||
toAST: (_, context) => {
|
||||
const { current: currentMdast } = context;
|
||||
return {
|
||||
type: 'emphasis',
|
||||
children: [currentMdast],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const strikeDeltaToMarkdownAdapterMatcher =
|
||||
InlineDeltaToMarkdownAdapterExtension({
|
||||
name: 'strike',
|
||||
match: delta => !!delta.attributes?.strike,
|
||||
toAST: (_, context) => {
|
||||
const { current: currentMdast } = context;
|
||||
return {
|
||||
type: 'delete',
|
||||
children: [currentMdast],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const inlineCodeDeltaToMarkdownAdapterMatcher =
|
||||
InlineDeltaToMarkdownAdapterExtension({
|
||||
name: 'inlineCode',
|
||||
match: delta => !!delta.attributes?.code,
|
||||
toAST: delta => ({
|
||||
type: 'inlineCode',
|
||||
value: delta.insert,
|
||||
}),
|
||||
});
|
||||
|
||||
export const latexDeltaToMarkdownAdapterMatcher =
|
||||
InlineDeltaToMarkdownAdapterExtension({
|
||||
name: 'inlineLatex',
|
||||
match: delta => !!delta.attributes?.latex,
|
||||
toAST: delta => {
|
||||
const mdast: PhrasingContent = {
|
||||
type: 'text',
|
||||
value: delta.insert,
|
||||
};
|
||||
if (delta.attributes?.latex) {
|
||||
return {
|
||||
type: 'inlineMath',
|
||||
value: delta.attributes.latex,
|
||||
};
|
||||
}
|
||||
return mdast;
|
||||
},
|
||||
});
|
||||
|
||||
export const footnoteReferenceDeltaToMarkdownAdapterMatcher =
|
||||
InlineDeltaToMarkdownAdapterExtension({
|
||||
name: 'footnote-reference',
|
||||
match: delta => !!delta.attributes?.footnote,
|
||||
toAST: (delta, context) => {
|
||||
const mdast: PhrasingContent = {
|
||||
type: 'text',
|
||||
value: delta.insert,
|
||||
};
|
||||
const footnote = delta.attributes?.footnote;
|
||||
if (!footnote) {
|
||||
return mdast;
|
||||
}
|
||||
const footnoteDefinitionKey = `${FOOTNOTE_DEFINITION_PREFIX}${footnote.label}`;
|
||||
const { configs } = context;
|
||||
// FootnoteReference should be paired with FootnoteDefinition
|
||||
// If the footnoteDefinition is not in the configs, set it to configs
|
||||
// We should add the footnoteDefinition markdown ast nodes to tree after all the footnoteReference markdown ast nodes are added
|
||||
if (!configs.has(footnoteDefinitionKey)) {
|
||||
// clone the footnote reference
|
||||
const clonedFootnoteReference = { ...footnote.reference };
|
||||
// If the footnote reference contains url, encode it
|
||||
if (clonedFootnoteReference.url) {
|
||||
clonedFootnoteReference.url = encodeURIComponent(
|
||||
clonedFootnoteReference.url
|
||||
);
|
||||
}
|
||||
configs.set(
|
||||
footnoteDefinitionKey,
|
||||
JSON.stringify(clonedFootnoteReference)
|
||||
);
|
||||
}
|
||||
return {
|
||||
type: 'footnoteReference',
|
||||
label: footnote.label,
|
||||
identifier: footnote.label,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const InlineDeltaToMarkdownAdapterExtensions = [
|
||||
referenceDeltaToMarkdownAdapterMatcher,
|
||||
linkDeltaToMarkdownAdapterMatcher,
|
||||
inlineCodeDeltaToMarkdownAdapterMatcher,
|
||||
boldDeltaToMarkdownAdapterMatcher,
|
||||
italicDeltaToMarkdownAdapterMatcher,
|
||||
strikeDeltaToMarkdownAdapterMatcher,
|
||||
latexDeltaToMarkdownAdapterMatcher,
|
||||
footnoteReferenceDeltaToMarkdownAdapterMatcher,
|
||||
];
|
||||
@@ -0,0 +1,142 @@
|
||||
import { markdownLinkToDeltaMatcher } from '@blocksuite/affine-inline-link';
|
||||
import { FootNoteReferenceParamsSchema } from '@blocksuite/affine-model';
|
||||
import {
|
||||
FOOTNOTE_DEFINITION_PREFIX,
|
||||
MarkdownASTToDeltaExtension,
|
||||
} from '@blocksuite/affine-shared/adapters';
|
||||
|
||||
export const markdownTextToDeltaMatcher = MarkdownASTToDeltaExtension({
|
||||
name: 'text',
|
||||
match: ast => ast.type === 'text',
|
||||
toDelta: ast => {
|
||||
if (!('value' in ast)) {
|
||||
return [];
|
||||
}
|
||||
return [{ insert: ast.value }];
|
||||
},
|
||||
});
|
||||
|
||||
export const markdownInlineCodeToDeltaMatcher = MarkdownASTToDeltaExtension({
|
||||
name: 'inlineCode',
|
||||
match: ast => ast.type === 'inlineCode',
|
||||
toDelta: ast => {
|
||||
if (!('value' in ast)) {
|
||||
return [];
|
||||
}
|
||||
return [{ insert: ast.value, attributes: { code: true } }];
|
||||
},
|
||||
});
|
||||
|
||||
export const markdownStrongToDeltaMatcher = MarkdownASTToDeltaExtension({
|
||||
name: 'strong',
|
||||
match: ast => ast.type === 'strong',
|
||||
toDelta: (ast, context) => {
|
||||
if (!('children' in ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, bold: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const markdownEmphasisToDeltaMatcher = MarkdownASTToDeltaExtension({
|
||||
name: 'emphasis',
|
||||
match: ast => ast.type === 'emphasis',
|
||||
toDelta: (ast, context) => {
|
||||
if (!('children' in ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, italic: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const markdownDeleteToDeltaMatcher = MarkdownASTToDeltaExtension({
|
||||
name: 'delete',
|
||||
match: ast => ast.type === 'delete',
|
||||
toDelta: (ast, context) => {
|
||||
if (!('children' in ast)) {
|
||||
return [];
|
||||
}
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, strike: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const markdownListToDeltaMatcher = MarkdownASTToDeltaExtension({
|
||||
name: 'list',
|
||||
match: ast => ast.type === 'list',
|
||||
toDelta: () => [],
|
||||
});
|
||||
|
||||
export const markdownInlineMathToDeltaMatcher = MarkdownASTToDeltaExtension({
|
||||
name: 'inlineMath',
|
||||
match: ast => ast.type === 'inlineMath',
|
||||
toDelta: ast => {
|
||||
if (!('value' in ast)) {
|
||||
return [];
|
||||
}
|
||||
return [{ insert: ' ', attributes: { latex: ast.value } }];
|
||||
},
|
||||
});
|
||||
|
||||
export const markdownFootnoteReferenceToDeltaMatcher =
|
||||
MarkdownASTToDeltaExtension({
|
||||
name: 'footnote-reference',
|
||||
match: ast => ast.type === 'footnoteReference',
|
||||
toDelta: (ast, context) => {
|
||||
if (ast.type !== 'footnoteReference') {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
const { configs } = context;
|
||||
const footnoteDefinitionKey = `${FOOTNOTE_DEFINITION_PREFIX}${ast.identifier}`;
|
||||
const footnoteDefinition = configs.get(footnoteDefinitionKey);
|
||||
if (!footnoteDefinition) {
|
||||
return [];
|
||||
}
|
||||
const footnoteDefinitionJson = JSON.parse(footnoteDefinition);
|
||||
// If the footnote definition contains url, decode it
|
||||
if (footnoteDefinitionJson.url) {
|
||||
footnoteDefinitionJson.url = decodeURIComponent(
|
||||
footnoteDefinitionJson.url
|
||||
);
|
||||
}
|
||||
const footnoteReference = FootNoteReferenceParamsSchema.parse(
|
||||
footnoteDefinitionJson
|
||||
);
|
||||
const footnote = {
|
||||
label: ast.identifier,
|
||||
reference: footnoteReference,
|
||||
};
|
||||
return [{ insert: ' ', attributes: { footnote } }];
|
||||
} catch (error) {
|
||||
console.warn('Error parsing footnote reference', error);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const MarkdownInlineToDeltaAdapterExtensions = [
|
||||
markdownTextToDeltaMatcher,
|
||||
markdownInlineCodeToDeltaMatcher,
|
||||
markdownStrongToDeltaMatcher,
|
||||
markdownEmphasisToDeltaMatcher,
|
||||
markdownDeleteToDeltaMatcher,
|
||||
markdownLinkToDeltaMatcher,
|
||||
markdownInlineMathToDeltaMatcher,
|
||||
markdownListToDeltaMatcher,
|
||||
markdownFootnoteReferenceToDeltaMatcher,
|
||||
];
|
||||
@@ -0,0 +1,258 @@
|
||||
import { notionHtmlLinkElementToDeltaMatcher } from '@blocksuite/affine-inline-link';
|
||||
import {
|
||||
HastUtils,
|
||||
type HtmlAST,
|
||||
NotionHtmlASTToDeltaExtension,
|
||||
} from '@blocksuite/affine-shared/adapters';
|
||||
import type { ExtensionType } from '@blocksuite/store';
|
||||
import { collapseWhiteSpace } from 'collapse-white-space';
|
||||
import type { Element, Text } from 'hast';
|
||||
|
||||
const isElement = (ast: HtmlAST): ast is Element => {
|
||||
return ast.type === 'element';
|
||||
};
|
||||
|
||||
const isText = (ast: HtmlAST): ast is Text => {
|
||||
return ast.type === 'text';
|
||||
};
|
||||
|
||||
const listElementTags = new Set(['ol', 'ul']);
|
||||
const strongElementTags = new Set(['strong', 'b']);
|
||||
const italicElementTags = new Set(['i', 'em']);
|
||||
|
||||
const NotionInlineEquationToken = 'notion-text-equation-token';
|
||||
const NotionUnderlineStyleToken = 'border-bottom:0.05em solid';
|
||||
|
||||
export const notionHtmlTextToDeltaMatcher = NotionHtmlASTToDeltaExtension({
|
||||
name: 'text',
|
||||
match: ast => isText(ast),
|
||||
toDelta: (ast, context) => {
|
||||
if (!isText(ast)) {
|
||||
return [];
|
||||
}
|
||||
const { options } = context;
|
||||
options.trim ??= true;
|
||||
if (options.pre || ast.value === ' ') {
|
||||
return [{ insert: ast.value }];
|
||||
}
|
||||
if (options.trim) {
|
||||
const value = collapseWhiteSpace(ast.value, { trim: options.trim });
|
||||
if (value) {
|
||||
return [{ insert: value }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (ast.value) {
|
||||
return [{ insert: collapseWhiteSpace(ast.value) }];
|
||||
}
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlSpanElementToDeltaMatcher =
|
||||
NotionHtmlASTToDeltaExtension({
|
||||
name: 'span-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'span',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const { toDelta, options } = context;
|
||||
if (
|
||||
Array.isArray(ast.properties?.className) &&
|
||||
ast.properties?.className.includes(NotionInlineEquationToken)
|
||||
) {
|
||||
const latex = HastUtils.getTextContent(
|
||||
HastUtils.querySelector(ast, 'annotation')
|
||||
);
|
||||
return [{ insert: ' ', attributes: { latex } }];
|
||||
}
|
||||
|
||||
// Add underline style detection
|
||||
if (
|
||||
typeof ast.properties?.style === 'string' &&
|
||||
ast.properties?.style?.includes(NotionUnderlineStyleToken)
|
||||
) {
|
||||
return ast.children.flatMap(child =>
|
||||
context.toDelta(child, options).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, underline: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return ast.children.flatMap(child => toDelta(child, options));
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlListToDeltaMatcher = NotionHtmlASTToDeltaExtension({
|
||||
name: 'list-element',
|
||||
match: ast => isElement(ast) && listElementTags.has(ast.tagName),
|
||||
toDelta: () => {
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlStrongElementToDeltaMatcher =
|
||||
NotionHtmlASTToDeltaExtension({
|
||||
name: 'strong-element',
|
||||
match: ast => isElement(ast) && strongElementTags.has(ast.tagName),
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const { toDelta, options } = context;
|
||||
return ast.children.flatMap(child =>
|
||||
toDelta(child, options).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, bold: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlItalicElementToDeltaMatcher =
|
||||
NotionHtmlASTToDeltaExtension({
|
||||
name: 'italic-element',
|
||||
match: ast => isElement(ast) && italicElementTags.has(ast.tagName),
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
const { toDelta, options } = context;
|
||||
return ast.children.flatMap(child =>
|
||||
toDelta(child, options).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, italic: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlCodeElementToDeltaMatcher =
|
||||
NotionHtmlASTToDeltaExtension({
|
||||
name: 'code-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'code',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
const { toDelta, options } = context;
|
||||
return ast.children.flatMap(child =>
|
||||
toDelta(child, options).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, code: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlDelElementToDeltaMatcher = NotionHtmlASTToDeltaExtension(
|
||||
{
|
||||
name: 'del-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'del',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
const { toDelta, options } = context;
|
||||
return ast.children.flatMap(child =>
|
||||
toDelta(child, options).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, strike: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export const notionHtmlUnderlineElementToDeltaMatcher =
|
||||
NotionHtmlASTToDeltaExtension({
|
||||
name: 'underline-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'u',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
const { toDelta, options } = context;
|
||||
return ast.children.flatMap(child =>
|
||||
toDelta(child, options).map(delta => {
|
||||
delta.attributes = { ...delta.attributes, underline: true };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlMarkElementToDeltaMatcher =
|
||||
NotionHtmlASTToDeltaExtension({
|
||||
name: 'mark-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'mark',
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast)) {
|
||||
return [];
|
||||
}
|
||||
const { toDelta, options } = context;
|
||||
return ast.children.flatMap(child =>
|
||||
toDelta(child, options).map(delta => {
|
||||
delta.attributes = { ...delta.attributes };
|
||||
return delta;
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlLiElementToDeltaMatcher = NotionHtmlASTToDeltaExtension({
|
||||
name: 'li-element',
|
||||
match: ast =>
|
||||
isElement(ast) &&
|
||||
ast.tagName === 'li' &&
|
||||
!!HastUtils.querySelector(ast, '.checkbox'),
|
||||
toDelta: (ast, context) => {
|
||||
if (!isElement(ast) || !HastUtils.querySelector(ast, '.checkbox')) {
|
||||
return [];
|
||||
}
|
||||
const { toDelta, options } = context;
|
||||
// Should ignore the children of to do list which is the checkbox and the space following it
|
||||
const checkBox = HastUtils.querySelector(ast, '.checkbox');
|
||||
const checkBoxIndex = ast.children.findIndex(child => child === checkBox);
|
||||
return ast.children
|
||||
.slice(checkBoxIndex + 2)
|
||||
.flatMap(child => toDelta(child, options));
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlBrElementToDeltaMatcher = NotionHtmlASTToDeltaExtension({
|
||||
name: 'br-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'br',
|
||||
toDelta: () => {
|
||||
return [{ insert: '\n' }];
|
||||
},
|
||||
});
|
||||
|
||||
export const notionHtmlStyleElementToDeltaMatcher =
|
||||
NotionHtmlASTToDeltaExtension({
|
||||
name: 'style-element',
|
||||
match: ast => isElement(ast) && ast.tagName === 'style',
|
||||
toDelta: () => {
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
export const NotionHtmlInlineToDeltaAdapterExtensions: ExtensionType[] = [
|
||||
notionHtmlTextToDeltaMatcher,
|
||||
notionHtmlSpanElementToDeltaMatcher,
|
||||
notionHtmlStrongElementToDeltaMatcher,
|
||||
notionHtmlItalicElementToDeltaMatcher,
|
||||
notionHtmlCodeElementToDeltaMatcher,
|
||||
notionHtmlDelElementToDeltaMatcher,
|
||||
notionHtmlUnderlineElementToDeltaMatcher,
|
||||
notionHtmlLinkElementToDeltaMatcher,
|
||||
notionHtmlMarkElementToDeltaMatcher,
|
||||
notionHtmlListToDeltaMatcher,
|
||||
notionHtmlLiElementToDeltaMatcher,
|
||||
notionHtmlBrElementToDeltaMatcher,
|
||||
notionHtmlStyleElementToDeltaMatcher,
|
||||
];
|
||||
@@ -0,0 +1,30 @@
|
||||
import { linkDeltaMarkdownAdapterMatch } from '@blocksuite/affine-inline-link';
|
||||
import { referenceDeltaMarkdownAdapterMatch } from '@blocksuite/affine-inline-reference';
|
||||
import {
|
||||
InlineDeltaToPlainTextAdapterExtension,
|
||||
type TextBuffer,
|
||||
} from '@blocksuite/affine-shared/adapters';
|
||||
import type { ExtensionType } from '@blocksuite/store';
|
||||
|
||||
export const latexDeltaMarkdownAdapterMatch =
|
||||
InlineDeltaToPlainTextAdapterExtension({
|
||||
name: 'inlineLatex',
|
||||
match: delta => !!delta.attributes?.latex,
|
||||
toAST: delta => {
|
||||
const node: TextBuffer = {
|
||||
content: delta.insert,
|
||||
};
|
||||
if (!delta.attributes?.latex) {
|
||||
return node;
|
||||
}
|
||||
return {
|
||||
content: delta.attributes?.latex,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const InlineDeltaToPlainTextAdapterExtensions: ExtensionType[] = [
|
||||
referenceDeltaMarkdownAdapterMatch,
|
||||
linkDeltaMarkdownAdapterMatch,
|
||||
latexDeltaMarkdownAdapterMatch,
|
||||
];
|
||||
138
blocksuite/affine/inlines/preset/src/command/config.ts
Normal file
138
blocksuite/affine/inlines/preset/src/command/config.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import {
|
||||
BoldIcon,
|
||||
CodeIcon,
|
||||
ItalicIcon,
|
||||
LinkIcon,
|
||||
StrikethroughIcon,
|
||||
UnderlineIcon,
|
||||
} from '@blocksuite/affine-components/icons';
|
||||
import { toggleLink } from '@blocksuite/affine-inline-link';
|
||||
import { type EditorHost, TextSelection } from '@blocksuite/block-std';
|
||||
import type { TemplateResult } from 'lit';
|
||||
|
||||
import {
|
||||
isTextStyleActive,
|
||||
toggleBold,
|
||||
toggleCode,
|
||||
toggleItalic,
|
||||
toggleStrike,
|
||||
toggleUnderline,
|
||||
} from './text-style.js';
|
||||
|
||||
export interface TextFormatConfig {
|
||||
id: string;
|
||||
name: string;
|
||||
icon: TemplateResult<1>;
|
||||
hotkey?: string;
|
||||
activeWhen: (host: EditorHost) => boolean;
|
||||
action: (host: EditorHost) => void;
|
||||
textChecker?: (host: EditorHost) => boolean;
|
||||
}
|
||||
|
||||
export const textFormatConfigs: TextFormatConfig[] = [
|
||||
{
|
||||
id: 'bold',
|
||||
name: 'Bold',
|
||||
icon: BoldIcon,
|
||||
hotkey: 'Mod-b',
|
||||
activeWhen: host => {
|
||||
const [result] = host.std.command
|
||||
.chain()
|
||||
.pipe(isTextStyleActive, { key: 'bold' })
|
||||
.run();
|
||||
return result;
|
||||
},
|
||||
action: host => {
|
||||
host.std.command.chain().pipe(toggleBold).run();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'italic',
|
||||
name: 'Italic',
|
||||
icon: ItalicIcon,
|
||||
hotkey: 'Mod-i',
|
||||
activeWhen: host => {
|
||||
const [result] = host.std.command
|
||||
.chain()
|
||||
.pipe(isTextStyleActive, { key: 'italic' })
|
||||
.run();
|
||||
return result;
|
||||
},
|
||||
action: host => {
|
||||
host.std.command.chain().pipe(toggleItalic).run();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'underline',
|
||||
name: 'Underline',
|
||||
icon: UnderlineIcon,
|
||||
hotkey: 'Mod-u',
|
||||
activeWhen: host => {
|
||||
const [result] = host.std.command
|
||||
.chain()
|
||||
.pipe(isTextStyleActive, { key: 'underline' })
|
||||
.run();
|
||||
return result;
|
||||
},
|
||||
action: host => {
|
||||
host.std.command.chain().pipe(toggleUnderline).run();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'strike',
|
||||
name: 'Strikethrough',
|
||||
icon: StrikethroughIcon,
|
||||
hotkey: 'Mod-shift-s',
|
||||
activeWhen: host => {
|
||||
const [result] = host.std.command
|
||||
.chain()
|
||||
.pipe(isTextStyleActive, { key: 'strike' })
|
||||
.run();
|
||||
return result;
|
||||
},
|
||||
action: host => {
|
||||
host.std.command.chain().pipe(toggleStrike).run();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'code',
|
||||
name: 'Code',
|
||||
icon: CodeIcon,
|
||||
hotkey: 'Mod-e',
|
||||
activeWhen: host => {
|
||||
const [result] = host.std.command
|
||||
.chain()
|
||||
.pipe(isTextStyleActive, { key: 'code' })
|
||||
.run();
|
||||
return result;
|
||||
},
|
||||
action: host => {
|
||||
host.std.command.chain().pipe(toggleCode).run();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'link',
|
||||
name: 'Link',
|
||||
icon: LinkIcon,
|
||||
hotkey: 'Mod-k',
|
||||
activeWhen: host => {
|
||||
const [result] = host.std.command
|
||||
.chain()
|
||||
.pipe(isTextStyleActive, { key: 'link' })
|
||||
.run();
|
||||
return result;
|
||||
},
|
||||
action: host => {
|
||||
host.std.command.chain().pipe(toggleLink).run();
|
||||
},
|
||||
// should check text length
|
||||
textChecker: host => {
|
||||
const textSelection = host.std.selection.find(TextSelection);
|
||||
if (!textSelection || textSelection.isCollapsed()) return false;
|
||||
|
||||
return Boolean(
|
||||
textSelection.from.length + (textSelection.to?.length ?? 0)
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
19
blocksuite/affine/inlines/preset/src/command/consts.ts
Normal file
19
blocksuite/affine/inlines/preset/src/command/consts.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
// corresponding to `formatText` command
|
||||
import { TableModelFlavour } from '@blocksuite/affine-model';
|
||||
|
||||
export const FORMAT_TEXT_SUPPORT_FLAVOURS = [
|
||||
'affine:paragraph',
|
||||
'affine:list',
|
||||
'affine:code',
|
||||
];
|
||||
// corresponding to `formatBlock` command
|
||||
export const FORMAT_BLOCK_SUPPORT_FLAVOURS = [
|
||||
'affine:paragraph',
|
||||
'affine:list',
|
||||
'affine:code',
|
||||
];
|
||||
// corresponding to `formatNative` command
|
||||
export const FORMAT_NATIVE_SUPPORT_FLAVOURS = [
|
||||
'affine:database',
|
||||
TableModelFlavour,
|
||||
];
|
||||
81
blocksuite/affine/inlines/preset/src/command/delete-text.ts
Normal file
81
blocksuite/affine/inlines/preset/src/command/delete-text.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { RootBlockModel } from '@blocksuite/affine-model';
|
||||
import { matchModels } from '@blocksuite/affine-shared/utils';
|
||||
import { type Command, TextSelection } from '@blocksuite/block-std';
|
||||
import type { Text } from '@blocksuite/store';
|
||||
|
||||
export const deleteTextCommand: Command<{
|
||||
currentTextSelection?: TextSelection;
|
||||
textSelection?: TextSelection;
|
||||
}> = (ctx, next) => {
|
||||
const textSelection = ctx.textSelection ?? ctx.currentTextSelection;
|
||||
if (!textSelection) return;
|
||||
|
||||
const range = ctx.std.range.textSelectionToRange(textSelection);
|
||||
if (!range) return;
|
||||
const selectedElements = ctx.std.range.getSelectedBlockComponentsByRange(
|
||||
range,
|
||||
{
|
||||
mode: 'flat',
|
||||
}
|
||||
);
|
||||
|
||||
const { from, to } = textSelection;
|
||||
|
||||
const fromElement = selectedElements.find(el => from.blockId === el.blockId);
|
||||
if (!fromElement) return;
|
||||
|
||||
let fromText: Text | undefined;
|
||||
if (matchModels(fromElement.model, [RootBlockModel])) {
|
||||
fromText = fromElement.model.props.title;
|
||||
} else {
|
||||
fromText = fromElement.model.text;
|
||||
}
|
||||
if (!fromText) return;
|
||||
if (!to) {
|
||||
fromText.delete(from.index, from.length);
|
||||
ctx.std.selection.setGroup('note', [
|
||||
ctx.std.selection.create(TextSelection, {
|
||||
from: {
|
||||
blockId: from.blockId,
|
||||
index: from.index,
|
||||
length: 0,
|
||||
},
|
||||
to: null,
|
||||
}),
|
||||
]);
|
||||
return next();
|
||||
}
|
||||
|
||||
const toElement = selectedElements.find(el => to.blockId === el.blockId);
|
||||
if (!toElement) return;
|
||||
|
||||
const toText = toElement.model.text;
|
||||
if (!toText) return;
|
||||
|
||||
fromText.delete(from.index, from.length);
|
||||
toText.delete(0, to.length);
|
||||
|
||||
fromText.join(toText);
|
||||
|
||||
selectedElements
|
||||
.filter(el => el.model.id !== fromElement.model.id)
|
||||
.forEach(el => {
|
||||
ctx.std.store.deleteBlock(el.model, {
|
||||
bringChildrenTo:
|
||||
el.model.id === toElement.model.id ? fromElement.model : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
ctx.std.selection.setGroup('note', [
|
||||
ctx.std.selection.create(TextSelection, {
|
||||
from: {
|
||||
blockId: from.blockId,
|
||||
index: from.index,
|
||||
length: 0,
|
||||
},
|
||||
to: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
next();
|
||||
};
|
||||
75
blocksuite/affine/inlines/preset/src/command/format-block.ts
Normal file
75
blocksuite/affine/inlines/preset/src/command/format-block.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { getSelectedBlocksCommand } from '@blocksuite/affine-shared/commands';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import type { BlockSelection, Command } from '@blocksuite/block-std';
|
||||
import {
|
||||
INLINE_ROOT_ATTR,
|
||||
type InlineRootElement,
|
||||
} from '@blocksuite/block-std/inline';
|
||||
|
||||
import { FORMAT_BLOCK_SUPPORT_FLAVOURS } from './consts.js';
|
||||
|
||||
// for block selection
|
||||
export const formatBlockCommand: Command<{
|
||||
currentBlockSelections?: BlockSelection[];
|
||||
blockSelections?: BlockSelection[];
|
||||
styles: AffineTextAttributes;
|
||||
mode?: 'replace' | 'merge';
|
||||
}> = (ctx, next) => {
|
||||
const blockSelections = ctx.blockSelections ?? ctx.currentBlockSelections;
|
||||
if (!blockSelections) {
|
||||
console.error(
|
||||
'`blockSelections` is required, you need to pass it in args or use `getBlockSelections` command before adding this command to the pipeline.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (blockSelections.length === 0) return;
|
||||
|
||||
const styles = ctx.styles;
|
||||
const mode = ctx.mode ?? 'merge';
|
||||
|
||||
const success = ctx.std.command
|
||||
.chain()
|
||||
.pipe(getSelectedBlocksCommand, {
|
||||
blockSelections,
|
||||
filter: el => FORMAT_BLOCK_SUPPORT_FLAVOURS.includes(el.model.flavour),
|
||||
types: ['block'],
|
||||
})
|
||||
.pipe((ctx, next) => {
|
||||
const { selectedBlocks } = ctx;
|
||||
if (!selectedBlocks) {
|
||||
console.error(
|
||||
'`selectedBlocks` is required, you need to pass it in args or use `getSelectedBlocksCommand` command before adding this command to the pipeline.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedInlineEditors = selectedBlocks.flatMap(el => {
|
||||
const inlineRoot = el.querySelector<
|
||||
InlineRootElement<AffineTextAttributes>
|
||||
>(`[${INLINE_ROOT_ATTR}]`);
|
||||
if (inlineRoot) {
|
||||
return inlineRoot.inlineEditor;
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
selectedInlineEditors.forEach(inlineEditor => {
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: 0,
|
||||
length: inlineEditor.yTextLength,
|
||||
},
|
||||
styles,
|
||||
{
|
||||
mode,
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
next();
|
||||
})
|
||||
.run();
|
||||
|
||||
if (success) next();
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import {
|
||||
BLOCK_ID_ATTR,
|
||||
type BlockComponent,
|
||||
type Command,
|
||||
} from '@blocksuite/block-std';
|
||||
import {
|
||||
INLINE_ROOT_ATTR,
|
||||
type InlineRootElement,
|
||||
} from '@blocksuite/block-std/inline';
|
||||
|
||||
import { FORMAT_NATIVE_SUPPORT_FLAVOURS } from './consts.js';
|
||||
|
||||
// for native range
|
||||
export const formatNativeCommand: Command<{
|
||||
range?: Range;
|
||||
styles: AffineTextAttributes;
|
||||
mode?: 'replace' | 'merge';
|
||||
}> = (ctx, next) => {
|
||||
const { styles, mode = 'merge' } = ctx;
|
||||
|
||||
let range = ctx.range;
|
||||
if (!range) {
|
||||
const selection = document.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return;
|
||||
range = selection.getRangeAt(0);
|
||||
}
|
||||
if (!range) return;
|
||||
|
||||
const selectedInlineEditors = Array.from<InlineRootElement>(
|
||||
ctx.std.host.querySelectorAll(`[${INLINE_ROOT_ATTR}]`)
|
||||
)
|
||||
.filter(el => range?.intersectsNode(el))
|
||||
.filter(el => {
|
||||
const block = el.closest<BlockComponent>(`[${BLOCK_ID_ATTR}]`);
|
||||
if (block) {
|
||||
return FORMAT_NATIVE_SUPPORT_FLAVOURS.includes(block.model.flavour);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.map(el => el.inlineEditor);
|
||||
|
||||
selectedInlineEditors.forEach(inlineEditor => {
|
||||
const inlineRange = inlineEditor.getInlineRange();
|
||||
if (!inlineRange) return;
|
||||
|
||||
inlineEditor.formatText(inlineRange, styles, {
|
||||
mode,
|
||||
});
|
||||
});
|
||||
|
||||
next();
|
||||
};
|
||||
91
blocksuite/affine/inlines/preset/src/command/format-text.ts
Normal file
91
blocksuite/affine/inlines/preset/src/command/format-text.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { clearMarksOnDiscontinuousInput } from '@blocksuite/affine-rich-text';
|
||||
import { getSelectedBlocksCommand } from '@blocksuite/affine-shared/commands';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import type { Command, TextSelection } from '@blocksuite/block-std';
|
||||
import {
|
||||
INLINE_ROOT_ATTR,
|
||||
type InlineRootElement,
|
||||
} from '@blocksuite/block-std/inline';
|
||||
|
||||
import { FORMAT_TEXT_SUPPORT_FLAVOURS } from './consts.js';
|
||||
|
||||
// for text selection
|
||||
export const formatTextCommand: Command<{
|
||||
currentTextSelection?: TextSelection;
|
||||
textSelection?: TextSelection;
|
||||
styles: AffineTextAttributes;
|
||||
mode?: 'replace' | 'merge';
|
||||
}> = (ctx, next) => {
|
||||
const { styles, mode = 'merge' } = ctx;
|
||||
|
||||
const textSelection = ctx.textSelection ?? ctx.currentTextSelection;
|
||||
if (!textSelection) return;
|
||||
|
||||
const success = ctx.std.command
|
||||
.chain()
|
||||
.pipe(getSelectedBlocksCommand, {
|
||||
textSelection,
|
||||
filter: el => FORMAT_TEXT_SUPPORT_FLAVOURS.includes(el.model.flavour),
|
||||
types: ['text'],
|
||||
})
|
||||
.pipe((ctx, next) => {
|
||||
const { selectedBlocks } = ctx;
|
||||
if (!selectedBlocks) return;
|
||||
|
||||
const selectedInlineEditors = selectedBlocks.flatMap(el => {
|
||||
const inlineRoot = el.querySelector<
|
||||
InlineRootElement<AffineTextAttributes>
|
||||
>(`[${INLINE_ROOT_ATTR}]`);
|
||||
if (inlineRoot && inlineRoot.inlineEditor.getInlineRange()) {
|
||||
return inlineRoot.inlineEditor;
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
selectedInlineEditors.forEach(inlineEditor => {
|
||||
const inlineRange = inlineEditor.getInlineRange();
|
||||
if (!inlineRange) return;
|
||||
|
||||
if (inlineRange.length === 0) {
|
||||
const delta = inlineEditor.getDeltaByRangeIndex(inlineRange.index);
|
||||
|
||||
inlineEditor.setMarks({
|
||||
...inlineEditor.marks,
|
||||
...Object.fromEntries(
|
||||
Object.entries(styles).map(([key, value]) => {
|
||||
if (typeof value === 'boolean') {
|
||||
return [
|
||||
key,
|
||||
(inlineEditor.marks &&
|
||||
inlineEditor.marks[key as keyof AffineTextAttributes]) ||
|
||||
(delta &&
|
||||
delta.attributes &&
|
||||
delta.attributes[key as keyof AffineTextAttributes])
|
||||
? null
|
||||
: value,
|
||||
];
|
||||
}
|
||||
return [key, value];
|
||||
})
|
||||
),
|
||||
});
|
||||
clearMarksOnDiscontinuousInput(inlineEditor);
|
||||
} else {
|
||||
inlineEditor.formatText(inlineRange, styles, {
|
||||
mode,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Promise.all(selectedBlocks.map(el => el.updateComplete))
|
||||
.then(() => {
|
||||
ctx.std.range.syncTextSelectionToRange(textSelection);
|
||||
})
|
||||
.catch(console.error);
|
||||
|
||||
next();
|
||||
})
|
||||
.run();
|
||||
|
||||
if (success) next();
|
||||
};
|
||||
23
blocksuite/affine/inlines/preset/src/command/index.ts
Normal file
23
blocksuite/affine/inlines/preset/src/command/index.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
export type { TextFormatConfig } from './config.js';
|
||||
export { textFormatConfigs } from './config.js';
|
||||
export {
|
||||
FORMAT_BLOCK_SUPPORT_FLAVOURS,
|
||||
FORMAT_NATIVE_SUPPORT_FLAVOURS,
|
||||
FORMAT_TEXT_SUPPORT_FLAVOURS,
|
||||
} from './consts.js';
|
||||
export { deleteTextCommand } from './delete-text.js';
|
||||
export { formatBlockCommand } from './format-block.js';
|
||||
export { formatNativeCommand } from './format-native.js';
|
||||
export { formatTextCommand } from './format-text.js';
|
||||
export { insertInlineLatex } from './insert-inline-latex.js';
|
||||
export {
|
||||
getTextStyle,
|
||||
isTextStyleActive,
|
||||
toggleBold,
|
||||
toggleCode,
|
||||
toggleItalic,
|
||||
toggleStrike,
|
||||
toggleTextStyleCommand,
|
||||
toggleUnderline,
|
||||
} from './text-style.js';
|
||||
export { isFormatSupported } from './utils.js';
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { Command, TextSelection } from '@blocksuite/block-std';
|
||||
|
||||
export const insertInlineLatex: Command<{
|
||||
currentTextSelection?: TextSelection;
|
||||
textSelection?: TextSelection;
|
||||
}> = (ctx, next) => {
|
||||
const textSelection = ctx.textSelection ?? ctx.currentTextSelection;
|
||||
if (!textSelection || !textSelection.isCollapsed()) return;
|
||||
|
||||
const blockComponent = ctx.std.view.getBlock(textSelection.from.blockId);
|
||||
if (!blockComponent) return;
|
||||
|
||||
const richText = blockComponent.querySelector('rich-text');
|
||||
if (!richText) return;
|
||||
|
||||
const inlineEditor = richText.inlineEditor;
|
||||
if (!inlineEditor) return;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: textSelection.from.index,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: textSelection.from.index,
|
||||
length: 1,
|
||||
},
|
||||
{
|
||||
latex: '',
|
||||
}
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: textSelection.from.index,
|
||||
length: 1,
|
||||
});
|
||||
|
||||
inlineEditor
|
||||
.waitForUpdate()
|
||||
.then(async () => {
|
||||
await inlineEditor.waitForUpdate();
|
||||
|
||||
const textPoint = inlineEditor.getTextPoint(textSelection.from.index + 1);
|
||||
if (!textPoint) return;
|
||||
const [text] = textPoint;
|
||||
const latexNode = text.parentElement?.closest('affine-latex-node');
|
||||
if (!latexNode) return;
|
||||
latexNode.toggleEditor();
|
||||
})
|
||||
.catch(console.error);
|
||||
|
||||
next();
|
||||
};
|
||||
105
blocksuite/affine/inlines/preset/src/command/text-style.ts
Normal file
105
blocksuite/affine/inlines/preset/src/command/text-style.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import {
|
||||
getBlockSelectionsCommand,
|
||||
getTextSelectionCommand,
|
||||
} from '@blocksuite/affine-shared/commands';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import type { Command } from '@blocksuite/block-std';
|
||||
|
||||
import { formatBlockCommand } from './format-block.js';
|
||||
import { formatNativeCommand } from './format-native.js';
|
||||
import { formatTextCommand } from './format-text.js';
|
||||
import { getCombinedTextStyle } from './utils.js';
|
||||
|
||||
export const toggleTextStyleCommand: Command<{
|
||||
key: Extract<
|
||||
keyof AffineTextAttributes,
|
||||
'bold' | 'italic' | 'underline' | 'strike' | 'code'
|
||||
>;
|
||||
}> = (ctx, next) => {
|
||||
const { std, key } = ctx;
|
||||
const [active] = std.command.chain().pipe(isTextStyleActive, { key }).run();
|
||||
|
||||
const payload: {
|
||||
styles: AffineTextAttributes;
|
||||
mode?: 'replace' | 'merge';
|
||||
} = {
|
||||
styles: {
|
||||
[key]: active ? null : true,
|
||||
},
|
||||
};
|
||||
|
||||
const [result] = std.command
|
||||
.chain()
|
||||
.try(chain => [
|
||||
chain.pipe(getTextSelectionCommand).pipe(formatTextCommand, payload),
|
||||
chain.pipe(getBlockSelectionsCommand).pipe(formatBlockCommand, payload),
|
||||
chain.pipe(formatNativeCommand, payload),
|
||||
])
|
||||
.run();
|
||||
|
||||
if (result) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const toggleTextStyleCommandWrapper = (
|
||||
key: Extract<
|
||||
keyof AffineTextAttributes,
|
||||
'bold' | 'italic' | 'underline' | 'strike' | 'code'
|
||||
>
|
||||
): Command => {
|
||||
return (ctx, next) => {
|
||||
const [success] = ctx.std.command
|
||||
.chain()
|
||||
.pipe(toggleTextStyleCommand, { key })
|
||||
.run();
|
||||
if (success) next();
|
||||
return false;
|
||||
};
|
||||
};
|
||||
|
||||
export const toggleBold = toggleTextStyleCommandWrapper('bold');
|
||||
export const toggleItalic = toggleTextStyleCommandWrapper('italic');
|
||||
export const toggleUnderline = toggleTextStyleCommandWrapper('underline');
|
||||
export const toggleStrike = toggleTextStyleCommandWrapper('strike');
|
||||
export const toggleCode = toggleTextStyleCommandWrapper('code');
|
||||
|
||||
export const getTextStyle: Command<{}, { textStyle: AffineTextAttributes }> = (
|
||||
ctx,
|
||||
next
|
||||
) => {
|
||||
const [result, innerCtx] = getCombinedTextStyle(
|
||||
ctx.std.command.chain()
|
||||
).run();
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return next({ textStyle: innerCtx.textStyle });
|
||||
};
|
||||
|
||||
export const isTextStyleActive: Command<{ key: keyof AffineTextAttributes }> = (
|
||||
ctx,
|
||||
next
|
||||
) => {
|
||||
const key = ctx.key;
|
||||
const [result] = getCombinedTextStyle(ctx.std.command.chain())
|
||||
.pipe((ctx, next) => {
|
||||
const { textStyle } = ctx;
|
||||
|
||||
if (textStyle && key in textStyle) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return false;
|
||||
})
|
||||
.run();
|
||||
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return next();
|
||||
};
|
||||
209
blocksuite/affine/inlines/preset/src/command/utils.ts
Normal file
209
blocksuite/affine/inlines/preset/src/command/utils.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
import {
|
||||
getBlockSelectionsCommand,
|
||||
getSelectedBlocksCommand,
|
||||
getTextSelectionCommand,
|
||||
} from '@blocksuite/affine-shared/commands';
|
||||
import type {
|
||||
AffineInlineEditor,
|
||||
AffineTextAttributes,
|
||||
} from '@blocksuite/affine-shared/types';
|
||||
import {
|
||||
BLOCK_ID_ATTR,
|
||||
type BlockComponent,
|
||||
type Chain,
|
||||
type InitCommandCtx,
|
||||
} from '@blocksuite/block-std';
|
||||
import {
|
||||
INLINE_ROOT_ATTR,
|
||||
type InlineEditor,
|
||||
type InlineRange,
|
||||
type InlineRootElement,
|
||||
} from '@blocksuite/block-std/inline';
|
||||
|
||||
import {
|
||||
FORMAT_BLOCK_SUPPORT_FLAVOURS,
|
||||
FORMAT_NATIVE_SUPPORT_FLAVOURS,
|
||||
FORMAT_TEXT_SUPPORT_FLAVOURS,
|
||||
} from './consts.js';
|
||||
|
||||
function getCombinedFormatFromInlineEditors(
|
||||
inlineEditors: [AffineInlineEditor, InlineRange | null][]
|
||||
): AffineTextAttributes {
|
||||
const formatArr: AffineTextAttributes[] = [];
|
||||
inlineEditors.forEach(([inlineEditor, inlineRange]) => {
|
||||
if (!inlineRange) return;
|
||||
|
||||
const format = inlineEditor.getFormat(inlineRange);
|
||||
formatArr.push(format);
|
||||
});
|
||||
|
||||
if (formatArr.length === 0) return {};
|
||||
|
||||
// format will be active only when all inline editors have the same format.
|
||||
return formatArr.reduce((acc, cur) => {
|
||||
const newFormat: AffineTextAttributes = {};
|
||||
for (const key in acc) {
|
||||
const typedKey = key as keyof AffineTextAttributes;
|
||||
if (acc[typedKey] === cur[typedKey]) {
|
||||
// This cast is secure because we have checked that the value of the key is the same.
|
||||
|
||||
newFormat[typedKey] = acc[typedKey] as any;
|
||||
}
|
||||
}
|
||||
return newFormat;
|
||||
});
|
||||
}
|
||||
|
||||
function getSelectedInlineEditors(
|
||||
blocks: BlockComponent[],
|
||||
filter: (
|
||||
inlineRoot: InlineRootElement<AffineTextAttributes>
|
||||
) => InlineEditor<AffineTextAttributes> | []
|
||||
) {
|
||||
return blocks.flatMap(el => {
|
||||
const inlineRoot = el.querySelector<
|
||||
InlineRootElement<AffineTextAttributes>
|
||||
>(`[${INLINE_ROOT_ATTR}]`);
|
||||
|
||||
if (inlineRoot) {
|
||||
return filter(inlineRoot);
|
||||
}
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
function handleCurrentSelection(
|
||||
chain: Chain<InitCommandCtx>,
|
||||
handler: (
|
||||
type: 'text' | 'block' | 'native',
|
||||
inlineEditors: InlineEditor<AffineTextAttributes>[]
|
||||
) => { textStyle: AffineTextAttributes } | boolean | void
|
||||
): Chain<InitCommandCtx & { textStyle: AffineTextAttributes }> {
|
||||
return chain.try(chain => [
|
||||
// text selection, corresponding to `formatText` command
|
||||
chain
|
||||
.pipe(getTextSelectionCommand)
|
||||
.pipe(getSelectedBlocksCommand, {
|
||||
types: ['text'],
|
||||
filter: el => FORMAT_TEXT_SUPPORT_FLAVOURS.includes(el.model.flavour),
|
||||
})
|
||||
.pipe((ctx, next) => {
|
||||
const { selectedBlocks } = ctx;
|
||||
if (!selectedBlocks) {
|
||||
console.error(
|
||||
'`selectedBlocks` is required, you need to pass it in args or use `getSelectedBlocksCommand` command before adding this command to the pipeline.'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const selectedInlineEditors = getSelectedInlineEditors(
|
||||
selectedBlocks,
|
||||
inlineRoot => {
|
||||
const inlineRange = inlineRoot.inlineEditor.getInlineRange();
|
||||
if (!inlineRange) return [];
|
||||
return inlineRoot.inlineEditor;
|
||||
}
|
||||
);
|
||||
|
||||
const result = handler('text', selectedInlineEditors);
|
||||
if (!result) return false;
|
||||
if (result === true) {
|
||||
return next();
|
||||
}
|
||||
return next(result);
|
||||
}),
|
||||
// block selection, corresponding to `formatBlock` command
|
||||
chain
|
||||
.pipe(getBlockSelectionsCommand)
|
||||
.pipe(getSelectedBlocksCommand, {
|
||||
types: ['block'],
|
||||
filter: el => FORMAT_BLOCK_SUPPORT_FLAVOURS.includes(el.model.flavour),
|
||||
})
|
||||
.pipe((ctx, next) => {
|
||||
const { selectedBlocks } = ctx;
|
||||
if (!selectedBlocks) {
|
||||
console.error(
|
||||
'`selectedBlocks` is required, you need to pass it in args or use `getSelectedBlocksCommand` command before adding this command to the pipeline.'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const selectedInlineEditors = getSelectedInlineEditors(
|
||||
selectedBlocks,
|
||||
inlineRoot =>
|
||||
inlineRoot.inlineEditor.yTextLength > 0
|
||||
? inlineRoot.inlineEditor
|
||||
: []
|
||||
);
|
||||
|
||||
const result = handler('block', selectedInlineEditors);
|
||||
if (!result) return false;
|
||||
if (result === true) {
|
||||
return next();
|
||||
}
|
||||
return next(result);
|
||||
}),
|
||||
// native selection, corresponding to `formatNative` command
|
||||
chain.pipe((ctx, next) => {
|
||||
const selectedInlineEditors = Array.from<InlineRootElement>(
|
||||
ctx.std.host.querySelectorAll(`[${INLINE_ROOT_ATTR}]`)
|
||||
)
|
||||
.filter(el => {
|
||||
const selection = document.getSelection();
|
||||
if (!selection || selection.rangeCount === 0) return false;
|
||||
const range = selection.getRangeAt(0);
|
||||
|
||||
return range.intersectsNode(el);
|
||||
})
|
||||
.filter(el => {
|
||||
const block = el.closest<BlockComponent>(`[${BLOCK_ID_ATTR}]`);
|
||||
if (block) {
|
||||
return FORMAT_NATIVE_SUPPORT_FLAVOURS.includes(block.model.flavour);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.map((el): AffineInlineEditor => el.inlineEditor);
|
||||
|
||||
const result = handler('native', selectedInlineEditors);
|
||||
if (!result) return false;
|
||||
if (result === true) {
|
||||
return next();
|
||||
}
|
||||
return next(result);
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
export function getCombinedTextStyle(chain: Chain<InitCommandCtx>) {
|
||||
return handleCurrentSelection(chain, (type, inlineEditors) => {
|
||||
if (type === 'text') {
|
||||
return {
|
||||
textStyle: getCombinedFormatFromInlineEditors(
|
||||
inlineEditors.map(e => [e, e.getInlineRange()])
|
||||
),
|
||||
};
|
||||
}
|
||||
if (type === 'block') {
|
||||
return {
|
||||
textStyle: getCombinedFormatFromInlineEditors(
|
||||
inlineEditors.map(e => [e, { index: 0, length: e.yTextLength }])
|
||||
),
|
||||
};
|
||||
}
|
||||
if (type === 'native') {
|
||||
return {
|
||||
textStyle: getCombinedFormatFromInlineEditors(
|
||||
inlineEditors.map(e => [e, e.getInlineRange()])
|
||||
),
|
||||
};
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
export function isFormatSupported(chain: Chain<InitCommandCtx>) {
|
||||
return handleCurrentSelection(
|
||||
chain,
|
||||
(_type, inlineEditors) => inlineEditors.length > 0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { LinkInlineSpecExtension } from '@blocksuite/affine-inline-link';
|
||||
import { ReferenceInlineSpecExtension } from '@blocksuite/affine-inline-reference';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import { InlineManagerExtension } from '@blocksuite/block-std/inline';
|
||||
|
||||
import {
|
||||
BackgroundInlineSpecExtension,
|
||||
BoldInlineSpecExtension,
|
||||
CodeInlineSpecExtension,
|
||||
ColorInlineSpecExtension,
|
||||
FootNoteInlineSpecExtension,
|
||||
ItalicInlineSpecExtension,
|
||||
LatexInlineSpecExtension,
|
||||
StrikeInlineSpecExtension,
|
||||
UnderlineInlineSpecExtension,
|
||||
} from './inline-spec';
|
||||
|
||||
export const DefaultInlineManagerExtension =
|
||||
InlineManagerExtension<AffineTextAttributes>({
|
||||
id: 'DefaultInlineManager',
|
||||
specs: [
|
||||
BoldInlineSpecExtension.identifier,
|
||||
ItalicInlineSpecExtension.identifier,
|
||||
UnderlineInlineSpecExtension.identifier,
|
||||
StrikeInlineSpecExtension.identifier,
|
||||
CodeInlineSpecExtension.identifier,
|
||||
BackgroundInlineSpecExtension.identifier,
|
||||
ColorInlineSpecExtension.identifier,
|
||||
LatexInlineSpecExtension.identifier,
|
||||
ReferenceInlineSpecExtension.identifier,
|
||||
LinkInlineSpecExtension.identifier,
|
||||
FootNoteInlineSpecExtension.identifier,
|
||||
],
|
||||
});
|
||||
29
blocksuite/affine/inlines/preset/src/effects.ts
Normal file
29
blocksuite/affine/inlines/preset/src/effects.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { AffineText } from './nodes/affine-text';
|
||||
import { AffineFootnoteNode } from './nodes/footnote-node/footnote-node';
|
||||
import { FootNotePopup } from './nodes/footnote-node/footnote-popup';
|
||||
import { FootNotePopupChip } from './nodes/footnote-node/footnote-popup-chip';
|
||||
import { LatexEditorMenu } from './nodes/latex-node/latex-editor-menu';
|
||||
import { LatexEditorUnit } from './nodes/latex-node/latex-editor-unit';
|
||||
import { AffineLatexNode } from './nodes/latex-node/latex-node';
|
||||
|
||||
export function effects() {
|
||||
customElements.define('affine-text', AffineText);
|
||||
customElements.define('latex-editor-menu', LatexEditorMenu);
|
||||
customElements.define('latex-editor-unit', LatexEditorUnit);
|
||||
customElements.define('affine-latex-node', AffineLatexNode);
|
||||
customElements.define('affine-footnote-node', AffineFootnoteNode);
|
||||
customElements.define('footnote-popup', FootNotePopup);
|
||||
customElements.define('footnote-popup-chip', FootNotePopupChip);
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'affine-latex-node': AffineLatexNode;
|
||||
'affine-footnote-node': AffineFootnoteNode;
|
||||
'footnote-popup': FootNotePopup;
|
||||
'footnote-popup-chip': FootNotePopupChip;
|
||||
'affine-text': AffineText;
|
||||
'latex-editor-unit': LatexEditorUnit;
|
||||
'latex-editor-menu': LatexEditorMenu;
|
||||
}
|
||||
}
|
||||
13
blocksuite/affine/inlines/preset/src/exts.ts
Normal file
13
blocksuite/affine/inlines/preset/src/exts.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { InlineAdapterExtensions } from './adapters/extensions';
|
||||
import { DefaultInlineManagerExtension } from './default-inline-manager';
|
||||
import { InlineSpecExtensions } from './inline-spec';
|
||||
import { MarkdownExtensions } from './markdown';
|
||||
import { LatexEditorInlineManagerExtension } from './nodes/latex-node/latex-editor-menu';
|
||||
|
||||
export const inlinePresetExtensions = [
|
||||
DefaultInlineManagerExtension,
|
||||
...MarkdownExtensions,
|
||||
LatexEditorInlineManagerExtension,
|
||||
...InlineSpecExtensions,
|
||||
...InlineAdapterExtensions,
|
||||
];
|
||||
12
blocksuite/affine/inlines/preset/src/index.ts
Normal file
12
blocksuite/affine/inlines/preset/src/index.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type * as RichTextEffects from '@blocksuite/affine-rich-text/effects';
|
||||
|
||||
declare type _GLOBAL_ = typeof RichTextEffects;
|
||||
|
||||
export * from './adapters/extensions';
|
||||
export * from './command';
|
||||
export * from './default-inline-manager';
|
||||
export * from './exts';
|
||||
export * from './inline-spec';
|
||||
export * from './keymap';
|
||||
export * from './markdown';
|
||||
export * from './nodes';
|
||||
168
blocksuite/affine/inlines/preset/src/inline-spec.ts
Normal file
168
blocksuite/affine/inlines/preset/src/inline-spec.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { inlineLinkExtensions } from '@blocksuite/affine-inline-link';
|
||||
import { inlineReferenceExtensions } from '@blocksuite/affine-inline-reference';
|
||||
import { FootNoteSchema } from '@blocksuite/affine-model';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import { StdIdentifier } from '@blocksuite/block-std';
|
||||
import {
|
||||
type InlineRootElement,
|
||||
InlineSpecExtension,
|
||||
} from '@blocksuite/block-std/inline';
|
||||
import type { ExtensionType } from '@blocksuite/store';
|
||||
import { html } from 'lit';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { FootNoteNodeConfigIdentifier } from './nodes/footnote-node/footnote-config.js';
|
||||
|
||||
export type AffineInlineRootElement = InlineRootElement<AffineTextAttributes>;
|
||||
|
||||
export const BoldInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'bold',
|
||||
schema: z.literal(true).optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.bold;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-text .delta=${delta}></affine-text>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const ItalicInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'italic',
|
||||
schema: z.literal(true).optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.italic;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-text .delta=${delta}></affine-text>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const UnderlineInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'underline',
|
||||
schema: z.literal(true).optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.underline;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-text .delta=${delta}></affine-text>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const StrikeInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'strike',
|
||||
schema: z.literal(true).optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.strike;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-text .delta=${delta}></affine-text>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const CodeInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'code',
|
||||
schema: z.literal(true).optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.code;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-text .delta=${delta}></affine-text>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const BackgroundInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'background',
|
||||
schema: z.string().optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.background;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-text .delta=${delta}></affine-text>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const ColorInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'color',
|
||||
schema: z.string().optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.color;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-text .delta=${delta}></affine-text>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const LatexInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>('latex', provider => {
|
||||
const std = provider.get(StdIdentifier);
|
||||
return {
|
||||
name: 'latex',
|
||||
schema: z.string().optional().nullable().catch(undefined),
|
||||
match: delta => typeof delta.attributes?.latex === 'string',
|
||||
renderer: ({ delta, selected, editor, startOffset, endOffset }) => {
|
||||
return html`<affine-latex-node
|
||||
.std=${std}
|
||||
.delta=${delta}
|
||||
.selected=${selected}
|
||||
.editor=${editor}
|
||||
.startOffset=${startOffset}
|
||||
.endOffset=${endOffset}
|
||||
></affine-latex-node>`;
|
||||
},
|
||||
embed: true,
|
||||
};
|
||||
});
|
||||
|
||||
export const LatexEditorUnitSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>({
|
||||
name: 'latex-editor-unit',
|
||||
schema: z.undefined(),
|
||||
match: () => true,
|
||||
renderer: ({ delta }) => {
|
||||
return html`<latex-editor-unit .delta=${delta}></latex-editor-unit>`;
|
||||
},
|
||||
});
|
||||
|
||||
export const FootNoteInlineSpecExtension =
|
||||
InlineSpecExtension<AffineTextAttributes>('footnote', provider => {
|
||||
const std = provider.get(StdIdentifier);
|
||||
const config =
|
||||
provider.getOptional(FootNoteNodeConfigIdentifier) ?? undefined;
|
||||
return {
|
||||
name: 'footnote',
|
||||
schema: FootNoteSchema.optional().nullable().catch(undefined),
|
||||
match: delta => {
|
||||
return !!delta.attributes?.footnote;
|
||||
},
|
||||
renderer: ({ delta }) => {
|
||||
return html`<affine-footnote-node
|
||||
.delta=${delta}
|
||||
.std=${std}
|
||||
.config=${config}
|
||||
></affine-footnote-node>`;
|
||||
},
|
||||
embed: true,
|
||||
};
|
||||
});
|
||||
|
||||
export const InlineSpecExtensions: ExtensionType[] = [
|
||||
BoldInlineSpecExtension,
|
||||
ItalicInlineSpecExtension,
|
||||
UnderlineInlineSpecExtension,
|
||||
StrikeInlineSpecExtension,
|
||||
CodeInlineSpecExtension,
|
||||
BackgroundInlineSpecExtension,
|
||||
ColorInlineSpecExtension,
|
||||
LatexInlineSpecExtension,
|
||||
...inlineLinkExtensions,
|
||||
...inlineReferenceExtensions,
|
||||
LatexEditorUnitSpecExtension,
|
||||
FootNoteInlineSpecExtension,
|
||||
];
|
||||
78
blocksuite/affine/inlines/preset/src/keymap/basic.ts
Normal file
78
blocksuite/affine/inlines/preset/src/keymap/basic.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
focusTextModel,
|
||||
getInlineEditorByModel,
|
||||
selectTextModel,
|
||||
} from '@blocksuite/affine-rich-text';
|
||||
import {
|
||||
BlockSelection,
|
||||
type BlockStdScope,
|
||||
TextSelection,
|
||||
type UIEventHandler,
|
||||
} from '@blocksuite/block-std';
|
||||
|
||||
export const textCommonKeymap = (
|
||||
std: BlockStdScope
|
||||
): Record<string, UIEventHandler> => {
|
||||
return {
|
||||
ArrowUp: () => {
|
||||
const text = std.selection.find(TextSelection);
|
||||
if (!text) return;
|
||||
const inline = getInlineEditorByModel(std, text.from.blockId);
|
||||
if (!inline) return;
|
||||
return !inline.isFirstLine(inline.getInlineRange());
|
||||
},
|
||||
ArrowDown: () => {
|
||||
const text = std.selection.find(TextSelection);
|
||||
if (!text) return;
|
||||
const inline = getInlineEditorByModel(std, text.from.blockId);
|
||||
if (!inline) return;
|
||||
return !inline.isLastLine(inline.getInlineRange());
|
||||
},
|
||||
Escape: ctx => {
|
||||
const text = std.selection.find(TextSelection);
|
||||
if (!text) return;
|
||||
|
||||
selectBlock(std, text.from.blockId);
|
||||
ctx.get('keyboardState').raw.stopPropagation();
|
||||
return true;
|
||||
},
|
||||
'Mod-a': ctx => {
|
||||
const text = std.selection.find(TextSelection);
|
||||
if (!text) return;
|
||||
|
||||
const model = std.store.getBlock(text.from.blockId)?.model;
|
||||
if (!model || !model.text) return;
|
||||
|
||||
ctx.get('keyboardState').raw.preventDefault();
|
||||
|
||||
if (
|
||||
text.from.index === 0 &&
|
||||
text.from.length === model.text.yText.length
|
||||
) {
|
||||
selectBlock(std, text.from.blockId);
|
||||
return true;
|
||||
}
|
||||
|
||||
selectTextModel(std, text.from.blockId, 0, model.text.yText.length);
|
||||
return true;
|
||||
},
|
||||
Enter: ctx => {
|
||||
const blocks = std.selection.filter(BlockSelection);
|
||||
const blockId = blocks.at(-1)?.blockId;
|
||||
|
||||
if (!blockId) return;
|
||||
const model = std.store.getBlock(blockId)?.model;
|
||||
if (!model || !model.text) return;
|
||||
|
||||
ctx.get('keyboardState').raw.preventDefault();
|
||||
focusTextModel(std, blockId, model.text.yText.length);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
function selectBlock(std: BlockStdScope, blockId: string) {
|
||||
std.selection.setGroup('note', [
|
||||
std.selection.create(BlockSelection, { blockId }),
|
||||
]);
|
||||
}
|
||||
162
blocksuite/affine/inlines/preset/src/keymap/bracket.ts
Normal file
162
blocksuite/affine/inlines/preset/src/keymap/bracket.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import { insertLinkedNode } from '@blocksuite/affine-inline-reference';
|
||||
import { CodeBlockModel } from '@blocksuite/affine-model';
|
||||
import { getInlineEditorByModel } from '@blocksuite/affine-rich-text';
|
||||
import { BRACKET_PAIRS } from '@blocksuite/affine-shared/consts';
|
||||
import { createDefaultDoc, matchModels } from '@blocksuite/affine-shared/utils';
|
||||
import {
|
||||
type BlockStdScope,
|
||||
TextSelection,
|
||||
type UIEventHandler,
|
||||
} from '@blocksuite/block-std';
|
||||
import type { InlineEditor } from '@blocksuite/block-std/inline';
|
||||
|
||||
export const bracketKeymap = (
|
||||
std: BlockStdScope
|
||||
): Record<string, UIEventHandler> => {
|
||||
const keymap = BRACKET_PAIRS.reduce(
|
||||
(acc, pair) => {
|
||||
return {
|
||||
...acc,
|
||||
[pair.right]: ctx => {
|
||||
const { store: doc, selection } = std;
|
||||
if (doc.readonly) return;
|
||||
|
||||
const textSelection = selection.find(TextSelection);
|
||||
if (!textSelection) return;
|
||||
const model = doc.getBlock(textSelection.from.blockId)?.model;
|
||||
if (!model) return;
|
||||
if (!matchModels(model, [CodeBlockModel])) return;
|
||||
const inlineEditor = getInlineEditorByModel(
|
||||
std,
|
||||
textSelection.from.blockId
|
||||
);
|
||||
if (!inlineEditor) return;
|
||||
const inlineRange = inlineEditor.getInlineRange();
|
||||
if (!inlineRange) return;
|
||||
const left = inlineEditor.yText.toString()[inlineRange.index - 1];
|
||||
const right = inlineEditor.yText.toString()[inlineRange.index];
|
||||
if (pair.left === left && pair.right === right) {
|
||||
inlineEditor.setInlineRange({
|
||||
index: inlineRange.index + 1,
|
||||
length: 0,
|
||||
});
|
||||
ctx.get('keyboardState').raw.preventDefault();
|
||||
}
|
||||
},
|
||||
[pair.left]: ctx => {
|
||||
const { store: doc, selection } = std;
|
||||
if (doc.readonly) return;
|
||||
|
||||
const textSelection = selection.find(TextSelection);
|
||||
if (!textSelection) return;
|
||||
const model = doc.getBlock(textSelection.from.blockId)?.model;
|
||||
if (!model) return;
|
||||
|
||||
const isCodeBlock = matchModels(model, [CodeBlockModel]);
|
||||
// When selection is collapsed, only trigger auto complete in code block
|
||||
if (textSelection.isCollapsed() && !isCodeBlock) return;
|
||||
if (!textSelection.isInSameBlock()) return;
|
||||
|
||||
ctx.get('keyboardState').raw.preventDefault();
|
||||
|
||||
const inlineEditor = getInlineEditorByModel(
|
||||
std,
|
||||
textSelection.from.blockId
|
||||
);
|
||||
if (!inlineEditor) return;
|
||||
const inlineRange = inlineEditor.getInlineRange();
|
||||
if (!inlineRange) return;
|
||||
const selectedText = inlineEditor.yText
|
||||
.toString()
|
||||
.slice(inlineRange.index, inlineRange.index + inlineRange.length);
|
||||
if (!isCodeBlock && pair.name === 'square bracket') {
|
||||
// [[Selected text]] should automatically be converted to a Linked doc with the title "Selected text".
|
||||
// See https://github.com/toeverything/blocksuite/issues/2730
|
||||
const success = tryConvertToLinkedDoc(std, inlineEditor);
|
||||
if (success) return true;
|
||||
}
|
||||
inlineEditor.insertText(
|
||||
inlineRange,
|
||||
pair.left + selectedText + pair.right
|
||||
);
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: inlineRange.index + 1,
|
||||
length: inlineRange.length,
|
||||
});
|
||||
|
||||
return true;
|
||||
},
|
||||
};
|
||||
},
|
||||
{} as Record<string, UIEventHandler>
|
||||
);
|
||||
|
||||
return {
|
||||
...keymap,
|
||||
'`': ctx => {
|
||||
const { store: doc, selection } = std;
|
||||
if (doc.readonly) return;
|
||||
|
||||
const textSelection = selection.find(TextSelection);
|
||||
if (!textSelection || textSelection.isCollapsed()) return;
|
||||
if (!textSelection.isInSameBlock()) return;
|
||||
const model = doc.getBlock(textSelection.from.blockId)?.model;
|
||||
if (!model) return;
|
||||
|
||||
ctx.get('keyboardState').raw.preventDefault();
|
||||
const inlineEditor = getInlineEditorByModel(
|
||||
std,
|
||||
textSelection.from.blockId
|
||||
);
|
||||
if (!inlineEditor) return;
|
||||
const inlineRange = inlineEditor.getInlineRange();
|
||||
if (!inlineRange) return;
|
||||
inlineEditor.formatText(inlineRange, { code: true });
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: inlineRange.index,
|
||||
length: inlineRange.length,
|
||||
});
|
||||
|
||||
return true;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
function tryConvertToLinkedDoc(std: BlockStdScope, inlineEditor: InlineEditor) {
|
||||
const root = std.store.root;
|
||||
if (!root) return false;
|
||||
const linkedDocWidgetEle = std.view.getWidget(
|
||||
'affine-linked-doc-widget',
|
||||
root.id
|
||||
);
|
||||
if (!linkedDocWidgetEle) return false;
|
||||
|
||||
const inlineRange = inlineEditor.getInlineRange();
|
||||
if (!inlineRange) return false;
|
||||
const text = inlineEditor.yText.toString();
|
||||
const left = text[inlineRange.index - 1];
|
||||
const right = text[inlineRange.index + inlineRange.length];
|
||||
const needConvert = left === '[' && right === ']';
|
||||
if (!needConvert) return false;
|
||||
|
||||
const docName = text.slice(
|
||||
inlineRange.index,
|
||||
inlineRange.index + inlineRange.length
|
||||
);
|
||||
inlineEditor.deleteText({
|
||||
index: inlineRange.index - 1,
|
||||
length: inlineRange.length + 2,
|
||||
});
|
||||
inlineEditor.setInlineRange({ index: inlineRange.index - 1, length: 0 });
|
||||
|
||||
const doc = createDefaultDoc(std.store.workspace, {
|
||||
title: docName,
|
||||
});
|
||||
insertLinkedNode({
|
||||
inlineEditor,
|
||||
docId: doc.id,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
36
blocksuite/affine/inlines/preset/src/keymap/format.ts
Normal file
36
blocksuite/affine/inlines/preset/src/keymap/format.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
type BlockStdScope,
|
||||
TextSelection,
|
||||
type UIEventHandler,
|
||||
} from '@blocksuite/block-std';
|
||||
|
||||
import { textFormatConfigs } from '../command/index.js';
|
||||
|
||||
export const textFormatKeymap = (std: BlockStdScope) =>
|
||||
textFormatConfigs
|
||||
.filter(config => config.hotkey)
|
||||
.reduce(
|
||||
(acc, config) => {
|
||||
return {
|
||||
...acc,
|
||||
[config.hotkey as string]: ctx => {
|
||||
const { store: doc, selection } = std;
|
||||
if (doc.readonly) return;
|
||||
|
||||
const textSelection = selection.find(TextSelection);
|
||||
if (!textSelection) return;
|
||||
|
||||
const allowed = config.textChecker?.(std.host) ?? true;
|
||||
if (!allowed) return;
|
||||
|
||||
const event = ctx.get('keyboardState').raw;
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
|
||||
config.action(std.host);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
},
|
||||
{} as Record<string, UIEventHandler>
|
||||
);
|
||||
15
blocksuite/affine/inlines/preset/src/keymap/index.ts
Normal file
15
blocksuite/affine/inlines/preset/src/keymap/index.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { BlockStdScope, UIEventHandler } from '@blocksuite/block-std';
|
||||
|
||||
import { textCommonKeymap } from './basic.js';
|
||||
import { bracketKeymap } from './bracket.js';
|
||||
import { textFormatKeymap } from './format.js';
|
||||
|
||||
export const textKeymap = (
|
||||
std: BlockStdScope
|
||||
): Record<string, UIEventHandler> => {
|
||||
return {
|
||||
...textCommonKeymap(std),
|
||||
...bracketKeymap(std),
|
||||
...textFormatKeymap(std),
|
||||
};
|
||||
};
|
||||
605
blocksuite/affine/inlines/preset/src/markdown.ts
Normal file
605
blocksuite/affine/inlines/preset/src/markdown.ts
Normal file
@@ -0,0 +1,605 @@
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import type { BlockComponent } from '@blocksuite/block-std';
|
||||
import { InlineMarkdownExtension } from '@blocksuite/block-std/inline';
|
||||
import type { ExtensionType } from '@blocksuite/store';
|
||||
|
||||
// inline markdown match rules:
|
||||
// covert: ***test*** + space
|
||||
// covert: ***t est*** + space
|
||||
// not convert: *** test*** + space
|
||||
// not convert: ***test *** + space
|
||||
// not convert: *** test *** + space
|
||||
|
||||
export const BoldItalicMarkdown = InlineMarkdownExtension<AffineTextAttributes>(
|
||||
{
|
||||
name: 'bolditalic',
|
||||
pattern: /.*\*{3}([^\s*][^*]*[^\s*])\*{3}$|.*\*{3}([^\s*])\*{3}$/,
|
||||
action: ({
|
||||
inlineEditor,
|
||||
prefixText,
|
||||
inlineRange,
|
||||
pattern,
|
||||
undoManager,
|
||||
}) => {
|
||||
const match = prefixText.match(pattern);
|
||||
if (!match) return;
|
||||
|
||||
const targetText = match[1] ?? match[2];
|
||||
const annotatedText = match[0].slice(-targetText.length - 3 * 2);
|
||||
const startIndex = inlineRange.index - annotatedText.length;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: annotatedText.length,
|
||||
},
|
||||
{
|
||||
bold: true,
|
||||
italic: true,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length - 3,
|
||||
length: 3,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 3,
|
||||
});
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length - 6,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export const BoldMarkdown = InlineMarkdownExtension<AffineTextAttributes>({
|
||||
name: 'bold',
|
||||
pattern: /.*\*{2}([^\s][^*]*[^\s*])\*{2}$|.*\*{2}([^\s*])\*{2}$/,
|
||||
action: ({ inlineEditor, prefixText, inlineRange, pattern, undoManager }) => {
|
||||
const match = prefixText.match(pattern);
|
||||
if (!match) return;
|
||||
|
||||
const targetText = match[1] ?? match[2];
|
||||
const annotatedText = match[0].slice(-targetText.length - 2 * 2);
|
||||
const startIndex = inlineRange.index - annotatedText.length;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: annotatedText.length,
|
||||
},
|
||||
{
|
||||
bold: true,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length - 2,
|
||||
length: 2,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 2,
|
||||
});
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length - 4,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const ItalicExtension = InlineMarkdownExtension<AffineTextAttributes>({
|
||||
name: 'italic',
|
||||
pattern: /.*\*{1}([^\s][^*]*[^\s*])\*{1}$|.*\*{1}([^\s*])\*{1}$/,
|
||||
action: ({ inlineEditor, prefixText, inlineRange, pattern, undoManager }) => {
|
||||
const match = prefixText.match(pattern);
|
||||
if (!match) return;
|
||||
|
||||
const targetText = match[1] ?? match[2];
|
||||
const annotatedText = match[0].slice(-targetText.length - 1 * 2);
|
||||
const startIndex = inlineRange.index - annotatedText.length;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: annotatedText.length,
|
||||
},
|
||||
{
|
||||
italic: true,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length - 1,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 1,
|
||||
});
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length - 2,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const StrikethroughExtension =
|
||||
InlineMarkdownExtension<AffineTextAttributes>({
|
||||
name: 'strikethrough',
|
||||
pattern: /.*~{2}([^\s][^~]*[^\s])~{2}$|.*~{2}([^\s~])~{2}$/,
|
||||
action: ({
|
||||
inlineEditor,
|
||||
prefixText,
|
||||
inlineRange,
|
||||
pattern,
|
||||
undoManager,
|
||||
}) => {
|
||||
const match = prefixText.match(pattern);
|
||||
if (!match) return;
|
||||
|
||||
const targetText = match[1] ?? match[2];
|
||||
const annotatedText = match[0].slice(-targetText.length - 2 * 2);
|
||||
const startIndex = inlineRange.index - annotatedText.length;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: annotatedText.length,
|
||||
},
|
||||
{
|
||||
strike: true,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length - 2,
|
||||
length: 2,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 2,
|
||||
});
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length - 4,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const UnderthroughExtension =
|
||||
InlineMarkdownExtension<AffineTextAttributes>({
|
||||
name: 'underthrough',
|
||||
pattern: /.*~{1}([^\s][^~]*[^\s~])~{1}$|.*~{1}([^\s~])~{1}$/,
|
||||
action: ({
|
||||
inlineEditor,
|
||||
prefixText,
|
||||
inlineRange,
|
||||
pattern,
|
||||
undoManager,
|
||||
}) => {
|
||||
const match = prefixText.match(pattern);
|
||||
if (!match) return;
|
||||
|
||||
const targetText = match[1] ?? match[2];
|
||||
const annotatedText = match[0].slice(-targetText.length - 1 * 2);
|
||||
const startIndex = inlineRange.index - annotatedText.length;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: annotatedText.length,
|
||||
},
|
||||
{
|
||||
underline: true,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: inlineRange.index - 1,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 1,
|
||||
});
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length - 2,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const CodeExtension = InlineMarkdownExtension<AffineTextAttributes>({
|
||||
name: 'code',
|
||||
pattern: /.*`([^\s][^`]*[^\s])`$|.*`([^\s`])`$/,
|
||||
action: ({ inlineEditor, prefixText, inlineRange, pattern, undoManager }) => {
|
||||
const match = prefixText.match(pattern);
|
||||
if (!match) return;
|
||||
|
||||
const targetText = match[1] ?? match[2];
|
||||
const annotatedText = match[0].slice(-targetText.length - 1 * 2);
|
||||
const startIndex = inlineRange.index - annotatedText.length;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: annotatedText.length,
|
||||
},
|
||||
{
|
||||
code: true,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + annotatedText.length - 1,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 1,
|
||||
});
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + annotatedText.length - 2,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const LinkExtension = InlineMarkdownExtension<AffineTextAttributes>({
|
||||
name: 'link',
|
||||
pattern: /.*\[(.+?)\]\((.+?)\)$/,
|
||||
action: ({ inlineEditor, prefixText, inlineRange, pattern, undoManager }) => {
|
||||
const match = prefixText.match(pattern);
|
||||
if (!match) return;
|
||||
|
||||
const linkText = match[1];
|
||||
const linkUrl = match[2];
|
||||
const annotatedText = match[0].slice(-linkText.length - linkUrl.length - 4);
|
||||
const startIndex = inlineRange.index - annotatedText.length;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: inlineRange.index,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: inlineRange.index + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
// aaa[bbb](baidu.com) + space
|
||||
|
||||
// delete (baidu.com) + space
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + 1 + linkText.length + 1,
|
||||
length: 1 + linkUrl.length + 1 + 1,
|
||||
});
|
||||
// delete [ and ]
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex + 1 + linkText.length,
|
||||
length: 1,
|
||||
});
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 1,
|
||||
});
|
||||
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: linkText.length,
|
||||
},
|
||||
{
|
||||
link: linkUrl,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + linkText.length,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const LatexExtension = InlineMarkdownExtension<AffineTextAttributes>({
|
||||
name: 'latex',
|
||||
|
||||
pattern:
|
||||
/(?:\$\$)(?<content>[^$]+)(?:\$\$)$|(?<blockPrefix>\$\$\$\$)|(?<inlinePrefix>\$\$)$/g,
|
||||
action: ({ inlineEditor, prefixText, inlineRange, pattern, undoManager }) => {
|
||||
const match = pattern.exec(prefixText);
|
||||
if (!match || !match.groups) return;
|
||||
const content = match.groups['content'];
|
||||
const inlinePrefix = match.groups['inlinePrefix'];
|
||||
const blockPrefix = match.groups['blockPrefix'];
|
||||
|
||||
if (blockPrefix === '$$$$') {
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: inlineRange.index,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: inlineRange.index + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
if (!inlineEditor.rootElement) return;
|
||||
const blockComponent =
|
||||
inlineEditor.rootElement.closest<BlockComponent>('[data-block-id]');
|
||||
if (!blockComponent) return;
|
||||
|
||||
const doc = blockComponent.doc;
|
||||
const parentComponent = blockComponent.parentComponent;
|
||||
if (!parentComponent) return;
|
||||
|
||||
const index = parentComponent.model.children.indexOf(
|
||||
blockComponent.model
|
||||
);
|
||||
if (index === -1) return;
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: inlineRange.index - 4,
|
||||
length: 5,
|
||||
});
|
||||
|
||||
const id = doc.addBlock(
|
||||
'affine:latex',
|
||||
{
|
||||
latex: '',
|
||||
},
|
||||
parentComponent.model,
|
||||
index + 1
|
||||
);
|
||||
blockComponent.host.updateComplete
|
||||
.then(() => {
|
||||
const latexBlock = blockComponent.std.view.getBlock(id);
|
||||
if (!latexBlock || latexBlock.flavour !== 'affine:latex') return;
|
||||
|
||||
//FIXME(@Flrande): wait for refactor
|
||||
// @ts-expect-error BS-2241
|
||||
latexBlock.toggleEditor();
|
||||
})
|
||||
.catch(console.error);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (inlinePrefix === '$$') {
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: inlineRange.index,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: inlineRange.index + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
inlineEditor.deleteText({
|
||||
index: inlineRange.index - 2,
|
||||
length: 3,
|
||||
});
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: inlineRange.index - 2,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: inlineRange.index - 2,
|
||||
length: 1,
|
||||
},
|
||||
{
|
||||
latex: '',
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor
|
||||
.waitForUpdate()
|
||||
.then(async () => {
|
||||
await inlineEditor.waitForUpdate();
|
||||
|
||||
const textPoint = inlineEditor.getTextPoint(
|
||||
inlineRange.index - 2 + 1
|
||||
);
|
||||
if (!textPoint) return;
|
||||
|
||||
const [text] = textPoint;
|
||||
const latexNode = text.parentElement?.closest('affine-latex-node');
|
||||
if (!latexNode) return;
|
||||
|
||||
latexNode.toggleEditor();
|
||||
})
|
||||
.catch(console.error);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!content || content.length === 0) return;
|
||||
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: inlineRange.index,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.setInlineRange({
|
||||
index: inlineRange.index + 1,
|
||||
length: 0,
|
||||
});
|
||||
|
||||
undoManager.stopCapturing();
|
||||
|
||||
const startIndex = inlineRange.index - 2 - content.length - 2;
|
||||
inlineEditor.deleteText({
|
||||
index: startIndex,
|
||||
length: 2 + content.length + 2 + 1,
|
||||
});
|
||||
inlineEditor.insertText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: 0,
|
||||
},
|
||||
' '
|
||||
);
|
||||
inlineEditor.formatText(
|
||||
{
|
||||
index: startIndex,
|
||||
length: 1,
|
||||
},
|
||||
{
|
||||
latex: String.raw`${content}`,
|
||||
}
|
||||
);
|
||||
|
||||
inlineEditor.setInlineRange({
|
||||
index: startIndex + 1,
|
||||
length: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const MarkdownExtensions: ExtensionType[] = [
|
||||
BoldItalicMarkdown,
|
||||
BoldMarkdown,
|
||||
ItalicExtension,
|
||||
StrikethroughExtension,
|
||||
UnderthroughExtension,
|
||||
CodeExtension,
|
||||
LinkExtension,
|
||||
LatexExtension,
|
||||
];
|
||||
35
blocksuite/affine/inlines/preset/src/nodes/affine-text.ts
Normal file
35
blocksuite/affine/inlines/preset/src/nodes/affine-text.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { affineTextStyles } from '@blocksuite/affine-shared/styles';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import { ShadowlessElement } from '@blocksuite/block-std';
|
||||
import { ZERO_WIDTH_SPACE } from '@blocksuite/block-std/inline';
|
||||
import type { DeltaInsert } from '@blocksuite/store';
|
||||
import { html } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
import { styleMap } from 'lit/directives/style-map.js';
|
||||
|
||||
export class AffineText extends ShadowlessElement {
|
||||
override render() {
|
||||
const style = this.delta.attributes
|
||||
? affineTextStyles(this.delta.attributes)
|
||||
: {};
|
||||
|
||||
// we need to avoid \n appearing before and after the span element, which will
|
||||
// cause the unexpected space
|
||||
if (this.delta.attributes?.code) {
|
||||
return html`<code style=${styleMap(style)}
|
||||
><v-text .str=${this.delta.insert}></v-text
|
||||
></code>`;
|
||||
}
|
||||
|
||||
// we need to avoid \n appearing before and after the span element, which will
|
||||
// cause the unexpected space
|
||||
return html`<span style=${styleMap(style)}
|
||||
><v-text .str=${this.delta.insert}></v-text
|
||||
></span>`;
|
||||
}
|
||||
|
||||
@property({ type: Object })
|
||||
accessor delta: DeltaInsert<AffineTextAttributes> = {
|
||||
insert: ZERO_WIDTH_SPACE,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { FootNote } from '@blocksuite/affine-model';
|
||||
import { type BlockStdScope, StdIdentifier } from '@blocksuite/block-std';
|
||||
import { createIdentifier } from '@blocksuite/global/di';
|
||||
import type { ExtensionType } from '@blocksuite/store';
|
||||
import type { TemplateResult } from 'lit';
|
||||
|
||||
type FootNoteNodeRenderer = (
|
||||
footnote: FootNote,
|
||||
std: BlockStdScope
|
||||
) => TemplateResult<1>;
|
||||
|
||||
type FootNotePopupRenderer = (
|
||||
footnote: FootNote,
|
||||
std: BlockStdScope,
|
||||
abortController: AbortController
|
||||
) => TemplateResult<1>;
|
||||
|
||||
export type FootNotePopupClickHandler = (
|
||||
footnote: FootNote,
|
||||
abortController: AbortController
|
||||
) => void;
|
||||
|
||||
export interface FootNoteNodeConfig {
|
||||
customNodeRenderer?: FootNoteNodeRenderer;
|
||||
customPopupRenderer?: FootNotePopupRenderer;
|
||||
interactive?: boolean;
|
||||
hidePopup?: boolean;
|
||||
disableHoverEffect?: boolean;
|
||||
onPopupClick?: FootNotePopupClickHandler;
|
||||
}
|
||||
|
||||
export class FootNoteNodeConfigProvider {
|
||||
private _customNodeRenderer?: FootNoteNodeRenderer;
|
||||
private _customPopupRenderer?: FootNotePopupRenderer;
|
||||
private _hidePopup: boolean;
|
||||
private _interactive: boolean;
|
||||
private _disableHoverEffect: boolean;
|
||||
private _onPopupClick?: FootNotePopupClickHandler;
|
||||
|
||||
get customNodeRenderer() {
|
||||
return this._customNodeRenderer;
|
||||
}
|
||||
|
||||
get customPopupRenderer() {
|
||||
return this._customPopupRenderer;
|
||||
}
|
||||
|
||||
get onPopupClick() {
|
||||
return this._onPopupClick;
|
||||
}
|
||||
|
||||
get doc() {
|
||||
return this.std.store;
|
||||
}
|
||||
|
||||
get hidePopup() {
|
||||
return this._hidePopup;
|
||||
}
|
||||
|
||||
get interactive() {
|
||||
return this._interactive;
|
||||
}
|
||||
|
||||
get disableHoverEffect() {
|
||||
return this._disableHoverEffect;
|
||||
}
|
||||
|
||||
constructor(
|
||||
config: FootNoteNodeConfig,
|
||||
readonly std: BlockStdScope
|
||||
) {
|
||||
this._customNodeRenderer = config.customNodeRenderer;
|
||||
this._customPopupRenderer = config.customPopupRenderer;
|
||||
this._hidePopup = config.hidePopup ?? false;
|
||||
this._interactive = config.interactive ?? true;
|
||||
this._disableHoverEffect = config.disableHoverEffect ?? false;
|
||||
this._onPopupClick = config.onPopupClick;
|
||||
}
|
||||
|
||||
setCustomNodeRenderer(renderer: FootNoteNodeRenderer) {
|
||||
this._customNodeRenderer = renderer;
|
||||
}
|
||||
|
||||
setCustomPopupRenderer(renderer: FootNotePopupRenderer) {
|
||||
this._customPopupRenderer = renderer;
|
||||
}
|
||||
|
||||
setHidePopup(hidePopup: boolean) {
|
||||
this._hidePopup = hidePopup;
|
||||
}
|
||||
|
||||
setInteractive(interactive: boolean) {
|
||||
this._interactive = interactive;
|
||||
}
|
||||
|
||||
setDisableHoverEffect(disableHoverEffect: boolean) {
|
||||
this._disableHoverEffect = disableHoverEffect;
|
||||
}
|
||||
|
||||
setPopupClick(onPopupClick: FootNotePopupClickHandler) {
|
||||
this._onPopupClick = onPopupClick;
|
||||
}
|
||||
}
|
||||
|
||||
export const FootNoteNodeConfigIdentifier =
|
||||
createIdentifier<FootNoteNodeConfigProvider>('AffineFootNoteNodeConfig');
|
||||
|
||||
export function FootNoteNodeConfigExtension(
|
||||
config: FootNoteNodeConfig
|
||||
): ExtensionType {
|
||||
return {
|
||||
setup: di => {
|
||||
di.addImpl(
|
||||
FootNoteNodeConfigIdentifier,
|
||||
provider =>
|
||||
new FootNoteNodeConfigProvider(config, provider.get(StdIdentifier))
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { HoverController } from '@blocksuite/affine-components/hover';
|
||||
import type { FootNote } from '@blocksuite/affine-model';
|
||||
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import {
|
||||
BlockSelection,
|
||||
type BlockStdScope,
|
||||
ShadowlessElement,
|
||||
TextSelection,
|
||||
} from '@blocksuite/block-std';
|
||||
import {
|
||||
INLINE_ROOT_ATTR,
|
||||
type InlineRootElement,
|
||||
ZERO_WIDTH_NON_JOINER,
|
||||
ZERO_WIDTH_SPACE,
|
||||
} from '@blocksuite/block-std/inline';
|
||||
import { WithDisposable } from '@blocksuite/global/lit';
|
||||
import type { DeltaInsert } from '@blocksuite/store';
|
||||
import { shift } from '@floating-ui/dom';
|
||||
import { baseTheme } from '@toeverything/theme';
|
||||
import { css, html, nothing, unsafeCSS } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
import { classMap } from 'lit-html/directives/class-map.js';
|
||||
import { ref } from 'lit-html/directives/ref.js';
|
||||
|
||||
import type { FootNoteNodeConfigProvider } from './footnote-config';
|
||||
|
||||
// Virtual padding for the footnote popup overflow detection offsets.
|
||||
const POPUP_SHIFT_PADDING = 8;
|
||||
|
||||
export class AffineFootnoteNode extends WithDisposable(ShadowlessElement) {
|
||||
static override styles = css`
|
||||
.footnote-node {
|
||||
padding: 0 2px;
|
||||
user-select: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.footnote-node {
|
||||
.footnote-content-default {
|
||||
display: inline-block;
|
||||
background: ${unsafeCSSVarV2('block/footnote/numberBgHover')};
|
||||
color: ${unsafeCSSVarV2('button/pureWhiteText')};
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
line-height: 14px;
|
||||
font-size: 10px;
|
||||
font-weight: 400;
|
||||
border-radius: 50%;
|
||||
text-align: center;
|
||||
text-overflow: ellipsis;
|
||||
font-family: ${unsafeCSS(baseTheme.fontSansFamily)};
|
||||
transition: background 0.3s ease-in-out;
|
||||
}
|
||||
}
|
||||
|
||||
.footnote-node.hover-effect {
|
||||
.footnote-content-default {
|
||||
color: var(--affine-text-primary-color);
|
||||
background: ${unsafeCSSVarV2('block/footnote/numberBg')};
|
||||
}
|
||||
}
|
||||
|
||||
.footnote-node.hover-effect:hover {
|
||||
.footnote-content-default {
|
||||
color: ${unsafeCSSVarV2('button/pureWhiteText')};
|
||||
background: ${unsafeCSSVarV2('block/footnote/numberBgHover')};
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
get customNodeRenderer() {
|
||||
return this.config?.customNodeRenderer;
|
||||
}
|
||||
|
||||
get customPopupRenderer() {
|
||||
return this.config?.customPopupRenderer;
|
||||
}
|
||||
|
||||
get interactive() {
|
||||
return this.config?.interactive;
|
||||
}
|
||||
|
||||
get hidePopup() {
|
||||
return this.config?.hidePopup;
|
||||
}
|
||||
|
||||
get disableHoverEffect() {
|
||||
return this.config?.disableHoverEffect;
|
||||
}
|
||||
|
||||
get onPopupClick() {
|
||||
return this.config?.onPopupClick;
|
||||
}
|
||||
|
||||
get inlineEditor() {
|
||||
const inlineRoot = this.closest<InlineRootElement<AffineTextAttributes>>(
|
||||
`[${INLINE_ROOT_ATTR}]`
|
||||
);
|
||||
return inlineRoot?.inlineEditor;
|
||||
}
|
||||
|
||||
get selfInlineRange() {
|
||||
const selfInlineRange = this.inlineEditor?.getInlineRangeFromElement(this);
|
||||
return selfInlineRange;
|
||||
}
|
||||
|
||||
private readonly _FootNoteDefaultContent = (footnote: FootNote) => {
|
||||
return html`<span class="footnote-content-default"
|
||||
>${footnote.label}</span
|
||||
>`;
|
||||
};
|
||||
|
||||
private readonly _FootNotePopup = (
|
||||
footnote: FootNote,
|
||||
abortController: AbortController
|
||||
) => {
|
||||
return this.customPopupRenderer
|
||||
? this.customPopupRenderer(footnote, this.std, abortController)
|
||||
: html`<footnote-popup
|
||||
.footnote=${footnote}
|
||||
.std=${this.std}
|
||||
.abortController=${abortController}
|
||||
.onPopupClick=${this.onPopupClick}
|
||||
></footnote-popup>`;
|
||||
};
|
||||
|
||||
private readonly _whenHover: HoverController = new HoverController(
|
||||
this,
|
||||
({ abortController }) => {
|
||||
const footnote = this.delta.attributes?.footnote;
|
||||
if (!footnote) return null;
|
||||
|
||||
if (
|
||||
this.config?.hidePopup ||
|
||||
!this.selfInlineRange ||
|
||||
!this.inlineEditor
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const selection = this.std?.selection;
|
||||
if (!selection) {
|
||||
return null;
|
||||
}
|
||||
const textSelection = selection.find(TextSelection);
|
||||
if (!!textSelection && !textSelection.isCollapsed()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const blockSelections = selection.filter(BlockSelection);
|
||||
if (blockSelections.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
template: this._FootNotePopup(footnote, abortController),
|
||||
container: this,
|
||||
computePosition: {
|
||||
referenceElement: this,
|
||||
placement: 'top',
|
||||
autoUpdate: true,
|
||||
middleware: [shift({ padding: POPUP_SHIFT_PADDING })],
|
||||
},
|
||||
};
|
||||
},
|
||||
{ enterDelay: 300 }
|
||||
);
|
||||
|
||||
override render() {
|
||||
const attributes = this.delta.attributes;
|
||||
const footnote = attributes?.footnote;
|
||||
if (!footnote) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const node = this.customNodeRenderer
|
||||
? this.customNodeRenderer(footnote, this.std)
|
||||
: this._FootNoteDefaultContent(footnote);
|
||||
|
||||
const nodeClasses = classMap({
|
||||
'footnote-node': true,
|
||||
'hover-effect': !this.disableHoverEffect,
|
||||
});
|
||||
|
||||
return html`<span
|
||||
${this.hidePopup ? '' : ref(this._whenHover.setReference)}
|
||||
class=${nodeClasses}
|
||||
>${node}<v-text .str=${ZERO_WIDTH_NON_JOINER}></v-text
|
||||
></span>`;
|
||||
}
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor config: FootNoteNodeConfigProvider | undefined = undefined;
|
||||
|
||||
@property({ type: Object })
|
||||
accessor delta: DeltaInsert<AffineTextAttributes> = {
|
||||
insert: ZERO_WIDTH_SPACE,
|
||||
attributes: {},
|
||||
};
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor std!: BlockStdScope;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
|
||||
import { css, html, LitElement, nothing, type TemplateResult } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
|
||||
export class FootNotePopupChip extends LitElement {
|
||||
static override styles = css`
|
||||
.popup-chip-container {
|
||||
display: flex;
|
||||
border-radius: 4px;
|
||||
max-width: 173px;
|
||||
height: 24px;
|
||||
padding: 2px 4px;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
box-sizing: border-box;
|
||||
cursor: default;
|
||||
transition: width 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
.prefix-icon,
|
||||
.suffix-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
color: ${unsafeCSSVarV2('icon/primary')};
|
||||
border-radius: 4px;
|
||||
|
||||
svg,
|
||||
object {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
fill: ${unsafeCSSVarV2('icon/primary')};
|
||||
}
|
||||
}
|
||||
|
||||
.suffix-icon:hover {
|
||||
background-color: ${unsafeCSSVarV2('layer/background/hoverOverlay')};
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.popup-chip-label {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: left;
|
||||
height: 20px;
|
||||
line-height: 20px;
|
||||
color: ${unsafeCSSVarV2('text/primary')};
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
`;
|
||||
|
||||
override render() {
|
||||
return html`
|
||||
<div class="popup-chip-container" @click=${this.onClick}>
|
||||
${this.prefixIcon
|
||||
? html`<div class="prefix-icon" @click=${this.onPrefixClick}>
|
||||
${this.prefixIcon}
|
||||
</div>`
|
||||
: nothing}
|
||||
<div class="popup-chip-label" title=${this.tooltip}>${this.label}</div>
|
||||
${this.suffixIcon
|
||||
? html`<div class="suffix-icon" @click=${this.onSuffixClick}>
|
||||
${this.suffixIcon}
|
||||
</div>`
|
||||
: nothing}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor prefixIcon: TemplateResult | undefined = undefined;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor label: string = '';
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor suffixIcon: TemplateResult | undefined = undefined;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor tooltip: string = '';
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor onClick: (() => void) | undefined = undefined;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor onPrefixClick: (() => void) | undefined = undefined;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor onSuffixClick: (() => void) | undefined = undefined;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import {
|
||||
DarkLoadingIcon,
|
||||
getAttachmentFileIcon,
|
||||
LightLoadingIcon,
|
||||
WebIcon16,
|
||||
} from '@blocksuite/affine-components/icons';
|
||||
import { PeekViewProvider } from '@blocksuite/affine-components/peek';
|
||||
import { ColorScheme, type FootNote } from '@blocksuite/affine-model';
|
||||
import {
|
||||
DocDisplayMetaProvider,
|
||||
LinkPreviewerService,
|
||||
ThemeProvider,
|
||||
} from '@blocksuite/affine-shared/services';
|
||||
import { unsafeCSSVar, unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
|
||||
import type { BlockStdScope } from '@blocksuite/block-std';
|
||||
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
|
||||
import { DualLinkIcon, LinkIcon } from '@blocksuite/icons/lit';
|
||||
import { computed, signal } from '@preact/signals-core';
|
||||
import { css, html, LitElement, type TemplateResult } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
|
||||
import type { FootNotePopupClickHandler } from './footnote-config';
|
||||
|
||||
export class FootNotePopup extends SignalWatcher(WithDisposable(LitElement)) {
|
||||
static override styles = css`
|
||||
.footnote-popup-container {
|
||||
border-radius: 4px;
|
||||
box-shadow: ${unsafeCSSVar('overlayPanelShadow')};
|
||||
background-color: ${unsafeCSSVarV2('layer/background/primary')};
|
||||
border: 0.5px solid ${unsafeCSSVarV2('layer/insideBorder/border')};
|
||||
}
|
||||
`;
|
||||
|
||||
private readonly _isLoading$ = signal(false);
|
||||
|
||||
private readonly _linkPreview$ = signal<
|
||||
{ favicon: string | undefined; title?: string } | undefined
|
||||
>({ favicon: undefined, title: undefined });
|
||||
|
||||
private readonly _prefixIcon$ = computed(() => {
|
||||
const referenceType = this.footnote.reference.type;
|
||||
if (referenceType === 'doc') {
|
||||
const docId = this.footnote.reference.docId;
|
||||
if (!docId) {
|
||||
return undefined;
|
||||
}
|
||||
return this.std.get(DocDisplayMetaProvider).icon(docId).value;
|
||||
} else if (referenceType === 'attachment') {
|
||||
const fileType = this.footnote.reference.fileType;
|
||||
if (!fileType) {
|
||||
return undefined;
|
||||
}
|
||||
return getAttachmentFileIcon(fileType);
|
||||
} else if (referenceType === 'url') {
|
||||
if (this._isLoading$.value) {
|
||||
return this._LoadingIcon();
|
||||
}
|
||||
|
||||
const favicon = this._linkPreview$.value?.favicon;
|
||||
if (!favicon) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const titleIconType =
|
||||
favicon.split('.').pop() === 'svg'
|
||||
? 'svg+xml'
|
||||
: favicon.split('.').pop();
|
||||
const titleIcon = html`<object
|
||||
type="image/${titleIconType}"
|
||||
data=${favicon}
|
||||
draggable="false"
|
||||
>
|
||||
${WebIcon16}
|
||||
</object>`;
|
||||
return titleIcon;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
private readonly _suffixIcon = (): TemplateResult | undefined => {
|
||||
const referenceType = this.footnote.reference.type;
|
||||
if (referenceType === 'doc') {
|
||||
return DualLinkIcon({ width: '16px', height: '16px' });
|
||||
} else if (referenceType === 'url') {
|
||||
return LinkIcon({ width: '16px', height: '16px' });
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
private readonly _popupLabel$ = computed(() => {
|
||||
const referenceType = this.footnote.reference.type;
|
||||
let label = '';
|
||||
const { docId, fileName, url } = this.footnote.reference;
|
||||
switch (referenceType) {
|
||||
case 'doc':
|
||||
if (!docId) {
|
||||
return label;
|
||||
}
|
||||
label = this.std.get(DocDisplayMetaProvider).title(docId).value;
|
||||
break;
|
||||
case 'attachment':
|
||||
if (!fileName) {
|
||||
return label;
|
||||
}
|
||||
label = fileName;
|
||||
break;
|
||||
case 'url':
|
||||
if (!url) {
|
||||
return label;
|
||||
}
|
||||
label = this._linkPreview$.value?.title ?? url;
|
||||
break;
|
||||
}
|
||||
return label;
|
||||
});
|
||||
|
||||
private readonly _tooltip$ = computed(() => {
|
||||
const referenceType = this.footnote.reference.type;
|
||||
if (referenceType === 'url') {
|
||||
return this.footnote.reference.url ?? '';
|
||||
}
|
||||
return this._popupLabel$.value;
|
||||
});
|
||||
|
||||
private readonly _LoadingIcon = () => {
|
||||
const theme = this.std.get(ThemeProvider).theme;
|
||||
return theme === ColorScheme.Light ? LightLoadingIcon : DarkLoadingIcon;
|
||||
};
|
||||
|
||||
/**
|
||||
* When clicking the chip, we will navigate to the reference doc or open the url
|
||||
*/
|
||||
private readonly _handleDocReference = (docId: string) => {
|
||||
this.std
|
||||
.getOptional(PeekViewProvider)
|
||||
?.peek({
|
||||
docId,
|
||||
})
|
||||
.catch(console.error);
|
||||
};
|
||||
|
||||
private readonly _handleUrlReference = (url: string) => {
|
||||
window.open(url, '_blank');
|
||||
};
|
||||
|
||||
private readonly _handleReference = () => {
|
||||
const { type, docId, url } = this.footnote.reference;
|
||||
|
||||
switch (type) {
|
||||
case 'doc':
|
||||
if (docId) {
|
||||
this._handleDocReference(docId);
|
||||
}
|
||||
break;
|
||||
case 'url':
|
||||
if (url) {
|
||||
this._handleUrlReference(url);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
this.abortController.abort();
|
||||
};
|
||||
|
||||
private readonly _onChipClick = () => {
|
||||
// If the onPopupClick is defined, use it
|
||||
if (this.onPopupClick) {
|
||||
this.onPopupClick(this.footnote, this.abortController);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, handle the reference by default
|
||||
this._handleReference();
|
||||
};
|
||||
|
||||
override connectedCallback() {
|
||||
super.connectedCallback();
|
||||
if (this.footnote.reference.type === 'url' && this.footnote.reference.url) {
|
||||
this._isLoading$.value = true;
|
||||
this.std.store
|
||||
.get(LinkPreviewerService)
|
||||
.query(this.footnote.reference.url)
|
||||
.then(data => {
|
||||
this._linkPreview$.value = {
|
||||
favicon: data.icon ?? undefined,
|
||||
title: data.title ?? undefined,
|
||||
};
|
||||
})
|
||||
.catch(console.error)
|
||||
.finally(() => {
|
||||
this._isLoading$.value = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
override render() {
|
||||
return html`
|
||||
<div class="footnote-popup-container">
|
||||
<footnote-popup-chip
|
||||
.prefixIcon=${this._prefixIcon$.value}
|
||||
.label=${this._popupLabel$.value}
|
||||
.suffixIcon=${this._suffixIcon()}
|
||||
.onClick=${this._onChipClick}
|
||||
.tooltip=${this._tooltip$.value}
|
||||
></footnote-popup-chip>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor footnote!: FootNote;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor std!: BlockStdScope;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor abortController!: AbortController;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor onPopupClick: FootNotePopupClickHandler | undefined = undefined;
|
||||
}
|
||||
2
blocksuite/affine/inlines/preset/src/nodes/index.ts
Normal file
2
blocksuite/affine/inlines/preset/src/nodes/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './footnote-node/footnote-config.js';
|
||||
export { AffineFootnoteNode } from './footnote-node/footnote-node.js';
|
||||
@@ -0,0 +1,199 @@
|
||||
import { ColorScheme } from '@blocksuite/affine-model';
|
||||
import { ThemeProvider } from '@blocksuite/affine-shared/services';
|
||||
import { unsafeCSSVar } from '@blocksuite/affine-shared/theme';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import { type BlockStdScope, ShadowlessElement } from '@blocksuite/block-std';
|
||||
import { InlineManagerExtension } from '@blocksuite/block-std/inline';
|
||||
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
|
||||
import { noop } from '@blocksuite/global/utils';
|
||||
import { DoneIcon } from '@blocksuite/icons/lit';
|
||||
import { effect, type Signal, signal } from '@preact/signals-core';
|
||||
import { css, html } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
import { codeToTokensBase, type ThemedToken } from 'shiki';
|
||||
import * as Y from 'yjs';
|
||||
|
||||
import { LatexEditorUnitSpecExtension } from '../../inline-spec';
|
||||
|
||||
export const LatexEditorInlineManagerExtension =
|
||||
InlineManagerExtension<AffineTextAttributes>({
|
||||
id: 'latex-inline-editor',
|
||||
enableMarkdown: false,
|
||||
specs: [LatexEditorUnitSpecExtension.identifier],
|
||||
});
|
||||
|
||||
export class LatexEditorMenu extends SignalWatcher(
|
||||
WithDisposable(ShadowlessElement)
|
||||
) {
|
||||
static override styles = css`
|
||||
.latex-editor-container {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
grid-template-rows: auto auto;
|
||||
grid-template-areas:
|
||||
'editor-box confirm-box'
|
||||
'hint-box hint-box';
|
||||
|
||||
padding: 8px;
|
||||
border-radius: 8px;
|
||||
border: 0.5px solid ${unsafeCSSVar('borderColor')};
|
||||
background: ${unsafeCSSVar('backgroundOverlayPanelColor')};
|
||||
|
||||
/* light/toolbarShadow */
|
||||
box-shadow: 0px 6px 16px 0px rgba(0, 0, 0, 0.14);
|
||||
}
|
||||
|
||||
.latex-editor {
|
||||
grid-area: editor-box;
|
||||
width: 280px;
|
||||
padding: 4px 10px;
|
||||
|
||||
border-radius: 4px;
|
||||
background: ${unsafeCSSVar('white10')};
|
||||
|
||||
/* light/activeShadow */
|
||||
box-shadow: 0px 0px 0px 2px rgba(30, 150, 235, 0.3);
|
||||
|
||||
font-family: ${unsafeCSSVar('fontCodeFamily')};
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.latex-editor:focus-within {
|
||||
border: 1px solid ${unsafeCSSVar('blue700')};
|
||||
}
|
||||
|
||||
.latex-editor-confirm {
|
||||
grid-area: confirm-box;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
padding-left: 10px;
|
||||
}
|
||||
|
||||
.latex-editor-hint {
|
||||
grid-area: hint-box;
|
||||
padding-top: 6px;
|
||||
|
||||
color: ${unsafeCSSVar('placeholderColor')};
|
||||
|
||||
/* MobileTypeface/caption */
|
||||
font-family: 'SF Pro Text';
|
||||
font-size: 12px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 16px; /* 133.333% */
|
||||
letter-spacing: -0.24px;
|
||||
}
|
||||
`;
|
||||
|
||||
highlightTokens$: Signal<ThemedToken[][]> = signal([]);
|
||||
|
||||
yText!: Y.Text;
|
||||
|
||||
get inlineManager() {
|
||||
return this.std.get(LatexEditorInlineManagerExtension.identifier);
|
||||
}
|
||||
|
||||
get richText() {
|
||||
return this.querySelector('rich-text');
|
||||
}
|
||||
|
||||
private _updateHighlightTokens(text: string) {
|
||||
const editorTheme = this.std.get(ThemeProvider).theme;
|
||||
const theme = editorTheme === ColorScheme.Dark ? 'dark-plus' : 'light-plus';
|
||||
|
||||
codeToTokensBase(text, {
|
||||
lang: 'latex',
|
||||
theme,
|
||||
})
|
||||
.then(token => {
|
||||
this.highlightTokens$.value = token;
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
|
||||
override connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
|
||||
const doc = new Y.Doc();
|
||||
this.yText = doc.getText('latex');
|
||||
this.yText.insert(0, this.latexSignal.value);
|
||||
|
||||
const yTextObserver = () => {
|
||||
const text = this.yText.toString();
|
||||
this.latexSignal.value = text;
|
||||
|
||||
this._updateHighlightTokens(text);
|
||||
};
|
||||
this.yText.observe(yTextObserver);
|
||||
this.disposables.add(() => {
|
||||
this.yText.unobserve(yTextObserver);
|
||||
});
|
||||
|
||||
this.disposables.add(
|
||||
effect(() => {
|
||||
noop(this.highlightTokens$.value);
|
||||
this.richText?.inlineEditor?.render();
|
||||
})
|
||||
);
|
||||
|
||||
this.disposables.add(
|
||||
this.std.get(ThemeProvider).theme$.subscribe(() => {
|
||||
this._updateHighlightTokens(this.yText.toString());
|
||||
})
|
||||
);
|
||||
|
||||
this.disposables.addFromEvent(this, 'keydown', e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.abortController.abort();
|
||||
}
|
||||
});
|
||||
|
||||
this.disposables.addFromEvent(this, 'pointerdown', e => {
|
||||
e.stopPropagation();
|
||||
});
|
||||
this.disposables.addFromEvent(this, 'pointerup', e => {
|
||||
e.stopPropagation();
|
||||
});
|
||||
|
||||
this.updateComplete
|
||||
.then(async () => {
|
||||
await this.richText?.updateComplete;
|
||||
|
||||
setTimeout(() => {
|
||||
this.richText?.inlineEditor?.focusEnd();
|
||||
});
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
|
||||
override render() {
|
||||
return html`<div class="latex-editor-container">
|
||||
<div class="latex-editor">
|
||||
<rich-text
|
||||
.yText=${this.yText}
|
||||
.attributesSchema=${this.inlineManager.getSchema()}
|
||||
.attributeRenderer=${this.inlineManager.getRenderer()}
|
||||
></rich-text>
|
||||
</div>
|
||||
<div class="latex-editor-confirm">
|
||||
<span @click=${() => this.abortController.abort()}
|
||||
>${DoneIcon({
|
||||
width: '24',
|
||||
height: '24',
|
||||
})}</span
|
||||
>
|
||||
</div>
|
||||
<div class="latex-editor-hint">Shift Enter to line break</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor abortController!: AbortController;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor latexSignal!: Signal<string>;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor std!: BlockStdScope;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import { ShadowlessElement } from '@blocksuite/block-std';
|
||||
import { ZERO_WIDTH_SPACE } from '@blocksuite/block-std/inline';
|
||||
import type { DeltaInsert } from '@blocksuite/store';
|
||||
import { html } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
import { styleMap } from 'lit/directives/style-map.js';
|
||||
|
||||
export class LatexEditorUnit extends ShadowlessElement {
|
||||
get latexMenu() {
|
||||
return this.closest('latex-editor-menu');
|
||||
}
|
||||
|
||||
get vElement() {
|
||||
return this.closest('v-element');
|
||||
}
|
||||
|
||||
override render() {
|
||||
const plainContent = html`<span
|
||||
><v-text .str=${this.delta.insert}></v-text
|
||||
></span>`;
|
||||
|
||||
const latexMenu = this.latexMenu;
|
||||
const vElement = this.vElement;
|
||||
if (!latexMenu || !vElement) {
|
||||
return plainContent;
|
||||
}
|
||||
|
||||
const lineIndex = this.vElement.lineIndex;
|
||||
const tokens = latexMenu.highlightTokens$.value[lineIndex] ?? [];
|
||||
if (
|
||||
tokens.length === 0 ||
|
||||
tokens.reduce((acc, token) => acc + token.content, '') !==
|
||||
this.delta.insert
|
||||
) {
|
||||
return plainContent;
|
||||
}
|
||||
|
||||
return html`<span
|
||||
>${tokens.map(token => {
|
||||
return html`<v-text
|
||||
.str=${token.content}
|
||||
style=${styleMap({
|
||||
color: token.color,
|
||||
})}
|
||||
></v-text>`;
|
||||
})}</span
|
||||
>`;
|
||||
}
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor delta: DeltaInsert<AffineTextAttributes> = {
|
||||
insert: ZERO_WIDTH_SPACE,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import { createLitPortal } from '@blocksuite/affine-components/portal';
|
||||
import { unsafeCSSVar, unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
|
||||
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
|
||||
import {
|
||||
type BlockComponent,
|
||||
type BlockStdScope,
|
||||
ShadowlessElement,
|
||||
} from '@blocksuite/block-std';
|
||||
import {
|
||||
type InlineEditor,
|
||||
ZERO_WIDTH_NON_JOINER,
|
||||
ZERO_WIDTH_SPACE,
|
||||
} from '@blocksuite/block-std/inline';
|
||||
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
|
||||
import type { DeltaInsert } from '@blocksuite/store';
|
||||
import { signal } from '@preact/signals-core';
|
||||
import katex from 'katex';
|
||||
import { css, html, render } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
|
||||
export class AffineLatexNode extends SignalWatcher(
|
||||
WithDisposable(ShadowlessElement)
|
||||
) {
|
||||
static override styles = css`
|
||||
affine-latex-node {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
affine-latex-node .affine-latex {
|
||||
white-space: nowrap;
|
||||
word-break: break-word;
|
||||
color: ${unsafeCSSVar('textPrimaryColor')};
|
||||
fill: var(--affine-icon-color);
|
||||
border-radius: 4px;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
padding: 1px 2px 1px 0;
|
||||
display: grid;
|
||||
grid-template-columns: auto 0;
|
||||
place-items: center;
|
||||
padding: 0 4px;
|
||||
margin: 0 2px;
|
||||
}
|
||||
affine-latex-node .affine-latex:hover {
|
||||
background: ${unsafeCSSVar('hoverColor')};
|
||||
}
|
||||
affine-latex-node .affine-latex[data-selected='true'] {
|
||||
background: ${unsafeCSSVar('hoverColor')};
|
||||
}
|
||||
|
||||
affine-latex-node .error-placeholder {
|
||||
display: flex;
|
||||
padding: 2px 4px;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
|
||||
border-radius: 4px;
|
||||
background: ${unsafeCSSVarV2('chip/label/red')};
|
||||
|
||||
color: ${unsafeCSSVarV2('text/highlight/fg/red')};
|
||||
font-family: Inter;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
affine-latex-node .placeholder {
|
||||
display: flex;
|
||||
padding: 2px 4px;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
|
||||
border-radius: 4px;
|
||||
background: ${unsafeCSSVarV2('layer/background/secondary')};
|
||||
|
||||
color: ${unsafeCSSVarV2('text/secondary')};
|
||||
font-family: Inter;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: normal;
|
||||
}
|
||||
`;
|
||||
|
||||
private _editorAbortController: AbortController | null = null;
|
||||
|
||||
readonly latex$ = signal('');
|
||||
|
||||
readonly latexEditorSignal = signal('');
|
||||
|
||||
get deltaLatex() {
|
||||
return this.delta.attributes?.latex as string;
|
||||
}
|
||||
|
||||
get latexContainer() {
|
||||
return this.querySelector<HTMLElement>('.latex-container');
|
||||
}
|
||||
|
||||
override connectedCallback() {
|
||||
const result = super.connectedCallback();
|
||||
|
||||
this.latex$.value = this.deltaLatex;
|
||||
this.latexEditorSignal.value = this.deltaLatex;
|
||||
|
||||
this.disposables.add(
|
||||
this.latex$.subscribe(latex => {
|
||||
this.latexEditorSignal.value = latex;
|
||||
if (latex !== this.deltaLatex) {
|
||||
this.editor.formatText(
|
||||
{
|
||||
index: this.startOffset,
|
||||
length: this.endOffset - this.startOffset,
|
||||
},
|
||||
{
|
||||
latex,
|
||||
}
|
||||
);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
this.disposables.add(
|
||||
this.latexEditorSignal.subscribe(latex => {
|
||||
this.updateComplete
|
||||
.then(() => {
|
||||
const latexContainer = this.latexContainer;
|
||||
if (!latexContainer) return;
|
||||
|
||||
latexContainer.replaceChildren();
|
||||
// @ts-expect-error lit hack won't fix
|
||||
delete latexContainer['_$litPart$'];
|
||||
|
||||
if (latex.length === 0) {
|
||||
render(
|
||||
html`<span class="placeholder">Equation</span>`,
|
||||
latexContainer
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
katex.render(latex, latexContainer, {
|
||||
displayMode: true,
|
||||
output: 'mathml',
|
||||
});
|
||||
} catch {
|
||||
latexContainer.replaceChildren();
|
||||
// @ts-expect-error lit hack won't fix
|
||||
delete latexContainer['_$litPart$'];
|
||||
render(
|
||||
html`<span class="error-placeholder">Error equation</span>`,
|
||||
latexContainer
|
||||
);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(console.error);
|
||||
})
|
||||
);
|
||||
|
||||
this._editorAbortController?.abort();
|
||||
this._editorAbortController = new AbortController();
|
||||
this.disposables.add(() => {
|
||||
this._editorAbortController?.abort();
|
||||
});
|
||||
|
||||
this.disposables.addFromEvent(this, 'click', e => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (this.readonly) {
|
||||
return;
|
||||
}
|
||||
this.toggleEditor();
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
override render() {
|
||||
return html`<span class="affine-latex" data-selected=${this.selected}
|
||||
><div class="latex-container"></div>
|
||||
<v-text .str=${ZERO_WIDTH_NON_JOINER}></v-text
|
||||
></span>`;
|
||||
}
|
||||
|
||||
toggleEditor() {
|
||||
const blockComponent = this.closest<BlockComponent>('[data-block-id]');
|
||||
if (!blockComponent) return;
|
||||
|
||||
this._editorAbortController?.abort();
|
||||
this._editorAbortController = new AbortController();
|
||||
|
||||
const portal = createLitPortal({
|
||||
template: html`<latex-editor-menu
|
||||
.std=${this.std}
|
||||
.latexSignal=${this.latexEditorSignal}
|
||||
.abortController=${this._editorAbortController}
|
||||
></latex-editor-menu>`,
|
||||
container: blockComponent.host,
|
||||
computePosition: {
|
||||
referenceElement: this,
|
||||
placement: 'bottom-start',
|
||||
autoUpdate: {
|
||||
animationFrame: true,
|
||||
},
|
||||
},
|
||||
closeOnClickAway: true,
|
||||
abortController: this._editorAbortController,
|
||||
shadowDom: false,
|
||||
portalStyles: {
|
||||
zIndex: 'var(--affine-z-index-popover)',
|
||||
},
|
||||
});
|
||||
|
||||
this._editorAbortController.signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
portal.remove();
|
||||
const latex = this.latexEditorSignal.peek();
|
||||
this.latex$.value = latex;
|
||||
|
||||
if (latex !== this.deltaLatex) {
|
||||
this.editor.formatText(
|
||||
{
|
||||
index: this.startOffset,
|
||||
length: this.endOffset - this.startOffset,
|
||||
},
|
||||
{
|
||||
latex,
|
||||
}
|
||||
);
|
||||
this.editor.setInlineRange({
|
||||
index: this.endOffset,
|
||||
length: 0,
|
||||
});
|
||||
}
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
|
||||
get readonly() {
|
||||
return this.std.store.readonly;
|
||||
}
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor delta: DeltaInsert<AffineTextAttributes> = {
|
||||
insert: ZERO_WIDTH_SPACE,
|
||||
};
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor editor!: InlineEditor<AffineTextAttributes>;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor endOffset!: number;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor selected = false;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor startOffset!: number;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor std!: BlockStdScope;
|
||||
}
|
||||
20
blocksuite/affine/inlines/preset/tsconfig.json
Normal file
20
blocksuite/affine/inlines/preset/tsconfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "./src",
|
||||
"outDir": "./dist",
|
||||
"tsBuildInfoFile": "./dist/tsconfig.tsbuildinfo"
|
||||
},
|
||||
"include": ["./src"],
|
||||
"references": [
|
||||
{ "path": "../../components" },
|
||||
{ "path": "../link" },
|
||||
{ "path": "../reference" },
|
||||
{ "path": "../../model" },
|
||||
{ "path": "../../rich-text" },
|
||||
{ "path": "../../shared" },
|
||||
{ "path": "../../../framework/block-std" },
|
||||
{ "path": "../../../framework/global" },
|
||||
{ "path": "../../../framework/store" }
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user