Skip to content

BlockSuite API Documentation / @blocksuite/affine-block-surface

@blocksuite/affine-block-surface

Enumerations

CanvasElementType

Enumeration Members

BRUSH

BRUSH: "brush"

CONNECTOR

CONNECTOR: "connector"

GROUP

GROUP: "group"

HIGHLIGHTER

HIGHLIGHTER: "highlighter"

MINDMAP

MINDMAP: "mindmap"

SHAPE

SHAPE: "shape"

TEXT

TEXT: "text"


DefaultModeDragType

Enumeration Members

ContentMoving

ContentMoving: "content-moving"

Moving selected contents

NativeEditing

NativeEditing: "native-editing"

Native range dragging inside active note block

None

None: "none"

Default void state

Selecting

Selecting: "selecting"

Expanding the dragging area, select the content covered inside

Classes

Extension

abstract EdgelessClipboardConfig

Understanding Extensions

Extensions provide a way to extend the functionality of a system using dependency injection. They allow you to register services, implementations, and factories in the DI container, which can then be retrieved and used by different parts of the application.

Extensions are particularly useful for:

  • Registering different implementations for different types
  • Creating pluggable architecture where components can be added or removed
  • Managing dependencies between different parts of the application

Usage Example: Fruit Processing System

Let's consider a fruit processing system where different types of fruits need different processing methods. We'll show how to implement this using extensions.

Step 1: Define the interfaces

ts
interface FruitProcessor {
  process(fruit: Fruit): void;
}

interface Fruit {
  type: string;
  // other properties
}

Step 2: Create a service identifier

ts
import { createIdentifier } from '@blocksuite/global/di';

const FruitProcessorProvider = createIdentifier<FruitProcessor>('fruit-processor-provider');

Step 3: Create implementations

ts
class AppleProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Slicing apple');
    // Apple-specific processing
  }
}

class BananaProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Peeling banana');
    // Banana-specific processing
  }
}

Step 4: Create an extension factory

ts
const FruitProcessorExtension = (
  fruitType: string,
  implementation: new () => FruitProcessor
): ExtensionType => {
  return {
    setup: di => {
      di.addImpl(FruitProcessorProvider(fruitType), implementation);
    }
  };
};

Step 5: Create concrete extensions

ts
export const AppleProcessorExtension = FruitProcessorExtension('apple', AppleProcessor);
export const BananaProcessorExtension = FruitProcessorExtension('banana', BananaProcessor);

Step 6: Use the extensions

ts
import { Container } from '@blocksuite/global/di';

class FruitProcessingSystem {
  provider: ServiceProvider;

  constructor(extensions: ExtensionType[]) {
    const container = new Container();

    // Set up all extensions
    extensions.forEach(ext => ext.setup(container));

    // Create a provider from the container
    this.provider = container.provider();
  }

  processFruit(fruit: Fruit) {
    // Get the appropriate processor based on fruit type
    const processor = this.provider.get(FruitProcessorProvider(fruit.type));

    // Process the fruit
    processor.process(fruit);
  }
}

// Initialize the system with extensions
const system = new FruitProcessingSystem([
  AppleProcessorExtension,
  BananaProcessorExtension
]);

// Use the system
system.processFruit({ type: 'apple' });  // Output: Slicing apple
system.processFruit({ type: 'banana' }); // Output: Peeling banana

Note: We deliberately used a non-block specific example here. In BlockSuite, the extension pattern can be applied to any entity that can be configured by third parties, not just blocks. This includes different tools in the whiteboard, different column types in database blocks, and many other extensible components. The pattern remains the same regardless of what you're extending.

Extends
Extended by
Constructors
Constructor

new EdgelessClipboardConfig(std): EdgelessClipboardConfig

Parameters
std

BlockStdScope

Returns

EdgelessClipboardConfig

Overrides

Extension.constructor

Properties
std

readonly std: BlockStdScope

key

static key: string

Accessors
crud
Get Signature

get crud(): EdgelessCRUDExtension

Returns

EdgelessCRUDExtension

surface
Get Signature

get surface(): SurfaceBlockComponent | null

Returns

SurfaceBlockComponent | null

Methods
createBlock()

abstract createBlock(snapshot, context): string | Promise<string | null> | null

Parameters
snapshot

BlockSnapshot

context

ClipboardConfigCreationContext

Returns

string | Promise<string | null> | null

onBlockSnapshotPaste()

onBlockSnapshotPaste(snapshot, doc, parent?, index?): Promise<string | null>

Parameters
snapshot

BlockSnapshot

doc

Store

parent?

string

index?

number

Returns

Promise<string | null>

setup()

static setup(di): void

Parameters
di

Container

Returns

void

Overrides

Extension.setup


EdgelessCRUDExtension

Understanding Extensions

Extensions provide a way to extend the functionality of a system using dependency injection. They allow you to register services, implementations, and factories in the DI container, which can then be retrieved and used by different parts of the application.

Extensions are particularly useful for:

  • Registering different implementations for different types
  • Creating pluggable architecture where components can be added or removed
  • Managing dependencies between different parts of the application

Usage Example: Fruit Processing System

Let's consider a fruit processing system where different types of fruits need different processing methods. We'll show how to implement this using extensions.

Step 1: Define the interfaces

ts
interface FruitProcessor {
  process(fruit: Fruit): void;
}

interface Fruit {
  type: string;
  // other properties
}

Step 2: Create a service identifier

ts
import { createIdentifier } from '@blocksuite/global/di';

const FruitProcessorProvider = createIdentifier<FruitProcessor>('fruit-processor-provider');

Step 3: Create implementations

ts
class AppleProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Slicing apple');
    // Apple-specific processing
  }
}

class BananaProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Peeling banana');
    // Banana-specific processing
  }
}

Step 4: Create an extension factory

ts
const FruitProcessorExtension = (
  fruitType: string,
  implementation: new () => FruitProcessor
): ExtensionType => {
  return {
    setup: di => {
      di.addImpl(FruitProcessorProvider(fruitType), implementation);
    }
  };
};

Step 5: Create concrete extensions

ts
export const AppleProcessorExtension = FruitProcessorExtension('apple', AppleProcessor);
export const BananaProcessorExtension = FruitProcessorExtension('banana', BananaProcessor);

Step 6: Use the extensions

ts
import { Container } from '@blocksuite/global/di';

class FruitProcessingSystem {
  provider: ServiceProvider;

  constructor(extensions: ExtensionType[]) {
    const container = new Container();

    // Set up all extensions
    extensions.forEach(ext => ext.setup(container));

    // Create a provider from the container
    this.provider = container.provider();
  }

  processFruit(fruit: Fruit) {
    // Get the appropriate processor based on fruit type
    const processor = this.provider.get(FruitProcessorProvider(fruit.type));

    // Process the fruit
    processor.process(fruit);
  }
}

// Initialize the system with extensions
const system = new FruitProcessingSystem([
  AppleProcessorExtension,
  BananaProcessorExtension
]);

// Use the system
system.processFruit({ type: 'apple' });  // Output: Slicing apple
system.processFruit({ type: 'banana' }); // Output: Peeling banana

Note: We deliberately used a non-block specific example here. In BlockSuite, the extension pattern can be applied to any entity that can be configured by third parties, not just blocks. This includes different tools in the whiteboard, different column types in database blocks, and many other extensible components. The pattern remains the same regardless of what you're extending.

Extends
Constructors
Constructor

new EdgelessCRUDExtension(std): EdgelessCRUDExtension

