Compare commits

..

10 Commits

Author SHA1 Message Date
Julian Freeman
bf9f08788e fix 3 2026-04-19 09:27:58 -04:00
Julian Freeman
f9a4c0e64a fix 2 2026-04-19 09:14:26 -04:00
Julian Freeman
e256e596c5 fix 1 2026-04-19 09:04:12 -04:00
Julian Freeman
eb1d802f5b fix history restore 2025-12-01 11:10:08 -04:00
Julian Freeman
4d20f2075f improve response panel 2025-12-01 11:03:12 -04:00
Julian Freeman
8fc4dbbf93 modify sidebar 2025-12-01 10:39:35 -04:00
Julian Freeman
d6dda10d2f fix settings select 2025-12-01 09:49:56 -04:00
Julian Freeman
c5d82a710d custom select 2025-12-01 09:35:42 -04:00
Julian Freeman
4f6c9f87e7 change icon 2025-12-01 09:28:35 -04:00
Julian Freeman
c2cf6fd644 fix font family settings 2025-12-01 09:03:01 -04:00
73 changed files with 1076 additions and 264 deletions

View File

@@ -1,7 +1,7 @@
# Tauri + Vue + TypeScript # LiteRequest
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more. A simple REST API client.
## Recommended IDE Setup Generated by Gemini CLI.
- [VS Code](https://code.visualstudio.com/) + [Vue - Official](https://marketplace.visualstudio.com/items?itemName=Vue.volar) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) App icon from https://iconarchive.com

BIN
app-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

View File

@@ -2,9 +2,8 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri + Vue + Typescript App</title> <title>LiteRequest</title>
</head> </head>
<body> <body>

View File

@@ -1,6 +0,0 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

67
spec/feat-history-ui.md Normal file
View File

@@ -0,0 +1,67 @@
# Feature Upgrade: History UI Overhaul
**Context:**
We are polishing the "Sidebar" component of the "LiteRequest" application.
**Goal:** Improve the information density of the History list and add management features (Delete/Clear All).
## 1. UI/UX Changes
### 1.1 History Item Layout (Sidebar.vue)
* **Current State:** Shows Method, URL, and Timestamp.
* **New Layout:**
* **Remove:** Completely remove the Date/Time display to save space.
* **Flex Row:** The item should be a flex container (`flex items-center justify-between`).
* **Left Side (Info):**
* **Method Badge:** (Existing) e.g., "GET".
* **Status Badge (New):** Add a badge immediately after the Method.
* *Content:* The HTTP Status Code (e.g., 200, 404, 500).
* *Style:* Small, pill-shaped, lighter opacity background.
* *Color Logic:*
* 2xx: Text Green / Bg Green-500/20
* 3xx: Text Blue / Bg Blue-500/20
* 4xx: Text Orange / Bg Orange-500/20
* 5xx: Text Red / Bg Red-500/20
* **URL:** Truncate text if it's too long (`truncate` class).
* **Right Side (Actions):**
* **Delete Button (New):** A small "Trash" icon (`Trash2` from lucide-vue-next).
* *Behavior:* Visible on hover (group-hover) or always visible with low opacity.
* *Interaction:* Clicking this **must not** trigger the "Load Request" action of the list item (use `.stop` modifier).
### 1.2 "Clear All" Functionality
* **Location:** Add a "Clear" or "Trash" icon button in the **Header** of the Sidebar (next to the "History" tab label or the "LiteRequest" title).
* **Style:** Subtle button, turns red on hover.
* **Tooltip (Optional):** "Clear All History".
## 2. Logic & State Management
### 2.1 Store Updates (`stores/requestStore.ts`)
* Add two new actions:
1. `deleteHistoryItem(id: string)`: Removes a specific item from the `history` array by ID.
2. `clearHistory()`: Empties the `history` array completely.
* **Persistence:** Ensure `localStorage` is updated immediately after these actions.
## 3. Implementation Details
### A. Sidebar Component (`Sidebar.vue`)
* **Status Badge Implementation:**
* Create a helper function `getStatusColor(code)` inside the component to return the correct Tailwind classes.
* **Event Handling:**
* `<button @click.stop="store.deleteHistoryItem(item.id)">`
* The `.stop` modifier is critical to prevent opening the request while trying to delete it.
### B. Icons
* Import `Trash2` (for single item) and `Trash` (for clear all) from `lucide-vue-next`.
## 4. Implementation Steps for AI
Please generate the code updates in the following order:
1. **Store:** Add the `deleteHistoryItem` and `clearHistory` actions to `requestStore.ts`.
2. **Sidebar (Script):** Update the `<script setup>` to include the new icons and the status color helper function.
3. **Sidebar (Template):**
* Show the updated **Header** section (with "Clear All" button).
* Show the updated **History List Item** structure (Method + Status + URL + Delete Button).
---
**Instruction to AI:**
Generate the code to apply these UI improvements and functional additions to the History module.

View File

@@ -0,0 +1,59 @@
# UI Improvement: Resizable Panels & Copy Action
**Context:**
We are polishing the "Main Workspace" area of the LiteRequest application.
**Goal:**
1. Add a **"Copy Body" button** to the Response Panel for quick access to the result.
2. Make the vertical split between the **Request Panel** (top) and **Response Panel** (bottom) resizable by the user.
## 1. Feature: Response Copy Button
### 1.1 UI Changes
* **Location:** Inside the `ResponsePanel.vue`, in the **Meta Bar / Header** (the row displaying Status Code and Time), aligned to the right.
* **Icon:** Use the `Clipboard` icon from `lucide-vue-next`.
* **Interaction:**
* **Default:** Shows the `Clipboard` icon.
* **On Click:** Copies the content of the Response Body to the system clipboard.
* **Feedback:** After clicking, change the icon to `Check` (Checkmark) for 2 seconds to indicate success, then revert to `Clipboard`.
* **Style:** Small, ghost-style button (transparent background, changing color on hover).
### 1.2 Logic Implementation
* Use the browser API: `navigator.clipboard.writeText(props.body)`.
* Use a local ref `isCopied` (boolean) to handle the icon toggle state.
* Use `setTimeout` to reset `isCopied` back to `false` after 2000ms.
## 2. Feature: Resizable Split Pane
### 2.1 UI Changes
* **Location:** The parent component that contains `<RequestPanel />` and `<ResponsePanel />` (likely `App.vue` or `MainWorkspace.vue`).
* **Visuals:** Insert a **Resizer Handle** (a thin horizontal bar) between the two panels.
* *Height:* 4px - 6px.
* *Color:* `bg-slate-800` (hover: `bg-indigo-500`).
* *Cursor:* `cursor-row-resize`.
### 2.2 Logic Implementation
* **State:** Use a `ref` for `topPanelHeight` (initially `50%` or `50vh`).
* **Drag Logic:**
1. **`onMouseDown`** (on the Resizer): Set a `isDragging` flag to true. Add `mousemove` and `mouseup` event listeners to the `window` (global).
2. **`onMouseMove`** (on Window): Calculate the new percentage or pixel height based on `e.clientY` relative to the window height. Update `topPanelHeight`.
3. **`onMouseUp`** (on Window): Set `isDragging` to false. Remove the window event listeners.
* **Layout Application:**
* Apply `:style="{ height: topPanelHeight }"` to the **Request Panel** container.
* Apply `flex-1` (or calculated remaining height) to the **Response Panel** container.
* Ensure `min-height` is set (e.g., 200px) on both panels to prevent them from collapsing completely.
## 3. Implementation Steps for AI
Please generate the code updates in the following order:
1. **ResponsePanel.vue:**
* Update the template to include the Copy Button in the header.
* Add the script logic for `copyToClipboard`.
2. **Main Layout (App.vue or similar):**
* Refactor the template to wrap RequestPanel and ResponsePanel in the resizable structure.
* Implement the `useDraggable` logic (or manual event handlers) in `<script setup>`.
* Add the `<div class="resizer ...">` element styles.
---
**Instruction to AI:**
Generate the specific code to add the copy functionality and the resizable split view logic.

View File

@@ -1,6 +1,7 @@
# Generated by Cargo # Generated by Cargo
# will have compiled files and executables # will have compiled files and executables
/target/ /target/
/target*/
# Generated by Tauri # Generated by Tauri
# will have schema files for capabilities auto-completion # will have schema files for capabilities auto-completion

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 974 B

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
src-tauri/icons/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 903 B

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 3.6 KiB

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 884 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@@ -1,6 +1,8 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::time::Instant; use std::time::Instant;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use tauri::State;
use tokio::sync::{Mutex, oneshot};
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct HttpResponse { struct HttpResponse {
@@ -8,6 +10,15 @@ struct HttpResponse {
headers: HashMap<String, String>, headers: HashMap<String, String>,
body: String, body: String,
time_elapsed: u128, // milliseconds time_elapsed: u128, // milliseconds
headers_size: usize,
body_size: usize,
total_size: usize,
}
#[derive(Serialize, Deserialize)]
struct AppError {
code: String,
message: String,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
@@ -39,23 +50,87 @@ struct AuthConfig {
api_key: ApiKeyAuth, api_key: ApiKeyAuth,
} }
struct AppState {
client: reqwest::Client,
pending_requests: Mutex<HashMap<String, oneshot::Sender<()>>>,
}
impl AppError {
fn new(code: &str, message: impl Into<String>) -> Self {
Self {
code: code.to_string(),
message: message.into(),
}
}
}
fn map_reqwest_error(error: reqwest::Error) -> AppError {
if error.is_timeout() {
return AppError::new("timeout", "The request timed out after 30 seconds.");
}
if error.is_connect() {
return AppError::new("connect", format!("Failed to connect: {error}"));
}
if error.is_decode() {
return AppError::new("decode", format!("Failed to decode response body: {error}"));
}
if error.is_request() {
return AppError::new("request", format!("Failed to build or send the request: {error}"));
}
AppError::new("network", format!("Request failed: {error}"))
}
async fn perform_request(
request_builder: reqwest::RequestBuilder,
) -> Result<HttpResponse, AppError> {
let start_time = Instant::now();
let response = request_builder.send().await.map_err(map_reqwest_error)?;
let time_elapsed = start_time.elapsed().as_millis();
let status = response.status().as_u16();
let mut response_headers = HashMap::new();
let mut headers_size = 2usize;
for (key, value) in response.headers() {
let val_bytes = value.as_bytes();
let val_str = value.to_str().unwrap_or("").to_string();
headers_size += key.as_str().len() + 2 + val_bytes.len() + 2;
response_headers.insert(key.to_string(), val_str);
}
let body_text = response.text().await.map_err(map_reqwest_error)?;
let body_size = body_text.as_bytes().len();
let total_size = headers_size + body_size;
Ok(HttpResponse {
status,
headers: response_headers,
body: body_text,
time_elapsed,
headers_size,
body_size,
total_size,
})
}
#[tauri::command] #[tauri::command]
async fn execute_request( async fn execute_request(
state: State<'_, AppState>,
request_id: String,
method: String, method: String,
url: String, url: String,
headers: HashMap<String, String>, headers: HashMap<String, String>,
body: Option<String>, body: Option<String>,
query_params: Option<HashMap<String, String>>, query_params: Option<HashMap<String, String>>,
auth: Option<AuthConfig>, auth: Option<AuthConfig>,
) -> Result<HttpResponse, String> { ) -> Result<HttpResponse, AppError> {
let client = reqwest::Client::builder() let req_method = method.parse::<reqwest::Method>()
.timeout(std::time::Duration::from_secs(30)) .map_err(|e| AppError::new("invalid_method", format!("Invalid HTTP method: {e}")))?;
.build() let mut request_builder = state.client.request(req_method, &url);
.map_err(|e| e.to_string())?;
let req_method = method.parse::<reqwest::Method>().map_err(|e| e.to_string())?;
let mut request_builder = client.request(req_method, &url);
// Add Query Params // Add Query Params
if let Some(params) = query_params { if let Some(params) = query_params {
@@ -99,36 +174,56 @@ async fn execute_request(
} }
} }
let start_time = Instant::now(); let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
// Execute request {
let response = request_builder.send().await.map_err(|e| e.to_string())?; let mut pending_requests = state.pending_requests.lock().await;
let time_elapsed = start_time.elapsed().as_millis(); pending_requests.insert(request_id.clone(), cancel_tx);
let status = response.status().as_u16();
let mut response_headers = HashMap::new();
for (key, value) in response.headers() {
// Handle header value to string conversion (skipping non-utf8 for simplicity or lossy conv)
let val_str = value.to_str().unwrap_or("").to_string();
// Capitalize or keep standard key format? keeping standard.
response_headers.insert(key.to_string(), val_str);
} }
let body_text = response.text().await.map_err(|e| e.to_string())?; let result = tokio::select! {
_ = &mut cancel_rx => Err(AppError::new("canceled", "The request was canceled.")),
result = perform_request(request_builder) => result,
};
Ok(HttpResponse { let mut pending_requests = state.pending_requests.lock().await;
status, pending_requests.remove(&request_id);
headers: response_headers,
body: body_text, result
time_elapsed, }
})
#[tauri::command]
async fn cancel_request(
state: State<'_, AppState>,
request_id: String,
) -> Result<bool, AppError> {
let sender = {
let mut pending_requests = state.pending_requests.lock().await;
pending_requests.remove(&request_id)
};
match sender {
Some(cancel_tx) => {
let _ = cancel_tx.send(());
Ok(true)
}
None => Ok(false),
}
} }
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.expect("failed to create HTTP client");
tauri::Builder::default() tauri::Builder::default()
.manage(AppState {
client,
pending_requests: Mutex::new(HashMap::new()),
})
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![execute_request]) .invoke_handler(tauri::generate_handler![execute_request, cancel_request])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }

View File

@@ -1,78 +1,75 @@
<script setup lang="ts"> <script setup lang="ts">
import { useRequestStore } from './stores/requestStore'; import { defineAsyncComponent, onUnmounted, ref, watch } from 'vue';
import RequestPanel from './components/RequestPanel.vue'; import RequestPanel from './components/RequestPanel.vue';
import ResponsePanel from './components/ResponsePanel.vue'; import ResponsePanel from './components/ResponsePanel.vue';
import MethodBadge from './components/MethodBadge.vue'; import Sidebar from './components/Sidebar.vue';
import SettingsModal from './components/SettingsModal.vue';
import { History, Layers, Zap, Settings } from 'lucide-vue-next'; const SettingsModal = defineAsyncComponent(() => import('./components/SettingsModal.vue'));
import { ref } from 'vue'; const PANEL_HEIGHT_STORAGE_KEY = 'topPanelHeight';
const DEFAULT_TOP_PANEL_HEIGHT = 50;
const clampPanelHeight = (value: number) => {
if (Number.isNaN(value)) return DEFAULT_TOP_PANEL_HEIGHT;
return Math.min(80, Math.max(20, value));
};
const store = useRequestStore();
const showSettings = ref(false); const showSettings = ref(false);
const topPanelHeight = ref(
clampPanelHeight(Number(localStorage.getItem(PANEL_HEIGHT_STORAGE_KEY)) || DEFAULT_TOP_PANEL_HEIGHT)
);
const isDragging = ref(false);
const startDrag = (event: MouseEvent) => {
event.preventDefault();
isDragging.value = true;
window.addEventListener('mousemove', onDrag);
window.addEventListener('mouseup', stopDrag);
};
const onDrag = (e: MouseEvent) => {
if (!isDragging.value) return;
const containerHeight = window.innerHeight;
const newPercentage = (e.clientY / containerHeight) * 100;
topPanelHeight.value = clampPanelHeight(newPercentage);
};
const stopDrag = () => {
isDragging.value = false;
window.removeEventListener('mousemove', onDrag);
window.removeEventListener('mouseup', stopDrag);
};
onUnmounted(() => {
window.removeEventListener('mousemove', onDrag);
window.removeEventListener('mouseup', stopDrag);
});
watch(topPanelHeight, (value) => {
localStorage.setItem(PANEL_HEIGHT_STORAGE_KEY, clampPanelHeight(value).toString());
});
</script> </script>
<template> <template>
<div class="flex h-screen w-full bg-slate-950 text-slate-200 font-sans overflow-hidden"> <div class="flex h-screen w-full bg-slate-950 text-slate-200 font-sans overflow-hidden">
<!-- Sidebar --> <!-- Sidebar -->
<aside class="w-64 flex-shrink-0 border-r border-slate-800 flex flex-col bg-slate-950"> <Sidebar @open-settings="showSettings = true" />
<!-- Header -->
<div class="h-14 flex items-center px-4 border-b border-slate-800 gap-2">
<div class="bg-indigo-500/20 p-1.5 rounded-lg">
<Zap class="w-5 h-5 text-indigo-400" />
</div>
<span class="font-bold text-slate-100 tracking-tight">LiteRequest</span>
</div>
<!-- Nav Tabs -->
<div class="flex p-2 gap-1">
<button class="flex-1 flex items-center justify-center gap-2 py-1.5 text-xs font-medium bg-slate-900 text-slate-200 rounded border border-slate-800 shadow-sm">
<History class="w-3.5 h-3.5" /> History
</button>
<button class="flex-1 flex items-center justify-center gap-2 py-1.5 text-xs font-medium text-slate-500 hover:bg-slate-900 hover:text-slate-300 rounded transition-colors">
<Layers class="w-3.5 h-3.5" /> Collections
</button>
</div>
<!-- History List -->
<div class="flex-1 overflow-y-auto">
<div v-if="store.history.length === 0" class="p-8 text-center text-slate-600 text-xs">
No history yet. Make a request!
</div>
<div v-else class="flex flex-col">
<button
v-for="item in store.history"
:key="item.timestamp"
@click="store.loadRequest(item)"
class="text-left px-3 py-3 border-b border-slate-800/50 hover:bg-slate-900 transition-colors group flex flex-col gap-1.5"
>
<div class="flex items-center gap-2 overflow-hidden w-full">
<MethodBadge :method="item.method" />
<span class="text-xs text-slate-400 truncate font-mono opacity-75">{{ new Date(item.timestamp).toLocaleTimeString() }}</span>
</div>
<div class="text-sm text-slate-300 truncate px-1 font-medium" :title="item.url">
{{ item.url || 'No URL' }}
</div>
</button>
</div>
</div>
<!-- Settings -->
<div class="p-2 border-t border-slate-800">
<button
@click="showSettings = true"
class="w-full flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-400 hover:text-slate-200 hover:bg-slate-900 rounded transition-colors"
>
<Settings class="w-4 h-4" /> Settings
</button>
</div>
</aside>
<!-- Main Workspace --> <!-- Main Workspace -->
<main class="flex-1 flex flex-col min-w-0 bg-slate-900"> <main class="flex-1 flex flex-col min-w-0 bg-slate-900 h-full relative">
<div class="flex-1 min-h-0"> <!-- Request Panel (Top) -->
<div class="min-h-0" :style="{ height: topPanelHeight + '%' }">
<RequestPanel /> <RequestPanel />
</div> </div>
<div class="h-1/2 border-t border-slate-800 min-h-0">
<!-- Resizer Handle -->
<div
class="h-1 bg-slate-800 hover:bg-indigo-500 cursor-row-resize transition-colors z-10 flex-shrink-0"
@mousedown="startDrag"
></div>
<!-- Response Panel (Bottom) -->
<div class="flex-1 min-h-0 overflow-hidden">
<ResponsePanel /> <ResponsePanel />
</div> </div>
</main> </main>

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

