Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jsx #133

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft

jsx #133

Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
2st draft
  • Loading branch information
numToStr committed Nov 17, 2023
commit 5541a4ff0e192dec497079e4fb2434bd12e6a318
2 changes: 2 additions & 0 deletions a.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const Yoo = () => {
<section>
<p>hello</p>
<p
he="llo"
wor="ld"
attr={{
...window,
hello: () => {
Expand Down
41 changes: 23 additions & 18 deletions lua/Comment/jsx.lua
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
local J = {
comment = '{/*%s*/}',
valid = { 'jsx_element', 'jsx_fragment', 'jsx_text', '<', '>' },
}

local query = [[
(parenthesized_expression
[(jsx_fragment) (jsx_element)] @jsx)

(return_statement
[(jsx_fragment) (jsx_element)] @jsx)
]]

local function is_jsx(lang)
local function is_jsx_tree(lang)
-- Name of the treesitter parsers that supports jsx syntax
return lang == 'tsx' or lang == 'javascript'
end

local function is_jsx_node(node)
if not node then
return false
end
return vim.tbl_contains(J.valid, node:type())
end

local function capture(child, range)
local lang = child:lang()

if not is_jsx(lang) then
local rng = {
range.srow - 1,
range.scol,
range.erow - 1,
range.ecol,
}

if not (is_jsx_tree(lang) and child:contains(rng)) then
return
end

local Q = vim.treesitter.query.parse_query(lang, query)

for _, tree in ipairs(child:trees()) do
for _, node in Q:iter_captures(tree:root(), child:source()) do
local srow, _, erow = node:range()
-- Why subtracting 2?
-- 1. Lua indexes starts from 1
-- 2. Removing the `return` keyword from the range
if srow <= range.srow - 2 and erow >= range.erow then
local root = tree:root()
local node = root:descendant_for_range(unpack(rng))
local srow, _, erow = node:range()
if srow <= range.srow - 1 and erow >= range.erow - 1 then
local nxt, prev = node:next_sibling(), node:prev_sibling()
if is_jsx_node(prev) or is_jsx_node(node) or is_jsx_node(nxt) then
return J.comment
end
end
Expand Down