Parameters
std

BlockStdScope

Returns

EdgelessCRUDExtension

Overrides

Extension.constructor

Properties
std

readonly std: BlockStdScope

Methods
addBlock()

addBlock(flavour, props, parentId?, parentIndex?): string

Parameters
flavour

string

props

Record<string, unknown>

parentId?

string | BlockModel<object>

parentIndex?

number

Returns

string

addElement()

addElement<T>(type, props): string | undefined

Type Parameters
T

T extends Record<string, unknown>

Parameters
type

string

props

T

Returns

string | undefined

deleteElements()

deleteElements(elements): void

Parameters
elements

GfxModel[]

Returns

void

getElementById()

getElementById(id): GfxModel | null

Parameters
id

string

Returns

GfxModel | null

getElementsByType()

getElementsByType<K>(type): SurfaceElementModelMap[K][]

Type Parameters
K

K extends keyof SurfaceElementModelMap

Parameters
type

K

Returns

SurfaceElementModelMap[K][]

removeElement()

removeElement(id): void

Parameters
id

string | GfxModel

Returns

void

updateElement()

updateElement(id, props): void

Parameters
id

string

props

Record<string, unknown>

Returns

void

setup()

static setup(di): void

Parameters
di

Container

Returns

void

Overrides

Extension.setup


EditPropsMiddlewareBuilder

Understanding Extensions

Extensions provide a way to extend the functionality of a system using dependency injection. They allow you to register services, implementations, and factories in the DI container, which can then be retrieved and used by different parts of the application.

Extensions are particularly useful for:

  • Registering different implementations for different types
  • Creating pluggable architecture where components can be added or removed
  • Managing dependencies between different parts of the application

Usage Example: Fruit Processing System

Let's consider a fruit processing system where different types of fruits need different processing methods. We'll show how to implement this using extensions.

Step 1: Define the interfaces

ts
interface FruitProcessor {
  process(fruit: Fruit): void;
}

interface Fruit {
  type: string;
  // other properties
}

Step 2: Create a service identifier

ts
import { createIdentifier } from '@blocksuite/global/di';

const FruitProcessorProvider = createIdentifier<FruitProcessor>('fruit-processor-provider');

Step 3: Create implementations

ts
class AppleProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Slicing apple');
    // Apple-specific processing
  }
}

class BananaProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Peeling banana');
    // Banana-specific processing
  }
}

Step 4: Create an extension factory

ts
const FruitProcessorExtension = (
  fruitType: string,
  implementation: new () => FruitProcessor
): ExtensionType => {
  return {
    setup: di => {
      di.addImpl(FruitProcessorProvider(fruitType), implementation);
    }
  };
};

Step 5: Create concrete extensions

ts
export const AppleProcessorExtension = FruitProcessorExtension('apple', AppleProcessor);
export const BananaProcessorExtension = FruitProcessorExtension('banana', BananaProcessor);

Step 6: Use the extensions

ts
import { Container } from '@blocksuite/global/di';

class FruitProcessingSystem {
  provider: ServiceProvider;

  constructor(extensions: ExtensionType[]) {
    const container = new Container();

    // Set up all extensions
    extensions.forEach(ext => ext.setup(container));

    // Create a provider from the container
    this.provider = container.provider();
  }

  processFruit(fruit: Fruit) {
    // Get the appropriate processor based on fruit type
    const processor = this.provider.get(FruitProcessorProvider(fruit.type));

    // Process the fruit
    processor.process(fruit);
  }
}

// Initialize the system with extensions
const system = new FruitProcessingSystem([
  AppleProcessorExtension,
  BananaProcessorExtension
]);

// Use the system
system.processFruit({ type: 'apple' });  // Output: Slicing apple
system.processFruit({ type: 'banana' }); // Output: Peeling banana

Note: We deliberately used a non-block specific example here. In BlockSuite, the extension pattern can be applied to any entity that can be configured by third parties, not just blocks. This includes different tools in the whiteboard, different column types in database blocks, and many other extensible components. The pattern remains the same regardless of what you're extending.

Extends
Constructors
Properties
middleware

middleware: SurfaceMiddleware

Overrides

SurfaceMiddlewareBuilder.middleware

key

static key: string = 'editProps'

Overrides

SurfaceMiddlewareBuilder.key

Accessors
Methods

DefaultTool

Understanding Extensions

Extensions provide a way to extend the functionality of a system using dependency injection. They allow you to register services, implementations, and factories in the DI container, which can then be retrieved and used by different parts of the application.

Extensions are particularly useful for:

  • Registering different implementations for different types
  • Creating pluggable architecture where components can be added or removed
  • Managing dependencies between different parts of the application

Usage Example: Fruit Processing System

Let's consider a fruit processing system where different types of fruits need different processing methods. We'll show how to implement this using extensions.

Step 1: Define the interfaces

ts
interface FruitProcessor {
  process(fruit: Fruit): void;
}

interface Fruit {
  type: string;
  // other properties
}

Step 2: Create a service identifier

ts
import { createIdentifier } from '@blocksuite/global/di';

const FruitProcessorProvider = createIdentifier<FruitProcessor>('fruit-processor-provider');

Step 3: Create implementations

ts
class AppleProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Slicing apple');
    // Apple-specific processing
  }
}

class BananaProcessor implements FruitProcessor {
  process(fruit: Fruit): void {
    console.log('Peeling banana');
    // Banana-specific processing
  }
}

Step 4: Create an extension factory

ts
const FruitProcessorExtension = (
  fruitType: string,
  implementation: new () => FruitProcessor
): ExtensionType => {
  return {
    setup: di => {
      di.addImpl(FruitProcessorProvider(fruitType), implementation);
    }
  };
};

Step 5: Create concrete extensions

ts
export const AppleProcessorExtension = FruitProcessorExtension('apple', AppleProcessor);
export const BananaProcessorExtension = FruitProcessorExtension('banana', BananaProcessor);

Step 6: Use the extensions

ts
import { Container } from '@blocksuite/global/di';

class FruitProcessingSystem {
  provider: ServiceProvider;

  constructor(extensions: ExtensionType[]) {
    const container = new Container();

    // Set up all extensions
    extensions.forEach(ext => ext.setup(container));

    // Create a provider from the container
    this.provider = container.provider();
  }

  processFruit(fruit: Fruit) {
    // Get the appropriate processor based on fruit type
    const processor = this.provider.get(FruitProcessorProvider(fruit.type));

    // Process the fruit
    processor.process(fruit);
  }
}

// Initialize the system with extensions
const system = new FruitProcessingSystem([
  AppleProcessorExtension,
  BananaProcessorExtension
]);

// Use the system
system.processFruit({ type: 'apple' });  // Output: Slicing apple
system.processFruit({ type: 'banana' }); // Output: Peeling banana

Note: We deliberately used a non-block specific example here. In BlockSuite, the extension pattern can be applied to any entity that can be configured by third parties, not just blocks. This includes different tools in the whiteboard, different column types in database blocks, and many other extensible components. The pattern remains the same regardless of what you're extending.

Extends
Constructors
Properties
dragType

dragType: DefaultModeDragType = DefaultModeDragType.None

movementDragging

movementDragging: boolean = false

toolName

static toolName: string = 'default'

Overrides

BaseTool.toolName

Accessors
dragLastPos
Get Signature

get dragLastPos(): IVec

Get the end position of the dragging area in the model coordinate

Returns

IVec

dragStartPos
Get Signature

