Skip to content

Commit

Permalink
Merge pull request #43 from grapp-dev/fix/prompt-value
Browse files Browse the repository at this point in the history
fix: display the initial value of the Prompt component correctly
  • Loading branch information
mobily authored May 4, 2024
2 parents b3e740a + 205677d commit 295c73b
Showing 1 changed file with 31 additions and 8 deletions.
39 changes: 31 additions & 8 deletions lua/nui-components/prompt.lua
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ local Text = require("nui.text")
local TextInput = require("nui-components.text-input")
local fn = require("nui-components.utils.fn")

local Prompt = TextInput:extend("Gap")
local Prompt = TextInput:extend("Prompt")

function Prompt:init(props, popup_options)
Prompt.super.init(
Expand Down Expand Up @@ -37,30 +37,38 @@ end
function Prompt:_attach_change_listener()
local props = self:get_props()

self._private.once = true

vim.api.nvim_buf_attach(self.bufnr, false, {
on_lines = self:if_not_mounting_phase_wrap(function()
local prefix_length = self._private.prefix:length()
local value_with_prompt = vim.api.nvim_buf_get_lines(self.bufnr, 0, 1, false)[1]

local lines = vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false)
local value_with_prompt = table.concat(lines, "")
local value = string.sub(value_with_prompt, prefix_length + 1)

self:set_current_value(value)
props.on_change(value, self)
if not self._private.once then
self:set_current_value(value)
props.on_change(value, self)
end

self:_update_placeholder()

if prefix_length > 0 then
if prefix_length > 0 and self._private.once then
vim.schedule(function()
self._private.prefix:highlight(self.bufnr, self.ns_id, 1, 0)
self._private.once = false
end)
end
end),
})
end

function Prompt:on_renderer_initialization(...)
Prompt.super.on_renderer_initialization(self, ...)

function Prompt:on_mount()
local props = self:get_props()

Prompt.super.on_mount(self)

local function is_nui_text(value)
return value.class and value.class.name == "NuiText"
end
Expand All @@ -69,6 +77,21 @@ function Prompt:on_renderer_initialization(...)
vim.fn.prompt_setprompt(self.bufnr, self._private.prefix:content())
end

function Prompt:on_update()
local mode = vim.fn.mode()
local current_winid = vim.api.nvim_get_current_win()

if not (current_winid == self.winid and mode == "i") then
vim.schedule(function()
if self:is_first_render() then
local value = table.concat(self:get_lines(), "")
vim.api.nvim_feedkeys(value, "n", true)
vim.api.nvim_win_set_cursor(self.winid, { 1, #value })
end
end)
end
end

function Prompt:mappings()
local props = self:get_props()

Expand Down

0 comments on commit 295c73b

Please sign in to comment.