import dedent from "dedent"
import { describe, it, expect, beforeAll } from "vitest"
import { Position, MarkupKind, Range } from "vscode-languageserver/node"
import { TextDocument } from "vscode-languageserver-textdocument"
import { HoverProvider } from "../src/hover_provider"
import type { FrameworkOptions } from "../src/types"
import { ParserService } from "../src/parser_service"
import { Herb } from "@herb-tools/node-wasm"
import type { ParseOptions, ParseResult } from "@herb-tools/core"
describe("herb state hover", () => {
let service: HoverProvider
beforeAll(async () => {
await Herb.load()
service = new HoverProvider(new ParserService(Herb))
})
function hover(content: string, line: number, character: number): string {
const document = TextDocument.create("file:///test.html.erb", "erb", 1, content)
const result = service.getHover(document, Position.create(line, character))
const contents = result?.contents
return contents && typeof contents === "object" && "value" in contents ? contents.value : ""
}
const TEMPLATE =
'<%# herb:state (pending: false, attempts: 0) %>\n' +
"<% @items.each do |item| %>\n" +
' <%# herb:state (locked: true) %>\n' +
'
<%= locked %>
\n' +
"<% end %>\n" +
"
<%= pending? %>
\n" +
''
it("documents a boolean state from a read", () => {
const value = hover(TEMPLATE, 5, 9)
expect(value).toContain("**pending** · Herb Client State")
expect(value).toContain("`boolean` · default `false` · one value per rendering")
expect(value).toContain("```erb")
expect(value).toContain("<%= pending %>")
expect(value).toContain('data-herb-toggle="pending"')
expect(value).toContain('stateFor(element).set({ pending: true })')
expect(value).toContain('<% if pending? %>')
})
it("documents an item state with its loop scope", () => {
const value = hover(TEMPLATE, 3, 10)
expect(value).toContain("**locked** · Herb Client State")
expect(value).toContain("one value for each `item`")
})
it("documents an integer state from an action attribute", () => {
const value = hover(TEMPLATE, 6, 30)
expect(value).toContain("**attempts** · Herb Client State")
expect(value).toContain("`integer` · default `0` · one value per rendering")
expect(value).toContain('data-herb-increment="attempts"')
expect(value).toContain('<% if attempts == 0 %>')
})
it("scopes the hover range to the state token inside an attribute", () => {
const document = TextDocument.create("file:///test.html.erb", "erb", 1, TEMPLATE)
const result = service.getHover(document, Position.create(6, 30))
expect(document.getText(result?.range)).toBe("attempts")
})
it("documents a state inside a tag helper's data hash", () => {
const content =
'<%# herb:state (draft: "") %>\n' +
'<%= tag.button data: { herb_set: "click->draft=abc" } do %>\n' +
" a\n" +
"<% end %>"
const value = hover(content, 1, content.split("\n")[1].indexOf("draft"))
expect(value).toContain("**draft** · Herb Client State")
})
it("documents the herb:state directive keyword", () => {
const value = hover(TEMPLATE, 0, 6)
expect(value).toContain("**herb:state** · Herb directive")
expect(value).toContain("strict-locals signature")
})
it("documents herb:slots and herb:key", () => {
const content = "<%# herb:slots client %>\n<% @items.each do |item| %><%# herb:key item %>
<%= item %>
<% end %>"
expect(hover(content, 0, 8)).toContain("**herb:slots** · Herb directive")
expect(hover(content, 1, 35)).toContain("**herb:key** · Herb directive")
})
function hoverAt(content: string, needle: string, shift = 0): string {
const document = TextDocument.create("file:///test.html.erb", "erb", 1, content)
const result = service.getHover(document, document.positionAt(content.indexOf(needle) + shift))
const contents = result?.contents
return contents && typeof contents === "object" && "value" in contents ? contents.value : ""
}
it("says a literal state is owned by the client", () => {
const value = hoverAt('<%# herb:state (draft: "") %>\n<%= draft %>', "draft:")
expect(value).toContain("**Owned by the client.** The server renders the default, and the client updates every read in place from then on.")
})
it("says a state with a Ruby default is seeded by the server", () => {
const value = hoverAt("<%# herb:state (total: @items.size) %>\n<%= total %>", "total:")
expect(value).toContain("**Seeded by the server.** The server evaluates `@items.size` on each render and hands the result to the client, which owns the value from then on.")
})
it("says a derived state is recomputed on the client from its sources", () => {
const value = hoverAt('<%# herb:state (draft: "", empty: draft == "") %>\n<%= empty %>', "empty:")
expect(value).toContain("**Derived on the client.** The client recomputes it from `draft` whenever that changes. Nothing sets it directly.")
})
it("lists the derived states and server values that depend on a state", () => {
const content =
'<%# herb:state (q: "", empty: q == "") %>\n' +
"
<%= User.search(q).count %>
\n" +
"<% @messages.search(q).each do |message| %><%= message %><% end %>"
const value = hoverAt(content, "q:")
expect(value).toContain("The server recomputes `User.search(q).count` and `@messages.search(q).each` when it changes.")
expect(value).toContain("The derived state `empty` follows it on the client.")
})
it("says a plain read is evaluated on the client", () => {
const value = hoverAt('<%# herb:state (draft: "") %>\n
<%= draft %>
', "<%= draft", 4)
expect(value).toContain("**Evaluated on the client.** This read updates in place when `draft` changes, with no request to the server.")
expect(value).not.toContain("The server recomputes")
})
it("says a predicate read is evaluated on the client", () => {
const value = hoverAt('<%# herb:state (draft: "") %>\n<% if draft.blank? %>a<% end %>', "draft.blank")
expect(value).toContain("**Evaluated on the client.** `draft.blank?` updates in place when `draft` changes, with no request to the server.")
})
it("says the condition of a ternary is evaluated on the client", () => {
const value = hoverAt('<%# herb:state (open: false) %>\n
<%= open ? "on" : "off" %>
', "open ?")
expect(value).toContain("**Evaluated on the client.** This read updates in place when `open` changes, with no request to the server.")
})
it("says server Ruby reading a state is computed on the server", () => {
const value = hoverAt('<%# herb:state (q: "") %>\n
<%= User.search(q).count %>
', "(q)", 1)
expect(value).toContain("**Computed on the server, depends on client state.** `User.search(q).count` is server Ruby, so the client asks the server for a fresh value when `q` changes.")
})
it("says a collection reading a state is computed on the server", () => {
const value = hoverAt('<%# herb:state (q: "") %>\n<% @messages.search(q).each do |message| %><%= message %><% end %>', "(q)", 1)
expect(value).toContain("**Computed on the server, depends on client state.** `@messages.search(q).each` is server Ruby")
})
it("says a server read of an item state is not resolvable", () => {
const content =
"<% @items.each do |item| %>\n" +
" <%# herb:key item.id %>\n" +
" <%# herb:state (count: 0) %>\n" +
"
<%= item.price * count %>
\n" +
"<% end %>"
const value = hoverAt(content, "* count", 2)
expect(value).toContain("**Not resolvable.** `item.price * count` needs server Ruby, and `count` lives on an item.")
})
it("says a condition that needs server Ruby is not resolvable", () => {
const value = hoverAt('<%# herb:state (q: "") %>\n<% if User.search(q).any? %>a<% end %>', "(q)", 1)
expect(value).toContain("**Not resolvable.** `User.search(q).any?` needs server Ruby to pick a branch, and the client picks branches on its own.")
})
it("says an action attribute writes the state on the client", () => {
const value = hoverAt('<%# herb:state (open: false) %>\n', '"open"', 1)
expect(value).toContain("**Written by the client.** This action attribute sets the state in the browser, with no request to the server.")
})
it("says a Float default is not a valid state", () => {
const value = hoverAt("<%# herb:state (ratio: 0.5) %>\n<%= ratio %>", "ratio:")
expect(value).toContain("`float` · default `0.5`")
expect(value).toContain("**Not a valid state.** Herb refuses `0.5` as a state default, so it never reaches the client.")
expect(value).not.toContain("Example usage")
})
it("says nothing for a block parameter named like a state", () => {
const content = "<%# herb:state (item: 0) %>\n<% @items.each do |item| %><%= item %><% end %>"
expect(hoverAt(content, "|item|", 1)).toBe("")
expect(hoverAt(content, "<%= item", 4)).toBe("")
expect(hoverAt(content, "item:")).toContain("**item** · Herb Client State")
})
it("says nothing for a plain local", () => {
const content = "<%# locals: (title:) %>\n
<%= title %>
"
expect(hover(content, 1, 9)).toBe("")
})
})
describe("HoverProvider", () => {
let parserService: ParserService
let service: HoverProvider
beforeAll(async () => {
await Herb.load()
parserService = new ParserService(Herb)
service = new HoverProvider(parserService)
})
function createDocument(content: string): TextDocument {
return TextDocument.create("file:///test.html.erb", "erb", 1, content)
}
function getHover(content: string, line: number, character: number, options: FrameworkOptions = { framework: "actionview" }) {
const document = createDocument(content)
return service.getHover(document, Position.create(line, character), options)
}
function hoverValue(content: string, line: number, character: number): string {
const hover = getHover(content, line, character)
return (hover!.contents as { value: string }).value
}
function hoverRange(content: string, line: number, character: number): Range {
const hover = getHover(content, line, character)
return hover!.range!
}
describe("tag.* helpers", () => {
it("shows hover for tag.div with block", () => {
const content = dedent`
<%= tag.div do %>
Content
<% end %>
`
const hover = getHover(content, 0, 5)
expect(hover).not.toBeNull()
expect(hover!.contents).toHaveProperty("kind", MarkupKind.Markdown)
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
tag.(content = nil, **options, &block)
\`\`\`
Returns an HTML5 compliant tag with a tag proxy. Every tag can be built with \`tag.(optional content, options)\`. Supports \`data-*\` and \`aria-*\` attributes via nested hashes. Sub-attributes are dasherized. Respects HTML5 void elements.
**HTML equivalent**
\`\`\`erb
Content
\`\`\`
[ActionView::Helpers::TagHelper#tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 11,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
})
it("shows hover for tag.div with attributes", () => {
const content = '<%= tag.div class: "container" do %><% end %>'
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
tag.(content = nil, **options, &block)
\`\`\`
Returns an HTML5 compliant tag with a tag proxy. Every tag can be built with \`tag.(optional content, options)\`. Supports \`data-*\` and \`aria-*\` attributes via nested hashes. Sub-attributes are dasherized. Respects HTML5 void elements.
**HTML equivalent**
\`\`\`erb
\`\`\`
[ActionView::Helpers::TagHelper#tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 11,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
})
it("shows hover for tag.p with content argument", () => {
const content = '<%= tag.p "Hello" %>'
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
tag.(content = nil, **options, &block)
\`\`\`
Returns an HTML5 compliant tag with a tag proxy. Every tag can be built with \`tag.(optional content, options)\`. Supports \`data-*\` and \`aria-*\` attributes via nested hashes. Sub-attributes are dasherized. Respects HTML5 void elements.
**HTML equivalent**
\`\`\`erb
Hello
\`\`\`
[ActionView::Helpers::TagHelper#tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 9,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
})
})
describe("content_tag", () => {
it("shows hover for content_tag with block", () => {
const content = '<%= content_tag :div do %><% end %>'
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
\`\`\`
Returns an HTML block tag of type name surrounding the content. Add HTML attributes by passing an attributes hash to options. Instead of passing the content as an argument, you can also use a block. This is legacy syntax; see the \`tag\` method for the modern equivalent.
**HTML equivalent**
\`\`\`erb
\`\`\`
[ActionView::Helpers::TagHelper#content_tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 15,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
})
it("shows hover for content_tag with content argument", () => {
const content = '<%= content_tag :div, "Hello" %>'
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
\`\`\`
Returns an HTML block tag of type name surrounding the content. Add HTML attributes by passing an attributes hash to options. Instead of passing the content as an argument, you can also use a block. This is legacy syntax; see the \`tag\` method for the modern equivalent.
**HTML equivalent**
\`\`\`erb
Hello
\`\`\`
[ActionView::Helpers::TagHelper#content_tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 15,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
})
})
describe("link_to", () => {
it("shows hover for link_to", () => {
const content = '<%= link_to "Home", root_path %>'
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
link_to(name = nil, options = nil, html_options = nil, &block)
\`\`\`
Creates an anchor element of the given name using a URL created by the set of options. It is also possible to pass a String instead of an options hash, which generates an anchor element that uses the value of the String as the href for the link. If \`nil\` is passed as the name the value of the link itself will become the name.
**HTML equivalent**
\`\`\`erb
Home
\`\`\`
[ActionView::Helpers::UrlHelper#link_to](https://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 11,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
})
})
describe("hover range targets method name only", () => {
it("only triggers hover on the method name for link_to", () => {
const content = '<%= link_to "Home", root_path %>'
expect(getHover(content, 0, 3)).toBeNull()
expect(getHover(content, 0, 12)).toBeNull()
expect(getHover(content, 0, 4)).not.toBeNull()
expect(getHover(content, 0, 11)).not.toBeNull()
})
it("only triggers hover on the method name for tag.div", () => {
const content = '<%= tag.div do %><% end %>'
expect(getHover(content, 0, 3)).toBeNull()
expect(getHover(content, 0, 12)).toBeNull()
expect(getHover(content, 0, 4)).not.toBeNull()
expect(getHover(content, 0, 11)).not.toBeNull()
})
it("only triggers hover on the method name for content_tag", () => {
const content = '<%= content_tag :div do %><% end %>'
expect(getHover(content, 0, 3)).toBeNull()
expect(getHover(content, 0, 16)).toBeNull()
expect(getHover(content, 0, 4)).not.toBeNull()
expect(getHover(content, 0, 15)).not.toBeNull()
})
})
describe("nested elements", () => {
it("shows hover for each nested method name independently", () => {
const content = dedent`
<%= link_to "Devices", sessions_path do %>
<%= tag.div class: "hello" %>
<% end %>
`
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
link_to(name = nil, options = nil, html_options = nil, &block)
\`\`\`
Creates an anchor element of the given name using a URL created by the set of options. It is also possible to pass a String instead of an options hash, which generates an anchor element that uses the value of the String as the href for the link. If \`nil\` is passed as the name the value of the link itself will become the name.
**HTML equivalent**
\`\`\`erb
...
\`\`\`
[ActionView::Helpers::UrlHelper#link_to](https://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 11,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
expect(hoverValue(content, 1, 6)).toMatchInlineSnapshot(`
"\`\`\`ruby
tag.(content = nil, **options, &block)
\`\`\`
Returns an HTML5 compliant tag with a tag proxy. Every tag can be built with \`tag.(optional content, options)\`. Supports \`data-*\` and \`aria-*\` attributes via nested hashes. Sub-attributes are dasherized. Respects HTML5 void elements.
**HTML equivalent**
\`\`\`erb
\`\`\`
[ActionView::Helpers::TagHelper#tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag) · Action View"
`)
expect(hoverRange(content, 1, 6)).toMatchInlineSnapshot(`
{
"end": {
"character": 13,
"line": 1,
},
"start": {
"character": 6,
"line": 1,
},
}
`)
})
it("does not show hover on body content between nested elements", () => {
const content = dedent`
<%= link_to "Devices", sessions_path do %>
some text
<% end %>
`
expect(getHover(content, 1, 5)).toBeNull()
})
it("shows shallow output with expandable details for deeply nested elements", () => {
const content = dedent`
<%= link_to "Devices", sessions_path do %>
<%= tag.div class: "hello" do %>
<%= content_tag :div, "Inner" %>
<% end %>
<% end %>
`
expect(hoverValue(content, 0, 5)).toMatchInlineSnapshot(`
"\`\`\`ruby
link_to(name = nil, options = nil, html_options = nil, &block)
\`\`\`
Creates an anchor element of the given name using a URL created by the set of options. It is also possible to pass a String instead of an options hash, which generates an anchor element that uses the value of the String as the href for the link. If \`nil\` is passed as the name the value of the link itself will become the name.
**HTML equivalent**
\`\`\`erb
...
\`\`\`
[ActionView::Helpers::UrlHelper#link_to](https://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) · Action View"
`)
expect(hoverRange(content, 0, 5)).toMatchInlineSnapshot(`
{
"end": {
"character": 11,
"line": 0,
},
"start": {
"character": 4,
"line": 0,
},
}
`)
expect(hoverValue(content, 1, 6)).toMatchInlineSnapshot(`
"\`\`\`ruby
tag.(content = nil, **options, &block)
\`\`\`
Returns an HTML5 compliant tag with a tag proxy. Every tag can be built with \`tag.(optional content, options)\`. Supports \`data-*\` and \`aria-*\` attributes via nested hashes. Sub-attributes are dasherized. Respects HTML5 void elements.
**HTML equivalent**
\`\`\`erb
...
\`\`\`
[ActionView::Helpers::TagHelper#tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag) · Action View"
`)
expect(hoverRange(content, 1, 6)).toMatchInlineSnapshot(`
{
"end": {
"character": 13,
"line": 1,
},
"start": {
"character": 6,
"line": 1,
},
}
`)
expect(hoverValue(content, 2, 8)).toMatchInlineSnapshot(`
"\`\`\`ruby
content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
\`\`\`
Returns an HTML block tag of type name surrounding the content. Add HTML attributes by passing an attributes hash to options. Instead of passing the content as an argument, you can also use a block. This is legacy syntax; see the \`tag\` method for the modern equivalent.
**HTML equivalent**
\`\`\`erb
Inner
\`\`\`
[ActionView::Helpers::TagHelper#content_tag](https://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag) · Action View"
`)
expect(hoverRange(content, 2, 8)).toMatchInlineSnapshot(`
{
"end": {
"character": 19,
"line": 2,
},
"start": {
"character": 8,
"line": 2,
},
}
`)
})
})
describe("ERB helper hover (unsupported helpers)", () => {
it("shows hover for csp_meta_tag", () => {
expect(hoverValue("<%= csp_meta_tag %>", 0, 6)).toMatchInlineSnapshot(`
"\`\`\`ruby
csp_meta_tag(**options)
\`\`\`
Returns a \`\` tag \`"csp-nonce"\` with the per-session nonce value for allowing inline \`