get dragStartPos(): IVec

Get the start position of the dragging area in the model coordinate

Returns

IVec

interactivity
Get Signature

get interactivity(): InteractivityManager | null

Returns

InteractivityManager | null

selection
Get Signature

get selection(): GfxSelectionManager

Returns

GfxSelectionManager

Methods
click()

click(e): void

Parameters
e

PointerEventState

Returns

void

Overrides

BaseTool.click

deactivate()

deactivate(): void

Called when the tool is deactivated.

Returns

void

Overrides

BaseTool.deactivate

doubleClick()

doubleClick(e): void

Parameters
e

PointerEventState

Returns

void

Overrides

BaseTool.doubleClick

dragEnd()

dragEnd(e): void

Parameters
e

PointerEventState

Returns

void

Overrides

BaseTool.dragEnd

dragMove()

dragMove(e): void

Parameters
e

PointerEventState

Returns

void

Overrides

BaseTool.dragMove

dragStart()

dragStart(e): Promise<void>

Parameters
e

PointerEventState

Returns

Promise<void>

Overrides

BaseTool.dragStart

mounted()

mounted(): void

Called when the tool is registered.

Returns

void

Overrides

BaseTool.mounted

pointerDown()

pointerDown(e): void

Parameters
e

PointerEventState

Returns

void

Overrides

BaseTool.pointerDown

pointerMove()

pointerMove(e): void

Parameters
e

PointerEventState

Returns

void

Overrides

BaseTool.pointerMove

pointerUp()

pointerUp(e): void

Parameters
e

PointerEventState

Returns

void

Overrides

BaseTool.pointerUp

unmounted()

unmounted(): void

Called when the tool is unloaded, usually when the whole ToolController is destroyed.

Returns

void

Overrides

BaseTool.unmounted

Other

MarkdownElementModelAdapter

Extends
  • ElementModelAdapter<MarkdownAST, MarkdownAST>
Constructors
Constructor

new MarkdownElementModelAdapter(elementModelMatchers): MarkdownElementModelAdapter

Parameters
elementModelMatchers

ElementToMarkdownAdapterMatcher[]

Returns

MarkdownElementModelAdapter

Overrides

ElementModelAdapter< MarkdownAST, MarkdownAST >.constructor

Properties
elementModelMatchers

readonly elementModelMatchers: ElementToMarkdownAdapterMatcher[]

Methods
fromElementModel()

fromElementModel(element, context): MarkdownAST | null

Convert element model to AST format

Parameters
element

Record<string, unknown>

context

ElementModelAdapterContext<MarkdownAST>

Returns

MarkdownAST | null

Overrides

ElementModelAdapter.fromElementModel


PlainTextElementModelAdapter

Extends
  • ElementModelAdapter<string, TextBuffer>
Constructors
Constructor

new PlainTextElementModelAdapter(elementModelMatchers): PlainTextElementModelAdapter

Parameters
elementModelMatchers

ElementToPlainTextAdapterMatcher[]

Returns

PlainTextElementModelAdapter

Overrides

ElementModelAdapter< string, TextBuffer >.constructor

Properties
elementModelMatchers

readonly elementModelMatchers: ElementToPlainTextAdapterMatcher[]

Methods
fromElementModel()

fromElementModel(element, context): string

Convert element model to AST format

Parameters
element

Record<string, unknown>

context

ElementModelAdapterContext<TextBuffer>

Returns

string

Overrides

ElementModelAdapter.fromElementModel


ExportManager

Constructors
Constructor

new ExportManager(std): ExportManager

Parameters
std

BlockStdScope

Returns

ExportManager

Properties
std

readonly std: BlockStdScope

Accessors
doc
Get Signature

get doc(): Store

Returns

Store

editorHost
Get Signature

get editorHost(): EditorHost

Returns

EditorHost

Methods
edgelessToCanvas()

edgelessToCanvas(surfaceRenderer, bound, gfx, blocks?, elements?, edgelessBackground?): Promise<HTMLCanvasElement | undefined>

Parameters
surfaceRenderer

CanvasRenderer

bound

IBound

gfx

GfxController

blocks?

GfxBlockElementModel<GfxCompatibleProps>[]

elements?

SurfaceElementModel<BaseElementProps>[]

edgelessBackground?
zoom

number

Returns

Promise<HTMLCanvasElement | undefined>

exportPdf()

exportPdf(): Promise<void>

Returns

Promise<void>

exportPng()

exportPng(): Promise<void>

Returns

Promise<void>

replaceImgSrcWithSvg()

replaceImgSrcWithSvg(element): Promise<void>

Parameters
element

HTMLElement

Returns

Promise<void>


CanvasRenderer

Constructors
Constructor

new CanvasRenderer(options): CanvasRenderer

Parameters
options

RendererOptions

Returns

CanvasRenderer

Properties
canvas

canvas: HTMLCanvasElement

ctx

ctx: CanvasRenderingContext2D

grid

grid: GridManager

layerManager

layerManager: LayerManager

provider

provider: Partial<EnvProvider>

stackingCanvasUpdated

stackingCanvasUpdated: Subject<{ added: HTMLCanvasElement[]; canvases: HTMLCanvasElement[]; removed: HTMLCanvasElement[]; }>

std

std: BlockStdScope

usePlaceholder

usePlaceholder: boolean = false

viewport

viewport: Viewport

Accessors
stackingCanvas
Get Signature

get stackingCanvas(): HTMLCanvasElement[]

Returns

HTMLCanvasElement[]

Methods
addOverlay()

addOverlay(overlay): void

Parameters
overlay

Overlay

Returns

void

attach()

attach(container): void

Used to attach main canvas, main canvas will always exist

Parameters
container

HTMLElement

Returns

void

dispose()

dispose(): void

Returns

void

generateColorProperty()

generateColorProperty(color, fallback?): string

Parameters
color

string | { normal: string; } | { dark: string; light: string; }

fallback?

string | { normal: string; } | { dark: string; light: string; }

Returns

string

getCanvasByBound()

getCanvasByBound(bound, surfaceElements?, canvas?, clearBeforeDrawing?, withZoom?): HTMLCanvasElement

Parameters
bound

IBound = ...

surfaceElements?

SurfaceElementModel<BaseElementProps>[]

canvas?

HTMLCanvasElement

clearBeforeDrawing?

boolean

withZoom?

boolean

Returns

HTMLCanvasElement

getColorScheme()

getColorScheme(): ColorScheme

Returns

ColorScheme

getColorValue()

getColorValue(color, fallback?, real?): string

Parameters
color

string | { normal: string; } | { dark: string; light: string; }

fallback?

string | { normal: string; } | { dark: string; light: string; }

real?

boolean

Returns

string

getDebugMetrics()

getDebugMetrics(): CanvasRendererDebugMetrics

Returns

CanvasRendererDebugMetrics

getPropertyValue()

getPropertyValue(property): string

Parameters
property

string

Returns

string

refresh()

refresh(target): void

Parameters
target

RefreshTarget = ...

Returns

void

removeOverlay()

removeOverlay(overlay): void

Parameters
overlay

Overlay

Returns

void

resetDebugMetrics()

resetDebugMetrics(): void

Returns

void


DomRenderer

DomRenderer Renders surface elements directly to the DOM using HTML elements and CSS.

