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

Nui popup is not working well #170

Closed
realtica opened this issue Jun 17, 2024 · 4 comments
Closed

Nui popup is not working well #170

realtica opened this issue Jun 17, 2024 · 4 comments
Labels
bug Something isn't working good first issue Good for newcomers

Comments

@realtica
Copy link

realtica commented Jun 17, 2024

Details: Nvim 0.10.0

Hello,

For some info like Global variables the popup works well but for results, only works in split mode.. help me please.

image

@realtica realtica added the sweep label Jun 17, 2024
Copy link
Contributor

sweep-ai bot commented Jun 17, 2024

🚀 Here's the PR! #171

💎 Sweep Pro: You have unlimited Sweep issues

Actions

  • ↻ Restart Sweep

Step 1: 🔎 Searching

(Click to expand) Here are the code search results. I'm now analyzing these search results to write the PR.

local Popup = require('nui.popup')
local event = require('nui.utils.autocmd').event
local Layout = require('nui.layout')
local utils = require('hurl.utils')
local M = {}
local popups = {
bottom = Popup({
border = 'single',
enter = true,
buf_options = { filetype = 'json' },
}),
top = Popup({
border = { style = 'rounded' },
buf_options = { filetype = 'bash' },
}),
}
local layout = Layout(
{
relative = 'editor',
position = _HURL_GLOBAL_CONFIG.popup_position,
size = _HURL_GLOBAL_CONFIG.popup_size,
},
Layout.Box({
Layout.Box(popups.top, { size = {
height = '20%',
} }),
Layout.Box(popups.bottom, { grow = 1 }),
}, { dir = 'col' })
)
-- Show content in a popup
---@param data table
--- - body string
--- - headers table
---@param type 'json' | 'html' | 'text'
M.show = function(data, type)
layout:mount()
-- Close popup when buffer is closed
if _HURL_GLOBAL_CONFIG.auto_close then
for _, popup in pairs(popups) do
popup:on(event.BufLeave, function()
vim.schedule(function()
local current_buffer = vim.api.nvim_get_current_buf()
for _, p in pairs(popups) do
if p.bufnr == current_buffer then
return
end
end
layout:unmount()
end)
end)
end
end
local function quit()
vim.cmd('q')
layout:unmount()
end
-- Map q to quit
popups.top:map('n', 'q', function()
quit()
end)
popups.bottom:map('n', 'q', function()
quit()
end)
-- Map <Ctr-n> to next popup
popups.top:map('n', '<C-n>', function()
vim.api.nvim_set_current_win(popups.bottom.winid)
end)
popups.bottom:map('n', '<C-n>', function()
vim.api.nvim_set_current_win(popups.top.winid)
end)
-- Map <Ctr-p> to previous popup
popups.top:map('n', '<C-p>', function()
vim.api.nvim_set_current_win(popups.bottom.winid)
end)
popups.bottom:map('n', '<C-p>', function()
vim.api.nvim_set_current_win(popups.top.winid)
end)
-- Add headers to the top
local headers_table = utils.render_header_table(data.headers)
-- Hide header block if empty headers
if headers_table.line == 0 then
vim.api.nvim_win_close(popups.top.winid, true)
else
if headers_table.line > 0 then
vim.api.nvim_buf_set_lines(popups.top.bufnr, 0, 1, false, headers_table.headers)
end
end
local content = utils.format(data.body, type)
if not content then
utils.log_info('No content')
return
end
-- Add content to the bottom
vim.api.nvim_buf_set_lines(popups.bottom.bufnr, 0, -1, false, content)
-- Set content to highlight, refer https://github.com/MunifTanjim/nui.nvim/issues/76#issuecomment-1001358770
vim.api.nvim_buf_set_option(popups.bottom.bufnr, 'filetype', type)
end
M.clear = function()
-- Check if popup is open
if not popups.bottom.winid then
return
end
-- Clear the buffer and adding `Processing...` message
vim.api.nvim_buf_set_lines(popups.top.bufnr, 0, -1, false, { 'Processing...' })
vim.api.nvim_buf_set_lines(popups.bottom.bufnr, 0, -1, false, { 'Processing...' })
end
--- Show text in a popup
---@param title string
---@param lines table
---@param bottom? string
---@return any
M.show_text = function(title, lines, bottom)
-- Create a new popup
local text_popup = Popup({
enter = true,
focusable = true,
border = {
style = 'rounded',
text = {
top = title,
top_align = 'center',
bottom = bottom or 'Press `q` to close',
bottom_align = 'left',
},
},
position = '50%',
size = {
width = '50%',
height = '50%',
},
})
text_popup:on('BufLeave', function()
text_popup:unmount()
end, { once = true })
vim.api.nvim_buf_set_lines(text_popup.bufnr, 0, 1, false, lines)
local function quit()
vim.cmd('q')
text_popup:unmount()
end
-- Map q to quit
text_popup:map('n', 'q', function()
quit()
end)
text_popup:mount()
return text_popup
end

