refactor(editor): remove assertExists (#10615)

This commit is contained in:
Saul-Mirone
2025-03-05 00:13:08 +00:00
parent a6692f70aa
commit b8ecfbdae6
106 changed files with 863 additions and 517 deletions
@@ -10,7 +10,8 @@ import {
import type { EditorHost } from '@blocksuite/block-std';
import { DataSourceBase, type PropertyMetaConfig } from '@blocksuite/data-view';
import { propertyPresets } from '@blocksuite/data-view/property-presets';
import { assertExists, Slot } from '@blocksuite/global/utils';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import { Slot } from '@blocksuite/global/utils';
import type { Block, Store } from '@blocksuite/store';
import type { BlockMeta } from './block-meta/base.js';
@@ -95,7 +96,12 @@ export class BlockQueryDataSource extends DataSourceBase {
private getProperty(propertyId: string) {
const property = this.meta.properties.find(v => v.key === propertyId);
assertExists(property, `property ${propertyId} not found`);
if (!property) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
`property ${propertyId} not found`
);
}
return property;
}
@@ -18,7 +18,6 @@ import {
createIcon,
} from '@blocksuite/data-view';
import { IS_MAC } from '@blocksuite/global/env';
import { assertExists } from '@blocksuite/global/utils';
import type { DeltaInsert } from '@blocksuite/inline';
import type { BlockSnapshot } from '@blocksuite/store';
import { Text } from '@blocksuite/store';
@@ -338,7 +337,7 @@ export class RichTextCellEditing extends BaseRichTextCell {
private readonly _onSoftEnter = () => {
if (this.value && this.inlineEditor) {
const inlineRange = this.inlineEditor.getInlineRange();
assertExists(inlineRange);
if (!inlineRange) return;
const text = new Text(this.inlineEditor.yText);
text.replace(inlineRange.index, inlineRange.length, '\n');
@@ -351,7 +350,7 @@ export class RichTextCellEditing extends BaseRichTextCell {
private readonly _onCopy = (e: ClipboardEvent) => {
const inlineEditor = this.inlineEditor;
assertExists(inlineEditor);
if (!inlineEditor) return;
const inlineRange = inlineEditor.getInlineRange();
if (!inlineRange) return;
@@ -368,7 +367,7 @@ export class RichTextCellEditing extends BaseRichTextCell {
private readonly _onCut = (e: ClipboardEvent) => {
const inlineEditor = this.inlineEditor;
assertExists(inlineEditor);
if (!inlineEditor) return;
const inlineRange = inlineEditor.getInlineRange();
if (!inlineRange) return;
@@ -13,7 +13,6 @@ import {
} from '@blocksuite/affine-shared/utils';
import { BaseCellRenderer } from '@blocksuite/data-view';
import { IS_MAC } from '@blocksuite/global/env';
import { assertExists } from '@blocksuite/global/utils';
import { LinkedPageIcon } from '@blocksuite/icons/lit';
import type { DeltaInsert } from '@blocksuite/inline';
import type { BlockSnapshot, Text } from '@blocksuite/store';
@@ -205,7 +204,7 @@ export class HeaderAreaTextCell extends BaseTextCell {
export class HeaderAreaTextCellEditing extends BaseTextCell {
private readonly _onCopy = (e: ClipboardEvent) => {
const inlineEditor = this.inlineEditor;
assertExists(inlineEditor);
if (!inlineEditor) return;
const inlineRange = inlineEditor.getInlineRange();
if (!inlineRange) return;
@@ -222,7 +221,7 @@ export class HeaderAreaTextCellEditing extends BaseTextCell {
private readonly _onCut = (e: ClipboardEvent) => {
const inlineEditor = this.inlineEditor;
assertExists(inlineEditor);
if (!inlineEditor) return;
const inlineRange = inlineEditor.getInlineRange();
if (!inlineRange) return;
@@ -11,7 +11,6 @@ import { EMBED_CARD_HEIGHT } from '@blocksuite/affine-shared/consts';
import { NotificationProvider } from '@blocksuite/affine-shared/services';
import { matchModels, SpecProvider } from '@blocksuite/affine-shared/utils';
import { BlockStdScope } from '@blocksuite/block-std';
import { assertExists } from '@blocksuite/global/utils';
import {
type BlockModel,
type BlockSnapshot,
@@ -36,10 +35,12 @@ export function renderLinkedDocInCard(
card: EmbedLinkedDocBlockComponent | EmbedSyncedDocCard
) {
const linkedDoc = card.linkedDoc;
assertExists(
linkedDoc,
`Trying to load page ${card.model.pageId} in linked page block, but the page is not found.`
);
if (!linkedDoc) {
console.error(
`Trying to load page ${card.model.pageId} in linked page block, but the page is not found.`
);
return;
}
// eslint-disable-next-line sonarjs/no-collapsible-if
if ('bannerContainer' in card) {
@@ -59,10 +60,12 @@ export function renderLinkedDocInCard(
async function renderPageAsBanner(card: EmbedSyncedDocCard) {
const linkedDoc = card.linkedDoc;
assertExists(
linkedDoc,
`Trying to load page ${card.model.pageId} in linked page block, but the page is not found.`
);
if (!linkedDoc) {
console.error(
`Trying to load page ${card.model.pageId} in linked page block, but the page is not found.`
);
return;
}
const notes = getNotesFromDoc(linkedDoc);
if (!notes) {
@@ -126,10 +129,12 @@ async function renderNoteContent(
card.isNoteContentEmpty = true;
const doc = card.linkedDoc;
assertExists(
doc,
`Trying to load page ${card.model.pageId} in linked page block, but the page is not found.`
);
if (!doc) {
console.error(
`Trying to load page ${card.model.pageId} in linked page block, but the page is not found.`
);
return;
}
const notes = getNotesFromDoc(doc);
if (!notes) {
@@ -4,7 +4,6 @@ import type {
} from '@blocksuite/affine-model';
import type { LinkPreviewerService } from '@blocksuite/affine-shared/services';
import { isAbortError } from '@blocksuite/affine-shared/utils';
import { assertExists } from '@blocksuite/global/utils';
import { nothing } from 'lit';
import type { EmbedGithubBlockComponent } from './embed-github-block.js';
@@ -89,8 +88,14 @@ export async function refreshEmbedGithubUrlData(
try {
embedGithubElement.loading = true;
// TODO(@mirone): remove service
const queryUrlData = embedGithubElement.service?.queryUrlData;
assertExists(queryUrlData);
if (!queryUrlData) {
console.error(
`Trying to refresh github url data, but the queryUrlData is not found.`
);
return;
}
const githubUrlData = await queryUrlData(embedGithubElement.model);
({
@@ -126,8 +131,15 @@ export async function refreshEmbedGithubStatus(
embedGithubElement: EmbedGithubBlockComponent,
signal?: AbortSignal
) {
// TODO(@mirone): remove service
const queryApiData = embedGithubElement.service?.queryApiData;
assertExists(queryApiData);
if (!queryApiData) {
console.error(
`Trying to refresh github status, but the queryApiData is not found.`
);
return;
}
const githubApiData = await queryApiData(embedGithubElement.model, signal);
if (!githubApiData.status || signal?.aborted) return;
@@ -35,7 +35,6 @@ import {
GfxExtension,
} from '@blocksuite/block-std/gfx';
import { Bound, getCommonBound } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import { type GetBlocksOptions, type Query, Text } from '@blocksuite/store';
import { computed, signal } from '@preact/signals-core';
import { html, nothing, type PropertyValues } from 'lit';
@@ -284,7 +283,12 @@ export class EmbedSyncedDocBlockComponent extends EmbedBlockComponent<EmbedSynce
const { doc, caption } = this.model;
const parent = doc.getParent(this.model);
assertExists(parent);
if (!parent) {
console.error(
`Trying to convert synced doc to card, but the parent is not found.`
);
return;
}
const index = parent.children.indexOf(this.model);
doc.addBlock(
@@ -301,7 +305,12 @@ export class EmbedSyncedDocBlockComponent extends EmbedBlockComponent<EmbedSynce
covertToInline = () => {
const { doc } = this.model;
const parent = doc.getParent(this.model);
assertExists(parent);
if (!parent) {
console.error(
`Trying to convert synced doc to inline, but the parent is not found.`
);
return;
}
const index = parent.children.indexOf(this.model);
const yText = new Y.Text();
@@ -4,7 +4,6 @@ import type {
} from '@blocksuite/affine-model';
import type { LinkPreviewerService } from '@blocksuite/affine-shared/services';
import { isAbortError } from '@blocksuite/affine-shared/utils';
import { assertExists } from '@blocksuite/global/utils';
import type { EmbedYoutubeBlockComponent } from './embed-youtube-block.js';
@@ -73,8 +72,14 @@ export async function refreshEmbedYoutubeUrlData(
try {
embedYoutubeElement.loading = true;
// TODO(@mirone): remove service
const queryUrlData = embedYoutubeElement.service?.queryUrlData;
assertExists(queryUrlData);
if (!queryUrlData) {
console.error(
`Trying to refresh youtube url data, but the queryUrlData is not found.`
);
return;
}
const youtubeUrlData = await queryUrlData(
embedYoutubeElement.model,
@@ -5,7 +5,6 @@ import {
} from '@blocksuite/affine-shared/utils';
import type { BlockComponent, PointerEventState } from '@blocksuite/block-std';
import { GfxControllerIdentifier } from '@blocksuite/block-std/gfx';
import { assertExists } from '@blocksuite/global/utils';
export class ImageResizeManager {
private _activeComponent: BlockComponent | null = null;
@@ -19,8 +18,9 @@ export class ImageResizeManager {
private _zoom = 1;
onEnd() {
assertExists(this._activeComponent);
assertExists(this._imageContainer);
if (!this._activeComponent || !this._imageContainer) {
return;
}
const dragModel = getModelByElement(this._activeComponent);
dragModel?.doc.captureSync();
@@ -32,12 +32,16 @@ export class ImageResizeManager {
}
onMove(e: PointerEventState) {
assertExists(this._activeComponent);
const activeComponent = this._activeComponent;
const activeImgContainer = this._imageContainer;
assertExists(activeImgContainer);
if (!activeComponent || !activeImgContainer) {
return;
}
const activeImg = activeComponent.querySelector('img');
assertExists(activeImg);
if (!activeImg) {
return;
}
let width = 0;
if (this._dragMoveTarget === 'right') {
@@ -84,7 +88,9 @@ export class ImageResizeManager {
}
this._imageContainer = eventTarget.closest('.resizable-img');
assertExists(this._imageContainer);
if (!this._imageContainer) {
return;
}
const rect = this._imageContainer.getBoundingClientRect() as DOMRect;
this._imageCenterX = rect.left + rect.width / 2;
if (eventTarget.className.includes('right')) {
@@ -1,5 +1,4 @@
import { BlockSuiteError, ErrorCode } from '@blocksuite/global/exceptions';
import { assertExists } from '@blocksuite/global/utils';
import type {
BlockSnapshot,
DocSnapshot,
@@ -50,7 +49,12 @@ export class ClipboardAdapter extends BaseAdapter<string> {
): Promise<FromSliceSnapshotResult<string>> {
const snapshot = payload.snapshot;
const assets = payload.assets;
assertExists(assets);
if (!assets) {
throw new BlockSuiteError(
ErrorCode.ValueNotExists,
'ClipboardAdapter.fromSliceSnapshot: assets is not found'
);
}
const map = assets.getAssets();
const blobs: Record<string, FileSnapshot> = await encodeClipboardBlobs(map);
return {
@@ -1,5 +1,4 @@
import { toast } from '@blocksuite/affine-components/toast';
import { assertExists } from '@blocksuite/global/utils';
import type { FileSnapshot } from './adapter.js';
@@ -113,12 +112,17 @@ export function decodeClipboardBlobs(
blobs: Record<string, FileSnapshot>,
map: Map<string, Blob> | undefined
) {
if (!map) {
console.error(
`Trying to decode clipboard blobs, but the map is not found.`
);
return;
}
Object.entries<FileSnapshot>(blobs).forEach(([sourceId, file]) => {
const blob = new Blob([decode(file.content)]);
const f = new File([blob], file.name, {
type: file.type,
});
assertExists(map);
map.set(sourceId, f);
});
}
@@ -57,12 +57,7 @@ import {
type SerializedXYWH,
Vec,
} from '@blocksuite/global/gfx';
import {
assertExists,
assertType,
DisposableGroup,
nToLast,
} from '@blocksuite/global/utils';
import { assertType, DisposableGroup, nToLast } from '@blocksuite/global/utils';
import {
type BlockSnapshot,
BlockSnapshotSchema,
@@ -519,17 +514,19 @@ export class EdgelessClipboardController extends PageClipboard {
clipboardData: SerializedElement,
context: CreationContext,
newXYWH: SerializedXYWH
) {
): GfxPrimitiveElementModel | null {
if (clipboardData.type === GROUP) {
const yMap = new Y.Map();
const children = clipboardData.children ?? {};
for (const [key, value] of Object.entries(children)) {
const newKey = context.oldToNewIdMap.get(key);
assertExists(
newKey,
'Copy failed: cannot find the copied child in group'
);
if (!newKey) {
console.error(
`Copy failed: cannot find the copied child in group, key: ${key}`
);
return null;
}
yMap.set(newKey, value);
}
clipboardData.children = yMap;
@@ -543,17 +540,21 @@ export class EdgelessClipboardController extends PageClipboard {
const newValue = {
...oldValue,
};
assertExists(
newKey,
'Copy failed: cannot find the copied node in mind map'
);
if (!newKey) {
console.error(
`Copy failed: cannot find the copied node in mind map, key: ${oldKey}`
);
return null;
}
if (oldValue.parent) {
const newParent = context.oldToNewIdMap.get(oldValue.parent);
assertExists(
newParent,
'Copy failed: cannot find the copied node in mind map'
);
if (!newParent) {
console.error(
`Copy failed: cannot find the copied node in mind map, parent: ${oldValue.parent}`
);
return null;
}
newValue.parent = newParent;
}
@@ -603,7 +604,10 @@ export class EdgelessClipboardController extends PageClipboard {
type: clipboardData.type as string,
});
const element = this.crud.getElementById(id) as GfxPrimitiveElementModel;
assertExists(element);
if (!element) {
console.error(`Copy failed: cannot find the copied element, id: ${id}`);
return null;
}
return element;
}
@@ -898,7 +902,7 @@ export class EdgelessClipboardController extends PageClipboard {
const editorMode = isInsidePageEditor(host);
const rootComponent = getRootByEditorHost(host);
assertExists(rootComponent);
if (!rootComponent) return;
const container = rootComponent.querySelector(
'.affine-block-children-container'
@@ -1355,7 +1359,10 @@ export class EdgelessClipboardController extends PageClipboard {
bounds.push(shape.elementBound);
});
const bound = getCommonBound(bounds);
assertExists(bound, 'bound not exist');
if (!bound) {
console.error('bound not exist');
return;
}
const canvas = await this._edgelessToCanvas(
this.host,
@@ -27,11 +27,7 @@ import { type BlockStdScope, stdContext } from '@blocksuite/block-std';
import { GfxControllerIdentifier } from '@blocksuite/block-std/gfx';
import type { Bound, IVec } from '@blocksuite/global/gfx';
import { Vec } from '@blocksuite/global/gfx';
import {
assertExists,
DisposableGroup,
WithDisposable,
} from '@blocksuite/global/utils';
import { DisposableGroup, WithDisposable } from '@blocksuite/global/utils';
import {
ArrowUpBigIcon,
PlusIcon,
@@ -194,7 +190,9 @@ export class EdgelessAutoComplete extends WithDisposable(LitElement) {
);
}
if (this._isMoving) {
assertExists(connector);
if (!connector) {
return;
}
const otherSideId = connector.source.id;
connector.target = this.connectionOverlay.renderConnector(
@@ -382,7 +380,9 @@ export class EdgelessAutoComplete extends WithDisposable(LitElement) {
);
} else {
const model = doc.getBlockById(id);
assertExists(model);
if (!model) {
return;
}
const [x, y] = service.viewport.toViewCoord(
bound.center[0],
bound.y + DEFAULT_NOTE_HEIGHT / 2
@@ -7,7 +7,6 @@ import {
type PointLocation,
rotatePoints,
} from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import type { SelectableProps } from '../../utils/query.js';
import { HandleDirection, type ResizeMode } from './resize-handles.js';
@@ -113,7 +112,9 @@ export class HandleResizeManager {
const rect = this._target
.closest('.affine-edgeless-selected-rect')
?.getBoundingClientRect();
assertExists(rect);
if (!rect) {
return;
}
const { left, top, right, bottom } = rect;
const x = (left + right) / 2;
const y = (top + bottom) / 2;
@@ -207,12 +208,10 @@ export class HandleResizeManager {
_rotate,
_resizeMode,
_zoom,
_target,
_originalRect,
_currentRect,
} = this;
proportion ||= this._proportion;
assertExists(_target);
const isAll = _resizeMode === 'all';
const isCorner = _resizeMode === 'corner';
@@ -11,7 +11,7 @@ import {
ShadowlessElement,
} from '@blocksuite/block-std';
import { Bound, Vec } from '@blocksuite/global/gfx';
import { assertExists, WithDisposable } from '@blocksuite/global/utils';
import { WithDisposable } from '@blocksuite/global/utils';
import { css, html, nothing } from 'lit';
import { property, query } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
@@ -94,12 +94,11 @@ export class EdgelessConnectorLabelEditor extends WithDisposable(
};
get inlineEditor() {
assertExists(this.richText.inlineEditor);
return this.richText.inlineEditor;
}
get inlineEditorContainer() {
return this.inlineEditor.rootElement;
return this.inlineEditor?.rootElement;
}
override connectedCallback() {
@@ -116,7 +115,6 @@ export class EdgelessConnectorLabelEditor extends WithDisposable(
override firstUpdated() {
const { edgeless, connector } = this;
const { dispatcher } = edgeless;
assertExists(dispatcher);
this._resizeObserver = new ResizeObserver(() => {
this._updateLabelRect();
@@ -126,6 +124,7 @@ export class EdgelessConnectorLabelEditor extends WithDisposable(
this.updateComplete
.then(() => {
if (!this.inlineEditor) return;
this.inlineEditor.selectAll();
this.inlineEditor.slots.renderComplete.on(() => {
@@ -10,7 +10,7 @@ import {
ShadowlessElement,
} from '@blocksuite/block-std';
import { Bound } from '@blocksuite/global/gfx';
import { assertExists, WithDisposable } from '@blocksuite/global/utils';
import { WithDisposable } from '@blocksuite/global/utils';
import { cssVarV2 } from '@toeverything/theme/v2';
import { css, html, nothing } from 'lit';
import { property, query } from 'lit/decorators.js';
@@ -63,7 +63,6 @@ export class EdgelessFrameTitleEditor extends WithDisposable(
override firstUpdated(): void {
const dispatcher = this.edgeless.dispatcher;
assertExists(dispatcher);
this.updateComplete
.then(() => {
if (!this.inlineEditor) return;
@@ -10,7 +10,7 @@ import {
ShadowlessElement,
} from '@blocksuite/block-std';
import { Bound } from '@blocksuite/global/gfx';
import { assertExists, WithDisposable } from '@blocksuite/global/utils';
import { WithDisposable } from '@blocksuite/global/utils';
import { html, nothing } from 'lit';
import { property, query } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
@@ -21,12 +21,11 @@ export class EdgelessGroupTitleEditor extends WithDisposable(
ShadowlessElement
) {
get inlineEditor() {
assertExists(this.richText.inlineEditor);
return this.richText.inlineEditor;
}
get inlineEditorContainer() {
return this.inlineEditor.rootElement;
return this.inlineEditor?.rootElement;
}
private _unmount() {
@@ -47,10 +46,10 @@ export class EdgelessGroupTitleEditor extends WithDisposable(
override firstUpdated(): void {
const dispatcher = this.edgeless.dispatcher;
assertExists(dispatcher);
this.updateComplete
.then(() => {
if (!this.inlineEditor) return;
this.inlineEditor.selectAll();
this.group.showTitle = false;
@@ -12,7 +12,7 @@ import {
ShadowlessElement,
} from '@blocksuite/block-std';
import { Bound, toRadian, Vec } from '@blocksuite/global/gfx';
import { assertExists, WithDisposable } from '@blocksuite/global/utils';
import { WithDisposable } from '@blocksuite/global/utils';
import { html, nothing } from 'lit';
import { property, query } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
@@ -32,12 +32,11 @@ export class EdgelessShapeTextEditor extends WithDisposable(ShadowlessElement) {
private _resizeObserver: ResizeObserver | null = null;
get inlineEditor() {
assertExists(this.richText.inlineEditor);
return this.richText.inlineEditor;
}
get inlineEditorContainer() {
return this.inlineEditor.rootElement;
return this.inlineEditor?.rootElement;
}
get isMindMapNode() {
@@ -175,7 +174,6 @@ export class EdgelessShapeTextEditor extends WithDisposable(ShadowlessElement) {
override firstUpdated(): void {
const dispatcher = this.edgeless.dispatcher;
assertExists(dispatcher);
this.element.textDisplay = false;
@@ -202,6 +200,7 @@ export class EdgelessShapeTextEditor extends WithDisposable(ShadowlessElement) {
this.updateComplete
.then(() => {
if (!this.inlineEditor) return;
if (this.element.group instanceof MindmapElementModel) {
this.inlineEditor.selectAll();
} else {
@@ -11,7 +11,7 @@ import {
ShadowlessElement,
} from '@blocksuite/block-std';
import { Bound, toRadian, Vec } from '@blocksuite/global/gfx';
import { assertExists, WithDisposable } from '@blocksuite/global/utils';
import { WithDisposable } from '@blocksuite/global/utils';
import { css, html, nothing } from 'lit';
import { property, query } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
@@ -144,12 +144,11 @@ export class EdgelessTextEditor extends WithDisposable(ShadowlessElement) {
};
get inlineEditor() {
assertExists(this.richText.inlineEditor);
return this.richText.inlineEditor;
}
get inlineEditorContainer() {
return this.inlineEditor.rootElement;
return this.inlineEditor?.rootElement;
}
override connectedCallback(): void {
@@ -170,10 +169,10 @@ export class EdgelessTextEditor extends WithDisposable(ShadowlessElement) {
const edgeless = this.edgeless;
const element = this.element;
const { dispatcher } = this.edgeless;
assertExists(dispatcher);
this.updateComplete
.then(() => {
if (!this.inlineEditor) return;
this.inlineEditor.slots.renderComplete.on(() => {
this._updateRect();
this.requestUpdate();
@@ -1,4 +1,4 @@
import { assertExists } from '@blocksuite/global/utils';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
// more than 100% due to the shadow
const leaveToPercent = `calc(100% + 10px)`;
@@ -28,26 +28,31 @@ export function createPopper<T extends keyof HTMLElementTagNameMap>(
onDispose?: () => void;
setProps?: (ele: HTMLElementTagNameMap[T]) => void;
}
) {
): MenuPopper<HTMLElementTagNameMap[T]> {
const duration = options?.duration ?? 230;
if (!popMap.has(reference)) popMap.set(reference, new Map());
const elMap = popMap.get(reference);
assertExists(elMap);
// if there is already a popper, cancel leave transition and apply enter transition
if (elMap.has(tagName)) {
if (elMap && elMap.has(tagName)) {
const popper = elMap.get(tagName);
assertExists(popper);
popper.cancel?.();
requestAnimationFrame(() => animateEnter(popper.element));
return popper as MenuPopper<HTMLElementTagNameMap[T]>;
if (popper) {
popper.cancel?.();
requestAnimationFrame(() => animateEnter(popper.element));
return popper as MenuPopper<HTMLElementTagNameMap[T]>;
}
}
const clipWrapper = document.createElement('div');
const menu = document.createElement(tagName);
options?.setProps?.(menu);
assertExists(reference.shadowRoot);
clipWrapper.append(menu);
if (!reference.shadowRoot) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'reference must be a shadow root'
);
}
reference.shadowRoot.append(clipWrapper);
// apply enter transition
@@ -3,7 +3,6 @@ import {
ThemeProvider,
} from '@blocksuite/affine-shared/services';
import { Bound } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import {
type ReactiveController,
type ReactiveControllerHost,
@@ -200,8 +199,7 @@ export class EdgelessDraggableElementController<T>
}
const { overlay } = this;
assertExists(overlay);
if (!overlay) return;
const { x, y } = e;
const { startPos, scopeRect } = info;
const offsetX = x - startPos.x;
@@ -12,7 +12,7 @@ import {
TelemetryProvider,
ThemeProvider,
} from '@blocksuite/affine-shared/services';
import { assertExists, SignalWatcher } from '@blocksuite/global/utils';
import { SignalWatcher } from '@blocksuite/global/utils';
import { css, html, LitElement, nothing } from 'lit';
import { property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
@@ -248,7 +248,10 @@ export class EdgelessToolbarShapeDraggable extends EdgelessToolbarToolMixin(
const el = this.shapeContainer.querySelector(
`.shape.${this.draggingShape}`
) as HTMLElement;
assertExists(el, 'Edgeless toolbar Shape element not found');
if (!el) {
console.error('Edgeless toolbar Shape element not found');
return;
}
const { x, y } = service.gfx.tool.lastMousePos$.peek();
const { left, top } = this.edgeless.viewport;
const clientPos = { x: x + left, y: y + top };
@@ -1,7 +1,6 @@
import type { CursorType, StandardCursor } from '@blocksuite/block-std/gfx';
import type { IVec } from '@blocksuite/global/gfx';
import { normalizeDegAngle, Vec } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import { css, html } from 'lit';
export function generateCursorUrl(
@@ -89,7 +88,11 @@ export function calcAngle(target: HTMLElement, point: IVec, offset = 0) {
const rect = target
.closest('.affine-edgeless-selected-rect')
?.getBoundingClientRect();
assertExists(rect);
if (!rect) {
console.error('rect not found when calc angle');
return 0;
}
const { left, top, right, bottom } = rect;
const center = Vec.med([left, top], [right, bottom]);
return normalizeDegAngle(
@@ -104,9 +107,7 @@ export function calcAngleWithRotation(
rotate: number
) {
const handle = target.parentElement;
assertExists(handle);
const ariaLabel = handle.getAttribute('aria-label');
assertExists(ariaLabel);
const ariaLabel = handle?.getAttribute('aria-label');
const { left, top, right, bottom, width, height } = rect;
const size = Math.min(width, height);
const sx = size / width;
@@ -160,9 +161,7 @@ export function calcAngleWithRotation(
export function calcAngleEdgeWithRotation(target: HTMLElement, rotate: number) {
let angleWithEdge = 0;
const handle = target.parentElement;
assertExists(handle);
const ariaLabel = handle.getAttribute('aria-label');
assertExists(ariaLabel);
const ariaLabel = handle?.getAttribute('aria-label');
switch (ariaLabel) {
case 'top': {
angleWithEdge = 270;
@@ -187,9 +186,7 @@ export function calcAngleEdgeWithRotation(target: HTMLElement, rotate: number) {
export function getResizeLabel(target: HTMLElement) {
const handle = target.parentElement;
assertExists(handle);
const ariaLabel = handle.getAttribute('aria-label');
assertExists(ariaLabel);
const ariaLabel = handle?.getAttribute('aria-label');
return ariaLabel;
}
@@ -39,8 +39,8 @@ import {
type GfxViewportElement,
} from '@blocksuite/block-std/gfx';
import { IS_WINDOWS } from '@blocksuite/global/env';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import { Bound, Point, Vec } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import { effect } from '@preact/signals-core';
import { css, html } from 'lit';
import { query } from 'lit/decorators.js';
@@ -191,7 +191,12 @@ export class EdgelessRootBlockComponent extends BlockComponent<
this._viewportElement = this.host.closest(
'.affine-edgeless-viewport'
) as HTMLElement | null;
assertExists(this._viewportElement);
if (!this._viewportElement) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'EdgelessRootBlockComponent.viewportElement: viewport element is not found'
);
}
return this._viewportElement;
}
@@ -17,7 +17,7 @@ import {
SurfaceSelection,
} from '@blocksuite/block-std';
import type { GfxViewportElement } from '@blocksuite/block-std/gfx';
import { assertExists } from '@blocksuite/global/utils';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import { css, html } from 'lit';
import { query, state } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
@@ -104,7 +104,12 @@ export class EdgelessRootPreviewBlockComponent
this._viewportElement = this.host.closest(
this.editorViewportSelector
) as HTMLElement | null;
assertExists(this._viewportElement);
if (!this._viewportElement) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'EdgelessRootPreviewBlockComponent.viewportElement: viewport element is not found'
);
}
return this._viewportElement;
}
@@ -4,7 +4,6 @@ import { TelemetryProvider } from '@blocksuite/affine-shared/services';
import type { PointerEventState } from '@blocksuite/block-std';
import { BaseTool } from '@blocksuite/block-std/gfx';
import type { IVec } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
export class BrushTool extends BaseTool {
static BRUSH_POP_GAP = 20;
@@ -40,8 +39,10 @@ export class BrushTool extends BaseTool {
: 'vertical';
}
private _tryGetPressurePoints(e: PointerEventState) {
assertExists(this._draggingPathPressures);
private _tryGetPressurePoints(e: PointerEventState): number[][] {
if (!this._draggingPathPressures) {
return [];
}
const pressures = [...this._draggingPathPressures, e.pressure];
this._draggingPathPressures = pressures;
@@ -56,8 +57,10 @@ export class BrushTool extends BaseTool {
this._pressureSupportedPointerIds.add(pointerId);
}
assertExists(this._draggingPathPoints);
const points = this._draggingPathPoints;
if (!points) {
return [];
}
if (this._pressureSupportedPointerIds.has(pointerId)) {
return points.map(([x, y], i) => [x, y, pressures[i]]);
} else {
@@ -83,12 +86,14 @@ export class BrushTool extends BaseTool {
}
override dragMove(e: PointerEventState) {
if (!this._draggingElementId || !this._draggingElement || !this.gfx.surface)
if (
!this._draggingElementId ||
!this._draggingElement ||
!this.gfx.surface ||
!this._draggingPathPoints
)
return;
assertExists(this._draggingElementId);
assertExists(this._draggingPathPoints);
let pointX = e.point.x;
let pointY = e.point.y;
const holdingShiftKey = e.keys.shift || this.gfx.keyboard.shiftKey$.peek();
@@ -1,7 +1,7 @@
import { generateElementId, sortIndex } from '@blocksuite/affine-block-surface';
import type { ConnectorElementModel } from '@blocksuite/affine-model';
import { Bound } from '@blocksuite/global/gfx';
import { assertExists, assertType } from '@blocksuite/global/utils';
import { assertType } from '@blocksuite/global/utils';
import type { BlockSnapshot, SnapshotNode } from '@blocksuite/store';
import type { SlotBlockPayload, TemplateJob } from './template.js';
@@ -154,8 +154,6 @@ export const createInsertPlaceMiddleware = (targetPlace: Bound) => {
const ignoreType = new Set(['group', 'connector']);
const changePosition = (blockJson: BlockSnapshot) => {
assertExists(templateBound);
if (blockJson.props.xywh) {
const bound = Bound.deserialize(blockJson.props['xywh'] as string);
@@ -4,7 +4,7 @@ import type {
} from '@blocksuite/affine-block-surface';
import type { ConnectorElementModel } from '@blocksuite/affine-model';
import { Bound, getCommonBound } from '@blocksuite/global/gfx';
import { assertExists, assertType, Slot } from '@blocksuite/global/utils';
import { assertType, Slot } from '@blocksuite/global/utils';
import {
type BlockModel,
type BlockSnapshot,
@@ -194,7 +194,9 @@ export class TemplateJob {
return;
}
assertExists(modelData);
if (!modelData) {
return;
}
doc.addBlock(
modelData.flavour,
@@ -8,7 +8,7 @@ import {
import { SpecProvider } from '@blocksuite/affine-shared/utils';
import { Container } from '@blocksuite/global/di';
import { BlockSuiteError, ErrorCode } from '@blocksuite/global/exceptions';
import { assertExists, sha } from '@blocksuite/global/utils';
import { sha } from '@blocksuite/global/utils';
import type { Schema, Store, Workspace } from '@blocksuite/store';
import { extMimeMap, Transformer } from '@blocksuite/store';
@@ -112,7 +112,12 @@ async function importMarkdownToBlock({
pageId: doc.id,
});
assertExists(snapshot, 'import markdown failed, expected to get a snapshot');
if (!snapshot) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'import markdown failed, expected to get a snapshot'
);
}
const blocks = snapshot.content.flatMap(x => x.children);
@@ -16,7 +16,6 @@ import {
} from '@blocksuite/affine-shared/commands';
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
import type { EditorHost } from '@blocksuite/block-std';
import { assertExists } from '@blocksuite/global/utils';
import { computePosition, flip, offset, shift } from '@floating-ui/dom';
import { html } from 'lit';
import { ref, type RefOrCallback } from 'lit/directives/ref.js';
@@ -125,8 +124,9 @@ export const HighlightButton = (formatBar: AffineFormatBarWidget) => {
formatBar.shadowRoot?.querySelector<HTMLElement>('.highlight-button');
const panel =
formatBar.shadowRoot?.querySelector<HTMLElement>('.highlight-panel');
assertExists(button);
assertExists(panel);
if (!button || !panel) {
return;
}
panel.style.display = 'flex';
computePosition(button, panel, {
placement: 'bottom',
@@ -3,7 +3,6 @@ import { ArrowDownIcon } from '@blocksuite/affine-components/icons';
import { textConversionConfigs } from '@blocksuite/affine-components/rich-text';
import type { ParagraphBlockModel } from '@blocksuite/affine-model';
import type { EditorHost } from '@blocksuite/block-std';
import { assertExists } from '@blocksuite/global/utils';
import { computePosition, flip, offset, shift } from '@floating-ui/dom';
import { html } from 'lit';
import { ref, type RefOrCallback } from 'lit/directives/ref.js';
@@ -85,13 +84,11 @@ export const ParagraphButton = (formatBar: AffineFormatBarWidget) => {
return;
}
const formatQuickBarElement = formatBar.formatBarElement;
const button =
formatBar.shadowRoot?.querySelector<HTMLElement>('.paragraph-button');
const panel =
formatBar.shadowRoot?.querySelector<HTMLElement>('.paragraph-panel');
assertExists(button);
assertExists(panel);
assertExists(formatQuickBarElement, 'format quick bar should exist');
if (!panel || !formatQuickBarElement) {
return;
}
panel.style.display = 'flex';
computePosition(formatQuickBarElement, panel, {
placement: 'top-start',
@@ -62,7 +62,6 @@ import type {
InitCommandCtx,
} from '@blocksuite/block-std';
import { tableViewMeta } from '@blocksuite/data-view/view-presets';
import { assertExists } from '@blocksuite/global/utils';
import { MoreVerticalIcon } from '@blocksuite/icons/lit';
import { Slice, toDraftModel } from '@blocksuite/store';
import { html, type TemplateResult } from 'lit';
@@ -377,13 +376,17 @@ export const BUILT_IN_GROUPS: MenuItemGroup<FormatBarContext>[] = [
.try<{ currentSelectionPath: string }>(cmd => [
cmd.pipe(getTextSelectionCommand).pipe((ctx, next) => {
const textSelection = ctx.currentTextSelection;
assertExists(textSelection);
if (!textSelection) {
return;
}
const end = textSelection.to ?? textSelection.from;
next({ currentSelectionPath: end.blockId });
}),
cmd.pipe(getBlockSelectionsCommand).pipe((ctx, next) => {
const currentBlockSelections = ctx.currentBlockSelections;
assertExists(currentBlockSelections);
if (!currentBlockSelections) {
return;
}
const blockSelection = currentBlockSelections.at(-1);
if (!blockSelection) {
return;
@@ -29,11 +29,7 @@ import {
TextSelection,
WidgetComponent,
} from '@blocksuite/block-std';
import {
assertExists,
DisposableGroup,
nextTick,
} from '@blocksuite/global/utils';
import { DisposableGroup, nextTick } from '@blocksuite/global/utils';
import type { BaseSelection } from '@blocksuite/store';
import {
autoUpdate,
@@ -239,7 +235,9 @@ export class AffineFormatBarWidget extends WidgetComponent {
private _listenFloatingElement() {
const formatQuickBarElement = this.formatBarElement;
assertExists(formatQuickBarElement, 'format quick bar should exist');
if (!formatQuickBarElement) {
return;
}
const listenFloatingElement = (
getElement: () => ReferenceElement | void
@@ -249,7 +247,10 @@ export class AffineFormatBarWidget extends WidgetComponent {
return;
}
assertExists(this._floatDisposables);
if (!this._floatDisposables) {
return;
}
HoverController.globalAbortController?.abort();
this._floatDisposables.add(
autoUpdate(
@@ -512,7 +513,9 @@ export class AffineFormatBarWidget extends WidgetComponent {
this._abortController = new AbortController();
const rootComponent = this.block;
assertExists(rootComponent);
if (!rootComponent) {
return;
}
const widgets = rootComponent.widgets;
// check if the host use the format bar widget
@@ -4,7 +4,7 @@ import type {
MenuItemGroup,
} from '@blocksuite/affine-components/toolbar';
import { renderGroups } from '@blocksuite/affine-components/toolbar';
import { assertExists, noop } from '@blocksuite/global/utils';
import { noop } from '@blocksuite/global/utils';
import { MoreVerticalIcon } from '@blocksuite/icons/lit';
import { flip, offset } from '@floating-ui/dom';
import { html, LitElement } from 'lit';
@@ -57,7 +57,9 @@ export class AffineImageToolbar extends LitElement {
this._currentOpenMenu = this._popMenuAbortController;
assertExists(this._moreButton);
if (!this._moreButton) {
return;
}
createLitPortal({
template: html`
@@ -4,7 +4,6 @@ import {
isInsidePageEditor,
} from '@blocksuite/affine-shared/utils';
import { BlockSelection } from '@blocksuite/block-std';
import { assertExists } from '@blocksuite/global/utils';
export function duplicate(
block: ImageBlockComponent,
@@ -23,7 +22,10 @@ export function duplicate(
const { doc } = model;
const parent = doc.getParent(model);
assertExists(parent, 'Parent not found');
if (!parent) {
console.error(`Parent not found for block(${model.flavour}) ${model.id}`);
return;
}
const index = parent?.children.indexOf(model);
const duplicateId = doc.addBlock(
@@ -13,11 +13,7 @@ import {
isFuzzyMatch,
substringMatchScore,
} from '@blocksuite/affine-shared/utils';
import {
assertExists,
throttle,
WithDisposable,
} from '@blocksuite/global/utils';
import { throttle, WithDisposable } from '@blocksuite/global/utils';
import { autoPlacement, offset } from '@floating-ui/dom';
import { html, LitElement, nothing, type PropertyValues } from 'lit';
import { property, state } from 'lit/decorators.js';
@@ -592,7 +588,11 @@ export class InnerSlashMenu extends WithDisposable(LitElement) {
override willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has('menu') && this.menu.length !== 0) {
const firstItem = getFirstNotDividerItem(this.menu);
assertExists(firstItem);
if (!firstItem) {
console.error('No item found in slash menu');
return;
}
this._activeItem = firstItem;
// this case happen on query updated
@@ -7,8 +7,8 @@ import {
GfxControllerIdentifier,
type GfxModel,
} from '@blocksuite/block-std/gfx';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import { Bound } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
export const edgelessToBlob = async (
host: EditorHost,
@@ -24,24 +24,25 @@ export const edgelessToBlob = async (
const isBlock = isTopLevelBlock(edgelessElement);
const gfx = host.std.get(GfxControllerIdentifier);
return exportManager
.edgelessToCanvas(
options.surfaceRenderer,
bound,
gfx,
isBlock ? [edgelessElement] : undefined,
isBlock ? undefined : [edgelessElement],
{ zoom: options.surfaceRenderer.viewport.zoom }
)
.then(canvas => {
assertExists(canvas);
return new Promise((resolve, reject) => {
canvas.toBlob(
blob => (blob ? resolve(blob) : reject(null)),
'image/png'
);
});
});
const canvas = await exportManager.edgelessToCanvas(
options.surfaceRenderer,
bound,
gfx,
isBlock ? [edgelessElement] : undefined,
isBlock ? undefined : [edgelessElement],
{ zoom: options.surfaceRenderer.viewport.zoom }
);
if (!canvas) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'Failed to export edgeless to canvas'
);
}
return new Promise((resolve, reject) => {
canvas.toBlob(blob => (blob ? resolve(blob) : reject(null)), 'image/png');
});
};
export const writeImageBlobToClipboard = async (blob: Blob) => {
@@ -41,7 +41,7 @@ import {
deserializeXYWH,
type SerializedXYWH,
} from '@blocksuite/global/gfx';
import { assertExists, DisposableGroup } from '@blocksuite/global/utils';
import { DisposableGroup } from '@blocksuite/global/utils';
import { DeleteIcon, EdgelessIcon, FrameIcon } from '@blocksuite/icons/lit';
import type { BaseSelection, Store } from '@blocksuite/store';
import { css, html, nothing, type TemplateResult } from 'lit';
@@ -279,7 +279,7 @@ export class SurfaceRefBlockComponent extends BlockComponent<SurfaceRefBlockMode
},
]);
const model = this.doc.getBlockById(paragraphId);
assertExists(model, `Failed to add paragraph block.`);
if (!model) return;
requestConnectedFrame(() => {
selection.update(selList => {
@@ -12,7 +12,6 @@ import {
toDegree,
toRadian,
} from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import { describe, expect, it } from 'vitest';
describe('Line', () => {
@@ -43,7 +42,7 @@ describe('Line', () => {
[0, 1],
[0, -1],
];
assertExists(rst);
if (!rst) throw new Error('Failed to get line ellipse intersects');
expect(
rst.every((point, index) => pointAlmostEqual(point, expected[index]))
).toBeTruthy();
@@ -76,7 +75,7 @@ describe('Line', () => {
[0, 10],
]
);
assertExists(rst);
if (!rst) throw new Error('Failed to get line polygon intersects');
expect(pointAlmostEqual(rst[0], [10, 5])).toBeTruthy();
});
@@ -12,6 +12,7 @@ import type {
GfxLocalElementModel,
GfxModel,
} from '@blocksuite/block-std/gfx';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import type { IBound, IVec, IVec3 } from '@blocksuite/global/gfx';
import {
almostEqual,
@@ -31,12 +32,7 @@ import {
toRadian,
Vec,
} from '@blocksuite/global/gfx';
import {
assertEquals,
assertExists,
assertType,
last,
} from '@blocksuite/global/utils';
import { assertEquals, assertType, last } from '@blocksuite/global/utils';
import { effect } from '@preact/signals-core';
import { Overlay } from '../renderer/overlay.js';
@@ -153,7 +149,10 @@ export function getAnchors(ele: GfxModel) {
)
.forEach(vec => {
const rst = ele.getLineIntersections(bound.center as IVec, vec as IVec);
assertExists(rst);
if (!rst) {
console.error(`Failed to get line intersections for ${ele.id}`);
return;
}
const originPoint = getPointFromBoundsWithRotation(
{ ...bound, rotate: -rotate },
rst[0]
@@ -497,9 +496,7 @@ function getConnectablePoints(
pushOuterPoints(points, expandStartBound, expandEndBound, outerBound);
}
if (startBound && endBound) {
assertExists(expandStartBound);
assertExists(expandEndBound);
if (startBound && endBound && expandStartBound && expandEndBound) {
pushGapMidPoint(
points,
startPoint,
@@ -564,8 +561,12 @@ function getConnectablePoints(
almostEqual(item[1], point[1], 0.02)
);
}) as IVec3[];
assertExists(startEnds[0]);
assertExists(startEnds[1]);
if (!startEnds[0] || !startEnds[1]) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'Failed to get start and end points when getting connectable points'
);
}
return { points, nextStartPoint: startEnds[0], lastEndPoint: startEnds[1] };
}
@@ -709,7 +710,12 @@ function getNextPoint(
result,
[bound.maxX + 10, result[1]]
);
assertExists(intersects);
if (!intersects) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'Failed to get line intersections for getNextPoint'
);
}
result[0] = intersects[0] + offsetX;
} else {
const intersects = lineIntersects(
@@ -718,7 +724,12 @@ function getNextPoint(
result,
[bound.x - 10, result[1]]
);
assertExists(intersects);
if (!intersects) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'Failed to get line intersections for getNextPoint'
);
}
result[0] = intersects[0] - offsetX;
}
} else {
@@ -729,7 +740,12 @@ function getNextPoint(
result,
[result[0], bound.maxY + 10]
);
assertExists(intersects);
if (!intersects) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'Failed to get line intersections for getNextPoint'
);
}
result[1] = intersects[1] + offsetY;
} else {
const intersects = lineIntersects(
@@ -738,7 +754,12 @@ function getNextPoint(
result,
[result[0], bound.y - 10]
);
assertExists(intersects);
if (!intersects) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'Failed to get line intersections for getNextPoint'
);
}
result[1] = intersects[1] - offsetY;
}
}
@@ -1204,9 +1225,14 @@ export class ConnectorPathGenerator extends PathGenerator {
let startPoint: PointLocation | null = null;
let endPoint: PointLocation | null = null;
if (source.id && !source.position && target.id && !target.position) {
assertExists(start);
assertExists(end);
if (
source.id &&
!source.position &&
target.id &&
!target.position &&
start &&
end
) {
const startAnchors = getAnchors(start);
const endAnchors = getAnchors(end);
let minDist = Infinity;
@@ -1,6 +1,5 @@
import type { Bound, IVec3 } from '@blocksuite/global/gfx';
import { almostEqual } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import { Graph } from './graph.js';
import { PriorityQueue } from './priority-queue.js';
@@ -67,9 +66,10 @@ export class AStarRunner {
const froms = this._cameFrom.get(current);
if (!froms) return result;
const index = nextIndexs.shift();
assertExists(index);
nextIndexs.push(froms.indexs[index]);
current = froms.from[index];
if (index !== undefined && index !== null) {
nextIndexs.push(froms.indexs[index]);
current = froms.from[index];
}
}
return result;
}
@@ -107,7 +107,9 @@ export class AStarRunner {
private _neighbors(cur: IVec3) {
const neighbors = this._graph.neighbors(cur);
const cameFroms = this._cameFrom.get(cur);
assertExists(cameFroms);
if (!cameFroms) {
return [];
}
cameFroms.from.forEach(from => {
const index = neighbors.findIndex(n => pointAlmostEqual(n, from));
@@ -154,17 +156,18 @@ export class AStarRunner {
const curDiagoalCounts = this._diagonalCount.get(current);
const curPointPrioritys = this._pointPriority.get(current);
const cameFroms = this._cameFrom.get(current);
assertExists(curCosts);
assertExists(curDiagoalCounts);
assertExists(curPointPrioritys);
assertExists(cameFroms);
if (!curCosts || !curDiagoalCounts || !curPointPrioritys || !cameFroms) {
continue;
}
const newCosts = curCosts.map(co => co + cost(current, next));
const newDiagonalCounts = curDiagoalCounts.map(
(count, index) =>
count + getDiagonalCount(next, current, cameFroms.from[index])
);
assertExists(next[2]);
if (!next[2]) {
continue;
}
const newPointPrioritys = curPointPrioritys.map(
pointPriority => pointPriority + next[2]
);
@@ -1,4 +1,5 @@
import { assertExists, Slot } from '@blocksuite/global/utils';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import { Slot } from '@blocksuite/global/utils';
import {
autoUpdate,
computePosition,
@@ -39,7 +40,12 @@ export function createSimplePortal({
});
const root = shadowDom ? portalRoot.shadowRoot : portalRoot;
assertExists(root);
if (!root) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
'Failed to create portal root'
);
}
let updateId = 0;
const updatePortal: (id: number) => void = id => {
@@ -55,7 +61,6 @@ export function createSimplePortal({
template instanceof Function
? template({ updatePortal: () => updatePortal(curId) })
: template;
assertExists(templateResult);
render(templateResult, root, renderOptions);
};
@@ -173,7 +178,6 @@ export function createLitPortal({
? positionConfigOrFn(portalRoot)
: positionConfigOrFn;
const { referenceElement, ...options } = computePositionOptions;
assertExists(referenceElement, 'referenceElement is required');
const update = () => {
if (
computePositionOptions.abortWhenRefRemoved !== false &&
@@ -1,7 +1,6 @@
import { getSelectedBlocksCommand } from '@blocksuite/affine-shared/commands';
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
import type { BlockSelection, Command } from '@blocksuite/block-std';
import { assertExists } from '@blocksuite/global/utils';
import { INLINE_ROOT_ATTR, type InlineRootElement } from '@blocksuite/inline';
import { FORMAT_BLOCK_SUPPORT_FLAVOURS } from './consts.js';
@@ -14,10 +13,12 @@ export const formatBlockCommand: Command<{
mode?: 'replace' | 'merge';
}> = (ctx, next) => {
const blockSelections = ctx.blockSelections ?? ctx.currentBlockSelections;
assertExists(
blockSelections,
'`blockSelections` is required, you need to pass it in args or use `getBlockSelections` command before adding this command to the pipeline.'
);
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;
@@ -33,7 +34,12 @@ export const formatBlockCommand: Command<{
})
.pipe((ctx, next) => {
const { selectedBlocks } = ctx;
assertExists(selectedBlocks);
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<
@@ -11,7 +11,6 @@ import {
type EditorHost,
type InitCommandCtx,
} from '@blocksuite/block-std';
import { assertExists } from '@blocksuite/global/utils';
import {
INLINE_ROOT_ATTR,
type InlineEditor,
@@ -92,7 +91,12 @@ function handleCurrentSelection(
})
.pipe((ctx, next) => {
const { selectedBlocks } = ctx;
assertExists(selectedBlocks);
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,
@@ -119,7 +123,12 @@ function handleCurrentSelection(
})
.pipe((ctx, next) => {
const { selectedBlocks } = ctx;
assertExists(selectedBlocks);
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,
@@ -8,11 +8,7 @@ import {
import { FONT_XS, PANEL_BASE } from '@blocksuite/affine-shared/styles';
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
import { type BlockStdScope, ShadowlessElement } from '@blocksuite/block-std';
import {
assertExists,
SignalWatcher,
WithDisposable,
} from '@blocksuite/global/utils';
import { SignalWatcher, WithDisposable } from '@blocksuite/global/utils';
import { DoneIcon, ResetIcon } from '@blocksuite/icons/lit';
import type { DeltaInsert, InlineRange } from '@blocksuite/inline';
import { computePosition, inline, offset, shift } from '@floating-ui/dom';
@@ -211,7 +207,9 @@ export class ReferenceAliasPopup extends SignalWatcher(
override updated() {
const range = this.inlineEditor.toDomRange(this.inlineRange);
assertExists(range);
if (!range) {
return;
}
const visualElement = {
getBoundingClientRect: () => range.getBoundingClientRect(),
@@ -16,7 +16,7 @@ import {
type BlockComponent,
type BlockStdScope,
} from '@blocksuite/block-std';
import { assertExists, WithDisposable } from '@blocksuite/global/utils';
import { WithDisposable } from '@blocksuite/global/utils';
import { ArrowDownSmallIcon, MoreVerticalIcon } from '@blocksuite/icons/lit';
import type { InlineRange } from '@blocksuite/inline';
import { computePosition, inline, offset, shift } from '@floating-ui/dom';
@@ -51,6 +51,10 @@ export class ReferencePopup extends WithDisposable(LitElement) {
static override styles = styles;
private readonly _copyLink = () => {
if (!this.std) {
console.error('`std` is not found');
return;
}
const url = this.std
.getOptional(GenerateDocUrlProvider)
?.generateDocUrl(this.referenceInfo.pageId, this.referenceInfo.params);
@@ -66,6 +70,10 @@ export class ReferencePopup extends WithDisposable(LitElement) {
};
private readonly _openDoc = (event?: Partial<DocLinkClickedEvent>) => {
if (!this.std) {
console.error('`std` is not found');
return;
}
this.std.getOptional(RefNodeSlotsProvider)?.docLinkClicked.emit({
...this.referenceInfo,
...event,
@@ -89,6 +97,11 @@ export class ReferencePopup extends WithDisposable(LitElement) {
abortController,
} = this;
if (!std) {
console.error('`std` is not found');
return;
}
const aliasPopup = new ReferenceAliasPopup();
aliasPopup.std = std;
@@ -105,6 +118,10 @@ export class ReferencePopup extends WithDisposable(LitElement) {
};
private readonly _toggleViewSelector = (e: Event) => {
if (!this.std) {
console.error('`std` is not found');
return;
}
const opened = (e as CustomEvent<boolean>).detail;
if (!opened) return;
@@ -112,6 +129,10 @@ export class ReferencePopup extends WithDisposable(LitElement) {
};
private readonly _trackViewSelected = (type: string) => {
if (!this.std) {
console.error('`std` is not found');
return;
}
track(this.std, 'SelectedView', {
control: 'select view',
type: `${type} view`,
@@ -119,6 +140,11 @@ export class ReferencePopup extends WithDisposable(LitElement) {
};
get _embedViewButtonDisabled() {
if (!this.block) {
console.error('`block` is not found');
return true;
}
if (
this.block.doc.readonly ||
isInsideBlockByFlavour(
@@ -131,13 +157,13 @@ export class ReferencePopup extends WithDisposable(LitElement) {
}
return (
!!this.block.closest('affine-embed-synced-doc-block') ||
this.referenceDocId === this.doc.id
this.referenceDocId === this.block.doc.id
);
}
_openButtonDisabled(openMode?: OpenDocMode) {
if (openMode === 'open-in-active-view') {
return this.referenceDocId === this.doc.id;
return this.referenceDocId === this.doc?.id;
}
return false;
}
@@ -146,34 +172,32 @@ export class ReferencePopup extends WithDisposable(LitElement) {
const block = this.inlineEditor.rootElement?.closest<BlockComponent>(
`[${BLOCK_ID_ATTR}]`
);
assertExists(block);
return block;
}
get doc() {
const doc = this.block.doc;
assertExists(doc);
const doc = this.block?.doc;
return doc;
}
get referenceDocId() {
const docId = this.inlineEditor.getFormat(this.targetInlineRange).reference
?.pageId;
assertExists(docId);
return docId;
}
get std() {
const std = this.block.std;
assertExists(std);
const std = this.block?.std;
return std;
}
private _convertToCardView() {
const block = this.block;
if (!block) return;
const doc = block.host.doc;
const parent = doc.getParent(block.model);
assertExists(parent);
if (!parent) return;
const index = parent.children.indexOf(block.model);
@@ -197,10 +221,17 @@ export class ReferencePopup extends WithDisposable(LitElement) {
private _convertToEmbedView() {
const block = this.block;
const std = block.std;
const std = block?.std;
if (!std || !block) {
console.error('`std` or `block` is not found');
return;
}
const doc = block.host.doc;
const parent = doc.getParent(block.model);
assertExists(parent);
if (!parent) {
console.error('`parent` is not found');
return;
}
const index = parent.children.indexOf(block.model);
const referenceInfo = this.referenceInfo;
@@ -242,7 +273,7 @@ export class ReferencePopup extends WithDisposable(LitElement) {
type: 'delete',
label: 'Delete',
icon: DeleteIcon,
disabled: this.doc.readonly,
disabled: this.doc?.readonly,
action: () => this._delete(),
},
],
@@ -250,6 +281,10 @@ export class ReferencePopup extends WithDisposable(LitElement) {
}
private _openMenuButton() {
if (!this.std) {
console.error('`std` is not found');
return nothing;
}
const openDocConfig = this.std.get(OpenDocExtensionIdentifier);
const buttons: MenuItem[] = openDocConfig.items
@@ -330,7 +365,7 @@ export class ReferencePopup extends WithDisposable(LitElement) {
type: 'card',
label: 'Card view',
action: () => this._convertToCardView(),
disabled: this.doc.readonly,
disabled: this.doc?.readonly,
});
buttons.push({
@@ -338,7 +373,9 @@ export class ReferencePopup extends WithDisposable(LitElement) {
label: 'Embed view',
action: () => this._convertToEmbedView(),
disabled:
this.doc.readonly || this.isLinkedNode || this._embedViewButtonDisabled,
this.doc?.readonly ||
this.isLinkedNode ||
this._embedViewButtonDisabled,
});
return html`
@@ -388,11 +425,14 @@ export class ReferencePopup extends WithDisposable(LitElement) {
return;
}
if (!this.block) return;
const parent = this.block.host.doc.getParent(this.block.model);
assertExists(parent);
if (!parent) return;
this.disposables.add(
effect(() => {
if (!this.block) return;
const children = parent.children;
if (children.includes(this.block.model)) return;
this.abortController.abort();
@@ -435,7 +475,7 @@ export class ReferencePopup extends WithDisposable(LitElement) {
aria-label="Edit"
data-testid="edit"
.tooltip=${'Edit'}
?disabled=${this.doc.readonly}
?disabled=${this.doc?.readonly}
@click=${this._openEditPopup}
>
${EditIcon}
@@ -479,10 +519,8 @@ export class ReferencePopup extends WithDisposable(LitElement) {
}
override updated() {
assertExists(this.popupContainer);
const range = this.inlineEditor.toDomRange(this.targetInlineRange);
assertExists(range);
if (!range) return;
const visualElement = {
getBoundingClientRect: () => range.getBoundingClientRect(),
getClientRects: () => range.getClientRects(),
@@ -1,6 +1,6 @@
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
import { ShadowlessElement } from '@blocksuite/block-std';
import { assertExists, WithDisposable } from '@blocksuite/global/utils';
import { WithDisposable } from '@blocksuite/global/utils';
import {
type AttributeRenderer,
type DeltaInsert,
@@ -148,7 +148,6 @@ export class RichText extends WithDisposable(ShadowlessElement) {
}
get inlineEditorContainer() {
assertExists(this._inlineEditorContainer);
return this._inlineEditorContainer;
}
@@ -1,5 +1,4 @@
import { requestConnectedFrame } from '@blocksuite/affine-shared/utils';
import { assertExists } from '@blocksuite/global/utils';
import {
arrow,
type ComputePositionReturn,
@@ -193,7 +192,10 @@ export class Tooltip extends LitElement {
);
const parent = this.parentElement;
assertExists(parent, 'Tooltip must have a parent element');
if (!parent) {
console.error('Tooltip must have a parent element');
return;
}
// Wait for render
requestConnectedFrame(() => {
@@ -1,6 +1,5 @@
import type { InsertToPosition } from '@blocksuite/affine-shared/utils';
import { Point, Rect } from '@blocksuite/global/gfx';
import { assertExists } from '@blocksuite/global/utils';
import { computed } from '@preact/signals-core';
import type { ReactiveController } from 'lit';
@@ -137,7 +136,6 @@ export class KanbanDragController implements ReactiveController {
const scrollContainer = this.host.querySelector(
'.affine-data-view-kanban-groups'
) as HTMLElement;
assertExists(scrollContainer);
return scrollContainer;
}
@@ -213,7 +211,10 @@ const createDropPreview = () => {
card?: KanbanCard
) {
const target = card ?? group.querySelector('.add-card');
assertExists(target);
if (!target) {
console.error('`target` is not found');
return;
}
if (target.previousElementSibling === self || target === self) {
div.remove();
return;
@@ -1,5 +1,4 @@
import { BlockSuiteError, ErrorCode } from '@blocksuite/global/exceptions';
import { assertExists } from '@blocksuite/global/utils';
import type { ReactiveController } from 'lit';
import type {
@@ -611,7 +610,7 @@ function getNextGroupFocusElement(
selection.selectionType === 'cell'
? getFocusCell(viewElement, selection)
: getSelectedCards(viewElement, selection)[0];
assertExists(element);
if (!element) return;
const rect = element.getBoundingClientRect();
const nextCards = Array.from(
nextGroup.querySelectorAll('affine-data-view-kanban-card')
@@ -1,9 +1,5 @@
import { ShadowlessElement } from '@blocksuite/block-std';
import {
assertExists,
SignalWatcher,
WithDisposable,
} from '@blocksuite/global/utils';
import { SignalWatcher, WithDisposable } from '@blocksuite/global/utils';
import { computed } from '@preact/signals-core';
import { css } from 'lit';
import { property, state } from 'lit/decorators.js';
@@ -102,7 +98,6 @@ export class DatabaseCellContainer extends SignalWatcher(
get table() {
const table = this.closest('affine-database-table');
assertExists(table);
return table;
}
@@ -15,7 +15,6 @@ import {
TextSelection,
} from '@blocksuite/block-std';
import { BlockSuiteError, ErrorCode } from '@blocksuite/global/exceptions';
import { assertExists } from '@blocksuite/global/utils';
import {
type BlockModel,
type BlockSnapshot,
@@ -64,9 +63,14 @@ const findLast = (snapshot: SliceSnapshot): BlockSnapshot | null => {
};
class PointState {
private readonly _blockFromPath = (path: string) => {
const block = this.std.view.getBlock(path);
assertExists(block);
private readonly _blockFromPath = (id: string) => {
const block = this.std.view.getBlock(id);
if (!block) {
throw new BlockSuiteError(
ErrorCode.TransformerError,
`Block not found when pasting: ${id}`
);
}
return block;
};
@@ -6,7 +6,7 @@ import type {
ParagraphBlockModel,
SurfaceRefBlockModel,
} from '@blocksuite/affine-model';
import { assertExists } from '@blocksuite/global/utils';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import type { DeltaOperation, TransformerMiddleware } from '@blocksuite/store';
export const replaceIdMiddleware =
@@ -166,13 +166,23 @@ export const replaceIdMiddleware =
let connection = value.source as Record<string, string>;
if (idMap.has(connection.id)) {
const newId = idMap.get(connection.id);
assertExists(newId, 'reference id must exist');
if (!newId) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.TransformerError,
`reference id must exist: ${connection.id}`
);
}
connection.id = newId;
}
connection = value.target as Record<string, string>;
if (idMap.has(connection.id)) {
const newId = idMap.get(connection.id);
assertExists(newId, 'reference id must exist');
if (!newId) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.TransformerError,
`reference id must exist: ${connection.id}`
);
}
connection.id = newId;
}
break;
@@ -184,7 +194,12 @@ export const replaceIdMiddleware =
if (idMap.has(key)) {
delete json[key];
const newKey = idMap.get(key);
assertExists(newKey, 'reference id must exist');
if (!newKey) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.TransformerError,
`reference id must exist: ${key}`
);
}
json[newKey] = value;
}
});
@@ -1,4 +1,4 @@
import { assertExists } from '@blocksuite/global/utils';
import { BlockSuiteError } from '@blocksuite/global/exceptions';
import type { ExtensionType } from '@blocksuite/store';
import { SpecBuilder } from './spec-builder.js';
@@ -45,7 +45,12 @@ export class SpecProvider {
getSpec(id: SpecId) {
const spec = this.specMap.get(id);
assertExists(spec, `Spec not found for ${id}`);
if (!spec) {
throw new BlockSuiteError(
BlockSuiteError.ErrorCode.ValueNotExists,
`Spec not found for ${id}`
);
}
return new SpecBuilder(spec);
}