1- local J = {
2- comment = ' {/*%s*/}' ,
3- }
1+ --- @mod comment.jsx JSX Integration
2+ --- @brief [[
3+ --- This module provides the jsx/tsx comment integration via `pre_hook`. The default
4+ --- treesitter integration doesn't provides tsx/jsx support as the syntax is weird
5+ --- enough to deserve its own module. Besides that not everyone is using jsx/tsx
6+ --- so it's better make it an ad-hoc integration.
7+ --- @brief ]]
8+
9+ local jsx = {}
410
511local query = [[
12+ ;; query
613 (jsx_opening_element [(jsx_attribute) (comment)] @nojsx)
714
815 (jsx_self_closing_element [(jsx_attribute) (comment)] @nojsx)
3845--- @param q table
3946--- @param tree table
4047--- @param parser table
41- --- @param range CRange
48+ --- @param range CommentRange
4249--- @return table
4350local function normalize (q , tree , parser , range )
4451 local prev , section , sections = nil , 0 , {}
7178
7279--- Runs the query and returns the commentstring by checking the cursor range
7380--- @param parser table
74- --- @param range CRange
81+ --- @param range CommentRange
7582--- @return boolean
7683local function capture (parser , range )
7784 local lang = parser :lang ()
7885
7986 if not is_jsx (lang ) then
80- return
87+ return false
8188 end
8289
8390 local Q = vim .treesitter .query .parse_query (lang , query )
@@ -105,10 +112,20 @@ local function capture(parser, range)
105112 return Q .captures [id ] == ' jsx'
106113end
107114
108- --- Calculates the `jsx` commentstring
109- --- @param ctx Ctx
110- --- @return string ?
111- function J .calculate (ctx )
115+ --- Static |commentstring| for jsx/tsx
116+ --- @type string
117+ jsx .commentstring = ' {/*%s*/}'
118+
119+ --- Calculates the `jsx/tsx` commentstring using |treesitter|
120+ --- @param ctx CommentCtx
121+ --- @return string ? _ jsx /tsx commenstring
122+ --- @see comment.utils.CommentCtx
123+ --- @usage [[
124+ --- require('Comment').setup({
125+ --- pre_hook = require('Comment.jsx').calculate
126+ --- })
127+ --- @usage ]]
128+ function jsx .calculate (ctx )
112129 local buf = vim .api .nvim_get_current_buf ()
113130 local filetype = vim .api .nvim_buf_get_option (buf , ' filetype' )
114131
@@ -132,12 +149,12 @@ function J.calculate(ctx)
132149 -- This is for `markdown` which embeds multiple `tsx` blocks
133150 for _ , child in pairs (tree :children ()) do
134151 if child :contains (range ) and capture (child , ctx .range ) then
135- return J . comment
152+ return jsx . commentstring
136153 end
137154 end
138155
139156 -- This is for `tsx` itself
140- return (tree :contains (range ) and capture (tree , ctx .range )) and J . comment
157+ return (tree :contains (range ) and capture (tree , ctx .range )) and jsx . commentstring or nil
141158end
142159
143- return J
160+ return jsx
0 commit comments