local log = require('hurl.vlog')
local git = require('hurl.git_utils')
local util = {}
--- Get the log file path
---@return string
util.get_log_file_path = function()
return log.get_log_file()
end
--- Log info
---@vararg any
util.log_info = function(...)
-- Only save log when debug is on
if not _HURL_GLOBAL_CONFIG.debug then
return
end
log.info(...)
end
--- Log error
---@vararg any
util.log_error = function(...)
-- Only save log when debug is on
if not _HURL_GLOBAL_CONFIG.debug then
return
end
log.error(...)
end
--- Show info notification
---@vararg any
util.notify = function(...)
-- Ignore if the flag is off
if not _HURL_GLOBAL_CONFIG.show_notification then
return
end
vim.notify(...)
end
--- Get visual selection
---@return string[]
util.get_visual_selection = function()
local s_start = vim.fn.getpos("'<")
local s_end = vim.fn.getpos("'>")
local n_lines = math.abs(s_end[2] - s_start[2]) + 1
local lines = vim.api.nvim_buf_get_lines(0, s_start[2] - 1, s_end[2], false)
lines[1] = string.sub(lines[1], s_start[3], -1)
if n_lines == 1 then
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3] - s_start[3] + 1)
else
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3])
end
return lines
end
--- Create tmp file
---@param content any
---@return string|nil
util.create_tmp_file = function(content)
-- create temp file base on pid and datetime
local tmp_file = string.format(
'%s/%s.hurl',
vim.fn.stdpath('cache'),
vim.fn.getpid() .. '-' .. vim.fn.localtime()
)
if not tmp_file then
util.lor_error('hurl: failed to create tmp file')
util.notify('hurl: failed to create tmp file', vim.log.levels.ERROR)
return
end
local f = io.open(tmp_file, 'w')
if not f then
return
end
if type(content) == 'table' then
local c = vim.fn.join(content, '\n')
f:write(c)
else
f:write(content)
end
f:close()
return tmp_file
end
--- Create custom command
---@param cmd string The command name
---@param func function The function to execute
---@param opt table The options
util.create_cmd = function(cmd, func, opt)
opt = vim.tbl_extend('force', { desc = 'hurl.nvim ' .. cmd }, opt or {})
vim.api.nvim_create_user_command(cmd, func, opt)
end
--- Format the body of the request
---@param body string
---@param type 'json' | 'html' | 'text'
---@return string[] | nil
util.format = function(body, type)
local formatters = _HURL_GLOBAL_CONFIG.formatters
or { json = { 'jq' }, html = { 'prettier', '--parser', 'html' } }
-- If no formatter is defined, return the body
if not formatters[type] then
return vim.split(body, '\n')
end
util.log_info('formatting body with ' .. type)
local stdout = vim.fn.systemlist(formatters[type], body)
if vim.v.shell_error ~= 0 then
util.log_error('formatter failed' .. vim.v.shell_error)
util.notify('formatter failed' .. vim.v.shell_error, vim.log.levels.ERROR)
return vim.split(body, '\n')
end
if stdout == nil or #stdout == 0 then
util.log_info('formatter returned empty body')
return vim.split(body, '\n')
end
util.log_info('formatted body: ' .. table.concat(stdout, '\n'))
return stdout
end
--- Render header table
---@param headers table
util.render_header_table = function(headers)
local result = {}
local maxKeyLength = 0
for k, _ in pairs(headers) do
maxKeyLength = math.max(maxKeyLength, #k)
end
local line = 0
for k, v in pairs(headers) do
line = line + 1
if line == 1 then
-- Add header for the table view
table.insert(
result,
string.format('%-' .. maxKeyLength .. 's | %s', 'Header Key', 'Header Value')
)
line = line + 1
end
table.insert(result, string.format('%-' .. maxKeyLength .. 's | %s', k, v))
end
return {
line = line,
headers = result,
}
end
--- Check if the response is json
---@param content_type string
---@return boolean
util.is_json_response = function(content_type)
return string.find(content_type, 'json') ~= nil
end
util.is_html_response = function(content_type)
return string.find(content_type, 'text/html') ~= nil
end
--- Check if nvim is running in nightly or stable version
---@return boolean
util.is_nightly = function()
local is_stable_version = false
if vim.fn.has('nvim-0.11.0') == 1 then
is_stable_version = true
end
return is_stable_version
end
--- Check if a treesitter parser is available
---@param ft string
---@return boolean
local function treesitter_parser_available(ft)
local res, parser = pcall(vim.treesitter.get_parser, 0, ft)
return res and parser ~= nil
end
util.is_hurl_parser_available = treesitter_parser_available('hurl')
-- Looking for vars.env file base on the current file buffer
---@return table
local function find_env_files(file, root_dir, cache_dir, current_file_dir, scan_dir)
local files = {
{
path = root_dir .. '/' .. file,
dest = cache_dir .. '/' .. file,
},
}
-- Scan git root directory and all sub directories with the current file buffer
if git.is_git_repo() then
local git_root = git.get_git_root()
table.insert(files, {
path = git_root .. '/' .. file,
dest = cache_dir .. '/' .. file,
})
local git_root_parts = git.split_path(git_root)
local current_dir_parts = git.split_path(current_file_dir)
local sub_path = git_root
for i = #git_root_parts + 1, #current_dir_parts do
sub_path = sub_path .. '/' .. current_dir_parts[i]
table.insert(files, {
path = sub_path .. '/' .. file,
dest = cache_dir .. '/' .. file,
})
end
end
for _, s in ipairs(scan_dir) do
local dir = root_dir .. s.dir
if vim.fn.isdirectory(dir) == 1 then
table.insert(files, {
path = dir .. '/' .. file,
dest = cache_dir .. '/' .. file,
})
end
end
-- sort by path length, the current buffer file path will be the first
table.sort(files, function(a, b)
return #a.path > #b.path
end)
return files
end
-- Looking for vars.env file base on the current file buffer
---@return table
util.find_env_files_in_folders = function()
local root_dir = vim.fn.expand('%:p:h')
local cache_dir = vim.fn.stdpath('cache')
local current_file_dir = vim.fn.expand('%:p:h:h')
local env_files = {}
local scan_dir = {
{
dir = '/src',
},
{
dir = '/test',
},
{
dir = '/tests',
},
{
dir = '/server',
},
{
dir = '/src/tests',
},
{
dir = '/server/tests',
},
}
for _, file in ipairs(_HURL_GLOBAL_CONFIG.env_file) do
local env_file = find_env_files(file, root_dir, cache_dir, current_file_dir, scan_dir)
vim.list_extend(env_files, env_file)
end
return env_files
end

hurl.nvim/README.md

Lines 1 to 374 in d5cce0b

<h1 align="center">Welcome to hurl.nvim 👋</h1>
<p>
<strong>Hurl.nvim</strong> is a Neovim plugin designed to run HTTP requests directly from `.hurl` files. Elevate your API development workflow by executing and viewing responses without leaving your editor.
</p>
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-8-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
[![IT Man - Effortless APIs with Hurl.nvim: A Developer's Guide to Neovim Tooling [Vietnamese]](https://i.ytimg.com/vi/nr_RbHvnnwk/hqdefault.jpg)](https://www.youtube.com/watch?v=nr_RbHvnnwk)
## Prerequisites
- Neovim stable (0.10.0) or nightly. It might not work with older versions of Neovim.
## Features
- 🚀 Execute HTTP requests directly from `.hurl` files.
- 👁‍🗨 Multiple display modes for API response: popup or split.
- 🌈 Highly customizable through settings.
## Usage
Add the following configuration to your Neovim setup with [lazy.nvim](https://github.com/folke/lazy.nvim):
```lua
{
"jellydn/hurl.nvim",
dependencies = {
"MunifTanjim/nui.nvim",
"nvim-lua/plenary.nvim",
"nvim-treesitter/nvim-treesitter"
},
ft = "hurl",
opts = {
-- Show debugging info
debug = false,
-- Show notification on run
show_notification = false,
-- Show response in popup or split
mode = "split",
-- Default formatter
formatters = {
json = { 'jq' }, -- Make sure you have install jq in your system, e.g: brew install jq
html = {
'prettier', -- Make sure you have install prettier in your system, e.g: npm install -g prettier
'--parser',
'html',
},
},
},
keys = {
-- Run API request
{ "<leader>A", "<cmd>HurlRunner<CR>", desc = "Run All requests" },
{ "<leader>a", "<cmd>HurlRunnerAt<CR>", desc = "Run Api request" },
{ "<leader>te", "<cmd>HurlRunnerToEntry<CR>", desc = "Run Api request to entry" },
{ "<leader>tm", "<cmd>HurlToggleMode<CR>", desc = "Hurl Toggle Mode" },
{ "<leader>tv", "<cmd>HurlVerbose<CR>", desc = "Run Api in verbose mode" },
-- Run Hurl request in visual mode
{ "<leader>h", ":HurlRunner<CR>", desc = "Hurl Runner", mode = "v" },
},
}
```
When configuring nvim-treesitter add `hurl` to the `ensure_installed` list of
parsers.
Simple demo in split mode:
[![Show in split mode](https://i.gyazo.com/19492e8b5366cec3f22d5fd97a63f37a.gif)](https://gyazo.com/19492e8b5366cec3f22d5fd97a63f37a)
> [!NOTE]
> I frequently utilize the nightly version of Neovim, so if you encounter any issues, I recommend trying that version first. I may not have the time to address problems in the stable version. Your contributions via pull requests are always welcome.
## Env File Support: vars.env
`hurl.nvim` seamlessly integrates with environment files named `vars.env` to manage environment variables for your HTTP requests. These environment variables are essential for customizing your requests with dynamic data such as API keys, base URLs, and other configuration values.
### Customization
You can specify the name of the environment file in your `hurl.nvim` configuration. By default, `hurl.nvim` looks for a file named `vars.env`, but you can customize this to any file name that fits your project's structure.
Here's how to set a custom environment file name in your `hurl.nvim` setup:
```lua
require('hurl').setup({
-- Specify your custom environment file name here
env_file = {
'hurl.env',
},
-- Other configuration options...
})
```
### File Location
The plugin searches for a `vars.env` (env_file config) in multiple locations to accommodate various project structures and ensure that environment-specific variables for your HTTP requests are easily accessible. The search occurs in the following order:
1. **Current File's Directory:** The directory where the current file is located. This is particularly useful for projects where environment variables are specific to a particular module or component.
2. **Specific Directories in Project:** The plugin scans predefined directories within the project, which are commonly used for organizing different aspects of a project:
- `src/`: The source code directory.
- `test/` and `tests/`: Directories typically used for test scripts.
- `server/`: If your project includes a server component, this directory is checked.
- `src/tests/` and `server/tests/`: These are checked for environment variables specific to tests within the respective `src` and `server` directories.
3. **Intermediate Directories from Git Root to Current File:** If the project is a git repository, the plugin identifies the root of the repository and then searches for `vars.env` in every directory on the path from this root to the current file's directory. This feature is particularly useful in monorepo setups or large projects, where different modules or packages may have their own environment variables.
By checking these locations, the plugin ensures a comprehensive search for environment variables, catering to a wide range of project structures and setups.
### Swappable environment
To change the environment file name, use the `HurlSetEnvFile` command followed by the new file name. You can have multiple variable files by having comma-separated values.
#### Notes
- Ensure that the new environment file exists in the directories where the plugin searches for it, as outlined in the [File Location](#file-location) section.
- This change will apply globally for the current session of Neovim. If you restart Neovim, it will revert to the default `vars.env` unless you change it again.
## Demo
Check out the following demos to see `hurl.nvim` in action:
### Run a File
Run the entire file by pressing `<leader>A` or run `HurlRunner` command.
[![Run a file in popup mode](https://i.gyazo.com/e554e81788aad910848ff991c9369d7b.gif)](https://gyazo.com/e554e81788aad910848ff991c9369d7b)
### Run a Selection
Select a range of lines and press `<leader>h` to execute the request or run `HurlRunner` command.
[![Run a selection in popup mode](https://i.gyazo.com/1a44dbbf165006fb5744c8f10883bb69.gif)](https://gyazo.com/1a44dbbf165006fb5744c8f10883bb69)
### Run at current line
Place your cursor on a HURL entry and press `<leader>a` or run `HurlRunnerAt` command to execute the entry request.
[![Run at current line in popup mode](https://i.gyazo.com/20efd2cf3f73238bd57e79fc662208b1.gif)](https://gyazo.com/20efd2cf3f73238bd57e79fc662208b1)
#### Verbose mode
Run `HurlVerbose` command to execute the request in verbose mode. The response will be displayed in QuickFix window. This is useful for debugging purposes or getting the curl command from hurl file.
[![Run at current line in verbose mode](https://i.gyazo.com/7d0f709e2db53f8c9e05655347f11bc9.gif)](https://gyazo.com/7d0f709e2db53f8c9e05655347f11bc9)
### Run to entry
Place your cursor on the line you want to run to that entry and press `<leader>te` or run `HurlRunnerToEntry` command to execute the request.
[![Run to entry in split mode](https://i.gyazo.com/14d47adbfcab9e945f89e020b83328a9.gif)](https://gyazo.com/14d47adbfcab9e945f89e020b83328a9)
Note: it's running from start of file to the selected entry and ignore the remaining of the file. It is useful for debugging purposes.
### Toggle Mode
Run `HurlToggleMode` command to toggle between split and popup mode.
[![Toggle mode](https://i.gyazo.com/b36b19ab76524b95015eafe4c6e1c81f.gif)](https://gyazo.com/b36b19ab76524b95015eafe4c6e1c81f)
## HurlSetVariable
The `HurlSetVariable` command allows you to set environment variables for your HTTP requests. This is particularly useful for setting dynamic data such as API keys, base URLs, and other configuration values.
To use this command, type `:HurlSetVariable` followed by the variable name and its value. For example:
```vim
:HurlSetVariable API_KEY your_api_key
```
This will set the `API_KEY` environment variable to `your_api_key`. You can then use this variable in your `.hurl` files like this:
```hurl
GET https://api.example.com
Authorization: Bearer {{API_KEY}}
```
## HurlManageVariable
The `HurlManageVariable` command provides a convenient way to view your environment variables. When you run this command, it opens a new buffer in popup with the current environment variables and their values.
To use this command, simply type `:HurlManageVariable` in the command line:
```vim
:HurlManageVariable
```
The default keymap for this buffer is:
- `q`: Close the buffer
- `e`: Edit the variable
[![Manage variables](https://i.gyazo.com/0492719eb7a14f42cebff6996bde8672.gif)](https://gyazo.com/0492719eb7a14f42cebff6996bde8672)
For now, if you want to modify the global variables, you can do so by using the `HurlSetVariable` command or by editing your `vars.env` file directly.
## HurlShowLastResponse
The `HurlShowLastResponse` command allows you to view the response of your last HTTP request.
```vim
:HurlShowLastResponse
```
## Default Key Mappings
`hurl.nvim` comes with some default key mappings to streamline your workflow:
- `q`: Close the current popup window.
- `<C-n>`: Switch to the next popup window.
- `<C-p>`: Switch to the previous popup window.
These key mappings are active within the popup windows that `hurl.nvim` displays.
## Configuration
`hurl.nvim` can be customized with the following default configurations:
```lua
local default_config = {
-- Toggle debugging information
debug = false, -- If true, logs will be saved at ~/.local/state/nvim/hurl.nvim.log
-- Set the display mode for the response: 'split' or 'popup'
mode = 'split',
-- Split settings
split_position = "right",
split_size = "50%",
-- Popup settings
popup_position = '50%',
popup_size = {
width = 80,
height = 40,
},
-- Default environment file name
env_file = {
'vars.env',
},
-- Specify formatters for different response types
formatters = {
json = { 'jq' }, -- Uses jq to format JSON responses
html = {
'prettier', -- Uses prettier to format HTML responses
'--parser',
'html',
},
},
}
```
To apply these configurations, include them in your Neovim setup like this:
```lua
require('hurl').setup({
debug = true, -- Enable to show detailed logs
mode = 'popup', -- Change to 'popup' to display responses in a popup window
env_file = { 'vars.env' }, -- Change this to use a different environment file name
formatters = {
json = { 'jq' }, -- Customize the JSON formatter command
html = {
'prettier', -- Customize the HTML formatter command
'--parser',
'html',
},
},
})
```
Adjust the settings as per your needs to enhance your development experience with `hurl.nvim`.
### Tips
> [!TIP]
> Enable debug mode with `debug = true` for detailed logs
- Logs are saved at `~/.local/state/nvim/hurl.nvim.log` on macOS.
> [!TIP]
> Split mode with Edgy
- `hurl.nvim` can be used with [edgy.nvim](https://github.com/folke/edgy.nvim) to manage layout when using the split mode.
```lua
right = {
{ title = "Hurl Nvim", size = { width = 0.5 }, ft = "hurl-nvim" },
}
```
> [!TIP]
> Syntax Highlighting in Stable Neovim
- If you're using a stable version of Neovim that doesn't support Hurl syntax highlighting, you can set the filetype to `sh` or `bash` for your `.hurl` files. This will enable basic syntax highlighting that can improve readability. To do this, add the following line to your Neovim configuration:
```vim
autocmd BufRead,BufNewFile *.hurl setfiletype sh
```
For example, here is my [autocmd](https://github.com/jellydn/lazy-nvim-ide/commit/141edf7114839ba7656c4484f852199179c4f11f) for `.hurl` files.
## Resources
[![IT Man - Building and Testing a #Hapi Server with #Hurl: A Step-By-Step Demo [Vietnamese]](https://i.ytimg.com/vi/LP_RXe8cM_s/mqdefault.jpg)](https://www.youtube.com/watch?v=LP_RXe8cM_s)
## Credits
- [Hurl - Run and Test HTTP Requests](https://hurl.dev/)
- Inspired by [ray-x/web-tools.nvim: Neovim plugin for web developers](https://github.com/ray-x/web-tools.nvim)
- Utilize [MunifTanjim/nui.nvim: UI components for Neovim plugins and configurations](https://github.com/MunifTanjim/nui.nvim)
## Author
👤 **Huynh Duc Dung**
- Website: https://productsway.com/
- Twitter: [@jellydn](https://twitter.com/jellydn)
- Github: [@jellydn](https://github.com/jellydn)
## Show your support
If this plugin has been helpful, please give it a ⭐️.
[![kofi](https://img.shields.io/badge/Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white)](https://ko-fi.com/dunghd)
[![paypal](https://img.shields.io/badge/PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://paypal.me/dunghd)
[![buymeacoffee](https://img.shields.io/badge/Buy_Me_A_Coffee-FFDD00?style=for-the-badge&logo=buy-me-a-coffee&logoColor=black)](https://www.buymeacoffee.com/dunghd)
### Star History
[![Star History Chart](https://api.star-history.com/svg?repos=jellydn/hurl.nvim&type=Date)](https://star-history.com/#jellydn/hurl.nvim)
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://productsway.com/"><img src="https://avatars.githubusercontent.com/u/870029?v=4?s=100" width="100px;" alt="Dung Duc Huynh (Kaka)"/><br /><sub><b>Dung Duc Huynh (Kaka)</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=jellydn" title="Code">💻</a> <a href="https://github.com/jellydn/hurl.nvim/commits?author=jellydn" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://cenk.kilic.dev/"><img src="https://avatars.githubusercontent.com/u/26881592?v=4?s=100" width="100px;" alt="Cenk Kılıç"/><br /><sub><b>Cenk Kılıç</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=cenk1cenk2" title="Code">💻</a> <a href="https://github.com/jellydn/hurl.nvim/commits?author=cenk1cenk2" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://www.andrevdm.com"><img src="https://avatars.githubusercontent.com/u/74154?v=4?s=100" width="100px;" alt="Andre Van Der Merwe"/><br /><sub><b>Andre Van Der Merwe</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=andrevdm" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/skoch13"><img src="https://avatars.githubusercontent.com/u/29177689?v=4?s=100" width="100px;" alt="Sergey Kochetkov"/><br /><sub><b>Sergey Kochetkov</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=skoch13" title="Documentation">📖</a> <a href="https://github.com/jellydn/hurl.nvim/commits?author=skoch13" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/rbingham"><img src="https://avatars.githubusercontent.com/u/7032804?v=4?s=100" width="100px;" alt="rbingham"/><br /><sub><b>rbingham</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=rbingham" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://www.allm.net"><img src="https://avatars.githubusercontent.com/u/900716?v=4?s=100" width="100px;" alt="Horacio Sanson"/><br /><sub><b>Horacio Sanson</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=hsanson" title="Code">💻</a> <a href="https://github.com/jellydn/hurl.nvim/commits?author=hsanson" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/bytedaring"><img src="https://avatars.githubusercontent.com/u/4506063?v=4?s=100" width="100px;" alt="xiwang"/><br /><sub><b>xiwang</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=bytedaring" title="Code">💻</a> <a href="https://github.com/jellydn/hurl.nvim/commits?author=bytedaring" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/wenjinnn"><img src="https://avatars.githubusercontent.com/u/30885216?v=4?s=100" width="100px;" alt="wenjin"/><br /><sub><b>wenjin</b></sub></a><br /><a href="https://github.com/jellydn/hurl.nvim/commits?author=wenjinnn" title="Code">💻</a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td align="center" size="13px" colspan="7">
<img src="https://raw.githubusercontent.com/all-contributors/all-contributors-cli/1b8533af435da9854653492b1327a23a4dbd0a10/assets/logo-small.svg">
<a href="https://all-contributors.js.org/docs/en/bot/usage">Add your contributions</a>
</img>
</td>
</tr>
</tfoot>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

local Split = require('nui.split')
local event = require('nui.utils.autocmd').event
local split = Split({
relative = 'editor',
position = _HURL_GLOBAL_CONFIG.split_position,
size = _HURL_GLOBAL_CONFIG.split_size,
})
local utils = require('hurl.utils')
local M = {}
-- Show content in a popup
---@param data table
--- - body string
--- - headers table
---@param type 'json' | 'html' | 'text'
M.show = function(data, type)
-- mount/open the component
split:mount()
-- Create a custom filetype so that we can use https://github.com/folke/edgy.nvim to manage the window
-- E.g: { title = "Hurl Nvim", ft = "hurl-nvim" },
vim.bo[split.bufnr].filetype = 'hurl-nvim'
vim.api.nvim_buf_set_name(split.bufnr, 'hurl-response')
if _HURL_GLOBAL_CONFIG.auto_close then
-- unmount component when buffer is closed
split:on(event.BufLeave, function()
split:unmount()
end)
end
-- Add headers to the top
local headers_table = utils.render_header_table(data.headers)
-- Hide header block if empty headers
if headers_table.line == 0 then
utils.log_info('no headers')
else
if headers_table.line > 0 then
vim.api.nvim_buf_set_lines(split.bufnr, 0, 1, false, headers_table.headers)
end
end
local content = utils.format(data.body, type)
if not content then
utils.log_info('No content')
return
end
-- Add content to the bottom
vim.api.nvim_buf_set_lines(split.bufnr, headers_table.line, -1, false, content)
-- Set content to highlight, refer https://github.com/MunifTanjim/nui.nvim/issues/76#issuecomment-1001358770
-- After 200ms, the highlight will be applied
vim.defer_fn(function()
vim.bo[split.bufnr].filetype = type
-- recomputing foldlevel, this is needed if we setup foldexpr
vim.api.nvim_feedkeys('zx', 'n', true)
end, 200)
local function quit()
-- set buffer name to empty string so it wouldn't conflict when next time buffer opened
vim.api.nvim_buf_set_name(split.bufnr, '')
vim.cmd('q')
split:unmount()
end
split:map('n', 'q', function()
quit()
end)
end
M.clear = function()
-- Check if split is open
if not split.winid then
return
end
-- Clear the buffer and adding `Processing...` message
vim.api.nvim_buf_set_lines(split.bufnr, 0, -1, false, { 'Processing...' })
end

Step 2: ⌨️ Coding

I'm going to follow the following steps to help you solve the GitHub issue:

  1. Investigate why the popup mode is not working properly for displaying API response results.
  2. Fix the issue preventing API responses from being displayed in the popup.
  3. Verify that API responses are displayed properly in the popup after the fix.

Here are the changes we decided to make. I'm done making edits and now I'm just validating the changes using a linter to catch any mistakes like syntax errors or undefined variables:

lua/hurl/popup.lua

Modify the logic for displaying the response headers in the `M.show` function:
--- 
+++ 
@@ -1,10 +1,5 @@
   -- Add headers to the top
   local headers_table = utils.render_header_table(data.headers)
-  -- Hide header block if empty headers
-  if headers_table.line == 0 then
-    vim.api.nvim_win_close(popups.top.winid, true)
-  else
-    if headers_table.line > 0 then
-      vim.api.nvim_buf_set_lines(popups.top.bufnr, 0, 1, false, headers_table.headers)
-    end
+  if headers_table.line > 0 then
+    vim.api.nvim_buf_set_lines(popups.top.bufnr, 0, 1, false, headers_table.headers)
   end

lua/hurl/popup.lua

Modify the logic for displaying the response body in the `M.show` function:
--- 
+++ 
@@ -1,11 +1,8 @@
   local content = utils.format(data.body, type)
-  if not content then
-    utils.log_info('No content')
-    return
-  end
+  if content then
+    -- Add content to the bottom
+    vim.api.nvim_buf_set_lines(popups.bottom.bufnr, 0, -1, false, content)
 
-  -- Add content to the bottom
-  vim.api.nvim_buf_set_lines(popups.bottom.bufnr, 0, -1, false, content)
-
-  -- Set content to highlight, refer https://github.com/MunifTanjim/nui.nvim/issues/76#issuecomment-1001358770
-  vim.api.nvim_buf_set_option(popups.bottom.bufnr, 'filetype', type)
+    -- Set content to highlight
+    vim.api.nvim_buf_set_option(popups.bottom.bufnr, 'filetype', type)
+  end

Step 3: 🔄️ Validating

Your changes have been successfully made to the branch sweep/nui_popup_is_not_working_well. I have validated these changes using a syntax checker and a linter.


Tip

To recreate the pull request, edit the issue title or description.

This is an automated message generated by Sweep AI.

@realtica realtica changed the title Nui popup not working well Nui popup is not working well Jun 17, 2024
@jellydn
Copy link
Owner

jellydn commented Jun 18, 2024

Thanks @realtica I will take a look on this issue sometime this week.

@jellydn jellydn added bug Something isn't working and removed sweep labels Jun 18, 2024
@jellydn
Copy link
Owner

jellydn commented Jun 22, 2024

Hi @realtica Could you help me to reproduce this issue? I tried but it's fine on my end.

  • What is your config?
  • Could you record video or write the reproduce steps?

@jellydn jellydn added the good first issue Good for newcomers label Jun 22, 2024
@jellydn
Copy link
Owner

jellydn commented Jul 24, 2024

Fixed with my latest commit.

@jellydn jellydn closed this as completed Jul 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working good first issue Good for newcomers
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants