Initial Commit

This commit is contained in:
Xyroscar
2024-11-06 19:31:39 +05:30
commit 2e29a1cb82
74 changed files with 10837 additions and 0 deletions

12
.gitignore vendored Normal file
View File

@@ -0,0 +1,12 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
src-tauri/target

7
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"recommendations": [
"svelte.svelte-vscode",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"svelte.enable-ts-plugin": true
}

7
README.md Normal file
View File

@@ -0,0 +1,7 @@
# Tauri + SvelteKit + TypeScript
This template should help get you started developing with Tauri, SvelteKit and TypeScript in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer).

BIN
bun.lockb Executable file

Binary file not shown.

38
package.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "api-client",
"version": "0.1.0",
"description": "",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri"
},
"license": "MIT",
"dependencies": {
"@tauri-apps/api": "^2.0.3",
"@tauri-apps/plugin-shell": ">=2.0.0",
"autoprefixer": "^10.4.20",
"daisyui": "^4.12.14",
"tailwind": "^4.0.0",
"tailwindcss": "^3.4.14"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.1",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^4.0.0",
"svelte": "^5.1.9",
"svelte-check": "^4.0.5",
"tslib": "^2.4.1",
"typescript": "^5.0.0",
"vite": "^5.0.3",
"@tauri-apps/cli": ">=2.0.0"
},
"trustedDependencies": [
"core-js",
"svelte-preprocess"
]
}

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}

4926
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

23
src-tauri/Cargo.toml Normal file
View File

@@ -0,0 +1,23 @@
[package]
name = "api-tester"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
license = ""
repository = ""
default-run = "api-tester"
edition = "2021"
rust-version = "1.60"
[build-dependencies]
tauri-build = { version = "2.0.2", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "2.0", features = [] }
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1.36", features = ["full"] }
uuid = { version = "1.7", features = ["v4", "serde"] }
rusqlite = "0.32"

3
src-tauri/build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@@ -0,0 +1,9 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default"
]
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"default":{"identifier":"default","description":"Capability for the main window","local":true,"windows":["main"],"permissions":["core:default"]}}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

75
src-tauri/src/api.rs Normal file
View File

@@ -0,0 +1,75 @@
use crate::models::{RequestBody, ResponseBody};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use std::collections::HashMap;
use std::str::FromStr;
use std::time::Instant;
pub async fn send_request(request: RequestBody) -> Result<ResponseBody, String> {
let client = reqwest::Client::new();
// Create headers
let mut headers = HeaderMap::new();
for header in request.headers.iter().filter(|h| h.enabled) {
headers.insert(
HeaderName::from_str(&header.key).map_err(|e| e.to_string())?,
HeaderValue::from_str(&header.value).map_err(|e| e.to_string())?,
);
}
let start_time = Instant::now();
// Build and send request
let response = match request.method.as_str() {
"GET" => client.get(&request.url),
"POST" => client.post(&request.url),
"PUT" => client.put(&request.url),
"DELETE" => client.delete(&request.url),
"PATCH" => client.patch(&request.url),
_ => return Err("Unsupported HTTP method".to_string()),
}
.headers(headers);
// Add body for methods that support it
let response = if let Some(body) = request.body {
response.body(body)
} else {
response
};
// Send the request
let response = response
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
// Process response
let status = response.status().as_u16();
let status_text = response.status().to_string();
// Convert response headers
let headers: HashMap<String, String> = response
.headers()
.iter()
.map(|(k, v)| {
(
k.to_string(),
v.to_str().unwrap_or("").to_string(),
)
})
.collect();
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response body: {}", e))?;
let elapsed = start_time.elapsed().as_millis();
Ok(ResponseBody {
status,
status_text,
headers,
body,
time: elapsed,
})
}

View File

@@ -0,0 +1,49 @@
use crate::storage::{Storage, Collection};
use std::sync::Mutex;
use tauri::State;
#[tauri::command]
pub async fn create_collection(
state: State<'_, Mutex<Storage>>,
workspace_id: String,
name: String,
description: Option<String>,
) -> Result<Collection, String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage
.create_collection(&workspace_id, &name, description.as_deref())
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn get_workspace_collections(
state: State<'_, Mutex<Storage>>,
workspace_id: String,
) -> Result<Vec<Collection>, String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage
.get_workspace_collections(&workspace_id)
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn update_collection(
state: State<'_, Mutex<Storage>>,
id: String,
name: String,
description: Option<String>,
) -> Result<Collection, String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage
.update_collection(&id, &name, description.as_deref())
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn delete_collection(
state: State<'_, Mutex<Storage>>,
id: String,
) -> Result<(), String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage.delete_collection(&id).map_err(|e| e.to_string())
}

View File

@@ -0,0 +1,5 @@
mod workspace;
mod collection;
pub use workspace::*;
pub use collection::*;

View File

@@ -0,0 +1,54 @@
use crate::storage::{Storage, Workspace};
use std::sync::Mutex;
use tauri::State;
#[tauri::command]
pub async fn create_workspace(
state: State<'_, Mutex<Storage>>,
name: String,
description: Option<String>,
) -> Result<Workspace, String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage
.create_workspace(&name, description.as_deref())
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn get_workspaces(
state: State<'_, Mutex<Storage>>,
) -> Result<Vec<Workspace>, String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage.get_workspaces().map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn get_workspace(
state: State<'_, Mutex<Storage>>,
id: String,
) -> Result<Option<Workspace>, String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage.get_workspace(&id).map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn update_workspace(
state: State<'_, Mutex<Storage>>,
id: String,
name: String,
description: Option<String>,
) -> Result<Workspace, String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage
.update_workspace(&id, &name, description.as_deref())
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn delete_workspace(
state: State<'_, Mutex<Storage>>,
id: String,
) -> Result<(), String> {
let mut storage = state.lock().map_err(|e| e.to_string())?;
storage.delete_workspace(&id).map_err(|e| e.to_string())
}

13
src-tauri/src/lib.rs Normal file
View File

@@ -0,0 +1,13 @@
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

35
src-tauri/src/main.rs Normal file
View File