Before

Width:  |  Height:  |  Size: 496 B

View File

@@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { useRequestStore } from '../stores/requestStore'; import { useRequestStore } from '../stores/requestStore';
import { ShieldCheck, Key, User, Lock, Fingerprint } from 'lucide-vue-next'; import { ShieldCheck, Key, User, Lock, Fingerprint } from 'lucide-vue-next';
import CustomSelect from './CustomSelect.vue';
import { ref } from 'vue'; import { ref } from 'vue';
const store = useRequestStore(); const store = useRequestStore();
@@ -21,15 +22,11 @@ const showApiKey = ref(false);
<!-- Type Selector --> <!-- Type Selector -->
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<label class="text-xs font-bold uppercase text-slate-500 tracking-wider">Authentication Type</label> <label class="text-xs font-bold uppercase text-slate-500 tracking-wider">Authentication Type</label>
<div class="relative"> <CustomSelect
<select v-model="store.activeRequest.auth.type"
v-model="store.activeRequest.auth.type" :options="authTypes"
class="w-full bg-slate-950 border border-slate-800 rounded-lg px-4 py-2.5 text-sm text-slate-200 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 outline-none appearance-none cursor-pointer" :full-width="true"
> />
<option v-for="t in authTypes" :key="t.value" :value="t.value">{{ t.label }}</option>
</select>
<ShieldCheck class="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500 pointer-events-none" />
</div>
</div> </div>
<!-- Dynamic Content --> <!-- Dynamic Content -->

View File

@@ -0,0 +1,65 @@
<script setup lang="ts">
import { computed } from 'vue';
import { Codemirror } from 'vue-codemirror';
import { json } from '@codemirror/lang-json';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView } from '@codemirror/view';
import { useSettingsStore } from '../stores/settingsStore';
const props = withDefaults(defineProps<{
modelValue?: string;
placeholder?: string;
readOnly?: boolean;
language?: 'json' | 'text';
}>(), {
modelValue: '',
placeholder: '',
readOnly: false,
language: 'text',
});
const emit = defineEmits<{
'update:modelValue': [value: string];
}>();
const settings = useSettingsStore();
const extensions = computed(() => {
const theme = EditorView.theme({
'&': {
backgroundColor: 'transparent !important',
height: '100%',
},
'.cm-content, .cm-gutter': {
fontFamily: `${settings.editorFontFamily} !important`,
},
'.cm-gutters': {
backgroundColor: 'transparent !important',
},
});
return [
oneDark,
theme,
...(props.language === 'json' ? [json()] : []),
...(props.readOnly ? [EditorView.editable.of(false)] : []),
];
});
</script>
<template>
<Codemirror
:model-value="props.modelValue"
:placeholder="props.placeholder"
:style="{
height: '100%',
fontSize: settings.editorFontSize + 'px',
fontFamily: settings.editorFontFamily,
}"
:autofocus="false"
:indent-with-tab="true"
:tab-size="2"
:extensions="extensions"
@update:model-value="emit('update:modelValue', $event)"
/>
</template>

View File