This renderer supports an extension mechanism to handle different types of surface elements. To add rendering support for a new element type (e.g., 'my-custom-element'), follow these steps:

  1. Define the Renderer Function: Create a function that implements the rendering logic for your element. This function will receive the element's model, the target HTMLElement, and the DomRenderer instance. Signature: (model: MyCustomElementModel, domElement: HTMLElement, renderer: DomRenderer) => void; Example: shapeDomRenderer in blocksuite/affine/gfx/shape/src/element-renderer/shape-dom/index.ts. In this function, you'll apply styles and attributes to the domElement based on the model.

  2. Create the Renderer Extension: Create a new file (e.g., my-custom-element-dom-renderer.extension.ts). Import DomElementRendererExtension (e.g., from @blocksuite/affine-block-surface or its source location blocksuite/affine/blocks/surface/src/extensions/dom-element-renderer.ts). Import your renderer function (from step 1). Use the factory to create your extension: export const MyCustomElementDomRendererExtension = DomElementRendererExtension('my-custom-element', myCustomElementRendererFn); Example: ShapeDomRendererExtension in blocksuite/affine/gfx/shape/src/element-renderer/shape-dom.ts.

  3. Register the Extension: In your application setup where BlockSuite services and view extensions are registered (e.g., a ViewExtensionProvider or a central DI configuration place), import your new extension (from step 2) and register it with the dependency injection container. Example: context.register(MyCustomElementDomRendererExtension); As seen with ShapeDomRendererExtension being registered in blocksuite/affine/gfx/shape/src/view.ts.

  4. Core Infrastructure (Provided by DomRenderer System):

    • DomElementRenderer (type): The function signature for renderers, defined in blocksuite/affine/blocks/surface/src/renderer/dom-elements/index.ts.
    • DomElementRendererIdentifier (function): Creates unique service identifiers for DI, used by DomRenderer to look up specific renderers. Defined in the same file.
    • DomElementRendererExtension (factory): A helper to create extension objects for easy registration. (e.g., from @blocksuite/affine-block-surface or its source).
    • DomRenderer._renderElement(): This method automatically looks up the registered renderer using DomElementRendererIdentifier(elementType) and calls it if found.
  5. Ensure Exports:

    • The DomRenderer class itself should be accessible (e.g., exported from @blocksuite/affine/blocks/surface).
    • The DomElementRendererExtension factory should be accessible.

By following these steps, DomRenderer will automatically pick up and use your custom rendering logic when it encounters elements of 'my-custom-element' type.

Constructors
Constructor

new DomRenderer(options): DomRenderer

Parameters
options

RendererOptions

Returns

DomRenderer

Properties
elementsUpdated

elementsUpdated: Subject<{ added: HTMLElement[]; elements: HTMLElement[]; removed: HTMLElement[]; }>

grid

grid: GridManager

layerManager

layerManager: LayerManager

provider

provider: Partial<EnvProvider>

rootElement

rootElement: HTMLElement

std

std: BlockStdScope

usePlaceholder

usePlaceholder: boolean = false

viewport

viewport: Viewport

Methods
addOverlay()

addOverlay(overlay): void

Parameters
overlay

Overlay

Returns

void

attach()

attach(container): void

Parameters
container

HTMLElement

Returns

void

dispose()

dispose(): void

Returns

void

forceFullRender()

forceFullRender(): void

Force a full re-render of all elements

Returns

void

generateColorProperty()

generateColorProperty(color, fallback?): string

Parameters
color

string | { normal: string; } | { dark: string; light: string; }

fallback?

string | { normal: string; } | { dark: string; light: string; }

Returns

string

getColorScheme()

getColorScheme(): ColorScheme

Returns

ColorScheme

getColorValue()

getColorValue(color, fallback?, real?): string

Parameters
color

string | { normal: string; } | { dark: string; light: string; }

fallback?

string | { normal: string; } | { dark: string; light: string; }

real?

boolean

Returns

string

getPropertyValue()

getPropertyValue(property): string

Parameters
property

string

Returns

string

markElementDirty()

markElementDirty(elementId, updateType): void

Mark a specific element as dirty for incremental updates

Parameters
elementId

string

The ID of the element to mark as dirty

updateType

UpdateType = UpdateType.ELEMENT_UPDATED

The type of update (optional, defaults to ELEMENT_UPDATED)

Returns

void

refresh()

refresh(): void

Returns

void

removeOverlay()

removeOverlay(overlay): void

Parameters
overlay

Overlay

Returns

void


abstract Overlay

An overlay is a layer covered on top of elements, can be used for rendering non-CRDT state indicators.

Extends
Extended by
Constructors
Constructor

new Overlay(gfx): Overlay

Parameters
gfx

GfxController

Returns

Overlay

Overrides

Extension.constructor

Properties
_renderer

protected _renderer: CanvasRenderer | null = null

gfx

protected gfx: GfxController

overlayName

static overlayName: string = ''

Methods
clear()

clear(): void

Returns

void

dispose()

dispose(): void

Returns

void

refresh()

refresh(): void

Returns

void

render()

abstract render(ctx, rc): void

Parameters
ctx

CanvasRenderingContext2D

rc

RoughCanvas

Returns

void

setRenderer()

setRenderer(renderer): void

Parameters
renderer

CanvasRenderer | null

Returns

void

setup()

static setup(di): void

Parameters
di

Container

Returns

void

Overrides

Extension.setup


ToolOverlay

An overlay is a layer covered on top of elements, can be used for rendering non-CRDT state indicators.

Extends
Extended by
Constructors
Constructor

new ToolOverlay(gfx): ToolOverlay

Parameters
gfx

GfxController

Returns

ToolOverlay

Overrides

Overlay.constructor

Properties
disposables

protected disposables: DisposableGroup

globalAlpha

globalAlpha: number

x

x: number

y

y: number

Methods
dispose()

dispose(): void

Returns

void

Overrides

Overlay.dispose

render()

render(ctx, rc): void

Parameters
ctx

CanvasRenderingContext2D

rc

RoughCanvas

Returns

void

Overrides

Overlay.render


SurfaceBlockComponent

Extends
Constructors
Other
renderer
Get Signature

get renderer(): DomRenderer | CanvasRenderer

Returns

DomRenderer | CanvasRenderer

connectedCallback()

connectedCallback(): void

Returns

void

Overrides

BlockComponent.connectedCallback

fitToViewport()

fitToViewport(bound): void

Parameters
bound

Bound

Returns

void

refresh()

refresh(): void

Returns

void

render()

render(): TemplateResult<1>

Invoked on each update to perform rendering tasks. This method may return any value renderable by lit-html's ChildPart - typically a TemplateResult. Setting properties inside this method will not trigger the element to update.

Returns

TemplateResult<1>

Overrides

BlockComponent.render

isConnector()

static isConnector(element): element is ConnectorElementModel

Parameters
element

unknown

Returns

element is ConnectorElementModel

attributes
controllers
dev-mode
lifecycle
properties
rendering
styles
styles

static styles: CSSResult

Array of styles to apply to the element. The styles should be defined using the css tag function, via constructible stylesheets, or imported from native CSS module scripts.

Note on Content Security Policy:

Element styles are implemented with <style> tags when the browser doesn't support adopted StyleSheets. To use such <style> tags with the style-src CSP directive, the style-src value must either include 'unsafe-inline' or nonce-<base64-value> with <base64-value> replaced be a server-generated nonce.

To provide a nonce to use on generated <style> elements, set window.litNonce to a server-generated nonce in your page's HTML, before loading application code:

html
<script>
  // Generated and unique per request:
  window.litNonce = 'a1b2c3d4';