@@ -0,0 +1,35 @@
mod api;
mod models;
mod storage;
mod commands;
use storage::Storage;
use tauri::Manager;
use std::sync::Mutex;
fn main() {
tauri::Builder::default()
.setup(|app| {
let app_dir = app.path().app_data_dir()
.expect("Failed to get app data dir");
let storage = Storage::new(app_dir)
.expect("Failed to initialize storage");
app.manage(Mutex::new(storage));
Ok(())
})
.invoke_handler(tauri::generate_handler![
commands::create_workspace,
commands::get_workspaces,
commands::get_workspace,
commands::update_workspace,
commands::delete_workspace,
commands::create_collection,
commands::get_workspace_collections,
commands::update_collection,
commands::delete_collection,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

35
src-tauri/src/models.rs Normal file
View File

@@ -0,0 +1,35 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Variable {
pub id: String,
pub name: String,
pub value: String,
pub description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Header {
pub id: String,
pub key: String,
pub value: String,
pub enabled: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RequestBody {
pub url: String,
pub method: String,
pub headers: Vec<Header>,
pub body: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct ResponseBody {
pub status: u16,
pub status_text: String,
pub headers: HashMap<String, String>,
pub body: String,
pub time: u128,
}

View File

@@ -0,0 +1,103 @@
use super::*;
use rusqlite::{params, Result};
impl Storage {
pub fn create_collection(
&mut self,
workspace_id: &str,
name: &str,
description: Option<&str>,
) -> Result<Collection> {
let now = Self::now();
let id = uuid::Uuid::new_v4().to_string();
self.conn.get_mut().unwrap().execute(
"INSERT INTO collections (id, workspace_id, name, description, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![id, workspace_id, name, description, now, now],
)?;
Ok(Collection {
id,
workspace_id: workspace_id.to_string(),
name: name.to_string(),
description: description.map(String::from),
created_at: now,
updated_at: now,
})
}
pub fn get_workspace_collections(&mut self, workspace_id: &str) -> Result<Vec<Collection>> {
let mut stmt = self.conn.get_mut().unwrap().prepare(
"SELECT id, workspace_id, name, description, created_at, updated_at
FROM collections
WHERE workspace_id = ?
ORDER BY created_at DESC"
)?;
let collections = stmt.query_map([workspace_id], |row| {
Ok(Collection {
id: row.get(0)?,
workspace_id: row.get(1)?,
name: row.get(2)?,
description: row.get(3)?,
created_at: row.get(4)?,
updated_at: row.get(5)?,
})
})?;
collections.collect()
}
pub fn update_collection(
&mut self,
id: &str,
name: &str,
description: Option<&str>,
) -> Result<Collection> {
let now = Self::now();
self.conn.get_mut().unwrap().execute(
"UPDATE collections
SET name = ?1, description = ?2, updated_at = ?3
WHERE id = ?4",
params![name, description, now, id],
)?;
let mut stmt = self.conn.get_mut().unwrap().prepare(
"SELECT workspace_id, created_at FROM collections WHERE id = ?"
)?;
let (workspace_id, created_at) = stmt.query_row([id], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
})?;
Ok(Collection {
id: id.to_string(),
workspace_id,
name: name.to_string(),
description: description.map(String::from),
created_at,
updated_at: now,
})
}
pub fn delete_collection(&mut self, id: &str) -> Result<()> {
let tx = self.conn.get_mut().unwrap().transaction()?;
// Delete all requests in this collection
tx.execute(
"DELETE FROM requests WHERE collection_id = ?",
params![id],
)?;
// Delete the collection
tx.execute(
"DELETE FROM collections WHERE id = ?",
params![id],
)?;
tx.commit()?;
Ok(())
}
}

View File

@@ -0,0 +1,158 @@
mod workspace;
mod collection;
pub use workspace::*;
pub use collection::*;
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::fs;
use std::sync::RwLock;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Serialize, Deserialize)]
pub struct Workspace {
pub id: String,
pub name: String,
pub description: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Collection {
pub id: String,
pub workspace_id: String,
pub name: String,
pub description: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Variable {
pub id: String,
pub workspace_id: String,
pub name: String,
pub value: String,
pub description: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Request {
pub id: String,
pub collection_id: String,
pub name: String,
pub method: String,
pub url: String,
pub created_at: i64,
pub updated_at: i64,
}
pub struct Storage {
conn: RwLock<Connection>,
data_dir: PathBuf,
}
impl Storage {
pub fn new(app_dir: PathBuf) -> rusqlite::Result<Self> {
let db_path = app_dir.join("api-client.db");
let data_dir = app_dir.join("data");
fs::create_dir_all(&data_dir).map_err(|e| rusqlite::Error::InvalidPath(data_dir.clone()))?;
let conn = Connection::open(db_path)?;
Self::init_database(&conn)?;
Ok(Storage { conn: RwLock::new(conn), data_dir })
}
fn init_database(conn: &Connection) -> rusqlite::Result<()> {
conn.execute(
"CREATE TABLE IF NOT EXISTS workspaces (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS collections (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY(workspace_id) REFERENCES workspaces(id)
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS variables (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
name TEXT NOT NULL,
value TEXT NOT NULL,
description TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY(workspace_id) REFERENCES workspaces(id)
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS requests (
id TEXT PRIMARY KEY,
collection_id TEXT NOT NULL,
name TEXT NOT NULL,
method TEXT NOT NULL,
url TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY(collection_id) REFERENCES collections(id)
)",
[],
)?;
// Create indexes
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_collections_workspace
ON collections(workspace_id)",
[],
)?;
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_variables_workspace
ON variables(workspace_id)",
[],
)?;
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_requests_collection
ON requests(collection_id)",
[],
)?;
Ok(())
}
pub(crate) fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64
}
pub(crate) fn get_request_data_path(&self, request_id: &str) -> PathBuf {
self.data_dir.join(format!("request_{}.json", request_id))
}
}

View File

@@ -0,0 +1,115 @@
use super::*;
use rusqlite::{params, Result, OptionalExtension};
impl Storage {
pub fn create_workspace(&mut self, name: &str, description: Option<&str>) -> Result<Workspace> {
let now = Self::now();
let id = uuid::Uuid::new_v4().to_string();
self.conn.get_mut().unwrap().execute(
"INSERT INTO workspaces (id, name, description, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![id, name, description, now, now],
)?;
Ok(Workspace {
id,
name: name.to_string(),
description: description.map(String::from),
created_at: now,
updated_at: now,
})
}
pub fn get_workspaces(&mut self) -> Result<Vec<Workspace>> {
let mut stmt = self.conn.get_mut().unwrap().prepare(
"SELECT id, name, description, created_at, updated_at
FROM workspaces
ORDER BY created_at DESC"
)?;
let workspace_iter = stmt.query_map([], |row| {
Ok(Workspace {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
created_at: row.get(3)?,
updated_at: row.get(4)?,
})
})?;
workspace_iter.collect()
}
pub fn get_workspace(&mut self, id: &str) -> Result<Option<Workspace>> {
let mut stmt = self.conn.get_mut().unwrap().prepare(
"SELECT id, name, description, created_at, updated_at
FROM workspaces
WHERE id = ?"
)?;
stmt.query_row(params![id], |row| {
Ok(Workspace {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
created_at: row.get(3)?,
updated_at: row.get(4)?,
})
})
.optional()
}
pub fn update_workspace(&mut self, id: &str, name: &str, description: Option<&str>) -> Result<Workspace> {
let now = Self::now();
self.conn.get_mut().unwrap().execute(
"UPDATE workspaces
SET name = ?1, description = ?2, updated_at = ?3
WHERE id = ?4",
params![name, description, now, id],
)?;
Ok(Workspace {
id: id.to_string(),
name: name.to_string(),
description: description.map(String::from),
created_at: self.get_workspace(id)?.map(|w| w.created_at).unwrap_or(now),
updated_at: now,
})
}
pub fn delete_workspace(&mut self, id: &str) -> Result<()> {
// Start a transaction to ensure data consistency
let tx = self.conn.get_mut().unwrap().transaction()?;
// Delete variables
tx.execute(
"DELETE FROM variables WHERE workspace_id = ?",
params![id],
)?;
// Delete requests from collections in this workspace
tx.execute(
"DELETE FROM requests
WHERE collection_id IN (
SELECT id FROM collections WHERE workspace_id = ?
)",
params![id],
)?;
// Delete collections
tx.execute(
"DELETE FROM collections WHERE workspace_id = ?",
params![id],
)?;
// Finally delete the workspace
tx.execute("DELETE FROM workspaces WHERE id = ?", params![id])?;
// Commit the transaction
tx.commit()?;
Ok(())
}
}

35
src-tauri/tauri.conf.json Normal file
View File

@@ -0,0 +1,35 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "api-client",
"version": "0.1.0",
"identifier": "com.api-client.app",
"build": {
"beforeDevCommand": "bun run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "bun run build",
"frontendDist": "../build"
},
"app": {
"windows": [
{
"title": "api-client",
"width": 800,
"height": 600
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

1
src/App.svelte Normal file
View File

@@ -0,0 +1 @@
<slot />

19
src/app.css Normal file
View File

@@ -0,0 +1,19 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--sidebar-width: 300px;
}
body {
@apply bg-base-100 text-base-content;
}
.drawer-side {
width: var(--sidebar-width) !important;
}
.drawer.drawer-open > .drawer-content {
padding-left: var(--sidebar-width);
}

13
src/app.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tauri + SvelteKit + Typescript App</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View File

@@ -0,0 +1,311 @@
<script lang="ts">
import { invoke } from '@tauri-apps/api/core';
import { activeRequest, variables, currentResponse } from '../../stores';
import type { Header, QueryParam } from '../../types';
let url = '';
let method = 'GET';
let headers: Header[] = [];
let queryParams: QueryParam[] = [];
let body = '';
let loading = false;
let activeTab = 'headers';
const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
// Subscribe to activeRequest changes
$: if ($activeRequest) {
url = $activeRequest.url;
method = $activeRequest.method;
headers = $activeRequest.headers;
queryParams = $activeRequest.queryParams || [];
body = $activeRequest.body || '';
}
function addHeader() {
headers = [...headers, {
id: crypto.randomUUID(),
key: '',
value: '',
enabled: true
}];
}
function addQueryParam() {
queryParams = [...queryParams, {
id: crypto.randomUUID(),
key: '',
value: '',
enabled: true
}];
}
function removeHeader(id: string) {
headers = headers.filter(h => h.id !== id);
}
function removeQueryParam(id: string) {
queryParams = queryParams.filter(p => p.id !== id);
}
function interpolateVariables(value: string): string {
return value.replace(/\{\{(.+?)\}\}/g, (_, key) => {
const variable = $variables.find(v => v.name === key.trim());
return variable ? variable.value : `{{${key}}}`;
});
}
function buildUrl(baseUrl: string, params: QueryParam[]): string {
try {
if (!baseUrl) return '';
const url = new URL(baseUrl);
params
.filter(p => p.enabled && p.key)
.forEach(p => {
try {
url.searchParams.append(
interpolateVariables(p.key),
interpolateVariables(p.value || '') // Handle undefined value
);
} catch (error) {
console.error('Error appending parameter:', error);
}
});
return url.toString();
} catch (error) {
console.error('Error building URL:', error);
return baseUrl; // Return original URL if there's an error
}
}
async function sendRequest() {
loading = true;
try {
const interpolatedHeaders = headers.map(h => ({
...h,
key: interpolateVariables(h.key),
value: interpolateVariables(h.value)
}));
const request = {
url: buildUrl(interpolateVariables(url), queryParams),
method,
headers: interpolatedHeaders,
body: body ? interpolateVariables(body) : undefined
};
const response = await invoke<{
status: number;
statusText: string;
headers: Record<string, string>;
body: string;
time: number;
}>('send_api_request', { request });
currentResponse.set(response);
} catch (error) {
console.error('Error:', error);
} finally {
loading = false;
}
}
// Add these functions to handle tab clicks explicitly
function setActiveTab(tab: 'headers' | 'body' | 'query') {
activeTab = tab;
}
// Separate function to handle query param updates
function updateQueryParam(param: QueryParam, field: 'key' | 'value' | 'enabled', value: string | boolean) {
queryParams = queryParams.map(p =>
p.id === param.id
? { ...p, [field]: value }
: p
);
}
</script>
<div class="card bg-base-100 shadow-lg border border-base-300">
<div class="card-body p-4">
<div class="flex space-x-2">
<div class="join flex-1">
<select
class="select select-bordered join-item w-28 font-medium"
bind:value={method}
>
{#each methods as m}
<option value={m}>{m}</option>
{/each}
</select>
<input
type="text"
placeholder="Enter request URL"
class="input input-bordered join-item flex-1 min-w-[400px]"
bind:value={url}
/>
<button
class="btn join-item btn-primary"
on:click={sendRequest}
disabled={loading || !url}
>
{#if loading}
<span class="loading loading-spinner loading-sm"></span>
{:else}
Send
{/if}
</button>
</div>
</div>
<div class="tabs tabs-boxed bg-base-200 mt-4">
<a
href="#headers"
class="tab"
class:tab-active={activeTab === 'headers'}
on:click|preventDefault={() => setActiveTab('headers')}
>
Headers
</a>
<a
href="#body"
class="tab"
class:tab-active={activeTab === 'body'}
on:click|preventDefault={() => setActiveTab('body')}
>
Body
</a>
<a
href="#query"
class="tab"
class:tab-active={activeTab === 'query'}
on:click|preventDefault={() => setActiveTab('query')}
>
Query
</a>
</div>
<!-- Headers Section -->
<div class="mt-4" class:hidden={activeTab !== 'headers'}>
<div class="flex justify-between items-center mb-2">
<h3 class="text-sm font-medium opacity-70">Request Headers</h3>
<button
type="button"
class="btn btn-sm btn-ghost"
on:click={() => addHeader()}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
Add Header
</button>
</div>
<div class="space-y-2">
{#each headers as header (header.id)}
<div class="join w-full">
<input
type="checkbox"
class="checkbox join-item ml-2"
bind:checked={header.enabled}
/>
<input
type="text"
placeholder="Header name"
class="input input-bordered input-sm join-item w-1/3"
bind:value={header.key}
/>
<input
type="text"
placeholder="Value"
class="input input-bordered input-sm join-item flex-1"
bind:value={header.value}
/>
<button
type="button"
class="btn btn-sm join-item btn-ghost text-error"
on:click={() => removeHeader(header.id)}
>
×
</button>
</div>
{/each}
</div>
</div>
<!-- Body Section -->
<div class="mt-4" class:hidden={activeTab !== 'body'}>
<h3 class="text-sm font-medium opacity-70 mb-2">Request Body</h3>
<textarea
class="textarea textarea-bordered w-full h-48 font-mono text-sm"
placeholder="Enter JSON body"
bind:value={body}
></textarea>
</div>
<!-- Query Section -->
<div class="mt-4" class:hidden={activeTab !== 'query'}>
<div class="flex justify-between items-center mb-2">
<h3 class="text-sm font-medium opacity-70">Query Parameters</h3>
<button
type="button"
class="btn btn-sm btn-ghost"
on:click={addQueryParam}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
Add Parameter
</button>
</div>
<div class="space-y-2">
{#each queryParams as param (param.id)}
<div class="join w-full">
<input
type="checkbox"
class="checkbox join-item ml-2"
checked={param.enabled}
on:change={(e) => updateQueryParam(param, 'enabled', e.currentTarget.checked)}
/>
<input
type="text"
placeholder="Parameter name"
class="input input-bordered input-sm join-item w-1/3"
value={param.key}
on:input={(e) => updateQueryParam(param, 'key', e.currentTarget.value)}
/>
<input
type="text"
placeholder="Value"
class="input input-bordered input-sm join-item flex-1"
value={param.value}
on:input={(e) => updateQueryParam(param, 'value', e.currentTarget.value)}
/>
<button
type="button"
class="btn btn-sm join-item btn-ghost text-error"
on:click={() => removeQueryParam(param.id)}
>
×
</button>
</div>
{/each}
</div>
{#if queryParams.length > 0 && url}
<div class="mt-4">
<h4 class="text-sm font-medium opacity-70 mb-2">Preview URL</h4>
<div class="bg-base-200 p-3 rounded-lg">
<code class="text-xs break-all">
{buildUrl(url, queryParams)}
</code>
</div>
</div>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,85 @@
<script lang="ts">
import { currentResponse } from '../../stores';
let activeTab = 'body';
function formatJson(json: string): string {
try {
return JSON.stringify(JSON.parse(json), null, 2);
} catch {
return json;
}
}
function getStatusColor(status: number): string {
if (status >= 200 && status < 300) return 'text-success';
if (status >= 400) return 'text-error';
return 'text-warning';
}
</script>
{#if $currentResponse}
<div class="card bg-base-100 shadow-lg border border-base-300">
<div class="card-body p-4">
<!-- Status and Time -->
<div class="flex justify-between items-center">
<div class="flex items-center space-x-2">
<span class={getStatusColor($currentResponse.status)}>
{$currentResponse.status}
</span>
<span class="text-base-content/70">
{$currentResponse.statusText}
</span>
</div>
<span class="text-base-content/70">
{$currentResponse.time}ms
</span>
</div>
<!-- Tabs -->
<div class="tabs tabs-boxed bg-base-200 mt-4">
<button
class="tab"
class:tab-active={activeTab === 'body'}
on:click={() => activeTab = 'body'}
>
Response Body
</button>
<button
class="tab"
class:tab-active={activeTab === 'headers'}
on:click={() => activeTab = 'headers'}
>
Response Headers
</button>
</div>
<!-- Content -->
{#if activeTab === 'body'}
<div class="bg-base-200 rounded-lg mt-4">
<pre class="overflow-x-auto p-4 text-sm">
<code>{formatJson($currentResponse.body)}</code>
</pre>
</div>
{:else}
<div class="overflow-x-auto mt-4">
<table class="table table-sm">
<thead>
<tr>
<th>Header</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{#each Object.entries($currentResponse.headers) as [key, value]}
<tr>
<td class="font-mono text-sm">{key}</td>
<td class="font-mono text-sm">{value}</td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
</div>
</div>
{/if}

View File

@@ -0,0 +1,87 @@
<script lang="ts">
import { collections, variables, activeCollection, activeRequest } from '../../stores';
import type { Collection, Request } from '../../types';
import CollectionModal from './modals/CollectionModal.svelte';
let showCollectionModal = false;
function selectRequest(collection: Collection, request: Request) {
activeCollection.set(collection);
activeRequest.set(request);
}
function handleCollectionSave(event: CustomEvent<Collection>) {
collections.update(cols => [...cols, event.detail]);
showCollectionModal = false;
}
</script>
<div class="bg-base-200 min-h-screen h-full p-4 border-r border-base-300">
<!-- Collections Section -->
<div class="flex flex-col">
<div class="flex justify-between items-center mb-4">
<h2 class="font-medium flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z" />
</svg>
Collections
</h2>
<button class="btn btn-sm btn-primary" on:click={() => showCollectionModal = true}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
New
</button>
</div>
{#if $collections.length === 0}
<div class="bg-base-100 rounded-lg p-4 text-center">
<p class="text-sm text-base-content/70">No collections yet</p>
<p class="text-xs text-base-content/50 mt-1">Create a new collection to get started</p>
</div>
{/if}
{#each $collections as collection}
<div class="collapse collapse-arrow bg-base-100 shadow-sm mb-2">
<input type="checkbox" />
<div class="collapse-title font-medium">
{collection.name}
</div>
<div class="collapse-content">
<div class="flex flex-col gap-1">
{#each collection.requests as request}
<button
class="flex items-center w-full px-3 py-2 hover:bg-base-300 rounded-lg text-left transition-colors"
class:bg-primary-content={$activeRequest?.id === request.id}
on:click={() => selectRequest(collection, request)}
>
<span class="text-xs font-medium px-2 py-0.5 rounded mr-2"
class:bg-success={request.method === 'GET'}
class:bg-info={request.method === 'POST'}
class:bg-warning={request.method === 'PUT'}
class:bg-error={request.method === 'DELETE'}
>
{request.method}
</span>
<span class="text-sm truncate">{request.name}</span>
</button>
{/each}
<button class="btn btn-sm btn-ghost mt-2 w-full">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
Add Request
</button>
</div>
</div>
</div>
{/each}
</div>
</div>
<CollectionModal
show={showCollectionModal}
on:save={handleCollectionSave}
on:close={() => showCollectionModal = false}
/>

View File

@@ -0,0 +1,99 @@
<script lang="ts">
import { goto } from '$app/navigation';
import type { Workspace } from '../../types';
import { formatDate } from '../utils/date';
import { collections } from '$lib/stores/collection';
import { workspaces } from '$lib/stores/workspace';
import WorkspaceModal from './modals/WorkspaceModal.svelte';
export let workspace: Workspace;
let showEditModal = false;
function openWorkspace() {
goto(`/workspace/${workspace.id}`);
}
function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
openWorkspace();
}
}
async function handleDelete(event: MouseEvent) {
event.stopPropagation();
if (confirm('Are you sure you want to delete this workspace?')) {
try {
await workspaces.deleteWorkspace(workspace.id);
} catch (error) {
console.error('Failed to delete workspace:', error);
}
}
}
function handleEdit(event: MouseEvent) {
event.stopPropagation();
showEditModal = true;
}
// Compute collections and variables count
$: workspaceCollections = $collections.filter(c => c.workspace_id === workspace.id);
$: workspaceVariables = workspace.variables || [];
</script>
<div class="w-full">
<button
class="card bg-base-100 shadow-lg hover:shadow-xl transition-shadow w-full text-left"
on:click={openWorkspace}
on:keydown={handleKeyDown}
>
<div class="card-body p-6">
<div class="flex justify-between items-start">
<h2 class="card-title text-xl">{workspace.name}</h2>
<div class="dropdown dropdown-end">
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="btn btn-ghost btn-sm btn-square"
on:click|stopPropagation
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
</svg>
</div>
<ul class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52">
<li><a href="#top" on:click|preventDefault={handleEdit}>Edit</a></li>
<li><a href="#top" class="text-error" on:click|preventDefault={handleDelete}>Delete</a></li>
</ul>
</div>
</div>
{#if workspace.description}
<p class="text-base-content/70 text-sm mt-2">{workspace.description}</p>
{/if}
<div class="flex gap-6 mt-6">
<div class="stat bg-base-200 rounded-lg p-4">
<div class="stat-title text-xs">Collections</div>
<div class="stat-value text-lg">{workspaceCollections.length}</div>
</div>
<div class="stat bg-base-200 rounded-lg p-4">
<div class="stat-title text-xs">Variables</div>
<div class="stat-value text-lg">{workspaceVariables.length}</div>
</div>
</div>
<div class="card-actions justify-end mt-4">
<div class="text-xs text-base-content/50">
Updated {formatDate(workspace.updated_at)}
</div>
</div>
</div>
</button>
</div>
<WorkspaceModal
show={showEditModal}
{workspace}
on:close={() => showEditModal = false}
/>

View File

@@ -0,0 +1,120 @@
<script lang="ts">
import { workspaces, activeWorkspace } from '../stores/workspace';
import { onMount } from 'svelte';
let showCreateModal = false;
let newWorkspaceName = '';
let newWorkspaceDescription = '';
let showDropdown = false;
onMount(() => {
workspaces.loadWorkspaces();
});
async function handleCreateWorkspace() {
try {
const workspace = await workspaces.createWorkspace(
newWorkspaceName,
newWorkspaceDescription || undefined
);
activeWorkspace.set(workspace);
showCreateModal = false;
newWorkspaceName = '';
newWorkspaceDescription = '';
} catch (error) {
console.error('Failed to create workspace:', error);
}
}
</script>
<div class="dropdown">
<button type="button" class="btn m-1" aria-haspopup="true" aria-expanded={showDropdown}>
{#if $activeWorkspace}
{$activeWorkspace.name}
{:else}
Select Workspace
{/if}
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 ml-2" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</button>
<div
class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52"
role="menu"
>
{#each $workspaces as workspace}
<li>
<button
class="btn btn-ghost justify-start"
class:btn-active={$activeWorkspace?.id === workspace.id}
on:click={() => activeWorkspace.set(workspace)}
>
{workspace.name}
</button>
</li>
{/each}
<li>
<button
class="btn btn-ghost justify-start text-primary"
on:click={() => showCreateModal = true}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
New Workspace
</button>
</li>
</div>
</div>
{#if showCreateModal}
<div class="modal modal-open">
<div class="modal-box">
<h3 class="font-bold text-lg">Create New Workspace</h3>
<form on:submit|preventDefault={handleCreateWorkspace} class="mt-4">
<div class="form-control">
<label class="label" for="name">
<span class="label-text">Workspace Name</span>
</label>
<input
type="text"
id="name"
class="input input-bordered"
bind:value={newWorkspaceName}
placeholder="My Workspace"
required
/>
</div>
<div class="form-control mt-4">
<label class="label" for="description">
<span class="label-text">Description</span>
</label>
<textarea
id="description"
class="textarea textarea-bordered"
bind:value={newWorkspaceDescription}
placeholder="Optional description"
/>
</div>
<div class="modal-action">
<button
type="button"
class="btn"
on:click={() => showCreateModal = false}
>
Cancel
</button>
<button
type="submit"
class="btn btn-primary"
disabled={!newWorkspaceName}
>
Create
</button>
</div>
</form>
</div>
</div>
{/if}

View File

@@ -0,0 +1,51 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { activeWorkspace } from '../stores/workspace';
import VariablesModal from './modals/VariablesModal.svelte';
let showVariablesModal = false;
function goToWorkspaces() {
goto('/');
}
</script>
<div class="navbar bg-base-100 border-b border-base-300">
<div class="flex-none lg:hidden">
<label for="drawer" class="btn btn-square btn-ghost">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="inline-block w-6 h-6 stroke-current">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
</svg>
</label>
</div>
<div class="flex-1 flex items-center gap-2">
<button
class="btn btn-ghost btn-sm"
on:click={goToWorkspaces}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
</svg>
All Workspaces
</button>
<span class="text-xl font-bold">{$activeWorkspace?.name}</span>
</div>
<div class="flex-none">
<button
class="btn btn-ghost btn-sm"
on:click={() => showVariablesModal = true}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M4.649 3.084A1 1 0 015.163 4.4 13.95 13.95 0 004 10c0 1.993.416 3.886 1.164 5.6a1 1 0 01-1.832.8A15.95 15.95 0 012 10c0-2.274.475-4.44 1.332-6.4a1 1 0 011.317-.516zM12.96 7a3 3 0 00-2.342 1.126l-.328.41-.111-.279A2 2 0 008.323 7H8a1 1 0 000 2h.323l.532 1.33-1.035 1.295a1 1 0 01-.781.375H7a1 1 0 100 2h.039a3 3 0 002.342-1.126l.328-.41.111.279A2 2 0 0011.677 14H12a1 1 0 100-2h-.323l-.532-1.33 1.035-1.295A1 1 0 0112.961 9H13a1 1 0 100-2h-.039z" clip-rule="evenodd" />
</svg>
Variables
</button>
</div>
</div>
<VariablesModal
show={showVariablesModal}
on:close={() => showVariablesModal = false}
/>

View File

@@ -0,0 +1,97 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import type { Collection } from '../../../types';
import { collections } from '../../stores/collection';
import { activeWorkspace } from '../../stores/workspace';
export let show = false;
export let collection: Collection | null = null;
let name = '';
let description = '';
$: if (collection) {
name = collection.name;
description = collection.description || '';
}
const dispatch = createEventDispatcher<{
close: void;
}>();
async function handleSubmit() {
try {
if (!$activeWorkspace) return;
if (collection) {
await collections.updateCollection(
collection.id,
name,
description || undefined
);
} else {
await collections.createCollection(
$activeWorkspace.id,
name,
description || undefined
);
}
handleClose();
} catch (error) {
console.error('Failed to save collection:', error);
}
}
function handleClose() {
name = '';
description = '';
dispatch('close');
}
</script>
{#if show}
<div class="modal modal-open">
<div class="modal-box">
<h3 class="font-bold text-lg">
{collection ? 'Edit' : 'Create New'} Collection
</h3>
<form on:submit|preventDefault={handleSubmit} class="mt-4">
<div class="form-control">
<label class="label" for="name">
<span class="label-text">Collection Name</span>
</label>
<input
type="text"
id="name"
class="input input-bordered"
bind:value={name}
placeholder="My Collection"
required
/>
</div>
<div class="form-control mt-4">
<label class="label" for="description">
<span class="label-text">Description</span>
</label>
<textarea
id="description"
class="textarea textarea-bordered"
bind:value={description}
placeholder="Optional description"
></textarea>
</div>
<div class="modal-action">
<button type="button" class="btn" on:click={handleClose}>
Cancel
</button>
<button type="submit" class="btn btn-primary" disabled={!name}>
{collection ? 'Save' : 'Create'}
</button>
</div>
</form>
</div>
</div>
{/if}

View File

@@ -0,0 +1,77 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import type { Variable } from '../../../types';
import { activeWorkspace } from '../../stores/workspace';
export let show = false;
let variables: Variable[] = [];
$: if ($activeWorkspace) {
variables = $activeWorkspace.variables || [];
}
const dispatch = createEventDispatcher<{
close: void;
}>();
function addVariable() {
variables = [...variables, {
id: crypto.randomUUID(),
name: '',
value: '',
description: ''
}];
}
function removeVariable(id: string) {
variables = variables.filter(v => v.id !== id);
}
async function handleSave() {
// TODO: Implement variable saving
dispatch('close');
}
</script>
{#if show}
<div class="modal modal-open">
<div class="modal-box max-w-3xl">
<h3 class="font-bold text-lg mb-4">Workspace Variables</h3>
<div class="space-y-4">
{#each variables as variable (variable.id)}
<div class="flex gap-2">
<input
type="text"
class="input input-bordered w-1/3"
placeholder="Variable name"
bind:value={variable.name}
/>
<input
type="text"
class="input input-bordered flex-1"
placeholder="Value"
bind:value={variable.value}
/>
<button
class="btn btn-ghost btn-sm text-error"
on:click={() => removeVariable(variable.id)}
>
×
</button>
</div>
{/each}
<button class="btn btn-ghost btn-sm w-full" on:click={addVariable}>
Add Variable
</button>
</div>
<div class="modal-action">
<button class="btn" on:click={() => dispatch('close')}>Cancel</button>
<button class="btn btn-primary" on:click={handleSave}>Save Changes</button>
</div>
</div>
</div>
{/if}

View File

@@ -0,0 +1,142 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import { workspaces } from '../../stores/workspace';
import type { Workspace } from '../../../types';
export let show = false;
export let workspace: Workspace | null = null;
let name = '';
let description = '';
let isSubmitting = false;
let error = '';
let initialized = false;
$: if (show && !initialized) {
if (workspace) {
name = workspace.name;
description = workspace.description || '';
} else {
name = '';
description = '';
}
initialized = true;
error = '';
}
$: if (!show) {
initialized = false;
}
const dispatch = createEventDispatcher<{
close: void;
}>();
async function handleSubmit(event: SubmitEvent) {
event.preventDefault();
if (isSubmitting) return;
error = '';
try {
isSubmitting = true;
if (workspace) {
await workspaces.updateWorkspace(
workspace.id,
name,
description || undefined
);
} else {
await workspaces.createWorkspace(
name,
description || undefined
);
}
handleClose();
} catch (e) {
error = e instanceof Error ? e.message : 'Failed to save workspace';
console.error('Failed to save workspace:', e);
} finally {
isSubmitting = false;
}
}
function handleClose() {
name = '';
description = '';
error = '';
initialized = false;
dispatch('close');
}
</script>
<div class="modal {show ? 'modal-open' : ''}" role="dialog">
<div class="modal-box">
<h3 class="font-bold text-lg">
{workspace ? 'Edit' : 'Create New'} Workspace
</h3>
<form on:submit={handleSubmit} class="mt-4">
{#if error}
<div class="alert alert-error mb-4">
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
<span>{error}</span>
</div>
{/if}
<div class="form-control">
<label class="label" for="name">
<span class="label-text">Workspace Name</span>
</label>
<input
type="text"
id="name"
class="input input-bordered"
bind:value={name}
placeholder="My Workspace"
required
/>
</div>
<div class="form-control mt-4">
<label class="label" for="description">
<span class="label-text">Description</span>
</label>
<textarea
id="description"
class="textarea textarea-bordered"
bind:value={description}
placeholder="Optional description"
></textarea>
</div>
<div class="modal-action">
<button
type="button"
class="btn"
on:click={handleClose}
disabled={isSubmitting}
>
Cancel
</button>
<button
type="submit"
class="btn btn-primary"
disabled={!name || isSubmitting}
>
{#if isSubmitting}
<span class="loading loading-spinner loading-sm"></span>
{/if}
{workspace ? 'Save' : 'Create'}
</button>
</div>
</form>
</div>
<button
type="button"
class="modal-backdrop"
on:click={handleClose}
aria-label="Close modal"
></button>
</div>

View File

@@ -0,0 +1,72 @@
import { writable, derived } from 'svelte/store';
import { invoke } from '@tauri-apps/api/core';
import type { Collection } from '../../types';
import { activeWorkspace } from './workspace';
function createCollectionStore() {
const { subscribe, set, update } = writable<Collection[]>([]);
return {
subscribe,
loadCollections: async (workspaceId: string) => {
try {
const collections = await invoke<Collection[]>('get_workspace_collections', {
workspaceId
});
set(collections);
} catch (error) {
console.error('Error loading collections:', error);
set([]);
}
},
createCollection: async (workspaceId: string, name: string, description?: string) => {
try {
const collection = await invoke<Collection>('create_collection', {
workspaceId,
name,
description,
});
update(collections => [...collections, collection]);
return collection;
} catch (error) {
console.error('Error creating collection:', error);
throw error;
}
},
updateCollection: async (id: string, name: string, description?: string) => {
try {
const collection = await invoke<Collection>('update_collection', {
id,
name,
description,
});
update(collections =>
collections.map(c => c.id === id ? collection : c)
);
return collection;
} catch (error) {
console.error('Error updating collection:', error);
throw error;
}
},
deleteCollection: async (id: string) => {
try {
await invoke('delete_collection', { id });
update(collections => collections.filter(c => c.id !== id));
} catch (error) {
console.error('Error deleting collection:', error);
throw error;
}
},
};
}
export const collections = createCollectionStore();
export const activeCollection = writable<Collection | null>(null);
// Auto-load collections when workspace changes
activeWorkspace.subscribe(workspace => {
if (workspace) {
collections.loadCollections(workspace.id);
}
});

View File

@@ -0,0 +1,76 @@
import { writable, derived } from 'svelte/store';
import { invoke } from '@tauri-apps/api/core';
import type { Workspace } from '../../types';
function createWorkspaceStore() {
const { subscribe, set, update } = writable<Workspace[]>([]);
return {
subscribe,
loadWorkspaces: async () => {
try {
const workspaces = await invoke<Workspace[]>('get_workspaces');
set(workspaces);
} catch (error) {
console.error('Error loading workspaces:', error);
throw error;
}
},
getWorkspace: async (id: string) => {
try {
const workspace = await invoke<Workspace>('get_workspace', { id });
return workspace;
} catch (error) {
console.error('Error getting workspace:', error);
throw error;
}
},
createWorkspace: async (name: string, description?: string) => {
try {
const workspace = await invoke<Workspace>('create_workspace', {
name,
description,
});
update(workspaces => [...workspaces, workspace]);
return workspace;
} catch (error) {
console.error('Error creating workspace:', error);
throw new Error(error instanceof Error ? error.message : 'Failed to create workspace');
}
},
updateWorkspace: async (id: string, name: string, description?: string) => {
try {
const workspace = await invoke<Workspace>('update_workspace', {
id,
name,
description,
});
update(workspaces =>
workspaces.map(w => w.id === id ? workspace : w)
);
return workspace;
} catch (error) {
console.error('Error updating workspace:', error);
throw new Error(error instanceof Error ? error.message : 'Failed to update workspace');
}
},
deleteWorkspace: async (id: string) => {
try {
await invoke('delete_workspace', { id });
update(workspaces => workspaces.filter(w => w.id !== id));
} catch (error) {
console.error('Error deleting workspace:', error);
throw new Error(error instanceof Error ? error.message : 'Failed to delete workspace');
}
},
};
}
export const workspaces = createWorkspaceStore();
export const activeWorkspace = writable<Workspace | null>(null);
// Derived store for the current workspace's variables
export const currentVariables = derived(
activeWorkspace,
$workspace => $workspace?.variables || []
);

18
src/lib/utils/date.ts Normal file
View File

@@ -0,0 +1,18 @@
export function formatDate(timestamp: number): string {
const date = new Date(timestamp * 1000);
const now = new Date();
const diff = now.getTime() - date.getTime();
// Less than 24 hours
if (diff < 24 * 60 * 60 * 1000) {
return date.toLocaleTimeString();
}
// Less than a week
if (diff < 7 * 24 * 60 * 60 * 1000) {
return date.toLocaleDateString(undefined, { weekday: 'long' });
}
// Otherwise
return date.toLocaleDateString();
}

11
src/routes/+error.svelte Normal file
View File

@@ -0,0 +1,11 @@
<script>
import { page } from '$app/stores';
</script>
<div class="min-h-screen flex items-center justify-center">
<div class="text-center">
<h1 class="text-9xl font-bold text-base-content/20">{$page.status}</h1>
<p class="text-xl mt-4">{$page.error?.message || 'Page not found'}</p>
<a href="/" class="btn btn-primary mt-8">Go Home</a>
</div>
</div>

View File

@@ -0,0 +1,5 @@
<script>
import "../app.css";
</script>
<slot />

5
src/routes/+layout.ts Normal file
View File

@@ -0,0 +1,5 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we will use adapter-static to prerender the app (SSG)
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
export const prerender = true;
export const ssr = false;

75
src/routes/+page.svelte Normal file
View File

@@ -0,0 +1,75 @@
<script lang="ts">
import { workspaces } from '$lib/stores/workspace';
import { onMount } from 'svelte';
import WorkspaceCard from '$lib/components/WorkspaceCard.svelte';
import WorkspaceModal from '$lib/components/modals/WorkspaceModal.svelte';
let showCreateModal = false;
let loading = true;
let error: string | null = null;
onMount(async () => {
try {
await workspaces.loadWorkspaces();
} catch (err) {
console.error('Failed to load workspaces:', err);
error = 'Failed to load workspaces';
} finally {
loading = false;
}
});
</script>
<div class="container mx-auto px-6 py-8 max-w-7xl">
<div class="flex justify-between items-center mb-8">
<div>
<h1 class="text-2xl font-bold">Workspaces</h1>
<p class="text-base-content/70">Manage your API collections and environments</p>
</div>
<button
class="btn btn-primary"
on:click={() => showCreateModal = true}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
New Workspace
</button>
</div>
{#if loading}
<div class="flex justify-center py-16">
<span class="loading loading-spinner loading-lg"></span>
</div>
{:else if error}
<div class="alert alert-error">
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
<span>{error}</span>
</div>
{:else if $workspaces.length === 0}
<div class="flex flex-col items-center justify-center py-16 text-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-base-content/20" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<h3 class="mt-4 text-lg font-medium">No workspaces yet</h3>
<p class="mt-1 text-base-content/70">Create a workspace to get started with your API collections</p>
<button
class="btn btn-primary mt-4"
on:click={() => showCreateModal = true}
>
Create Your First Workspace
</button>
</div>
{:else}
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{#each $workspaces as workspace}
<WorkspaceCard {workspace} />
{/each}
</div>
{/if}
</div>
<WorkspaceModal
show={showCreateModal}
on:close={() => showCreateModal = false}
/>

View File

@@ -0,0 +1,49 @@
<script lang="ts">
import { page } from '$app/stores';
import { workspaces, activeWorkspace } from '$lib/stores/workspace';
import { onMount } from 'svelte';
import Sidebar from '$lib/components/Sidebar.svelte';
import WorkspaceToolbar from '$lib/components/WorkspaceToolbar.svelte';
let drawerOpen = true;
onMount(async () => {
const workspace = await workspaces.getWorkspace($page.params.id);
if (workspace) {
activeWorkspace.set(workspace);
}
});
</script>
<div class="drawer lg:drawer-open">
<input
id="drawer"
type="checkbox"
class="drawer-toggle"
bind:checked={drawerOpen}
/>
<div class="drawer-content flex flex-col">
{#if drawerOpen}
<button
class="lg:hidden fixed bottom-4 right-4 btn btn-circle btn-primary z-50"
on:click={() => drawerOpen = false}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
{/if}
<WorkspaceToolbar />
<slot />
</div>
<div class="drawer-side">
<label
for="drawer"
class="drawer-overlay"
on:click={() => drawerOpen = false}
></label>
<Sidebar />
</div>
</div>

View File

@@ -0,0 +1,23 @@
<script lang="ts">
import { page } from '$app/stores';
import { onMount } from 'svelte';
import { workspaces, activeWorkspace } from '$lib/stores/workspace';
import RequestPanel from '$lib/components/RequestPanel.svelte';
import ResponsePanel from '$lib/components/ResponsePanel.svelte';
onMount(async () => {
try {
const workspace = await workspaces.getWorkspace($page.params.id);
if (workspace) {
activeWorkspace.set(workspace);
}
} catch (error) {
console.error('Failed to load workspace:', error);
}
});
</script>
<div class="p-4 space-y-4">
<RequestPanel />
<ResponsePanel />
</div>

14
src/stores/index.ts Normal file
View File

@@ -0,0 +1,14 @@
import { writable } from 'svelte/store';
import type { Collection, Variable, Request as ApiRequest } from '../types';
export const collections = writable<Collection[]>([]);
export const variables = writable<Variable[]>([]);
export const activeCollection = writable<Collection | null>(null);
export const activeRequest = writable<ApiRequest | null>(null);
export const currentResponse = writable<{
status: number;
statusText: string;
headers: Record<string, string>;
body: string;
time: number;
} | null>(null);

58
src/types/index.ts Normal file
View File

@@ -0,0 +1,58 @@
export interface Variable {
id: string;
name: string;
value: string;
description?: string;
}
export interface Collection {
id: string;
workspace_id: string;
name: string;
description?: string;
created_at: number;
updated_at: number;
requests: Request[];
}
export interface Request {
id: string;
name: string;
url: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
headers: Header[];
queryParams: QueryParam[];
body?: string;
}
export interface Header {
id: string;
key: string;
value: string;
enabled: boolean;
}
export interface QueryParam {
id: string;
key: string;
value: string;
enabled: boolean;
}
export interface RequestResponse {
status: number;
statusText: string;
headers: Record<string, string>;
body: any;
time: number;
}
export interface Workspace {
id: string;
name: string;
variables?: Variable[];
collections?: Collection[];
description?: string;
created_at: number;
updated_at: number;
}

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

1
static/svelte.svg Normal file
View File

@@ -0,0 +1 @@
<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="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

6
static/tauri.svg Normal file
View File

@@ -0,0 +1,6 @@
<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>

After

Width:  |  Height:  |  Size: 2.5 KiB

1
static/vite.svg Normal file
View File

@@ -0,0 +1 @@
<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>

After

Width:  |  Height:  |  Size: 1.5 KiB

16
svelte.config.js Normal file
View File

@@ -0,0 +1,16 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we will use adapter-static to prerender the app (SSG)
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
import adapter from "@sveltejs/adapter-static";
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter(),
},
preprocess: vitePreprocess()
};
export default config;

14
tailwind.config.js Normal file
View File

@@ -0,0 +1,14 @@
import daisyui from "daisyui";
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {},
},
plugins: [daisyui],
daisyui: {
themes: ["light", "dark"],
}
}

19
tsconfig.json Normal file
View File

@@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

32
vite.config.js Normal file
View File

@@ -0,0 +1,32 @@
import { defineConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
// @ts-expect-error process is a nodejs global
const host = process.env.TAURI_DEV_HOST;
// https://vitejs.dev/config/
export default defineConfig(async () => ({
plugins: [sveltekit()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || false,
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));

15
vite.config.ts Normal file
View File

@@ -0,0 +1,15 @@
import { defineConfig } from "vite";
import { sveltekit } from "@sveltejs/kit/vite";
export default defineConfig(async () => ({
plugins: [sveltekit()],
clearScreen: false,
server:{
port: 1420,
strictPort: true
},
envPrefix: ["VITE_", "TAURI_"],
}))