@@ -0,0 +1,106 @@
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ChevronDown, Check } from 'lucide-vue-next';
interface Option {
value: string;
label?: string;
}
const props = defineProps<{
modelValue: string;
options: (string | Option)[];
placeholder?: string;
fullWidth?: boolean;
triggerClass?: string;
}>();
const emit = defineEmits(['update:modelValue']);
const isOpen = ref(false);
const containerRef = ref<HTMLElement | null>(null);
const normalizedOptions = computed(() => {
return props.options.map(opt => {
if (typeof opt === 'string') {
return { value: opt, label: opt };
}
return opt;
});
});
const selectedLabel = computed(() => {
const found = normalizedOptions.value.find(o => o.value === props.modelValue);
return found ? (found.label || found.value) : (props.modelValue || props.placeholder || '');
});
const toggle = () => { isOpen.value = !isOpen.value;
};
const select = (value: string) => {
emit('update:modelValue', value);
isOpen.value = false;
};
const handleClickOutside = (event: MouseEvent) => {
if (containerRef.value && !containerRef.value.contains(event.target as Node)) {
isOpen.value = false;
}
};
onMounted(() => {
document.addEventListener('click', handleClickOutside);
});
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside);
});
</script>
<template>
<div
ref="containerRef"
class="relative text-sm"
:class="{ 'w-full': fullWidth }"
>
<!-- Trigger -->
<button
type="button"
@click="toggle"
class="flex items-center justify-between gap-2 px-3 py-2 transition-colors text-slate-200 focus:outline-none"
:class="[
triggerClass ? triggerClass : 'bg-slate-950 border border-slate-800 rounded-lg hover:border-slate-700 focus:ring-1 focus:ring-indigo-500/50',
{ 'w-full': fullWidth, 'border-indigo-500 ring-1 ring-indigo-500/50': isOpen && !triggerClass }
]"
>
<span class="truncate font-bold">{{ selectedLabel }}</span>
<ChevronDown class="w-4 h-4 text-slate-500 transition-transform duration-200" :class="{ 'rotate-180': isOpen }" />
</button>
<!-- Dropdown Menu -->
<transition
enter-active-class="transition duration-100 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-75 ease-in"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<div
v-if="isOpen"
class="absolute top-full left-0 mt-1 w-full min-w-[120px] max-h-60 overflow-y-auto bg-slate-900 border border-slate-800 rounded-lg shadow-xl z-50 py-1"
>
<button
v-for="opt in normalizedOptions"
:key="opt.value"
@click="select(opt.value)"
class="w-full text-left px-3 py-2 text-sm flex items-center justify-between group hover:bg-slate-800 transition-colors"
:class="modelValue === opt.value ? 'text-indigo-400 bg-indigo-500/10' : 'text-slate-300'"
>
<span class="truncate font-medium">{{ opt.label || opt.value }}</span>
<Check v-if="modelValue === opt.value" class="w-3.5 h-3.5 text-indigo-500" />
</button>
</div>
</transition>
</div>
</template>

View File

