chore: fix eslint in blocksuite (#9232)

This commit is contained in:
Saul-Mirone
2024-12-20 16:48:10 +00:00
parent bfcc53dc1f
commit 3a82da0e5b
269 changed files with 935 additions and 842 deletions
@@ -51,11 +51,11 @@ type HtmlToSliceSnapshotPayload = {
};
export class HtmlAdapter extends BaseAdapter<Html> {
private _astToHtml = (ast: Root) => {
private readonly _astToHtml = (ast: Root) => {
return unified().use(rehypeStringify).stringify(ast);
};
private _traverseHtml = async (
private readonly _traverseHtml = async (
html: HtmlAST,
snapshot: BlockSnapshot,
assets?: AssetsManager
@@ -108,7 +108,7 @@ export class HtmlAdapter extends BaseAdapter<Html> {
return walker.walk(html, snapshot);
};
private _traverseSnapshot = async (
private readonly _traverseSnapshot = async (
snapshot: BlockSnapshot,
html: HtmlAST,
assets?: AssetsManager
@@ -50,7 +50,7 @@ type MarkdownToSliceSnapshotPayload = {
};
export class MarkdownAdapter extends BaseAdapter<Markdown> {
private _traverseMarkdown = (
private readonly _traverseMarkdown = (
markdown: MarkdownAST,
snapshot: BlockSnapshot,
assets?: AssetsManager
@@ -105,7 +105,7 @@ export class MarkdownAdapter extends BaseAdapter<Markdown> {
return walker.walk(markdown, snapshot);
};
private _traverseSnapshot = async (
private readonly _traverseSnapshot = async (
snapshot: BlockSnapshot,
markdown: MarkdownAST,
assets?: AssetsManager
@@ -38,7 +38,7 @@ type MixTextToSliceSnapshotPayload = {
};
export class MixTextAdapter extends BaseAdapter<MixText> {
private _markdownAdapter: MarkdownAdapter;
private readonly _markdownAdapter: MarkdownAdapter;
constructor(job: Job) {
super(job);
@@ -54,7 +54,7 @@ type NotionHtmlToDocSnapshotPayload = {
type NotionHtmlToBlockSnapshotPayload = NotionHtmlToDocSnapshotPayload;
export class NotionHtmlAdapter extends BaseAdapter<NotionHtml> {
private _traverseNotionHtml = async (
private readonly _traverseNotionHtml = async (
html: HtmlAST,
snapshot: BlockSnapshot,
assets?: AssetsManager,
@@ -48,7 +48,7 @@ export class AIItemList extends WithDisposable(LitElement) {
private _activeSubMenuItem: AIItemConfig | null = null;
private _closeSubMenu = () => {
private readonly _closeSubMenu = () => {
if (this._abortController) {
this._abortController.abort();
this._abortController = null;
@@ -56,11 +56,11 @@ export class AIItemList extends WithDisposable(LitElement) {
this._activeSubMenuItem = null;
};
private _itemClassName = (item: AIItemConfig) => {
private readonly _itemClassName = (item: AIItemConfig) => {
return 'ai-item-' + item.name.split(' ').join('-').toLocaleLowerCase();
};
private _openSubMenu = (item: AIItemConfig) => {
private readonly _openSubMenu = (item: AIItemConfig) => {
if (!item.subItem || item.subItem.length === 0) {
this._closeSubMenu();
return;
@@ -45,7 +45,7 @@ export class AISubItemList extends WithDisposable(LitElement) {
${menuItemStyles}
`;
private _handleClick = (subItem: AISubItemConfig) => {
private readonly _handleClick = (subItem: AISubItemConfig) => {
this.onClick?.();
if (subItem.handler) {
// TODO: add parameters to ai handler
@@ -22,11 +22,11 @@ import { embedCardModalStyles } from './styles.js';
export class EmbedCardCreateModal extends WithDisposable(ShadowlessElement) {
static override styles = embedCardModalStyles;
private _onCancel = () => {
private readonly _onCancel = () => {
this.remove();
};
private _onConfirm = () => {
private readonly _onConfirm = () => {
const url = this.input.value;
if (!isValidUrl(url)) {
@@ -91,7 +91,7 @@ export class EmbedCardCreateModal extends WithDisposable(ShadowlessElement) {
this.remove();
};
private _onDocumentKeydown = (e: KeyboardEvent) => {
private readonly _onDocumentKeydown = (e: KeyboardEvent) => {
e.stopPropagation();
if (e.key === 'Enter' && !e.isComposing) {
this._onConfirm();
@@ -144,11 +144,11 @@ export class EmbedCardEditModal extends SignalWatcher(
private _blockComponent: BlockComponent | null = null;
private _hide = () => {
private readonly _hide = () => {
this.remove();
};
private _onKeydown = (e: KeyboardEvent) => {
private readonly _onKeydown = (e: KeyboardEvent) => {
e.stopPropagation();
if (e.key === 'Enter' && !(e.isComposing || e.shiftKey)) {
this._onSave();
@@ -159,7 +159,7 @@ export class EmbedCardEditModal extends SignalWatcher(
}
};
private _onReset = () => {
private readonly _onReset = () => {
const blockComponent = this._blockComponent;
if (!blockComponent) {
@@ -186,7 +186,7 @@ export class EmbedCardEditModal extends SignalWatcher(
this.remove();
};
private _onSave = () => {
private readonly _onSave = () => {
const blockComponent = this._blockComponent;
if (!blockComponent) {
@@ -224,12 +224,12 @@ export class EmbedCardEditModal extends SignalWatcher(
this.remove();
};
private _updateDescription = (e: InputEvent) => {
private readonly _updateDescription = (e: InputEvent) => {
const target = e.target as HTMLTextAreaElement;
this.description$.value = target.value;
};
private _updateTitle = (e: InputEvent) => {
private readonly _updateTitle = (e: InputEvent) => {
const target = e.target as HTMLInputElement;
this.title$.value = target.value;
};
@@ -31,13 +31,13 @@ export type FileDropOptions = {
export class FileDropManager {
private static _dropResult: DropResult | null = null;
private _blockService: BlockService;
private readonly _blockService: BlockService;
private _fileDropOptions: FileDropOptions;
private readonly _fileDropOptions: FileDropOptions;
private _indicator!: DragIndicator;
private readonly _indicator!: DragIndicator;
private _onDrop = (event: DragEvent) => {
private readonly _onDrop = (event: DragEvent) => {
this._indicator.rect = null;
const { onDrop } = this._fileDropOptions;
@@ -64,7 +64,7 @@ export class SmoothCorner extends LitElement {
}
`;
private _resizeObserver: ResizeObserver | null = null;
private readonly _resizeObserver: ResizeObserver | null = null;
get _path() {
return getFigmaSquircleSvgPath({
@@ -137,16 +137,18 @@ export const quickActionConfig: QuickActionConfig[] = [
const doc = host.doc;
const autofill = getTitleFromSelectedModels(selectedModels);
void promptDocTitle(host, autofill).then(title => {
if (title === null) return;
convertSelectedBlocksToLinkedDoc(
host.std,
doc,
draftedModels,
title
).catch(console.error);
notifyDocCreated(host, doc);
});
promptDocTitle(host, autofill)
.then(title => {
if (title === null) return;
convertSelectedBlocksToLinkedDoc(
host.std,
doc,
draftedModels,
title
).catch(console.error);
notifyDocCreated(host, doc);
})
.catch(console.error);
},
},
];
@@ -44,11 +44,11 @@ export type ExportOptions = {
imageProxyEndpoint: string;
};
export class ExportManager {
private _exportOptions: ExportOptions = {
private readonly _exportOptions: ExportOptions = {
imageProxyEndpoint: DEFAULT_IMAGE_PROXY_ENDPOINT,
};
private _replaceRichTextWithSvgElement = (element: HTMLElement) => {
private readonly _replaceRichTextWithSvgElement = (element: HTMLElement) => {
const richList = Array.from(element.querySelectorAll('.inline-editor'));
richList.forEach(rich => {
const svgEle = this._elementToSvgElement(
@@ -8,7 +8,7 @@ export class Zip {
private finalized = false;
private zip = new fflate.Zip((err, chunk, final) => {
private readonly zip = new fflate.Zip((err, chunk, final) => {
if (!err) {
const temp = new Uint8Array(this.compressed.length + chunk.length);
temp.set(this.compressed);
@@ -26,7 +26,7 @@ import { addSiblingAttachmentBlocks } from './utils.js';
export class AttachmentBlockService extends BlockService {
static override readonly flavour = AttachmentBlockSchema.model.flavour;
private _fileDropOptions: FileDropOptions = {
private readonly _fileDropOptions: FileDropOptions = {
flavour: this.flavour,
onDrop: async ({ files, targetModel, place, point }) => {
if (!files.length) return false;
@@ -67,7 +67,7 @@ export class AttachmentEmbedService extends Extension {
return this.configs.values();
}
constructor(private configs: Map<string, AttachmentEmbedConfig>) {
constructor(private readonly configs: Map<string, AttachmentEmbedConfig>) {
super();
}
@@ -24,9 +24,12 @@ export type BlockQueryDataSourceConfig = {
// @ts-expect-error FIXME: ts error
export class BlockQueryDataSource extends DataSourceBase {
private columnMetaMap = new Map<string, PropertyMetaConfig<any, any, any>>();
private readonly columnMetaMap = new Map<
string,
PropertyMetaConfig<any, any, any>
>();
private meta: BlockMeta;
private readonly meta: BlockMeta;
blockMap = new Map<string, Block>();
@@ -60,8 +63,8 @@ export class BlockQueryDataSource extends DataSourceBase {
}
constructor(
private host: EditorHost,
private block: DataViewBlockModel,
private readonly host: EditorHost,
private readonly block: DataViewBlockModel,
config: BlockQueryDataSourceConfig
) {
super();
@@ -92,7 +92,7 @@ export class DataViewBlockComponent extends CaptionedBlockComponent<DataViewBloc
}
`;
private _clickDatabaseOps = (e: MouseEvent) => {
private readonly _clickDatabaseOps = (e: MouseEvent) => {
popMenu(popupTargetFromElement(e.currentTarget as HTMLElement), {
options: {
items: [
@@ -136,7 +136,7 @@ export class DataViewBlockComponent extends CaptionedBlockComponent<DataViewBloc
private _dataSource?: DataSource;
private dataView = new DataView();
private readonly dataView = new DataView();
_bindHotkey: DataViewProps['bindHotkey'] = hotkeys => {
return {
@@ -70,29 +70,29 @@ export class DatabaseTitle extends WithDisposable(ShadowlessElement) {
}
`;
private compositionEnd = () => {
private readonly compositionEnd = () => {
this.titleText.replace(0, this.titleText.length, this.input.value);
};
private onBlur = () => {
private readonly onBlur = () => {
this.isFocus = false;
};
private onFocus = () => {
private readonly onFocus = () => {
this.isFocus = true;
if (this.database?.viewSelection$?.value) {
this.database?.setSelection(undefined);
}
};
private onInput = (e: InputEvent) => {
private readonly onInput = (e: InputEvent) => {
this.text = this.input.value;
if (!e.isComposing) {
this.titleText.replace(0, this.titleText.length, this.input.value);
}
};
private onKeyDown = (event: KeyboardEvent) => {
private readonly onKeyDown = (event: KeyboardEvent) => {
event.stopPropagation();
if (event.key === 'Enter' && !event.isComposing) {
event.preventDefault();
@@ -106,7 +106,7 @@ export class DatabaseBlockComponent extends CaptionedBlockComponent<
}
`;
private _clickDatabaseOps = (e: MouseEvent) => {
private readonly _clickDatabaseOps = (e: MouseEvent) => {
const options = this.optionsConfig.configure(this.model, {
items: [
menu.input({
@@ -156,9 +156,9 @@ export class DatabaseBlockComponent extends CaptionedBlockComponent<
private _dataSource?: DatabaseBlockDataSource;
private dataView = new DataView();
private readonly dataView = new DataView();
private renderTitle = (dataViewMethod: DataViewInstance) => {
private readonly renderTitle = (dataViewMethod: DataViewInstance) => {
const addRow = () => dataViewMethod.addRow?.('start');
return html` <affine-database-title
style="overflow: hidden"
@@ -82,7 +82,7 @@ export class LinkCell extends BaseCellRenderer<string> {
}
`;
private _onClick = (event: Event) => {
private readonly _onClick = (event: Event) => {
event.stopPropagation();
const value = this.value ?? '';
@@ -102,7 +102,7 @@ export class LinkCell extends BaseCellRenderer<string> {
}
};
private _onEdit = (e: Event) => {
private readonly _onEdit = (e: Event) => {
e.stopPropagation();
this.selectCurrentCell(true);
};
@@ -199,13 +199,13 @@ export class LinkCellEditing extends BaseCellRenderer<string> {
}
`;
private _focusEnd = () => {
private readonly _focusEnd = () => {
const end = this._container.value.length;
this._container.focus();
this._container.setSelectionRange(end, end);
};
private _onKeydown = (e: KeyboardEvent) => {
private readonly _onKeydown = (e: KeyboardEvent) => {
if (e.key === 'Enter' && !e.isComposing) {
this._setValue();
setTimeout(() => {
@@ -214,7 +214,7 @@ export class LinkCellEditing extends BaseCellRenderer<string> {
}
};
private _setValue = (value: string = this._container.value) => {
private readonly _setValue = (value: string = this._container.value) => {
let url = value;
if (isValidUrl(value)) {
url = normalizeUrl(value);
@@ -205,7 +205,7 @@ export class RichTextCellEditing extends BaseCellRenderer<Text> {
}
`;
private _handleKeyDown = (event: KeyboardEvent) => {
private readonly _handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') {
if (event.key === 'Tab') {
event.preventDefault();
@@ -274,12 +274,12 @@ export class RichTextCellEditing extends BaseCellRenderer<Text> {
}
};
private _initYText = (text?: string) => {
private readonly _initYText = (text?: string) => {
const yText = new Text(text);
this.onChange(yText);
};
private _onSoftEnter = () => {
private readonly _onSoftEnter = () => {
if (this.value && this.inlineEditor) {
const inlineRange = this.inlineEditor.getInlineRange();
assertExists(inlineRange);
@@ -205,7 +205,7 @@ export class HeaderAreaTextCell extends BaseTextCell {
}
export class HeaderAreaTextCellEditing extends BaseTextCell {
private _onCopy = (e: ClipboardEvent) => {
private readonly _onCopy = (e: ClipboardEvent) => {
const inlineEditor = this.inlineEditor;
assertExists(inlineEditor);
@@ -222,7 +222,7 @@ export class HeaderAreaTextCellEditing extends BaseTextCell {
e.stopPropagation();
};
private _onCut = (e: ClipboardEvent) => {
private readonly _onCut = (e: ClipboardEvent) => {
const inlineEditor = this.inlineEditor;
assertExists(inlineEditor);
@@ -244,7 +244,7 @@ export class HeaderAreaTextCellEditing extends BaseTextCell {
e.stopPropagation();
};
private _onPaste = (e: ClipboardEvent) => {
private readonly _onPaste = (e: ClipboardEvent) => {
const inlineEditor = this.inlineEditor;
const inlineRange = inlineEditor?.getInlineRange();
if (!inlineRange) return;
@@ -31,7 +31,7 @@ export class EdgelessTextBlockComponent extends GfxBlockComponent<EdgelessTextBl
}
`;
private _resizeObserver = new ResizeObserver(() => {
private readonly _resizeObserver = new ResizeObserver(() => {
if (this.doc.readonly) {
return;
}
@@ -28,7 +28,7 @@ export class ImageBlockService extends BlockService {
static setImageProxyURL = setImageProxyMiddlewareURL;
private _fileDropOptions: FileDropOptions = {
private readonly _fileDropOptions: FileDropOptions = {
flavour: this.flavour,
onDrop: async ({ files, targetModel, place, point }) => {
const imageFiles = files.filter(file => file.type.startsWith('image/'));
@@ -22,7 +22,7 @@ export class NoteBlockService extends BlockService {
private _anchorSel: BlockSelection | null = null;
private _bindMoveBlockHotKey = () => {
private readonly _bindMoveBlockHotKey = () => {
return moveBlockConfigs.reduce(
(acc, config) => {
const keys = config.hotkey.reduce(
@@ -46,7 +46,7 @@ export class NoteBlockService extends BlockService {
);
};
private _bindQuickActionHotKey = () => {
private readonly _bindQuickActionHotKey = () => {
return quickActionConfig
.filter(config => config.hotkey)
.reduce(
@@ -65,7 +65,7 @@ export class NoteBlockService extends BlockService {
);
};
private _bindTextConversionHotKey = () => {
private readonly _bindTextConversionHotKey = () => {
return textConversionConfigs
.filter(item => item.hotkey)
.reduce(
@@ -131,7 +131,7 @@ export class NoteBlockService extends BlockService {
private _focusBlock: BlockComponent | null = null;
private _getClosestNoteByBlockId = (blockId: string) => {
private readonly _getClosestNoteByBlockId = (blockId: string) => {
const doc = this._std.doc;
let parent = doc.getBlock(blockId)?.model ?? null;
while (parent) {
@@ -143,7 +143,7 @@ export class NoteBlockService extends BlockService {
return null;
};
private _onArrowDown = (ctx: UIEventStateContext) => {
private readonly _onArrowDown = (ctx: UIEventStateContext) => {
const event = ctx.get('defaultState').event;
const [result] = this._std.command
@@ -240,7 +240,7 @@ export class NoteBlockService extends BlockService {
return result;
};
private _onArrowUp = (ctx: UIEventStateContext) => {
private readonly _onArrowUp = (ctx: UIEventStateContext) => {
const event = ctx.get('defaultState').event;
const [result] = this._std.command
@@ -336,7 +336,7 @@ export class NoteBlockService extends BlockService {
return result;
};
private _onBlockShiftDown = (cmd: BlockSuite.CommandChain) => {
private readonly _onBlockShiftDown = (cmd: BlockSuite.CommandChain) => {
return cmd
.getBlockSelections()
.inline<'currentSelectionPath' | 'anchorBlock'>((ctx, next) => {
@@ -376,7 +376,7 @@ export class NoteBlockService extends BlockService {
.selectBlocksBetween({ tail: true });
};
private _onBlockShiftUp = (cmd: BlockSuite.CommandChain) => {
private readonly _onBlockShiftUp = (cmd: BlockSuite.CommandChain) => {
return cmd
.getBlockSelections()
.inline<'currentSelectionPath' | 'anchorBlock'>((ctx, next) => {
@@ -414,7 +414,7 @@ export class NoteBlockService extends BlockService {
.selectBlocksBetween({ tail: false });
};
private _onEnter = (ctx: UIEventStateContext) => {
private readonly _onEnter = (ctx: UIEventStateContext) => {
const event = ctx.get('defaultState').event;
const [result] = this._std.command
.chain()
@@ -461,7 +461,7 @@ export class NoteBlockService extends BlockService {
return result;
};
private _onEsc = () => {
private readonly _onEsc = () => {
const [result] = this._std.command
.chain()
.getBlockSelections()
@@ -482,7 +482,7 @@ export class NoteBlockService extends BlockService {
return result;
};
private _onSelectAll: UIEventHandler = ctx => {
private readonly _onSelectAll: UIEventHandler = ctx => {
const selection = this._std.selection;
const block = selection.find('block');
if (!block) {
@@ -506,7 +506,7 @@ export class NoteBlockService extends BlockService {
});
};
private _onShiftArrowDown = () => {
private readonly _onShiftArrowDown = () => {
const [result] = this._std.command
.chain()
.try(cmd => [
@@ -518,7 +518,7 @@ export class NoteBlockService extends BlockService {
return result;
};
private _onShiftArrowUp = () => {
private readonly _onShiftArrowUp = () => {
const [result] = this._std.command
.chain()
.try(cmd => [
@@ -530,7 +530,7 @@ export class NoteBlockService extends BlockService {
return result;
};
private _reset = () => {
private readonly _reset = () => {
this._anchorSel = null;
this._focusBlock = null;
};
@@ -18,7 +18,7 @@ import { ClipboardAdapter } from './adapter.js';
import { copyMiddleware, pasteMiddleware } from './middlewares/index.js';
export class PageClipboard {
private _copySelected = (onCopy?: () => void) => {
private readonly _copySelected = (onCopy?: () => void) => {
return this._std.command
.chain()
.with({ onCopy })
@@ -57,7 +57,7 @@ const findLast = (snapshot: SliceSnapshot): BlockSnapshot | null => {
};
class PointState {
private _blockFromPath = (path: string) => {
private readonly _blockFromPath = (path: string) => {
const block = this.std.view.getBlock(path);
assertExists(block);
return block;
@@ -88,7 +88,7 @@ class PointState {
}
class PasteTr {
private _getDeltas = () => {
private readonly _getDeltas = () => {
const firstTextSnapshot = this._textFromSnapshot(this.firstSnapshot!);
const lastTextSnapshot = this._textFromSnapshot(this.lastSnapshot!);
const fromDelta = this.pointState.text.sliceToDelta(
@@ -111,7 +111,7 @@ class PasteTr {
};
};
private _mergeCode = () => {
private readonly _mergeCode = () => {
const deltas: DeltaOperation[] = [{ retain: this.pointState.point.index }];
this.snapshot.content.forEach((blockSnapshot, i) => {
if (blockSnapshot.props.text) {
@@ -126,7 +126,7 @@ class PasteTr {
this.snapshot.content = [];
};
private _mergeMultiple = () => {
private readonly _mergeMultiple = () => {
this._updateFlavour();
const { lastTextSnapshot, toDelta, firstDelta, lastDelta } =
@@ -152,7 +152,7 @@ class PasteTr {
lastTextSnapshot.delta = [...lastDelta, ...toDelta];
};
private _mergeSingle = () => {
private readonly _mergeSingle = () => {
this._updateFlavour();
const { firstDelta } = this._getDeltas();
const { index, length } = this.pointState.point;
@@ -172,14 +172,14 @@ class PasteTr {
this._updateSnapshot();
};
private _textFromSnapshot = (snapshot: BlockSnapshot) => {
private readonly _textFromSnapshot = (snapshot: BlockSnapshot) => {
return (snapshot.props.text ?? { delta: [] }) as Record<
'delta',
DeltaOperation[]
>;
};
private _updateSnapshot = () => {
private readonly _updateSnapshot = () => {
if (this.snapshot.content.length === 0) {
this.firstSnapshot = this.lastSnapshot = undefined;
return;
@@ -192,7 +192,7 @@ class PasteTr {
private readonly firstSnapshotIsPlainText: boolean;
private lastIndex: number;
private readonly lastIndex: number;
private lastSnapshot?: BlockSnapshot;
@@ -123,9 +123,9 @@ interface BlockConfig {
}
export class EdgelessClipboardController extends PageClipboard {
private _blockConfigs: BlockConfig[] = [];
private readonly _blockConfigs: BlockConfig[] = [];
private _initEdgelessClipboard = () => {
private readonly _initEdgelessClipboard = () => {
this.host.handleEvent(
'copy',
ctx => {
@@ -156,7 +156,7 @@ export class EdgelessClipboardController extends PageClipboard {
);
};
private _onCopy = async (
private readonly _onCopy = async (
_context: UIEventStateContext,
surfaceSelection: SurfaceSelection[]
) => {
@@ -184,7 +184,7 @@ export class EdgelessClipboardController extends PageClipboard {
});
};
private _onCut = async (_context: UIEventStateContext) => {
private readonly _onCut = async (_context: UIEventStateContext) => {
const { surfaceSelections, selectedElements } = this.selectionManager;
if (selectedElements.length === 0) return;
@@ -214,7 +214,7 @@ export class EdgelessClipboardController extends PageClipboard {
});
};
private _onPaste = async (_context: UIEventStateContext) => {
private readonly _onPaste = async (_context: UIEventStateContext) => {
if (
document.activeElement instanceof HTMLInputElement ||
document.activeElement instanceof HTMLTextAreaElement
@@ -162,7 +162,7 @@ export class EdgelessAutoComplete extends WithDisposable(LitElement) {
private _autoCompleteOverlay!: AutoCompleteOverlay;
private _onPointerDown = (e: PointerEvent, type: Direction) => {
private readonly _onPointerDown = (e: PointerEvent, type: Direction) => {
const { service } = this.edgeless;
const viewportRect = service.viewport.boundingClientRect;
const start = service.viewport.toModelCoord(
@@ -80,7 +80,7 @@ export class AutoCompleteTextOverlay extends AutoCompleteTargetOverlay {
}
export class AutoCompleteNoteOverlay extends AutoCompleteTargetOverlay {
private _background: string;
private readonly _background: string;
constructor(gfx: GfxController, xywh: XYWH, background: string) {
super(gfx, xywh);
@@ -110,7 +110,7 @@ export class AutoCompleteNoteOverlay extends AutoCompleteTargetOverlay {
}
export class AutoCompleteFrameOverlay extends AutoCompleteTargetOverlay {
private _strokeColor;
private readonly _strokeColor;
constructor(gfx: GfxController, xywh: XYWH, strokeColor: string) {
super(gfx, xywh);
@@ -151,7 +151,7 @@ export class AutoCompleteFrameOverlay extends AutoCompleteTargetOverlay {
}
export class AutoCompleteShapeOverlay extends Overlay {
private _shape: Shape;
private readonly _shape: Shape;
constructor(
gfx: GfxController,
@@ -17,7 +17,7 @@ import { keepColor, preprocessColor } from './utils.js';
type Type = 'normal' | 'custom';
export class EdgelessColorPickerButton extends WithDisposable(LitElement) {
#select = (e: ColorEvent) => {
readonly #select = (e: ColorEvent) => {
this.#pick({ palette: e.detail });
};
@@ -49,7 +49,7 @@ export class EdgelessColorPicker extends SignalWatcher(
#alphaRect = new DOMRect();
#editAlpha = (e: InputEvent) => {
readonly #editAlpha = (e: InputEvent) => {
const target = e.target as HTMLInputElement;
const orignalValue = target.value;
let value = orignalValue.trim().replace(/[^0-9]/, '');
@@ -71,7 +71,7 @@ export class EdgelessColorPicker extends SignalWatcher(
this.#pick();
};
#editHex = (e: KeyboardEvent) => {
readonly #editHex = (e: KeyboardEvent) => {
e.stopPropagation();
const target = e.target as HTMLInputElement;
@@ -61,12 +61,12 @@ const styles = css`
export class FramePreview extends WithDisposable(ShadowlessElement) {
static override styles = styles;
private _clearFrameDisposables = () => {
private readonly _clearFrameDisposables = () => {
this._frameDisposables?.dispose();
this._frameDisposables = null;
};
private _docFilter: Query = {
private readonly _docFilter: Query = {
mode: 'loose',
match: [
{
@@ -80,9 +80,10 @@ export class FramePreview extends WithDisposable(ShadowlessElement) {
private _previewDoc: Doc | null = null;
private _previewSpec = SpecProvider.getInstance().getSpec('edgeless:preview');
private readonly _previewSpec =
SpecProvider.getInstance().getSpec('edgeless:preview');
private _updateFrameViewportWH = () => {
private readonly _updateFrameViewportWH = () => {
const [, , w, h] = deserializeXYWH(this.frame.xywh);
let scale = 1;
@@ -107,7 +107,10 @@ export class EdgelessLineWidthPanel extends WithDisposable(LitElement) {
private _dragConfig: DragConfig | null = null;
private _getDragHandlePosition = (e: PointerEvent, config: DragConfig) => {
private readonly _getDragHandlePosition = (
e: PointerEvent,
config: DragConfig
) => {
const x = e.clientX;
const { boundLeft, bottomLineWidth, stepWidth, containerWidth } = config;
@@ -128,7 +131,7 @@ export class EdgelessLineWidthPanel extends WithDisposable(LitElement) {
return dragHandlerPosition;
};
private _onPointerDown = (e: PointerEvent) => {
private readonly _onPointerDown = (e: PointerEvent) => {
e.preventDefault();
if (this.disable) return;
const { left, width } = this._lineWidthPanel.getBoundingClientRect();
@@ -142,7 +145,7 @@ export class EdgelessLineWidthPanel extends WithDisposable(LitElement) {
this._onPointerMove(e);
};
private _onPointerMove = (e: PointerEvent) => {
private readonly _onPointerMove = (e: PointerEvent) => {
e.preventDefault();
if (!this._dragConfig) return;
const dragHandlerPosition = this._getDragHandlePosition(
@@ -154,7 +157,7 @@ export class EdgelessLineWidthPanel extends WithDisposable(LitElement) {
this._updateIconsColor();
};
private _onPointerOut = (e: PointerEvent) => {
private readonly _onPointerOut = (e: PointerEvent) => {
// If the pointer is out of the line width panel
// Stop dragging and update the selected size by nearest size.
e.preventDefault();
@@ -167,7 +170,7 @@ export class EdgelessLineWidthPanel extends WithDisposable(LitElement) {
this._dragConfig = null;
};
private _onPointerUp = (e: PointerEvent) => {
private readonly _onPointerUp = (e: PointerEvent) => {
e.preventDefault();
if (!this._dragConfig) return;
const dragHandlerPosition = this._getDragHandlePosition(
@@ -178,7 +181,7 @@ export class EdgelessLineWidthPanel extends WithDisposable(LitElement) {
this._dragConfig = null;
};
private _updateIconsColor = () => {
private readonly _updateIconsColor = () => {
if (!this._dragHandle.offsetParent) {
requestConnectedFrame(() => this._updateIconsColor(), this);
return;
@@ -45,7 +45,7 @@ export class EdgelessScalePanel extends LitElement {
}
`;
private _onKeydown = (e: KeyboardEvent) => {
private readonly _onKeydown = (e: KeyboardEvent) => {
e.stopPropagation();
if (e.key === 'Enter' && !e.isComposing) {
@@ -54,7 +54,7 @@ export class EdgelessSizePanel extends LitElement {
}
`;
private _onKeydown = (e: KeyboardEvent) => {
private readonly _onKeydown = (e: KeyboardEvent) => {
e.stopPropagation();
if (e.key === 'Enter' && !e.isComposing) {
@@ -451,7 +451,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
private _dragEndCallback: (() => void)[] = [];
private _initSelectedSlot = () => {
private readonly _initSelectedSlot = () => {
this._propDisposables.forEach(disposable => disposable.dispose());
this._propDisposables = [];
@@ -466,7 +466,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
});
};
private _onDragEnd = () => {
private readonly _onDragEnd = () => {
this.slots.dragEnd.emit();
this.doc.transact(() => {
@@ -488,7 +488,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
this.frameOverlay.clear();
};
private _onDragMove = (
private readonly _onDragMove = (
newBounds: Map<
string,
{
@@ -561,7 +561,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
});
};
private _onDragRotate = (center: IPoint, delta: number) => {
private readonly _onDragRotate = (center: IPoint, delta: number) => {
this.slots.dragRotate.emit();
const { selection } = this;
@@ -606,7 +606,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
this._updateMode();
};
private _onDragStart = () => {
private readonly _onDragStart = () => {
this.slots.dragStart.emit();
const rotation = this._resizeManager.rotation;
@@ -651,9 +651,9 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
private _propDisposables: Disposable[] = [];
private _resizeManager: HandleResizeManager;
private readonly _resizeManager: HandleResizeManager;
private _updateCursor = (
private readonly _updateCursor = (
dragging: boolean,
options?: {
type: 'resize' | 'rotate';
@@ -711,7 +711,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
this.gfx.cursor$.value = cursor;
};
private _updateMode = () => {
private readonly _updateMode = () => {
if (this._cursorRotate) {
this._mode = 'rotate';
return;
@@ -738,7 +738,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
}
};
private _updateOnElementChange = (
private readonly _updateOnElementChange = (
element: string | { id: string },
fromRemote: boolean = false
) => {
@@ -754,7 +754,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
}
};
private _updateOnSelectionChange = () => {
private readonly _updateOnSelectionChange = () => {
this._initSelectedSlot();
this._updateSelectedRect();
this._updateResizeManagerState(true);
@@ -763,7 +763,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
this._updateMode();
};
private _updateOnViewportChange = () => {
private readonly _updateOnViewportChange = () => {
if (this.selection.empty) {
return;
}
@@ -775,7 +775,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
/**
* @param refresh indicate whether to completely refresh the state of resize manager, otherwise only update the position
*/
private _updateResizeManagerState = (refresh: boolean) => {
private readonly _updateResizeManagerState = (refresh: boolean) => {
const {
_resizeManager,
_selectedRect,
@@ -813,7 +813,7 @@ export class EdgelessSelectedRectWidget extends WidgetComponent<
borderStyle: 'solid',
};
private _updateSelectedRect = requestThrottledConnectedFrame(() => {
private readonly _updateSelectedRect = requestThrottledConnectedFrame(() => {
const { zoom, selection, gfx } = this;
const elements = selection.selectedElements;
@@ -64,13 +64,13 @@ export class HandleResizeManager {
private _locked = false;
private _onDragEnd: DragEndHandler;
private readonly _onDragEnd: DragEndHandler;
private _onDragStart: DragStartHandler;
private readonly _onDragStart: DragStartHandler;
private _onResizeMove: ResizeMoveHandler;
private readonly _onResizeMove: ResizeMoveHandler;
private _onRotateMove: RotateMoveHandler;
private readonly _onRotateMove: RotateMoveHandler;
private _origin: { x: number; y: number } = { x: 0, y: 0 };
@@ -67,7 +67,7 @@ export class EdgelessConnectorLabelEditor extends WithDisposable(
private _resizeObserver: ResizeObserver | null = null;
private _updateLabelRect = () => {
private readonly _updateLabelRect = () => {
const { connector, edgeless } = this;
if (!connector || !edgeless) return;
@@ -69,7 +69,7 @@ export class EdgelessTextEditor extends WithDisposable(ShadowlessElement) {
private _keeping = false;
private _updateRect = () => {
private readonly _updateRect = () => {
const edgeless = this.edgeless;
const element = this.element;
@@ -36,7 +36,7 @@ export class EdgelessBrushMenu extends EdgelessToolbarToolMixin(
}
`;
private _props$ = computed(() => {
private readonly _props$ = computed(() => {
const { color, lineWidth } =
this.edgeless.std.get(EditPropsStore).lastProps$.value.brush;
return {
@@ -43,7 +43,7 @@ export class EdgelessBrushToolButton extends EdgelessToolbarToolMixin(
}
`;
private _color$ = computed(() => {
private readonly _color$ = computed(() => {
const theme = this.edgeless.std.get(ThemeProvider).theme$.value;
return this.edgeless.std
.get(ThemeProvider)
@@ -97,7 +97,7 @@ export class EdgelessConnectorMenu extends EdgelessToolbarToolMixin(
}
`;
private _props$ = computed(() => {
private readonly _props$ = computed(() => {
const { mode, stroke, strokeWidth } =
this.edgeless.std.get(EditPropsStore).lastProps$.value.connector;
return { mode, stroke, strokeWidth };
@@ -39,7 +39,7 @@ export class EdgelessConnectorToolButton extends QuickToolMixin(
}
`;
private _mode$ = computed(() => {
private readonly _mode$ = computed(() => {
return this.edgeless.std.get(EditPropsStore).lastProps$.value.connector
.mode;
});
@@ -229,7 +229,7 @@ export class EdgelessToolbarWidget extends WidgetComponent<
@state()
accessor containerWidth = 1920;
private _onContainerResize = debounce(({ w }: { w: number }) => {
private readonly _onContainerResize = debounce(({ w }: { w: number }) => {
if (!this.isConnected) return;
this.slots.resize.emit({ w, h: TOOLBAR_HEIGHT });
@@ -262,17 +262,17 @@ export class EdgelessToolbarWidget extends WidgetComponent<
private _resizeObserver: ResizeObserver | null = null;
private _slotsProvider = new ContextProvider(this, {
private readonly _slotsProvider = new ContextProvider(this, {
context: edgelessToolbarSlotsContext,
initialValue: { resize: new Slot() } satisfies EdgelessToolbarSlots,
});
private _themeProvider = new ContextProvider(this, {
private readonly _themeProvider = new ContextProvider(this, {
context: edgelessToolbarThemeContext,
initialValue: ColorScheme.Light,
});
private _toolbarProvider = new ContextProvider(this, {
private readonly _toolbarProvider = new ContextProvider(this, {
context: edgelessToolbarContext,
initialValue: this,
});
@@ -33,7 +33,7 @@ export class EdgelessLassoToolButton extends QuickToolMixin(
}
`;
private _changeTool = () => {
private readonly _changeTool = () => {
const tool = this.edgelessTool;
if (tool.type !== 'lasso') {
this.setEdgelessTool({ type: 'lasso', mode: this.curMode });
@@ -95,7 +95,7 @@ export class EdgelessMindmapMenu extends EdgelessToolbarToolMixin(
}
`;
private _style$ = computed(() => {
private readonly _style$ = computed(() => {
const { style } =
this.edgeless.std.get(EditPropsStore).lastProps$.value.mindmap;
return style;
@@ -124,7 +124,7 @@ export class EdgelessMindmapToolButton extends EdgelessToolbarToolMixin(
}
`;
private _style$ = computed(() => {
private readonly _style$ = computed(() => {
const { style } =
this.edgeless.std.get(EditPropsStore).lastProps$.value.mindmap;
return style;
@@ -125,7 +125,7 @@ export class EdgelessNoteSeniorButton extends EdgelessToolbarToolMixin(
}
`;
private _noteBg$ = computed(() => {
private readonly _noteBg$ = computed(() => {
return this.edgeless.std
.get(ThemeProvider)
.generateColorProperty(
@@ -134,7 +134,7 @@ export class EdgelessNoteSeniorButton extends EdgelessToolbarToolMixin(
);
});
private _states = ['childFlavour', 'childType', 'tip'] as const;
private readonly _states = ['childFlavour', 'childType', 'tip'] as const;
override enableActiveBackground = true;
@@ -27,7 +27,7 @@ export class EdgelessNoteToolButton extends QuickToolMixin(LitElement) {
private _noteMenu: MenuPopper<EdgelessNoteMenu> | null = null;
private _states = ['childFlavour', 'childType', 'tip'] as const;
private readonly _states = ['childFlavour', 'childType', 'tip'] as const;
override type: GfxToolsFullOptionValue['type'] = 'affine:note';
@@ -71,7 +71,7 @@ export class EdgelessNavigatorSettingButton extends WithDisposable(LitElement) {
typeof createButtonPopper
> | null = null;
private _onBlackBackgroundChange = (checked: boolean) => {
private readonly _onBlackBackgroundChange = (checked: boolean) => {
this.blackBackground = checked;
this.edgeless.slots.navigatorSettingUpdated.emit({
blackBackground: this.blackBackground,
@@ -59,12 +59,12 @@ export class EdgelessShapeMenu extends SignalWatcher(
}
`;
private _shapeName$: Signal<ShapeName> = signal(ShapeType.Rect);
private readonly _shapeName$: Signal<ShapeName> = signal(ShapeType.Rect);
@property({ attribute: false })
accessor edgeless!: EdgelessRootBlockComponent;
private _props$ = computed(() => {
private readonly _props$ = computed(() => {
const shapeName: ShapeName = this._shapeName$.value;
const { shapeStyle, fillColor, strokeColor, radius } =
this.edgeless.std.get(EditPropsStore).lastProps$.value[
@@ -79,7 +79,7 @@ export class EdgelessShapeMenu extends SignalWatcher(
};
});
private _setFillColor = (fillColor: ShapeFillColor) => {
private readonly _setFillColor = (fillColor: ShapeFillColor) => {
const filled = !isTransparent(fillColor);
let strokeColor = fillColor.replace(
SHAPE_COLOR_PREFIX,
@@ -101,7 +101,7 @@ export class EdgelessShapeMenu extends SignalWatcher(
this.onChange(shapeName);
};
private _setShapeStyle = (shapeStyle: ShapeStyle) => {
private readonly _setShapeStyle = (shapeStyle: ShapeStyle) => {
const { shapeName } = this._props$.value;
this.edgeless.std
.get(EditPropsStore)
@@ -23,14 +23,14 @@ export class EdgelessShapeToolButton extends EdgelessToolbarToolMixin(
}
`;
private _handleShapeClick = (shape: DraggableShape) => {
private readonly _handleShapeClick = (shape: DraggableShape) => {
this.setEdgelessTool(this.type, {
shapeName: shape.name,
});
if (!this.popper) this._toggleMenu();
};
private _handleWrapperClick = () => {
private readonly _handleWrapperClick = () => {
if (this.tryDisposePopper()) return;
this.setEdgelessTool(this.type, {
@@ -67,7 +67,7 @@ export class EdgelessShapeToolElement extends WithDisposable(LitElement) {
}
`;
private _addShape = (coord: Coord, padding: Coord) => {
private readonly _addShape = (coord: Coord, padding: Coord) => {
const width = 100;
const height = 100;
const { x: edgelessX, y: edgelessY } =
@@ -85,7 +85,7 @@ export class EdgelessShapeToolElement extends WithDisposable(LitElement) {
});
};
private _onDragEnd = async (coord: Coord) => {
private readonly _onDragEnd = async (coord: Coord) => {
if (this._startCoord.x === coord.x && this._startCoord.y === coord.y) {
this.handleClick();
this._dragging = false;
@@ -118,7 +118,7 @@ export class EdgelessShapeToolElement extends WithDisposable(LitElement) {
}
};
private _onDragMove = (coord: Coord) => {
private readonly _onDragMove = (coord: Coord) => {
if (!this._dragging) {
return;
}
@@ -153,7 +153,7 @@ export class EdgelessShapeToolElement extends WithDisposable(LitElement) {
this._isOutside = isOut;
};
private _onDragStart = (coord: Coord) => {
private readonly _onDragStart = (coord: Coord) => {
this._startCoord = { x: coord.x, y: coord.y };
if (this.order !== 1) {
return;
@@ -162,20 +162,20 @@ export class EdgelessShapeToolElement extends WithDisposable(LitElement) {
this._shapeElement.classList.add('dragging');
};
private _onMouseMove = (event: MouseEvent) => {
private readonly _onMouseMove = (event: MouseEvent) => {
if (!this._dragging) {
return;
}
this._onDragMove({ x: event.clientX, y: event.clientY });
};
private _onMouseUp = (event: MouseEvent) => {
private readonly _onMouseUp = (event: MouseEvent) => {
this._onDragEnd({ x: event.clientX, y: event.clientY }).catch(
console.error
);
};
private _onTouchEnd = (event: TouchEvent) => {
private readonly _onTouchEnd = (event: TouchEvent) => {
if (!event.changedTouches.length) return;
this._onDragEnd({
@@ -185,7 +185,7 @@ export class EdgelessShapeToolElement extends WithDisposable(LitElement) {
}).catch(console.error);
};
private _touchMove = (event: TouchEvent) => {
private readonly _touchMove = (event: TouchEvent) => {
if (!this._dragging) {
return;
}
@@ -195,7 +195,7 @@ export class EdgelessShapeToolElement extends WithDisposable(LitElement) {
});
};
private _transformMap: TransformMap = {
private readonly _transformMap: TransformMap = {
z1: { x: 0, y: 5, scale: 1.1, origin: '50% 100%' },
z2: { x: -15, y: 0, scale: 0.75, origin: '20% 20%' },
z3: { x: 15, y: 0, scale: 0.75, origin: '80% 20%' },
@@ -50,7 +50,7 @@ export class OverlayScrollbar extends LitElement {
}
`;
private _disposable = new DisposableGroup();
private readonly _disposable = new DisposableGroup();
private _handleVisible = false;
@@ -98,21 +98,24 @@ export class EdgelessRootBlockComponent extends BlockComponent<
}
`;
private _refreshLayerViewport = requestThrottledConnectedFrame(() => {
const { zoom, translateX, translateY } = this.gfx.viewport;
const { gap } = getBackgroundGrid(zoom, true);
private readonly _refreshLayerViewport = requestThrottledConnectedFrame(
() => {
const { zoom, translateX, translateY } = this.gfx.viewport;
const { gap } = getBackgroundGrid(zoom, true);
if (this.backgroundElm) {
this.backgroundElm.style.setProperty(
'background-position',
`${translateX}px ${translateY}px`
);
this.backgroundElm.style.setProperty(
'background-size',
`${gap}px ${gap}px`
);
}
}, this);
if (this.backgroundElm) {
this.backgroundElm.style.setProperty(
'background-position',
`${translateX}px ${translateY}px`
);
this.backgroundElm.style.setProperty(
'background-size',
`${gap}px ${gap}px`
);
}
},
this
);
private _resizeObserver: ResizeObserver | null = null;
@@ -64,16 +64,19 @@ export class EdgelessRootPreviewBlockComponent extends BlockComponent<
@query('.edgeless-background')
accessor background!: HTMLDivElement;
private _refreshLayerViewport = requestThrottledConnectedFrame(() => {
const { zoom, translateX, translateY } = this.service.viewport;
const { gap } = getBackgroundGrid(zoom, true);
private readonly _refreshLayerViewport = requestThrottledConnectedFrame(
() => {
const { zoom, translateX, translateY } = this.service.viewport;
const { gap } = getBackgroundGrid(zoom, true);
this.background.style.setProperty(
'background-position',
`${translateX}px ${translateY}px`
);
this.background.style.setProperty('background-size', `${gap}px ${gap}px`);
}, this);
this.background.style.setProperty(
'background-position',
`${translateX}px ${translateY}px`
);
this.background.style.setProperty('background-size', `${gap}px ${gap}px`);
},
this
);
private _resizeObserver: ResizeObserver | null = null;
@@ -56,7 +56,7 @@ import {
export class EdgelessRootService extends RootService implements SurfaceContext {
static override readonly flavour = RootBlockSchema.model.flavour;
private _surface: SurfaceBlockModel;
private readonly _surface: SurfaceBlockModel;
elementRenderers: Record<string, ElementRenderer> = elementRenderers;
@@ -37,7 +37,7 @@ export class FrameOverlay extends Overlay {
private _innerElements = new Set<GfxModel>();
private _prevXYWH: SerializedXYWH | null = null;
private readonly _prevXYWH: SerializedXYWH | null = null;
private get _frameManager() {
return this.gfx.std.get(
@@ -132,7 +132,7 @@ export class FrameOverlay extends Overlay {
export class EdgelessFrameManager extends GfxExtension {
static override key = 'frame-manager';
private _disposable = new DisposableGroup();
private readonly _disposable = new DisposableGroup();
/**
* Get all sorted frames by presentation orderer,
@@ -19,7 +19,7 @@ export class BrushTool extends BaseTool {
private _lastPopLength = 0;
private _pressureSupportedPointerIds = new Set<number>();
private readonly _pressureSupportedPointerIds = new Set<number>();
private _straightLineType: 'horizontal' | 'vertical' | null = null;
@@ -36,7 +36,7 @@ type DragMindMapCtx = {
};
export class MindMapExt extends DefaultToolExt {
private _responseAreaUpdated = new Set<MindmapElementModel>();
private readonly _responseAreaUpdated = new Set<MindmapElementModel>();
override supportedDragTypes: DefaultModeDragType[] = [
DefaultModeDragType.ContentMoving,
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import {
ConnectorUtils,
OverlayIdentifier,
@@ -79,14 +78,14 @@ export class DefaultTool extends BaseTool {
private _autoPanTimer: number | null = null;
private _clearDisposable = () => {
private readonly _clearDisposable = () => {
if (this._disposables) {
this._disposables.dispose();
this._disposables = null;
}
};
private _clearSelectingState = () => {
private readonly _clearSelectingState = () => {
this._stopAutoPanning();
this._clearDisposable();
@@ -110,13 +109,13 @@ export class DefaultTool extends BaseTool {
private _lock = false;
private _panViewport = (delta: IVec) => {
private readonly _panViewport = (delta: IVec) => {
this._accumulateDelta[0] += delta[0];
this._accumulateDelta[1] += delta[1];
this.gfx.viewport.applyDeltaCenter(delta[0], delta[1]);
};
private _pendingUpdates = new Map<
private readonly _pendingUpdates = new Map<
GfxBlockModel | GfxPrimitiveElementModel,
Partial<GfxBlockModel>
>();
@@ -139,7 +138,7 @@ export class DefaultTool extends BaseTool {
endY: number;
} = null;
private _startAutoPanning = (delta: IVec) => {
private readonly _startAutoPanning = (delta: IVec) => {
this._panViewport(delta);
this._updateSelectingState(delta);
this._stopAutoPanning();
@@ -150,7 +149,7 @@ export class DefaultTool extends BaseTool {
}, 30);
};
private _stopAutoPanning = () => {
private readonly _stopAutoPanning = () => {
if (this._autoPanTimer) {
clearTimeout(this._autoPanTimer);
this._autoPanTimer = null;
@@ -159,7 +158,7 @@ export class DefaultTool extends BaseTool {
private _toBeMoved: GfxModel[] = [];
private _updateSelectingState = (delta: IVec = [0, 0]) => {
private readonly _updateSelectingState = (delta: IVec = [0, 0]) => {
const { gfx } = this;
if (gfx.keyboard.spaceKey$.peek() && this._selectionRectTransition) {
@@ -943,6 +942,7 @@ export class DefaultTool extends BaseTool {
}
}
// eslint-disable-next-line @typescript-eslint/no-misused-promises
override async dragStart(e: PointerEventState) {
if (this.edgelessSelectionManager.editing) return;
// Determine the drag type based on the current state and event
@@ -30,9 +30,9 @@ export class EraserTool extends BaseTool {
private _eraserPoints: IVec[] = [];
private _eraseTargets = new Set<BlockSuite.EdgelessModel>();
private readonly _eraseTargets = new Set<BlockSuite.EdgelessModel>();
private _loop = () => {
private readonly _loop = () => {
const now = Date.now();
const elapsed = now - this._timestamp;
@@ -62,7 +62,7 @@ export class EraserTool extends BaseTool {
this._timer = requestAnimationFrame(this._loop);
};
private _overlay = new EraserOverlay(this.gfx);
private readonly _overlay = new EraserOverlay(this.gfx);
private _prevEraserPoint: IVec = [0, 0];
@@ -68,7 +68,7 @@ export class LassoTool extends BaseTool<LassoToolOption> {
private _lastPoint: IVec = [0, 0];
private _loop = () => {
private readonly _loop = () => {
const path =
this.activatedOption.mode === LassoMode.FreeHand
? CommonUtils.getSvgPathFromStroke(this._lassoPoints)
@@ -79,7 +79,7 @@ export class LassoTool extends BaseTool<LassoToolOption> {
this._raf = requestAnimationFrame(this._loop);
};
private _overlay = new LassoOverlay(this.gfx);
private readonly _overlay = new LassoOverlay(this.gfx);
private _raf = 0;
@@ -11,7 +11,7 @@ import {
} from '../../_common/utils/render-linked-doc.js';
export class PageKeyboardManager {
private _handleDelete = () => {
private readonly _handleDelete = () => {
const blockSelections = this._currentSelection.filter(sel =>
sel.is('block')
);
@@ -117,16 +117,18 @@ export class PageKeyboardManager {
const doc = rootComponent.host.doc;
const autofill = getTitleFromSelectedModels(selectedModels);
void promptDocTitle(rootComponent.host, autofill).then(title => {
if (title === null) return;
convertSelectedBlocksToLinkedDoc(
this.rootComponent.std,
doc,
draftedModels,
title
).catch(console.error);
notifyDocCreated(rootComponent.host, doc);
});
promptDocTitle(rootComponent.host, autofill)
.then(title => {
if (title === null) return;
convertSelectedBlocksToLinkedDoc(
this.rootComponent.std,
doc,
draftedModels,
title
).catch(console.error);
notifyDocCreated(rootComponent.host, doc);
})
.catch(console.error);
}
private _deleteBlocksBySelection(selections: BlockSelection[]) {
@@ -1,7 +1,7 @@
class RandomPicker<T> {
private _copyArray: T[];
private _originalArray: T[];
private readonly _originalArray: T[];
constructor(array: T[]) {
this._originalArray = [...array];
@@ -16,7 +16,7 @@ import type { RootBlockComponent } from './types.js';
export abstract class RootService extends BlockService {
static override readonly flavour = RootBlockSchema.model.flavour;
private _fileDropOptions: FileDropOptions = {
private readonly _fileDropOptions: FileDropOptions = {
flavour: this.flavour,
};
@@ -84,18 +84,18 @@ export class AffineAIPanelWidget extends WidgetComponent {
private _answer: string | null = null;
private _cancelCallback = () => {
private readonly _cancelCallback = () => {
this.focus();
};
private _clearDiscardModal = () => {
private readonly _clearDiscardModal = () => {
if (this._discardModalAbort) {
this._discardModalAbort.abort();
this._discardModalAbort = null;
}
};
private _clickOutside = () => {
private readonly _clickOutside = () => {
switch (this.state) {
case 'hidden':
return;
@@ -112,21 +112,21 @@ export class AffineAIPanelWidget extends WidgetComponent {
}
};
private _discardCallback = () => {
private readonly _discardCallback = () => {
this.hide();
this.config?.discardCallback?.();
};
private _discardModalAbort: AbortController | null = null;
private _inputFinish = (text: string) => {
private readonly _inputFinish = (text: string) => {
this._inputText = text;
this.generate();
};
private _inputText: string | null = null;
private _onDocumentClick = (e: MouseEvent) => {
private readonly _onDocumentClick = (e: MouseEvent) => {
if (
this.state !== 'hidden' &&
e.target !== this &&
@@ -139,7 +139,7 @@ export class AffineAIPanelWidget extends WidgetComponent {
return false;
};
private _onKeyDown = (event: KeyboardEvent) => {
private readonly _onKeyDown = (event: KeyboardEvent) => {
event.stopPropagation();
const { state } = this;
if (state !== 'generating' && state !== 'input') {
@@ -157,7 +157,7 @@ export class AffineAIPanelWidget extends WidgetComponent {
}
};
private _resetAbortController = () => {
private readonly _resetAbortController = () => {
if (this.state === 'generating') {
this._abortController.abort();
}
@@ -127,7 +127,7 @@ export class AIPanelError extends WithDisposable(LitElement) {
}
`;
private _getResponseGroup = () => {
private readonly _getResponseGroup = () => {
let responseGroup: AIItemGroupConfig[] = [];
const errorType = this.config.error?.type;
if (errorType && errorType !== AIErrorType.GeneralNetworkError) {
@@ -84,7 +84,7 @@ export class AIPanelInput extends WithDisposable(LitElement) {
}
`;
private _onInput = () => {
private readonly _onInput = () => {
this.textarea.style.height = 'auto';
this.textarea.style.height = this.textarea.scrollHeight + 'px';
@@ -99,14 +99,14 @@ export class AIPanelInput extends WithDisposable(LitElement) {
}
};
private _onKeyDown = (e: KeyboardEvent) => {
private readonly _onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
e.preventDefault();
this._sendToAI();
}
};
private _sendToAI = () => {
private readonly _sendToAI = () => {
const value = this.textarea.value.trim();
if (value.length === 0) return;
@@ -47,7 +47,7 @@ export class LanguageListButton extends WithDisposable(
private _abortController?: AbortController;
private _clickLangBtn = () => {
private readonly _clickLangBtn = () => {
if (this.blockComponent.doc.readonly) return;
if (this._abortController) {
// Close the language list if it's already opened.
@@ -24,7 +24,7 @@ export class AffineCodeToolbarWidget extends WidgetComponent<
private _isActivated = false;
private _setHoverController = () => {
private readonly _setHoverController = () => {
this._hoverController = null;
this._hoverController = new HoverController(
this,
@@ -34,11 +34,11 @@ export class AffineDocRemoteSelectionWidget extends WidgetComponent {
}
`;
private _abortController = new AbortController();
private readonly _abortController = new AbortController();
private _remoteColorManager: RemoteColorManager | null = null;
private _remoteSelections = computed(() => {
private readonly _remoteSelections = computed(() => {
const status = this.doc.awarenessStore.getStates();
return [...this.std.selection.remoteSelections.entries()].map(
([id, selections]) => {
@@ -51,7 +51,7 @@ export class AffineDocRemoteSelectionWidget extends WidgetComponent {
);
});
private _resizeObserver: ResizeObserver = new ResizeObserver(() => {
private readonly _resizeObserver: ResizeObserver = new ResizeObserver(() => {
this.requestUpdate();
});
@@ -31,7 +31,7 @@ export type DropResult = {
};
export class DragHandleOptionsRunner {
private optionMap = new Map<DragHandleOption, number>();
private readonly optionMap = new Map<DragHandleOption, number>();
get options(): DragHandleOption[] {
return Array.from(this.optionMap.keys());
@@ -58,16 +58,18 @@ export class AffineDragHandleWidget extends WidgetComponent<RootBlockModel> {
private _anchorModelDisposables: DisposableGroup | null = null;
private _dragEventWatcher = new DragEventWatcher(this);
private readonly _dragEventWatcher = new DragEventWatcher(this);
private _getBlockView = (blockId: string) => {
private readonly _getBlockView = (blockId: string) => {
return this.host.view.getBlock(blockId);
};
/**
* When dragging, should update indicator position and target drop block id
*/
private _getDropResult = (state: DndEventState): DropResult | null => {
private readonly _getDropResult = (
state: DndEventState
): DropResult | null => {
const point = new Point(state.raw.x, state.raw.y);
const closestBlock = getClosestBlockByPoint(
this.host,
@@ -137,22 +139,22 @@ export class AffineDragHandleWidget extends WidgetComponent<RootBlockModel> {
return dropIndicator;
};
private _handleEventWatcher = new HandleEventWatcher(this);
private readonly _handleEventWatcher = new HandleEventWatcher(this);
private _keyboardEventWatcher = new KeyboardEventWatcher(this);
private readonly _keyboardEventWatcher = new KeyboardEventWatcher(this);
private _legacyDragEventWatcher = new LegacyDragEventWatcher(this);
private readonly _legacyDragEventWatcher = new LegacyDragEventWatcher(this);
private _pageWatcher = new PageWatcher(this);
private readonly _pageWatcher = new PageWatcher(this);
private _removeDropIndicator = () => {
private readonly _removeDropIndicator = () => {
if (this.dropIndicator) {
this.dropIndicator.remove();
this.dropIndicator = null;
}
};
private _reset = () => {
private readonly _reset = () => {
this.draggingElements = [];
this.dropBlockId = '';
this.dropType = null;
@@ -173,17 +175,17 @@ export class AffineDragHandleWidget extends WidgetComponent<RootBlockModel> {
this._resetCursor();
};
private _resetCursor = () => {
private readonly _resetCursor = () => {
document.documentElement.classList.remove('affine-drag-preview-grabbing');
};
private _resetDropResult = () => {
private readonly _resetDropResult = () => {
this.dropBlockId = '';
this.dropType = null;
if (this.dropIndicator) this.dropIndicator.rect = null;
};
private _updateDropResult = (dropResult: DropResult | null) => {
private readonly _updateDropResult = (dropResult: DropResult | null) => {
if (!this.dropIndicator) return;
this.dropBlockId = dropResult?.dropBlockId ?? '';
this.dropType = dropResult?.dropType ?? null;
@@ -11,7 +11,7 @@ import { DragPreview } from '../components/drag-preview.js';
import type { AffineDragHandleWidget } from '../drag-handle.js';
export class PreviewHelper {
private _calculatePreviewOffset = (
private readonly _calculatePreviewOffset = (
blocks: BlockComponent[],
state: DndEventState
) => {
@@ -20,7 +20,7 @@ export class PreviewHelper {
return previewOffset;
};
private _calculateQuery = (selectedIds: string[]): Query => {
private readonly _calculateQuery = (selectedIds: string[]): Query => {
const ids: Array<{ id: string; viewType: BlockViewType }> = selectedIds.map(
id => ({
id,
@@ -15,7 +15,7 @@ import {
} from '../utils.js';
export class RectHelper {
private _getHoveredBlocks = (): BlockComponent[] => {
private readonly _getHoveredBlocks = (): BlockComponent[] => {
if (!this.widget.isHoverDragHandleVisible || !this.widget.anchorBlockId)
return [];
@@ -44,7 +44,7 @@ import { surfaceRefToEmbed } from '../middleware/surface-ref-to-embed.js';
import { containBlock, includeTextSelection } from '../utils.js';
export class DragEventWatcher {
private _computeEdgelessBound = (
private readonly _computeEdgelessBound = (
x: number,
y: number,
width: number,
@@ -70,19 +70,19 @@ export class DragEventWatcher {
);
};
private _createDropIndicator = () => {
private readonly _createDropIndicator = () => {
if (!this.widget.dropIndicator) {
this.widget.dropIndicator = new DropIndicator();
this.widget.rootComponent.append(this.widget.dropIndicator);
}
};
private _dragEndHandler: UIEventHandler = () => {
private readonly _dragEndHandler: UIEventHandler = () => {
this.widget.clearRaf();
this.widget.hide(true);
};
private _dragMoveHandler: UIEventHandler = ctx => {
private readonly _dragMoveHandler: UIEventHandler = ctx => {
if (
this.widget.isHoverDragHandleVisible ||
this.widget.isTopLevelDragHandleVisible
@@ -104,7 +104,7 @@ export class DragEventWatcher {
/**
* When start dragging, should set dragging elements and create drag preview
*/
private _dragStartHandler: UIEventHandler = ctx => {
private readonly _dragStartHandler: UIEventHandler = ctx => {
const state = ctx.get('dndState');
// If not click left button to start dragging, should do nothing
const { button } = state.raw;
@@ -115,14 +115,14 @@ export class DragEventWatcher {
return this._onDragStart(state);
};
private _dropHandler = (context: UIEventStateContext) => {
private readonly _dropHandler = (context: UIEventStateContext) => {
this._onDrop(context);
this._std.selection.setGroup('gfx', []);
this.widget.clearRaf();
this.widget.hide(true);
};
private _onDragMove = (state: DndEventState) => {
private readonly _onDragMove = (state: DndEventState) => {
this.widget.clearRaf();
this.widget.rafID = requestAnimationFrame(() => {
@@ -132,7 +132,7 @@ export class DragEventWatcher {
return true;
};
private _onDragStart = (state: DndEventState) => {
private readonly _onDragStart = (state: DndEventState) => {
// Get current hover block element by path
const hoverBlock = this.widget.anchorBlockComponent.peek();
if (!hoverBlock) return false;
@@ -234,7 +234,7 @@ export class DragEventWatcher {
return true;
};
private _onDrop = (context: UIEventStateContext) => {
private readonly _onDrop = (context: UIEventStateContext) => {
const state = context.get('dndState');
const event = state.raw;
@@ -280,7 +280,7 @@ export class DragEventWatcher {
this._deserializeData(state, parent.id, index).catch(console.error);
};
private _onDropNoteOnNote = (
private readonly _onDropNoteOnNote = (
snapshot: SliceSnapshot,
parent?: string,
index?: number
@@ -305,7 +305,7 @@ export class DragEventWatcher {
.catch(console.error);
};
private _onDropOnEdgelessCanvas = (context: UIEventStateContext) => {
private readonly _onDropOnEdgelessCanvas = (context: UIEventStateContext) => {
const state = context.get('dndState');
// If drop a note, should do nothing
const snapshot = this._deserializeSnapshot(state);
@@ -405,7 +405,7 @@ export class DragEventWatcher {
this._deserializeData(state, newNoteId).catch(console.error);
};
private _startDragging = (
private readonly _startDragging = (
blocks: BlockComponent[],
state: DndEventState,
dragPreviewEl?: HTMLElement,
@@ -435,7 +435,7 @@ export class DragEventWatcher {
this._serializeData(slice, state);
};
private _trackLinkedDocCreated = (id: string) => {
private readonly _trackLinkedDocCreated = (id: string) => {
const isNewBlock = !this._std.doc.hasBlock(id);
if (!isNewBlock) {
return;
@@ -24,7 +24,9 @@ import {
import type { AffineDragHandleWidget } from '../drag-handle.js';
export class EdgelessWatcher {
private _handleEdgelessToolUpdated = (newTool: GfxToolsFullOptionValue) => {
private readonly _handleEdgelessToolUpdated = (
newTool: GfxToolsFullOptionValue
) => {
if (newTool.type === 'default') {
this.checkTopLevelBlockSelection();
} else {
@@ -32,7 +34,7 @@ export class EdgelessWatcher {
}
};
private _handleEdgelessViewPortUpdated = ({
private readonly _handleEdgelessViewPortUpdated = ({
zoom,
center,
}: {
@@ -60,7 +62,7 @@ export class EdgelessWatcher {
}
};
private _showDragHandleOnTopLevelBlocks = async () => {
private readonly _showDragHandleOnTopLevelBlocks = async () => {
if (this.widget.mode === 'page') return;
const { edgelessRoot } = this;
await edgelessRoot.surface.updateComplete;
@@ -99,13 +101,13 @@ export class EdgelessWatcher {
this.widget.isTopLevelDragHandleVisible = true;
};
private _updateDragHoverRectTopLevelBlock = () => {
private readonly _updateDragHoverRectTopLevelBlock = () => {
if (!this.widget.dragHoverRect) return;
this.widget.dragHoverRect = this.hoverAreaRectTopLevelBlock;
};
private _updateDragPreviewOnViewportUpdate = () => {
private readonly _updateDragPreviewOnViewportUpdate = () => {
if (this.widget.dragPreview && this.widget.lastDragPointerState) {
this.updateDragPreviewPosition(this.widget.lastDragPointerState);
}
@@ -6,14 +6,14 @@ import {
import type { AffineDragHandleWidget } from '../drag-handle.js';
export class HandleEventWatcher {
private _onDragHandlePointerDown = () => {
private readonly _onDragHandlePointerDown = () => {
if (!this.widget.isHoverDragHandleVisible || !this.widget.anchorBlockId)
return;
this.widget.dragHoverRect = this.widget.draggingAreaRect.value;
};
private _onDragHandlePointerEnter = () => {
private readonly _onDragHandlePointerEnter = () => {
const container = this.widget.dragHandleContainer;
const grabber = this.widget.dragHandleGrabber;
if (!container || !grabber) return;
@@ -42,7 +42,7 @@ export class HandleEventWatcher {
}
};
private _onDragHandlePointerLeave = () => {
private readonly _onDragHandlePointerLeave = () => {
this.widget.isDragHandleHovered = false;
this.widget.dragHoverRect = null;
@@ -53,7 +53,7 @@ export class HandleEventWatcher {
this.widget.pointerEventWatcher.showDragHandleOnHoverBlock();
};
private _onDragHandlePointerUp = () => {
private readonly _onDragHandlePointerUp = () => {
if (!this.widget.isHoverDragHandleVisible) return;
this.widget.dragHoverRect = null;
};
@@ -3,7 +3,7 @@ import type { UIEventHandler } from '@blocksuite/block-std';
import type { AffineDragHandleWidget } from '../drag-handle.js';
export class KeyboardEventWatcher {
private _keyboardHandler: UIEventHandler = ctx => {
private readonly _keyboardHandler: UIEventHandler = ctx => {
if (!this.widget.dragging || !this.widget.dragPreview) {
return;
}
@@ -30,11 +30,11 @@ import {
} from '../utils.js';
export class LegacyDragEventWatcher {
private _changeCursorToGrabbing = () => {
private readonly _changeCursorToGrabbing = () => {
document.documentElement.classList.add('affine-drag-preview-grabbing');
};
private _createDropIndicator = () => {
private readonly _createDropIndicator = () => {
if (!this.widget.dropIndicator) {
this.widget.dropIndicator = new DropIndicator();
this.widget.rootComponent.append(this.widget.dropIndicator);
@@ -44,7 +44,7 @@ export class LegacyDragEventWatcher {
/**
* When drag end, should move blocks to drop position
*/
private _dragEndHandler: UIEventHandler = ctx => {
private readonly _dragEndHandler: UIEventHandler = ctx => {
this.widget.clearRaf();
if (!this.widget.dragging || !this.widget.dragPreview) return false;
if (this.widget.draggingElements.length === 0 || this.widget.doc.readonly) {
@@ -96,7 +96,7 @@ export class LegacyDragEventWatcher {
* Update indicator position
* Update drop block id
*/
private _dragMoveHandler: UIEventHandler = ctx => {
private readonly _dragMoveHandler: UIEventHandler = ctx => {
if (
this.widget.isHoverDragHandleVisible ||
this.widget.isTopLevelDragHandleVisible
@@ -130,7 +130,7 @@ export class LegacyDragEventWatcher {
/**
* When start dragging, should set dragging elements and create drag preview
*/
private _dragStartHandler: UIEventHandler = ctx => {
private readonly _dragStartHandler: UIEventHandler = ctx => {
const state = ctx.get('pointerState');
// If not click left button to start dragging, should do nothing
const { button } = state.raw;
@@ -156,7 +156,7 @@ export class LegacyDragEventWatcher {
return this._onDragStart(state);
};
private _onDragEnd = (state: PointerEventState) => {
private readonly _onDragEnd = (state: PointerEventState) => {
const targetBlockId = this.widget.dropBlockId;
const dropType = this.widget.dropType;
const draggingElements = this.widget.draggingElements;
@@ -306,7 +306,7 @@ export class LegacyDragEventWatcher {
return true;
};
private _onDragMove = (state: PointerEventState) => {
private readonly _onDragMove = (state: PointerEventState) => {
this.widget.clearRaf();
this.widget.rafID = requestAnimationFrame(() => {
@@ -318,7 +318,7 @@ export class LegacyDragEventWatcher {
return true;
};
private _onDragStart = (state: PointerEventState) => {
private readonly _onDragStart = (state: PointerEventState) => {
// Get current hover block element by path
const hoverBlock = this.widget.anchorBlockComponent.peek();
if (!hoverBlock) return false;
@@ -432,7 +432,7 @@ export class LegacyDragEventWatcher {
return true;
};
private _startDragging = (
private readonly _startDragging = (
blocks: BlockComponent[],
state: PointerEventState,
dragPreviewEl?: HTMLElement,
@@ -30,7 +30,7 @@ import {
} from '../utils.js';
export class PointerEventWatcher {
private _canEditing = (noteBlock: BlockComponent) => {
private readonly _canEditing = (noteBlock: BlockComponent) => {
if (noteBlock.doc.id !== this.widget.doc.id) return false;
if (this.widget.mode === 'page') return true;
@@ -50,7 +50,7 @@ export class PointerEventWatcher {
* Should select the block and show slash menu if current block is not selected
* Should clear selection if current block is the first selected block
*/
private _clickHandler: UIEventHandler = ctx => {
private readonly _clickHandler: UIEventHandler = ctx => {
if (!this.widget.isHoverDragHandleVisible) return;
const state = ctx.get('pointerState');
@@ -90,7 +90,7 @@ export class PointerEventWatcher {
};
// Need to consider block padding and scale
private _getTopWithBlockComponent = (block: BlockComponent) => {
private readonly _getTopWithBlockComponent = (block: BlockComponent) => {
const computedStyle = getComputedStyle(block);
const { top } = block.getBoundingClientRect();
const paddingTop =
@@ -102,7 +102,7 @@ export class PointerEventWatcher {
);
};
private _containerStyle = computed(() => {
private readonly _containerStyle = computed(() => {
const draggingAreaRect = this.widget.draggingAreaRect.value;
if (!draggingAreaRect) return null;
@@ -135,7 +135,7 @@ export class PointerEventWatcher {
};
});
private _grabberStyle = computed(() => {
private readonly _grabberStyle = computed(() => {
const scaleInNote = this.widget.scaleInNote.value;
return {
width: `${DRAG_HANDLE_GRABBER_WIDTH * scaleInNote}px`,
@@ -151,7 +151,7 @@ export class PointerEventWatcher {
* When pointer move on block, should show drag handle
* And update hover block id and path
*/
private _pointerMoveOnBlock = (state: PointerEventState) => {
private readonly _pointerMoveOnBlock = (state: PointerEventState) => {
if (this.widget.isTopLevelDragHandleVisible) return;
const point = new Point(state.raw.x, state.raw.y);
@@ -190,7 +190,7 @@ export class PointerEventWatcher {
}
};
private _pointerOutHandler: UIEventHandler = ctx => {
private readonly _pointerOutHandler: UIEventHandler = ctx => {
const state = ctx.get('pointerState');
state.raw.preventDefault();
@@ -214,57 +214,60 @@ export class PointerEventWatcher {
}
};
private _throttledPointerMoveHandler = throttle<UIEventHandler>(ctx => {
if (
this.widget.doc.readonly ||
this.widget.dragging ||
!this.widget.isConnected
) {
this.widget.hide();
return;
}
if (this.widget.isTopLevelDragHandleVisible) return;
private readonly _throttledPointerMoveHandler = throttle<UIEventHandler>(
ctx => {
if (
this.widget.doc.readonly ||
this.widget.dragging ||
!this.widget.isConnected
) {
this.widget.hide();
return;
}
if (this.widget.isTopLevelDragHandleVisible) return;
const state = ctx.get('pointerState');
const { target } = state.raw;
const element = captureEventTarget(target);
// When pointer not on block or on dragging, should do nothing
if (!element) return;
const state = ctx.get('pointerState');
const { target } = state.raw;
const element = captureEventTarget(target);
// When pointer not on block or on dragging, should do nothing
if (!element) return;
// When pointer on drag handle, should do nothing
if (element.closest('.affine-drag-handle-container')) return;
// When pointer on drag handle, should do nothing
if (element.closest('.affine-drag-handle-container')) return;
// When pointer out of note block hover area or inside database, should hide drag handle
const point = new Point(state.raw.x, state.raw.y);
// When pointer out of note block hover area or inside database, should hide drag handle
const point = new Point(state.raw.x, state.raw.y);
const closestNoteBlock = getClosestNoteBlock(
this.widget.host,
this.widget.rootComponent,
point
) as NoteBlockComponent | null;
this.widget.noteScale.value =
this.widget.mode === 'page'
? 1
: (closestNoteBlock?.model.edgeless.scale ?? 1);
if (
closestNoteBlock &&
this._canEditing(closestNoteBlock) &&
!isOutOfNoteBlock(
const closestNoteBlock = getClosestNoteBlock(
this.widget.host,
closestNoteBlock,
point,
this.widget.scaleInNote.peek()
)
) {
this._pointerMoveOnBlock(state);
return true;
}
this.widget.rootComponent,
point
) as NoteBlockComponent | null;
this.widget.hide();
return false;
}, 1000 / 60);
this.widget.noteScale.value =
this.widget.mode === 'page'
? 1
: (closestNoteBlock?.model.edgeless.scale ?? 1);
if (
closestNoteBlock &&
this._canEditing(closestNoteBlock) &&
!isOutOfNoteBlock(
this.widget.host,
closestNoteBlock,
point,
this.widget.scaleInNote.peek()
)
) {
this._pointerMoveOnBlock(state);
return true;
}
this.widget.hide();
return false;
},
1000 / 60
);
// Multiple blocks: drag handle should show on the vertical middle of all blocks
showDragHandleOnHoverBlock = () => {
@@ -172,7 +172,7 @@ export class EdgelessAutoConnectWidget extends WidgetComponent<
}
`;
private _updateLabels = () => {
private readonly _updateLabels = () => {
const service = this.service;
if (!service.doc.root) return;
@@ -21,7 +21,7 @@ export class EdgelessCopilotToolbarEntry extends WithDisposable(LitElement) {
}
`;
private _onClick = () => {
private readonly _onClick = () => {
this.onClick?.();
this._showCopilotPanel();
};
@@ -81,14 +81,16 @@ export class EdgelessRemoteSelectionWidget extends WidgetComponent<
private _remoteColorManager: RemoteColorManager | null = null;
private _updateOnElementChange = (element: string | { id: string }) => {
private readonly _updateOnElementChange = (
element: string | { id: string }
) => {
const id = typeof element === 'string' ? element : element.id;
if (this.isConnected && this.selection.hasRemote(id))
this._updateRemoteRects();
};
private _updateRemoteCursor = () => {
private readonly _updateRemoteCursor = () => {
const remoteCursors: EdgelessRemoteSelectionWidget['_remoteCursors'] =
new Map();
const status = this.doc.awarenessStore.getStates();
@@ -106,7 +108,7 @@ export class EdgelessRemoteSelectionWidget extends WidgetComponent<
this._remoteCursors = remoteCursors;
};
private _updateRemoteRects = () => {
private readonly _updateRemoteRects = () => {
const { selection, block } = this;
const remoteSelectionsMap = selection.remoteSurfaceSelectionsMap;
const remoteRects: EdgelessRemoteSelectionWidget['_remoteRects'] =
@@ -148,7 +150,7 @@ export class EdgelessRemoteSelectionWidget extends WidgetComponent<
this._remoteRects = remoteRects;
};
private _updateTransform = requestThrottledConnectedFrame(() => {
private readonly _updateTransform = requestThrottledConnectedFrame(() => {
const { translateX, translateY, zoom } = this.edgeless.service.viewport;
this.style.setProperty('--v-zoom', `${zoom}`);
@@ -14,7 +14,7 @@ export class EdgelessAddFrameButton extends WithDisposable(LitElement) {
}
`;
private _createFrame = () => {
private readonly _createFrame = () => {
const frame = this.edgeless.service.frame.createFrameOnSelected();
if (!frame) return;
this.edgeless.std
@@ -16,7 +16,7 @@ export class EdgelessAddGroupButton extends WithDisposable(LitElement) {
}
`;
private _createGroup = () => {
private readonly _createGroup = () => {
this.edgeless.service.createGroupFromSelected();
};
@@ -23,11 +23,11 @@ import { attachmentViewToggleMenu } from '../../../attachment-block/index.js';
import type { EdgelessRootBlockComponent } from '../../edgeless/edgeless-root-block.js';
export class EdgelessChangeAttachmentButton extends WithDisposable(LitElement) {
private _download = () => {
private readonly _download = () => {
this._block?.download();
};
private _setCardStyle = (style: EmbedCardStyle) => {
private readonly _setCardStyle = (style: EmbedCardStyle) => {
const bounds = Bound.deserialize(this.model.xywh);
bounds.w = EMBED_CARD_WIDTH[style];
bounds.h = EMBED_CARD_HEIGHT[style];
@@ -35,7 +35,7 @@ export class EdgelessChangeAttachmentButton extends WithDisposable(LitElement) {
this.model.doc.updateBlock(this.model, { style, xywh });
};
private _showCaption = () => {
private readonly _showCaption = () => {
this._block?.captionEditor?.show();
};
@@ -44,12 +44,12 @@ function notEqual<K extends keyof BrushProps>(key: K, value: BrushProps[K]) {
}
export class EdgelessChangeBrushButton extends WithDisposable(LitElement) {
private _setBrushColor = ({ detail: color }: ColorEvent) => {
private readonly _setBrushColor = ({ detail: color }: ColorEvent) => {
this._setBrushProp('color', color);
this._selectedColor = color;
};
private _setLineWidth = ({ detail: lineWidth }: LineWidthEvent) => {
private readonly _setLineWidth = ({ detail: lineWidth }: LineWidthEvent) => {
this._setBrushProp('lineWidth', lineWidth);
this._selectedSize = lineWidth;
};
@@ -112,7 +112,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
}
`;
private _convertToCardView = () => {
private readonly _convertToCardView = () => {
if (this._isCardView) {
return;
}
@@ -162,7 +162,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
this._doc.deleteBlock(this.model);
};
private _convertToEmbedView = () => {
private readonly _convertToEmbedView = () => {
if (this._isEmbedView) {
return;
}
@@ -217,7 +217,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
this._doc.deleteBlock(this.model);
};
private _copyUrl = () => {
private readonly _copyUrl = () => {
let url!: ReturnType<GenerateDocUrlService['generateDocUrl']>;
if ('url' in this.model) {
@@ -241,7 +241,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
private _embedOptions: EmbedOptions | null = null;
private _getScale = () => {
private readonly _getScale = () => {
if ('scale' in this.model) {
return this.model.scale ?? 1;
} else if (isEmbedHtmlBlock(this.model)) {
@@ -252,11 +252,11 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
return bound.h / EMBED_CARD_HEIGHT[this.model.style];
};
private _open = () => {
private readonly _open = () => {
this._blockComponent?.open();
};
private _openEditPopup = (e: MouseEvent) => {
private readonly _openEditPopup = (e: MouseEvent) => {
e.stopPropagation();
if (isEmbedHtmlBlock(this.model)) return;
@@ -277,12 +277,12 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
});
};
private _peek = () => {
private readonly _peek = () => {
if (!this._blockComponent) return;
peek(this._blockComponent);
};
private _setCardStyle = (style: EmbedCardStyle) => {
private readonly _setCardStyle = (style: EmbedCardStyle) => {
const bounds = Bound.deserialize(this.model.xywh);
bounds.w = EMBED_CARD_WIDTH[style];
bounds.h = EMBED_CARD_HEIGHT[style];
@@ -295,7 +295,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
});
};
private _setEmbedScale = (scale: number) => {
private readonly _setEmbedScale = (scale: number) => {
if (isEmbedHtmlBlock(this.model)) return;
const bound = Bound.deserialize(this.model.xywh);
@@ -320,7 +320,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
});
};
private _toggleCardScaleSelector = (e: Event) => {
private readonly _toggleCardScaleSelector = (e: Event) => {
const opened = (e as CustomEvent<boolean>).detail;
if (!opened) return;
@@ -329,7 +329,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
});
};
private _toggleCardStyleSelector = (e: Event) => {
private readonly _toggleCardStyleSelector = (e: Event) => {
const opened = (e as CustomEvent<boolean>).detail;
if (!opened) return;
@@ -338,7 +338,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
});
};
private _toggleViewSelector = (e: Event) => {
private readonly _toggleViewSelector = (e: Event) => {
const opened = (e as CustomEvent<boolean>).detail;
if (!opened) return;
@@ -347,7 +347,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
});
};
private _trackViewSelected = (type: string) => {
private readonly _trackViewSelected = (type: string) => {
track(this.std, this.model, this._viewType, 'SelectedView', {
control: 'select view',
type: `${type} view`,
@@ -9,12 +9,12 @@ import { downloadImageBlob } from '../../../image-block/utils.js';
import type { EdgelessRootBlockComponent } from '../../edgeless/edgeless-root-block.js';
export class EdgelessChangeImageButton extends WithDisposable(LitElement) {
private _download = () => {
private readonly _download = () => {
if (!this._blockComponent) return;
downloadImageBlob(this._blockComponent).catch(console.error);
};
private _showCaption = () => {
private readonly _showCaption = () => {
this._blockComponent?.captionEditor?.show();
};
@@ -155,7 +155,7 @@ export class EdgelessChangeMindmapLayoutPanel extends LitElement {
}
export class EdgelessChangeMindmapButton extends WithDisposable(LitElement) {
private _updateLayoutType = (layoutType: LayoutType) => {
private readonly _updateLayoutType = (layoutType: LayoutType) => {
this.edgeless.std.get(EditPropsStore).recordLastProps('mindmap', {
layoutType,
});
@@ -166,7 +166,7 @@ export class EdgelessChangeMindmapButton extends WithDisposable(LitElement) {
this.layoutType = layoutType;
};
private _updateStyle = (style: MindmapStyle) => {
private readonly _updateStyle = (style: MindmapStyle) => {
this.edgeless.std.get(EditPropsStore).recordLastProps('mindmap', { style });
this._mindmaps.forEach(element => (element.style = style));
};
@@ -78,7 +78,7 @@ function getMostCommonBackground(
}
export class EdgelessChangeNoteButton extends WithDisposable(LitElement) {
private _setBorderRadius = (borderRadius: number) => {
private readonly _setBorderRadius = (borderRadius: number) => {
this.notes.forEach(note => {
const props = {
edgeless: {
@@ -92,7 +92,7 @@ export class EdgelessChangeNoteButton extends WithDisposable(LitElement) {
});
};
private _setNoteScale = (scale: number) => {
private readonly _setNoteScale = (scale: number) => {
this.notes.forEach(note => {
this.doc.updateBlock(note, () => {
const bound = Bound.deserialize(note.xywh);
@@ -176,7 +176,7 @@ export class EdgelessChangeTextMenu extends WithDisposable(LitElement) {
}
`;
private _setFontFamily = (fontFamily: FontFamily) => {
private readonly _setFontFamily = (fontFamily: FontFamily) => {
const currentFontWeight = getMostCommonFontWeight(this.elements);
const fontWeight = TextUtils.isFontWeightSupported(
fontFamily,
@@ -199,7 +199,7 @@ export class EdgelessChangeTextMenu extends WithDisposable(LitElement) {
});
};
private _setFontSize = (fontSize: number) => {
private readonly _setFontSize = (fontSize: number) => {
const props = { fontSize };
this.elements.forEach(element => {
this.service.updateElement(element.id, buildProps(element, props));
@@ -207,7 +207,7 @@ export class EdgelessChangeTextMenu extends WithDisposable(LitElement) {
});
};
private _setFontWeightAndStyle = (
private readonly _setFontWeightAndStyle = (
fontWeight: FontWeight,
fontStyle: FontStyle
) => {
@@ -218,21 +218,23 @@ export class EdgelessChangeTextMenu extends WithDisposable(LitElement) {
});
};
private _setTextAlign = (textAlign: TextAlign) => {
private readonly _setTextAlign = (textAlign: TextAlign) => {
const props = { textAlign };
this.elements.forEach(element => {
this.service.updateElement(element.id, buildProps(element, props));
});
};
private _setTextColor = ({ detail: color }: ColorEvent) => {
private readonly _setTextColor = ({ detail: color }: ColorEvent) => {
const props = { color };
this.elements.forEach(element => {
this.service.updateElement(element.id, buildProps(element, props));
});
};
private _updateElementBound = (element: BlockSuite.EdgelessTextModelType) => {
private readonly _updateElementBound = (
element: BlockSuite.EdgelessTextModelType
) => {
const elementType = this.elementType;
if (elementType === 'text' && element instanceof TextElementModel) {
// the change of font family will change the bound of the text
@@ -112,7 +112,7 @@ export class EdgelessElementToolbarWidget extends WidgetComponent<
}
`;
private _quickConnect = ({ x, y }: MouseEvent) => {
private readonly _quickConnect = ({ x, y }: MouseEvent) => {
const element = this.selection.selectedElements[0];
const point = this.edgeless.service.viewport.toViewCoordFromClientCoord([
x,
@@ -127,7 +127,9 @@ export class EdgelessElementToolbarWidget extends WidgetComponent<
ctc.quickConnect(point, element);
};
private _updateOnSelectedChange = (element: string | { id: string }) => {
private readonly _updateOnSelectedChange = (
element: string | { id: string }
) => {
const id = typeof element === 'string' ? element : element.id;
if (this.isConnected && !this._dragging && this.selection.has(id)) {
@@ -20,13 +20,13 @@ import {
} from '../../../edgeless/utils/query.js';
export class ElementToolbarMoreMenuContext extends MenuContext {
#empty = true;
readonly #empty: boolean;
#includedFrame = false;
readonly #includedFrame: boolean;
#multiple = false;
readonly #multiple: boolean;
#single = false;
readonly #single: boolean;
edgeless!: EdgelessRootBlockComponent;
@@ -82,7 +82,7 @@ export class EmbedCardToolbar extends WidgetComponent<
private _abortController = new AbortController();
private _copyUrl = () => {
private readonly _copyUrl = () => {
const model = this.focusModel;
if (!model) return;
@@ -109,7 +109,7 @@ export class EmbedCardToolbar extends WidgetComponent<
private _embedOptions: EmbedOptions | null = null;
private _openEditPopup = (e: MouseEvent) => {
private readonly _openEditPopup = (e: MouseEvent) => {
e.stopPropagation();
const model = this.focusModel;
@@ -126,12 +126,12 @@ export class EmbedCardToolbar extends WidgetComponent<
});
};
private _resetAbortController = () => {
private readonly _resetAbortController = () => {
this._abortController.abort();
this._abortController = new AbortController();
};
private _showCaption = () => {
private readonly _showCaption = () => {
const focusBlock = this.focusBlock;
if (!focusBlock) {
return;
@@ -151,7 +151,7 @@ export class EmbedCardToolbar extends WidgetComponent<
});
};
private _toggleCardStyleSelector = (e: Event) => {
private readonly _toggleCardStyleSelector = (e: Event) => {
const opened = (e as CustomEvent<boolean>).detail;
if (!opened) return;
@@ -163,7 +163,7 @@ export class EmbedCardToolbar extends WidgetComponent<
});
};
private _toggleViewSelector = (e: Event) => {
private readonly _toggleViewSelector = (e: Event) => {
const opened = (e as CustomEvent<boolean>).detail;
if (!opened) return;
@@ -175,7 +175,7 @@ export class EmbedCardToolbar extends WidgetComponent<
});
};
private _trackViewSelected = (type: string) => {
private readonly _trackViewSelected = (type: string) => {
const model = this.focusModel;
if (!model) return;
@@ -209,28 +209,30 @@ export function toolbarDefaultConfig(toolbar: AffineFormatBarWidget) {
const doc = host.doc;
const autofill = getTitleFromSelectedModels(selectedModels);
void promptDocTitle(host, autofill).then(async title => {
if (title === null) return;
await convertSelectedBlocksToLinkedDoc(
host.std,
doc,
draftedModels,
title
);
notifyDocCreated(host, doc);
host.std.getOptional(TelemetryProvider)?.track('DocCreated', {
control: 'create linked doc',
page: 'doc editor',
module: 'format toolbar',
type: 'embed-linked-doc',
});
host.std.getOptional(TelemetryProvider)?.track('LinkedDocCreated', {
control: 'create linked doc',
page: 'doc editor',
module: 'format toolbar',
type: 'embed-linked-doc',
});
});
promptDocTitle(host, autofill)
.then(async title => {
if (title === null) return;
await convertSelectedBlocksToLinkedDoc(
host.std,
doc,
draftedModels,
title
);
notifyDocCreated(host, doc);
host.std.getOptional(TelemetryProvider)?.track('DocCreated', {
control: 'create linked doc',
page: 'doc editor',
module: 'format toolbar',
type: 'embed-linked-doc',
});
host.std.getOptional(TelemetryProvider)?.track('LinkedDocCreated', {
control: 'create linked doc',
page: 'doc editor',
module: 'format toolbar',
type: 'embed-linked-doc',
});
})
.catch(console.error);
},
showWhen: chain => {
const [_, ctx] = chain
@@ -25,7 +25,7 @@ export class AffineImageToolbarWidget extends WidgetComponent<
private _isActivated = false;
private _setHoverController = () => {
private readonly _setHoverController = () => {
this._hoverController = null;
this._hoverController = new HoverController(
this,

Some files were not shown because too many files have changed in this diff Show More