Use collapsePreambleEffect (#15866)

GitOrigin-RevId: e07a48ba5a7ca2ce30aa6933030f8eae970a65b5
This commit is contained in:
Alf Eaton 2024-01-03 12:41:41 +00:00 committed by Copybot
parent c84e45bc06
commit 621bae03ca
2 changed files with 16 additions and 12 deletions

View file

@ -6,7 +6,7 @@ import {
StateField,
} from '@codemirror/state'
import { syntaxTree } from '@codemirror/language'
import { Preamble } from './visual-widgets/preamble'
import { collapsePreambleEffect, Preamble } from './visual-widgets/preamble'
/**
* A view plugin that moves the cursor from the start of the preamble into the document body when the doc is opened.
*/
@ -63,11 +63,17 @@ export const skipPreambleWithCursor = (
}
}
view.dom.addEventListener('editor:collapse-preamble', escapeFromPreamble)
return {
update(update) {
if (!checkedOnce) {
if (checkedOnce) {
if (
update.transactions.some(tr =>
tr.effects.some(effect => effect.is(collapsePreambleEffect))
)
) {
escapeFromPreamble()
}
} else {
const { state } = update
if (syntaxTree(state).length === state.doc.length) {
@ -88,12 +94,6 @@ export const skipPreambleWithCursor = (
}
}
},
destroy() {
view.dom?.removeEventListener(
'editor:collapse-preamble',
escapeFromPreamble
)
},
}
})

View file

@ -1,4 +1,4 @@
import { EditorSelection } from '@codemirror/state'
import { EditorSelection, StateEffect } from '@codemirror/state'
import { EditorView, WidgetType } from '@codemirror/view'
import { SyntaxNode } from '@lezer/common'
@ -15,6 +15,8 @@ export type Preamble = {
}[]
}
export const collapsePreambleEffect = StateEffect.define<boolean>()
export class PreambleWidget extends WidgetType {
constructor(public expanded: boolean) {
super()
@ -60,7 +62,9 @@ export class PreambleWidget extends WidgetType {
}
event.preventDefault()
if (this.expanded) {
view.dom.dispatchEvent(new Event('editor:collapse-preamble'))
view.dispatch({
effects: collapsePreambleEffect.of(true),
})
} else {
view.dispatch({
selection: EditorSelection.cursor(0),