import * as wordgard_doc from 'wordgard/doc';
import { Elt, Node as Node$1, ChangeSet, Plot, Pos } from 'wordgard/doc';
import { GardState, TextblockMap, Transaction, GardSelection } from 'wordgard/state';
import { PhraseSet } from 'wordgard/phrases';
import { StyleModule, StyleSpec } from 'style-mod';
import { Command, Menu } from 'wordgard/command';
type MakeSelectionStyle = (wg: Wordgard, event: MouseEvent) => Wordgard.MouseSelectionStyle | null;
/**
A widget describes a piece of DOM content that can be used to
render a node, a part of a node, or an extra element added via a
decoration. The `Widget` object is separate from its DOM
representation. It describes how the DOM widget is to be rendered
and how it behaves, but it itself is an immutable value.
*/
declare class Widget {
/**
The parameter for this widget.
*/
readonly value: Param;
private constructor();
/**
Compare this widget to another widget object.
*/
eq(other: any): boolean;
/**
Define a widget type.
*/
static define(spec: Widget.Spec): Widget.Type;
/**
Create a singleton widget.
*/
static create(spec: Widget.Spec): Widget;
/**
This widget's type. The type mangling is a kludge to make sure
`Widget` is a subtype of `Widget`.
*/
readonly type: Widget.Type;
}
declare namespace Widget {
/**
Specifies a widget type.
*/
type Spec = {
/**
How to render the widget as DOM content.
*/
render: (value: Param, wg: Wordgard) => Element | Text;
/**
Compare the widget value for equality. Will default to `===`.
*/
eq?: (a: Param, b: Param) => boolean;
/**
Called when a widget of this type is added to an editor that
is connected to a DOM document, or an editor with the widget
in it is connected.
*/
connect?: (value: Param, dom: Element | Text) => void;
/**
Called when a widget of this type is removed from an editor
that is connected to a document, or when the editor containing
the widget is disconnected.
*/
disconnect?: (value: Param, dom: Element | Text) => void;
/**
Used to determine whether events originating from the widget's
DOM should ignored by the editor. `false` or a function that
returns `false` for the event will prevent the editor's
regular event handling for the event.
*/
propagateEvent?: boolean | ((event: Event) => boolean);
/**
Set this to false for widgets that either aren't visible or
are positioned outside of the regular document flow.
*/
inFlow?: boolean;
/**
By default, widgets are set to be ineditable. Set this to
`true` to suppress that.
*/
editable?: boolean;
};
/**
Each widget has an associated type that describes how it
behaves.
*/
class Type {
private constructor();
/**
Create an instance of this widget type.
*/
of(value: Param): Widget;
}
}
type DecoElt = Elt;
declare namespace Decoration {
/**
Node shapes can be either a widget or an element which may
contain widgets.
*/
type Shape = Widget | DecoElt;
namespace Tag {
/**
Override the way a given node type is drawn in the editor. By
default, the {@link doc.Node.Spec.shape `shape`} field in the
type's definition will be used, but extensions created with
this function can provide an alternative shape for a given
type.
When providing a function for the shape, keep in mind that the
result will be cached by tag, and you should make sure your
function is pure.
When providing a function that returns a shape that changes
whether the node is rendered as an atom, you need to provide
the `atom`.
*/
function shape>(type: T, shape: Shape | ((tag: Node$1.Tag.For) => Shape), config?: {
atom?: boolean;
}): GardState.Extension;
namespace shape {
/**
This function allows you to define a {@link Decoration.Tag.shape
custom node shape} that depends on the editor state. It will
automatically track what slots (see {@link
GardState.Facet.compute}) you use, and make sure the nodes
are redrawn when those change.
If your shape function returns a function from a tag, you
must be careful do any state access you need in the _outer_
function, not the returned function, or it won't be tracked.
You generally don't want to make your shapes depend on
constantly-changing slots like the document or selection,
because when the document is big, there's a non-trivial
amount of work involved when a node shape changes (or may
have changed).
When providing a shape for a plot that changes whether it is
rendered as an atom, provide the `atom` option.
*/
function dynamic>(// FIXME find better name?
type: T, shape: (state: GardState) => Shape | ((tag: Node$1.Tag.For) => Shape), config?: {
atom?: boolean;
}): GardState.Extension;
}
/**
Define a wrapper to be added around a given node type, or some
part of it. The given elt should include a hole (`0`) to
indicate where the original shape goes.
If a `target` option is given, and matching some element in
the node's existing shape, only that element will be wrapped.
Uses a subset of CSS selectors that supports only tag name and
class names (`img.x.y`).
*/
function wrapper(type: Node$1.Type.Ref, wrapper: DecoElt, options?: {
target?: string;
}): GardState.Extension;
/**
Add a widget to every instance of the given node type. Such
widgets can appear before or after the node, and for plots
that aren't rendered as atoms, at its start or end.
When a function, `widget` will be cached by tag, and should be
pure.
*/
function widget>(type: T, place: "before" | "after" | "start" | "end", widget: Widget | ((tag: Node$1.Tag.For) => Widget)): GardState.Extension;
namespace widget {
/**
Define a node widget decoration that depends on some aspect
of the editor state. See the notes for {@link
Decoration.Tag.shape.dynamic}.
*/
function dynamic>(type: T, place: "before" | "after" | "start" | "end", widget: (state: GardState) => Widget | ((tag: Node$1.Tag.For) => Widget)): GardState.Extension;
}
/**
Add an attribute to the representation of a given node type.
By default, the attribute is added to the outer element (or a
wrapper element if the node is rendered as a widget). If the
`target` option is given, and
[matches](#editor.Decoration.Tag.wrapper.options.target) an
element in the representation, it will be added to that
element instead.
*/
function attribute>(type: T, attr: string, value: string | ((tag: Node$1.Tag.For) => string), options?: {
target?: string;
}): GardState.Extension;
}
/**
A point decoration is a decoration that targets a given position
in the document, or the node after a given position. Sets of
point decorations can be provided as point sets through {@link
Decoration.Point.source}.
*/
abstract class Point implements PointSet.Value {
abstract eq(other: PointSet.Value): boolean;
abstract side: number;
abstract trackMode: ChangeSet.TrackMode | undefined;
/**
Display a widget at this point.
*/
static widget(widget: Widget, options?: {
/**
Determines where this widget appears relative to the cursor
(negative means before, positive after, zero means to make
it depend on the cursor's own side) and other widgets in the
same position. Defaults to zero.
*/
side?: number;
/**
What side to track when changes happen around the widget.
The default is to keep the widget around unless the content
on both sides is deleted. You can pass undefined to indicate
the widget should not be deleted by changes, or
`"before"`/`"after"` to use one specific side.
*/
trackMode?: ChangeSet.TrackMode | undefined;
}): Point;
/**
Add a set of attributes to the node after this decoration's
position.
You can target a [specific
element](#editor.Decoration.Tag.wrapper.options.target) in the
node's representation with the `target` option.
*/
static attributes(attrs: Record, options?: {
target?: string;
}): Point;
/**
Override the shape of the node after the decoration's point
with the given one.
*/
static shape(shape: Shape): Point;
/**
Wrap the node, or inner node selected with `target`, at the
given position with a wrapper.
*/
static wrapper(wrapper: DecoElt, spec?: {
target?: string;
}): Point;
/**
The facet used to register a point decoration source.
Functions provided in this way will be called on every editor
update, so computing the set on the fly will only perform well
for very simple decoration sets, and you'll usually want to
keep your set in a state field and update it incrementally.
*/
static source: GardState.Facet<(state: GardState) => PointSet, readonly ((state: GardState) => PointSet)[]>;
}
/**
Range decorations apply to a document range. They are stored in
{@link RangeSet}s and registered in an editor configuration with
{@link Decoration.Range.source}.
*/
abstract class Range implements RangeSet.Value {
/**
@hidden
*/
protected constructor(spec: Decoration.Range.Spec);
get inclusiveStart(): boolean;
get inclusiveEnd(): boolean;
abstract eq(other: RangeSet.Value): boolean;
/**
Create a range decoration that wraps nodes in a range with
an element, using the given tag name.
*/
static wrapper(tagName: string, spec: Decoration.Range.WrapperSpec): Range;
/**
Create a range decoration that adds an attribute to nodes in a
range.
*/
static attribute(attr: string, value: string, options?: Decoration.Range.Spec): Range;
/**
The facet used to register range decoration sources. The
source function will be called on every update. Generating big
range sets on the fly will not perform well, so you'll often
want to store these in a state field.
*/
static source: GardState.Facet<(state: GardState) => RangeSet, readonly ((state: GardState) => RangeSet)[]>;
}
namespace Range {
/**
Configuration object for range decorations.
*/
interface Spec {
/**
Determines whether content inserted next to the range is
included when mapping the range through a change. Defaults
to false.
*/
inclusive?: boolean | "start" | "end";
/**
If given, apply this decoration only to matching nodes.
*/
query?: Node$1.Query;
/**
The type of nodes in the range to apply the decoration to.
Defaults to `"atom"`.
*/
scope?: "atom" | "inlineatom" | "all";
}
/**
Configuration object for wrapper range decorations.
*/
interface WrapperSpec extends Decoration.Range.Spec {
/**
Attributes to add to the wrapper element.
*/
attributes?: Record;
/**
A wrapper's rank determines the nesting order between it and
other wrappers created by range decorations or marks. Should be
a number between 0 and 100, if given.
*/
rank?: number;
/**
Whether this wrapper may span multiple sibling nodes.
Non-spanning wrappers will be created separately for each
node. Defaults to true.
*/
spanning?: boolean;
}
}
}
/**
Data structure used to store sets of points and then track them
across document changes. Mostly used for {@link Decoration.Point
point decorations}, but can also track your own types, if you make
sure they implement the {@link PointSet.Value} interface.
*/
declare class PointSet {
/**
The values in this set.
*/
readonly values: readonly T[];
/**
The positions of the values in this set.
*/
readonly positions: readonly number[];
private constructor();
/**
The number of points in this set.
*/
get length(): number;
/**
Adjust the points for a set of document changes. Returns a new
set with the adjusted points. May delete points when the content
around them was deleted.
*/
map(changes: ChangeSet, start?: number): PointSet;
/**
Returns the union of this set and the given set. If
`maskFrom`/`maskTo` are given, drop any points from `this`
between or at those positions.
*/
merge(other: PointSet, maskFrom?: number, maskTo?: number | undefined): PointSet;
/**
Get the value at the given position, if any. If there's multiple
values at that position, the one with the lowest side is
returned.
*/
at(pos: number): T | undefined;
/**
Create a point set from an iterable of `[position, value]`
tuples, or a function that calls its argument for every point to
add.
*/
static create(source: Iterable<[number, T]> | ((add: (pos: number, value: T) => void) => void)): PointSet;
/**
The empty point set.
*/
static empty: PointSet;
}
declare namespace PointSet {
/**
Objects stored in a point set must conform to this interface.
*/
interface Value {
/**
The side of the point. Used to provide a sorting of points at
the same position
*/
side: number;
/**
Specifies whether the point should be deleted when content
next to it is deleted. See {@link ChangeSet.mapPos}.
*/
trackMode: ChangeSet.TrackMode | undefined;
/**
Method to compare this value to another.
*/
eq(other: PointSet.Value): boolean;
}
}
/**
Data structure that stores sets of ranges, for use with {@link
Decoration.Range range decorations} or other data types
implementing {@link RangeSet.Value}.
*/
declare class RangeSet {
/**
The value associated with the ranges in the set.
*/
readonly values: readonly T[];
/**
The start positions of the ranges in this set.
*/
readonly from: readonly number[];
/**
The end positions of the ranges.
*/
readonly to: readonly number[];
private constructor();
/**
The number of ranges stored in this set.
*/
get length(): number;
/**
Adjust the positions of the ranges for the given change set.
Returns a set with the updated ranges.
*/
map(changes: ChangeSet, start?: number): RangeSet;
/**
Merge this set with another set. If `maskFrom`/`maskTo` are
given, any ranges overlapping the masked range in `this` are
not included in the merged set.
*/
merge(other: RangeSet, maskFrom?: number, maskTo?: number | undefined): RangeSet;
/**
Create a range set from an iterable of `[from, to, value]`
tuples, or a function that calls its argument for every range to
add.
*/
static create(source: Iterable<[number, number, T]> | ((add: (from: number, to: number, value: T) => void) => void)): RangeSet;
/**
The empty range set.
*/
static empty: RangeSet;
}
declare namespace RangeSet {
/**
Values stored in a range set must conform to this interface.
*/
interface Value {
/**
Whether content inserted at the start of this value's range is
included in the range.
*/
inclusiveStart: boolean;
/**
Whether content inserted at the end is included.
*/
inclusiveEnd: boolean;
/**
Compare this value to another.
*/
eq(other: Value): boolean;
}
}
declare const enum TileFlag {
None = 0,
NodeInner = 1,
PlotContent = 2,
Spanning = 4,
Wrapper = 8,
Point = 16,
PointBefore = 32,
PointAfter = 64,
PointSide = 96,
Composition = 128,
Synced = 256,// Node has been synced. DOM content matches child list / text content, child array becomes read-only
Atom = 512,// Composite tile whose length isn't determined by child length
HasContent = 1024,// EltTile whose elt has a content hole
AfterContent = 2048,// Tiles that sit after their parent's content position
ContentNotLast = 4096,// EltTile that has children with AfterContent flag
Dirty = 8192
}
declare const enum Orientation {
Row = 0,
Col = 1
}
declare class CoordPos {
readonly pos: number;
readonly target: number | null;
readonly side: -1 | 1;
readonly vertOutside: boolean;
constructor(pos: number, target: number | null, side: -1 | 1, vertOutside: boolean);
map(mapping: ChangeSet): CoordPos;
static create(pos: number, side: -1 | 1, target?: number | null, vertOutside?: boolean): CoordPos;
}
declare abstract class Tile {
dom: Element | Text;
parent: CompositeTile | null;
abstract children: Tile[];
length: number;
flags: TileFlag;
constructor(dom: Element | Text, flags: number);
get isAtom(): boolean;
get isNodeOuter(): boolean;
get isNodeInner(): boolean;
get isNode(): boolean;
get isPlotContent(): boolean;
get isText(): boolean;
get isDoc(): boolean;
get isWrapper(): boolean;
get isSpanning(): boolean;
get isComposition(): boolean;
get isPoint(): boolean;
get node(): Node$1 | null;
posBeforeChild(child: Tile, ownStart?: number): number;
get posBefore(): number;
get posAtStart(): number;
get posAfter(): number;
get posAtEnd(): number;
get boundary(): 0 | 1;
get firstChild(): Tile | null;
get lastChild(): Tile | null;
get nodeParent(): Tile;
ignoreEvent(event: Event): boolean;
get ignoreMutations(): boolean;
toString(): string;
abstract sync(): void;
connect(): void;
disconnect(reused?: Map): void;
nearestNode(): Tile;
markDirty(): void;
posAtCoords(state: GardState, x: number, y: number): CoordPos;
abstract posAtCoordsInner(start: number, state: GardState, x: number, y: number, textblock: TextblockMap | null, orientation: Orientation): CoordPos;
static get(node: DOMNode): Tile | undefined;
}
declare class CompositeTile extends Tile {
children: Tile[];
dom: Element;
addChild(child: Tile): void;
sync(): void;
syncChildren(): void;
posAtCoordsInner(start: number, state: GardState, x: number, y: number, textblock: TextblockMap | null, orientation: Orientation): CoordPos;
posAtCoordsRow(start: number, state: GardState, x: number, y: number, textblock: TextblockMap | null): CoordPos | null;
posAtCoordsCol(start: number, state: GardState, x: number, y: number, textblock: TextblockMap | null): CoordPos;
}
declare const enum Reused {
Full = 1,
DOM = 2
}
type DOMNode = Node;
declare global {
interface Node {
wgTile?: Tile;
}
}
/**
This class implements the editor's user interface. It wraps the
editable DOM surface and possibly other elements such as panels.
*/
declare class Wordgard {
/**
Construct a new editor. You'll want to either provide a `parent`
option, or put the editor's {@link Wordgard.dom DOM element}
into your document after creating an editor, so that the user
can see it.
*/
static create(spec: Wordgard.Spec): Wordgard;
/**
The current editor state.
*/
get state(): GardState;
/**
Indicates whether the user is currently composing text via
[IME](https://en.wikipedia.org/wiki/Input_method), and at least
one change has been made in the current composition.
*/
get composing(): boolean;
/**
Indicates whether the user is currently in composing state. Note
that on some platforms, like Android, this will be the case a
lot, since just putting the cursor on a word starts a
composition there.
*/
get compositionStarted(): boolean | null;
/**
Queries whether the editor's DOM is {@link Wordgard#editable
editable}.
*/
get editable(): boolean;
/**
Returns true if the editor can be focused (is {@link
Wordgard.editable editable} or has a tabindex).
*/
get focusable(): boolean;
/**
The document or shadow root that the editor lives in.
*/
root: DocumentOrShadowRoot;
/**
The outer DOM element that represents the editor.
*/
readonly dom: HTMLElement;
/**
The DOM element that can be styled to scroll. (Note that it may
not have been, so you can't assume this is scrollable.)
*/
readonly scrollDOM: HTMLElement;
/**
The editable DOM element holding the editor content. You should
not, usually, interact with this content directly though the
DOM, since the editor will immediately undo most of the changes
you make. Instead, {@link Wordgard.dispatch dispatch} {@link
Transaction transactions} to modify content, and {@link
Decoration decorations} to style it.
*/
readonly contentDOM: HTMLElement;
private announceDOM;
private id;
private pluginMap;
private editorAttrs;
private contentAttrs;
private styleModules;
/**
True when the editor is connected to a DOM document.
*/
connected: boolean;
private flushing;
private willFlush;
private flushFunc;
private autoColorScheme;
private domReaders;
private domWriters;
private pendingTransactionListeners;
private constructor();
/**
All editor state updates go through this. It takes a transaction
or transaction spec and updates the editor to show the new state
produced by that transaction. This function is bound to the editor
instance, so it does not have to be called as a method.
Will apply {@link Transaction.appender transaction appenders}
and include any extra transactions they produce in the editor's
state.
Updates will be immediately be reflected in the object's `state`
property, but updating the DOM will be deferred to the next
display update.
*/
dispatch(tr: Transaction | Transaction.Spec): void;
/**
Force a flush on the editor content, updating its DOM
representation for any pending changes.
*/
flush(): void;
private scrollTo;
private runUpdate;
private updatePlugins;
private updateAttrs;
private checkDir;
private showAnnouncements;
private mountStyles;
/**
Schedule a function that needs to read from the (flushed) DOM.
During an editor update, when doing anything that needs to
access the DOM layout, it is important to schedule it with this
method, to avoid forcing unnecessary DOM layouts.
*/
scheduleDOMRead(read: (wg: Wordgard) => void): void;
/**
Schedule a function that needs to modify the DOM. When doing any
kind of DOM mutation that depends on a {@link
Wordgard.scheduleDOMRead | DOM read}, use this method, so that
read and write phases remain separate.
*/
scheduleDOMWrite(write: (wg: Wordgard) => void): void;
/**
Get the value of a specific plugin, if present. Note that
plugins that crash can be dropped from an editor, so even when
you know you registered a given plugin, it is recommended to
check the return value of this method.
*/
plugin(plugin: Wordgard.Plugin): T | null;
private ensureFlushed;
/**
Find the position at the end or start of the (wrapped) line. If
the given position isn't in a textblock, this will return null.
*/
moveToLineBoundary(start: GardSelection, forward: boolean): GardSelection.Text | null;
/**
Move a cursor position vertically. When `distance` isn't given,
it defaults to moving to the vertical element below or above the
start position. Otherwise, `distance` should provide a positive
distance in pixels.
When `start` has a
{@link GardSelection.goalColumn `goalColumn`}, the vertical
motion will use that as a target horizontal position. Otherwise,
the cursor's own horizontal position is used. The returned
cursor will have its goal column set to whichever column was
used. If `allowNode` is true, this may return a node selection
on a block node.
*/
moveVertically(start: GardSelection, forward: boolean, distance?: number, allowNode?: boolean): GardSelection | null;
/**
Find the DOM parent node and offset (child offset if `node` is
an element, character offset when it is a text node) at the
given document position.
*/
domAtPos(pos: number, assoc?: -1 | 1): {
node: DOMNode;
offset: number;
};
/**
Get the DOM element for the node at the given position, if any.
*/
nodeDOM(pos: number): Element | null;
/**
Find the document position at the given DOM node. Can be useful
for associating positions with DOM events. Will raise an error
when `node` isn't part of the editor content.
*/
posAtDOM(node: DOMNode, offset?: number): number;
/**
Find the Wordgard node represented by the given DOM node, or one
of its parent nodes, if any. Will not return the outer document node.
*/
nodeFromDOM(node: Element): {
pos: number;
node: Node$1;
} | null;
/**
Get the document position at the given screen coordinates.
*/
posAtCoords(coords: {
x: number;
y: number;
}): {
pos: number;
side: -1 | 1;
target: number | null;
};
/**
Get the screen coordinates at the given document position.
`side` determines whether the coordinates are based on the
element before (-1) or after (1) the position (if no element is
available on the given side, the method will transparently use
another strategy to get reasonable coordinates).
*/
coordsAtPos(pos: number, assoc?: -1 | 1): DOMRect;
/**
Return the rectangle around a given node or character. If there
is no element directly after `pos`, this will return null. For
space characters that are a line wrap point, this will return
the position before the line break.
*/
coordsForElement(pos: number): DOMRect | null;
/**
Check whether the editor has focus.
*/
get hasFocus(): boolean;
/**
Put focus on the editor.
*/
focus(): void;
/**
Get the CSS classes for the currently active editor themes.
*/
get themeClasses(): string;
/**
Returns an effect that can be {@link Transaction.Spec.effects
added} to a transaction to cause it to scroll the given position
or range into view.
*/
static scrollIntoView(pos: number | GardSelection, options?: Wordgard.ScrollSpec): Transaction.Effect;
/**
Add an
[`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Reference/Attributes/aria-label)
attribute to the editable element holding the given string or
phrase.
*/
static label(label: string | PhraseSet.Ref): GardState.Extension;
/**
Filter functions provided through this facet will be run on a
slice before it is serialized to the clipboard.
*/
static clipboardOutputFilter: GardState.Facet<(content: wordgard_doc.Slice, state: GardState) => wordgard_doc.Slice, readonly ((content: wordgard_doc.Slice, state: GardState) => wordgard_doc.Slice)[]>;
/**
Filter functions provided through this facet will be run on an
HTML string before it put onto the clipboard.
*/
static clipboardOutputHTMLFilter: GardState.Facet<(html: string, state: GardState) => string, readonly ((html: string, state: GardState) => string)[]>;
/**
This can be used to provide a function that converts a document
slice to a string that is put onto the plain-text clipboard.
Serializers are tried in order of precedence until one returns
a string.
*/
static clipboardTextSerializer: GardState.Facet<(slice: wordgard_doc.Slice, context: readonly wordgard_doc.Plot.Tag[], state: GardState) => string | null, readonly ((slice: wordgard_doc.Slice, context: readonly wordgard_doc.Plot.Tag[], state: GardState) => string | null)[]>;
/**
Filter to run on the plain text representation of content put
onto the clipboard.
*/
static clipboardOutputTextFilter: GardState.Facet<(html: string, state: GardState) => string, readonly ((html: string, state: GardState) => string)[]>;
/**
Filter functions provided through this facet will be run on a
slice after it is read from the clipboard.
*/
static clipboardInputFilter: GardState.Facet<(content: wordgard_doc.Slice, state: GardState) => wordgard_doc.Slice, readonly ((content: wordgard_doc.Slice, state: GardState) => wordgard_doc.Slice)[]>;
/**
Filter functions to run on HTML text that is read from the
clipboard.
*/
static clipboardInputHTMLFilter: GardState.Facet<(html: string, state: GardState) => string, readonly ((html: string, state: GardState) => string)[]>;
/**
When the editor reads plain text from the clipboard, this facet
can be used to provide a custom parser. Each provided function
is tried in order of precedence, until one returns a slice.
*/
static clipboardTextParser: GardState.Facet<(text: string, state: GardState) => wordgard_doc.Slice | null, readonly ((text: string, state: GardState) => wordgard_doc.Slice | null)[]>;
/**
Filter to run on plain text read from the clipboard.
*/
static clipboardInputTextFilter: GardState.Facet<(html: string, state: GardState) => string, readonly ((html: string, state: GardState) => string)[]>;
/**
Facet that allows you to register handlers to override paste
behavior.
*/
static pasteHandler: GardState.Facet<(wg: Wordgard, event: ClipboardEvent, slice: wordgard_doc.Slice, context: readonly wordgard_doc.Plot.Tag[]) => boolean, readonly ((wg: Wordgard, event: ClipboardEvent, slice: wordgard_doc.Slice, context: readonly wordgard_doc.Plot.Tag[]) => boolean)[]>;
/**
Facet for custom drop handlers. When the drop is done inside the
editor and should move an existing range, the `move` parameter
will hold the origin range.
*/
static dropHandler: GardState.Facet<(wg: Wordgard, event: DragEvent, pos: number, move: {
from: number;
to: number;
} | null, slice: wordgard_doc.Slice, context: readonly wordgard_doc.Plot.Tag[]) => boolean, readonly ((wg: Wordgard, event: DragEvent, pos: number, move: {
from: number;
to: number;
} | null, slice: wordgard_doc.Slice, context: readonly wordgard_doc.Plot.Tag[]) => boolean)[]>;
/**
This annotation is added to transactions created because the
editor's focused status changed. It holds `true` when the editor
gained focus, `false` when it lost focus.
*/
static isFocusChange: Transaction.Annotation.Type;
/**
Facet to add a [style
module](https://github.com/marijnh/style-mod#documentation) to
an editor. The editor will ensure that the module is mounted in
its {@link Wordgard.root document root}.
*/
static styleModule: GardState.Facet;
/**
Returns an extension that can be used to add a DOM event handler
to the editor. For any given event, such functions are ordered
by extension precedence, and the first handler to return true
will be assumed to have handled that event, and no other
handlers or built-in behavior will be activated for it. These
are registered on the {@link Wordgard.contentDOM content
element}, except for `scroll` handlers, which will be called any
time the editor's {@link Wordgard.scrollDOM scroll element} or
one of its parent nodes is scrolled.
*/
static domEventHandler(event: Event, handler: (event: HTMLElementEventMap[Event], wg: Wordgard) => boolean | void): GardState.Extension;
/**
Create an extension that registers a DOM event observers. Contrary
to event {@link Wordgard.domEventHandler handlers},
observers can't be prevented from running by a higher-precedence
handler returning true. They also don't prevent other handlers
and observers from running when they return true, and should not
call `preventDefault`.
*/
static domEventObserver(event: Event, observer: (event: HTMLElementEventMap[Event], wg: Wordgard) => void): GardState.Extension;
/**
Scroll handlers can override how editor content is scrolled into
view. If they return `true`, no further handling happens for the
scrolling. If they return false, the default scroll behavior is
applied. Scroll handlers should never initiate editor updates.
*/
static scrollHandler: GardState.Facet<(wg: Wordgard, target: {
from: number;
to: number;
} & Wordgard.ScrollSpec) => boolean, readonly ((wg: Wordgard, target: {
from: number;
to: number;
} & Wordgard.ScrollSpec) => boolean)[]>;
/**
Allows you to provide a function that should be called when the
library catches an exception from an extension (mostly from
plugins, but may be used by other extensions to route exceptions
from user-code-provided callbacks). This is mostly useful for
debugging and logging. See {@link Wordgard.logException}.
*/
static exceptionSink: GardState.Facet<(exception: any) => void, readonly ((exception: any) => void)[]>;
/**
Registers a listener function to be called whenever a set of
transactions is applied to the editor. This function may
dispatch additional transactions, if needed.
*/
static transactionListener: GardState.Facet<(trs: readonly Transaction[], wg: Wordgard) => void, readonly ((trs: readonly Transaction[], wg: Wordgard) => void)[]>;
private runTransactionListeners;
/**
A facet that can be used to register a function to be called
after the editor flushes updates to the DOM. Dispatching
transactions from such a function is allowed, but will cause a
new, separate update to happen.
*/
static updateListener: GardState.Facet<(update: Wordgard.Update) => void, readonly ((update: Wordgard.Update) => void)[]>;
/**
Facet that controls whether the editor content DOM is editable.
When its highest-precedence value is `false`, the element will
not have its `contenteditable` attribute set. (Note that this
doesn't affect API calls that change the editor content, even
when those are bound to keys or buttons. See the {@link
GardState.readOnly `readOnly` facet} for that.)
A non-editable editor will, by default, not be focusable. You
can set a {@link Wordgard.contentAttributes content attribute}
of `tabindex: 0` to make an uneditable Wordgard focusable.
*/
static editable: GardState.Facet;
/**
Controls the length of a full cursor blink cycle, in milliseconds.
Defaults to 1200. Can be set to 0 to disable blinking.
*/
static cursorBlinkRate: GardState.Facet;
/**
Allows you to influence the way mouse selection happens. The
functions in this facet will be called for a `mousedown` event
on the editor, and can return an object that overrides the way a
selection is computed from that mouse click or drag.
*/
static mouseSelectionStyle: GardState.Facet;
/**
Facet used to configure whether a given selection drag event
should move or copy the selection. The given predicate will be
called with the `mousedown` event, and can return `true` when
the drag should move the content. The default behavior is to
copy when holding Alt on Mac and Control on other platforms, and
move otherwise.
*/
static dragMovesSelection: GardState.Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>;
/**
Create a theme extension. The first argument can be a
[`style-mod`](https://github.com/marijnh/style-mod#documentation)
style spec providing the styles for the theme. These will be
prefixed with a generated scope class.
Because the selectors are prefixed, rules that directly match
the editor's {@link Wordgard.dom wrapper element} (to which the
scope class will be added) need to be explicitly differentiated
by adding an `&` to the selector for that element—for example
`&:has(wg-content:focus)`.
*/
static theme(spec: Record): GardState.Extension;
/**
This facet controls whether a dark or light color scheme is
active, which determines whether style rules with a `&dark` or
`&light` selector are applied. Defaults to `"light"`. If set to
`"auto"`, the editor uses a CSS `prefers-color-scheme: dark`
query to determine whether to enable light or dark mode.
Note that setting this to dark will not automatically make the
editor look dark. The default styling does not override the
inherited background and color of the editor. In case of a
page-wide `prefers-color-scheme` selection, those might already
be dark. But when setting an editor on a light background to
explicitly to use a dark theme, you'll need to make sure you
also load styles for that.
*/
static colorScheme: GardState.Facet<"auto" | "dark" | "light", "auto" | "dark" | "light">;
/**
Create an extension that loads a set of style rules. Like
with {@link Wordgard.theme `theme`}, use `&` to indicate the
place of the editor wrapper element when directly targeting
that. You can also use `&dark` or `&light` instead to only
target editors with a dark or light {@link Wordgard.colorScheme
color scheme}.
*/
static styles(spec: Record): GardState.Extension;
/**
Creates a simple theme that sets a height (given in pixels or,
if a string, a CSS number + unit) and automatic overflow
scrolling on the editor. (The default styling makes the editor
height fit its content.)
*/
static scrolling(height: number | string): GardState.Extension;
/**
Provides a Content Security Policy nonce to use when creating
the style sheets for the editor. Holds the empty string when no
nonce has been provided.
*/
static cspNonce: GardState.Facet;
/**
Facet that provides additional DOM attributes for the editor's
editable DOM element, either directly, or as a function from the
editor state.
*/
static contentAttributes: GardState.Facet;
/**
Facet that provides DOM attributes for the editor's outer
element.
*/
static editorAttributes: GardState.Facet;
/**
State effect used to include screen reader announcements in a
transaction. These will be added to the DOM in a visually hidden
element with `aria-live="polite"` set, and should be used to
describe effects that are visually obvious but may not be
noticed by screen reader users (such as moving to the next
search match).
*/
static announce: Transaction.Effect.Type;
/**
Facet that allows extensions to indicate that some amount of
space around the sides of the scrolling element should be
considered blocked from view when scrolling something into view.
This is only used by plugins that introduce elements that cover
part of the editor (for example a gutter).
*/
static coveredMargins: GardState.Facet<(wg: Wordgard) => Partial | null, readonly ((wg: Wordgard) => Partial | null)[]>;
}
declare namespace Wordgard {
/**
The type of object given to {@link Wordgard.create}.
*/
interface Spec extends Partial {
/**
The editor's initial state. If not given, a new state is
created by passing this configuration object to {@link
GardState.create}, using its `doc`, `selection`, and
`config` fields (if provided).
*/
state?: GardState;
/**
When present, the editor is immediately appended to the given
element on creation. (Otherwise, you'll have to place the
editor {@link Wordgard.dom element} in the document yourself.)
*/
parent?: Element | DocumentFragment;
/**
Pass an effect created with {@link Wordgard.scrollIntoView}
here to set an initial scroll position.
*/
scrollTo?: Transaction.Effect;
}
/**
Options passed to {@link Wordgard.scrollIntoView}.
*/
type ScrollSpec = {
/**
By default (`"nearest"`) the position will be vertically
scrolled only the minimal amount required to move the given
position into view. You can set this to `"start"` to move it
to the top of the editor, `"end"` to move it to the bottom, or
`"center"` to move it to the center.
*/
y?: "nearest" | "start" | "end" | "center";
/**
Effect similar to `y`, but for the horizontal scroll position.
*/
x?: "nearest" | "start" | "end" | "center";
/**
Extra vertical distance to add when moving something into
view. Not used with the `"center"` strategy. Defaults to 5.
Must be less than the height of the editor.
*/
yMargin?: number;
/**
Extra horizontal distance to add. Not used with the `"center"`
strategy. Defaults to 5. Must be less than the width of the
editor.
*/
xMargin?: number;
};
/**
The interface that objects registered with {@link
Wordgard.mouseSelectionStyle} must conform to.
*/
interface MouseSelectionStyle {
/**
Return a new selection for the mouse gesture that starts with
the event that was originally given to the constructor, and ends
with the event passed here. In case of a plain click, those may
both be the `mousedown` event, in case of a drag gesture, the
latest `mousemove` event will be passed.
When `extend` is true, that means the new selection should, if
possible, extend the start selection.
*/
get: (curEvent: MouseEvent, extend: boolean) => GardSelection;
/**
Called when the editor is updated while the gesture is in
progress. When the document changes, it may be necessary to map
some data (like the original selection or start position)
through the changes.
This may return `true` to indicate that the `get` method should
get queried again after the update, because something in the
update could change its result. Be wary of infinite loops when
using this (where `get` returns a new selection, which will
trigger `update`, which schedules another `get` in response).
*/
update: (update: Wordgard.Update) => boolean | void;
}
/**
Log or report an unhandled exception in client code. Should
probably only be used by extension code that allows client code to
provide functions, and calls those functions in a context where an
exception can't be propagated to calling code in a reasonable way
(for example when in an event handler).
Either calls a handler registered with {@link
Wordgard.exceptionSink}, `window.onerror`, if defined, or
`console.error` (in which case it'll pass `context`, when given,
as first argument).
*/
function logException(state: GardState, exception: any, context?: string): void;
/**
Plugins associate stateful values with an editor. They can be
useful for displaying interface elements, or keeping ephemeral
interface state.
*/
class Plugin {
/**
Instances of this class act as extensions.
*/
extension: GardState.Extension;
private constructor();
/**
Define a plugin from a constructor function that creates the
plugin's value, given an editor.
*/
static define(create: (wg: Wordgard) => V, provide?: (plugin: Wordgard.Plugin) => GardState.Extension): Plugin;
/**
Create a plugin for a class whose constructor takes an editor
as only argument.
*/
static fromClass(cls: {
new (wg: Wordgard): V;
}, provide?: (plugin: Wordgard.Plugin) => GardState.Extension): Plugin;
/**
Create an {@link Wordgard.domEventHandler event handler} for this
plugin. Usually called from the plugin's `provide` function.
*/
eventHandler(event: Event, handler: (event: HTMLElementEventMap[Event], wg: Wordgard, value: V) => boolean | void): GardState.Extension;
/**
Create an {@link Wordgard.domEventObserver event observer} for this
plugin.
*/
eventObserver(event: Event, observer: (event: HTMLElementEventMap[Event], wg: Wordgard, value: V) => void): GardState.Extension;
}
namespace Plugin {
/**
This is the interface plugin objects must expose.
*/
interface Value {
/**
Notifies the plugin of an update that happened in the
editor. This is called _before_ the editor updates its own
DOM. It is responsible for updating the plugin's internal
state (including any state that may be read by plugin
fields) and _writing_ to the DOM for the changes in the
update. To avoid unnecessary layout recomputations, it
should _not_ read the DOM layout—use {@link
Wordgard.scheduleDOMRead} to schedule your
code in a DOM reading phase if you need to.
*/
update?(update: Wordgard.Update): void;
/**
When present, this will be called when an update causes any
changes in the DOM representation of the document.
*/
docUpdate?(wg: Wordgard): void;
/**
Called when the editor is attached to the DOM. If the plugin
needs to allocate any resource that must be released, or modify
something outside the editor, it should do it in this method,
and make sure to release/undo it in its `disconnect` method.
*/
connect?(wg: Wordgard): void;
/**
Called when the editor is removed from the DOM, or the
plugin is removed from the editor.
*/
disconnect?(wg: Wordgard): void;
/**
Called when the plugin is removed from an editor. This
should clean up any changes it made to the editor itself. If
the editor was connected to a document, {@link
Wordgard.Plugin.Value.disconnect `disconnect`} will be called
before this.
*/
remove?(wg: Wordgard): void;
}
}
/**
Editor {@link Wordgard.Plugin plugins} and {@link
Wordgard.updateListener update listeners} are given instances of
this class whenever the editor is updated.
*/
class Update {
/**
The editor that the update is associated with.
*/
readonly editor: Wordgard;
/**
The previous editor state.
*/
readonly startState: GardState;
/**
The new editor state.
*/
readonly state: GardState;
/**
The transactions involved in the update. May be empty.
*/
readonly transactions: readonly Transaction[];
/**
The changes made to the document by this update.
*/
readonly changes: ChangeSet;
private constructor();
/**
Returns true when the document was modified or when the size
of the editor, or elements within the editor, changed.
*/
get geometryChanged(): boolean;
/**
True when this update indicates a focus change.
*/
get focusChanged(): boolean;
/**
Whether the document changed in this update.
*/
get docChanged(): boolean;
/**
Whether the selection was explicitly set in this update.
*/
get selectionSet(): boolean;
}
}
type AttrSource = Record | ((wg: Wordgard) => Record);
/**
Key bindings associate keys with functions that should be run when
a matching keyboard event happens.
A key binding can either specify a specific {@link
KeyBinding.Spec.char character} to match on, which will be
compared against the actual character produced by a key event, or
describe a {@link KeyBinding.Spec.key key combination}.
Bindings for a given key event are evaluated in order of
precedence, with each getting a chance to handle the event,
stopping when the first handler returns true.
Key combinations are described by strings like
`"Shift-Ctrl-Enter"`—a key identifier prefixed with zero or more
modifiers. Key identifiers are based on the strings that can
appear in
[`KeyEvent.key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).
Use lowercase letters to refer to letter keys. You can use
`"Space"` as an alias for the `" "` name.
Modifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or
`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or
`Meta-`) are recognized.
You can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on
other platforms. So `Mod-b` is `Ctrl-b` on Linux but `Cmd-b` on
macOS.
Unlike character bindings, key combination bindings should refer
to the unmodified base key that is being pressed, not the
character produced by combining that key with Shift or AltGraph.
Keyboard mappings that rearrange the positions of Latin characters
_are_ taken into account for this (the mapped position is used),
but the library tries to 'see through' keyboard mappings that
assign non-Latin characters to keys (so that both the Latin and
the non-Latin name can be used).
*/
declare class KeyBinding {
/**
The configuration object used to define this binding.
*/
readonly spec: KeyBinding.Spec;
/**
Bindings count as extensions and can be included in an editor
configuration.
*/
extension: GardState.Extension;
private constructor();
/**
Define a binding.
*/
static of(spec: KeyBinding.Spec): KeyBinding;
}
declare namespace KeyBinding {
/**
A description of a key binding.
*/
interface Spec {
/**
A textual character that this binding should trigger for.
*/
char?: string;
/**
A key combination to use for this binding. If the
platform-specific property (`mac`, `win`, or `linux`) for the
current platform is used as well in the binding, that one takes
precedence. If `key` isn't defined and the platform-specific
binding isn't either, a binding is ignored.
*/
key?: string;
/**
Key to use specifically on macOS.
*/
mac?: string;
/**
Key to use specifically on Windows.
*/
win?: string;
/**
Key to use specifically on Linux.
*/
linux?: string;
/**
The command to execute when this binding is triggered.
*/
run: Command.Bound | Command;
/**
When given, this defines a second binding, using the (possibly
platform-specific) key name, prefixed with `Shift-`, to activate
this command.
*/
shift?: Command.Bound | Command;
/**
When this property is present, the function is called for every
key, and may return true to indicate the key was handled.
*/
any?: (wg: Wordgard, event: KeyboardEvent) => boolean;
/**
By default, key bindings apply when focus is on the editor
content (the `"editor"` scope). Some extensions, mostly those
that define their own panels, might want to allow registering
bindings local to that panel. Such bindings should use a custom
scope name. You may also assign multiple scope names to a
binding, separating them by spaces.
*/
scope?: string;
/**
By default, all keys events for which a handler exists have
their `preventDefault` called, even if no handler returns
true. You can set this to true to disable that behavior.
*/
allowDefault?: boolean;
}
/**
Run the key handlers registered for a given scope. The event
object should be a `"keydown"` event. Returns true if any of the
handlers handled it.
*/
function runScopeHandlers(wg: Wordgard, event: KeyboardEvent, scope: string): boolean;
/**
Facet used for registering key bindings. Extension precedence
determines the order in which bindings that match the same key
are called. When a handler has returned `true` for a given key,
no further handlers are called.
*/
const source: GardState.Facet;
/**
By default, the {@link KeyBinding.defaultKeymap default keymap}
is automatically active. You can configure this to false if you
want to completely replace it.
*/
const useDefaultKeymap: GardState.Facet;
/**
The editor's set of default key bindings. Binds the following
keys. Most cursor motion bindings include a `Shift-` variant
that passes the `extend` flag to the command. Enabled by default
unless {@link KeyBinding.useDefaultKeymap} is disabled.
- `Enter` to {@link command.enter}
- `Shift-Enter` to {@link command.insertLineBreak}
- `Backspace` to {@link command.deleteUnit} (`"backward"`)
- `Delete` to {@link command.deleteUnit} (`"forward"`)
- `Ctrl-Backspace` (`Alt-Backspace` on MacOS) to {@link command.deleteWord} (`"backward"`)
- `Ctrl-Delete` (`Alt-Delete` on MacOS) to {@link command.deleteWord} (`"forward"`)
- `Cmd-Backspace` (MacOS) to {@link command.deleteToLineEnd} (`"backward"`)
- `Cmd-Delete` (MacOS) to {@link command.deleteToLineEnd} (`"forward"`)
- `ArrowLeft` to {@link command.moveByUnit} (`{dir: "left"}`)
- `ArrowRight` to {@link command.moveByUnit} (`{dir: "right"}`)
- `ArrowUp` to {@link command.moveByLine} (`{dir: "up"}`)
- `ArrowDown` to {@link command.moveByLine} (`{dir: "down"}`)
- `Ctrl-AllowLeft` (`Cmd-ArrowLeft` on MacOS) to {@link command.moveByWord} (`{dir: "left"}`)
- `Ctrl-AllowRight` (`Cmd-ArrowRight` on MacOS) to {@link command.moveByWord} (`{dir: "right"}`)
- `Cmd-ArrowUp` (MacOS) to {@link command.moveToDocSide} (`{side: "start"}`)
- `Cmd-ArrowDown` (MacOS) to {@link command.moveToDocSide} (`{side: "end"}`)
- `Ctrl-ArrowUp` (MacOS) to {@link command.moveByPage} (`{dir: "up"}`)
- `Ctrl-ArrowDown` (MacOS) to {@link command.moveByPage} (`{dir: "down"}`)
- `PageUp` to {@link command.moveByPage} (`{dir: "up"}`)
- `PageDown` to {@link command.moveByPage} (`{dir: "down"}`)
- `Home` to {@link command.moveToLineSide} (`{dir: "backward"}`)
- `End` to {@link command.moveToLineSide} (`{dir: "forward"}`)
- `Ctrl-Home` (`Cmd-Home` on MacOS) to {@link command.moveToDocSide} (`{side: "start"}`)
- `Ctrl-End` (`Cmd-End` on MacOS) to {@link command.moveToDocSide} (`{side: "end"}`)
- `Ctrl-a` (`Cmd-a` on MacOS) to {@link command.selectAll}
- `Ctrl-z` (`Cmd-z` on MacOS) to {@link command.undo}
- `Ctrl-y` (`Shift-Cmd-z` on MacOS) to {@link command.redo}
On MacOS, the following Emacs-style bindings are available:
- `Ctrl-b` to {@link command.moveByUnit} (`{dir: "backward"}`)
- `Ctrl-f` to {@link command.moveByUnit} (`{dir: "forward"}`)
- `Ctrl-p` to {@link command.moveByLine} (`{dir: "up"}`)
- `Ctrl-n` to {@link command.moveByLine} (`{dir: "down"}`)
- `Ctrl-a` to {@link command.moveToTextblockSide} (`{dir: "backward"}`)
- `Ctrl-e` to {@link command.moveToTextblockSide} (`{dir: "forward"}`)
- `Ctrl-d` to {@link command.deleteUnit} (`"forward"`)
- `Ctrl-h` to {@link command.deleteUnit} (`"backward"`)
- `Ctrl-k` to {@link command.killToLineEnd}
- `Ctrl-Alt-h` to {@link command.deleteWord} (`"backward"`)
- `Ctrl-o` to {@link command.insertLineBreak}
- `Ctrl-t` to {@link command.transposeChars}
- `Ctrl-v` to {@link command.moveByPage} (`{dir: "down"}`)
- `Ctrl-y` to {@link command.yankKilled}
*/
const defaultKeymap: readonly KeyBinding[];
}
type PanelConfig = {
/**
By default, panels will be placed inside the editor's DOM
structure. You can use this option to override where panels with
`top: true` are placed.
*/
topContainer?: HTMLElement;
/**
Override where panels with `top: false` are placed.
*/
bottomContainer?: HTMLElement;
};
/**
Object that describes an active panel.
*/
interface Panel {
/**
The element representing this panel. The library will add the
`"wg-panel"` DOM class to this.
*/
dom: HTMLElement;
/**
Controls whether the panel should be at the top or bottom of the
editor. Defaults to false.
*/
top?: boolean;
/**
Update the panel DOM for a given editor update.
*/
update?(update: Wordgard.Update): void;
/**
Called, when present, when the panel has been added the DOM.
*/
connect?(wg: Wordgard): void;
/**
Called when the editor with the panel is disconnected from the
DOM, or the panel is removed from an editor.
*/
disconnect?(wg: Wordgard): void;
/**
Called when the panel is removed from the editor.
*/
remove?(wg: Wordgard): void;
}
declare namespace Panel {
/**
A function that initializes a panel. Used in {@link Panel.show}.
*/
type Constructor = (wg: Wordgard) => Panel;
/**
Opening a panel is done by providing a constructor function for
the panel through this facet. (The panel is closed again when its
constructor is no longer provided.) Values of `null` are ignored.
*/
const show: GardState.Facet;
/**
Get the active panel created by the given constructor, if any.
This can be useful when you need access to your panels' DOM
structure.
*/
function get(wg: Wordgard, constructor: (wg: Wordgard) => T): T | null;
/**
Configures the panel-managing extension.
*/
function configure(config?: PanelConfig): GardState.Extension;
}
/**
Provides a menu bar that displays menu items defined via the
{@link command.Menu menu system} in a button bar at the top of the
editor. The same menu items can be used by custom menu
implementations, but this extension provides a solid default menu
style.
*/
declare function menuBar(config?: {
template?: Menu.Template | readonly Menu.Template[];
}): GardState.Extension;
/**
Dialogs are {@link Panel panels} opened as a side-effect, and
closed by user action. This interface is used to describe them.
*/
interface Dialog {
/**
A function to render the content of the dialog. The result
should contain at least one `