</script>
Nocollapse
Overrides

BlockComponent.styles

updates
firstUpdated()

firstUpdated(): void

Invoked when the element is first updated. Implement to perform one time work on the element after update.

ts
firstUpdated() {
  this.renderRoot.getElementById('my-text-area').focus();
}

Setting properties inside this method will trigger the element to update again after this update cycle completes.

Returns

void

Overrides

BlockComponent.firstUpdated


SurfaceBlockModel

Extends
Constructors
Properties
Accessors
Methods
_init()

_init(): void

Returns

void

Overrides

SurfaceBlockModel._init

getConnectors()

getConnectors(id): ConnectorElementModel[]

Parameters
id

string

Returns

ConnectorElementModel[]

getElementsByType()

getElementsByType<K>(type): SurfaceElementModelMap[K][]

Type Parameters
K

K extends keyof SurfaceElementModelMap

Parameters
type

K

Returns

SurfaceElementModelMap[K][]

Overrides

SurfaceBlockModel.getElementsByType


SurfaceBlockTransformer

Extends
Constructors
Properties
Methods
elementFromJSON()

elementFromJSON(element): YMap<unknown>

Parameters
element

Record<string, unknown>

Returns

YMap<unknown>

fromSnapshot()

fromSnapshot(payload): Promise<SnapshotNode<SurfaceBlockProps>>

Parameters
payload

FromSnapshotPayload

Returns

Promise<SnapshotNode<SurfaceBlockProps>>

Overrides

BaseBlockTransformer.fromSnapshot

toSnapshot()

toSnapshot(payload): BlockSnapshotLeaf

Parameters
payload

ToSnapshotPayload<SurfaceBlockProps>

Returns

BlockSnapshotLeaf

Overrides

BaseBlockTransformer.toSnapshot


AStarRunner

Constructors
Constructor

new AStarRunner(points, _sp, _ep, _originalSp, _originalEp, blocks, expandBlocks): AStarRunner

Parameters
points

IVec3[]

_sp

IVec3

_ep

IVec3

_originalSp

IVec3

_originalEp

IVec3

blocks

Bound[] = []

expandBlocks

Bound[] = []

Returns

AStarRunner

Accessors
path
Get Signature

get path(): IVec3[]

Returns

IVec3[]

Methods
reset()

reset(): void

Returns

void

run()

run(): void

Returns

void

step()

step(): void

Returns

void


RoughCanvas

Constructors
Constructor

new RoughCanvas(canvas, config?): RoughCanvas

Parameters
canvas

HTMLCanvasElement

config?

Config

Returns

RoughCanvas

Accessors
generator
Get Signature

get generator(): RoughGenerator

Returns

RoughGenerator

Methods
arc()

arc(x, y, width, height, start, stop, closed, options?): Drawable

Parameters
x

number

y

number

width

number

height

number

start

number

stop

number

closed

boolean = false

options?

Options

Returns

Drawable

circle()

circle(x, y, diameter, options?): Drawable

Parameters
x

number

y

number

diameter

number

options?

Options

Returns

Drawable

curve()

curve(points, options?): Drawable

Parameters
points

Point[]

options?

Options

Returns

Drawable

draw()

draw(drawable): void

Parameters
drawable

Drawable

Returns

void

ellipse()

ellipse(x, y, width, height, options?): Drawable

Parameters
x

number

y

number

width

number

height

number

options?

Options

Returns

Drawable

getDefaultOptions()

getDefaultOptions(): ResolvedOptions

Returns

ResolvedOptions

line()

line(x1, y1, x2, y2, options?): Drawable

Parameters
x1

number

y1

number

x2

number

y2

number

options?

Options

Returns

Drawable

linearPath()

linearPath(points, options?): Drawable

Parameters
points

Point[]

options?

Options

Returns

Drawable

path()

path(d, options?): Drawable

Parameters
d

string

options?

Options

Returns

Drawable

polygon()

polygon(points, options?): Drawable

Parameters
points

Point[]

options?

Options

Returns

Drawable

rectangle()

rectangle(x, y, width, height, options?): Drawable

Parameters
x

number

y

number

width

number

height

number

options?

Options

Returns

Drawable


abstract SurfaceElementModel<Props>

All the model that can be rendered in graphics mode should implement this interface.

Extended by
Type Parameters
Props

Props extends BaseElementProps = BaseElementProps

Implements
Constructors
Constructor

new SurfaceElementModel<Props>(options): SurfaceElementModel<Props>

Parameters
options
id

string

model

SurfaceBlockModel

onChange

(payload) => void

stashedStore

Map<unknown, unknown>

yMap

YMap<unknown>

Returns

SurfaceElementModel<Props>

Properties
_disposable

protected _disposable: DisposableGroup

_id

protected _id: string

_local

protected _local: Map<string | symbol, unknown>

_onChange()

protected _onChange: (payload) => void

Parameters
payload
local

boolean

oldValues

Record<string, unknown>

props

Record<string, unknown>

Returns

void

_preserved

protected _preserved: Map<string, unknown>

Used to store a copy of data in the yMap.

_stashed

protected _stashed: Map<string | keyof Props, unknown>

propsUpdated

propsUpdated: Subject<{ key: string; }>

rotate

abstract rotate: number

Implementation of

GfxCompatibleInterface.rotate

surface

surface: SurfaceBlockModel

xywh

abstract xywh: `[${number},${number},${number},${number}]`

Implementation of

GfxCompatibleInterface.xywh

yMap

yMap: YMap<unknown>

Accessors
comments
connectable
Get Signature

get connectable(): boolean

Returns

boolean

deserializedXYWH
Get Signature

get deserializedXYWH(): XYWH

Returns

XYWH

Implementation of

GfxCompatibleInterface.deserializedXYWH

display
elementBound
Get Signature

get elementBound(): Bound

The bound of the element after rotation. The bound without rotation should be created by Bound.deserialize(this.xywh).

Returns

Bound

The bound of the element without considering the response extension.

Implementation of

GfxCompatibleInterface.elementBound

externalBound
Get Signature

get externalBound(): Bound | null

Returns

Bound | null

externalXYWH

In some cases, you need to draw something related to the element, but it does not belong to the element itself. And it is also interactive, you can select element by clicking on it. E.g. the title of the group element. In this case, we need to store this kind of external xywh in order to do hit test. This property should not be synced to the doc. This property should be updated every time it gets rendered.

group
Get Signature

get group(): GfxGroupModel | null

Returns

GfxGroupModel | null

Implementation of

GfxCompatibleInterface.group

groups
Get Signature

get groups(): GfxGroupModel[]

Return the ancestor elements in order from the most recent to the earliest.

Returns

GfxGroupModel[]

Implementation of

GfxCompatibleInterface.groups

h
Get Signature

get h(): number

Returns

number

Implementation of

GfxCompatibleInterface.h

hidden
id
Get Signature

get id(): string

Returns

string

index
Implementation of

GfxCompatibleInterface.index

isConnected
Get Signature

get isConnected(): boolean

Returns

boolean

lockedBySelf

Indicates whether the current block is explicitly locked by self. For checking the lock status of the element, use isLocked instead. For (un)locking the element, use (un)lock instead.

Implementation of

GfxCompatibleInterface.lockedBySelf

opacity
responseBound
Get Signature

get responseBound(): Bound

The bound of the element considering the response extension.

Returns

Bound

The bound of the element considering the response extension.

Implementation of

GfxCompatibleInterface.responseBound

responseExtension

