Skip to content

Commit

Permalink
feat: extmark-based placeholder for text inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
willothy committed Mar 28, 2024
1 parent ca7d5fc commit 2597173
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lua/nui-components/prompt.lua
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ function Prompt:_attach_change_listener()
self:set_current_value(value)
props.on_change(value, self)

self:_update_placeholder(self:get_current_value() == "")

if prefix_length > 0 then
vim.schedule(function()
self._private.prefix:highlight(self.bufnr, self.ns_id, 1, 0)
Expand Down
33 changes: 33 additions & 0 deletions lua/nui-components/text-input.lua
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ function TextInput:init(props, popup_options)
autoresize = false,
max_lines = nil,
value = "",
placeholder = "",
on_change = fn.ignore,
border_style = "rounded",
}, props)
Expand Down Expand Up @@ -52,9 +53,38 @@ function TextInput:prop_types()
autoresize = { "boolean", "nil" },
wrap = { "boolean", "nil" },
filetype = { "string", "nil" },
placeholder = { "string", "table", "nil" },
}
end

function TextInput:_update_placeholder(show)
local props = self:get_props()
local placeholder = props.placeholder
if show and placeholder and placeholder ~= "" then
local virt_text
if type(placeholder) == "table" then
if type(placeholder[1]) == "table" then
-- multiple virt-text chunks
virt_text = placeholder
else
-- single virt-text chunk
virt_text = { placeholder }
end
else
-- string
virt_text = { { placeholder, "Comment" } }
end
self._private.placeholder_extmark = vim.api.nvim_buf_set_extmark(self.bufnr, self.ns_id, 0, 0, {
virt_text = virt_text,
virt_text_pos = "inline",
id = self._private.placeholder_extmark,
})
elseif self._private.placeholder_extmark then
vim.api.nvim_buf_del_extmark(self.bufnr, self.ns_id, self._private.placeholder_extmark)
self._private.placeholder_extmark = nil
end
end

function TextInput:_attach_change_listener()
local props = self:get_props()

Expand All @@ -66,6 +96,8 @@ function TextInput:_attach_change_listener()
self:set_current_value(value)
props.on_change(value, self)

self:_update_placeholder(self:get_current_value() == "")

if props.autoresize then
self._private.text_input_signal.size = math.max(#lines, self._private.text_input_initial_size)
end
Expand Down Expand Up @@ -184,6 +216,7 @@ end

function TextInput:on_mount()
self:_attach_change_listener()
self:_update_placeholder(self:get_current_value() == "")
end

return TextInput

0 comments on commit 2597173

Please sign in to comment.