Skip to content

Show format state

Jiuqing Song edited this page Feb 24, 2018 · 5 revisions

Go back to How to use

It is very popular to show current format state on format bar when user is editing. For example, if current selected text is in bold state, the "bold" button will show a checked state. RoosterJs provides getFormatState() API in roosterjs-editor-api package to get current state.

function getFormatState(editor: Editor, event?: PluginEvent): FormatState;

An optional event parameter provides the ability to get some of the result from event cache, which means if we have already queried format state with this event object before, it will cache the result and no need to calculate again.

This API returns a FormatState object which contains all available state of current format:

// The format state
interface FormatState {
    // Font name
    fontName?: string;

    // Font size
    fontSize?: string;

    // Whether the text is bolded
    isBold?: boolean;

    // Whether the text is italic
    isItalic?: boolean;

    // Whether the text has underline
    isUnderline?: boolean;

    // Background color
    backgroundColor?: string;

    // Text color
    textColor?: string;

    // Whether the text is in bullet mode
    isBullet?: boolean;

    // Whether the text is in numbering mode
    isNumbering?: boolean;

    // Whether the text has strike through line
    isStrikeThrough?: boolean;

    // Whether the text is in block quote
    isBlockQuote?: boolean;

    // Whether the text is in subscript mode
    isSubscript?: boolean;

    // Whether the text is in superscript mode
    isSuperscript?: boolean;

    // Whether unlink command can be called to the text
    canUnlink?: boolean;

    // Whether add image alt text command can be called to the text
    canAddImageAltText?: boolean;

    // Whether the content can be undone
    canUndo?: boolean;

    // Whether the content ca nbe redone
    canRedo?: boolean;

    // Header level (0-6, 0 means no header)
    headerLevel?: number;
}

To query format state after each edit event, you need to have a plugin to handle event such as MouseDown, KeyDown and ContentChanged. There is a sample plugin in roosterjs sample site. You can git pull the source code and see [roosterjs]/sample/scripts/plugins/ShowFormatState.ts, there is code to get current format state and show it in UI.

Another example is a sample Ribbon, you can check out source code from roosterjs-react project and see files under packages/roosterjs-react-ribbon.

More info

Package: roosterjs-editor-api

Support from: 6.0.0

Source code: getFormatState.ts