Defines the extension of the response area beyond the element's bounding box. This tuple specifies the horizontal and vertical margins to be added to the element's bound.

The first value represents the horizontal extension (added to both left and right sides), and the second value represents the vertical extension (added to both top and bottom sides).

The response area is computed as: [x - horizontal, y - vertical, w + 2 * horizontal, h + 2 * vertical].

Example:

  • xywh: [0, 0, 100, 100], responseExtension: [10, 20] Resulting response area: [-10, -20, 120, 140].
  • responseExtension: [0, 0] keeps the response area equal to the bounding box.
Implementation of

GfxCompatibleInterface.responseExtension

seed
type
Get Signature

get abstract type(): string

Returns

string

w
Get Signature

get w(): number

Returns

number

Implementation of

GfxCompatibleInterface.w

x
Get Signature

get x(): number

Returns

number

Implementation of

GfxCompatibleInterface.x

y
Get Signature

get y(): number

Returns

number

Implementation of

GfxCompatibleInterface.y

Methods
containsBound()

containsBound(bounds): boolean

Parameters
bounds

Bound

Returns

boolean

Implementation of

GfxCompatibleInterface.containsBound

getLineIntersections()

getLineIntersections(start, end): PointLocation[] | null

Parameters
start

IVec

end

IVec

Returns

PointLocation[] | null

Implementation of

GfxCompatibleInterface.getLineIntersections

getNearestPoint()

getNearestPoint(point): IVec

Parameters
point

IVec

Returns

IVec

Implementation of

GfxCompatibleInterface.getNearestPoint

getRelativePointLocation()

getRelativePointLocation(relativePoint): PointLocation

Parameters
relativePoint

IVec

Returns

PointLocation

Implementation of

GfxCompatibleInterface.getRelativePointLocation

includesPoint()

includesPoint(x, y, opt, __): boolean

Parameters
x

number

y

number

opt

PointTestOptions

__

EditorHost

Returns

boolean

Implementation of

GfxCompatibleInterface.includesPoint

intersectsBound()

intersectsBound(bound): boolean

Parameters
bound

Bound

Returns

boolean

Implementation of

GfxCompatibleInterface.intersectsBound

isLocked()

isLocked(): boolean

Check if the element is locked. It will check the lock status of the element and its ancestors.

Returns

boolean

Implementation of

GfxCompatibleInterface.isLocked

isLockedByAncestor()

isLockedByAncestor(): boolean

Returns

boolean

Implementation of

GfxCompatibleInterface.isLockedByAncestor

isLockedBySelf()

isLockedBySelf(): boolean

Returns

boolean

Implementation of

GfxCompatibleInterface.isLockedBySelf

lock()

lock(): void

Returns

void

Implementation of

GfxCompatibleInterface.lock

onCreated()

onCreated(): void

Returns

void

onDestroyed()

onDestroyed(): void

Returns

void

pop()

pop(prop): void

Parameters
prop

string | keyof Props

Returns

void

serialize()

serialize(): SerializedElement

Returns

SerializedElement

stash()

stash(prop): void

Parameters
prop

string | keyof Props

Returns

void

unlock()

unlock(): void

Returns

void

Implementation of

GfxCompatibleInterface.unlock


abstract SurfaceGroupLikeModel<Props>

GfxGroupCompatibleElement is a model that can contain other models. It just like a group that in common graphic software.

Extends
Type Parameters
Props

Props extends BaseElementProps = BaseElementProps

Implements
Constructors
Properties
[gfxGroupCompatibleSymbol]

[gfxGroupCompatibleSymbol]: true

Implementation of

GfxGroupCompatibleInterface.[gfxGroupCompatibleSymbol]

children

abstract children: YMap<any>

Accessors
childElements
Get Signature

get childElements(): GfxModel[]

All child element models of this container. Note that the childElements may not contains all the children in childIds, because some children may not be loaded.

Returns

GfxModel[]

All child element models of this container. Note that the childElements may not contains all the children in childIds, because some children may not be loaded.

Implementation of

GfxGroupCompatibleInterface.childElements

childIds
Get Signature

get childIds(): string[]

The ids of the children. Its role is to provide a unique way to access the children. You should update this field through setChildIds when the children are added or removed.

Returns

string[]

All child ids of this container.

Implementation of

GfxGroupCompatibleInterface.childIds

descendantElements
Get Signature

get descendantElements(): GfxModel[]

Returns

GfxModel[]

Implementation of

GfxGroupCompatibleInterface.descendantElements

xywh
Get Signature

get xywh(): `[${number},${number},${number},${number}]`

Returns

`[${number},${number},${number},${number}]`

Set Signature

set xywh(_): void

Parameters
_

`[${number},${number},${number},${number}]`

Returns

void

Implementation of

GfxGroupCompatibleInterface.xywh

Overrides

SurfaceElementModel.xywh

Methods
_getXYWH()

protected _getXYWH(): Bound

Returns

Bound

addChild()

abstract addChild(element): void

Parameters
element

GfxModel

Returns

void

Implementation of

GfxGroupCompatibleInterface.addChild

hasChild()

hasChild(element): boolean

The actual field that stores the children of the group. It should be a ymap decorated with @field.

Parameters
element

GfxCompatibleInterface

Returns

boolean

Implementation of

GfxGroupCompatibleInterface.hasChild

hasDescendant()

hasDescendant(element): boolean

Check if the group has the given descendant.

Parameters
element

GfxCompatibleInterface

Returns

boolean

Implementation of

GfxGroupCompatibleInterface.hasDescendant

invalidateXYWH()

invalidateXYWH(): void

Returns

void

refreshXYWH()

refreshXYWH(local): void

Parameters
local

boolean

Returns

void

removeChild()

abstract removeChild(element): void

Remove the child from the group

Parameters
element

GfxCompatibleInterface

Returns

void

Implementation of

GfxGroupCompatibleInterface.removeChild

setChildIds()

setChildIds(value, fromLocal): void

Set the new value of the childIds

Parameters
value

string[]

the new value of the childIds

fromLocal

boolean

if true, the change is happened in the local

Returns

void

Interfaces

IModelCoord

Properties

x

x: number

y

y: number


Options

Properties

bowing?

optional bowing: number

curveFitting?

optional curveFitting: number

curveStepCount?

optional curveStepCount: number

curveTightness?

optional curveTightness: number

dashGap?

optional dashGap: number

dashOffset?

optional dashOffset: number

disableMultiStroke?

optional disableMultiStroke: boolean

disableMultiStrokeFill?

optional disableMultiStrokeFill: boolean

fill?

optional fill: string

fillLineDash?

optional fillLineDash: number[]

fillLineDashOffset?

optional fillLineDashOffset: number

fillStyle?

optional fillStyle: string

fillWeight?

optional fillWeight: number

fixedDecimalPlaceDigits?

optional fixedDecimalPlaceDigits: number

hachureAngle?

optional hachureAngle: number

hachureGap?

optional hachureGap: number

maxRandomnessOffset?

optional maxRandomnessOffset: number

preserveVertices?

optional preserveVertices: boolean

roughness?

optional roughness: number

seed?

optional seed: number

simplification?

optional simplification: number

stroke?

optional stroke: string

strokeLineDash?

optional strokeLineDash: number[]

strokeLineDashOffset?

optional strokeLineDashOffset: number

strokeWidth?

optional strokeWidth: number

zigzagOffset?

optional zigzagOffset: number


SurfaceContext

Properties

host

host: EditorHost

selection

selection: object

