1- import { Decoration } from '@codemirror/view' ;
2- import { Range } from '@codemirror/state' ;
1+ import { BlockWrapper , Decoration } from '@codemirror/view' ;
2+ import { Range , RangeValue } from '@codemirror/state' ;
33import { syntaxTree } from '@codemirror/language' ;
44import { SyntaxNodeRef } from '@lezer/common' ;
55import { WidgetView } from '../views/types' ;
66import { lineDecoRanges } from '../helper' ;
77
8+ /**
9+ * Build block wrappers by leveraging language lexers.
10+ *
11+ * @param nodeName Node name(s), such as "CodeBlock" for code blocks
12+ * @param className Class to decorate the node
13+ */
14+ export function createBlockWrappers ( nodeName : string | string [ ] , className : string , attributes ?: { [ key : string ] : string } ) {
15+ return BlockWrapper . set ( createNodeRanges ( nodeName , node => BlockWrapper . create ( {
16+ tagName : 'div' ,
17+ attributes : {
18+ 'class' : className ,
19+ ...attributes ,
20+ } ,
21+ } ) . range ( node . from , node . to ) ) ) ;
22+ }
23+
824/**
925 * Create mark decorations.
1026 *
@@ -53,8 +69,18 @@ export function createLineDeco(nodeName: string | string[], className: string, a
5369 * @param builder Closure to create the Decoration(s)
5470 */
5571export function createDecos ( nodeName : string | string [ ] , builder : ( node : SyntaxNodeRef ) => Range < Decoration > | Range < Decoration > [ ] | null ) {
72+ return Decoration . set ( createNodeRanges ( nodeName , builder ) ) ;
73+ }
74+
75+ /**
76+ * Build generic node ranges by leveraging language lexers.
77+ *
78+ * @param nodeName Node name(s), such as "ATXHeading1" for headings
79+ * @param builder Closure to create the range(s)
80+ */
81+ function createNodeRanges < T extends RangeValue > ( nodeName : string | string [ ] , builder : ( node : SyntaxNodeRef ) => Range < T > | Range < T > [ ] | null ) {
5682 const editor = window . editor ;
57- const ranges : Range < Decoration > [ ] = [ ] ;
83+ const ranges : Range < T > [ ] = [ ] ;
5884 const nodeNames = Array . isArray ( nodeName ) ? nodeName : [ nodeName ] ;
5985
6086 for ( const { from, to } of editor . visibleRanges ) {
@@ -69,5 +95,5 @@ export function createDecos(nodeName: string | string[], builder: (node: SyntaxN
6995 } ) ;
7096 }
7197
72- return Decoration . set ( ranges . sort ( ( lhs , rhs ) => lhs . from - rhs . from ) ) ;
98+ return ranges . sort ( ( lhs , rhs ) => lhs . from - rhs . from ) ;
7399}
0 commit comments