Trevixal API
    Preparing search index...

    Module @trevixal/core

    @trevixal/core

    CI npm types license

    Documentation · Live editor · Changelog · Issues

    The Trevixal editor

    • Immutable document model: schema-validated JSON you can store, diff and transform
    • Invertible transactions, so undo is step inversion rather than a second history
    • Runs headless in Node with no DOM, for migrations, tests and server rendering
    • Imported HTML parsed inside an inert template through an allowlist
    • 36.2 kB minified and gzipped, with TypeScript types in the package

    The editing engine: an immutable document model, invertible transactions, and a contenteditable view that treats the DOM as a render target rather than the truth. No framework code, no runtime dependencies, safe to import on a server.

    npm install @trevixal/core
    
    import { createEditor, Schema, defaultNodes, defaultMarks } from '@trevixal/core'

    const editor = createEditor({
    schema: new Schema({ nodes: defaultNodes(), marks: defaultMarks() }),
    element: document.querySelector('#editor'), // omit for a headless editor
    placeholder: 'Write something…',
    onChange: ({ json }) => save(json),
    })

    editor.commands.toggleMark('bold')
    editor.chain().focus().setHeading(2).insertText('Hello').run()
    editor.getJSON() // what you store
    editor.getHTML() // an export format, not the storage format

    Omit element and the identical engine runs with no DOM at all, for server-side processing, migrations and tests.

    Area What lives there
    model/ EditorNode, Fragment, Mark, Schema, content expressions, and positions as { path, offset }
    state/ EditorState, Transaction, and ten invertible step types
    commands/ (state) => Transaction | null functions; editor.commands is a facade over them
    view/ The renderer, beforeinput handling, the IME composition machine, MutationObserver repair, decoration layers
    history/ Undo over inverted steps, with time and adjacency grouping
    serialize/ HTML, Markdown and text out; sanitized HTML in; paste-source cleanup
    suggest/ The trigger driver behind / and : menus
    a11y/ The live-region announcer for edits a screen reader cannot see coming

    The DOM is never the source of truth. State is immutable; the surface is an input source and a render target. Everything else follows from that.

    Every change is an invertible step. Undo is step inversion, not a second bookkeeping system, and every step remaps positions, so selections, decorations and suggestion ranges survive arbitrary edits. A property test applies 200 random steps, inverts them, and checks the document is restored.

    Imported HTML is parsed inside an inert <template> through an allowlist, with a protocol allowlist on every URL. Scripts cannot run during parsing, and an XSS corpus holds it to that.

    The DOM is patched, never rewritten. An attribute is only written when its value actually changed. Assigning one the value it already has is still a write. It invalidates style, it shows up as a mutation to anything watching, and on an <iframe> assigning src reloads the frame. Since a decoration layer puts the whole document through the renderer again, and extensions refresh those on a timer, writing unconditionally restarted every embed in the document a few hundred milliseconds after every keystroke.

    Focusing the surface never moves the page. view.focus() hands focus back without scrolling: it is called after a menu, a dialog or the command palette took focus, and the caret can be a whole document away from what the reader is looking at. Navigation says so instead: view.scrollSelectionIntoView().

    Four public hooks, and every extension package in this repository is built on them alone: onTransaction, addDispatchTransform, setDecorationLayer, and the suggestion trigger module, plus schema merging, keymap, inputRules and nodeViews. If something needs more, the hook set is incomplete; see ADR-0008.

    Apache-2.0

    AddMarkStep
    AllSelection
    Chain
    DOMRenderer
    Editor
    EditorCommands
    EditorNode
    EditorState
    EditorView
    FormatPainter
    Fragment
    History
    JoinNodesStep
    LiftNodesStep
    Mark
    MarkType
    MoveNodeStep
    NodeSelection
    NodeType
    RemoveMarkStep
    ReplaceInlineStep
    ReplaceNodesStep
    Schema
    Selection
    SetNodeAttrsStep
    SplitNodeStep
    Step
    TableMap
    TextNode
    TextSelection
    Transaction
    UnsupportedEnvironmentError
    UploadError
    WrapNodesStep
    Announcer
    AnnouncerOptions
    AutocorrectOptions
    BlockRange
    ContentTerm
    CopiedFormat
    CustomListLevel
    DefaultInputRuleOptions
    DOMPoint
    DropCap
    EditorChange
    EditorOptions
    EditorSnapshot
    EditorStateConfig
    EditorViewOptions
    FormatPainterOptions
    FormatPainterState
    HeadingNumber
    HistoryEntry
    HistoryOptions
    HTMLDocumentOptions
    HTMLDocumentTheme
    HTMLSerializeOptions
    HTMLSpec
    InlineDecoration
    InputRule
    InputRuleContext
    InsertEmailLinkOptions
    LinkUpdate
    ListNumberingScheme
    MarkdownParseOptions
    MarkdownSerializeOptions
    MarkJSON
    MarkSpec
    NamedStyle
    NodeJSON
    NodeSpec
    NodeViewInstance
    PageMargins
    PageSection
    PageSetup
    ParagraphBorder
    ParseRule
    Position
    PositionMapper
    ResolvedPosition
    SchemaSpec
    SearchMatch
    SearchOptions
    SelectionJSON
    SetContentOptions
    StepResult
    StyleDefinition
    StyleProps
    SuggestionListHandle
    SuggestionListOptions
    SuggestionListState
    SuggestionOptions
    TableMapCell
    TableRect
    TabStop
    TransactionEvent
    TriggerMatch
    TriggerOptions
    TypographyOptions
    AnnouncePriority
    Attrs
    Bias
    BorderSide
    BorderStyle
    CaseMode
    Command
    CustomLevelStyle
    DecorationSource
    DispatchTransform
    DocJSON
    DropCapKind
    EditorEvent
    KeyBinding
    Keymap
    ListCounterStyle
    NodeViewConstructor
    NodeViewFactory
    PageOrientation
    PageTemplatePart
    PaperSize
    PasteSource
    Path
    StyleAlign
    StyleKind
    TabAlignment
    TabLeader
    TextDirection
    ADD_TO_HISTORY
    AUTOCORRECT_WORDS
    BORDER_SIDES
    BORDER_STYLES
    BUILT_IN_STYLES
    BULLET_LIST_STYLES
    clearAllFormatting
    clearBlockFormatting
    clearFormatting
    CODE_TITLE_MAX
    continueNumberingFromPrevious
    CUSTOM_LEVEL_STYLES
    DEFAULT_LIST_NUMBERING
    DEFAULT_PAGE_SETUP
    DEFAULT_TAB_INTERVAL
    deleteBackwardInPreformatted
    deleteCharBackward
    deleteCharForward
    deleteEmptyBlockAfterContainer
    deleteSelection
    DOCUMENT_ATTRIBUTE
    DROP_CAP_LINES
    escapeWrapperOnBackspace
    escapeWrapperOnEnter
    exitEnclosingBlock
    exitPreformatted
    HEADING_NUMBERING_SCHEMES
    HISTORY_LABEL
    indentInPreformatted
    insertNewlineInPreformatted
    insertTabAtStop
    joinBackward
    joinForward
    LEVEL_INDENT
    LEVEL_START
    lift
    liftEmptyListItem
    liftListItem
    LIST_LEVELS
    LIST_NUMBERING_SCHEMES
    LIST_STYLES
    MAX_BORDER_WIDTH
    MAX_COLUMNS
    MAX_INDENT
    MAX_PAGE_MARGIN
    NEW_HISTORY_GROUP
    noMarks
    ORDERED_LIST_STYLES
    outdentInPreformatted
    PAPER_SIZES
    restartNumbering
    selectAll
    sinkListItem
    splitBlock
    splitBlockInPreformatted
    splitListItem
    TAB_ALIGNMENTS
    TAB_LEADERS
    toggleSmallCaps
    toggleTaskChecked
    toggleTaskList
    TREVIXAL_MIME
    unwrapList
    applyInlineMark
    applyInputRules
    applyTypedTextRules
    attrsEq
    autocorrectRule
    baseKeymap
    blockLayoutAttrs
    blockLayoutHTML
    blocksInRange
    chainCommands
    characterCount
    characterStyleAt
    clampPosition
    cleanPastedHTML
    codeBlockTitle
    coerceInlineFor
    columnCount
    comparePositions
    continueNumbering
    convertCase
    createAnnouncer
    createEditor
    customListScheme
    defaultCustomLevel
    defaultInputRules
    defaultMarks
    defaultNodes
    deleteRange
    deleteStyle
    describeDocChange
    describeFormat
    detectPasteSource
    documentAttrs
    documentCommentsOf
    documentListSchemes
    documentSettingsAttrs
    documentSettingsElement
    documentSignatureOf
    documentStyle
    documentStyles
    documentThemeOf
    domPointFromPosition
    dropCapOf
    editorDocument
    escapeHTML
    escapeMarkdown
    exportTextOf
    fillPageTemplate
    findMatches
    findTrigger
    firstTextblockPath
    formatFromSnapshot
    formatListCounter
    formatTabStops
    frontMatterOf
    headingLevelOfStyle
    headingNumberingOf
    headingNumberingScheme
    headingNumbers
    indentBlocks
    inlineLength
    inlineOffsetFromText
    inlineSize
    insertBlockAfter
    insertContent
    insertInlineNode
    insertText
    isCustomNumberingId
    isEmailAddress
    isListItemTypeName
    isMarkActive
    isStoredNumbering
    keydownHandler
    lastIndexOfPath
    levelMarker
    lineRangeTest
    linkifyText
    listMarker
    listNumberingAt
    listNumberingOf
    listNumberingScheme
    listSchemesCSS
    listStylesFor
    looksLikeMarkdown
    markFromJSON
    marksAtInlineOffset
    marksEq
    matchesContent
    maxPosition
    mergeInline
    mergeKeymaps
    minPosition
    moveNodeTo
    namedStylesCSS
    newStyleId
    nodeAtPath
    nodeFromJSON
    normalizeDoc
    normalizeKeyName
    normalizeLineRanges
    pageDimensions
    pageMargin
    pageOrientation
    pageSectionOf
    pageSetupAttr
    pageSetupOf
    pageTemplateParts
    paperSize
    paragraphBorderOf
    paragraphCount
    paragraphShadingOf
    paragraphStyleOf
    parentPathOf
    parseBlockLayout
    parseContentExpr
    parseDocumentSettings
    parseHTML
    parseListSchemes
    parseMarkdown
    parseStoredStyles
    parseTabStops
    pathOfElement
    pathsEqual
    pathStartsWith
    pos
    positionFromDOMPoint
    positionsEqual
    rangeHasMark
    rangesWithMark
    replaceAll
    replaceInline
    replaceMatch
    replaceNodeAt
    resolvePosition
    safeAssignee
    safeColor
    safeCSSValue
    safeElementId
    safeFontFamily
    safeHref
    safeImageSrc
    safeLanguageName
    safeLength
    safeLineHeight
    safeStyleId
    safeTaskDate
    sanitizeStyleProps
    schema
    selectionNear
    sentenceCount
    serializeToHTML
    serializeToHTMLDocument
    serializeToMarkdown
    serializeToText
    serializeToTextFile
    setBlockAttrs
    setBlockType
    setColumnRule
    setColumns
    setDocumentAttrs
    setDocumentDirection
    setDropCap
    setHeadingNumbering
    setHyphenation
    setLetterSpacing
    setLineHeight
    setLineNumbers
    setLinkTarget
    setListNumbering
    setListStyle
    setMark
    setParagraphBorder
    setParagraphShading
    setParagraphSpacing
    setParagraphStyle
    setStyle
    setTabStops
    setTaskChecked
    setTextAlign
    setTextDirection
    setWidowControl
    sliceInline
    smartTypographyRules
    stepFail
    stepOk
    storedListSchemesAttr
    storedNumbering
    storedNumberingsFor
    storedPageSetup
    storedStylesAttr
    storedVariables
    styleDeclarations
    suggestion
    suggestionList
    tabStopsOf
    taskMetaText
    templateVariables
    textblocks
    textDirection
    toggleCharacterStyle
    toggleList
    toggleMark
    toggleWrap
    typeInPreformatted
    unsetMark
    updateAtPath
    validateSelection
    wordCount
    wrapIn
    Node → EditorNode