selectedIds

selectedIds: string[]

slots

slots: object

slots.updated

slots.updated: Subject<SurfaceSelection[]>

viewport

viewport: Viewport

Type Aliases

CanvasElementWithText

CanvasElementWithText = ShapeElementModel | TextElementModel


ClipboardConfigCreationContext

ClipboardConfigCreationContext = object

Properties

newPresentationIndexes

newPresentationIndexes: Map<string, string>

frame old id to new presentation index

oldToNewIdMap

oldToNewIdMap: Map<string, string>

element old id to new id

originalIndexes

originalIndexes: Map<string, string>

element old id to new layer index


ElementRenderer()<T>

ElementRenderer<T> = (model, ctx, matrix, renderer, rc, viewportBound) => void

Type Parameters

T

T extends SurfaceElementModel | GfxLocalElementModel = SurfaceElementModel

Parameters

model

T

ctx

CanvasRenderingContext2D

matrix

DOMMatrix

renderer

CanvasRenderer

rc

RoughCanvas

viewportBound

IBound

Returns

void


ElementToMarkdownAdapterMatcher

ElementToMarkdownAdapterMatcher = ElementModelMatcher<MarkdownAST>


ElementToPlainTextAdapterMatcher

ElementToPlainTextAdapterMatcher = ElementModelMatcher<TextBuffer>


SurfaceMiddleware()

SurfaceMiddleware = (surface) => () => void

Parameters

surface

SurfaceBlockModel

Returns

(): void

Returns

void

Variables

autoArrangeElementsCommand

const autoArrangeElementsCommand: Command

Automatically arrange elements according to fixed row and column rules


autoResizeElementsCommand

const autoResizeElementsCommand: Command

Adjust the height of the selected element to a fixed value and arrange the elements


DEFAULT_CENTRAL_AREA_RATIO

const DEFAULT_CENTRAL_AREA_RATIO: 0.3 = 0.3


DEFAULT_NOTE_OFFSET_X

const DEFAULT_NOTE_OFFSET_X: 30 = 30


DEFAULT_NOTE_OFFSET_Y

const DEFAULT_NOTE_OFFSET_Y: 40 = 40


EdgelessClipboardConfigIdentifier

const EdgelessClipboardConfigIdentifier: ServiceIdentifier<EdgelessClipboardConfig> & <U>(variant) => ServiceIdentifier<U>


EdgelessCRUDIdentifier

const EdgelessCRUDIdentifier: ServiceIdentifier<EdgelessCRUDExtension> & <U>(variant) => ServiceIdentifier<U>


EdgelessLegacySlotExtension

const EdgelessLegacySlotExtension: ExtensionType


EdgelessLegacySlotIdentifier

const EdgelessLegacySlotIdentifier: ServiceIdentifier<{ elementResizeEnd: Subject<void>; elementResizeStart: Subject<void>; fullScreenToggled: Subject<void>; navigatorFrameChanged: Subject<FrameBlockModel>; navigatorSettingUpdated: Subject<{ blackBackground?: boolean; fillScreen?: boolean; hideToolbar?: boolean; }>; readonlyUpdated: Subject<boolean>; toggleNoteSlicer: Subject<void>; toolbarLocked: Subject<boolean>; }> & <U>(variant) => ServiceIdentifier<U>


EdgelessSurfaceBlockAdapterExtensions

const EdgelessSurfaceBlockAdapterExtensions: (ExtensionType & object | ExtensionType & object)[]


ElementRendererIdentifier

const ElementRendererIdentifier: ServiceIdentifier<unknown> & <U>(variant) => ServiceIdentifier<U>


ElementToMarkdownAdapterMatcherIdentifier

const ElementToMarkdownAdapterMatcherIdentifier: ServiceIdentifier<ElementToMarkdownAdapterMatcher> & <U>(variant) => ServiceIdentifier<U>


ElementToPlainTextAdapterMatcherIdentifier

const ElementToPlainTextAdapterMatcherIdentifier: ServiceIdentifier<ElementToPlainTextAdapterMatcher> & <U>(variant) => ServiceIdentifier<U>


EXCLUDING_MOUSE_OUT_CLASS_LIST

const EXCLUDING_MOUSE_OUT_CLASS_LIST: string[]


ExportManagerExtension

const ExportManagerExtension: ExtensionType


GRID_GAP_MAX

const GRID_GAP_MAX: 50 = 50


GRID_GAP_MIN

const GRID_GAP_MIN: 10 = 10


GRID_SIZE

const GRID_SIZE: 3000 = 3000


OverlayIdentifier

const OverlayIdentifier: ServiceIdentifier<Overlay> & <U>(variant) => ServiceIdentifier<U>


reassociateConnectorsCommand

const reassociateConnectorsCommand: Command<{ newId: string; oldId: string; }>

Re-associate bindings for block that have been converted.

Param

the old block id

Param

the new block id


SurfaceBlockAdapterExtensions

const SurfaceBlockAdapterExtensions: (ExtensionType & object | ExtensionType & object)[]


SurfaceBlockSchema

const SurfaceBlockSchema: object

Type Declaration

model

model: object & object

Type Declaration
flavour

flavour: "affine:surface"

props

props: PropsGetter<SurfaceBlockProps>

Type Declaration
children

children: string[]

parent

parent: string[]

role

role: "hub" = 'hub'

version

version: number = 5

transformer()?

optional transformer: (transformerConfig) => SurfaceBlockTransformer

Parameters
transformerConfig

Map<string, unknown>

Returns

SurfaceBlockTransformer

version

version: number


SurfaceBlockSchemaExtension

const SurfaceBlockSchemaExtension: ExtensionType


surfaceMiddlewareIdentifier

const surfaceMiddlewareIdentifier: ServiceIdentifier<{ middleware: SurfaceMiddleware; }> & <U>(variant) => ServiceIdentifier<U>


TextUtils

const TextUtils: object

Type Declaration

getFontFaces()

getFontFaces: () => FontFace[]

Returns

FontFace[]

getFontFacesByFontFamily()

getFontFacesByFontFamily: (fontFamily) => FontFace[]

Parameters
fontFamily

string

Returns

FontFace[]

isSameFontFamily()

isSameFontFamily: (fontFamily) => (fontFace) => boolean

Parameters
fontFamily

string

Returns

(fontFace): boolean

Parameters
fontFace

FontFace

Returns

boolean

wrapFontFamily()

wrapFontFamily: (fontFamily) => string

Parameters
fontFamily

string

Returns

string


ZOOM_INITIAL

const ZOOM_INITIAL: 1 = 1.0


ZOOM_MAX

const ZOOM_MAX: 6 = 6.0


ZOOM_MIN

const ZOOM_MIN: 0.1 = 0.1


ZOOM_STEP

const ZOOM_STEP: 0.25 = 0.25


ZOOM_WHEEL_STEP

const ZOOM_WHEEL_STEP: 0.1 = 0.1

Functions

DomElementRendererExtension()

DomElementRendererExtension<T>(elementType, implementation): ExtensionType

Creates an extension for registering a DomElementRenderer for a specific element type.

Type Parameters

T

T extends SurfaceElementModel<BaseElementProps> = SurfaceElementModel<BaseElementProps>

Parameters

elementType

string

The type of the surface element (e.g., 'shape', 'text') for which this renderer is.

implementation

DomElementRenderer<T>

The DomElementRenderer function that handles rendering for this element type.

Returns

ExtensionType

An ExtensionType object that can be used to set up the renderer in the DI container.


