[visual] Place cursor in editable content when closing the preamble (#14162)

GitOrigin-RevId: 35f146caa4469c7f31fb00dc6047a421b1daadb0
This commit is contained in:
Alf Eaton
2023-08-30 08:04:27 +00:00
committed by Copybot
parent 1e286c263c
commit 03fbc5e0a8
7 changed files with 174 additions and 162 deletions
@@ -1,6 +1,6 @@
import { ensureSyntaxTree } from '@codemirror/language'
import { EditorState } from '@codemirror/state'
import { SyntaxNode, SyntaxNodeRef, Tree } from '@lezer/common'
import { SyntaxNode, SyntaxNodeRef } from '@lezer/common'
import { previousSiblingIs } from './common'
import { NodeIntersectsChangeFn, ProjectionItem } from './projection'
import { FigureData } from '../../extensions/figure-modal'
@@ -138,72 +138,6 @@ export const cursorIsAtEndEnvironment = (
}
}
}
const findStartOfDocumentEnvironment = (tree: Tree): number | null => {
const docEnvironment = findNodeInDocument(tree, 'DocumentEnvironment')
return docEnvironment?.getChild('Content')?.from || null
}
const findStartOfAbstractEnvironment = (
tree: Tree,
state: EditorState
): number | null => {
const abstractEnvironment = findNodeInDocument(
tree,
(nodeRef: SyntaxNodeRef) => {
return Boolean(
nodeRef.type.is('$Environment') &&
getEnvironmentName(nodeRef.node, state) === 'abstract'
)
}
)
return abstractEnvironment?.getChild('Content')?.from || null
}
const findMaketitleCommand = (tree: Tree): number | null => {
const maketitle = findNodeInDocument(tree, 'Maketitle')
return maketitle?.to ?? null
}
const findNodeInDocument = (
tree: Tree,
predicate: number | string | ((node: SyntaxNodeRef) => boolean)
): SyntaxNode | null => {
let node: SyntaxNode | null = null
const predicateFn =
typeof predicate !== 'function'
? (nodeRef: SyntaxNodeRef) => {
return nodeRef.type.is(predicate)
}
: predicate
tree?.iterate({
enter(nodeRef) {
if (node !== null) {
return false
}
if (predicateFn(nodeRef)) {
node = nodeRef.node
return false
}
},
})
return node
}
export const findStartOfDocumentContent = (
state: EditorState
): number | null => {
const tree = ensureSyntaxTree(state, state.doc.length, HUNDRED_MS)
if (!tree) {
return null
}
return (
findStartOfAbstractEnvironment(tree, state) ??
findMaketitleCommand(tree) ??
findStartOfDocumentEnvironment(tree)
)
}
/**
*
* @param node A node of type `$Environment`, `BeginEnv`, or `EndEnv`