add basic enter command

This commit is contained in:
Philipp Kühn 2021-02-09 10:06:13 +01:00
parent 2bd3033207
commit e8232dd737
4 changed files with 81 additions and 0 deletions

View File

@ -1,6 +1,21 @@
<template>
<div>
<div v-if="editor">
<button
@click="editor
.can()
.chain()
.focus()
.enter()
.insertText('1')
.enter()
.insertText('2')
.enter()
.insertText('3')
.run()"
>
enter
</button>
<button @click="editor.chain().focus().toggleBold().run()" :class="{ 'is-active': editor.isActive('bold') }">
bold
</button>

View File

@ -307,12 +307,40 @@ export class Editor extends EventEmitter {
return this.createDocument('')
}
public isCapturingTransaction = false
private capturedTransaction: Transaction | null = null
public captureTransaction(fn: Function) {
this.isCapturingTransaction = true
fn()
this.isCapturingTransaction = false
const tr = this.capturedTransaction
this.capturedTransaction = null
return tr
}
/**
* The callback over which to send transactions (state updates) produced by the view.
*
* @param transaction An editor state transaction
*/
private dispatchTransaction(transaction: Transaction): void {
if (this.isCapturingTransaction) {
if (!this.capturedTransaction) {
this.capturedTransaction = transaction
return
}
transaction.steps.forEach(step => this.capturedTransaction?.step(step))
return
}
const state = this.state.apply(transaction)
const selectionHasChanged = !this.state.selection.eq(state.selection)

View File

@ -0,0 +1,36 @@
import { Command } from '../types'
/**
* Press Enter
*/
export const enter = (): Command => ({
editor,
view,
tr,
dispatch,
}) => {
const keyCode = 13
const key = 'Enter'
const event = document.createEvent('Event')
event.initEvent('keydown', true, true)
// @ts-ignore
event.keyCode = keyCode
// @ts-ignore
event.key = key
// @ts-ignore
event.code = key
const capturedTransaction = editor.captureTransaction(() => {
view.someProp('handleKeyDown', f => f(view, event))
})
capturedTransaction?.steps.forEach(step => {
const newStep = step.map(tr.mapping)
if (newStep && dispatch) {
tr.step(newStep)
}
})
return true
}

View File

@ -6,6 +6,7 @@ import * as command from '../commands/command'
import * as createParagraphNear from '../commands/createParagraphNear'
import * as deleteRange from '../commands/deleteRange'
import * as deleteSelection from '../commands/deleteSelection'
import * as enter from '../commands/enter'
import * as exitCode from '../commands/exitCode'
import * as extendMarkRange from '../commands/extendMarkRange'
import * as first from '../commands/first'
@ -55,6 +56,7 @@ export const Commands = Extension.create({
...createParagraphNear,
...deleteRange,
...deleteSelection,
...enter,
...exitCode,
...extendMarkRange,
...first,