ElementRendererExtension()

ElementRendererExtension<T>(id, renderer): ExtensionType & object

Type Parameters

T

T extends SurfaceElementModel<BaseElementProps> | GfxLocalElementModel

Parameters

id

string

renderer

ElementRenderer<T>

Returns

ExtensionType & object


ElementToMarkdownAdapterExtension()

ElementToMarkdownAdapterExtension(matcher): ExtensionType & object

Parameters

matcher

ElementToMarkdownAdapterMatcher

Returns

ExtensionType & object


ElementToPlainTextAdapterExtension()

ElementToPlainTextAdapterExtension(matcher): ExtensionType & object

Parameters

matcher

ElementToPlainTextAdapterMatcher

Returns

ExtensionType & object


generateElementId()

generateElementId(): string

Returns

string


getBgGridGap()

getBgGridGap(zoom): number

Parameters

zoom

number

Returns

number


getLastPropsKey()

getLastPropsKey(modelType, modelProps): "brush" | "connector" | "mindmap" | "text" | "highlighter" | "affine:frame" | "affine:edgeless-text" | "affine:note" | "shape:diamond" | "shape:ellipse" | "shape:rect" | "shape:triangle" | "shape:roundedRect" | null

Parameters

modelType

string

modelProps

Partial<{ color: string | { normal: string; } | { dark: string; light: string; }; lineWidth: LineWidth; } | { frontEndpointStyle: PointStyle; labelStyle: { color: string | { normal: string; } | { dark: string; light: string; }; fontFamily: FontFamily; fontSize: number; fontStyle: FontStyle; fontWeight: FontWeight; textAlign: TextAlign; }; mode: ConnectorMode; rearEndpointStyle: PointStyle; rough: boolean; stroke: string | { normal: string; } | { dark: string; light: string; }; strokeStyle: StrokeStyle; strokeWidth: LineWidth; } | { layoutType: LayoutType; style: MindmapStyle; } | { color: string | { normal: string; } | { dark: string; light: string; }; fontFamily: FontFamily; fontSize: number; fontStyle: FontStyle; fontWeight: FontWeight; textAlign: TextAlign; } | { color: string | { normal: string; } | { dark: string; light: string; }; lineWidth: number; } | { background: string | { normal: string; } | { dark: string; light: string; }; } | { color: string | { normal: string; } | { dark: string; light: string; }; fontFamily: FontFamily; fontStyle: FontStyle; fontWeight: FontWeight; textAlign: TextAlign; } | { background: string | { normal: string; } | { dark: string; light: string; }; displayMode: NoteDisplayMode; edgeless: { style: { borderRadius: number; borderSize: number; borderStyle: StrokeStyle; shadowType: NoteShadow; }; }; } | { color: string | { normal: string; } | { dark: string; light: string; }; fillColor: string | { normal: string; } | { dark: string; light: string; }; filled: boolean; fontFamily: FontFamily; fontSize: number; fontStyle: FontStyle; fontWeight: FontWeight; radius: number; roughness: number; shapeStyle: ShapeStyle; strokeColor: string | { normal: string; } | { dark: string; light: string; }; strokeStyle: StrokeStyle; strokeWidth: number; textAlign: TextAlign; textHorizontalAlign?: TextAlign; textVerticalAlign?: TextVerticalAlign; } | { color: string | { normal: string; } | { dark: string; light: string; }; fillColor: string | { normal: string; } | { dark: string; light: string; }; filled: boolean; fontFamily: FontFamily; fontSize: number; fontStyle: FontStyle; fontWeight: FontWeight; radius: number; roughness: number; shapeStyle: ShapeStyle; strokeColor: string | { normal: string; } | { dark: string; light: string; }; strokeStyle: StrokeStyle; strokeWidth: number; textAlign: TextAlign; textHorizontalAlign?: TextAlign; textVerticalAlign?: TextVerticalAlign; } | { color: string | { normal: string; } | { dark: string; light: string; }; fillColor: string | { normal: string; } | { dark: string; light: string; }; filled: boolean; fontFamily: FontFamily; fontSize: number; fontStyle: FontStyle; fontWeight: FontWeight; radius: number; roughness: number; shapeStyle: ShapeStyle; strokeColor: string | { normal: string; } | { dark: string; light: string; }; strokeStyle: StrokeStyle; strokeWidth: number; textAlign: TextAlign; textHorizontalAlign?: TextAlign; textVerticalAlign?: TextVerticalAlign; } | { color: string | { normal: string; } | { dark: string; light: string; }; fillColor: string | { normal: string; } | { dark: string; light: string; }; filled: boolean; fontFamily: FontFamily; fontSize: number; fontStyle: FontStyle; fontWeight: FontWeight; radius: number; roughness: number; shapeStyle: ShapeStyle; strokeColor: string | { normal: string; } | { dark: string; light: string; }; strokeStyle: StrokeStyle; strokeWidth: number; textAlign: TextAlign; textHorizontalAlign?: TextAlign; textVerticalAlign?: TextVerticalAlign; } | { color: string | { normal: string; } | { dark: string; light: string; }; fillColor: string | { normal: string; } | { dark: string; light: string; }; filled: boolean; fontFamily: FontFamily; fontSize: number; fontStyle: FontStyle; fontWeight: FontWeight; radius: number; roughness: number; shapeStyle: ShapeStyle; strokeColor: string | { normal: string; } | { dark: string; light: string; }; strokeStyle: StrokeStyle; strokeWidth: number; textAlign: TextAlign; textHorizontalAlign?: TextAlign; textVerticalAlign?: TextVerticalAlign; }>

Returns

"brush" | "connector" | "mindmap" | "text" | "highlighter" | "affine:frame" | "affine:edgeless-text" | "affine:note" | "shape:diamond" | "shape:ellipse" | "shape:rect" | "shape:triangle" | "shape:roundedRect" | null


getSurfaceBlock()

getSurfaceBlock(doc): SurfaceBlockModel | null

Parameters

doc

Store

Returns

SurfaceBlockModel | null


getSurfaceComponent()

getSurfaceComponent(std): SurfaceBlockComponent | null

Parameters

std

BlockStdScope

Returns

SurfaceBlockComponent | null


isConnectable()

isConnectable(element): element is Connectable

Parameters

element

GfxModel | null

Returns

element is Connectable


isNoteBlock()

isNoteBlock(element): element is NoteBlockModel

Parameters

element

GfxModel | BlockModel<object> | null

Returns

element is NoteBlockModel


normalizeWheelDeltaY()

normalizeWheelDeltaY(delta, zoom): number

Normalizes wheel delta.

See https://stackoverflow.com/a/13650579

From https://github.com/excalidraw/excalidraw/blob/master/src/components/App.tsx MIT License

Parameters

delta

number

zoom

number = 1

Returns

number


sortIndex()

sortIndex(a, b, groupIndexMap): -1 | 0 | 1

Parameters

a
id

string

index

string

b
id

string

index

string

groupIndexMap

Map<string, { id: string; index: string; }>

Returns

-1 | 0 | 1


surfaceMiddlewareExtension()

surfaceMiddlewareExtension(id, middleware): ExtensionType

Parameters

id

string

middleware

SurfaceMiddleware

Returns

ExtensionType


updateXYWH()

updateXYWH(ele, bound, updateElement, updateBlock): void

Parameters

ele

GfxModel

bound

Bound

updateElement

(id, props) => void

updateBlock

(model, callBackOrProps) => void

Returns

void