@@ -12,35 +12,55 @@ export type BlockInfo = {
1212} ;
1313
1414/**
15- * Retrieves information regarding the most nested block node in a ProseMirror doc, that a given position lies in.
15+ * Retrieves information regarding the nearest blockContainer node in a
16+ * ProseMirror doc, relative to a position.
1617 * @param doc The ProseMirror doc.
17- * @param posInBlock A position somewhere within a block node.
18- * @returns A BlockInfo object for the block the given position is in, or undefined if the position is not in a block
19- * for the given doc.
18+ * @param pos An integer position.
19+ * @returns A BlockInfo object for the nearest blockContainer node.
2020 */
21- export function getBlockInfoFromPos (
22- doc : Node ,
23- posInBlock : number
24- ) : BlockInfo | undefined {
25- if ( posInBlock < 0 || posInBlock > doc . nodeSize ) {
26- return undefined ;
21+ export function getBlockInfoFromPos ( doc : Node , pos : number ) : BlockInfo {
22+ // If the position is outside the outer block group, we need to move it to the
23+ // nearest block. This happens when the collaboration plugin is active, where
24+ // the selection is placed at the very end of the doc.
25+ const outerBlockGroupStartPos = 1 ;
26+ const outerBlockGroupEndPos = doc . nodeSize - 2 ;
27+ if ( pos <= outerBlockGroupStartPos ) {
28+ pos = outerBlockGroupStartPos + 1 ;
29+
30+ while (
31+ doc . resolve ( pos ) . parent . type . name !== "blockContainer" &&
32+ pos < outerBlockGroupEndPos
33+ ) {
34+ pos ++ ;
35+ }
36+ } else if ( pos >= outerBlockGroupEndPos ) {
37+ pos = outerBlockGroupEndPos - 1 ;
38+
39+ while (
40+ doc . resolve ( pos ) . parent . type . name !== "blockContainer" &&
41+ pos > outerBlockGroupStartPos
42+ ) {
43+ pos -- ;
44+ }
2745 }
2846
2947 // This gets triggered when a node selection on a block is active, i.e. when
3048 // you drag and drop a block.
31- if ( doc . resolve ( posInBlock ) . parent . type . name === "blockGroup" ) {
32- posInBlock ++ ;
49+ if ( doc . resolve ( pos ) . parent . type . name === "blockGroup" ) {
50+ pos ++ ;
3351 }
3452
35- const $pos = doc . resolve ( posInBlock ) ;
53+ const $pos = doc . resolve ( pos ) ;
3654
3755 const maxDepth = $pos . depth ;
3856 let node = $pos . node ( maxDepth ) ;
3957 let depth = maxDepth ;
4058
4159 while ( true ) {
4260 if ( depth < 0 ) {
43- return undefined ;
61+ throw new Error (
62+ "Could not find blockContainer node. This can only happen if the underlying BlockNote schema has been edited."
63+ ) ;
4464 }
4565
4666 if ( node . type . name === "blockContainer" ) {
0 commit comments