Compare commits
30 Commits
release-20
...
release-20
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5a68fb630 | ||
|
|
155dd07193 | ||
|
|
e5f76fe548 | ||
|
|
5e098817f2 | ||
|
|
4dcbd8187e | ||
|
|
6c0c0a0919 | ||
|
|
3158a11229 | ||
|
|
45f5d1b678 | ||
|
|
c8e3caa4fc | ||
|
|
98555f16ca | ||
|
|
5449651db6 | ||
|
|
1156f0a111 | ||
|
|
9b8c075d41 | ||
|
|
c5679f043d | ||
|
|
0b3d4d1fd4 | ||
|
|
b2fb411bb1 | ||
|
|
1225c550b7 | ||
|
|
48193db81b | ||
|
|
48d8a8e0ee | ||
|
|
945f4718eb | ||
|
|
6a2952c6f3 | ||
|
|
03b63dd5d0 | ||
|
|
7717dffc56 | ||
|
|
3a2cab7ca7 | ||
|
|
e0b5411eb1 | ||
|
|
f85adfa007 | ||
|
|
88c3cd57c1 | ||
|
|
d67215a6eb | ||
|
|
5cc2fdd8b4 | ||
|
|
38bce3fecf |
37
Cargo.lock
generated
37
Cargo.lock
generated
@@ -1259,6 +1259,7 @@ dependencies = [
|
||||
"gloo-console",
|
||||
"gloo-net",
|
||||
"gloo-timers",
|
||||
"icons",
|
||||
"js-sys",
|
||||
"leptos",
|
||||
"leptos-use",
|
||||
@@ -1271,7 +1272,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"shared",
|
||||
"struct-patch",
|
||||
"strum",
|
||||
"strum 0.26.3",
|
||||
"tailwind_fuse",
|
||||
"thiserror 2.0.18",
|
||||
"tw_merge",
|
||||
@@ -1864,6 +1865,17 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icons"
|
||||
version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75da3d473e24e0b541bf28cf31e67b262c379a4cbc2149f4865b7d99406711dc"
|
||||
dependencies = [
|
||||
"leptos",
|
||||
"strum 0.27.2",
|
||||
"tw_merge",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.1.1"
|
||||
@@ -4137,7 +4149,16 @@ version = "0.26.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
|
||||
dependencies = [
|
||||
"strum_macros",
|
||||
"strum_macros 0.26.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum"
|
||||
version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
|
||||
dependencies = [
|
||||
"strum_macros 0.27.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4153,6 +4174,18 @@ dependencies = [
|
||||
"syn 2.0.114",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum_macros"
|
||||
version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.114",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
|
||||
@@ -20,11 +20,13 @@
|
||||
<link rel="apple-touch-icon" sizes="512x512" href="icon-512.png" />
|
||||
|
||||
<!-- Trunk Assets -->
|
||||
<link data-trunk rel="rust" href="Cargo.toml" data-wasm-opt="0" />
|
||||
<link data-trunk rel="rust" href="Cargo.toml" data-wasm-opt="0" data-no-preload />
|
||||
<link data-trunk rel="css" href="public/tailwind.css" />
|
||||
<link data-trunk rel="copy-file" href="manifest.json" />
|
||||
<link data-trunk rel="copy-file" href="icon-192.png" />
|
||||
<link data-trunk rel="copy-file" href="icon-512.png" />
|
||||
<link data-trunk rel="copy-file" href="public/lock_scroll.js" />
|
||||
<script src="/lock_scroll.js"></script>
|
||||
<link data-trunk rel="copy-file" href="sw.js" />
|
||||
<script>
|
||||
(function () {
|
||||
|
||||
@@ -1,177 +1,92 @@
|
||||
@import "tailwindcss";
|
||||
@config "./tailwind.config.js";
|
||||
@source "../src/**/*.rs";
|
||||
@source "/Users/bilal/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/leptos-shadcn-*/src/**/*.rs";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@theme {
|
||||
/* Shadcn Colors */
|
||||
--color-border: hsl(var(--border));
|
||||
--color-input: hsl(var(--input));
|
||||
--color-ring: hsl(var(--ring));
|
||||
--color-background: hsl(var(--background));
|
||||
--color-foreground: hsl(var(--foreground));
|
||||
|
||||
--color-primary: hsl(var(--primary));
|
||||
--color-primary-foreground: hsl(var(--primary-foreground));
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 240 10% 3.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 240 10% 3.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 240 10% 3.9%;
|
||||
--primary: 240 5.9% 10%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 240 4.8% 95.9%;
|
||||
--secondary-foreground: 240 5.9% 10%;
|
||||
--muted: 240 4.8% 95.9%;
|
||||
--muted-foreground: 240 3.8% 46.1%;
|
||||
--accent: 240 4.8% 95.9%;
|
||||
--accent-foreground: 240 5.9% 10%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 240 5.9% 90%;
|
||||
--input: 240 5.9% 90%;
|
||||
--ring: 240 5.9% 10%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
--color-secondary: hsl(var(--secondary));
|
||||
--color-secondary-foreground: hsl(var(--secondary-foreground));
|
||||
.dark {
|
||||
--background: 240 10% 3.9%;
|
||||
--foreground: 0 0% 98%;
|
||||
--card: 240 10% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
--popover: 240 10% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 240 5.9% 10%;
|
||||
--secondary: 240 3.7% 15.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 240 3.7% 15.9%;
|
||||
--muted-foreground: 240 5% 64.9%;
|
||||
--accent: 240 3.7% 15.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 240 3.7% 15.9%;
|
||||
--input: 240 3.7% 15.9%;
|
||||
--ring: 240 4.9% 83.9%;
|
||||
}
|
||||
|
||||
--color-destructive: hsl(var(--destructive));
|
||||
--color-destructive-foreground: hsl(var(--destructive-foreground));
|
||||
|
||||
--color-muted: hsl(var(--muted));
|
||||
--color-muted-foreground: hsl(var(--muted-foreground));
|
||||
|
||||
--color-accent: hsl(var(--accent));
|
||||
--color-accent-foreground: hsl(var(--accent-foreground));
|
||||
|
||||
--color-popover: hsl(var(--popover));
|
||||
--color-popover-foreground: hsl(var(--popover-foreground));
|
||||
|
||||
--color-card: hsl(var(--card));
|
||||
--color-card-foreground: hsl(var(--card-foreground));
|
||||
|
||||
--radius-lg: var(--radius);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
|
||||
--animate-accordion-down: accordion-down 0.2s ease-out;
|
||||
--animate-accordion-up: accordion-up 0.2s ease-out;
|
||||
|
||||
@keyframes accordion-down {
|
||||
from {
|
||||
height: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes accordion-up {
|
||||
from {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
|
||||
to {
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
@theme inline {
|
||||
--color-background: hsl(var(--background));
|
||||
--color-foreground: hsl(var(--foreground));
|
||||
--color-card: hsl(var(--card));
|
||||
--color-card-foreground: hsl(var(--card-foreground));
|
||||
--color-popover: hsl(var(--popover));
|
||||
--color-popover-foreground: hsl(var(--popover-foreground));
|
||||
--color-primary: hsl(var(--primary));
|
||||
--color-primary-foreground: hsl(var(--primary-foreground));
|
||||
--color-secondary: hsl(var(--secondary));
|
||||
--color-secondary-foreground: hsl(var(--secondary-foreground));
|
||||
--color-muted: hsl(var(--muted));
|
||||
--color-muted-foreground: hsl(var(--muted-foreground));
|
||||
--color-accent: hsl(var(--accent));
|
||||
--color-accent-foreground: hsl(var(--accent-foreground));
|
||||
--color-destructive: hsl(var(--destructive));
|
||||
--color-destructive-foreground: hsl(var(--destructive-foreground));
|
||||
--color-border: hsl(var(--border));
|
||||
--color-input: hsl(var(--input));
|
||||
--color-ring: hsl(var(--ring));
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 222.2 84% 4.9%;
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222.2 84% 4.9%;
|
||||
button:not(:disabled),
|
||||
[role="button"]:not(:disabled) {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222.2 84% 4.9%;
|
||||
|
||||
--primary: 222.2 47.4% 11.2%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
|
||||
--secondary: 210 40% 96.1%;
|
||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--muted: 210 40% 96.1%;
|
||||
--muted-foreground: 215.4 16.3% 46.9%;
|
||||
|
||||
--accent: 210 40% 96.1%;
|
||||
--accent-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
|
||||
--border: 214.3 31.8% 91.4%;
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 222.2 84% 4.9%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
|
||||
--primary: 210 40% 98%;
|
||||
--primary-foreground: 222.2 47.4% 11.2%;
|
||||
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 212.7 26.8% 83.9%;
|
||||
}
|
||||
dialog {
|
||||
margin: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
|
||||
/* Ensure Shadcn Utilities are always available */
|
||||
.bg-popover {
|
||||
background-color: hsl(var(--popover));
|
||||
}
|
||||
|
||||
.text-popover-foreground {
|
||||
color: hsl(var(--popover-foreground));
|
||||
}
|
||||
|
||||
.border-border {
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
|
||||
.shadow-md {
|
||||
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
|
||||
}
|
||||
|
||||
.z-50 {
|
||||
z-index: 50;
|
||||
}
|
||||
|
||||
.z-100 {
|
||||
z-index: 100;
|
||||
}
|
||||
}
|
||||
|
||||
/* Fix for iOS click/blur events */
|
||||
@media (hover: none) {
|
||||
body {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove default focus outline/tap highlight */
|
||||
* {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
outline: none !important;
|
||||
}
|
||||
|
||||
:focus {
|
||||
outline: none !important;
|
||||
}
|
||||
253
frontend/public/hooks/lock_scroll.js
Normal file
253
frontend/public/hooks/lock_scroll.js
Normal file
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Scroll Lock Utility
|
||||
* Handles locking and unlocking scroll for both window and all scrollable containers
|
||||
* Similar to react-remove-scroll but in vanilla JavaScript
|
||||
*/
|
||||
|
||||
(() => {
|
||||
// Prevent multiple initializations
|
||||
if (window.ScrollLock) {
|
||||
return;
|
||||
}
|
||||
|
||||
class ScrollLock {
|
||||
constructor() {
|
||||
this.locked = false;
|
||||
this.scrollableElements = [];
|
||||
this.scrollPositions = new Map();
|
||||
this.originalStyles = new Map();
|
||||
this.fixedElements = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all scrollable elements in the DOM (optimized)
|
||||
* Uses more targeted selectors instead of querying all elements
|
||||
*/
|
||||
findScrollableElements() {
|
||||
const scrollables = [];
|
||||
|
||||
// More targeted query - only look for elements with overflow properties
|
||||
const candidates = document.querySelectorAll(
|
||||
'[style*="overflow"], [class*="overflow"], [class*="scroll"], main, aside, section, div',
|
||||
);
|
||||
|
||||
// Batch all style reads first to minimize reflows
|
||||
const elementsToCheck = [];
|
||||
for (const el of candidates) {
|
||||
// Skip the element itself or if it's inside these containers
|
||||
const dataName = el.getAttribute("data-name");
|
||||
const isExcludedElement =
|
||||
dataName === "ScrollArea" ||
|
||||
dataName === "CommandList" ||
|
||||
dataName === "SelectContent" ||
|
||||
dataName === "MultiSelectContent" ||
|
||||
dataName === "DropdownMenuContent" ||
|
||||
dataName === "ContextMenuContent";
|
||||
|
||||
if (
|
||||
el !== document.body &&
|
||||
el !== document.documentElement &&
|
||||
!isExcludedElement &&
|
||||
!el.closest('[data-name="ScrollArea"]') &&
|
||||
!el.closest('[data-name="CommandList"]') &&
|
||||
!el.closest('[data-name="SelectContent"]') &&
|
||||
!el.closest('[data-name="MultiSelectContent"]') &&
|
||||
!el.closest('[data-name="DropdownMenuContent"]') &&
|
||||
!el.closest('[data-name="ContextMenuContent"]')
|
||||
) {
|
||||
elementsToCheck.push(el);
|
||||
}
|
||||
}
|
||||
|
||||
// Now batch read all computed styles and dimensions
|
||||
elementsToCheck.forEach((el) => {
|
||||
const style = window.getComputedStyle(el);
|
||||
const hasOverflow =
|
||||
style.overflow === "auto" ||
|
||||
style.overflow === "scroll" ||
|
||||
style.overflowY === "auto" ||
|
||||
style.overflowY === "scroll";
|
||||
|
||||
// Only check scrollHeight if overflow is set
|
||||
if (hasOverflow && el.scrollHeight > el.clientHeight) {
|
||||
scrollables.push(el);
|
||||
}
|
||||
});
|
||||
|
||||
return scrollables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock scrolling on all scrollable elements (optimized)
|
||||
* Batches all DOM reads before DOM writes to prevent forced reflows
|
||||
*/
|
||||
lock() {
|
||||
if (this.locked) return;
|
||||
|
||||
this.locked = true;
|
||||
|
||||
// Find all scrollable elements
|
||||
this.scrollableElements = this.findScrollableElements();
|
||||
|
||||
// ===== BATCH 1: READ PHASE - Read all layout properties first =====
|
||||
const windowScrollY = window.scrollY;
|
||||
const scrollbarWidth = window.innerWidth - document.body.clientWidth;
|
||||
|
||||
// Store window scroll position
|
||||
this.scrollPositions.set("window", windowScrollY);
|
||||
|
||||
// Store original body styles
|
||||
this.originalStyles.set("body", {
|
||||
position: document.body.style.position,
|
||||
top: document.body.style.top,
|
||||
width: document.body.style.width,
|
||||
overflow: document.body.style.overflow,
|
||||
paddingRight: document.body.style.paddingRight,
|
||||
});
|
||||
|
||||
// Read all fixed-position elements and their padding (only if we have scrollbar)
|
||||
if (scrollbarWidth > 0) {
|
||||
// Use more targeted query for fixed elements
|
||||
const fixedCandidates = document.querySelectorAll(
|
||||
'[style*="fixed"], [class*="fixed"], header, nav, aside, [role="dialog"], [role="alertdialog"]',
|
||||
);
|
||||
|
||||
this.fixedElements = Array.from(fixedCandidates).filter((el) => {
|
||||
const style = window.getComputedStyle(el);
|
||||
return (
|
||||
style.position === "fixed" &&
|
||||
!el.closest('[data-name="DropdownMenuContent"]') &&
|
||||
!el.closest('[data-name="MultiSelectContent"]') &&
|
||||
!el.closest('[data-name="ContextMenuContent"]')
|
||||
);
|
||||
});
|
||||
|
||||
// Batch read all padding values
|
||||
this.fixedElements.forEach((el) => {
|
||||
const computedStyle = window.getComputedStyle(el);
|
||||
const currentPadding = Number.parseInt(computedStyle.paddingRight, 10) || 0;
|
||||
|
||||
this.originalStyles.set(el, {
|
||||
paddingRight: el.style.paddingRight,
|
||||
computedPadding: currentPadding,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Read scrollable elements info
|
||||
const scrollableInfo = this.scrollableElements.map((el) => {
|
||||
const scrollTop = el.scrollTop;
|
||||
const elementScrollbarWidth = el.offsetWidth - el.clientWidth;
|
||||
const computedStyle = window.getComputedStyle(el);
|
||||
const currentPadding = Number.parseInt(computedStyle.paddingRight, 10) || 0;
|
||||
|
||||
this.scrollPositions.set(el, scrollTop);
|
||||
this.originalStyles.set(el, {
|
||||
overflow: el.style.overflow,
|
||||
overflowY: el.style.overflowY,
|
||||
paddingRight: el.style.paddingRight,
|
||||
});
|
||||
|
||||
return { el, elementScrollbarWidth, currentPadding };
|
||||
});
|
||||
|
||||
// ===== BATCH 2: WRITE PHASE - Apply all styles at once =====
|
||||
|
||||
// Apply body lock
|
||||
document.body.style.position = "fixed";
|
||||
document.body.style.top = `-${windowScrollY}px`;
|
||||
document.body.style.width = "100%";
|
||||
document.body.style.overflow = "hidden";
|
||||
|
||||
if (scrollbarWidth > 0) {
|
||||
document.body.style.paddingRight = `${scrollbarWidth}px`;
|
||||
|
||||
// Apply padding compensation to fixed elements
|
||||
this.fixedElements.forEach((el) => {
|
||||
const stored = this.originalStyles.get(el);
|
||||
if (stored) {
|
||||
el.style.paddingRight = `${stored.computedPadding + scrollbarWidth}px`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Lock all scrollable containers
|
||||
scrollableInfo.forEach(({ el, elementScrollbarWidth, currentPadding }) => {
|
||||
el.style.overflow = "hidden";
|
||||
|
||||
if (elementScrollbarWidth > 0) {
|
||||
el.style.paddingRight = `${currentPadding + elementScrollbarWidth}px`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlock scrolling on all elements (optimized)
|
||||
* @param {number} delay - Delay in milliseconds before unlocking (for animations)
|
||||
*/
|
||||
unlock(delay = 0) {
|
||||
if (!this.locked) return;
|
||||
|
||||
const performUnlock = () => {
|
||||
// Restore body scroll
|
||||
const bodyStyles = this.originalStyles.get("body");
|
||||
if (bodyStyles) {
|
||||
document.body.style.position = bodyStyles.position;
|
||||
document.body.style.top = bodyStyles.top;
|
||||
document.body.style.width = bodyStyles.width;
|
||||
document.body.style.overflow = bodyStyles.overflow;
|
||||
document.body.style.paddingRight = bodyStyles.paddingRight;
|
||||
}
|
||||
|
||||
// Restore window scroll position
|
||||
const windowScrollY = this.scrollPositions.get("window") || 0;
|
||||
window.scrollTo(0, windowScrollY);
|
||||
|
||||
// Restore all scrollable containers
|
||||
this.scrollableElements.forEach((el) => {
|
||||
const originalStyles = this.originalStyles.get(el);
|
||||
if (originalStyles) {
|
||||
el.style.overflow = originalStyles.overflow;
|
||||
el.style.overflowY = originalStyles.overflowY;
|
||||
el.style.paddingRight = originalStyles.paddingRight;
|
||||
}
|
||||
|
||||
// Restore scroll position
|
||||
const scrollPosition = this.scrollPositions.get(el) || 0;
|
||||
el.scrollTop = scrollPosition;
|
||||
});
|
||||
|
||||
// Restore fixed-position elements padding
|
||||
this.fixedElements.forEach((el) => {
|
||||
const styles = this.originalStyles.get(el);
|
||||
if (styles && styles.paddingRight !== undefined) {
|
||||
el.style.paddingRight = styles.paddingRight;
|
||||
}
|
||||
});
|
||||
|
||||
// Clear storage
|
||||
this.scrollableElements = [];
|
||||
this.fixedElements = [];
|
||||
this.scrollPositions.clear();
|
||||
this.originalStyles.clear();
|
||||
this.locked = false;
|
||||
};
|
||||
|
||||
if (delay > 0) {
|
||||
setTimeout(performUnlock, delay);
|
||||
} else {
|
||||
performUnlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if scrolling is currently locked
|
||||
*/
|
||||
isLocked() {
|
||||
return this.locked;
|
||||
}
|
||||
}
|
||||
|
||||
// Export as singleton
|
||||
window.ScrollLock = new ScrollLock();
|
||||
})();
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::components::layout::protected::Protected;
|
||||
use crate::components::ui::skeleton::Skeleton;
|
||||
use crate::components::ui::card::{Card, CardHeader, CardContent};
|
||||
use crate::components::torrent::table::TorrentTable;
|
||||
use crate::components::auth::login::Login;
|
||||
use crate::components::auth::setup::Setup;
|
||||
use leptos::prelude::*;
|
||||
use leptos::task::spawn_local;
|
||||
use leptos_router::components::{Router, Routes, Route};
|
||||
use leptos_router::hooks::use_navigate;
|
||||
use leptos_router::hooks::{use_navigate, use_location};
|
||||
use crate::components::ui::toast::Toaster;
|
||||
use crate::components::hooks::use_theme_mode::ThemeMode;
|
||||
|
||||
@@ -30,7 +32,9 @@ pub fn App() -> impl IntoView {
|
||||
|
||||
view! {
|
||||
<Toaster />
|
||||
<InnerApp />
|
||||
<Router>
|
||||
<InnerApp />
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +42,7 @@ pub fn App() -> impl IntoView {
|
||||
fn InnerApp() -> impl IntoView {
|
||||
crate::store::provide_torrent_store();
|
||||
let store = use_context::<crate::store::TorrentStore>();
|
||||
let loc = use_location();
|
||||
|
||||
let is_loading = signal(true);
|
||||
let is_authenticated = signal(false);
|
||||
@@ -97,119 +102,148 @@ fn InnerApp() -> impl IntoView {
|
||||
|
||||
view! {
|
||||
<div class="relative w-full h-screen" style="height: 100dvh;">
|
||||
<Router>
|
||||
<Routes fallback=|| view! { <div class="p-4">"404 Not Found"</div> }>
|
||||
<Route path=leptos_router::path!("/login") view=move || {
|
||||
let authenticated = is_authenticated.0.get();
|
||||
let setup_needed = needs_setup.0.get();
|
||||
|
||||
Effect::new(move |_| {
|
||||
if setup_needed {
|
||||
let navigate = use_navigate();
|
||||
<Routes fallback=|| view! { <div class="p-4">"404 Not Found"</div> }>
|
||||
<Route path=leptos_router::path!("/login") view=move || {
|
||||
let authenticated = is_authenticated.0.get();
|
||||
let setup_needed = needs_setup.0.get();
|
||||
|
||||
Effect::new(move |_| {
|
||||
if setup_needed {
|
||||
let navigate = use_navigate();
|
||||
navigate("/setup", Default::default());
|
||||
} else if authenticated {
|
||||
log::info!("Already authenticated, redirecting to home");
|
||||
let navigate = use_navigate();
|
||||
navigate("/", Default::default());
|
||||
}
|
||||
});
|
||||
|
||||
view! { <Login /> }
|
||||
} />
|
||||
<Route path=leptos_router::path!("/setup") view=move || {
|
||||
Effect::new(move |_| {
|
||||
if is_authenticated.0.get() {
|
||||
let navigate = use_navigate();
|
||||
navigate("/", Default::default());
|
||||
}
|
||||
});
|
||||
|
||||
view! { <Setup /> }
|
||||
} />
|
||||
|
||||
<Route path=leptos_router::path!("/") view=move || {
|
||||
let navigate = use_navigate();
|
||||
Effect::new(move |_| {
|
||||
if !is_loading.0.get() {
|
||||
if needs_setup.0.get() {
|
||||
log::info!("Setup not completed, redirecting to setup");
|
||||
navigate("/setup", Default::default());
|
||||
} else if authenticated {
|
||||
log::info!("Already authenticated, redirecting to home");
|
||||
let navigate = use_navigate();
|
||||
navigate("/", Default::default());
|
||||
}
|
||||
});
|
||||
|
||||
view! { <Login /> }
|
||||
} />
|
||||
<Route path=leptos_router::path!("/setup") view=move || {
|
||||
Effect::new(move |_| {
|
||||
if is_authenticated.0.get() {
|
||||
let navigate = use_navigate();
|
||||
navigate("/", Default::default());
|
||||
}
|
||||
});
|
||||
|
||||
view! { <Setup /> }
|
||||
} />
|
||||
|
||||
<Route path=leptos_router::path!("/") view=move || {
|
||||
let navigate = use_navigate();
|
||||
Effect::new(move |_| {
|
||||
if !is_loading.0.get() {
|
||||
if needs_setup.0.get() {
|
||||
log::info!("Setup not completed, redirecting to setup");
|
||||
navigate("/setup", Default::default());
|
||||
} else if !is_authenticated.0.get() {
|
||||
log::info!("Not authenticated, redirecting to login");
|
||||
navigate("/login", Default::default());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
view! {
|
||||
<Show when=move || !is_loading.0.get() fallback=|| view! {
|
||||
<div class="flex h-screen bg-background">
|
||||
// Sidebar skeleton
|
||||
<div class="w-56 border-r border-border p-4 space-y-4">
|
||||
<div class="h-8 w-3/4 animate-pulse rounded-md bg-muted" />
|
||||
<div class="space-y-2">
|
||||
<div class="h-6 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-6 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-6 w-4/5 animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-6 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-6 w-3/5 animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-6 w-full animate-pulse rounded-md bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
// Main content skeleton
|
||||
<div class="flex-1 flex flex-col">
|
||||
<div class="border-b border-border p-4 flex items-center gap-4">
|
||||
<div class="h-8 w-48 animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-8 w-64 animate-pulse rounded-md bg-muted" />
|
||||
<div class="ml-auto"><div class="h-8 w-24 animate-pulse rounded-md bg-muted" /></div>
|
||||
</div>
|
||||
<div class="flex-1 p-4 space-y-3">
|
||||
<div class="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-10 w-full animate-pulse rounded-md bg-muted" />
|
||||
<div class="h-10 w-3/4 animate-pulse rounded-md bg-muted" />
|
||||
</div>
|
||||
<div class="border-t border-border p-3">
|
||||
<div class="h-5 w-96 animate-pulse rounded-md bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}.into_any()>
|
||||
<Show when=move || is_authenticated.0.get() fallback=|| ()>
|
||||
<Protected>
|
||||
<div class="flex flex-col h-full overflow-hidden">
|
||||
<div class="flex-1 overflow-hidden">
|
||||
<TorrentTable />
|
||||
</div>
|
||||
</div>
|
||||
</Protected>
|
||||
</Show>
|
||||
</Show>
|
||||
}.into_any()
|
||||
}/>
|
||||
|
||||
<Route path=leptos_router::path!("/settings") view=move || {
|
||||
Effect::new(move |_| {
|
||||
if !is_authenticated.0.get() {
|
||||
let navigate = use_navigate();
|
||||
} else if !is_authenticated.0.get() {
|
||||
log::info!("Not authenticated, redirecting to login");
|
||||
navigate("/login", Default::default());
|
||||
}
|
||||
});
|
||||
|
||||
view! {
|
||||
<Show when=move || !is_loading.0.get() fallback=|| ()>
|
||||
<Show when=move || is_authenticated.0.get() fallback=|| ()>
|
||||
<Protected>
|
||||
<div class="p-4">"Settings Page (Coming Soon)"</div>
|
||||
</Protected>
|
||||
</Show>
|
||||
</Show>
|
||||
}
|
||||
}/>
|
||||
</Routes>
|
||||
</Router>
|
||||
});
|
||||
|
||||
view! {
|
||||
<Show when=move || !is_loading.0.get() fallback=move || {
|
||||
let path = loc.pathname.get();
|
||||
if path == "/login" {
|
||||
// Login Skeleton
|
||||
view! {
|
||||
<div class="flex items-center justify-center min-h-screen bg-muted/40 px-4">
|
||||
<Card class="w-full max-w-sm shadow-lg border-none">
|
||||
<CardHeader class="pb-2 items-center space-y-4">
|
||||
<Skeleton class="w-12 h-12 rounded-xl" />
|
||||
<Skeleton class="h-8 w-32" />
|
||||
<Skeleton class="h-4 w-48" />
|
||||
</CardHeader>
|
||||
<CardContent class="pt-4 space-y-6">
|
||||
<div class="space-y-2">
|
||||
<Skeleton class="h-4 w-24" />
|
||||
<Skeleton class="h-10 w-full" />
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Skeleton class="h-4 w-24" />
|
||||
<Skeleton class="h-10 w-full" />
|
||||
</div>
|
||||
<Skeleton class="h-10 w-full rounded-md mt-4" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
}.into_any()
|
||||
} else {
|
||||
// Dashboard Skeleton
|
||||
view! {
|
||||
<div class="flex h-screen bg-background">
|
||||
// Sidebar skeleton
|
||||
<div class="w-56 border-r border-border p-4 space-y-4">
|
||||
<Skeleton class="h-8 w-3/4" />
|
||||
<div class="space-y-2">
|
||||
<Skeleton class="h-6 w-full" />
|
||||
<Skeleton class="h-6 w-full" />
|
||||
<Skeleton class="h-6 w-4/5" />
|
||||
<Skeleton class="h-6 w-full" />
|
||||
<Skeleton class="h-6 w-3/5" />
|
||||
<Skeleton class="h-6 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
// Main content skeleton
|
||||
<div class="flex-1 flex flex-col">
|
||||
<div class="border-b border-border p-4 flex items-center gap-4">
|
||||
<Skeleton class="h-8 w-48" />
|
||||
<Skeleton class="h-8 w-64" />
|
||||
<div class="ml-auto"><Skeleton class="h-8 w-24" /></div>
|
||||
</div>
|
||||
<div class="flex-1 p-4 space-y-3">
|
||||
<Skeleton class="h-10 w-full" />
|
||||
<Skeleton class="h-10 w-full" />
|
||||
<Skeleton class="h-10 w-full" />
|
||||
<Skeleton class="h-10 w-full" />
|
||||
<Skeleton class="h-10 w-full" />
|
||||
<Skeleton class="h-10 w-3/4" />
|
||||
</div>
|
||||
<div class="border-t border-border p-3">
|
||||
<Skeleton class="h-5 w-96" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}.into_any()
|
||||
}
|
||||
}>
|
||||
<Show when=move || is_authenticated.0.get() fallback=|| ()>
|
||||
<Protected>
|
||||
<div class="flex flex-col h-full overflow-hidden">
|
||||
<div class="flex-1 overflow-hidden">
|
||||
<TorrentTable />
|
||||
</div>
|
||||
</div>
|
||||
</Protected>
|
||||
</Show>
|
||||
</Show>
|
||||
}.into_any()
|
||||
}/>
|
||||
|
||||
<Route path=leptos_router::path!("/settings") view=move || {
|
||||
let authenticated = is_authenticated.0.get();
|
||||
Effect::new(move |_| {
|
||||
if !authenticated {
|
||||
let navigate = use_navigate();
|
||||
navigate("/login", Default::default());
|
||||
}
|
||||
});
|
||||
|
||||
view! {
|
||||
<Show when=move || !is_loading.0.get() fallback=|| ()>
|
||||
<Show when=move || authenticated fallback=|| ()>
|
||||
<Protected>
|
||||
<div class="p-4">"Settings Page (Coming Soon)"</div>
|
||||
</Protected>
|
||||
</Show>
|
||||
</Show>
|
||||
}
|
||||
}/>
|
||||
</Routes>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod use_random;
|
||||
pub mod use_theme_mode;
|
||||
pub mod use_can_scroll_vertical;
|
||||
25
frontend/src/components/hooks/use_can_scroll_vertical.rs
Normal file
25
frontend/src/components/hooks/use_can_scroll_vertical.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use leptos::prelude::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
/// Hook to determine if an element can scroll vertically.
|
||||
///
|
||||
/// Returns (on_scroll_callback, can_scroll_up_signal, can_scroll_down_signal)
|
||||
pub fn use_can_scroll_vertical() -> (Callback<web_sys::Event>, ReadSignal<bool>, ReadSignal<bool>) {
|
||||
let can_scroll_up = RwSignal::new(false);
|
||||
let can_scroll_down = RwSignal::new(false);
|
||||
|
||||
let on_scroll = Callback::new(move |ev: web_sys::Event| {
|
||||
if let Some(target) = ev.target() {
|
||||
if let Some(el) = target.dyn_ref::<web_sys::HtmlElement>() {
|
||||
let scroll_top = el.scroll_top();
|
||||
let scroll_height = el.scroll_height();
|
||||
let client_height = el.client_height();
|
||||
|
||||
can_scroll_up.set(scroll_top > 0);
|
||||
can_scroll_down.set(scroll_top + client_height < scroll_height - 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
(on_scroll, can_scroll_up.read_only(), can_scroll_down.read_only())
|
||||
}
|
||||
30
frontend/src/components/layout/footer.rs
Normal file
30
frontend/src/components/layout/footer.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use leptos::prelude::*;
|
||||
use crate::components::ui::separator::Separator;
|
||||
|
||||
#[component]
|
||||
pub fn Footer() -> impl IntoView {
|
||||
let year = chrono::Local::now().format("%Y").to_string();
|
||||
|
||||
view! {
|
||||
<footer class="mt-auto px-4 py-6 md:px-8">
|
||||
<Separator class="mb-6 opacity-50" />
|
||||
<div class="flex flex-col items-center justify-between gap-4 md:flex-row">
|
||||
<p class="text-center text-sm leading-loose text-muted-foreground md:text-left">
|
||||
{format!("© {} VibeTorrent. Tüm hakları saklıdır.", year)}
|
||||
</p>
|
||||
<div class="flex items-center gap-4 text-sm font-medium text-muted-foreground">
|
||||
<a
|
||||
href="https://git.karatatar.com/admin/vibetorrent"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="underline underline-offset-4 hover:text-foreground transition-colors"
|
||||
>
|
||||
"Gitea"
|
||||
</a>
|
||||
<span class="size-1 rounded-full bg-muted-foreground/30" />
|
||||
<span class="text-[10px] tracking-widest uppercase opacity-70">"v3.0.0-beta"</span>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
pub mod sidebar;
|
||||
pub mod statusbar;
|
||||
pub mod toolbar;
|
||||
pub mod footer;
|
||||
pub mod protected;
|
||||
|
||||
@@ -1,52 +1,31 @@
|
||||
use leptos::prelude::*;
|
||||
use crate::components::layout::sidebar::Sidebar;
|
||||
use crate::components::layout::toolbar::Toolbar;
|
||||
use crate::components::layout::statusbar::StatusBar;
|
||||
use crate::components::layout::footer::Footer;
|
||||
use crate::components::ui::sidenav::{SidenavWrapper, Sidenav, SidenavInset};
|
||||
|
||||
#[component]
|
||||
pub fn Protected(children: Children) -> impl IntoView {
|
||||
// Mobil menü durumu için bir sinyal oluşturuyoruz (RwSignal for easier passing)
|
||||
let is_mobile_menu_open = RwSignal::new(false);
|
||||
|
||||
// Sinyali context olarak sağlıyoruz ki Toolbar ve Sidebar buna erişebilsin
|
||||
provide_context(is_mobile_menu_open);
|
||||
|
||||
view! {
|
||||
<div class="flex h-screen w-full overflow-hidden bg-background">
|
||||
|
||||
// --- SIDEBAR (Desktop: Sabit, Mobil: Overlay) ---
|
||||
<aside class=move || {
|
||||
let base = "fixed inset-y-0 left-0 z-50 w-64 transform transition-transform duration-300 ease-in-out border-r border-border bg-card lg:relative lg:translate-x-0";
|
||||
if is_mobile_menu_open.get() {
|
||||
format!("{} translate-x-0", base)
|
||||
} else {
|
||||
format!("{} -translate-x-full", base)
|
||||
}
|
||||
}>
|
||||
<SidenavWrapper attr:style="--sidenav-width:16rem; --sidenav-width-icon:3rem;">
|
||||
// Masaüstü Sidenav
|
||||
<Sidenav>
|
||||
<Sidebar />
|
||||
</aside>
|
||||
</Sidenav>
|
||||
|
||||
// Mobil arka plan karartma (Overlay)
|
||||
<Show when=move || is_mobile_menu_open.get()>
|
||||
<div
|
||||
class="fixed inset-0 z-40 bg-background/80 backdrop-blur-sm lg:hidden"
|
||||
on:click=move |_| is_mobile_menu_open.set(false)
|
||||
></div>
|
||||
</Show>
|
||||
|
||||
// --- MAIN CONTENT AREA ---
|
||||
<div class="flex flex-1 flex-col overflow-hidden">
|
||||
// --- TOOLBAR (TOP) ---
|
||||
// İçerik Alanı
|
||||
<SidenavInset class="flex flex-col h-screen overflow-hidden">
|
||||
// Toolbar (Üst Bar)
|
||||
<Toolbar />
|
||||
|
||||
// --- MAIN CONTENT ---
|
||||
<main class="flex-1 overflow-hidden relative bg-background">
|
||||
{children()}
|
||||
// Ana İçerik
|
||||
<main class="flex-1 overflow-y-auto relative bg-background flex flex-col">
|
||||
<div class="flex-1">
|
||||
{children()}
|
||||
</div>
|
||||
<Footer />
|
||||
</main>
|
||||
|
||||
// --- STATUS BAR (BOTTOM) ---
|
||||
<StatusBar />
|
||||
</div>
|
||||
</div>
|
||||
</SidenavInset>
|
||||
</SidenavWrapper>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos::task::spawn_local;
|
||||
use crate::components::ui::sidenav::*;
|
||||
use crate::components::ui::button::{Button, ButtonVariant, ButtonSize};
|
||||
use crate::components::ui::theme_toggle::ThemeToggle;
|
||||
|
||||
#[component]
|
||||
pub fn Sidebar() -> impl IntoView {
|
||||
let store = use_context::<crate::store::TorrentStore>().expect("store not provided");
|
||||
let is_mobile_menu_open = use_context::<RwSignal<bool>>().expect("mobile menu state not provided");
|
||||
|
||||
let total_count = move || store.torrents.with(|map| map.len());
|
||||
let downloading_count = move || {
|
||||
@@ -52,7 +53,6 @@ pub fn Sidebar() -> impl IntoView {
|
||||
|
||||
let set_filter = move |f: crate::store::FilterStatus| {
|
||||
store.filter.set(f);
|
||||
is_mobile_menu_open.set(false);
|
||||
};
|
||||
|
||||
let is_active = move |f: crate::store::FilterStatus| store.filter.get() == f;
|
||||
@@ -66,83 +66,89 @@ pub fn Sidebar() -> impl IntoView {
|
||||
};
|
||||
|
||||
view! {
|
||||
<div class="w-full h-full flex flex-col bg-card" style="padding-top: env(safe-area-inset-top);">
|
||||
<div class="p-4 flex-1 overflow-y-auto">
|
||||
<div class="mb-4 px-2 text-lg font-semibold tracking-tight text-foreground">
|
||||
"VibeTorrent"
|
||||
<SidenavHeader>
|
||||
<div class="flex items-center gap-2 px-2 py-4">
|
||||
<div class="flex size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-sm">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.25 0 003 2.48z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="space-y-1">
|
||||
<h4 class="mb-1 rounded-md px-2 py-1 text-sm font-semibold text-muted-foreground">"Filters"</h4>
|
||||
|
||||
<SidebarButton
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::All))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::All)
|
||||
icon="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"
|
||||
label="All"
|
||||
count=Signal::derive(total_count)
|
||||
/>
|
||||
<SidebarButton
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Downloading))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Downloading)
|
||||
icon="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"
|
||||
label="Downloading"
|
||||
count=Signal::derive(downloading_count)
|
||||
/>
|
||||
<SidebarButton
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Seeding))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Seeding)
|
||||
icon="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"
|
||||
label="Seeding"
|
||||
count=Signal::derive(seeding_count)
|
||||
/>
|
||||
<SidebarButton
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Completed))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Completed)
|
||||
icon="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
label="Completed"
|
||||
count=Signal::derive(completed_count)
|
||||
/>
|
||||
<SidebarButton
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Paused))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Paused)
|
||||
icon="M15.75 5.25v13.5m-7.5-13.5v13.5"
|
||||
label="Paused"
|
||||
count=Signal::derive(paused_count)
|
||||
/>
|
||||
<SidebarButton
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Inactive))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Inactive)
|
||||
icon="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"
|
||||
label="Inactive"
|
||||
count=Signal::derive(inactive_count)
|
||||
/>
|
||||
<div class="grid flex-1 text-left text-sm leading-tight overflow-hidden">
|
||||
<span class="truncate font-semibold text-foreground text-base">"VibeTorrent"</span>
|
||||
<span class="truncate text-[10px] text-muted-foreground opacity-70">"v3.0.0"</span>
|
||||
</div>
|
||||
</div>
|
||||
</SidenavHeader>
|
||||
|
||||
// Separator
|
||||
<div class="border-t border-border" />
|
||||
<SidenavContent>
|
||||
<SidenavGroup>
|
||||
<SidenavGroupLabel>"Filtreler"</SidenavGroupLabel>
|
||||
<SidenavGroupContent>
|
||||
<SidenavMenu>
|
||||
<SidebarItem
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::All))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::All)
|
||||
icon="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"
|
||||
label="Tümü"
|
||||
count=Signal::derive(total_count)
|
||||
/>
|
||||
<SidebarItem
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Downloading))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Downloading)
|
||||
icon="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"
|
||||
label="İndirilenler"
|
||||
count=Signal::derive(downloading_count)
|
||||
/>
|
||||
<SidebarItem
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Seeding))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Seeding)
|
||||
icon="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"
|
||||
label="Gönderilenler"
|
||||
count=Signal::derive(seeding_count)
|
||||
/>
|
||||
<SidebarItem
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Completed))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Completed)
|
||||
icon="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
label="Tamamlananlar"
|
||||
count=Signal::derive(completed_count)
|
||||
/>
|
||||
<SidebarItem
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Paused))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Paused)
|
||||
icon="M15.75 5.25v13.5m-7.5-13.5v13.5"
|
||||
label="Durdurulanlar"
|
||||
count=Signal::derive(paused_count)
|
||||
/>
|
||||
<SidebarItem
|
||||
active=Signal::derive(move || is_active(crate::store::FilterStatus::Inactive))
|
||||
on_click=move |_| set_filter(crate::store::FilterStatus::Inactive)
|
||||
icon="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"
|
||||
label="Pasif"
|
||||
count=Signal::derive(inactive_count)
|
||||
/>
|
||||
</SidenavMenu>
|
||||
</SidenavGroupContent>
|
||||
</SidenavGroup>
|
||||
</SidenavContent>
|
||||
|
||||
<div class="p-4 bg-card" style="padding-bottom: calc(1rem + env(safe-area-inset-bottom));">
|
||||
<div class="flex items-center gap-3">
|
||||
// Avatar
|
||||
<div class="h-8 w-8 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-medium shrink-0">
|
||||
{first_letter}
|
||||
</div>
|
||||
<div class="flex-1 overflow-hidden">
|
||||
<div class="font-medium text-sm truncate text-foreground">{username}</div>
|
||||
<div class="text-[10px] text-muted-foreground truncate">"Online"</div>
|
||||
</div>
|
||||
|
||||
// Theme toggle button
|
||||
<div class="inline-flex items-center justify-center size-8 rounded-md hover:bg-accent hover:text-accent-foreground text-muted-foreground hover:text-foreground transition-colors">
|
||||
<crate::components::ui::theme_toggle::ThemeToggle />
|
||||
</div>
|
||||
// Logout button
|
||||
<SidenavFooter>
|
||||
<div class="flex items-center gap-3 p-2 rounded-lg border bg-muted/30 shadow-xs overflow-hidden">
|
||||
<div class="h-8 w-8 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-medium shrink-0 border border-primary-foreground/10">
|
||||
{first_letter}
|
||||
</div>
|
||||
<div class="flex-1 overflow-hidden">
|
||||
<div class="font-medium text-[11px] truncate text-foreground leading-tight">{username}</div>
|
||||
<div class="text-[9px] text-muted-foreground truncate opacity-70">"Yönetici"</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-1">
|
||||
<ThemeToggle />
|
||||
|
||||
<Button
|
||||
variant=ButtonVariant::Ghost
|
||||
size=ButtonSize::Icon
|
||||
class="text-destructive hover:bg-destructive/10"
|
||||
attr:disabled=move || false
|
||||
class="size-7 text-destructive hover:bg-destructive/10"
|
||||
on:click=move |_| {
|
||||
spawn_local(async move {
|
||||
if shared::server_fns::auth::logout().await.is_ok() {
|
||||
@@ -152,37 +158,40 @@ pub fn Sidebar() -> impl IntoView {
|
||||
});
|
||||
}
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-4">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75" />
|
||||
</svg>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SidenavFooter>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn SidebarButton(
|
||||
fn SidebarItem(
|
||||
active: Signal<bool>,
|
||||
on_click: impl Fn(web_sys::MouseEvent) + 'static,
|
||||
on_click: impl Fn(web_sys::MouseEvent) + 'static + Send,
|
||||
#[prop(into)] icon: String,
|
||||
#[prop(into)] label: &'static str,
|
||||
count: Signal<usize>,
|
||||
) -> impl IntoView {
|
||||
let variant = move || if active.get() { ButtonVariant::Secondary } else { ButtonVariant::Ghost };
|
||||
|
||||
let variant = move || if active.get() { SidenavMenuButtonVariant::Outline } else { SidenavMenuButtonVariant::Default };
|
||||
let class = move || if active.get() { "bg-accent/50 border-accent text-foreground".to_string() } else { "text-muted-foreground hover:text-foreground".to_string() };
|
||||
|
||||
view! {
|
||||
<Button
|
||||
variant=Signal::derive(variant)
|
||||
class="justify-start gap-2 w-full h-8 px-3"
|
||||
on:click=on_click
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d=icon.clone() />
|
||||
</svg>
|
||||
{label}
|
||||
<span class="ml-auto text-xs font-mono opacity-70">{count}</span>
|
||||
</Button>
|
||||
<SidenavMenuItem>
|
||||
<SidenavMenuButton
|
||||
variant=Signal::derive(variant)
|
||||
class=Signal::derive(class)
|
||||
on:click=on_click
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-4 shrink-0">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d=icon.clone() />
|
||||
</svg>
|
||||
<span class="flex-1 truncate">{label}</span>
|
||||
<span class="text-[10px] font-mono opacity-50">{count}</span>
|
||||
</SidenavMenuButton>
|
||||
</SidenavMenuItem>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos::html;
|
||||
use shared::GlobalLimitRequest;
|
||||
use crate::api;
|
||||
|
||||
fn format_bytes(bytes: i64) -> String {
|
||||
const UNITS: [&str; 6] = ["B", "KB", "MB", "GB", "TB", "PB"];
|
||||
if bytes < 1024 {
|
||||
return format!("{} B", bytes);
|
||||
}
|
||||
let i = (bytes as f64).log2().div_euclid(10.0) as usize;
|
||||
format!(
|
||||
"{:.1} {}",
|
||||
(bytes as f64) / 1024_f64.powi(i as i32),
|
||||
UNITS[i]
|
||||
)
|
||||
}
|
||||
|
||||
fn format_speed(bytes_per_sec: i64) -> String {
|
||||
if bytes_per_sec == 0 {
|
||||
return "0 B/s".to_string();
|
||||
}
|
||||
format!("{}/s", format_bytes(bytes_per_sec))
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn StatusBar() -> impl IntoView {
|
||||
let store = use_context::<crate::store::TorrentStore>().expect("store not provided");
|
||||
let stats = store.global_stats;
|
||||
|
||||
|
||||
|
||||
// Preset limits in bytes/s
|
||||
let limits: Vec<(i64, &str)> = vec!(
|
||||
(0, "Unlimited"),
|
||||
(100 * 1024, "100 KB/s"),
|
||||
(500 * 1024, "500 KB/s"),
|
||||
(1024 * 1024, "1 MB/s"),
|
||||
(2 * 1024 * 1024, "2 MB/s"),
|
||||
(5 * 1024 * 1024, "5 MB/s"),
|
||||
(10 * 1024 * 1024, "10 MB/s"),
|
||||
(20 * 1024 * 1024, "20 MB/s"),
|
||||
);
|
||||
|
||||
let set_limit = move |limit_type: &str, val: i64| {
|
||||
let limit_type = limit_type.to_string();
|
||||
log::info!("Setting {} limit to {}", limit_type, val);
|
||||
|
||||
let req = if limit_type == "down" {
|
||||
GlobalLimitRequest {
|
||||
max_download_rate: Some(val),
|
||||
max_upload_rate: None,
|
||||
}
|
||||
} else {
|
||||
GlobalLimitRequest {
|
||||
max_download_rate: None,
|
||||
max_upload_rate: Some(val),
|
||||
}
|
||||
};
|
||||
|
||||
leptos::task::spawn_local(async move {
|
||||
if let Err(e) = api::settings::set_global_limits(&req).await {
|
||||
log::error!("Failed to set limit: {:?}", e);
|
||||
} else {
|
||||
log::info!("Limit set successfully");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
let down_details_ref = NodeRef::<html::Details>::new();
|
||||
let up_details_ref = NodeRef::<html::Details>::new();
|
||||
|
||||
let close_details = move |node_ref: NodeRef<html::Details>| {
|
||||
if let Some(el) = node_ref.get_untracked() {
|
||||
el.set_open(false);
|
||||
}
|
||||
};
|
||||
|
||||
view! {
|
||||
<div class="fixed bottom-0 left-0 right-0 h-8 min-h-8 bg-muted border-t border-border flex items-center px-4 text-xs gap-4 text-muted-foreground z-[99] cursor-pointer">
|
||||
|
||||
// --- DOWNLOAD SPEED DROPDOWN ---
|
||||
<details class="group relative" node_ref=down_details_ref>
|
||||
<summary class="flex items-center gap-2 cursor-pointer hover:text-foreground transition-colors select-none list-none [&::-webkit-details-marker]:hidden outline-none">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3" />
|
||||
</svg>
|
||||
<span class="font-mono">{move || format_speed(stats.get().down_rate)}</span>
|
||||
<Show when=move || { stats.get().down_limit.unwrap_or(0) > 0 } fallback=|| ()>
|
||||
<span class="text-[10px] opacity-60">
|
||||
{move || format!("(Limit: {})", format_speed(stats.get().down_limit.unwrap_or(0)))}
|
||||
</span>
|
||||
</Show>
|
||||
</summary>
|
||||
|
||||
<div class="absolute bottom-full left-0 mb-2 z-[100] min-w-[8rem] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md hidden group-open:block animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2">
|
||||
<ul class="w-full">
|
||||
{
|
||||
limits.clone().into_iter().map(|(val, label)| {
|
||||
let is_active = move || {
|
||||
let current = stats.get().down_limit.unwrap_or(0);
|
||||
(current - val).abs() < 1024
|
||||
};
|
||||
view! {
|
||||
<li>
|
||||
<button
|
||||
class=move || {
|
||||
let base = "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-xs outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-accent hover:text-accent-foreground";
|
||||
if is_active() { format!("{} bg-accent text-accent-foreground font-medium", base) } else { base.to_string() }
|
||||
}
|
||||
on:click=move |_| {
|
||||
set_limit("down", val);
|
||||
close_details(down_details_ref);
|
||||
}
|
||||
>
|
||||
<span class="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<Show when=is_active fallback=|| ()>
|
||||
<span>"✓"</span>
|
||||
</Show>
|
||||
</span>
|
||||
{label}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
}).collect::<Vec<_>>()
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
// --- UPLOAD SPEED DROPDOWN ---
|
||||
<details class="group relative" node_ref=up_details_ref>
|
||||
<summary class="flex items-center gap-2 cursor-pointer hover:text-foreground transition-colors select-none list-none [&::-webkit-details-marker]:hidden outline-none">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 10.5L12 3m0 0l7.5 7.5M12 3v18" />
|
||||
</svg>
|
||||
<span class="font-mono">{move || format_speed(stats.get().up_rate)}</span>
|
||||
<Show when=move || { stats.get().up_limit.unwrap_or(0) > 0 } fallback=|| ()>
|
||||
<span class="text-[10px] opacity-60">
|
||||
{move || format!("(Limit: {})", format_speed(stats.get().up_limit.unwrap_or(0)))}
|
||||
</span>
|
||||
</Show>
|
||||
</summary>
|
||||
|
||||
<div class="absolute bottom-full left-0 mb-2 z-[100] min-w-[8rem] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md hidden group-open:block animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2">
|
||||
<ul class="w-full">
|
||||
{
|
||||
limits.clone().into_iter().map(|(val, label)| {
|
||||
let is_active = move || {
|
||||
let current = stats.get().up_limit.unwrap_or(0);
|
||||
(current - val).abs() < 1024
|
||||
};
|
||||
view! {
|
||||
<li>
|
||||
<button
|
||||
class=move || {
|
||||
let base = "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-xs outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-accent hover:text-accent-foreground";
|
||||
if is_active() { format!("{} bg-accent text-accent-foreground font-medium", base) } else { base.to_string() }
|
||||
}
|
||||
on:click=move |_| {
|
||||
set_limit("up", val);
|
||||
close_details(up_details_ref);
|
||||
}
|
||||
>
|
||||
<span class="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<Show when=is_active fallback=|| ()>
|
||||
<span>"✓"</span>
|
||||
</Show>
|
||||
</span>
|
||||
{label}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
}).collect::<Vec<_>>()
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div class="ml-auto flex items-center gap-4">
|
||||
<button
|
||||
class="inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:bg-accent hover:text-accent-foreground h-7 w-7"
|
||||
title="Settings & Notification Permissions"
|
||||
on:click=move |_| {
|
||||
// Request push notification permission
|
||||
leptos::task::spawn_local(async {
|
||||
// ... existing logic ...
|
||||
crate::store::subscribe_to_push_notifications().await;
|
||||
// ... existing logic ...
|
||||
});
|
||||
}
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.212 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 012.6-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,52 @@
|
||||
use leptos::prelude::*;
|
||||
use icons::PanelLeft;
|
||||
use crate::components::torrent::add_torrent::AddTorrentDialog;
|
||||
use crate::components::ui::button::{Button, ButtonVariant, ButtonSize};
|
||||
use crate::components::ui::sheet::{Sheet, SheetContent, SheetTrigger, SheetDirection};
|
||||
use crate::components::layout::sidebar::Sidebar;
|
||||
|
||||
#[component]
|
||||
pub fn Toolbar() -> impl IntoView {
|
||||
let show_add_modal = signal(false);
|
||||
let store = use_context::<crate::store::TorrentStore>().expect("store not provided");
|
||||
let is_mobile_menu_open = use_context::<RwSignal<bool>>().expect("mobile menu state not provided");
|
||||
|
||||
let search_value = RwSignal::new(String::new());
|
||||
|
||||
// Sync search_value to store
|
||||
Effect::new(move |_| {
|
||||
let val = search_value.get();
|
||||
store.search_query.set(val);
|
||||
});
|
||||
|
||||
view! {
|
||||
<div class="flex min-h-14 h-auto items-center border-b border-border bg-background px-4" style="padding-top: env(safe-area-inset-top);">
|
||||
// Sol kısım: Menü butonu + Add Torrent
|
||||
// Sol kısım: Menü butonu (Mobil) + Add Torrent
|
||||
<div class="flex items-center gap-3">
|
||||
// Mobile Menu Trigger
|
||||
<button
|
||||
class="inline-flex items-center justify-center size-9 rounded-md hover:bg-accent hover:text-accent-foreground lg:hidden"
|
||||
on:click=move |_| is_mobile_menu_open.update(|v| *v = !*v)
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="w-5 h-5 stroke-current"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
|
||||
</button>
|
||||
|
||||
<button
|
||||
class="inline-flex items-center justify-center gap-2 h-9 px-4 py-2 rounded-md text-sm font-medium bg-primary text-primary-foreground shadow-xs hover:bg-primary/90 transition-all active:scale-[0.98]"
|
||||
// --- MOBILE SHEET (SIDEBAR) ---
|
||||
<div class="lg:hidden">
|
||||
<Sheet>
|
||||
<SheetTrigger variant=ButtonVariant::Ghost size=ButtonSize::Icon class="size-9">
|
||||
<PanelLeft class="size-5" />
|
||||
<span class="hidden">"Menüyü Aç"</span>
|
||||
</SheetTrigger>
|
||||
<SheetContent
|
||||
direction=SheetDirection::Left
|
||||
class="p-0 w-[18rem] bg-card border-r border-border"
|
||||
hide_close_button=true
|
||||
>
|
||||
<div class="flex flex-col h-full overflow-hidden">
|
||||
<Sidebar />
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
on:click=move |_| show_add_modal.1.set(true)
|
||||
class="gap-2"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-4 h-4 md:w-5 md:h-5">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
|
||||
</svg>
|
||||
<span class="hidden sm:inline">"Add Torrent"</span>
|
||||
<span class="sm:hidden">"Add"</span>
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
// Sağ kısım: Search kutusu
|
||||
// Sağ kısım boş
|
||||
<div class="flex flex-1 items-center justify-end gap-2">
|
||||
<div class="hidden md:flex items-center gap-2 w-full max-w-xs">
|
||||
<div class="relative flex-1">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
|
||||
</svg>
|
||||
<input
|
||||
type="search"
|
||||
placeholder="Search..."
|
||||
class="file:text-foreground placeholder:text-muted-foreground border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-2 md:text-sm pl-8"
|
||||
bind:value=search_value
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Show when=move || show_add_modal.0.get()>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos::task::spawn_local;
|
||||
use std::collections::HashSet;
|
||||
use icons::{ArrowUpDown};
|
||||
use icons::{ArrowUpDown, Inbox, Settings2, Play, Square, Trash2, Ellipsis, ArrowUp, ArrowDown, Check, ListFilter};
|
||||
use crate::store::{get_action_messages, show_toast};
|
||||
use crate::api;
|
||||
use shared::NotificationLevel;
|
||||
@@ -9,6 +9,24 @@ use crate::components::context_menu::TorrentContextMenu;
|
||||
use crate::components::ui::card::{Card, CardHeader, CardTitle, CardContent as CardBody};
|
||||
use crate::components::ui::data_table::*;
|
||||
use crate::components::ui::checkbox::Checkbox;
|
||||
use crate::components::ui::button::{Button, ButtonVariant};
|
||||
use crate::components::ui::empty::*;
|
||||
use crate::components::ui::input::Input;
|
||||
use crate::components::ui::multi_select::*;
|
||||
use crate::components::ui::dropdown_menu::*;
|
||||
use crate::components::ui::alert_dialog::*;
|
||||
use tailwind_fuse::tw_merge;
|
||||
|
||||
const ALL_COLUMNS: [(&str, &str); 8] = [
|
||||
("Name", "Name"),
|
||||
("Size", "Size"),
|
||||
("Progress", "Progress"),
|
||||
("Status", "Status"),
|
||||
("DownSpeed", "DL Speed"),
|
||||
("UpSpeed", "UP Speed"),
|
||||
("ETA", "ETA"),
|
||||
("AddedDate", "Date"),
|
||||
];
|
||||
|
||||
fn format_bytes(bytes: i64) -> String {
|
||||
const UNITS: [&str; 6] = ["B", "KB", "MB", "GB", "TB", "PB"];
|
||||
@@ -54,8 +72,13 @@ pub fn TorrentTable() -> impl IntoView {
|
||||
let sort_col = signal(SortColumn::AddedDate);
|
||||
let sort_dir = signal(SortDirection::Descending);
|
||||
|
||||
// Multi-selection state
|
||||
let selected_hashes = RwSignal::new(HashSet::<String>::new());
|
||||
|
||||
let visible_columns = RwSignal::new(HashSet::from([
|
||||
"Name".to_string(), "Size".to_string(), "Progress".to_string(),
|
||||
"Status".to_string(), "DownSpeed".to_string(), "UpSpeed".to_string(),
|
||||
"ETA".to_string(), "AddedDate".to_string()
|
||||
]));
|
||||
|
||||
let sorted_hashes_data = Memo::new(move |_| {
|
||||
let torrents_map = store.torrents.get();
|
||||
@@ -110,15 +133,14 @@ pub fn TorrentTable() -> impl IntoView {
|
||||
})
|
||||
});
|
||||
|
||||
let has_selection = Signal::derive(move || selected_count.get() > 0);
|
||||
|
||||
let handle_select_all = Callback::new(move |checked: bool| {
|
||||
selected_hashes.update(|selected| {
|
||||
let hashes = filtered_hashes.get_untracked();
|
||||
for h in hashes {
|
||||
if checked {
|
||||
selected.insert(h);
|
||||
} else {
|
||||
selected.remove(&h);
|
||||
}
|
||||
if checked { selected.insert(h); }
|
||||
else { selected.remove(&h); }
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -134,6 +156,37 @@ pub fn TorrentTable() -> impl IntoView {
|
||||
}
|
||||
};
|
||||
|
||||
let sort_icon = move |col: SortColumn| {
|
||||
let is_active = sort_col.0.get() == col;
|
||||
let class = if is_active { "size-3 text-primary" } else { "size-3 opacity-30 group-hover:opacity-100 transition-opacity" };
|
||||
view! { <ArrowUpDown class=class.to_string() /> }.into_any()
|
||||
};
|
||||
|
||||
let bulk_action = move |action: &'static str| {
|
||||
let hashes: Vec<String> = selected_hashes.get().into_iter().collect();
|
||||
if hashes.is_empty() { return; }
|
||||
|
||||
spawn_local(async move {
|
||||
let mut success = true;
|
||||
for hash in hashes {
|
||||
let res = match action {
|
||||
"start" => api::torrent::start(&hash).await,
|
||||
"stop" => api::torrent::stop(&hash).await,
|
||||
"delete" => api::torrent::delete(&hash).await,
|
||||
"delete_with_data" => api::torrent::delete_with_data(&hash).await,
|
||||
_ => Ok(()),
|
||||
};
|
||||
if res.is_err() { success = false; }
|
||||
}
|
||||
if success {
|
||||
show_toast(NotificationLevel::Success, format!("Toplu işlem başarıyla tamamlandı: {}", action));
|
||||
selected_hashes.update(|s| s.clear());
|
||||
} else {
|
||||
show_toast(NotificationLevel::Error, "Bazı işlemler başarısız oldu.");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
let on_action = Callback::new(move |(action, hash): (String, String)| {
|
||||
let (success_msg_str, error_msg_str): (&'static str, &'static str) = get_action_messages(&action);
|
||||
let success_msg = success_msg_str.to_string();
|
||||
@@ -154,15 +207,169 @@ pub fn TorrentTable() -> impl IntoView {
|
||||
});
|
||||
|
||||
view! {
|
||||
<div class="h-full bg-background relative flex flex-col overflow-hidden px-4 py-2">
|
||||
// --- DESKTOP VIEW ---
|
||||
<div class="hidden md:flex flex-col h-full overflow-hidden">
|
||||
<DataTableWrapper class="flex-1 min-h-0 bg-card/50">
|
||||
<div class="h-full bg-background relative flex flex-col overflow-hidden px-4 py-4 gap-4">
|
||||
// --- TOPBAR ---
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div class="flex items-center gap-2 flex-1 max-w-md">
|
||||
<Input
|
||||
class="h-9"
|
||||
placeholder="Torrent ara..."
|
||||
bind_value=store.search_query
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<Show when=move || has_selection.get()>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger class="w-[140px] h-9 gap-2">
|
||||
<Ellipsis class="size-4" />
|
||||
{move || format!("Toplu İşlem ({})", selected_count.get())}
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent class="w-48">
|
||||
<DropdownMenuLabel>"Seçili Torrentler"</DropdownMenuLabel>
|
||||
<DropdownMenuGroup class="mt-2">
|
||||
<DropdownMenuItem on:click=move |_| bulk_action("start")>
|
||||
<Play class="mr-2 size-4" /> "Başlat"
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem on:click=move |_| bulk_action("stop")>
|
||||
<Square class="mr-2 size-4" /> "Durdur"
|
||||
</DropdownMenuItem>
|
||||
|
||||
<div class="my-1 h-px bg-border" />
|
||||
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger class="w-full text-left">
|
||||
<div class="inline-flex gap-2 items-center w-full rounded-sm px-2 py-1.5 text-sm transition-colors text-destructive hover:bg-destructive/10 focus:bg-destructive/10">
|
||||
<Trash2 class="size-4" /> "Toplu Sil..."
|
||||
</div>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle class="text-destructive flex items-center gap-2">
|
||||
<Trash2 class="size-5" />
|
||||
"Toplu Silme Onayı"
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription class="pt-2">
|
||||
{move || format!("Seçili {} adet torrent silinecek. Lütfen silme yöntemini seçin:", selected_count.get())}
|
||||
<div class="mt-4 p-3 bg-muted/50 rounded-md text-xs border border-border italic">
|
||||
"Dikkat: Verilerle birlikte silme işlemi dosyaları diskten de kalıcı olarak kaldıracaktır."
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter class="gap-2 sm:gap-0">
|
||||
<div class="flex flex-col sm:flex-row gap-2 w-full justify-end">
|
||||
<AlertDialogClose class="order-3 sm:order-1">"Vazgeç"</AlertDialogClose>
|
||||
<Button
|
||||
variant=ButtonVariant::Outline
|
||||
class="order-2 text-foreground"
|
||||
on:click=move |_| bulk_action("delete")
|
||||
>
|
||||
"Sadece Listeden Sil"
|
||||
</Button>
|
||||
<Button
|
||||
variant=ButtonVariant::Destructive
|
||||
class="order-1"
|
||||
on:click=move |_| bulk_action("delete_with_data")
|
||||
>
|
||||
"Verilerle Birlikte Sil"
|
||||
</Button>
|
||||
</div>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</Show>
|
||||
|
||||
// Mobile Sort Menu
|
||||
<div class="block md:hidden">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger class="w-[100px] h-9 gap-2 text-xs">
|
||||
<ListFilter class="size-4" />
|
||||
"Sırala"
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent class="w-56">
|
||||
<DropdownMenuLabel>"Sıralama Ölçütü"</DropdownMenuLabel>
|
||||
<DropdownMenuGroup class="mt-2">
|
||||
{move || {
|
||||
let current_col = sort_col.0.get();
|
||||
let current_dir = sort_dir.0.get();
|
||||
|
||||
let sort_items = vec![
|
||||
(SortColumn::Name, "İsim"),
|
||||
(SortColumn::Size, "Boyut"),
|
||||
(SortColumn::Progress, "İlerleme"),
|
||||
(SortColumn::Status, "Durum"),
|
||||
(SortColumn::DownSpeed, "DL Hızı"),
|
||||
(SortColumn::UpSpeed, "UP Hızı"),
|
||||
(SortColumn::ETA, "Kalan Süre"),
|
||||
(SortColumn::AddedDate, "Tarih"),
|
||||
];
|
||||
|
||||
sort_items.into_iter().map(|(col, label)| {
|
||||
let is_active = current_col == col;
|
||||
view! {
|
||||
<DropdownMenuItem on:click=move |_| handle_sort(col)>
|
||||
<div class="flex items-center justify-between w-full">
|
||||
<div class="flex items-center gap-2">
|
||||
{if is_active { view! { <Check class="size-4 text-primary" /> }.into_any() } else { view! { <div class="size-4" /> }.into_any() }}
|
||||
<span class=if is_active { "font-bold text-primary" } else { "" }>{label}</span>
|
||||
</div>
|
||||
{if is_active {
|
||||
match current_dir {
|
||||
SortDirection::Ascending => view! { <ArrowUp class="size-3 opacity-50" /> }.into_any(),
|
||||
SortDirection::Descending => view! { <ArrowDown class="size-3 opacity-50" /> }.into_any(),
|
||||
}
|
||||
} else { view! { "" }.into_any() }}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
}.into_any()
|
||||
}).collect_view()
|
||||
}}
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
// Desktop Columns Menu
|
||||
<div class="hidden md:flex">
|
||||
<MultiSelect values=visible_columns>
|
||||
<MultiSelectTrigger class="w-[140px] h-9">
|
||||
<div class="flex items-center gap-2 text-xs">
|
||||
<Settings2 class="size-4" />
|
||||
"Sütunlar"
|
||||
</div>
|
||||
</MultiSelectTrigger>
|
||||
<MultiSelectContent>
|
||||
<MultiSelectGroup>
|
||||
{ALL_COLUMNS.into_iter().map(|(id, label)| {
|
||||
let id_val = id.to_string();
|
||||
view! {
|
||||
<MultiSelectItem>
|
||||
<MultiSelectOption value=id_val.clone() attr:disabled=move || id_val == "Name">
|
||||
{label}
|
||||
</MultiSelectOption>
|
||||
</MultiSelectItem>
|
||||
}.into_any()
|
||||
}).collect_view()}
|
||||
</MultiSelectGroup>
|
||||
</MultiSelectContent>
|
||||
</MultiSelect>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
// --- MAIN CONTENT ---
|
||||
<div class="flex-1 min-h-0 overflow-hidden">
|
||||
// Desktop Table View
|
||||
<DataTableWrapper class="hidden md:block h-full bg-card/50">
|
||||
// ... (Masaüstü tablosu aynı kalıyor)
|
||||
<div class="h-full overflow-auto">
|
||||
<DataTable>
|
||||
<DataTableHeader class="sticky top-0 bg-muted/80 backdrop-blur-sm z-10">
|
||||
<DataTableRow class="hover:bg-transparent">
|
||||
<DataTableHead class="w-12">
|
||||
<DataTableHead class="w-12 px-4">
|
||||
<Checkbox
|
||||
checked=Signal::derive(move || {
|
||||
let hashes = filtered_hashes.get();
|
||||
@@ -171,72 +378,158 @@ pub fn TorrentTable() -> impl IntoView {
|
||||
on_checked_change=handle_select_all
|
||||
/>
|
||||
</DataTableHead>
|
||||
<DataTableHead class="cursor-pointer group select-none" on:click=move |_| handle_sort(SortColumn::Name)>
|
||||
<div class="flex items-center gap-2">
|
||||
"Name"
|
||||
<ArrowUpDown class="size-3 opacity-50 group-hover:opacity-100 transition-opacity" />
|
||||
</div>
|
||||
</DataTableHead>
|
||||
<DataTableHead class="w-24">"Size"</DataTableHead>
|
||||
<DataTableHead class="w-48">"Progress"</DataTableHead>
|
||||
<DataTableHead class="w-24">"Status"</DataTableHead>
|
||||
<DataTableHead class="w-24 text-right">"DL Speed"</DataTableHead>
|
||||
<DataTableHead class="w-24 text-right">"UP Speed"</DataTableHead>
|
||||
<DataTableHead class="w-24 text-right">"ETA"</DataTableHead>
|
||||
<DataTableHead class="w-32 text-right">"Date"</DataTableHead>
|
||||
|
||||
{move || visible_columns.get().contains("Name").then(|| view! {
|
||||
<DataTableHead class="cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground" on:click=move |_| handle_sort(SortColumn::Name)>
|
||||
<div class="flex items-center gap-2">"Name" {move || sort_icon(SortColumn::Name)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("Size").then(|| view! {
|
||||
<DataTableHead class="w-24 cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground" on:click=move |_| handle_sort(SortColumn::Size)>
|
||||
<div class="flex items-center gap-2">"Size" {move || sort_icon(SortColumn::Size)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("Progress").then(|| view! {
|
||||
<DataTableHead class="w-48 cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground" on:click=move |_| handle_sort(SortColumn::Progress)>
|
||||
<div class="flex items-center gap-2">"Progress" {move || sort_icon(SortColumn::Progress)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("Status").then(|| view! {
|
||||
<DataTableHead class="w-24 cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground" on:click=move |_| handle_sort(SortColumn::Status)>
|
||||
<div class="flex items-center gap-2">"Status" {move || sort_icon(SortColumn::Status)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("DownSpeed").then(|| view! {
|
||||
<DataTableHead class="w-24 cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground text-right" on:click=move |_| handle_sort(SortColumn::DownSpeed)>
|
||||
<div class="flex items-center justify-end gap-2">"DL Speed" {move || sort_icon(SortColumn::DownSpeed)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("UpSpeed").then(|| view! {
|
||||
<DataTableHead class="w-24 cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground text-right" on:click=move |_| handle_sort(SortColumn::UpSpeed)>
|
||||
<div class="flex items-center justify-end gap-2">"UP Speed" {move || sort_icon(SortColumn::UpSpeed)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("ETA").then(|| view! {
|
||||
<DataTableHead class="w-24 cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground text-right" on:click=move |_| handle_sort(SortColumn::ETA)>
|
||||
<div class="flex items-center justify-end gap-2">"ETA" {move || sort_icon(SortColumn::ETA)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("AddedDate").then(|| view! {
|
||||
<DataTableHead class="w-32 cursor-pointer group select-none transition-all duration-100 active:scale-[0.98] hover:bg-muted/30 hover:text-foreground text-right" on:click=move |_| handle_sort(SortColumn::AddedDate)>
|
||||
<div class="flex items-center justify-end gap-2">"Date" {move || sort_icon(SortColumn::AddedDate)}</div>
|
||||
</DataTableHead>
|
||||
}).into_any()}
|
||||
</DataTableRow>
|
||||
</DataTableHeader>
|
||||
<DataTableBody>
|
||||
<For each=move || filtered_hashes.get() key=|hash| hash.clone() children={
|
||||
let on_action = on_action.clone();
|
||||
move |hash| {
|
||||
let h = hash.clone();
|
||||
let is_selected = Signal::derive(move || {
|
||||
selected_hashes.with(|selected| selected.contains(&h))
|
||||
});
|
||||
let h_for_change = hash.clone();
|
||||
view! {
|
||||
<TorrentRow
|
||||
hash=hash.clone()
|
||||
on_action=on_action.clone()
|
||||
is_selected=is_selected
|
||||
on_select=Callback::new(move |checked| {
|
||||
selected_hashes.update(|selected| {
|
||||
if checked { selected.insert(h_for_change.clone()); }
|
||||
else { selected.remove(&h_for_change); }
|
||||
});
|
||||
})
|
||||
/>
|
||||
<Show
|
||||
when=move || !filtered_hashes.get().is_empty()
|
||||
fallback=move || view! {
|
||||
<DataTableRow class="hover:bg-transparent">
|
||||
<DataTableCell attr:colspan="10" class="h-[400px]">
|
||||
<Empty class="h-full">
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant=EmptyMediaVariant::Icon>
|
||||
<Inbox class="size-10 text-muted-foreground" />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>"Torrent Bulunamadı"</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{move || {
|
||||
let query = store.search_query.get();
|
||||
if query.is_empty() { "Henüz torrent bulunmuyor.".to_string() }
|
||||
else { "Arama kriterlerinize uygun sonuç bulunamadı.".to_string() }
|
||||
}}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
</DataTableCell>
|
||||
</DataTableRow>
|
||||
}.into_any()
|
||||
>
|
||||
<For each=move || filtered_hashes.get() key=|hash| hash.clone() children={
|
||||
let on_action = on_action.clone();
|
||||
move |hash| {
|
||||
let h = hash.clone();
|
||||
let is_selected = Signal::derive(move || {
|
||||
selected_hashes.with(|selected| selected.contains(&h))
|
||||
});
|
||||
let h_for_change = hash.clone();
|
||||
view! {
|
||||
<TorrentRow
|
||||
hash=hash.clone()
|
||||
on_action=on_action.clone()
|
||||
is_selected=is_selected
|
||||
visible_columns=visible_columns
|
||||
on_select=Callback::new(move |checked| {
|
||||
selected_hashes.update(|selected| {
|
||||
if checked { selected.insert(h_for_change.clone()); }
|
||||
else { selected.remove(&h_for_change); }
|
||||
});
|
||||
})
|
||||
/>
|
||||
}
|
||||
}
|
||||
}
|
||||
} />
|
||||
} />
|
||||
</Show>
|
||||
</DataTableBody>
|
||||
</DataTable>
|
||||
</div>
|
||||
</DataTableWrapper>
|
||||
|
||||
// Selection Info Footer
|
||||
<div class="flex items-center justify-between py-2 text-xs text-muted-foreground">
|
||||
<div>
|
||||
{move || format!("{} / {} torrent seçili", selected_count.get(), filtered_hashes.get().len())}
|
||||
</div>
|
||||
|
||||
// Mobile Card View
|
||||
<div class="block md:hidden h-full overflow-y-auto space-y-4 pb-32">
|
||||
<Show
|
||||
when=move || !filtered_hashes.get().is_empty()
|
||||
fallback=move || view! {
|
||||
<div class="flex flex-col items-center justify-center h-64 opacity-50 text-muted-foreground">
|
||||
<Inbox class="size-12 mb-2" />
|
||||
<p>"Torrent Bulunamadı"</p>
|
||||
</div>
|
||||
}.into_any()
|
||||
>
|
||||
<For each=move || filtered_hashes.get() key=|hash| hash.clone() children={
|
||||
let on_action = on_action.clone();
|
||||
move |hash| {
|
||||
let h = hash.clone();
|
||||
let is_selected = Signal::derive(move || {
|
||||
selected_hashes.with(|selected| selected.contains(&h))
|
||||
});
|
||||
let h_for_change = hash.clone();
|
||||
|
||||
view! {
|
||||
<TorrentCard
|
||||
hash=hash.clone()
|
||||
on_action=on_action.clone()
|
||||
is_selected=is_selected
|
||||
on_select=Callback::new(move |checked| {
|
||||
selected_hashes.update(|selected| {
|
||||
if checked { selected.insert(h_for_change.clone()); }
|
||||
else { selected.remove(&h_for_change); }
|
||||
});
|
||||
})
|
||||
/>
|
||||
}
|
||||
}
|
||||
} />
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
// --- MOBILE VIEW ---
|
||||
<div class="md:hidden flex flex-col h-full bg-muted/10 relative overflow-hidden">
|
||||
<div class="flex-1 overflow-y-auto p-3 min-h-0">
|
||||
<For each=move || filtered_hashes.get() key=|hash| hash.clone() children={
|
||||
let on_action = on_action.clone();
|
||||
move |hash| {
|
||||
view! {
|
||||
<div class="pb-3">
|
||||
<TorrentCard hash=hash.clone() on_action=on_action.clone() />
|
||||
</div>
|
||||
}
|
||||
}
|
||||
} />
|
||||
<div class="hidden md:flex items-center justify-between px-2 py-1 text-[11px] text-muted-foreground bg-muted/20 border rounded-md">
|
||||
<div class="flex gap-4">
|
||||
<span>{move || format!("Toplam: {} torrent", filtered_hashes.get().len())}</span>
|
||||
<Show when=move || has_selection.get()>
|
||||
<span class="text-primary font-medium">{move || format!("{} torrent seçili", selected_count.get())}</span>
|
||||
</Show>
|
||||
</div>
|
||||
<div>"VibeTorrent v3"</div>
|
||||
</div>
|
||||
</div>
|
||||
}.into_any()
|
||||
@@ -247,6 +540,7 @@ fn TorrentRow(
|
||||
hash: String,
|
||||
on_action: Callback<(String, String)>,
|
||||
is_selected: Signal<bool>,
|
||||
visible_columns: RwSignal<HashSet<String>>,
|
||||
on_select: Callback<bool>,
|
||||
) -> impl IntoView {
|
||||
let store = use_context::<crate::store::TorrentStore>().expect("store not provided");
|
||||
@@ -269,8 +563,7 @@ fn TorrentRow(
|
||||
selected.as_deref() == Some(stored_hash.get_value().as_str())
|
||||
});
|
||||
|
||||
let t_name_for_title = t_name.clone();
|
||||
let t_name_for_content = t_name.clone();
|
||||
let t_name_stored = StoredValue::new(t_name.clone());
|
||||
let h_for_menu = stored_hash.get_value();
|
||||
|
||||
view! {
|
||||
@@ -280,41 +573,80 @@ fn TorrentRow(
|
||||
attr:data-state=move || if is_selected.get() || is_active_selection.get() { "selected" } else { "" }
|
||||
on:click=move |_| store.selected_torrent.set(Some(stored_hash.get_value()))
|
||||
>
|
||||
<DataTableCell class="w-12">
|
||||
<DataTableCell class="w-12 px-4">
|
||||
<Checkbox
|
||||
checked=is_selected
|
||||
on_checked_change=on_select
|
||||
/>
|
||||
</DataTableCell>
|
||||
<DataTableCell class="font-medium truncate max-w-[200px] lg:max-w-md" attr:title=t_name_for_title>
|
||||
{t_name_for_content}
|
||||
</DataTableCell>
|
||||
<DataTableCell class="font-mono text-xs text-muted-foreground">
|
||||
{format_bytes(t.size)}
|
||||
</DataTableCell>
|
||||
<DataTableCell>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="h-1.5 w-full bg-secondary rounded-full overflow-hidden min-w-[80px]">
|
||||
<div class="h-full bg-primary transition-all duration-500" style=format!("width: {}%", t.percent_complete)></div>
|
||||
</div>
|
||||
<span class="text-[10px] text-muted-foreground w-10 text-right">{format!("{:.1}%", t.percent_complete)}</span>
|
||||
</div>
|
||||
</DataTableCell>
|
||||
<DataTableCell class={format!("text-xs font-semibold {}", status_color)}>
|
||||
{format!("{:?}", t.status)}
|
||||
</DataTableCell>
|
||||
<DataTableCell class="text-right font-mono text-xs text-green-600 dark:text-green-500 whitespace-nowrap">
|
||||
{format_speed(t.down_rate)}
|
||||
</DataTableCell>
|
||||
<DataTableCell class="text-right font-mono text-xs text-blue-600 dark:text-blue-500 whitespace-nowrap">
|
||||
{format_speed(t.up_rate)}
|
||||
</DataTableCell>
|
||||
<DataTableCell class="text-right font-mono text-xs text-muted-foreground whitespace-nowrap">
|
||||
{format_duration(t.eta)}
|
||||
</DataTableCell>
|
||||
<DataTableCell class="text-right font-mono text-xs text-muted-foreground whitespace-nowrap">
|
||||
{format_date(t.added_date)}
|
||||
</DataTableCell>
|
||||
|
||||
{move || visible_columns.get().contains("Name").then({
|
||||
move || view! {
|
||||
<DataTableCell class="font-medium truncate max-w-[200px] lg:max-w-md" attr:title=t_name_stored.get_value()>
|
||||
{t_name_stored.get_value()}
|
||||
</DataTableCell>
|
||||
}
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("Size").then({
|
||||
let size_bytes = t.size;
|
||||
move || {
|
||||
let size_str = format_bytes(size_bytes);
|
||||
view! { <DataTableCell class="font-mono text-xs text-muted-foreground whitespace-nowrap">{size_str}</DataTableCell> }
|
||||
}
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("Progress").then({
|
||||
let percent = t.percent_complete;
|
||||
move || view! {
|
||||
<DataTableCell>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="h-1.5 w-full bg-secondary rounded-full overflow-hidden min-w-[80px]">
|
||||
<div class="h-full bg-primary transition-all duration-500" style=format!("width: {}%", percent)></div>
|
||||
</div>
|
||||
<span class="text-[10px] text-muted-foreground w-10 text-right">{format!("{:.1}%", percent)}</span>
|
||||
</div>
|
||||
</DataTableCell>
|
||||
}
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("Status").then({
|
||||
let status_text = format!("{:?}", t.status);
|
||||
let color = status_color;
|
||||
move || view! { <DataTableCell class={format!("text-xs font-semibold whitespace-nowrap {}", color)}>{status_text.clone()}</DataTableCell> }
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("DownSpeed").then({
|
||||
let rate = t.down_rate;
|
||||
move || {
|
||||
let speed_str = format_speed(rate);
|
||||
view! { <DataTableCell class="text-right font-mono text-xs text-green-600 dark:text-green-500 whitespace-nowrap">{speed_str}</DataTableCell> }
|
||||
}
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("UpSpeed").then({
|
||||
let rate = t.up_rate;
|
||||
move || {
|
||||
let speed_str = format_speed(rate);
|
||||
view! { <DataTableCell class="text-right font-mono text-xs text-blue-600 dark:text-blue-500 whitespace-nowrap">{speed_str}</DataTableCell> }
|
||||
}
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("ETA").then({
|
||||
let eta = t.eta;
|
||||
move || {
|
||||
let eta_str = format_duration(eta);
|
||||
view! { <DataTableCell class="text-right font-mono text-xs text-muted-foreground whitespace-nowrap">{eta_str}</DataTableCell> }
|
||||
}
|
||||
}).into_any()}
|
||||
|
||||
{move || visible_columns.get().contains("AddedDate").then({
|
||||
let date = t.added_date;
|
||||
move || {
|
||||
let date_str = format_date(date);
|
||||
view! { <DataTableCell class="text-right font-mono text-xs text-muted-foreground whitespace-nowrap">{date_str}</DataTableCell> }
|
||||
}
|
||||
}).into_any()}
|
||||
</DataTableRow>
|
||||
</TorrentContextMenu>
|
||||
}.into_any()
|
||||
@@ -328,6 +660,8 @@ fn TorrentRow(
|
||||
fn TorrentCard(
|
||||
hash: String,
|
||||
on_action: Callback<(String, String)>,
|
||||
is_selected: Signal<bool>,
|
||||
on_select: Callback<bool>,
|
||||
) -> impl IntoView {
|
||||
let store = use_context::<crate::store::TorrentStore>().expect("store not provided");
|
||||
let h = hash.clone();
|
||||
@@ -342,48 +676,73 @@ fn TorrentCard(
|
||||
move || {
|
||||
let t = torrent.get().unwrap();
|
||||
let t_name = t.name.clone();
|
||||
let status_badge_class = match t.status { shared::TorrentStatus::Seeding => "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 border-green-200 dark:border-green-800", shared::TorrentStatus::Downloading => "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 border-blue-200 dark:border-blue-800", shared::TorrentStatus::Paused => "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800", shared::TorrentStatus::Error => "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 border-red-200 dark:border-red-800", _ => "bg-muted text-muted-foreground" };
|
||||
let status_badge_class = match t.status {
|
||||
shared::TorrentStatus::Seeding => "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 border-green-200 dark:border-green-800",
|
||||
shared::TorrentStatus::Downloading => "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 border-blue-200 dark:border-blue-800",
|
||||
shared::TorrentStatus::Paused => "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800",
|
||||
shared::TorrentStatus::Error => "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400 border-red-200 dark:border-red-800",
|
||||
_ => "bg-muted text-muted-foreground"
|
||||
};
|
||||
let h_for_menu = stored_hash.get_value();
|
||||
|
||||
view! {
|
||||
<TorrentContextMenu torrent_hash=h_for_menu on_action=on_action.clone()>
|
||||
<div
|
||||
class=move || {
|
||||
let selected = store.selected_torrent.get();
|
||||
let is_selected = selected.as_deref() == Some(stored_hash.get_value().as_str());
|
||||
if is_selected {
|
||||
"ring-2 ring-primary rounded-lg transition-all"
|
||||
} else {
|
||||
"transition-all"
|
||||
class=move || tw_merge!(
|
||||
"rounded-lg transition-all duration-200 border cursor-pointer select-none overflow-hidden active:scale-[0.98]",
|
||||
if is_selected.get() {
|
||||
"bg-primary/10 border-primary shadow-sm"
|
||||
} else {
|
||||
"bg-card border-border hover:border-primary/50"
|
||||
}
|
||||
)
|
||||
on:click=move |_| {
|
||||
let current = is_selected.get();
|
||||
on_select.run(!current);
|
||||
store.selected_torrent.set(Some(stored_hash.get_value()));
|
||||
}
|
||||
on:click=move |_| store.selected_torrent.set(Some(stored_hash.get_value()))
|
||||
>
|
||||
<Card class="h-full select-none cursor-pointer hover:border-primary transition-colors">
|
||||
<CardHeader class="p-3 pb-0">
|
||||
<div class="flex justify-between items-start gap-2">
|
||||
<CardTitle class="text-sm font-medium leading-tight line-clamp-2">{t_name.clone()}</CardTitle>
|
||||
<div class={format!("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 {}", status_badge_class)}>{format!("{:?}", t.status)}</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody class="p-3 pt-2 gap-3 flex flex-col">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex justify-between text-[10px] text-muted-foreground">
|
||||
<span>{format_bytes(t.size)}</span>
|
||||
<span>{format!("{:.1}%", t.percent_complete)}</span>
|
||||
<div class="p-4 space-y-3">
|
||||
<div class="flex justify-between items-start gap-3">
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="text-sm font-bold leading-tight line-clamp-2 break-all">{t_name.clone()}</h3>
|
||||
</div>
|
||||
<div class="h-1.5 w-full bg-secondary rounded-full overflow-hidden">
|
||||
<div class="h-full bg-primary transition-all duration-500" style=format!("width: {}%", t.percent_complete)></div>
|
||||
<div class={format!("shrink-0 inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider {}", status_badge_class)}>
|
||||
{format!("{:?}", t.status)}
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-4 gap-2 text-[10px] font-mono text-muted-foreground pt-1 border-t border-border/50">
|
||||
<div class="flex flex-col text-blue-600 dark:text-blue-500"><span>"DL"</span><span>{format_speed(t.down_rate)}</span></div>
|
||||
<div class="flex flex-col text-green-600 dark:text-green-500"><span>"UP"</span><span>{format_speed(t.up_rate)}</span></div>
|
||||
<div class="flex flex-col"><span>"ETA"</span><span>{format_duration(t.eta)}</span></div>
|
||||
<div class="flex flex-col text-right"><span>"DATE"</span><span>{format_date(t.added_date)}</span></div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex justify-between text-[10px] font-medium text-muted-foreground">
|
||||
<span class="flex items-center gap-1">
|
||||
<span class="opacity-70">"Boyut:"</span> {format_bytes(t.size)}
|
||||
</span>
|
||||
<span class="font-bold text-primary">{format!("{:.1}%", t.percent_complete)}</span>
|
||||
</div>
|
||||
<div class="h-2 w-full bg-secondary rounded-full overflow-hidden">
|
||||
<div class="h-full bg-primary transition-all duration-500 ease-out" style=format!("width: {}%", t.percent_complete)></div>
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
<div class="grid grid-cols-2 gap-y-2 gap-x-4 text-[10px] font-mono pt-2 border-t border-border/40">
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-muted-foreground uppercase text-[8px] tracking-tighter">"İndirme"</span>
|
||||
<span class="text-blue-600 dark:text-blue-400 font-bold">{format_speed(t.down_rate)}</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-muted-foreground uppercase text-[8px] tracking-tighter">"Gönderme"</span>
|
||||
<span class="text-green-600 dark:text-green-400 font-bold">{format_speed(t.up_rate)}</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-muted-foreground uppercase text-[8px] tracking-tighter">"Kalan Süre"</span>
|
||||
<span class="text-foreground font-medium">{format_duration(t.eta)}</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5 items-end text-right">
|
||||
<span class="text-muted-foreground uppercase text-[8px] tracking-tighter">"Eklenme"</span>
|
||||
<span class="text-foreground/70">{format_date(t.added_date)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</TorrentContextMenu>
|
||||
}.into_any()
|
||||
@@ -391,4 +750,4 @@ fn TorrentCard(
|
||||
}
|
||||
</Show>
|
||||
}.into_any()
|
||||
}
|
||||
}
|
||||
|
||||
39
frontend/src/components/ui/accordion.rs
Normal file
39
frontend/src/components/ui/accordion.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use leptos::prelude::*;
|
||||
use tw_merge::tw_merge;
|
||||
|
||||
#[component]
|
||||
pub fn Accordion(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!("w-full", class);
|
||||
view! { <div class=class>{children()}</div> }
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AccordionItem(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!("border-b", class);
|
||||
view! { <div class=class>{children()}</div> }
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AccordionHeader(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!("flex", class);
|
||||
view! { <div class=class>{children()}</div> }
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AccordionTrigger(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!(
|
||||
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
|
||||
class
|
||||
);
|
||||
view! {
|
||||
<button type="button" class=class>
|
||||
{children()}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AccordionContent(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!("overflow-hidden text-sm transition-all", class);
|
||||
view! { <div class=class>{children()}</div> }
|
||||
}
|
||||
94
frontend/src/components/ui/alert_dialog.rs
Normal file
94
frontend/src/components/ui/alert_dialog.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use leptos::prelude::*;
|
||||
|
||||
use crate::components::ui::button::{ButtonSize, ButtonVariant};
|
||||
use crate::components::ui::dialog::{
|
||||
Dialog, DialogBody, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
|
||||
DialogTrigger,
|
||||
};
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialog(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
view! { <Dialog class=class>{children()}</Dialog> }
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogTrigger(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = ButtonVariant::Outline)] variant: ButtonVariant,
|
||||
#[prop(default = ButtonSize::Default)] size: ButtonSize,
|
||||
) -> impl IntoView {
|
||||
view! {
|
||||
<DialogTrigger class=class variant=variant size=size>
|
||||
{children()}
|
||||
</DialogTrigger>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogContent(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
view! {
|
||||
<DialogContent class=class close_on_backdrop_click=false data_name_prefix="AlertDialog">
|
||||
{children()}
|
||||
</DialogContent>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogBody(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
view! {
|
||||
<DialogBody class=class attr:data-name="AlertDialogBody">
|
||||
{children()}
|
||||
</DialogBody>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogHeader(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
view! {
|
||||
<DialogHeader class=class attr:data-name="AlertDialogHeader">
|
||||
{children()}
|
||||
</DialogHeader>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogTitle(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
view! {
|
||||
<DialogTitle class=class attr:data-name="AlertDialogTitle">
|
||||
{children()}
|
||||
</DialogTitle>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogDescription(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
view! {
|
||||
<DialogDescription class=class attr:data-name="AlertDialogDescription">
|
||||
{children()}
|
||||
</DialogDescription>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogFooter(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
view! {
|
||||
<DialogFooter class=class attr:data-name="AlertDialogFooter">
|
||||
{children()}
|
||||
</DialogFooter>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn AlertDialogClose(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = ButtonVariant::Outline)] variant: ButtonVariant,
|
||||
#[prop(default = ButtonSize::Default)] size: ButtonSize,
|
||||
) -> impl IntoView {
|
||||
view! {
|
||||
<DialogClose class=class variant=variant size=size>
|
||||
{children()}
|
||||
</DialogClose>
|
||||
}
|
||||
}
|
||||
@@ -237,8 +237,6 @@ pub fn ContextMenuContent(
|
||||
let target_id_for_script = ctx.target_id.clone();
|
||||
|
||||
view! {
|
||||
<script src="/lock_scroll.js"></script>
|
||||
|
||||
<div
|
||||
data-name="ContextMenuContent"
|
||||
class=class
|
||||
|
||||
251
frontend/src/components/ui/dialog.rs
Normal file
251
frontend/src/components/ui/dialog.rs
Normal file
@@ -0,0 +1,251 @@
|
||||
use icons::X;
|
||||
use leptos::context::Provider;
|
||||
use leptos::prelude::*;
|
||||
use leptos_ui::clx;
|
||||
use tw_merge::*;
|
||||
|
||||
use crate::components::hooks::use_random::use_random_id_for;
|
||||
use crate::components::ui::button::{Button, ButtonSize, ButtonVariant};
|
||||
|
||||
mod components {
|
||||
use super::*;
|
||||
clx! {DialogBody, div, "flex flex-col gap-4"}
|
||||
clx! {DialogHeader, div, "flex flex-col gap-2 text-center sm:text-left"}
|
||||
clx! {DialogTitle, h3, "text-lg leading-none font-semibold"}
|
||||
clx! {DialogDescription, p, "text-muted-foreground text-sm"}
|
||||
clx! {DialogFooter, footer, "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end"}
|
||||
}
|
||||
|
||||
pub use components::*;
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DialogContext {
|
||||
target_id: String,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Dialog(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let dialog_target_id = use_random_id_for("dialog");
|
||||
|
||||
let ctx = DialogContext { target_id: dialog_target_id.clone() };
|
||||
|
||||
let merged_class = tw_merge!("w-fit", class);
|
||||
|
||||
view! {
|
||||
<Provider value=ctx>
|
||||
<div class=merged_class data-name="__Dialog">
|
||||
{children()}
|
||||
</div>
|
||||
</Provider>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DialogTrigger(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = ButtonVariant::Outline)] variant: ButtonVariant,
|
||||
#[prop(default = ButtonSize::Default)] size: ButtonSize,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<DialogContext>();
|
||||
let trigger_id = format!("trigger_{}", ctx.target_id);
|
||||
|
||||
view! {
|
||||
<Button
|
||||
class=class
|
||||
attr:id=trigger_id
|
||||
attr:tabindex="0"
|
||||
attr:data-dialog-trigger=ctx.target_id
|
||||
variant=variant
|
||||
size=size
|
||||
>
|
||||
{children()}
|
||||
</Button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DialogContent(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(into, optional)] hide_close_button: Option<bool>,
|
||||
#[prop(default = true)] close_on_backdrop_click: bool,
|
||||
#[prop(default = "Dialog")] data_name_prefix: &'static str,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<DialogContext>();
|
||||
let merged_class = tw_merge!(
|
||||
// "flex flex-col gap-4", // TODO 🐛 Bug when I try to have this.. Using DialogBody instead.
|
||||
"relative bg-background border rounded-2xl shadow-lg p-6 w-full max-w-[calc(100%-2rem)] max-h-[85vh] fixed top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%] z-100 transition-all duration-200 data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100",
|
||||
class
|
||||
);
|
||||
|
||||
let backdrop_data_name = format!("{}Backdrop", data_name_prefix);
|
||||
let content_data_name = format!("{}Content", data_name_prefix);
|
||||
|
||||
let target_id_clone = ctx.target_id.clone();
|
||||
let backdrop_id = format!("{}_backdrop", ctx.target_id);
|
||||
let target_id_for_script = ctx.target_id.clone();
|
||||
let backdrop_id_for_script = backdrop_id.clone();
|
||||
let backdrop_behavior = if close_on_backdrop_click { "auto" } else { "manual" };
|
||||
|
||||
view! {
|
||||
<script src="/hooks/lock_scroll.js"></script>
|
||||
|
||||
<div
|
||||
data-name=backdrop_data_name
|
||||
id=backdrop_id
|
||||
class="fixed inset-0 transition-opacity duration-200 pointer-events-none z-60 bg-black/50 data-[state=closed]:opacity-0 data-[state=open]:opacity-100"
|
||||
data-state="closed"
|
||||
/>
|
||||
|
||||
<div
|
||||
data-name=content_data_name
|
||||
class=merged_class
|
||||
id=ctx.target_id
|
||||
data-target="target__dialog"
|
||||
data-state="closed"
|
||||
data-backdrop=backdrop_behavior
|
||||
style="pointer-events: none;"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class=format!(
|
||||
"absolute top-4 right-4 p-1 rounded-sm focus:ring-2 focus:ring-offset-2 focus:outline-none [&_svg:not([class*='size-'])]:size-4 focus:ring-ring{}",
|
||||
if hide_close_button.unwrap_or(false) { " hidden" } else { "" },
|
||||
)
|
||||
data-dialog-close=target_id_clone.clone()
|
||||
aria-label="Close dialog"
|
||||
>
|
||||
<span class="hidden">"Close Dialog"</span>
|
||||
<X />
|
||||
</button>
|
||||
|
||||
{children()}
|
||||
</div>
|
||||
|
||||
<script>
|
||||
{format!(
|
||||
r#"
|
||||
(function() {{
|
||||
const setupDialog = () => {{
|
||||
const dialog = document.querySelector('#{}');
|
||||
const backdrop = document.querySelector('#{}');
|
||||
const trigger = document.querySelector('[data-dialog-trigger="{}"]');
|
||||
|
||||
if (!dialog || !backdrop || !trigger) {{
|
||||
setTimeout(setupDialog, 50);
|
||||
return;
|
||||
}}
|
||||
|
||||
if (dialog.hasAttribute('data-initialized')) {{
|
||||
return;
|
||||
}}
|
||||
dialog.setAttribute('data-initialized', 'true');
|
||||
|
||||
const openDialog = () => {{
|
||||
// Lock scrolling
|
||||
window.ScrollLock.lock();
|
||||
|
||||
dialog.setAttribute('data-state', 'open');
|
||||
backdrop.setAttribute('data-state', 'open');
|
||||
dialog.style.pointerEvents = 'auto';
|
||||
backdrop.style.pointerEvents = 'auto';
|
||||
}};
|
||||
|
||||
const closeDialog = () => {{
|
||||
dialog.setAttribute('data-state', 'closed');
|
||||
backdrop.setAttribute('data-state', 'closed');
|
||||
dialog.style.pointerEvents = 'none';
|
||||
backdrop.style.pointerEvents = 'none';
|
||||
|
||||
// Unlock scrolling after animation
|
||||
window.ScrollLock.unlock(200);
|
||||
}};
|
||||
|
||||
// Open dialog when trigger is clicked
|
||||
trigger.addEventListener('click', openDialog);
|
||||
|
||||
// Close buttons
|
||||
const closeButtons = dialog.querySelectorAll('[data-dialog-close]');
|
||||
closeButtons.forEach(btn => {{
|
||||
btn.addEventListener('click', closeDialog);
|
||||
}});
|
||||
|
||||
// Close on backdrop click (if data-backdrop="auto")
|
||||
backdrop.addEventListener('click', () => {{
|
||||
if (dialog.getAttribute('data-backdrop') === 'auto') {{
|
||||
closeDialog();
|
||||
}}
|
||||
}});
|
||||
|
||||
// Handle ESC key to close
|
||||
document.addEventListener('keydown', (e) => {{
|
||||
if (e.key === 'Escape' && dialog.getAttribute('data-state') === 'open') {{
|
||||
e.preventDefault();
|
||||
closeDialog();
|
||||
}}
|
||||
}});
|
||||
}};
|
||||
|
||||
if (document.readyState === 'loading') {{
|
||||
document.addEventListener('DOMContentLoaded', setupDialog);
|
||||
}} else {{
|
||||
setupDialog();
|
||||
}}
|
||||
}})();
|
||||
"#,
|
||||
target_id_for_script,
|
||||
backdrop_id_for_script,
|
||||
target_id_for_script,
|
||||
)}
|
||||
</script>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DialogClose(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = ButtonVariant::Outline)] variant: ButtonVariant,
|
||||
#[prop(default = ButtonSize::Default)] size: ButtonSize,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<DialogContext>();
|
||||
|
||||
view! {
|
||||
<Button
|
||||
class=class
|
||||
attr:data-dialog-close=ctx.target_id
|
||||
attr:aria-label="Close dialog"
|
||||
variant=variant
|
||||
size=size
|
||||
>
|
||||
{children()}
|
||||
</Button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DialogAction(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = ButtonVariant::Default)] variant: ButtonVariant,
|
||||
#[prop(default = ButtonSize::Default)] size: ButtonSize,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<DialogContext>();
|
||||
|
||||
view! {
|
||||
<Button
|
||||
class=class
|
||||
attr:data-dialog-close=ctx.target_id
|
||||
attr:aria-label="Close dialog"
|
||||
variant=variant
|
||||
size=size
|
||||
>
|
||||
{children()}
|
||||
</Button>
|
||||
}
|
||||
}
|
||||
25
frontend/src/components/ui/drag_and_drop.rs
Normal file
25
frontend/src/components/ui/drag_and_drop.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_ui::clx;
|
||||
|
||||
mod components {
|
||||
use super::*;
|
||||
clx! {Draggable, div, "flex flex-col gap-4 w-full max-w-4xl"}
|
||||
clx! {DraggableZone, div, "dragabble__container", "bg-neutral-600 p-4 mt-4"}
|
||||
|
||||
// TODO. ItemRoot (needs `draggable` as clx attribute).
|
||||
}
|
||||
|
||||
pub use components::*;
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[component]
|
||||
pub fn DraggableItem(#[prop(into)] text: String) -> impl IntoView {
|
||||
view! {
|
||||
<div class="p-4 border cursor-move border-input bg-card draggable" draggable="true">
|
||||
{text}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
536
frontend/src/components/ui/dropdown_menu.rs
Normal file
536
frontend/src/components/ui/dropdown_menu.rs
Normal file
@@ -0,0 +1,536 @@
|
||||
use icons::{Check, ChevronRight};
|
||||
use leptos::context::Provider;
|
||||
use leptos::prelude::*;
|
||||
use leptos_ui::clx;
|
||||
use tw_merge::*;
|
||||
|
||||
use crate::components::hooks::use_random::use_random_id_for;
|
||||
pub use crate::components::ui::separator::Separator as DropdownMenuSeparator;
|
||||
|
||||
mod components {
|
||||
use super::*;
|
||||
clx! {DropdownMenuLabel, span, "px-2 py-1.5 text-sm font-medium data-inset:pl-8", "mb-1"}
|
||||
clx! {DropdownMenuGroup, ul, "group"}
|
||||
clx! {DropdownMenuItem, li, "inline-flex gap-2 items-center w-full rounded-sm px-2 py-1.5 text-sm no-underline transition-colors duration-200 text-popover-foreground hover:bg-accent hover:text-accent-foreground [&_svg:not([class*='size-'])]:size-4"}
|
||||
clx! {DropdownMenuSubContent, ul, "dropdown__menu_sub_content", "rounded-md border bg-card shadow-lg p-1 absolute z-[100] min-w-[160px] opacity-0 invisible translate-x-[-8px] transition-all duration-200 ease-out pointer-events-none"}
|
||||
clx! {DropdownMenuLink, a, "w-full inline-flex gap-2 items-center"}
|
||||
}
|
||||
|
||||
pub use components::*;
|
||||
|
||||
/* ========================================================== */
|
||||
/* RADIO GROUP */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DropdownMenuRadioContext<T: Clone + PartialEq + Send + Sync + 'static> {
|
||||
value_signal: RwSignal<T>,
|
||||
}
|
||||
|
||||
/// A group of radio items where only one can be selected at a time.
|
||||
#[component]
|
||||
pub fn DropdownMenuRadioGroup<T>(
|
||||
children: Children,
|
||||
/// The signal holding the current selected value
|
||||
value: RwSignal<T>,
|
||||
) -> impl IntoView
|
||||
where
|
||||
T: Clone + PartialEq + Send + Sync + 'static,
|
||||
{
|
||||
let ctx = DropdownMenuRadioContext { value_signal: value };
|
||||
|
||||
view! {
|
||||
<Provider value=ctx>
|
||||
<ul data-name="DropdownMenuRadioGroup" role="group" class="group">
|
||||
{children()}
|
||||
</ul>
|
||||
</Provider>
|
||||
}
|
||||
}
|
||||
|
||||
/// A radio item that shows a checkmark when selected.
|
||||
#[component]
|
||||
pub fn DropdownMenuRadioItem<T>(
|
||||
children: Children,
|
||||
/// The value this item represents
|
||||
value: T,
|
||||
#[prop(optional, into)] class: String,
|
||||
) -> impl IntoView
|
||||
where
|
||||
T: Clone + PartialEq + Send + Sync + 'static,
|
||||
{
|
||||
let ctx = expect_context::<DropdownMenuRadioContext<T>>();
|
||||
|
||||
let value_for_check = value.clone();
|
||||
let value_for_click = value.clone();
|
||||
let is_selected = move || ctx.value_signal.get() == value_for_check;
|
||||
|
||||
let merged_class = tw_merge!(
|
||||
"group inline-flex gap-2 items-center w-full rounded-sm pl-2 pr-2 py-1.5 text-sm cursor-pointer no-underline transition-colors duration-200 text-popover-foreground hover:bg-accent hover:text-accent-foreground [&_svg:not([class*='size-'])]:size-4",
|
||||
class
|
||||
);
|
||||
|
||||
view! {
|
||||
<li
|
||||
data-name="DropdownMenuRadioItem"
|
||||
class=merged_class
|
||||
role="menuitemradio"
|
||||
aria-checked=move || is_selected().to_string()
|
||||
data-dropdown-close="true"
|
||||
on:click=move |_| {
|
||||
ctx.value_signal.set(value_for_click.clone());
|
||||
}
|
||||
>
|
||||
{children()}
|
||||
<Check class="ml-auto opacity-0 size-4 text-muted-foreground group-aria-checked:opacity-100" />
|
||||
</li>
|
||||
}
|
||||
}
|
||||
|
||||
/// An action item in a dropdown menu (no checkmark, just triggers an action).
|
||||
#[component]
|
||||
pub fn DropdownMenuAction(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(optional, into)] href: Option<String>,
|
||||
) -> impl IntoView {
|
||||
let _ctx = expect_context::<DropdownMenuContext>();
|
||||
|
||||
let class = tw_merge!(
|
||||
"inline-flex gap-2 items-center w-full text-sm text-left transition-colors duration-200 focus:outline-none focus-visible:outline-none text-popover-foreground [&_svg:not([class*='size-'])]:size-4 hover:bg-accent hover:text-accent-foreground",
|
||||
class
|
||||
);
|
||||
|
||||
if let Some(href) = href {
|
||||
// Render as <a> tag when href is provided
|
||||
view! {
|
||||
<a data-name="DropdownMenuAction" class=class href=href data-dropdown-close="true">
|
||||
{children()}
|
||||
</a>
|
||||
|
||||
<script>
|
||||
{r#"
|
||||
(function() {
|
||||
const link = document.currentScript.previousElementSibling;
|
||||
if (!link) return;
|
||||
|
||||
link.addEventListener('click', function() {
|
||||
// Close dropdown on route change after navigation
|
||||
let currentPath = window.location.pathname;
|
||||
const checkRouteChange = () => {
|
||||
if (window.location.pathname !== currentPath) {
|
||||
currentPath = window.location.pathname;
|
||||
|
||||
// Find and close the dropdown
|
||||
const dropdown = link.closest('[data-target="target__dropdown"]');
|
||||
if (dropdown) {
|
||||
dropdown.setAttribute('data-state', 'closed');
|
||||
dropdown.style.pointerEvents = 'none';
|
||||
|
||||
// Unlock scroll
|
||||
if (window.ScrollLock) {
|
||||
window.ScrollLock.unlock(200);
|
||||
}
|
||||
}
|
||||
|
||||
clearInterval(routeCheckInterval);
|
||||
}
|
||||
};
|
||||
|
||||
const routeCheckInterval = setInterval(checkRouteChange, 50);
|
||||
|
||||
// Clear interval after 2 seconds to prevent memory leaks
|
||||
setTimeout(() => clearInterval(routeCheckInterval), 2000);
|
||||
});
|
||||
})();
|
||||
"#}
|
||||
</script>
|
||||
}
|
||||
.into_any()
|
||||
} else {
|
||||
// Render as <button> tag when no href
|
||||
view! {
|
||||
<button type="button" data-name="DropdownMenuAction" class=class data-dropdown-close="true">
|
||||
{children()}
|
||||
</button>
|
||||
}
|
||||
.into_any()
|
||||
}
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum DropdownMenuAlign {
|
||||
#[default]
|
||||
Start,
|
||||
StartOuter,
|
||||
End,
|
||||
EndOuter,
|
||||
Center,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DropdownMenuContext {
|
||||
target_id: String,
|
||||
align: DropdownMenuAlign,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DropdownMenu(
|
||||
children: Children,
|
||||
#[prop(default = DropdownMenuAlign::default())] align: DropdownMenuAlign,
|
||||
) -> impl IntoView {
|
||||
let dropdown_target_id = use_random_id_for("dropdown");
|
||||
|
||||
let ctx = DropdownMenuContext { target_id: dropdown_target_id.clone(), align };
|
||||
|
||||
view! {
|
||||
<Provider value=ctx>
|
||||
<style>
|
||||
"
|
||||
/* Submenu Styles */
|
||||
.dropdown__menu_sub_content {
|
||||
position: absolute;
|
||||
inset-inline-start: calc(100% + 8px);
|
||||
inset-block-start: -4px;
|
||||
z-index: 100;
|
||||
min-inline-size: 160px;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateX(-8px);
|
||||
transition: all 0.2s ease-out;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.dropdown__menu_sub_trigger:hover .dropdown__menu_sub_content {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateX(0);
|
||||
pointer-events: auto;
|
||||
}
|
||||
"
|
||||
</style>
|
||||
|
||||
<div data-name="DropdownMenu">{children()}</div>
|
||||
</Provider>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DropdownMenuTrigger(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let ctx = expect_context::<DropdownMenuContext>();
|
||||
let button_class = tw_merge!(
|
||||
"px-4 py-2 h-9 inline-flex justify-center items-center text-sm font-medium whitespace-nowrap rounded-md transition-colors w-fit focus:outline-none focus:ring-1 focus:ring-ring focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&_svg:not([class*='size-'])]:size-4 border bg-background border-input hover:bg-accent hover:text-accent-foreground",
|
||||
class
|
||||
);
|
||||
|
||||
view! {
|
||||
<button
|
||||
type="button"
|
||||
class=button_class
|
||||
data-name="DropdownMenuTrigger"
|
||||
data-dropdown-trigger=ctx.target_id
|
||||
tabindex="0"
|
||||
>
|
||||
{children()}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum DropdownMenuPosition {
|
||||
#[default]
|
||||
Auto,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DropdownMenuContent(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = DropdownMenuPosition::default())] position: DropdownMenuPosition,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<DropdownMenuContext>();
|
||||
|
||||
let base_classes = "z-50 p-1 rounded-md border bg-card shadow-md h-fit fixed transition-all duration-200 data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100";
|
||||
let width_class = match ctx.align {
|
||||
DropdownMenuAlign::Center => "min-w-full",
|
||||
_ => "w-[180px]",
|
||||
};
|
||||
|
||||
let class = tw_merge!(width_class, base_classes, class);
|
||||
|
||||
let target_id_for_script = ctx.target_id.clone();
|
||||
let align_for_script = match ctx.align {
|
||||
DropdownMenuAlign::Start => "start",
|
||||
DropdownMenuAlign::StartOuter => "start-outer",
|
||||
DropdownMenuAlign::End => "end",
|
||||
DropdownMenuAlign::EndOuter => "end-outer",
|
||||
DropdownMenuAlign::Center => "center",
|
||||
};
|
||||
|
||||
let position_for_script = match position {
|
||||
DropdownMenuPosition::Auto => "auto",
|
||||
DropdownMenuPosition::Top => "top",
|
||||
DropdownMenuPosition::Bottom => "bottom",
|
||||
};
|
||||
|
||||
view! {
|
||||
<div
|
||||
data-name="DropdownMenuContent"
|
||||
class=class
|
||||
id=ctx.target_id
|
||||
data-target="target__dropdown"
|
||||
data-state="closed"
|
||||
data-align=align_for_script
|
||||
data-position=position_for_script
|
||||
style="pointer-events: none;"
|
||||
>
|
||||
{children()}
|
||||
</div>
|
||||
|
||||
<script>
|
||||
{format!(
|
||||
r#"
|
||||
(function() {{
|
||||
const setupDropdown = () => {{
|
||||
const dropdown = document.querySelector('#{}');
|
||||
const trigger = document.querySelector('[data-dropdown-trigger="{}"]');
|
||||
|
||||
if (!dropdown || !trigger) {{
|
||||
setTimeout(setupDropdown, 50);
|
||||
return;
|
||||
}}
|
||||
|
||||
if (dropdown.hasAttribute('data-initialized')) {{
|
||||
return;
|
||||
}}
|
||||
dropdown.setAttribute('data-initialized', 'true');
|
||||
|
||||
let isOpen = false;
|
||||
|
||||
const updatePosition = () => {{
|
||||
const triggerRect = trigger.getBoundingClientRect();
|
||||
const dropdownRect = dropdown.getBoundingClientRect();
|
||||
const viewportHeight = window.innerHeight;
|
||||
const viewportWidth = window.innerWidth;
|
||||
const spaceBelow = viewportHeight - triggerRect.bottom;
|
||||
const spaceAbove = triggerRect.top;
|
||||
|
||||
const align = dropdown.getAttribute('data-align') || 'start';
|
||||
const position = dropdown.getAttribute('data-position') || 'auto';
|
||||
|
||||
// Determine if we should position above
|
||||
let shouldPositionAbove = false;
|
||||
if (position === 'top') {{
|
||||
shouldPositionAbove = true;
|
||||
}} else if (position === 'bottom') {{
|
||||
shouldPositionAbove = false;
|
||||
}} else {{
|
||||
// Auto: position above if there's space above AND not enough space below
|
||||
shouldPositionAbove = spaceAbove >= dropdownRect.height && spaceBelow < dropdownRect.height;
|
||||
}}
|
||||
|
||||
switch (align) {{
|
||||
case 'start':
|
||||
if (shouldPositionAbove) {{
|
||||
dropdown.style.top = `${{triggerRect.top - dropdownRect.height - 6}}px`;
|
||||
dropdown.style.transformOrigin = 'left bottom';
|
||||
}} else {{
|
||||
dropdown.style.top = `${{triggerRect.bottom + 6}}px`;
|
||||
dropdown.style.transformOrigin = 'left top';
|
||||
}}
|
||||
dropdown.style.left = `${{triggerRect.left}}px`;
|
||||
break;
|
||||
|
||||
case 'end':
|
||||
if (shouldPositionAbove) {{
|
||||
dropdown.style.top = `${{triggerRect.top - dropdownRect.height - 6}}px`;
|
||||
dropdown.style.transformOrigin = 'right bottom';
|
||||
}} else {{
|
||||
dropdown.style.top = `${{triggerRect.bottom + 6}}px`;
|
||||
dropdown.style.transformOrigin = 'right top';
|
||||
}}
|
||||
dropdown.style.left = `${{triggerRect.right - dropdownRect.width}}px`;
|
||||
break;
|
||||
|
||||
case 'start-outer':
|
||||
if (shouldPositionAbove) {{
|
||||
dropdown.style.top = `${{triggerRect.top - dropdownRect.height - 6}}px`;
|
||||
dropdown.style.transformOrigin = 'right bottom';
|
||||
}} else {{
|
||||
dropdown.style.top = `${{triggerRect.top}}px`;
|
||||
dropdown.style.transformOrigin = 'right top';
|
||||
}}
|
||||
dropdown.style.left = `${{triggerRect.left - dropdownRect.width - 16}}px`;
|
||||
break;
|
||||
|
||||
case 'end-outer':
|
||||
if (shouldPositionAbove) {{
|
||||
dropdown.style.top = `${{triggerRect.top - dropdownRect.height - 6}}px`;
|
||||
dropdown.style.transformOrigin = 'left bottom';
|
||||
}} else {{
|
||||
dropdown.style.top = `${{triggerRect.top}}px`;
|
||||
dropdown.style.transformOrigin = 'left top';
|
||||
}}
|
||||
dropdown.style.left = `${{triggerRect.right + 8}}px`;
|
||||
break;
|
||||
|
||||
case 'center':
|
||||
if (shouldPositionAbove) {{
|
||||
dropdown.style.top = `${{triggerRect.top - dropdownRect.height - 6}}px`;
|
||||
dropdown.style.transformOrigin = 'center bottom';
|
||||
}} else {{
|
||||
dropdown.style.top = `${{triggerRect.bottom + 6}}px`;
|
||||
dropdown.style.transformOrigin = 'center top';
|
||||
}}
|
||||
dropdown.style.left = `${{triggerRect.left}}px`;
|
||||
dropdown.style.minWidth = `${{triggerRect.width}}px`;
|
||||
break;
|
||||
}}
|
||||
}};
|
||||
|
||||
const openDropdown = () => {{
|
||||
isOpen = true;
|
||||
|
||||
// Set state to open first to remove scale transform for accurate measurements
|
||||
dropdown.setAttribute('data-state', 'open');
|
||||
|
||||
// Make dropdown invisible but rendered to measure true height
|
||||
dropdown.style.visibility = 'hidden';
|
||||
dropdown.style.pointerEvents = 'auto';
|
||||
|
||||
// Force reflow to ensure height is calculated
|
||||
dropdown.offsetHeight;
|
||||
|
||||
// Calculate position with accurate height
|
||||
updatePosition();
|
||||
|
||||
// Now make it visible
|
||||
dropdown.style.visibility = 'visible';
|
||||
|
||||
// Lock all scrollable elements
|
||||
window.ScrollLock.lock();
|
||||
|
||||
// Close on click outside
|
||||
setTimeout(() => {{
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
}}, 0);
|
||||
}};
|
||||
|
||||
const closeDropdown = () => {{
|
||||
isOpen = false;
|
||||
dropdown.setAttribute('data-state', 'closed');
|
||||
dropdown.style.pointerEvents = 'none';
|
||||
document.removeEventListener('click', handleClickOutside);
|
||||
|
||||
// Unlock scroll after animation (200ms delay)
|
||||
window.ScrollLock.unlock(200);
|
||||
}};
|
||||
|
||||
const handleClickOutside = (e) => {{
|
||||
if (!dropdown.contains(e.target) && !trigger.contains(e.target)) {{
|
||||
closeDropdown();
|
||||
}}
|
||||
}};
|
||||
|
||||
// Toggle dropdown when trigger is clicked
|
||||
trigger.addEventListener('click', (e) => {{
|
||||
e.stopPropagation();
|
||||
|
||||
// Check if any other dropdown is open
|
||||
const allDropdowns = document.querySelectorAll('[data-target=\"target__dropdown\"]');
|
||||
let otherDropdownOpen = false;
|
||||
allDropdowns.forEach(dd => {{
|
||||
if (dd !== dropdown && dd.getAttribute('data-state') === 'open') {{
|
||||
otherDropdownOpen = true;
|
||||
dd.setAttribute('data-state', 'closed');
|
||||
dd.style.pointerEvents = 'none';
|
||||
// Unlock scroll
|
||||
if (window.ScrollLock) {{
|
||||
window.ScrollLock.unlock(200);
|
||||
}}
|
||||
}}
|
||||
}});
|
||||
|
||||
// If another dropdown was open, just close it and don't open this one
|
||||
if (otherDropdownOpen) {{
|
||||
return;
|
||||
}}
|
||||
|
||||
// Normal toggle behavior
|
||||
if (isOpen) {{
|
||||
closeDropdown();
|
||||
}} else {{
|
||||
openDropdown();
|
||||
}}
|
||||
}});
|
||||
|
||||
// Close when action is clicked
|
||||
const actions = dropdown.querySelectorAll('[data-dropdown-close]');
|
||||
actions.forEach(action => {{
|
||||
action.addEventListener('click', () => {{
|
||||
closeDropdown();
|
||||
}});
|
||||
}});
|
||||
|
||||
// Handle ESC key to close
|
||||
document.addEventListener('keydown', (e) => {{
|
||||
if (e.key === 'Escape' && isOpen) {{
|
||||
e.preventDefault();
|
||||
closeDropdown();
|
||||
}}
|
||||
}});
|
||||
}};
|
||||
|
||||
if (document.readyState === 'loading') {{
|
||||
document.addEventListener('DOMContentLoaded', setupDropdown);
|
||||
}} else {{
|
||||
setupDropdown();
|
||||
}}
|
||||
}})();
|
||||
"#,
|
||||
target_id_for_script,
|
||||
target_id_for_script,
|
||||
)}
|
||||
</script>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DropdownMenuSub(children: Children) -> impl IntoView {
|
||||
// TODO. Find a better way for dropdown__menu_sub_trigger.
|
||||
clx! {DropdownMenuSubRoot, li, "dropdown__menu_sub_trigger", " relative inline-flex relative gap-2 items-center py-1.5 px-2 w-full text-sm no-underline rounded-sm transition-colors duration-200 cursor-pointer text-popover-foreground [&_svg:not([class*='size-'])]:size-4 hover:bg-accent hover:text-accent-foreground"}
|
||||
|
||||
view! { <DropdownMenuSubRoot>{children()}</DropdownMenuSubRoot> }
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DropdownMenuSubTrigger(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!("flex items-center justify-between w-full", class);
|
||||
|
||||
view! {
|
||||
<span attr:data-name="DropdownMenuSubTrigger" class=class>
|
||||
<span class="flex gap-2 items-center">{children()}</span>
|
||||
<ChevronRight class="opacity-70 size-4" />
|
||||
</span>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn DropdownMenuSubItem(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!(
|
||||
"inline-flex gap-2 items-center w-full rounded-sm px-3 py-2 text-sm transition-all duration-150 ease text-popover-foreground hover:bg-accent hover:text-accent-foreground cursor-pointer hover:translate-x-[2px]",
|
||||
class
|
||||
);
|
||||
|
||||
view! {
|
||||
<li data-name="DropdownMenuSubItem" class=class data-dropdown-close="true">
|
||||
{children()}
|
||||
</li>
|
||||
}
|
||||
}
|
||||
35
frontend/src/components/ui/empty.rs
Normal file
35
frontend/src/components/ui/empty.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_ui::{clx, variants};
|
||||
|
||||
mod components {
|
||||
use super::*;
|
||||
clx! {Empty, div, "flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed p-8 text-center"}
|
||||
clx! {EmptyHeader, div, "flex flex-col items-center gap-2"}
|
||||
clx! {EmptyTitle, h3, "text-lg font-semibold leading-none"}
|
||||
clx! {EmptyDescription, p, "text-muted-foreground text-sm"}
|
||||
clx! {EmptyContent, div, "flex items-center justify-center gap-2"}
|
||||
}
|
||||
|
||||
pub use components::*;
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
variants! {
|
||||
EmptyMedia {
|
||||
base: "flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
variants: {
|
||||
variant: {
|
||||
Default: "bg-transparent",
|
||||
Icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
|
||||
},
|
||||
size: {
|
||||
Default: "",
|
||||
}
|
||||
},
|
||||
component: {
|
||||
element: div
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,21 @@
|
||||
pub mod accordion;
|
||||
pub mod alert_dialog;
|
||||
pub mod button;
|
||||
pub mod card;
|
||||
pub mod input;
|
||||
pub mod toast;
|
||||
pub mod checkbox;
|
||||
pub mod context_menu;
|
||||
pub mod theme_toggle;
|
||||
pub mod data_table;
|
||||
pub mod dialog;
|
||||
pub mod dropdown_menu;
|
||||
pub mod empty;
|
||||
pub mod input;
|
||||
pub mod multi_select;
|
||||
pub mod select;
|
||||
pub mod separator;
|
||||
pub mod sheet;
|
||||
pub mod sidenav;
|
||||
pub mod skeleton;
|
||||
pub mod svg_icon;
|
||||
pub mod table;
|
||||
pub mod data_table;pub mod checkbox;
|
||||
pub mod theme_toggle;
|
||||
pub mod toast;
|
||||
294
frontend/src/components/ui/multi_select.rs
Normal file
294
frontend/src/components/ui/multi_select.rs
Normal file
@@ -0,0 +1,294 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use icons::{Check, ChevronDown, ChevronUp};
|
||||
use leptos::context::Provider;
|
||||
use leptos::prelude::*;
|
||||
use tw_merge::*;
|
||||
|
||||
use crate::components::hooks::use_can_scroll_vertical::use_can_scroll_vertical;
|
||||
use crate::components::hooks::use_random::use_random_id_for;
|
||||
// * Reuse @select.rs
|
||||
pub use crate::components::ui::select::{
|
||||
SelectGroup as MultiSelectGroup, SelectItem as MultiSelectItem, SelectLabel as MultiSelectLabel,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum MultiSelectAlign {
|
||||
Start,
|
||||
#[default]
|
||||
Center,
|
||||
End,
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[component]
|
||||
pub fn MultiSelectValue(#[prop(optional, into)] placeholder: String) -> impl IntoView {
|
||||
let multi_select_ctx = expect_context::<MultiSelectContext>();
|
||||
|
||||
view! {
|
||||
<span data-name="MultiSelectValue" class="text-sm text-muted-foreground truncate">
|
||||
{move || {
|
||||
let values = multi_select_ctx.values_signal.get();
|
||||
if values.is_empty() {
|
||||
placeholder.clone()
|
||||
} else {
|
||||
let count = values.len();
|
||||
if count == 1 { "1 selected".to_string() } else { format!("{} selected", count) }
|
||||
}
|
||||
}}
|
||||
</span>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn MultiSelectOption(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(optional, into)] value: Option<String>,
|
||||
) -> impl IntoView {
|
||||
let multi_select_ctx = expect_context::<MultiSelectContext>();
|
||||
|
||||
let value_clone = value.clone();
|
||||
let is_selected = Signal::derive(move || {
|
||||
if let Some(ref val) = value_clone {
|
||||
multi_select_ctx.values_signal.with(|values| values.contains(val))
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
let class = tw_merge!(
|
||||
"group inline-flex gap-2 items-center w-full text-sm text-left transition-colors duration-200 focus:outline-none focus-visible:outline-none text-popover-foreground [&_svg:not([class*='size-'])]:size-4 hover:bg-accent hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
||||
class
|
||||
);
|
||||
|
||||
view! {
|
||||
<button
|
||||
type="button"
|
||||
data-name="MultiSelectOption"
|
||||
class=class
|
||||
role="option"
|
||||
aria-selected=move || is_selected.get().to_string()
|
||||
on:click=move |ev: web_sys::MouseEvent| {
|
||||
ev.prevent_default();
|
||||
ev.stop_propagation();
|
||||
if let Some(val) = value.clone() {
|
||||
multi_select_ctx
|
||||
.values_signal
|
||||
.update(|values| {
|
||||
if values.contains(&val) {
|
||||
values.remove(&val);
|
||||
} else {
|
||||
values.insert(val);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
>
|
||||
{children()}
|
||||
<Check class="ml-auto opacity-0 size-4 text-muted-foreground group-aria-selected:opacity-100" />
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MultiSelectContext {
|
||||
target_id: String,
|
||||
values_signal: RwSignal<HashSet<String>>,
|
||||
align: MultiSelectAlign,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn MultiSelect(
|
||||
children: Children,
|
||||
#[prop(optional, into)] values: Option<RwSignal<HashSet<String>>>,
|
||||
#[prop(default = MultiSelectAlign::default())] align: MultiSelectAlign,
|
||||
) -> impl IntoView {
|
||||
let multi_select_target_id = use_random_id_for("multi_select");
|
||||
let values_signal = values.unwrap_or_else(|| RwSignal::new(HashSet::<String>::new()));
|
||||
|
||||
let multi_select_ctx = MultiSelectContext { target_id: multi_select_target_id.clone(), values_signal, align };
|
||||
|
||||
view! {
|
||||
<Provider value=multi_select_ctx>
|
||||
<div data-name="MultiSelect" class="relative w-fit">
|
||||
{children()}
|
||||
</div>
|
||||
</Provider>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn MultiSelectTrigger(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(optional, into)] id: String,
|
||||
) -> impl IntoView {
|
||||
let multi_select_ctx = expect_context::<MultiSelectContext>();
|
||||
|
||||
let peer_class = if !id.is_empty() { format!("peer/{}", id) } else { String::new() };
|
||||
|
||||
let button_class = tw_merge!(
|
||||
"w-full p-2 h-9 inline-flex items-center justify-between text-sm font-medium whitespace-nowrap rounded-md transition-colors focus:outline-none focus:ring-1 focus:ring-ring focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&_svg:not(:last-child)]:mr-2 [&_svg:not(:first-child)]:ml-2 [&_svg:not([class*='size-'])]:size-4 border bg-background border-input hover:bg-accent hover:text-accent-foreground",
|
||||
&peer_class,
|
||||
class
|
||||
);
|
||||
|
||||
let button_id = if !id.is_empty() { id } else { format!("trigger_{}", multi_select_ctx.target_id) };
|
||||
|
||||
view! {
|
||||
<button
|
||||
type="button"
|
||||
data-name="MultiSelectTrigger"
|
||||
class=button_class
|
||||
id=button_id
|
||||
tabindex="0"
|
||||
data-multi-select-trigger=multi_select_ctx.target_id
|
||||
>
|
||||
{children()}
|
||||
<ChevronDown class="text-muted-foreground" />
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn MultiSelectContent(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let multi_select_ctx = expect_context::<MultiSelectContext>();
|
||||
|
||||
let align_str = match multi_select_ctx.align {
|
||||
MultiSelectAlign::Start => "start",
|
||||
MultiSelectAlign::Center => "center",
|
||||
MultiSelectAlign::End => "end",
|
||||
};
|
||||
|
||||
let class = tw_merge!(
|
||||
"w-[150px] overflow-auto z-50 p-1 rounded-md border bg-card shadow-md h-fit max-h-[300px] absolute top-[calc(100%+4px)] transition-all duration-200 data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100 data-[align=start]:left-0 data-[align=center]:left-1/2 data-[align=center]:-translate-x-1/2 data-[align=end]:right-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
|
||||
class
|
||||
);
|
||||
|
||||
let target_id_for_script = multi_select_ctx.target_id.clone();
|
||||
let target_id_for_script_2 = multi_select_ctx.target_id.clone();
|
||||
|
||||
// Scroll indicator signals
|
||||
let (on_scroll, can_scroll_up_signal, can_scroll_down_signal) = use_can_scroll_vertical();
|
||||
|
||||
view! {
|
||||
<div
|
||||
data-name="MultiSelectContent"
|
||||
class=class
|
||||
id=multi_select_ctx.target_id
|
||||
data-target="target__multi_select"
|
||||
data-state="closed"
|
||||
data-align=align_str
|
||||
style="pointer-events: none;"
|
||||
on:scroll=move |ev| on_scroll.run(ev)
|
||||
>
|
||||
<div
|
||||
data-scroll-up="true"
|
||||
class=move || {
|
||||
let is_up: bool = can_scroll_up_signal.get();
|
||||
if is_up {
|
||||
"sticky -top-1 z-10 flex items-center justify-center py-1 bg-card"
|
||||
} else {
|
||||
"hidden"
|
||||
}
|
||||
}
|
||||
>
|
||||
<ChevronUp class="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
{children()}
|
||||
<div
|
||||
data-scroll-down="true"
|
||||
class=move || {
|
||||
let is_down: bool = can_scroll_down_signal.get();
|
||||
if is_down {
|
||||
"sticky -bottom-1 z-10 flex items-center justify-center py-1 bg-card"
|
||||
} else {
|
||||
"hidden"
|
||||
}
|
||||
}
|
||||
>
|
||||
<ChevronDown class="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
{format!(
|
||||
r#"
|
||||
(function() {{
|
||||
const setupMultiSelect = () => {{
|
||||
const multiSelect = document.querySelector('#{}');
|
||||
const trigger = document.querySelector('[data-multi-select-trigger="{}"]');
|
||||
|
||||
if (!multiSelect || !trigger) {{
|
||||
setTimeout(setupMultiSelect, 50);
|
||||
return;
|
||||
}}
|
||||
|
||||
if (multiSelect.hasAttribute('data-initialized')) {{
|
||||
return;
|
||||
}}
|
||||
multiSelect.setAttribute('data-initialized', 'true');
|
||||
|
||||
let isOpen = false;
|
||||
|
||||
const openMultiSelect = () => {{
|
||||
isOpen = true;
|
||||
if (window.ScrollLock) window.ScrollLock.lock();
|
||||
multiSelect.setAttribute('data-state', 'open');
|
||||
multiSelect.style.pointerEvents = 'auto';
|
||||
const triggerRect = trigger.getBoundingClientRect();
|
||||
multiSelect.style.minWidth = `${{triggerRect.width}}px`;
|
||||
multiSelect.dispatchEvent(new Event('scroll'));
|
||||
setTimeout(() => {{
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
}}, 0);
|
||||
}};
|
||||
|
||||
const closeMultiSelect = () => {{
|
||||
isOpen = false;
|
||||
multiSelect.setAttribute('data-state', 'closed');
|
||||
multiSelect.style.pointerEvents = 'none';
|
||||
document.removeEventListener('click', handleClickOutside);
|
||||
if (window.ScrollLock) window.ScrollLock.unlock(200);
|
||||
}};
|
||||
|
||||
const handleClickOutside = (e) => {{
|
||||
if (!multiSelect.contains(e.target) && !trigger.contains(e.target)) {{
|
||||
closeMultiSelect();
|
||||
}}
|
||||
}};
|
||||
|
||||
trigger.addEventListener('click', (e) => {{
|
||||
e.stopPropagation();
|
||||
if (isOpen) closeMultiSelect(); else openMultiSelect();
|
||||
}});
|
||||
|
||||
document.addEventListener('keydown', (e) => {{
|
||||
if (e.key === 'Escape' && isOpen) {{
|
||||
e.preventDefault();
|
||||
closeMultiSelect();
|
||||
}}
|
||||
}});
|
||||
}};
|
||||
|
||||
if (document.readyState === 'loading') {{
|
||||
document.addEventListener('DOMContentLoaded', setupMultiSelect);
|
||||
}} else {{
|
||||
setupMultiSelect();
|
||||
}}
|
||||
}})();
|
||||
"#,
|
||||
target_id_for_script,
|
||||
target_id_for_script_2,
|
||||
)}
|
||||
</script>
|
||||
}.into_any()
|
||||
}
|
||||
311
frontend/src/components/ui/select.rs
Normal file
311
frontend/src/components/ui/select.rs
Normal file
@@ -0,0 +1,311 @@
|
||||
use icons::{Check, ChevronDown, ChevronUp};
|
||||
use leptos::context::Provider;
|
||||
use leptos::prelude::*;
|
||||
use leptos_ui::clx;
|
||||
use strum::{AsRefStr, Display};
|
||||
use tw_merge::*;
|
||||
|
||||
use crate::components::hooks::use_can_scroll_vertical::use_can_scroll_vertical;
|
||||
use crate::components::hooks::use_random::use_random_id_for;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Display, AsRefStr)]
|
||||
pub enum SelectPosition {
|
||||
#[default]
|
||||
Below,
|
||||
Above,
|
||||
}
|
||||
|
||||
mod components {
|
||||
use super::*;
|
||||
clx! {SelectLabel, span, "px-2 py-1.5 text-sm font-medium data-inset:pl-8", "mb-1"}
|
||||
clx! {SelectItem, li, "inline-flex gap-2 items-center w-full rounded-sm px-2 py-1.5 text-sm no-underline transition-colors duration-200 text-popover-foreground hover:bg-accent hover:text-accent-foreground [&_svg:not([class*='size-'])]:size-4"}
|
||||
}
|
||||
|
||||
pub use components::*;
|
||||
|
||||
#[component]
|
||||
pub fn SelectGroup(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = "Select options".into(), into)] aria_label: String,
|
||||
) -> impl IntoView {
|
||||
let merged_class = tw_merge!("group", class);
|
||||
|
||||
view! {
|
||||
<ul data-name="SelectGroup" role="listbox" aria-label=aria_label class=merged_class>
|
||||
{children()}
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SelectValue(#[prop(optional, into)] placeholder: String) -> impl IntoView {
|
||||
let select_ctx = expect_context::<SelectContext>();
|
||||
|
||||
view! {
|
||||
<span data-name="SelectValue" class="text-sm text-muted-foreground truncate">
|
||||
{move || { select_ctx.value_signal.get().unwrap_or_else(|| placeholder.clone()) }}
|
||||
</span>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SelectOption(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = false.into(), into)] aria_selected: Signal<bool>,
|
||||
#[prop(optional, into)] value: Option<String>,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<SelectContext>();
|
||||
|
||||
let merged_class = tw_merge!(
|
||||
"group inline-flex gap-2 items-center w-full rounded-sm px-2 py-1.5 text-sm cursor-pointer no-underline transition-colors duration-200 text-popover-foreground hover:bg-accent hover:text-accent-foreground [&_svg:not([class*='size-'])]:size-4",
|
||||
class
|
||||
);
|
||||
|
||||
let value_for_check = value.clone();
|
||||
let is_selected = move || aria_selected.get() || ctx.value_signal.get() == value_for_check;
|
||||
|
||||
view! {
|
||||
<li
|
||||
data-name="SelectOption"
|
||||
class=merged_class
|
||||
role="option"
|
||||
tabindex="0"
|
||||
aria-selected=move || is_selected().to_string()
|
||||
data-select-option="true"
|
||||
on:click=move |_| {
|
||||
let val = value.clone();
|
||||
ctx.value_signal.set(val.clone());
|
||||
if let Some(on_change) = ctx.on_change {
|
||||
on_change.run(val);
|
||||
}
|
||||
}
|
||||
>
|
||||
{children()}
|
||||
<Check class="ml-auto opacity-0 size-4 text-muted-foreground group-aria-selected:opacity-100" />
|
||||
</li>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SelectContext {
|
||||
target_id: String,
|
||||
value_signal: RwSignal<Option<String>>,
|
||||
on_change: Option<Callback<Option<String>>>,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Select(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(optional, into)] default_value: Option<String>,
|
||||
#[prop(optional)] on_change: Option<Callback<Option<String>>>,
|
||||
) -> impl IntoView {
|
||||
let select_target_id = use_random_id_for("select");
|
||||
let value_signal = RwSignal::new(default_value);
|
||||
|
||||
let ctx = SelectContext { target_id: select_target_id.clone(), value_signal, on_change };
|
||||
|
||||
let merged_class = tw_merge!("relative w-fit", class);
|
||||
|
||||
view! {
|
||||
<Provider value=ctx>
|
||||
<div data-name="Select" class=merged_class>
|
||||
{children()}
|
||||
</div>
|
||||
</Provider>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SelectTrigger(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(optional, into)] id: String,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<SelectContext>();
|
||||
|
||||
let peer_class = if !id.is_empty() { format!("peer/{}", id) } else { String::new() };
|
||||
|
||||
let button_class = tw_merge!(
|
||||
"w-full p-2 h-9 inline-flex items-center justify-between text-sm font-medium whitespace-nowrap rounded-md transition-colors focus:outline-none focus:ring-1 focus:ring-ring focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&_svg:not(:last-child)]:mr-2 [&_svg:not(:first-child)]:ml-2 [&_svg:not([class*='size-'])]:size-4 border bg-background border-input hover:bg-accent hover:text-accent-foreground",
|
||||
&peer_class,
|
||||
class
|
||||
);
|
||||
|
||||
let button_id = if !id.is_empty() { id } else { format!("trigger_{}", ctx.target_id) };
|
||||
|
||||
view! {
|
||||
<button
|
||||
type="button"
|
||||
data-name="SelectTrigger"
|
||||
class=button_class
|
||||
id=button_id
|
||||
tabindex="0"
|
||||
data-select-trigger=ctx.target_id
|
||||
>
|
||||
{children()}
|
||||
<ChevronDown class="text-muted-foreground" />
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SelectContent(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = SelectPosition::default())] position: SelectPosition,
|
||||
#[prop(optional)] on_close: Option<Callback<()>>,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<SelectContext>();
|
||||
|
||||
let merged_class = tw_merge!(
|
||||
"w-[150px] overflow-auto z-50 p-1 rounded-md border bg-card shadow-md h-fit max-h-[300px] absolute top-[calc(100%+4px)] left-0 data-[position=Above]:top-auto data-[position=Above]:bottom-[calc(100%+4px)] transition-all duration-200 data-[state=closed]:opacity-0 data-[state=closed]:scale-95 data-[state=open]:opacity-100 data-[state=open]:scale-100 data-[state=closed]:data-[position=Below]:origin-top data-[state=open]:data-[position=Below]:origin-top data-[state=closed]:data-[position=Above]:origin-bottom data-[state=open]:data-[position=Above]:origin-bottom [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
|
||||
class
|
||||
);
|
||||
|
||||
let target_id_for_script = ctx.target_id.clone();
|
||||
let target_id_for_script_2 = ctx.target_id.clone();
|
||||
|
||||
// Scroll indicator signals
|
||||
let (on_scroll, can_scroll_up_signal, can_scroll_down_signal) = use_can_scroll_vertical();
|
||||
|
||||
view! {
|
||||
<div
|
||||
data-name="SelectContent"
|
||||
class=merged_class
|
||||
on:selectclose=move |_: web_sys::CustomEvent| {
|
||||
if let Some(cb) = on_close {
|
||||
cb.run(());
|
||||
}
|
||||
}
|
||||
id=ctx.target_id
|
||||
data-target="target__select"
|
||||
data-state="closed"
|
||||
data-position=position.to_string()
|
||||
style="pointer-events: none;"
|
||||
on:scroll=move |ev| on_scroll.run(ev)
|
||||
>
|
||||
<div
|
||||
data-scroll-up="true"
|
||||
class=move || {
|
||||
let is_up: bool = can_scroll_up_signal.get();
|
||||
if is_up {
|
||||
"sticky -top-1 z-10 flex items-center justify-center py-1 bg-card"
|
||||
} else {
|
||||
"hidden"
|
||||
}
|
||||
}
|
||||
>
|
||||
<ChevronUp class="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
{children()}
|
||||
<div
|
||||
data-scroll-down="true"
|
||||
class=move || {
|
||||
let is_down: bool = can_scroll_down_signal.get();
|
||||
if is_down {
|
||||
"sticky -bottom-1 z-10 flex items-center justify-center py-1 bg-card"
|
||||
} else {
|
||||
"hidden"
|
||||
}
|
||||
}
|
||||
>
|
||||
<ChevronDown class="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
{format!(
|
||||
r#"
|
||||
(function() {{
|
||||
const setupSelect = () => {{
|
||||
const select = document.querySelector('#{}');
|
||||
const trigger = document.querySelector('[data-select-trigger="{}"]');
|
||||
|
||||
if (!select || !trigger) {{
|
||||
setTimeout(setupSelect, 50);
|
||||
return;
|
||||
}}
|
||||
|
||||
if (select.hasAttribute('data-initialized')) {{
|
||||
return;
|
||||
}}
|
||||
select.setAttribute('data-initialized', 'true');
|
||||
|
||||
let isOpen = false;
|
||||
|
||||
const updatePosition = () => {{
|
||||
const triggerRect = trigger.getBoundingClientRect();
|
||||
const viewportHeight = window.innerHeight;
|
||||
const spaceBelow = viewportHeight - triggerRect.bottom;
|
||||
const spaceAbove = triggerRect.top;
|
||||
|
||||
if (spaceBelow < 200 && spaceAbove > spaceBelow) {{
|
||||
select.setAttribute('data-position', 'Above');
|
||||
}} else {{
|
||||
select.setAttribute('data-position', 'Below');
|
||||
}}
|
||||
|
||||
select.style.minWidth = `${{triggerRect.width}}px`;
|
||||
}};
|
||||
|
||||
const openSelect = () => {{
|
||||
isOpen = true;
|
||||
if (window.ScrollLock) window.ScrollLock.lock();
|
||||
updatePosition();
|
||||
select.setAttribute('data-state', 'open');
|
||||
select.style.pointerEvents = 'auto';
|
||||
select.dispatchEvent(new Event('scroll'));
|
||||
setTimeout(() => {{
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
}}, 0);
|
||||
}};
|
||||
|
||||
const closeSelect = () => {{
|
||||
isOpen = false;
|
||||
select.setAttribute('data-state', 'closed');
|
||||
select.style.pointerEvents = 'none';
|
||||
document.removeEventListener('click', handleClickOutside);
|
||||
select.dispatchEvent(new CustomEvent('selectclose', {{ bubbles: false }}));
|
||||
if (window.ScrollLock) window.ScrollLock.unlock(200);
|
||||
}};
|
||||
|
||||
const handleClickOutside = (e) => {{
|
||||
if (!select.contains(e.target) && !trigger.contains(e.target)) {{
|
||||
closeSelect();
|
||||
}}
|
||||
}};
|
||||
|
||||
trigger.addEventListener('click', (e) => {{
|
||||
e.stopPropagation();
|
||||
if (isOpen) closeSelect(); else openSelect();
|
||||
}});
|
||||
|
||||
const options = select.querySelectorAll('[data-select-option]');
|
||||
options.forEach(option => {{
|
||||
option.addEventListener('click', () => closeSelect());
|
||||
}});
|
||||
|
||||
document.addEventListener('keydown', (e) => {{
|
||||
if (e.key === 'Escape' && isOpen) {{
|
||||
e.preventDefault();
|
||||
closeSelect();
|
||||
}}
|
||||
}});
|
||||
}};
|
||||
|
||||
if (document.readyState === 'loading') {{
|
||||
document.addEventListener('DOMContentLoaded', setupSelect);
|
||||
}} else {{
|
||||
setupSelect();
|
||||
}}
|
||||
}})();
|
||||
"#,
|
||||
target_id_for_script,
|
||||
target_id_for_script_2,
|
||||
)}
|
||||
</script>
|
||||
}.into_any()
|
||||
}
|
||||
35
frontend/src/components/ui/separator.rs
Normal file
35
frontend/src/components/ui/separator.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use leptos::prelude::*;
|
||||
use tw_merge::*;
|
||||
|
||||
#[component]
|
||||
pub fn Separator(
|
||||
#[prop(into, optional)] orientation: Signal<SeparatorOrientation>,
|
||||
#[prop(into, optional)] class: String,
|
||||
// children: Children,
|
||||
) -> impl IntoView {
|
||||
let merged_class = Memo::new(move |_| {
|
||||
let orientation = orientation.get();
|
||||
let separator = SeparatorClass { orientation };
|
||||
separator.with_class(class.clone())
|
||||
});
|
||||
|
||||
view! { <div class=merged_class role="separator" /> }
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* 🧬 STRUCT 🧬 */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(TwClass, Default)]
|
||||
#[tw(class = "shrink-0 bg-border")]
|
||||
pub struct SeparatorClass {
|
||||
orientation: SeparatorOrientation,
|
||||
}
|
||||
|
||||
#[derive(TwVariant)]
|
||||
pub enum SeparatorOrientation {
|
||||
#[tw(default, class = "w-full h-[1px]")]
|
||||
Default,
|
||||
#[tw(class = "h-full w-[1px]")]
|
||||
Vertical,
|
||||
}
|
||||
239
frontend/src/components/ui/sheet.rs
Normal file
239
frontend/src/components/ui/sheet.rs
Normal file
@@ -0,0 +1,239 @@
|
||||
use icons::X;
|
||||
use leptos::context::Provider;
|
||||
use leptos::prelude::*;
|
||||
use leptos_ui::clx;
|
||||
use tw_merge::*;
|
||||
|
||||
use super::button::ButtonSize;
|
||||
use crate::components::hooks::use_random::use_random_id_for;
|
||||
use crate::components::ui::button::{Button, ButtonVariant};
|
||||
|
||||
mod components {
|
||||
use super::*;
|
||||
clx! {SheetTitle, h2, "font-bold text-2xl"}
|
||||
clx! {SheetDescription, p, "text-muted-foreground"}
|
||||
clx! {SheetBody, div, "flex flex-col gap-4"}
|
||||
clx! {SheetFooter, footer, "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end"}
|
||||
}
|
||||
|
||||
pub use components::*;
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ CONTEXT ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SheetContext {
|
||||
pub target_id: String,
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
pub type SheetVariant = ButtonVariant;
|
||||
pub type SheetSize = ButtonSize;
|
||||
|
||||
#[component]
|
||||
pub fn Sheet(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let sheet_target_id = use_random_id_for("sheet");
|
||||
let ctx = SheetContext { target_id: sheet_target_id };
|
||||
|
||||
let merged_class = tw_merge!("", class);
|
||||
|
||||
view! {
|
||||
<Provider value=ctx>
|
||||
<div data-name="Sheet" class=merged_class>
|
||||
{children()}
|
||||
</div>
|
||||
</Provider>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SheetTrigger(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = ButtonVariant::Outline)] variant: ButtonVariant,
|
||||
#[prop(default = ButtonSize::Default)] size: ButtonSize,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<SheetContext>();
|
||||
let trigger_id = format!("trigger_{}", ctx.target_id);
|
||||
|
||||
view! {
|
||||
<Button class=class attr:id=trigger_id attr:data-sheet-trigger=ctx.target_id variant=variant size=size>
|
||||
{children()}
|
||||
</Button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SheetClose(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = ButtonVariant::Outline)] variant: ButtonVariant,
|
||||
#[prop(default = ButtonSize::Default)] size: ButtonSize,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<SheetContext>();
|
||||
|
||||
view! {
|
||||
<Button class=class attr:data-sheet-close=ctx.target_id attr:aria-label="Close sheet" variant=variant size=size>
|
||||
{children()}
|
||||
</Button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SheetContent(
|
||||
children: Children,
|
||||
#[prop(optional, into)] class: String,
|
||||
#[prop(default = SheetDirection::Right)] direction: SheetDirection,
|
||||
#[prop(into, optional)] hide_close_button: Option<bool>,
|
||||
) -> impl IntoView {
|
||||
let ctx = expect_context::<SheetContext>();
|
||||
|
||||
let backdrop_id = format!("{}_backdrop", ctx.target_id);
|
||||
let target_id_for_script = ctx.target_id.clone();
|
||||
let backdrop_id_for_script = backdrop_id.clone();
|
||||
|
||||
let merged_class = tw_merge!(
|
||||
"fixed z-100 bg-card shadow-lg p-6 transition-transform duration-300 overflow-y-auto overscroll-y-contain",
|
||||
direction.initial_position(),
|
||||
direction.closed_class(),
|
||||
class
|
||||
);
|
||||
|
||||
view! {
|
||||
<div
|
||||
data-name="SheetBackdrop"
|
||||
id=backdrop_id
|
||||
class="fixed inset-0 transition-opacity duration-200 pointer-events-none z-60 bg-black/50 data-[state=closed]:opacity-0 data-[state=open]:opacity-100"
|
||||
data-state="closed"
|
||||
/>
|
||||
|
||||
<div
|
||||
data-name="SheetContent"
|
||||
class=merged_class
|
||||
id=ctx.target_id
|
||||
data-direction=direction.to_string()
|
||||
data-state="closed"
|
||||
style="pointer-events: none;"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class=format!(
|
||||
"absolute top-4 right-4 p-1 rounded-sm focus:ring-2 focus:ring-offset-2 focus:outline-none [&_svg:not([class*='size-'])]:size-4 focus:ring-ring{}",
|
||||
if hide_close_button.unwrap_or(false) { " hidden" } else { "" },
|
||||
)
|
||||
data-sheet-close=ctx.target_id.clone()
|
||||
aria-label="Close sheet"
|
||||
>
|
||||
<span class="hidden">"Close Sheet"</span>
|
||||
<X />
|
||||
</button>
|
||||
|
||||
{children()}
|
||||
</div>
|
||||
|
||||
<script>
|
||||
{format!(
|
||||
r#"
|
||||
(function() {{
|
||||
const setupSheet = () => {{
|
||||
const sheet = document.querySelector('#{}');
|
||||
const backdrop = document.querySelector('#{}');
|
||||
const trigger = document.querySelector('[data-sheet-trigger="{}"]');
|
||||
|
||||
if (!sheet || !backdrop || !trigger) {{
|
||||
setTimeout(setupSheet, 50);
|
||||
return;
|
||||
}}
|
||||
|
||||
if (sheet.hasAttribute('data-initialized')) {{
|
||||
return;
|
||||
}}
|
||||
sheet.setAttribute('data-initialized', 'true');
|
||||
|
||||
const openSheet = () => {{
|
||||
if (window.ScrollLock) window.ScrollLock.lock();
|
||||
sheet.setAttribute('data-state', 'open');
|
||||
backdrop.setAttribute('data-state', 'open');
|
||||
sheet.style.pointerEvents = 'auto';
|
||||
backdrop.style.pointerEvents = 'auto';
|
||||
const direction = sheet.getAttribute('data-direction');
|
||||
sheet.classList.remove('translate-x-full', '-translate-x-full', 'translate-y-full', '-translate-y-full');
|
||||
sheet.classList.add('translate-x-0', 'translate-y-0');
|
||||
}};
|
||||
|
||||
const closeSheet = () => {{
|
||||
sheet.setAttribute('data-state', 'closed');
|
||||
backdrop.setAttribute('data-state', 'closed');
|
||||
sheet.style.pointerEvents = 'none';
|
||||
backdrop.style.pointerEvents = 'none';
|
||||
const direction = sheet.getAttribute('data-direction');
|
||||
sheet.classList.remove('translate-x-0', 'translate-y-0');
|
||||
if (direction === 'Right') sheet.classList.add('translate-x-full');
|
||||
else if (direction === 'Left') sheet.classList.add('-translate-x-full');
|
||||
else if (direction === 'Top') sheet.classList.add('-translate-y-full');
|
||||
else if (direction === 'Bottom') sheet.classList.add('translate-y-full');
|
||||
if (window.ScrollLock) window.ScrollLock.unlock(300);
|
||||
}};
|
||||
|
||||
trigger.addEventListener('click', openSheet);
|
||||
const closeButtons = sheet.querySelectorAll('[data-sheet-close]');
|
||||
closeButtons.forEach(btn => btn.addEventListener('click', closeSheet));
|
||||
backdrop.addEventListener('click', closeSheet);
|
||||
document.addEventListener('keydown', (e) => {{
|
||||
if (e.key === 'Escape' && sheet.getAttribute('data-state') === 'open') {{
|
||||
e.preventDefault();
|
||||
closeSheet();
|
||||
}}
|
||||
}});
|
||||
}};
|
||||
|
||||
if (document.readyState === 'loading') {{
|
||||
document.addEventListener('DOMContentLoaded', setupSheet);
|
||||
}} else {{
|
||||
setupSheet();
|
||||
}}
|
||||
}})();
|
||||
"#,
|
||||
target_id_for_script,
|
||||
backdrop_id_for_script,
|
||||
target_id_for_script,
|
||||
)}
|
||||
</script>
|
||||
}.into_any()
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ ENUM ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone, Copy, strum::AsRefStr, strum::Display)]
|
||||
pub enum SheetDirection {
|
||||
Right,
|
||||
Left,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl SheetDirection {
|
||||
fn closed_class(self) -> &'static str {
|
||||
match self {
|
||||
SheetDirection::Right => "translate-x-full",
|
||||
SheetDirection::Left => "-translate-x-full",
|
||||
SheetDirection::Top => "-translate-y-full",
|
||||
SheetDirection::Bottom => "translate-y-full",
|
||||
}
|
||||
}
|
||||
|
||||
fn initial_position(self) -> &'static str {
|
||||
match self {
|
||||
SheetDirection::Right => "top-0 right-0 h-full w-[400px]",
|
||||
SheetDirection::Left => "top-0 left-0 h-full w-[400px]",
|
||||
SheetDirection::Top => "top-0 left-0 w-full h-[400px]",
|
||||
SheetDirection::Bottom => "bottom-0 left-0 w-full h-[400px]",
|
||||
}
|
||||
}
|
||||
}
|
||||
232
frontend/src/components/ui/sidenav.rs
Normal file
232
frontend/src/components/ui/sidenav.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_router::hooks::use_location;
|
||||
use leptos_ui::{clx, variants, void};
|
||||
|
||||
mod components {
|
||||
use super::*;
|
||||
clx! {SidenavWrapper, div, "group/sidenav-wrapper has-data-[variant=Inset]:bg-sidenav flex h-full w-full"}
|
||||
// clx! {SidenavInset, div, "bg-background relative flex w-full flex-1 flex-col md:peer-data-[variant=Inset]:m-2 md:peer-data-[variant=Inset]:ml-0 md:peer-data-[variant=Inset]:rounded-xl md:peer-data-[variant=Inset]:shadow-sm md:peer-data-[variant=Inset]:peer-data-[state=Collapsed]:ml-2"}
|
||||
clx! {SidenavInset, div, "bg-background relative flex w-full flex-1 flex-col data-[variant=Inset]:rounded-lg data-[variant=Inset]:border data-[variant=Inset]:border-sidenav-border data-[variant=Inset]:shadow-sm data-[variant=Inset]:m-2"}
|
||||
// * data-[], not group-data-[]
|
||||
clx! {SidenavInner, div, "flex flex-col w-full h-full bg-sidenav data-[variant=Floating]:rounded-lg data-[variant=Floating]:border data-[variant=Floating]:border-sidenav-border data-[variant=Floating]:shadow-sm"}
|
||||
clx! {SidenavHeader, div, "flex flex-col gap-2 p-2"}
|
||||
clx! {SidenavMenu, ul, "flex flex-col gap-1 w-full min-w-0"}
|
||||
clx! {SidenavMenuSub, ul, "border-sidenav-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5 group-data-[collapsible=Icon]:hidden"}
|
||||
clx! {SidenavMenuItem, li, "relative group/menu-item"}
|
||||
clx! {SidenavContent, div, "scrollbar__on_hover", "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=Icon]:overflow-hidden"}
|
||||
clx! {SidenavGroup, div, "flex relative flex-col p-2 w-full min-w-0"}
|
||||
clx! {SidenavGroupContent, div, "w-full text-sm"}
|
||||
clx! {SidenavGroupLabel, div, "text-sidenav-foreground/70 ring-sidenav-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=Icon]:-mt-8 group-data-[collapsible=Icon]:opacity-0"}
|
||||
clx! {SidenavFooter, footer, "flex flex-col gap-2 p-2"}
|
||||
// Button "More"
|
||||
clx! {DropdownMenuTriggerEllipsis, button, "text-sidenav-foreground ring-sidenav-ring hover:bg-sidenav-accent hover:text-sidenav-accent-foreground peer-hover/menu-button:text-sidenav-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0 after:absolute after:-inset-2 md:after:hidden peer-data-[size=sm]/menu-button:top-1 peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 group-data-[collapsible=Icon]:hidden peer-data-[active=true]/menu-button:text-sidenav-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0"}
|
||||
|
||||
void! {SidenavInput, input,
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50",
|
||||
"focus-visible:ring-2", // TODO. Port tw_merge to Tailwind V4.
|
||||
// "focus-visible:ring-[3px]", // TODO. Port tw_merge to Tailwind V4.
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
"read-only:bg-muted",
|
||||
// Specific to Sidenav
|
||||
"w-full h-8 shadow-none bg-background"
|
||||
}
|
||||
}
|
||||
|
||||
pub use components::*;
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[component]
|
||||
pub fn SidenavLink(
|
||||
children: Children,
|
||||
#[prop(into)] href: String,
|
||||
#[prop(optional, into)] class: String,
|
||||
) -> impl IntoView {
|
||||
let merged_class = tw_merge!(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left outline-hidden ring-sidenav-ring transition-[width,height,padding] focus-visible:ring-2 active:bg-sidenav-accent active:text-sidenav-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidenav=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 aria-[current=page]:bg-sidenav-accent aria-[current=page]:font-semibold aria-[current=page]:text-sidenav-accent-foreground data-[state=open]:hover:bg-sidenav-accent data-[state=open]:hover:text-sidenav-accent-foreground group-data-[collapsible=Icon]:size-8! group-data-[collapsible=Icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 hover:bg-sidenav-accent hover:text-sidenav-accent-foreground h-8 text-sm",
|
||||
class
|
||||
);
|
||||
|
||||
let location = use_location();
|
||||
|
||||
// Check if the link is active based on current path
|
||||
let href_clone = href.clone();
|
||||
let is_active = move || {
|
||||
let path = location.pathname.get();
|
||||
path == href_clone || path.starts_with(&format!("{}/", href_clone))
|
||||
};
|
||||
|
||||
let aria_current = move || if is_active() { "page" } else { "false" };
|
||||
|
||||
view! {
|
||||
<a data-name="SidenavLink" class=merged_class href=href aria-current=aria_current>
|
||||
{children()}
|
||||
</a>
|
||||
}
|
||||
}
|
||||
|
||||
variants! {
|
||||
SidenavMenuButton {
|
||||
base: "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidenav-ring transition-[width,height,padding] hover:bg-sidenav-accent hover:text-sidenav-accent-foreground focus-visible:ring-2 active:bg-sidenav-accent active:text-sidenav-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidenav=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 aria-[current=page]:bg-sidenav-accent aria-[current=page]:font-medium aria-[current=page]:text-sidenav-accent-foreground data-[state=open]:hover:bg-sidenav-accent data-[state=open]:hover:text-sidenav-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=Icon]:size-8! group-data-[collapsible=Icon]:p-0! [&>svg]:stroke-2 aria-[current=page]:[&>svg]:stroke-[2.7]",
|
||||
variants: {
|
||||
variant: {
|
||||
Default: "hover:bg-sidenav-accent hover:text-sidenav-accent-foreground", // Already in base
|
||||
Outline: "bg-background shadow-[0_0_0_1px_hsl(var(--sidenav-border))] hover:bg-sidenav-accent hover:text-sidenav-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidenav-accent))]",
|
||||
},
|
||||
size: {
|
||||
Default: "h-8 text-sm",
|
||||
Sm: "h-7 text-xs",
|
||||
Lg: "h-12",
|
||||
}
|
||||
},
|
||||
component: {
|
||||
element: button,
|
||||
support_href: true,
|
||||
support_aria_current: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, strum::Display, strum::IntoStaticStr)]
|
||||
pub enum SidenavVariant {
|
||||
#[default]
|
||||
Sidenav,
|
||||
Floating,
|
||||
Inset,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, strum::Display)]
|
||||
pub enum SidenavSide {
|
||||
#[default]
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, PartialEq, Eq, strum::Display)]
|
||||
pub enum SidenavCollapsible {
|
||||
#[default]
|
||||
Offcanvas,
|
||||
None,
|
||||
Icon,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Sidenav(
|
||||
#[prop(into, optional)] class: String,
|
||||
#[prop(default = SidenavVariant::default())] variant: SidenavVariant,
|
||||
#[prop(default = SidenavState::default())] data_state: SidenavState,
|
||||
#[prop(default = SidenavSide::default())] data_side: SidenavSide,
|
||||
#[prop(default = SidenavCollapsible::default())] data_collapsible: SidenavCollapsible,
|
||||
children: Children,
|
||||
) -> impl IntoView {
|
||||
view! {
|
||||
{if data_collapsible == SidenavCollapsible::None {
|
||||
view! {
|
||||
<aside
|
||||
data-name="Sidenav"
|
||||
class=tw_merge!(
|
||||
"flex flex-col h-full bg-sidenav text-sidenav-foreground w-(--sidenav-width)", class.clone()
|
||||
)
|
||||
>
|
||||
{children()}
|
||||
</aside>
|
||||
}
|
||||
.into_any()
|
||||
} else {
|
||||
view! {
|
||||
<aside
|
||||
data-name="Sidenav"
|
||||
data-sidenav=data_state.to_string()
|
||||
data-side=data_side.to_string()
|
||||
class="hidden md:block group peer text-sidenav-foreground data-[state=Collapsed]:hidden"
|
||||
>
|
||||
// * SidenavGap: This is what handles the sidenav gap on desktop
|
||||
<div
|
||||
data-name="SidenavGap"
|
||||
class=tw_merge!(
|
||||
"relative w-(--sidenav-width) bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=Offcanvas]:w-0",
|
||||
"group-data-[side=Right]:rotate-180",
|
||||
match variant {
|
||||
SidenavVariant::Sidenav => "group-data-[collapsible=Icon]:w-(--sidenav-width-icon)",
|
||||
SidenavVariant::Floating | SidenavVariant::Inset =>
|
||||
"group-data-[collapsible=Icon]:w-[calc(var(--sidenav-width-icon)+(--spacing(4)))]",
|
||||
}
|
||||
)
|
||||
/>
|
||||
<div
|
||||
data-name="SidenavContainer"
|
||||
class=tw_merge!(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-(--sidenav-width) transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
class,
|
||||
match data_side {
|
||||
SidenavSide::Left => "left-0 group-data-[collapsible=Offcanvas]:left-[calc(var(--sidenav-width)*-1)]",
|
||||
SidenavSide::Right => "right-0 group-data-[collapsible=Offcanvas]:right-[calc(var(--sidenav-width)*-1)]"
|
||||
},
|
||||
match variant {
|
||||
SidenavVariant::Sidenav => "group-data-[collapsible=Icon]:w-(--sidenav-width-icon) group-data-[side=Left]:border-r group-data-[side=Right]:border-l",
|
||||
SidenavVariant::Floating | SidenavVariant::Inset =>
|
||||
"p-2 group-data-[collapsible=Icon]:w-[calc(var(--sidenav-width-icon)+(--spacing(4))+2px)]",
|
||||
},
|
||||
)
|
||||
>
|
||||
// * Act as a Sidenav for the onclick trigger to work with nested Sidenavs.
|
||||
<SidenavInner attr:data-sidenav="Sidenav" attr:data-variant=variant.to_string()>
|
||||
{children()}
|
||||
<SidenavToggleRail />
|
||||
</SidenavInner>
|
||||
</div>
|
||||
</aside>
|
||||
}
|
||||
.into_any()
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
/* ========================================================== */
|
||||
/* ✨ FUNCTIONS ✨ */
|
||||
/* ========================================================== */
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, strum::Display)]
|
||||
pub enum SidenavState {
|
||||
#[default]
|
||||
Expanded,
|
||||
Collapsed,
|
||||
}
|
||||
|
||||
const ONCLICK_TRIGGER: &str = "document.querySelector('[data-name=\"Sidenav\"]').setAttribute('data-state', document.querySelector('[data-name=\"Sidenav\"]').getAttribute('data-state') === 'Collapsed' ? 'Expanded' : 'Collapsed')";
|
||||
|
||||
#[component]
|
||||
pub fn SidenavTrigger(children: Children) -> impl IntoView {
|
||||
view! {
|
||||
// TODO. Use Button.
|
||||
|
||||
<button
|
||||
onclick=ONCLICK_TRIGGER
|
||||
data-name="SidenavTrigger"
|
||||
class="inline-flex gap-2 justify-center items-center -ml-1 text-sm font-medium whitespace-nowrap rounded-md transition-all outline-none disabled:opacity-50 disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 aria-invalid:ring-destructive/20 aria-invalid:border-destructive size-7 dark:aria-invalid:ring-destructive/40 dark:hover:bg-accent/50 hover:bg-accent hover:text-accent-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
|
||||
>
|
||||
{children()}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn SidenavToggleRail() -> impl IntoView {
|
||||
view! {
|
||||
<button
|
||||
data-name="SidenavToggleRail"
|
||||
aria-label="Toggle Sidenav"
|
||||
tabindex="-1"
|
||||
onclick=ONCLICK_TRIGGER
|
||||
class="hidden absolute inset-y-0 z-20 w-4 transition-all ease-linear -translate-x-1/2 sm:flex group-data-[side=Left]:-right-4 group-data-[side=Right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] in-data-[side=Left]:cursor-w-resize in-data-[side=Right]:cursor-e-resize [[data-side=Left][data-state=Collapsed]_&]:cursor-e-resize [[data-side=Right][data-state=Collapsed]_&]:cursor-w-resize group-data-[collapsible=Offcanvas]:translate-x-0 group-data-[collapsible=Offcanvas]:after:left-full [[data-side=Left][data-collapsible=Offcanvas]_&]:-right-2 [[data-side=Right][data-collapsible=Offcanvas]_&]:-left-0eft-2 hover:after:bg-sidenav-border hover:group-data-[collapsible=Offcanvas]:bg-sidenav"
|
||||
/>
|
||||
}
|
||||
}
|
||||
13
frontend/src/components/ui/skeleton.rs
Normal file
13
frontend/src/components/ui/skeleton.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use leptos::prelude::*;
|
||||
use tw_merge::tw_merge;
|
||||
|
||||
#[component]
|
||||
pub fn Skeleton(
|
||||
#[prop(optional, into)] class: String,
|
||||
) -> impl IntoView {
|
||||
let class = tw_merge!(
|
||||
"animate-pulse rounded-md bg-muted",
|
||||
class
|
||||
);
|
||||
view! { <div class=class /> }
|
||||
}
|
||||
145
frontend/src/components/ui/sonner.rs
Normal file
145
frontend/src/components/ui/sonner.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
use leptos::prelude::*;
|
||||
use tw_merge::*;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, strum::Display)]
|
||||
pub enum ToastType {
|
||||
#[default]
|
||||
Default,
|
||||
Success,
|
||||
Error,
|
||||
Warning,
|
||||
Info,
|
||||
Loading,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, strum::Display)]
|
||||
pub enum SonnerPosition {
|
||||
TopLeft,
|
||||
TopCenter,
|
||||
TopRight,
|
||||
#[default]
|
||||
BottomRight,
|
||||
BottomCenter,
|
||||
BottomLeft,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, strum::Display)]
|
||||
pub enum SonnerDirection {
|
||||
TopDown,
|
||||
#[default]
|
||||
BottomUp,
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SonnerTrigger(
|
||||
children: Children,
|
||||
#[prop(into, optional)] class: String,
|
||||
#[prop(optional, default = ToastType::default())] variant: ToastType,
|
||||
#[prop(into)] title: String,
|
||||
#[prop(into)] description: String,
|
||||
#[prop(into, optional)] position: String,
|
||||
) -> impl IntoView {
|
||||
let variant_classes = match variant {
|
||||
ToastType::Default => "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
ToastType::Success => "bg-success text-success-foreground hover:bg-success/90",
|
||||
ToastType::Error => "bg-destructive text-white shadow-xs hover:bg-destructive/90 dark:bg-destructive/60",
|
||||
ToastType::Warning => "bg-warning text-warning-foreground hover:bg-warning/90",
|
||||
ToastType::Info => "bg-info text-info-foreground shadow-xs hover:bg-info/90",
|
||||
ToastType::Loading => "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
};
|
||||
|
||||
let merged_class = tw_merge!(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] w-fit cursor-pointer h-9 px-4 py-2",
|
||||
variant_classes,
|
||||
class
|
||||
);
|
||||
|
||||
// Only set position attribute if not empty
|
||||
let position_attr = if position.is_empty() { None } else { Some(position) };
|
||||
|
||||
view! {
|
||||
<button
|
||||
class=merged_class
|
||||
data-name="SonnerTrigger"
|
||||
data-variant=variant.to_string()
|
||||
data-toast-title=title
|
||||
data-toast-description=description
|
||||
data-toast-position=position_attr
|
||||
>
|
||||
{children()}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SonnerContainer(
|
||||
children: Children,
|
||||
#[prop(into, optional)] class: String,
|
||||
#[prop(optional, default = SonnerPosition::default())] position: SonnerPosition,
|
||||
) -> impl IntoView {
|
||||
let merged_class = tw_merge!("toast__container fixed z-50", class);
|
||||
|
||||
view! {
|
||||
<div class=merged_class data-position=position.to_string()>
|
||||
{children()}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SonnerList(
|
||||
children: Children,
|
||||
#[prop(into, optional)] class: String,
|
||||
#[prop(optional, default = SonnerPosition::default())] position: SonnerPosition,
|
||||
#[prop(optional, default = SonnerDirection::default())] direction: SonnerDirection,
|
||||
#[prop(into, default = "false".to_string())] expanded: String,
|
||||
#[prop(into, optional)] style: String,
|
||||
) -> impl IntoView {
|
||||
// pointer-events-none: container doesn't block clicks when empty
|
||||
// [&>*]:pointer-events-auto: toast items still receive clicks
|
||||
let merged_class = tw_merge!(
|
||||
"flex relative flex-col opacity-100 gap-[15px] h-[100px] w-[400px] pointer-events-none [&>*]:pointer-events-auto",
|
||||
class
|
||||
);
|
||||
|
||||
view! {
|
||||
<ol
|
||||
class=merged_class
|
||||
data-name="SonnerList"
|
||||
data-sonner-toaster="true"
|
||||
data-sonner-theme="light"
|
||||
data-position=position.to_string()
|
||||
data-expanded=expanded
|
||||
data-direction=direction.to_string()
|
||||
style=style
|
||||
>
|
||||
{children()}
|
||||
</ol>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn SonnerToaster(#[prop(default = SonnerPosition::default())] position: SonnerPosition) -> impl IntoView {
|
||||
// Auto-derive direction from position
|
||||
let direction = match position {
|
||||
SonnerPosition::TopLeft | SonnerPosition::TopCenter | SonnerPosition::TopRight => SonnerDirection::TopDown,
|
||||
_ => SonnerDirection::BottomUp,
|
||||
};
|
||||
|
||||
let container_class = match position {
|
||||
SonnerPosition::TopLeft => "left-6 top-6",
|
||||
SonnerPosition::TopRight => "right-6 top-6",
|
||||
SonnerPosition::TopCenter => "left-1/2 -translate-x-1/2 top-6",
|
||||
SonnerPosition::BottomCenter => "left-1/2 -translate-x-1/2 bottom-6",
|
||||
SonnerPosition::BottomLeft => "left-6 bottom-6",
|
||||
SonnerPosition::BottomRight => "right-6 bottom-6",
|
||||
};
|
||||
|
||||
view! {
|
||||
<SonnerContainer class=container_class position=position>
|
||||
<SonnerList position=position direction=direction>
|
||||
""
|
||||
</SonnerList>
|
||||
</SonnerContainer>
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,11 @@ pub fn TableRow(children: Children, #[prop(optional, into)] class: String) -> im
|
||||
|
||||
#[component]
|
||||
pub fn TableHead(children: Children, #[prop(optional, into)] class: String) -> impl IntoView {
|
||||
let class = tw_merge!("h-10 px-4 text-left align-middle font-medium text-muted-foreground whitespace-nowrap", class);
|
||||
let class = tw_merge!(
|
||||
"h-10 px-4 text-left align-middle font-medium text-muted-foreground whitespace-nowrap",
|
||||
"transition-all duration-100 active:scale-[0.98] cursor-pointer select-none hover:bg-muted/30 hover:text-foreground",
|
||||
class
|
||||
);
|
||||
view! { <th class=class>{children()}</th> }
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ pub struct ToastData {
|
||||
pub description: Option<String>,
|
||||
pub variant: ToastType,
|
||||
pub duration: u64, // ms
|
||||
pub is_exiting: RwSignal<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -45,51 +46,62 @@ pub fn SonnerTrigger(
|
||||
index: usize,
|
||||
total: usize,
|
||||
position: SonnerPosition,
|
||||
is_expanded: Signal<bool>,
|
||||
#[prop(optional)] on_dismiss: Option<Callback<()>>,
|
||||
) -> impl IntoView {
|
||||
let variant_classes = match toast.variant {
|
||||
ToastType::Default => "bg-background text-foreground border-border",
|
||||
ToastType::Success => "bg-background text-foreground border-border [&_.icon]:text-success",
|
||||
ToastType::Success => "bg-background text-foreground border-border [&_.icon]:text-green-500",
|
||||
ToastType::Error => "bg-background text-foreground border-border [&_.icon]:text-destructive",
|
||||
ToastType::Warning => "bg-background text-foreground border-border [&_.icon]:text-warning",
|
||||
ToastType::Info => "bg-background text-foreground border-border [&_.icon]:text-info",
|
||||
ToastType::Warning => "bg-background text-foreground border-border [&_.icon]:text-yellow-500",
|
||||
ToastType::Info => "bg-background text-foreground border-border [&_.icon]:text-blue-500",
|
||||
ToastType::Loading => "bg-background text-foreground border-border",
|
||||
};
|
||||
|
||||
// Sonner Stacking Logic
|
||||
// We calculate inverse index: 0 is the newest (top), 1 is older, etc.
|
||||
let inverse_index = index;
|
||||
let offset = inverse_index as f64 * 16.0;
|
||||
let scale = 1.0 - (inverse_index as f64 * 0.05);
|
||||
let opacity = if inverse_index > 2 { 0.0 } else { 1.0 - (inverse_index as f64 * 0.2) };
|
||||
|
||||
let is_bottom = !position.to_string().contains("Top");
|
||||
let y_direction = if is_bottom { -1.0 } else { 1.0 };
|
||||
let translate_y = offset * y_direction;
|
||||
let bar_color = match toast.variant {
|
||||
ToastType::Success => "bg-green-500",
|
||||
ToastType::Error => "bg-destructive",
|
||||
ToastType::Warning => "bg-yellow-500",
|
||||
ToastType::Info => "bg-blue-500",
|
||||
_ => "bg-primary",
|
||||
};
|
||||
|
||||
let style = format!(
|
||||
"z-index: {}; transform: translateY({}px) scale({}); opacity: {};",
|
||||
total - index,
|
||||
translate_y,
|
||||
scale,
|
||||
opacity
|
||||
);
|
||||
// Simplified Style (No manual translateY needed with Flexbox)
|
||||
let style = move || {
|
||||
format!(
|
||||
"z-index: {}; opacity: 1; transition: all 0.3s ease;",
|
||||
total - index
|
||||
)
|
||||
};
|
||||
|
||||
let animation_class = move || {
|
||||
let pos = position.to_string();
|
||||
let is_left = pos.contains("Left");
|
||||
let is_exiting = toast.is_exiting.get();
|
||||
|
||||
match (is_left, is_exiting) {
|
||||
(true, false) => "animate-sonner-in-left",
|
||||
(true, true) => "animate-sonner-out-left",
|
||||
(false, false) => "animate-sonner-in-right",
|
||||
(false, true) => "animate-sonner-out-right",
|
||||
}
|
||||
};
|
||||
|
||||
let icon = match toast.variant {
|
||||
ToastType::Success => Some(view! { <span class="icon text-success">"✓"</span> }.into_any()),
|
||||
ToastType::Error => Some(view! { <span class="icon text-destructive">"✕"</span> }.into_any()),
|
||||
ToastType::Warning => Some(view! { <span class="icon text-warning">"⚠"</span> }.into_any()),
|
||||
ToastType::Info => Some(view! { <span class="icon text-info">"ℹ"</span> }.into_any()),
|
||||
ToastType::Success => Some(view! { <span class="icon font-bold text-lg">"✓"</span> }.into_any()),
|
||||
ToastType::Error => Some(view! { <span class="icon font-bold text-lg">"✕"</span> }.into_any()),
|
||||
ToastType::Warning => Some(view! { <span class="icon font-bold text-lg">"⚠"</span> }.into_any()),
|
||||
ToastType::Info => Some(view! { <span class="icon font-bold text-lg">"ℹ"</span> }.into_any()),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
view! {
|
||||
<div
|
||||
class=tw_merge!(
|
||||
"absolute transition-all duration-300 ease-in-out cursor-pointer pointer-events-auto",
|
||||
"flex items-center gap-3 min-w-[350px] p-4 rounded-lg border shadow-lg bg-card",
|
||||
if is_bottom { "bottom-0" } else { "top-0" },
|
||||
variant_classes
|
||||
class=move || tw_merge!(
|
||||
"relative transition-all duration-300 ease-in-out cursor-pointer pointer-events-auto",
|
||||
"flex items-center gap-3 w-full max-w-[calc(100vw-2rem)] sm:max-w-[380px] p-4 rounded-lg border shadow-xl bg-card",
|
||||
variant_classes,
|
||||
animation_class()
|
||||
)
|
||||
style=style
|
||||
on:click=move |_| {
|
||||
@@ -99,15 +111,23 @@ pub fn SonnerTrigger(
|
||||
}
|
||||
>
|
||||
{icon}
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-sm font-semibold">{toast.title}</div>
|
||||
{move || toast.description.as_ref().map(|d| view! { <div class="text-xs opacity-70">{d.clone()}</div> })}
|
||||
<div class="flex flex-col gap-0.5 overflow-hidden flex-1">
|
||||
<div class="text-sm font-bold truncate leading-tight">{toast.title}</div>
|
||||
{move || toast.description.as_ref().map(|d| view! { <div class="text-xs opacity-80 truncate">{d.clone()}</div> })}
|
||||
</div>
|
||||
|
||||
// Progress Bar
|
||||
<div
|
||||
class=tw_merge!("absolute bottom-0 left-0 h-1 w-full opacity-30", bar_color)
|
||||
style=format!(
|
||||
"animation: sonner-progress {}ms linear forwards; transform-origin: left;",
|
||||
toast.duration
|
||||
)
|
||||
/>
|
||||
</div>
|
||||
}.into_any()
|
||||
}
|
||||
|
||||
// Thread local storage for global access
|
||||
thread_local! {
|
||||
static TOASTS: std::cell::RefCell<Option<RwSignal<Vec<ToastData>>>> = std::cell::RefCell::new(None);
|
||||
}
|
||||
@@ -122,7 +142,8 @@ pub fn provide_toaster() {
|
||||
pub fn Toaster(#[prop(default = SonnerPosition::default())] position: SonnerPosition) -> impl IntoView {
|
||||
let store = use_context::<ToasterStore>().expect("Toaster context not found");
|
||||
let toasts = store.toasts;
|
||||
let is_hovered = RwSignal::new(false);
|
||||
|
||||
let is_bottom = position.to_string().contains("Bottom");
|
||||
|
||||
let container_class = match position {
|
||||
SonnerPosition::TopLeft => "left-6 top-6 items-start",
|
||||
@@ -134,47 +155,51 @@ pub fn Toaster(#[prop(default = SonnerPosition::default())] position: SonnerPosi
|
||||
};
|
||||
|
||||
view! {
|
||||
<style>
|
||||
"@keyframes sonner-progress { from { transform: scaleX(1); } to { transform: scaleX(0); } }
|
||||
@keyframes sonner-in-right { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
|
||||
@keyframes sonner-out-right { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } }
|
||||
@keyframes sonner-in-left { from { transform: translateX(-100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
|
||||
@keyframes sonner-out-left { from { transform: translateX(0); opacity: 1; } to { transform: translateX(-100%); opacity: 0; } }
|
||||
.animate-sonner-in-right { animation: sonner-in-right 0.3s ease-out forwards; }
|
||||
.animate-sonner-out-right { animation: sonner-out-right 0.3s ease-in forwards; }
|
||||
.animate-sonner-in-left { animation: sonner-in-left 0.3s ease-out forwards; }
|
||||
.animate-sonner-out-left { animation: sonner-out-left 0.3s ease-in forwards; }"
|
||||
</style>
|
||||
<div
|
||||
class=tw_merge!("fixed z-[100] flex flex-col pointer-events-none min-h-[200px] w-[400px]", container_class)
|
||||
on:mouseenter=move |_| is_hovered.set(true)
|
||||
on:mouseleave=move |_| is_hovered.set(false)
|
||||
class=tw_merge!(
|
||||
"fixed z-[100] flex gap-3 pointer-events-none w-full sm:w-[400px]",
|
||||
if is_bottom { "flex-col-reverse" } else { "flex-col" },
|
||||
container_class,
|
||||
"pb-[env(safe-area-inset-bottom)] pt-[env(safe-area-inset-top)] px-4 sm:px-0"
|
||||
)
|
||||
>
|
||||
<For
|
||||
each=move || {
|
||||
let list = toasts.get();
|
||||
// Reverse the list so newest is at the end (for stacking)
|
||||
// or newest is at the beginning (for display logic)
|
||||
list.into_iter().rev().enumerate().collect::<Vec<_>>()
|
||||
list.into_iter().enumerate().collect::<Vec<_>>()
|
||||
}
|
||||
key=|(_, toast)| toast.id
|
||||
children=move |(index, toast)| {
|
||||
let id = toast.id;
|
||||
let total = toasts.with(|t| t.len());
|
||||
let is_exiting = toast.is_exiting;
|
||||
|
||||
// If hovered, expand the stack
|
||||
let expanded_style = move || {
|
||||
if is_hovered.get() {
|
||||
let offset = index as f64 * 70.0;
|
||||
let is_bottom = !position.to_string().contains("Top");
|
||||
let y_dir = if is_bottom { -1.0 } else { 1.0 };
|
||||
format!("transform: translateY({}px) scale(1); opacity: 1;", offset * y_dir)
|
||||
} else {
|
||||
"".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
view! {
|
||||
<div style=expanded_style>
|
||||
<SonnerTrigger
|
||||
toast=toast
|
||||
index=index
|
||||
total=total
|
||||
position=position
|
||||
on_dismiss=Callback::new(move |_| {
|
||||
<SonnerTrigger
|
||||
toast=toast
|
||||
index=index
|
||||
total=total
|
||||
position=position
|
||||
is_expanded=Signal::derive(move || true)
|
||||
on_dismiss=Callback::new(move |_| {
|
||||
is_exiting.set(true);
|
||||
leptos::task::spawn_local(async move {
|
||||
gloo_timers::future::TimeoutFuture::new(300).await;
|
||||
toasts.update(|vec| vec.retain(|t| t.id != id));
|
||||
})
|
||||
/>
|
||||
</div>
|
||||
});
|
||||
})
|
||||
/>
|
||||
}
|
||||
}
|
||||
/>
|
||||
@@ -182,7 +207,6 @@ pub fn Toaster(#[prop(default = SonnerPosition::default())] position: SonnerPosi
|
||||
}.into_any()
|
||||
}
|
||||
|
||||
// Global Helper Functions
|
||||
pub fn toast(title: impl Into<String>, variant: ToastType) {
|
||||
let signal_opt = TOASTS.with(|t| *t.borrow());
|
||||
|
||||
@@ -194,6 +218,7 @@ pub fn toast(title: impl Into<String>, variant: ToastType) {
|
||||
description: None,
|
||||
variant,
|
||||
duration: 4000,
|
||||
is_exiting: RwSignal::new(false),
|
||||
};
|
||||
|
||||
toasts.update(|t| {
|
||||
@@ -204,8 +229,11 @@ pub fn toast(title: impl Into<String>, variant: ToastType) {
|
||||
});
|
||||
|
||||
let duration = new_toast.duration;
|
||||
let is_exiting = new_toast.is_exiting;
|
||||
leptos::task::spawn_local(async move {
|
||||
gloo_timers::future::TimeoutFuture::new(duration as u32).await;
|
||||
is_exiting.set(true);
|
||||
gloo_timers::future::TimeoutFuture::new(300).await;
|
||||
toasts.update(|vec| vec.retain(|t| t.id != id));
|
||||
});
|
||||
}
|
||||
@@ -218,4 +246,4 @@ pub fn toast_error(title: impl Into<String>) { toast(title, ToastType::Error); }
|
||||
#[allow(dead_code)]
|
||||
pub fn toast_warning(title: impl Into<String>) { toast(title, ToastType::Warning); }
|
||||
#[allow(dead_code)]
|
||||
pub fn toast_info(title: impl Into<String>) { toast(title, ToastType::Info); }
|
||||
pub fn toast_info(title: impl Into<String>) { toast(title, ToastType::Info); }
|
||||
Reference in New Issue
Block a user