@@ -9,6 +9,14 @@ const props = defineProps<{
const emit = defineEmits(['update:modelValue']); const emit = defineEmits(['update:modelValue']);
const updateRow = (index: number, key: keyof KeyValue, value: string | boolean) => {
const newData = props.modelValue.map((item, itemIndex) => {
if (itemIndex !== index) return item;
return { ...item, [key]: value };
});
emit('update:modelValue', newData);
};
const addRow = () => { const addRow = () => {
const newData = [...props.modelValue, { const newData = [...props.modelValue, {
id: crypto.randomUUID(), id: crypto.randomUUID(),
@@ -47,14 +55,16 @@ const removeRow = (index: number) => {
<td class="py-1 pl-2 align-middle"> <td class="py-1 pl-2 align-middle">
<input <input
type="checkbox" type="checkbox"
v-model="item.enabled" :checked="item.enabled"
@change="updateRow(index, 'enabled', ($event.target as HTMLInputElement).checked)"
class="rounded bg-slate-800 border-slate-700 text-indigo-500 focus:ring-indigo-500/50 focus:ring-offset-0" class="rounded bg-slate-800 border-slate-700 text-indigo-500 focus:ring-indigo-500/50 focus:ring-offset-0"
> >
</td> </td>
<td class="py-1 pr-2 align-middle"> <td class="py-1 pr-2 align-middle">
<input <input
type="text" type="text"
v-model="item.key" :value="item.key"
@input="updateRow(index, 'key', ($event.target as HTMLInputElement).value)"
placeholder="Key" placeholder="Key"
class="w-full bg-transparent border-b border-transparent hover:border-slate-700 focus:border-indigo-500 focus:outline-none py-1 px-1 text-sm text-slate-300 transition-colors" class="w-full bg-transparent border-b border-transparent hover:border-slate-700 focus:border-indigo-500 focus:outline-none py-1 px-1 text-sm text-slate-300 transition-colors"
> >
@@ -62,7 +72,8 @@ const removeRow = (index: number) => {
<td class="py-1 pr-2 align-middle"> <td class="py-1 pr-2 align-middle">
<input <input
type="text" type="text"
v-model="item.value" :value="item.value"
@input="updateRow(index, 'value', ($event.target as HTMLInputElement).value)"
placeholder="Value" placeholder="Value"
class="w-full bg-transparent border-b border-transparent hover:border-slate-700 focus:border-indigo-500 focus:outline-none py-1 px-1 text-sm text-slate-300 transition-colors" class="w-full bg-transparent border-b border-transparent hover:border-slate-700 focus:border-indigo-500 focus:outline-none py-1 px-1 text-sm text-slate-300 transition-colors"
> >

View File

@@ -1,108 +1,218 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import { computed, defineAsyncComponent, ref } from 'vue';
import { useRequestStore } from '../stores/requestStore'; import { useRequestStore, type RequestError, type KeyValue } from '../stores/requestStore';
import { useSettingsStore } from '../stores/settingsStore';
import KeyValueEditor from './KeyValueEditor.vue'; import KeyValueEditor from './KeyValueEditor.vue';
import AuthPanel from './AuthPanel.vue'; import AuthPanel from './AuthPanel.vue';
import CustomSelect from './CustomSelect.vue';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { Codemirror } from 'vue-codemirror'; import { Play, Loader2, Square } from 'lucide-vue-next';
import { json } from '@codemirror/lang-json';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView } from '@codemirror/view';
import { Play, Loader2 } from 'lucide-vue-next';
const CodeEditor = defineAsyncComponent(() => import('./CodeEditor.vue'));
const store = useRequestStore(); const store = useRequestStore();
const settings = useSettingsStore();
const activeTab = ref('params'); const activeTab = ref('params');
const isLoading = ref(false); const isLoading = ref(false);
const currentRequestId = ref<string | null>(null);
const transparentTheme = EditorView.theme({ const bodyMode = ref<'auto' | 'json' | 'text'>('auto');
"&": {
backgroundColor: "transparent !important",
height: "100%"
},
".cm-gutters": {
backgroundColor: "transparent !important"
}
});
const extensions = [json(), oneDark, transparentTheme];
const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']; const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
const bodyModeOptions = [
{ value: 'auto', label: 'Auto' },
{ value: 'json', label: 'JSON' },
{ value: 'text', label: 'Text' },
];
const methodSupportsBody = computed(() => !['GET', 'HEAD'].includes(store.activeRequest.method));
const inferredBodyLanguage = computed<'json' | 'text'>(() => {
if (bodyMode.value !== 'auto') return bodyMode.value;
const contentTypeHeader = store.activeRequest.headers.find((header) => (
header.enabled && header.key.trim().toLowerCase() === 'content-type'
));
const contentType = contentTypeHeader?.value.trim().toLowerCase() || '';
return contentType.includes('json') ? 'json' : 'text';
});
const requestBodyPlaceholder = computed(() => (
inferredBodyLanguage.value === 'json'
? 'Request Body (JSON)'
: 'Request Body'
));
const normalizeError = (error: unknown): RequestError => {
if (error && typeof error === 'object' && 'code' in error && 'message' in error) {
return {
code: String((error as { code: unknown }).code),
message: String((error as { message: unknown }).message),
};
}
return {
code: 'unknown',
message: String(error),
};
};
const findDuplicateKey = (items: KeyValue[]) => {
const seen = new Set<string>();
for (const item of items) {
const key = item.key.trim().toLowerCase();
if (!item.enabled || !key) continue;
if (seen.has(key)) return item.key.trim();
seen.add(key);
}
return null;
};
const validateRequest = (): RequestError | null => {
const url = store.activeRequest.url.trim();
if (!url) {
return { code: 'validation', message: 'URL is required.' };
}
let parsedUrl: URL;
try {
parsedUrl = new URL(url);
} catch {
return { code: 'invalid_url', message: 'URL is invalid. Use a full http:// or https:// address.' };
}
if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
return { code: 'invalid_url', message: 'Only http:// and https:// URLs are supported.' };
}
const duplicateHeader = findDuplicateKey(store.activeRequest.headers);
if (duplicateHeader) {
return { code: 'duplicate_header', message: `Duplicate enabled header: ${duplicateHeader}` };
}
const duplicateParam = findDuplicateKey(store.activeRequest.params);
if (duplicateParam) {
return { code: 'duplicate_query_param', message: `Duplicate enabled query param: ${duplicateParam}` };
}
if (inferredBodyLanguage.value === 'json' && store.activeRequest.body.trim()) {
try {
JSON.parse(store.activeRequest.body);
} catch {
return { code: 'invalid_json', message: 'Request body is set to JSON mode but contains invalid JSON.' };
}
}
return null;
};
const executeRequest = async () => { const executeRequest = async () => {
if (!store.activeRequest.url) return; if (isLoading.value || !store.activeRequest.url) return;
const validationError = validateRequest();
if (validationError) {
store.setRequestError(validationError);
return;
}
const requestId = crypto.randomUUID();
currentRequestId.value = requestId;
isLoading.value = true; isLoading.value = true;
store.setRequestError(null);
try { try {
// Prepare headers and params map
const headers: Record<string, string> = {}; const headers: Record<string, string> = {};
store.activeRequest.headers.filter(h => h.enabled && h.key).forEach(h => headers[h.key] = h.value); store.activeRequest.headers.filter(h => h.enabled && h.key).forEach(h => headers[h.key] = h.value);
const params: Record<string, string> = {}; const params: Record<string, string> = {};
store.activeRequest.params.filter(p => p.enabled && p.key).forEach(p => params[p.key] = p.value); store.activeRequest.params.filter(p => p.enabled && p.key).forEach(p => params[p.key] = p.value);
// Execute
const response: any = await invoke('execute_request', { const response: any = await invoke('execute_request', {
requestId,
method: store.activeRequest.method, method: store.activeRequest.method,
url: store.activeRequest.url, url: store.activeRequest.url,
headers, headers,
body: store.activeRequest.body || null, body: store.activeRequest.body.trim() ? store.activeRequest.body : null,
queryParams: params, queryParams: params,
auth: store.activeRequest.auth, auth: store.activeRequest.auth,
}); });
// Update Store store.setRequestError(null);
store.activeRequest.response = { store.activeRequest.response = {
status: response.status, status: response.status,
headers: response.headers, headers: response.headers,
body: response.body, body: response.body,
time: response.time_elapsed, time: response.time_elapsed,
size: new Blob([response.body]).size size: response.total_size,
headersSize: response.headers_size,
bodySize: response.body_size,
}; };
// Add to history if successful
store.addToHistory(store.activeRequest); store.addToHistory(store.activeRequest);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
// Simple alert for now, or could use a toast store.activeRequest.response = undefined;
alert('Request Failed: ' + error); store.setRequestError(normalizeError(error));
} finally { } finally {
currentRequestId.value = null;
isLoading.value = false; isLoading.value = false;
} }
}; };
const cancelRequest = async () => {
if (!currentRequestId.value) return;
try {
await invoke('cancel_request', { requestId: currentRequestId.value });
} catch (error) {
console.error(error);
store.setRequestError(normalizeError(error));
}
};
</script> </script>
<template> <template>
<div class="flex flex-col h-full bg-slate-900"> <div class="flex flex-col h-full bg-slate-900">
<!-- Top Bar --> <!-- Top Bar -->
<div class="p-4 border-b border-slate-800 flex gap-2 items-center"> <div class="p-4 border-b border-slate-800 flex gap-2 items-center">
<div class="flex-1 flex items-center bg-slate-950 rounded-lg border border-slate-800 focus-within:border-indigo-500/50 focus-within:ring-1 focus-within:ring-indigo-500/50 transition-all overflow-hidden"> <div class="flex-1 flex items-center bg-slate-950 rounded-lg border border-slate-800 focus-within:border-indigo-500/50 focus-within:ring-1 focus-within:ring-indigo-500/50 transition-all overflow-visible z-20">
<select <CustomSelect
v-model="store.activeRequest.method" v-model="store.activeRequest.method"
class="bg-slate-900 text-xs font-bold px-3 py-2 text-white border-r border-slate-800 focus:outline-none hover:bg-slate-800 cursor-pointer uppercase appearance-none" :options="methods"
> triggerClass="bg-transparent text-xs font-bold px-3 py-2 text-slate-200 border-r border-slate-800 focus:outline-none hover:bg-slate-900 cursor-pointer uppercase h-full min-w-[90px]"
<option v-for="m in methods" :key="m" :value="m" class="bg-slate-900 text-white">{{ m }}</option> />
</select>
<input <input
type="text" type="text"
v-model="store.activeRequest.url" v-model="store.activeRequest.url"
placeholder="https://api.example.com/v1/users" placeholder="https://api.example.com/v1/users"
class="flex-1 bg-transparent border-none focus:ring-0 text-sm text-slate-200 px-3 py-2 placeholder-slate-600" class="flex-1 bg-transparent border-none focus:ring-0 text-sm text-slate-200 px-3 py-2 placeholder-slate-600 h-full"
@keydown.enter="executeRequest" @keydown.enter="executeRequest"
> >
</div> </div>
<button <button
v-if="!isLoading"
@click="executeRequest" @click="executeRequest"
:disabled="isLoading" class="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded-lg font-medium text-sm flex items-center gap-2 transition-all shadow-lg shadow-indigo-900/20"
class="bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg font-medium text-sm flex items-center gap-2 transition-all shadow-lg shadow-indigo-900/20"
> >
<Loader2 v-if="isLoading" class="w-4 h-4 animate-spin" /> <Play class="w-4 h-4 fill-current" />
<Play v-else class="w-4 h-4 fill-current" />
Send Send
</button> </button>
<button
v-else
@click="cancelRequest"
class="bg-rose-600 hover:bg-rose-500 text-white px-4 py-2 rounded-lg font-medium text-sm flex items-center gap-2 transition-all shadow-lg shadow-rose-900/20"
>
<Loader2 class="w-4 h-4 animate-spin" />
<Square class="w-3.5 h-3.5 fill-current" />
Cancel
</button>
</div>
<div
v-if="store.requestError"
class="mx-4 mt-4 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200"
>
<div class="font-medium uppercase tracking-wide text-[11px] text-rose-300/80">{{ store.requestError.code }}</div>
<div class="mt-1">{{ store.requestError.message }}</div>
</div> </div>
<!-- Configuration Tabs --> <!-- Configuration Tabs -->
@@ -133,18 +243,26 @@ const executeRequest = async () => {
/> />
</KeepAlive> </KeepAlive>
<div v-if="activeTab === 'body'" class="h-full w-full overflow-hidden"> <div v-if="activeTab === 'body'" class="h-full w-full overflow-hidden">
<Codemirror <div class="flex items-center justify-between border-b border-slate-800 px-4 py-2 text-xs">
<div class="text-slate-500">
Mode: <span class="text-slate-300 uppercase">{{ inferredBodyLanguage }}</span>
</div>
<CustomSelect
v-model="bodyMode"
:options="bodyModeOptions"
triggerClass="bg-slate-950 text-xs font-medium px-3 py-1.5 text-slate-200 border border-slate-800 rounded-md focus:outline-none hover:bg-slate-900 cursor-pointer min-w-[88px]"
/>
</div>
<div
v-if="!methodSupportsBody"
class="mx-4 mt-4 rounded-lg border border-amber-500/20 bg-amber-500/10 px-3 py-2 text-sm text-amber-100"
>
{{ store.activeRequest.method }} requests usually do not send a body. The editor stays available, but some servers may ignore it.
</div>
<CodeEditor
v-model="store.activeRequest.body" v-model="store.activeRequest.body"
placeholder="Request Body (JSON)" :placeholder="requestBodyPlaceholder"
:style="{ :language="inferredBodyLanguage"
height: '100%',
fontSize: settings.editorFontSize + 'px',
fontFamily: settings.editorFontFamily
}"
:autofocus="true"
:indent-with-tab="true"
:tab-size="2"
:extensions="extensions"
/> />
</div> </div>
<KeepAlive> <KeepAlive>

View File

@@ -1,74 +1,155 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed, defineAsyncComponent, ref } from 'vue';
import { useRequestStore } from '../stores/requestStore'; import { useRequestStore } from '../stores/requestStore';
import { useSettingsStore } from '../stores/settingsStore'; import { Clipboard, Check } from 'lucide-vue-next';
import { Codemirror } from 'vue-codemirror';
import { json } from '@codemirror/lang-json';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView } from '@codemirror/view'; // Import EditorView
const CodeEditor = defineAsyncComponent(() => import('./CodeEditor.vue'));
const store = useRequestStore(); const store = useRequestStore();
const settings = useSettingsStore(); const isCopied = ref(false);
const activeTab = ref<'body' | 'headers'>('body');
const transparentTheme = EditorView.theme({ const responseFormat = computed<'json' | 'xml' | 'html' | 'text'>(() => {
"&": { const response = store.activeRequest.response;
backgroundColor: "transparent !important", if (!response) return 'text';
height: "100%"
}, const contentType = response.headers['content-type'] || response.headers['Content-Type'] || '';
".cm-gutters": { const normalizedContentType = contentType.toLowerCase();
backgroundColor: "transparent !important"
if (normalizedContentType.includes('json')) {
return 'json';
}
if (normalizedContentType.includes('xml')) {
return 'xml';
}
if (normalizedContentType.includes('html')) {
return 'html';
}
try {
JSON.parse(response.body);
return 'json';
} catch {
return 'text';
} }
}); });
const extensions = [json(), oneDark, transparentTheme, EditorView.editable.of(false)]; const isJsonResponse = computed(() => responseFormat.value === 'json');
const formattedHeaders = computed(() => {
const response = store.activeRequest.response;
if (!response) return '';
return Object.entries(response.headers)
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
.map(([key, value]) => `${key}: ${value}`)
.join('\n');
});
const formattedBody = computed(() => { const formattedBody = computed(() => {
if (!store.activeRequest.response) return ''; if (!store.activeRequest.response) return '';
if (!isJsonResponse.value) return store.activeRequest.response.body;
try { try {
// Auto pretty print
return JSON.stringify(JSON.parse(store.activeRequest.response.body), null, 2); return JSON.stringify(JSON.parse(store.activeRequest.response.body), null, 2);
} catch (e) { } catch {
return store.activeRequest.response.body; return store.activeRequest.response.body;
} }
}); });
const displayedContent = computed(() => (
activeTab.value === 'headers' ? formattedHeaders.value : formattedBody.value
));
const statusColor = computed(() => { const statusColor = computed(() => {
const s = store.activeRequest.response?.status || 0; const s = store.activeRequest.response?.status || 0;
if (s >= 200 && s < 300) return 'text-emerald-400'; if (s >= 200 && s < 300) return 'text-emerald-400';
if (s >= 400) return 'text-rose-400'; if (s >= 400) return 'text-rose-400';
return 'text-amber-400'; return 'text-amber-400';
}); });
const copyToClipboard = async () => {
if (!displayedContent.value) return;
try {
await navigator.clipboard.writeText(displayedContent.value);
isCopied.value = true;
setTimeout(() => {
isCopied.value = false;
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
};
</script> </script>
<template> <template>
<div class="flex flex-col h-full border-t border-slate-800 bg-slate-900"> <div class="flex flex-col h-full border-t border-slate-800 bg-slate-900">
<div v-if="store.activeRequest.response" class="flex flex-col h-full"> <div v-if="store.activeRequest.response" class="flex flex-col h-full">
<!-- Meta Bar --> <!-- Meta Bar -->
<div class="px-4 py-2 border-b border-slate-800 flex gap-4 text-xs items-center bg-slate-950/50"> <div class="px-4 py-2 border-b border-slate-800 flex justify-between text-xs items-center bg-slate-950/50">
<div class="font-mono"> <div class="flex gap-4 items-center">
Status: <span :class="['font-bold', statusColor]">{{ store.activeRequest.response.status }}</span> <div class="font-mono">
Status: <span :class="['font-bold', statusColor]">{{ store.activeRequest.response.status }}</span>
</div>
<div class="text-slate-500">
Time: <span class="text-slate-300">{{ store.activeRequest.response.time }}ms</span>
</div>
<div class="text-slate-500">
Size:
<span class="text-slate-300">{{ (store.activeRequest.response.size / 1024).toFixed(2) }} KB</span>
<span class="ml-1 text-slate-500">
(H {{ (store.activeRequest.response.headersSize / 1024).toFixed(2) }} / B {{ (store.activeRequest.response.bodySize / 1024).toFixed(2) }} KB)
</span>
</div>
<div class="text-slate-500">
Format: <span class="text-slate-300 uppercase">{{ responseFormat }}</span>
</div>
</div> </div>
<div class="text-slate-500">
Time: <span class="text-slate-300">{{ store.activeRequest.response.time }}ms</span> <div class="flex items-center gap-2">
</div> <div class="flex rounded-lg border border-slate-800 bg-slate-900 p-0.5">
<div class="text-slate-500"> <button
Size: <span class="text-slate-300">{{ (store.activeRequest.response.size / 1024).toFixed(2) }} KB</span> @click="activeTab = 'body'"
class="rounded-md px-2.5 py-1 transition-colors"
:class="activeTab === 'body' ? 'bg-indigo-500/15 text-indigo-300' : 'text-slate-400 hover:text-slate-200'"
>
Body
</button>
<button
@click="activeTab = 'headers'"
class="rounded-md px-2.5 py-1 transition-colors"
:class="activeTab === 'headers' ? 'bg-indigo-500/15 text-indigo-300' : 'text-slate-400 hover:text-slate-200'"
>
Headers
</button>
</div>
<button
@click="copyToClipboard"
class="p-1.5 text-slate-400 hover:text-indigo-400 hover:bg-indigo-500/10 rounded transition-colors"
:title="activeTab === 'headers' ? 'Copy Headers' : 'Copy Body'"
>
<Check v-if="isCopied" class="w-3.5 h-3.5" />
<Clipboard v-else class="w-3.5 h-3.5" />
</button>
</div> </div>
</div> </div>
<!-- Output --> <!-- Output -->
<div class="flex-1 overflow-hidden"> <div class="flex-1 overflow-hidden">
<Codemirror <CodeEditor
:model-value="formattedBody" :model-value="displayedContent"
:style="{ :language="activeTab === 'body' && responseFormat === 'json' ? 'json' : 'text'"
height: '100%', :read-only="true"
fontSize: settings.editorFontSize + 'px',
fontFamily: settings.editorFontFamily
}"
:extensions="extensions"
/> />
</div> </div>
</div> </div>
<div v-else-if="store.requestError" class="flex-1 flex items-center justify-center p-6">
<div class="max-w-2xl rounded-xl border border-rose-500/30 bg-rose-500/10 p-4 text-sm text-rose-200">
<div class="font-medium uppercase tracking-wide text-[11px] text-rose-300/80">{{ store.requestError.code }}</div>
<div class="mt-1">{{ store.requestError.message }}</div>
</div>
</div>
<div v-else class="flex-1 flex items-center justify-center text-slate-600 text-sm"> <div v-else class="flex-1 flex items-center justify-center text-slate-600 text-sm">
No response yet No response yet
</div> </div>

View File

@@ -1,6 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { useSettingsStore } from '../stores/settingsStore'; import { useSettingsStore } from '../stores/settingsStore';
import CustomSelect from './CustomSelect.vue';
import { X } from 'lucide-vue-next'; import { X } from 'lucide-vue-next';
import { computed } from 'vue';
const emit = defineEmits(['close']); const emit = defineEmits(['close']);
const settings = useSettingsStore(); const settings = useSettingsStore();
@@ -12,13 +14,20 @@ const fontOptions = [
"Monaco, Menlo, 'Ubuntu Mono', monospace", "Monaco, Menlo, 'Ubuntu Mono', monospace",
"Arial, sans-serif" "Arial, sans-serif"
]; ];
const displayFontOptions = computed(() => {
return fontOptions.map(font => ({
value: font,
label: font.split(',')[0].replace(/['"]/g, '')
}));
});
</script> </script>
<template> <template>
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm" @click.self="emit('close')"> <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm" @click.self="emit('close')">
<div class="bg-slate-900 border border-slate-700 rounded-xl shadow-2xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in-95 duration-200"> <div class="bg-slate-900 border border-slate-700 rounded-xl shadow-2xl w-full max-w-md animate-in fade-in zoom-in-95 duration-200">
<!-- Header --> <!-- Header -->
<div class="flex items-center justify-between px-6 py-4 border-b border-slate-800 bg-slate-950/50"> <div class="flex items-center justify-between px-6 py-4 border-b border-slate-800 bg-slate-950/50 rounded-t-xl">
<h2 class="text-lg font-semibold text-slate-100">Editor Settings</h2> <h2 class="text-lg font-semibold text-slate-100">Editor Settings</h2>
<button <button
@click="emit('close')" @click="emit('close')"
@@ -52,18 +61,13 @@ const fontOptions = [
<div class="space-y-3"> <div class="space-y-3">
<label class="text-sm font-medium text-slate-300">Font Family</label> <label class="text-sm font-medium text-slate-300">Font Family</label>
<div class="space-y-2"> <div class="space-y-2">
<select <CustomSelect
v-model="settings.editorFontFamily" v-model="settings.editorFontFamily"
class="w-full bg-slate-950 border border-slate-700 text-slate-300 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block p-2.5" :options="displayFontOptions"
> :full-width="true"
<option v-for="font in fontOptions" :key="font" :value="font"> placeholder="Select or enter font family"
{{ font.split(',')[0].replace(/['"]/g, '') }} />
</option>
<option value="custom">Custom...</option>
</select>
<input <input
v-if="settings.editorFontFamily === 'custom' || !fontOptions.includes(settings.editorFontFamily)"
type="text" type="text"
v-model="settings.editorFontFamily" v-model="settings.editorFontFamily"
placeholder="e.g. 'JetBrains Mono', monospace" placeholder="e.g. 'JetBrains Mono', monospace"
@@ -74,7 +78,7 @@ const fontOptions = [
</div> </div>
<!-- Footer --> <!-- Footer -->
<div class="px-6 py-4 bg-slate-950/50 border-t border-slate-800 flex justify-end"> <div class="px-6 py-4 bg-slate-950/50 border-t border-slate-800 flex justify-end rounded-b-xl">
<button <button
@click="emit('close')" @click="emit('close')"
class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 text-sm font-medium rounded-lg transition-colors border border-slate-700" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 text-sm font-medium rounded-lg transition-colors border border-slate-700"

104
src/components/Sidebar.vue Normal file
View File

@@ -0,0 +1,104 @@
<script setup lang="ts">
import { useRequestStore } from '../stores/requestStore';
import MethodBadge from './MethodBadge.vue';
import { Zap, Settings, Trash, Trash2, Plus } from 'lucide-vue-next';
const emit = defineEmits(['open-settings']);
const store = useRequestStore();
const getStatusColor = (code?: number) => {
if (!code) return 'text-slate-500 bg-slate-800/50';
if (code >= 200 && code < 300) return 'text-emerald-400 bg-emerald-500/10';
if (code >= 300 && code < 400) return 'text-blue-400 bg-blue-500/10';
if (code >= 400 && code < 500) return 'text-amber-400 bg-amber-500/10';
if (code >= 500) return 'text-rose-400 bg-rose-500/10';
return 'text-slate-400 bg-slate-500/10';
};
</script>
<template>
<aside class="w-64 flex-shrink-0 border-r border-slate-800 flex flex-col bg-slate-950">
<!-- Header -->
<div class="h-14 flex items-center justify-between px-4 border-b border-slate-800">
<div class="flex items-center gap-2">
<div class="bg-indigo-500/20 p-1.5 rounded-lg">
<Zap class="w-5 h-5 text-indigo-400" />
</div>
<span class="font-bold text-slate-100 tracking-tight">LiteRequest</span>
</div>
</div>
<!-- Action Buttons -->
<div class="flex p-2 gap-2 border-b border-slate-800/50">
<button
@click="store.resetActiveRequest()"
class="flex-1 flex items-center justify-center gap-2 py-1.5 text-xs font-medium bg-indigo-600 hover:bg-indigo-500 text-white rounded transition-all shadow-lg shadow-indigo-900/20"
>
<Plus class="w-3.5 h-3.5" /> New Request
</button>
<button
@click="store.clearHistory()"
class="flex-none flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-medium bg-slate-800 hover:bg-red-500/10 hover:text-red-400 text-slate-400 rounded transition-all border border-slate-700 hover:border-red-500/50"
title="Clear History"
>
<Trash class="w-3.5 h-3.5" />
</button>
</div>
<!-- History List -->
<div class="flex-1 overflow-y-auto">
<div v-if="store.history.length === 0" class="p-8 text-center text-slate-600 text-xs">
No history yet. Make a request!
</div>
<div v-else class="flex flex-col">
<button
v-for="item in store.history"
:key="item.id"
@click="store.loadRequest(item)"
class="group flex flex-col text-left px-3 py-2 border-b border-slate-800/50 hover:bg-slate-900 transition-colors w-full"
>
<!-- First Row: Method, Status, Delete Button -->
<div class="flex items-center justify-between w-full">
<div class="flex items-center gap-2">
<MethodBadge :method="item.method" />
<!-- Status Badge -->
<span
v-if="item.response?.status"
class="text-[10px] font-mono font-bold px-1.5 py-0.5 rounded-full"
:class="getStatusColor(item.response?.status)"
>
{{ item.response.status }}
</span>
</div>
<!-- Delete Button -->
<button
@click.stop="store.deleteHistoryItem(item.id)"
class="opacity-0 group-hover:opacity-100 transition-opacity p-1.5 text-slate-500 hover:text-red-400 hover:bg-slate-800 rounded-md cursor-pointer flex-shrink-0"
>
<Trash2 class="w-3.5 h-3.5" />
</button>
</div>
<!-- Second Row: URL -->
<div class="mt-1">
<span class="text-xs text-slate-400 truncate font-medium block" :title="item.url">
{{ item.url || '/' }}
</span>
</div>
</button>
</div>
</div>
<!-- Settings -->
<div class="p-2 border-t border-slate-800">
<button
@click="emit('open-settings')"
class="w-full flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-400 hover:text-slate-200 hover:bg-slate-900 rounded transition-colors"
>
<Settings class="w-4 h-4" /> Settings
</button>
</div>
</aside>
</template>

View File

@@ -29,38 +29,124 @@ export interface RequestData {
body: string; body: string;
time: number; time: number;
size: number; size: number;
headersSize: number;
bodySize: number;
}; };
timestamp: number; timestamp: number;
} }
export interface RequestError {
code: string;
message: string;
}
const createEmptyKeyValue = (): KeyValue => ({
id: crypto.randomUUID(),
key: '',
value: '',
enabled: true,
});
const createDefaultAuthState = (): AuthState => ({
type: 'none',
basic: { username: '', password: '' },
bearer: { token: '' },
apiKey: { key: '', value: '', addTo: 'header' },
});
const createDefaultRequest = (): RequestData => ({
id: crypto.randomUUID(),
method: 'GET',
url: '',
params: [createEmptyKeyValue()],
headers: [createEmptyKeyValue()],
body: '',
auth: createDefaultAuthState(),
timestamp: Date.now(),
});
const cloneKeyValueList = (items: KeyValue[] | undefined): KeyValue[] => {
if (!Array.isArray(items) || items.length === 0) return [];
return items.map((item) => ({
id: item.id || crypto.randomUUID(),
key: item.key || '',
value: item.value || '',
enabled: item.enabled ?? true,
}));
};
const cloneAuthState = (auth: Partial<AuthState> | undefined): AuthState => ({
type: auth?.type || 'none',
basic: {
username: auth?.basic?.username || '',
password: auth?.basic?.password || '',
},
bearer: {
token: auth?.bearer?.token || '',
},
apiKey: {
key: auth?.apiKey?.key || '',
value: auth?.apiKey?.value || '',
addTo: auth?.apiKey?.addTo || 'header',
},
});
const cloneRequest = (req: Partial<RequestData>): RequestData => ({
id: typeof req.id === 'string' && req.id ? req.id : crypto.randomUUID(),
method: req.method || 'GET',
url: req.url || '',
params: cloneKeyValueList(req.params),
headers: cloneKeyValueList(req.headers),
body: req.body || '',
auth: cloneAuthState(req.auth),
response: req.response
? {
status: req.response.status,
headers: { ...req.response.headers },
body: req.response.body,
time: req.response.time,
size: req.response.size,
headersSize: req.response.headersSize ?? 0,
bodySize: req.response.bodySize ?? req.response.body.length,
}
: undefined,
timestamp: typeof req.timestamp === 'number' ? req.timestamp : Date.now(),
});
const normalizeHistoryItem = (item: Partial<RequestData>): RequestData => {
const cloned = cloneRequest(item);
return {
id: cloned.id,
method: cloned.method,
url: cloned.url,
params: cloned.params.length > 0
? cloned.params
: [createEmptyKeyValue()],
headers: cloned.headers.length > 0
? cloned.headers
: [createEmptyKeyValue()],
body: cloned.body,
auth: cloned.auth,
response: cloned.response,
timestamp: cloned.timestamp,
};
};
export const useRequestStore = defineStore('request', () => { export const useRequestStore = defineStore('request', () => {
// State // State
const history = ref<RequestData[]>([]); const history = ref<RequestData[]>([]);
const activeRequest = ref<RequestData>({ const activeRequest = ref<RequestData>(createDefaultRequest());
id: crypto.randomUUID(), const requestError = ref<RequestError | null>(null);
method: 'GET',
url: '',
params: [
{ id: crypto.randomUUID(), key: '', value: '', enabled: true }
],
headers: [
{ id: crypto.randomUUID(), key: '', value: '', enabled: true }
],
body: '',
auth: {
type: 'none',
basic: { username: '', password: '' },
bearer: { token: '' },
apiKey: { key: '', value: '', addTo: 'header' }
},
timestamp: Date.now(),
});
// Load history from local storage // Load history from local storage
const savedHistory = localStorage.getItem('request_history'); const savedHistory = localStorage.getItem('request_history');
if (savedHistory) { if (savedHistory) {
try { try {
history.value = JSON.parse(savedHistory); const parsed = JSON.parse(savedHistory);
history.value = Array.isArray(parsed)
? parsed.map((item) => normalizeHistoryItem(item))
: [];
} catch (e) { } catch (e) {
console.error('Failed to parse history', e); console.error('Failed to parse history', e);
} }
@@ -68,12 +154,11 @@ export const useRequestStore = defineStore('request', () => {
// Actions // Actions
const addToHistory = (req: RequestData) => { const addToHistory = (req: RequestData) => {
// Add to beginning, limit to 50 const newEntry = cloneRequest(req);
const newEntry = { ...req, timestamp: Date.now() }; newEntry.id = crypto.randomUUID();
// Don't store the empty trailing rows in history to save space? newEntry.timestamp = Date.now();
// Actually keep them for consistency or filter them. Let's filter empty keys. newEntry.params = newEntry.params.filter((p) => p.key.trim() !== '');
newEntry.params = newEntry.params.filter(p => p.key.trim() !== ''); newEntry.headers = newEntry.headers.filter((h) => h.key.trim() !== '');
newEntry.headers = newEntry.headers.filter(h => h.key.trim() !== '');
history.value.unshift(newEntry); history.value.unshift(newEntry);
if (history.value.length > 50) { if (history.value.length > 50) {
@@ -85,27 +170,30 @@ export const useRequestStore = defineStore('request', () => {
history.value = []; history.value = [];
}; };
const loadRequest = (req: RequestData) => { const deleteHistoryItem = (id: string) => {
// Deep copy const index = history.value.findIndex(item => item.id === id);
const loaded = JSON.parse(JSON.stringify(req)); if (index !== -1) {
loaded.id = crypto.randomUUID(); history.value.splice(index, 1);
loaded.response = undefined;
// Ensure at least one empty row for editing
if (loaded.params.length === 0) loaded.params.push({ id: crypto.randomUUID(), key: '', value: '', enabled: true });
if (loaded.headers.length === 0) loaded.headers.push({ id: crypto.randomUUID(), key: '', value: '', enabled: true });
// Ensure auth object exists (migration for old history)
if (!loaded.auth) {
loaded.auth = {
type: 'none',
basic: { username: '', password: '' },
bearer: { token: '' },
apiKey: { key: '', value: '', addTo: 'header' }
};
} }
};
const resetActiveRequest = () => {
activeRequest.value = createDefaultRequest();
requestError.value = null;
};
const loadRequest = (req: RequestData) => {
const loaded = normalizeHistoryItem(cloneRequest(req));
loaded.id = crypto.randomUUID();
if (loaded.params.length === 0) loaded.params.push(createEmptyKeyValue());
if (loaded.headers.length === 0) loaded.headers.push(createEmptyKeyValue());
activeRequest.value = loaded; activeRequest.value = loaded;
requestError.value = null;
};
const setRequestError = (error: RequestError | null) => {
requestError.value = error;
}; };
// Watch and Save // Watch and Save
@@ -116,8 +204,12 @@ export const useRequestStore = defineStore('request', () => {
return { return {
history, history,
activeRequest, activeRequest,
requestError,
addToHistory, addToHistory,
clearHistory, clearHistory,
loadRequest deleteHistoryItem,
loadRequest,
resetActiveRequest,
setRequestError,
}; };
}); });

View File

@@ -7,6 +7,21 @@ const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig(async () => ({ export default defineConfig(async () => ({
plugins: [vue()], plugins: [vue()],
build: {
rollupOptions: {
output: {
manualChunks: {
codemirror: [
'vue-codemirror',
'@codemirror/lang-json',
'@codemirror/theme-one-dark',
'@codemirror/view',
],
vue: ['vue', 'pinia'],
},
},
},
},
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build` // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
// //