Merge pull request #10 from Lissy93/ref/test-and-ui-improvments

Ref/test and UI improvments
This commit is contained in:
Alicia Sykes authored and GitHub committed 2025-10-16 21:14:51 +01:00
commit 7efcd84916
251 files changed
+17721 -6402

No files matched your search

+15 -4
View File
@@ -111,12 +111,23 @@ If you're new to GitHub or open source, take a look at [git-in.to](https://git-i
---
### Features
100+ networking and sysadmin tools, zero third-party dependencies, works ofline.
<h3 align="center">Make it your own</h3>
<p align="center"><i>Custom layouts, theming, bookmarking, multi-language support and more</i></p>
<p align="center">
<img width="2761" height="1229" alt="networking-toolbox" src="https://github.com/user-attachments/assets/2a128ee2-9bcb-49f0-be41-f69a3b8f2474" />
<br>
<sup><i>We've got 100+ tools, covering all aspects of network engineering</i></sup>
<img width="800" src="https://storage.googleapis.com/as93-screenshots/networking-toolbox/light-dark-mode-single.png" />
</p>
<h3 align="center">Works anywhere</h3>
<p align="center"><i>Offline-capable, mobile optimized, zero third-party dependencies</i></p>
<p align="center">
<img width="800" src="https://storage.googleapis.com/as93-screenshots/networking-toolbox/mobile-views.png" />
</p>
<h3 align="center">100s of tools</h3>
<p align="center"><i>Everything you need for converting, calculating, diagnosing and verifying server configs</i></p>
<p align="center">
<img width="800" src="https://github.com/user-attachments/assets/2dfe66b7-2325-4b41-b116-32eab74d3cf6" />
</p>
---
+23
View File
@@ -0,0 +1,23 @@
name: "CodeQL Config"
paths:
- src/
paths-ignore:
- "**/node_modules"
- "**/.svelte-kit"
- "**/build"
- "**/dist"
- "**/.next"
- "**/coverage"
- "**/*.config.js"
- "**/*.config.ts"
- "**/vite.config.*"
- "**/vitest.config.*"
- "**/playwright.config.*"
- "**/tailwind.config.*"
- "**/postcss.config.*"
- "**/svelte.config.js"
queries:
- uses: security-and-quality
+161
View File
@@ -0,0 +1,161 @@
# Error Tracking and Handling
This app has a global error handling system that automatically catches and logs errors across both server and client side.
## How It Works
All errors are automatically captured by SvelteKit hooks and global listeners. You don't need to wrap everything in try-catch blocks.
**Key Files:**
- [`src/lib/types/error.ts`](https://github.com/Lissy93/networking-toolbox/blob/main/src/lib/types/error.ts) - Error types and custom error classes
- [`src/lib/utils/logger.ts`](https://github.com/Lissy93/networking-toolbox/blob/main/src/lib/utils/logger.ts) - Environment-aware logger with styled console output
- [`src/lib/utils/error-manager.ts`](https://github.com/Lissy93/networking-toolbox/blob/main/src/lib/utils/error-manager.ts) - Central error management with deduplication
- [`src/hooks.server.ts`](https://github.com/Lissy93/networking-toolbox/blob/main/src/hooks.server.ts) - Server-side error hook
- [`src/hooks.client.ts`](https://github.com/Lissy93/networking-toolbox/blob/main/src/hooks.client.ts) - Client-side error hook with global listeners
- [`src/routes/+error.svelte`](https://github.com/Lissy93/networking-toolbox/blob/main/src/routes/+error.svelte) - Error page UI
**What Gets Caught Automatically:**
- Server errors (API routes, server load functions)
- Client errors (component errors, runtime errors)
- Unhandled promise rejections
- Window errors (global `window.onerror`)
## For Developers
### Most of the time: Do nothing
The hooks catch everything. Just write your code normally.
### When you want custom context
Use the error manager to add specific context for debugging:
```typescript
import { errorManager } from '$lib/utils/error-manager';
try {
await saveUserData(data);
} catch (error) {
errorManager.captureException(error, 'error', {
component: 'UserSettings',
action: 'saveData',
dataSize: data.length
});
throw error; // Re-throw so user sees it
}
```
### Custom error types
Use `AppError` for domain-specific errors with user-friendly messages:
```typescript
import { AppError, NetworkError, ValidationError } from '$lib/types/error';
// Generic app error
throw new AppError('Database query failed', 'Unable to save your changes');
// Specific error types
throw new NetworkError('Connection timeout');
throw new ValidationError('Invalid email format', 'Please enter a valid email');
```
### Logging
Use the logger instead of `console.log`:
```typescript
import { logger } from '$lib/utils/logger';
logger.debug('Cache hit', { key, size });
logger.info('User action completed', { action: 'export', format: 'csv' });
logger.warn('Rate limit approaching', { requests: 95, limit: 100 });
logger.error('Operation failed', error, { component: 'DataExporter' });
```
The logger automatically adjusts based on environment (more verbose in dev, quieter in prod) and provides styled, collapsible output in the browser.
## Configuration
Set the log level via environment variable:
```bash
VITE_LOG_LEVEL=debug # Options: debug, info, warn, error
```
Defaults to `debug` in development, `warn` in production.
## Expanding with External Services
The error manager uses a transport pattern, making it easy to add services like Sentry or GlitchTip.
### Adding Sentry
1. Install Sentry:
```bash
npm install @sentry/sveltekit
```
2. Create a Sentry transport in [`src/lib/utils/error-manager.ts`](https://github.com/Lissy93/networking-toolbox/blob/main/src/lib/utils/error-manager.ts):
```typescript
import * as Sentry from '@sentry/sveltekit';
class SentryTransport implements ErrorTransport {
send(error: SerializedError): void {
Sentry.captureException(new Error(error.message), {
level: error.level,
tags: { component: error.context.component },
extra: error.context,
});
}
}
// Add to error manager
if (import.meta.env.VITE_SENTRY_DSN) {
errorManager.addTransport(new SentryTransport());
}
```
3. Initialize Sentry in your hooks:
```typescript
// src/hooks.client.ts
import * as Sentry from '@sentry/sveltekit';
Sentry.init({
dsn: import.meta.env.VITE_SENTRY_DSN,
environment: import.meta.env.MODE,
});
```
### Adding GlitchTip
GlitchTip is Sentry-compatible, so use the same approach with a different DSN.
### Custom Transport
Create any transport that implements the `ErrorTransport` interface:
```typescript
class CustomTransport implements ErrorTransport {
async send(error: SerializedError): Promise<void> {
await fetch('/api/log-error', {
method: 'POST',
body: JSON.stringify(error),
});
}
}
errorManager.addTransport(new CustomTransport());
```
## Error Deduplication
The error manager automatically deduplicates identical errors within a 5-second window. This prevents log spam when an error repeats rapidly.
## Testing
See [`tests/unit/utils/error-manager.test.ts`](https://github.com/Lissy93/networking-toolbox/blob/main/tests/unit/utils/error-manager.test.ts) for examples of testing error handling in your code.
+1
View File
@@ -69,6 +69,7 @@ jobs:
- name: Create Release
uses: softprops/action-gh-release@v2
with:
token: ${{ secrets.BOT_TOKEN }}
tag_name: ${{ github.ref_name }}
name: Networking Toolbox ${{ steps.version.outputs.version }}
body: |
+4
View File
@@ -25,6 +25,10 @@ Thumbs.db
/test-results
e2e-results.xml
# Other generated results
codeql-db/
*.sarif
# AI Crap
.claude/
.playwright-mcp/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Alicia Sykes
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+3 -3
View File
@@ -11,14 +11,14 @@ coverage:
status:
project:
default:
target: 60%
threshold: 0%
target: 80%
threshold: 5%
informational: true
if_ci_failed: success
patch:
default:
target: 50%
threshold: 0%
threshold: 10%
informational: true
if_ci_failed: success
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "networking-toolbox",
"private": true,
"version": "1.2.0",
"version": "1.3.0",
"type": "module",
"scripts": {
"dev": "vite dev",
+5 -1
View File
@@ -5,7 +5,10 @@
declare global {
namespace App {
// interface Error {}
interface Error {
message: string;
errorId?: string;
}
// interface Locals {}
// interface PageData {}
// interface PageState {}
@@ -14,6 +17,7 @@ declare global {
// Make version available globally
const __APP_VERSION__: string;
const __DEPLOY_ENV__: string;
}
// SVG imports
+48 -2
View File
@@ -4,17 +4,63 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Preload self-hosted fonts for default themes (Tokyo Night, Dark, Light) -->
<link rel="preload" as="style" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/fonts/fonts.css" media="print" onload="this.media='all';this.onload=null;" />
<noscript>
<link rel="stylesheet" href="/fonts/fonts.css" />
</noscript>
<!-- Preconnect to Google Fonts for other themes -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<!-- Prevent FOUC by applying theme before page renders -->
<script>
(function () {
try {
// Apply theme
const theme = localStorage.getItem('theme') || 'dark';
// Get saved theme from localStorage
const savedTheme = localStorage.getItem('theme');
let theme;
if (savedTheme) {
// Use saved theme if it exists
theme = savedTheme;
} else {
// No saved theme - check system preference
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const prefersLight = window.matchMedia('(prefers-color-scheme: light)').matches;
if (prefersLight) {
theme = 'light';
} else if (prefersDark) {
theme = 'dark';
} else {
theme = 'ocean';
}
}
// Apply theme class (dark theme doesn't need a class)
if (theme !== 'dark') {
document.documentElement.classList.add('theme-' + theme);
}
} catch (e) {
// Ignore localStorage errors (private browsing, etc.)
// Fall back to system preference or ocean
try {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const prefersLight = window.matchMedia('(prefers-color-scheme: light)').matches;
if (prefersLight) {
document.documentElement.classList.add('theme-light');
} else if (!prefersDark) {
// Neither dark nor light preferred - use ocean
document.documentElement.classList.add('theme-ocean');
}
// If prefersDark, no class needed (dark is default)
} catch (e2) {
// If all fails, use ocean
document.documentElement.classList.add('theme-ocean');
}
}
})();
</script>
+72
View File
@@ -0,0 +1,72 @@
/**
* Client-side hooks for error handling
*/
import type { HandleClientError } from '@sveltejs/kit';
import { dev } from '$app/environment';
import { errorManager } from '$lib/utils/error-manager';
/**
* Handle client-side errors from SvelteKit
*/
export const handleError: HandleClientError = ({ error, event, status, message }) => {
// Extract context
const context = {
url: event.url.pathname,
status,
component: 'SvelteKit',
};
// Capture error
const errorId = errorManager.captureException(error, 'error', context);
// Return safe message
return {
message: dev ? message : 'An unexpected error occurred',
errorId: errorId || undefined,
};
};
/**
* Set up global error listeners for unhandled errors
*/
if (typeof window !== 'undefined') {
// Handle uncaught errors
window.addEventListener('error', (event) => {
const context = {
url: window.location.pathname,
component: 'GlobalErrorHandler',
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
};
errorManager.captureException(event.error || new Error(event.message), 'error', context);
// Prevent default browser error handling in dev for better DX
if (dev) {
event.preventDefault();
}
});
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
const context = {
url: window.location.pathname,
component: 'GlobalErrorHandler',
promise: true,
};
const error =
event.reason instanceof Error
? event.reason
: new Error(typeof event.reason === 'string' ? event.reason : 'Unhandled promise rejection');
errorManager.captureException(error, 'error', context);
// Prevent default browser handling in dev
if (dev) {
event.preventDefault();
}
});
}
+31
View File
@@ -0,0 +1,31 @@
/**
* Server-side hooks for error handling and request processing
*/
import type { HandleServerError } from '@sveltejs/kit';
import { dev } from '$app/environment';
import { errorManager } from '$lib/utils/error-manager';
/**
* Handle server-side errors
* Called when an error is thrown during server-side rendering or in API routes
*/
export const handleError: HandleServerError = ({ error, event, status, message }) => {
// Extract request context
const context = {
url: event.url.pathname,
method: event.request.method,
userAgent: event.request.headers.get('user-agent') || undefined,
status,
};
// Capture error with context
const errorId = errorManager.captureException(error, 'error', context);
// Return safe error message to client
// In dev: return actual message, in prod: return generic message
return {
message: dev ? message : 'An unexpected error occurred 😵',
errorId: errorId || undefined,
};
};
@@ -0,0 +1,44 @@
<script lang="ts">
import Icon, { type IconName } from '$lib/components/global/Icon.svelte';
interface Props {
loading?: boolean;
disabled?: boolean;
icon?: IconName;
loadingIcon?: IconName;
loadingText?: string;
children: any;
onclick?: () => void;
class?: string;
}
let {
loading = false,
disabled = false,
icon,
loadingIcon = 'loader',
loadingText,
children,
onclick,
class: className = '',
}: Props = $props();
const isDisabled = $derived(loading || disabled);
</script>
<button class="lookup-btn {className}" {onclick} disabled={isDisabled}>
{#if loading}
<Icon name={loadingIcon} size="sm" animate="spin" />
{loadingText || children}
{:else}
{#if icon}
<Icon name={icon} size="sm" />
{/if}
{@render children()}
{/if}
</button>
<style>
/* Styles are already in diagnostics-pages.scss */
/* .lookup-btn is defined globally */
</style>
@@ -0,0 +1,29 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
interface Props {
title?: string;
error: string | null;
}
let { title = 'Error', error }: Props = $props();
</script>
{#if error}
<div class="card error-card">
<div class="card-content">
<div class="error-content">
<Icon name="alert-triangle" size="md" />
<div>
<strong>{title}</strong>
<p>{error}</p>
</div>
</div>
</div>
</div>
{/if}
<style>
/* Styles are already in diagnostics-pages.scss */
/* .error-card, .error-content are defined globally */
</style>
@@ -0,0 +1,51 @@
<script lang="ts" generics="T extends Record<string, any>">
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip.js';
interface Props {
examples: T[];
selectedIndex?: number | null;
onSelect: (example: T, index: number) => void;
title?: string;
getLabel: (example: T) => string;
getDescription: (example: T) => string;
getTooltip?: (example: T) => string;
}
let {
examples,
selectedIndex = null,
onSelect,
title = 'Quick Examples',
getLabel,
getDescription,
getTooltip,
}: Props = $props();
</script>
<div class="card examples-card">
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h4>{title}</h4>
</summary>
<div class="examples-grid">
{#each examples as example, i (i)}
<button
class="example-card"
class:selected={selectedIndex === i}
onclick={() => onSelect(example, i)}
use:tooltip={getTooltip ? getTooltip(example) : getDescription(example)}
>
<h5>{getLabel(example)}</h5>
<p>{getDescription(example)}</p>
</button>
{/each}
</div>
</details>
</div>
<style>
/* Styles are already in diagnostics-pages.scss */
/* This component uses existing shared styles */
</style>
@@ -0,0 +1,45 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
interface Props {
title: string;
onCopy?: () => void;
copied?: boolean;
copyText?: string;
copiedText?: string;
showCopyButton?: boolean;
children: any;
}
let {
title,
onCopy,
copied = false,
copyText = 'Copy Results',
copiedText = 'Copied!',
showCopyButton = true,
children,
}: Props = $props();
</script>
<div class="card results-card">
<div class="card-header row">
<h3>{title}</h3>
{#if showCopyButton && onCopy}
<button class="copy-btn" onclick={onCopy} disabled={copied}>
<span class={copied ? 'text-green-500' : ''}>
<Icon name={copied ? 'check' : 'copy'} size="xs" />
</span>
{copied ? copiedText : copyText}
</button>
{/if}
</div>
<div class="card-content">
{@render children()}
</div>
</div>
<style>
/* Styles are already in diagnostics-pages.scss */
/* .results-card, .copy-btn are defined globally */
</style>
@@ -0,0 +1,39 @@
<script lang="ts">
import Icon, { type IconName } from '$lib/components/global/Icon.svelte';
interface StatusItem {
icon: IconName;
value: string;
label: string;
status?: 'success' | 'warning' | 'error' | 'info';
tooltip?: string;
}
interface Props {
items: StatusItem[];
}
let { items }: Props = $props();
</script>
<div class="status-overview">
{#each items as item (item.label)}
<div class="status-item {item.status || ''}">
<Icon name={item.icon} size="sm" />
<div>
<strong>{item.value}</strong>
<div class="status-text">{item.label}</div>
</div>
</div>
{/each}
</div>
<style>
/* Styles are already in diagnostics-pages.scss */
/* .status-overview, .status-item are defined globally */
.status-text {
font-size: var(--font-size-xs);
color: var(--text-secondary);
margin-top: 2px;
}
</style>
@@ -0,0 +1,38 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
interface Props {
title?: string;
warnings: string[];
}
let { title = 'Warning', warnings }: Props = $props();
</script>
{#if warnings.length > 0}
<div class="card warning-card">
<div class="card-content">
<div class="warning-content">
<Icon name="alert-triangle" size="sm" />
<div class="warning-messages">
{#if title}
<strong>{title}</strong>
{/if}
{#each warnings as warning (warning)}
<p>{warning}</p>
{/each}
</div>
</div>
</div>
</div>
{/if}
<style>
/* Styles are already in diagnostics-pages.scss */
/* .warning-card, .warning-content are defined globally */
.warning-messages {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
}
</style>
+2 -2
View File
@@ -47,10 +47,10 @@
aria-label="Keyboard shortcuts"
use:tooltip={`Shortcuts (${formatShortcut('^/')})`}
>
<Icon name="info" size="sm" />
<Icon name="cli" size="sm" />
</button>
<SettingsMenu onSearchTrigger={() => globalSearchRef?.showSearch()} />
<SettingsMenu />
<BurgerMenu />
</div>
@@ -3,6 +3,7 @@
import { browser } from '$app/environment';
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip';
import { SHOW_TIPS_ON_HOMEPAGE } from '$lib/config/customizable-settings';
interface Tip {
icon: string;
@@ -39,6 +40,7 @@
const TOOL_USAGE_KEY = 'networking-toolbox-tool-usage';
function shouldShowTips(): boolean {
const defaultShow = SHOW_TIPS_ON_HOMEPAGE;
if (!browser) return false;
try {
@@ -53,10 +55,9 @@
const visitCount = Object.keys(toolUsage).length;
if (visitCount >= 3) return false;
}
return true;
return defaultShow;
} catch {
return true;
return defaultShow;
}
}
+11 -634
View File
@@ -1,78 +1,22 @@
<script lang="ts">
import { onMount } from 'svelte';
import { slide } from 'svelte/transition';
import Icon from '$lib/components/global/Icon.svelte';
import { accessibility, type AccessibilityOption } from '$lib/stores/accessibility';
import { tooltip } from '$lib/actions/tooltip';
import { browser } from '$app/environment';
import { theme, themes, type ThemeOption, type Theme } from '$lib/stores/theme';
import { navbarDisplay, navbarDisplayOptions, type NavbarDisplayMode } from '$lib/stores/navbarDisplay';
import { homepageLayout, homepageLayoutOptions, type HomepageLayoutMode } from '$lib/stores/homepageLayout';
import { site } from '$lib/constants/site';
import { resolve } from '$app/paths';
interface Props {
onSearchTrigger?: () => void;
}
let { onSearchTrigger }: Props = $props();
import { accessibility } from '$lib/stores/accessibility';
import { theme } from '$lib/stores/theme';
import { navbarDisplay } from '$lib/stores/navbarDisplay';
import { homepageLayout } from '$lib/stores/homepageLayout';
import SettingsPanel from '$lib/components/furniture/SettingsPanel.svelte';
let isOpen = $state(false);
let showMoreA11y = $state(false);
let showMoreThemes = $state(false);
let menuRef = $state<HTMLDivElement>();
let triggerRef = $state<HTMLButtonElement>();
let accessibilitySettings = $state(accessibility);
let currentTheme = $state(theme);
let currentNavbarDisplay = $state(navbarDisplay);
let currentHomepageLayout = $state(homepageLayout);
// Shortcut key detection
const isMac = browser && navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const shortcutKey = isMac ? '⌘' : 'Ctrl';
// Language selection
let selectedLanguage = $state('en');
const languages = [
{ code: 'en', name: 'English', available: true, flag: '🇺🇸' },
{ code: 'es', name: 'Español', available: false, flag: '🇪🇸' },
{ code: 'fr', name: 'Français', available: false, flag: '🇫🇷' },
{ code: 'de', name: 'Deutsch', available: false, flag: '🇩🇪' },
];
// Handle theme change
function handleThemeChange(themeId: ThemeOption) {
theme.setTheme(themeId);
}
// Handle accessibility setting toggle
function handleAccessibilityToggle(optionId: string) {
accessibility.toggle(optionId);
}
// Handle navbar display mode change
function handleNavbarDisplayChange(event: Event) {
const target = event.currentTarget as HTMLSelectElement;
navbarDisplay.setMode(target.value as NavbarDisplayMode);
}
// Handle homepage layout mode change
function handleHomepageLayoutChange(event: Event) {
const target = event.currentTarget as HTMLSelectElement;
homepageLayout.setMode(target.value as HomepageLayoutMode);
}
// Primary accessibility options (always visible)
const primaryA11yOptions = ['reduce-motion'];
// const primaryA11yOptions: string[] = [];
// Get filtered accessibility options
const primaryOptions = $derived($accessibilitySettings.options.filter((opt) => primaryA11yOptions.includes(opt.id)));
const additionalOptions = $derived(
$accessibilitySettings.options.filter((opt) => !primaryA11yOptions.includes(opt.id)),
);
// Handle clicks outside menu
function handleClickOutside(event: MouseEvent) {
if (isOpen && menuRef && !menuRef.contains(event.target as Node) && !triggerRef?.contains(event.target as Node)) {
@@ -88,17 +32,6 @@
}
}
// Handle search action
function handleSearch() {
isOpen = false;
onSearchTrigger?.();
}
// Handle link clicks to close menu
function handleLinkClick() {
isOpen = false;
}
// Handle global keyboard shortcuts
function handleGlobalKeydown(event: KeyboardEvent) {
if ((event.metaKey || event.ctrlKey) && event.key === ',') {
@@ -107,6 +40,11 @@
}
}
// Handle close from panel
function handleClose() {
isOpen = false;
}
onMount(() => {
document.addEventListener('click', handleClickOutside);
document.addEventListener('keydown', handleKeydown);
@@ -126,40 +64,6 @@
});
</script>
{#snippet accessibilityOption(option: AccessibilityOption)}
<label class="toggle-option" use:tooltip={option.description}>
<input
type="checkbox"
checked={option.enabled}
onchange={() => handleAccessibilityToggle(option.id)}
aria-describedby="a11y-{option.id}-desc"
/>
<span class="toggle-slider"></span>
<div class="toggle-content">
<span>{option.name}</span>
<small id="a11y-{option.id}-desc" class="toggle-description">{option.description}</small>
</div>
</label>
{/snippet}
{#snippet themeButton(themeOption: Theme)}
<button
class="theme-option"
class:active={$currentTheme === themeOption.id}
class:disabled={!themeOption.available}
onclick={() => handleThemeChange(themeOption.id)}
role="radio"
aria-checked={$currentTheme === themeOption.id}
disabled={!themeOption.available}
>
<div class="theme-preview theme-preview-{themeOption.id}"></div>
<span>
{themeOption.name}
{!themeOption.available ? ' (Soon)' : ''}
</span>
</button>
{/snippet}
<div class="settings-menu" bind:this={menuRef}>
<button
bind:this={triggerRef}
@@ -174,143 +78,7 @@
</button>
{#if isOpen}
<div class="settings-panel" role="menu">
<!-- Theme Selection -->
<div class="settings-section">
<h3>Theme</h3>
<div class="theme-options" role="radiogroup" aria-label="Theme selection">
<!-- Primary themes (always visible - first 6) -->
{#each themes.slice(0, 6) as themeOption (themeOption.id)}
{@render themeButton(themeOption)}
{/each}
<!-- Additional themes (expandable if more than 6) -->
{#if showMoreThemes && themes.length > 6}
<div class="additional-themes" transition:slide={{ duration: 300 }}>
{#each themes.slice(6) as themeOption (themeOption.id)}
{@render themeButton(themeOption)}
{/each}
</div>
{/if}
</div>
<!-- Show more/less button (only if there are more than 6 themes) -->
{#if themes.length > 6}
<button
class="show-more-btn"
onclick={() => (showMoreThemes = !showMoreThemes)}
aria-expanded={showMoreThemes}
>
<Icon name={showMoreThemes ? 'chevron-up' : 'chevron-down'} size="sm" />
<span>{showMoreThemes ? 'Show less' : 'Show more themes'}</span>
</button>
{/if}
</div>
<!-- Language Selection -->
<div class="settings-section">
<h3>Language</h3>
<div class="language-dropdown">
{#each languages as lang (lang.code)}
<button
class="language-option"
class:active={selectedLanguage === lang.code}
class:disabled={!lang.available}
onclick={() => (selectedLanguage = lang.code)}
disabled={!lang.available}
>
{lang.flag}
{lang.name}
</button>
{/each}
</div>
</div>
<!-- Homepage Layout -->
<div class="settings-section">
<h3>Homepage Layout</h3>
<div class="navbar-select-wrapper">
<select class="navbar-select" value={$currentHomepageLayout} onchange={handleHomepageLayoutChange}>
{#each homepageLayoutOptions as option (option.id)}
<option value={option.id}>{option.name}</option>
{/each}
</select>
<div class="dropdown-icon">
<Icon name="chevron-down" size="xs" />
</div>
</div>
<small class="navbar-description">
{homepageLayoutOptions.find((opt) => opt.id === $currentHomepageLayout)?.description}
</small>
</div>
<!-- Navbar Display -->
<div class="settings-section">
<h3>Top Navigation</h3>
<div class="navbar-select-wrapper">
<select class="navbar-select" value={$currentNavbarDisplay} onchange={handleNavbarDisplayChange}>
{#each navbarDisplayOptions as option (option.id)}
<option value={option.id}>{option.name}</option>
{/each}
</select>
<div class="dropdown-icon">
<Icon name="chevron-down" size="xs" />
</div>
</div>
<small class="navbar-description">
{navbarDisplayOptions.find((opt) => opt.id === $currentNavbarDisplay)?.description}
</small>
</div>
<!-- Accessibility Options -->
<div class="settings-section">
<h3>Accessibility</h3>
<div class="accessibility-options">
<!-- Primary options (always visible) -->
{#each primaryOptions as option (option.id)}
{@render accessibilityOption(option)}
{/each}
<!-- Expandable additional options -->
{#if showMoreA11y}
<div class="additional-options" transition:slide={{ duration: 300 }}>
{#each additionalOptions as option (option.id)}
{@render accessibilityOption(option)}
{/each}
</div>
{/if}
<!-- Show more/less button -->
<button class="show-more-btn" onclick={() => (showMoreA11y = !showMoreA11y)} aria-expanded={showMoreA11y}>
<Icon name={showMoreA11y ? 'chevron-up' : 'chevron-down'} size="sm" />
<span>{showMoreA11y ? 'Show less' : 'Show all a11y options'}</span>
</button>
</div>
</div>
<!-- Navigation Links -->
<div class="settings-section settings-links">
<button class="settings-link" onclick={handleSearch}>
<Icon name="search" size="sm" />
<span>Search</span>
</button>
<a href={resolve('/bookmarks')} class="settings-link" onclick={handleLinkClick}>
<Icon name="bookmarks" size="sm" />
<span>Bookmarks</span>
</a>
<a href={resolve('/about')} class="settings-link" onclick={handleLinkClick}>
<Icon name="info" size="sm" />
<span>About</span>
</a>
<a href={site.repo} class="settings-link" target="_blank" rel="noopener noreferrer" onclick={handleLinkClick}>
<Icon name="github" size="sm" />
<span>GitHub</span>
</a>
</div>
</div>
<SettingsPanel onClose={handleClose} />
{/if}
</div>
@@ -340,395 +108,4 @@
}
}
}
.settings-panel {
position: absolute;
top: calc(100% + var(--spacing-xs));
right: 0;
width: 16rem;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-md);
box-shadow: var(--shadow-lg);
padding: var(--spacing-md);
z-index: 1000;
animation: slideIn var(--transition-slow);
@media (max-width: 768px) {
position: fixed;
top: auto;
bottom: 0;
left: 0;
right: 0;
width: 100%;
max-height: 85vh;
overflow-y: auto;
border-radius: var(--radius-lg) var(--radius-lg) 0 0;
animation: slideUp var(--transition-slow);
}
}
.settings-section {
&:not(:last-child) {
margin-bottom: var(--spacing-md);
padding-bottom: var(--spacing-md);
border-bottom: 1px solid var(--border-primary);
}
h3 {
font-size: var(--font-size-sm);
font-weight: 600;
color: var(--text-primary);
margin: 0 0 var(--spacing-sm) 0;
}
}
.theme-options,
.additional-themes {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(64px, 1fr));
gap: var(--spacing-xs);
.additional-themes {
grid-column: 1 / -1;
}
}
.theme-option {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
cursor: pointer;
transition: all var(--transition-normal);
font-size: var(--font-size-xs);
color: var(--text-secondary);
&:hover:not(.disabled) {
background: var(--surface-hover);
border-color: var(--border-secondary);
}
&.active {
background: color-mix(in srgb, var(--color-primary), transparent 90%);
border-color: var(--color-primary);
color: var(--text-primary);
}
&.disabled {
opacity: 0.6;
cursor: not-allowed;
}
}
.theme-preview {
width: 1.5rem;
height: 1rem;
border-radius: var(--radius-xs);
border: 1px solid var(--border-secondary);
&.theme-preview-light {
background: linear-gradient(135deg, #f4f2fa 50%, #fff 50%);
}
&.theme-preview-dark {
background: linear-gradient(135deg, #0d1117 50%, #161b22 50%);
}
&.theme-preview-ocean {
background: linear-gradient(135deg, #131c2b 50%, #70edb7 50%);
}
&.theme-preview-purple {
background: linear-gradient(135deg, #13182b 50%, #cca6ff 50%);
}
&.theme-preview-cyberpunk {
background: linear-gradient(135deg, #000308 30%, #f700ff 70%);
box-shadow: 0 0 8px rgba(0, 255, 204, 0.4);
}
&.theme-preview-midnight {
background: linear-gradient(135deg, #0a0e27 50%, #5e72e4 50%);
}
&.theme-preview-arctic {
background: linear-gradient(135deg, #f0f4f8 50%, #00acc1 50%);
}
&.theme-preview-terminal {
background: linear-gradient(135deg, #000000 50%, #00ff00 50%);
}
&.theme-preview-lightpurple {
background: linear-gradient(135deg, #fafafa 50%, #cca6ff 50%);
}
&.theme-preview-muteddark {
background: linear-gradient(135deg, #21252b 50%, #f1f86d 50%);
}
&.theme-preview-solarized {
background: linear-gradient(135deg, #002b36 50%, #268bd2 50%);
}
}
.language-dropdown {
gap: var(--spacing-xs);
display: grid;
grid-template-columns: repeat(auto-fit, minmax(96px, 1fr));
}
.language-option {
padding: var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
text-align: left;
cursor: pointer;
transition: all var(--transition-normal);
font-size: var(--font-size-sm);
color: var(--text-secondary);
&:hover:not(.disabled) {
background: var(--surface-hover);
color: var(--text-primary);
}
&.active {
background: color-mix(in srgb, var(--color-primary), transparent 90%);
border-color: var(--color-primary);
color: var(--text-primary);
}
&.disabled {
opacity: 0.6;
cursor: not-allowed;
}
}
.navbar-select-wrapper {
position: relative;
display: block;
.dropdown-icon {
position: absolute;
right: var(--spacing-sm);
top: 50%;
transform: translateY(-50%);
pointer-events: none;
color: var(--text-secondary);
transition: all var(--transition-fast);
width: 0.75rem;
height: 0.75rem;
z-index: 1;
}
}
.navbar-select {
width: 100%;
padding: var(--spacing-sm) 2rem var(--spacing-sm) var(--spacing-sm);
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
font-size: var(--font-size-sm);
color: var(--text-primary);
cursor: pointer;
transition: all var(--transition-normal);
appearance: none;
position: relative;
&:hover {
background: var(--surface-hover);
border-color: var(--border-secondary);
}
&:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-primary), transparent 85%);
}
&:focus ~ .dropdown-icon {
color: var(--color-primary);
transform: translateY(-50%) rotate(180deg);
}
&:hover ~ .dropdown-icon {
color: var(--text-primary);
}
// Try to customize option colors (browser support varies)
option {
background: var(--bg-secondary);
color: var(--text-primary);
padding: var(--spacing-sm);
&:hover {
background: var(--surface-hover);
}
&:checked {
background: color-mix(in srgb, var(--color-primary), transparent 90%);
color: var(--text-primary);
}
}
}
.navbar-description {
color: var(--text-tertiary);
font-size: var(--font-size-xs);
line-height: 1.3;
margin-top: var(--spacing-xs);
display: block;
display: none;
}
.accessibility-options {
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
}
.toggle-option {
display: flex;
align-items: flex-start;
gap: var(--spacing-sm);
cursor: pointer;
font-size: var(--font-size-sm);
color: var(--text-primary);
padding: var(--spacing-xs) 0;
input[type='checkbox'] {
position: absolute;
opacity: 0;
width: 0;
height: 0;
&:checked + .toggle-slider {
background: var(--color-primary);
&::before {
transform: translateX(1rem);
}
}
&:focus + .toggle-slider {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
}
.toggle-slider {
position: relative;
width: 2rem;
height: 1.125rem;
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 1rem;
transition: all var(--transition-normal);
flex-shrink: 0;
margin-top: 0.125rem;
&::before {
content: '';
position: absolute;
top: 1px;
left: 1px;
width: 0.875rem;
height: 0.875rem;
background: var(--bg-primary);
border-radius: 50%;
transition: transform var(--transition-normal);
}
}
.toggle-content {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
min-width: 0;
flex: 1;
font-weight: 400;
.toggle-description {
display: none;
color: var(--text-secondary);
font-size: var(--font-size-xs);
line-height: 1.3;
}
}
}
.additional-options {
overflow: hidden;
}
.show-more-btn {
display: flex;
align-items: center;
gap: var(--spacing-xs);
width: 100%;
padding: var(--spacing-sm);
background: transparent;
border: 1px solid var(--border-primary);
border-radius: var(--radius-sm);
color: var(--text-secondary);
font-size: var(--font-size-xs);
cursor: pointer;
transition: all var(--transition-normal);
margin-top: var(--spacing-sm);
justify-content: center;
&:hover {
background: var(--surface-hover);
color: var(--text-primary);
border-color: var(--border-secondary);
}
&[aria-expanded='true'] {
color: var(--color-primary);
border-color: var(--color-primary);
}
}
.settings-links {
border-bottom: none;
padding-bottom: 0;
margin-bottom: 0;
.settings-link {
display: flex;
align-items: center;
gap: var(--spacing-sm);
width: 100%;
padding: var(--spacing-xs);
background: transparent;
border: none;
border-radius: var(--radius-sm);
text-align: left;
text-decoration: none;
color: var(--text-secondary);
cursor: pointer;
transition: all var(--transition-normal);
font-size: var(--font-size-sm);
&:hover {
background: var(--surface-hover);
color: var(--text-primary);
}
}
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-0.5rem);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(100%);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
File diff suppressed because it is too large. Load diff
@@ -4,6 +4,7 @@
import Icon from '$lib/components/global/Icon.svelte';
import { bookmarks } from '$lib/stores/bookmarks';
import { formatShortcut } from '$lib/utils/keyboard';
import SegmentedControl from '$lib/components/global/SegmentedControl.svelte';
interface Shortcut {
keys: string;
@@ -102,65 +103,134 @@
});
return groups;
});
const viewOptions = [
{ label: 'Keyboard Shortcuts', value: 'keyboard-shortcuts', icon: 'keyboard' },
{ label: 'About', value: 'about', icon: 'info' },
];
let activeView = $state('keyboard-shortcuts');
// Compute dialog title based on active view
const dialogTitle = $derived(activeView === 'keyboard-shortcuts' ? 'Command Palette' : 'Networking Toolbox');
// Close dialog when clicking links in About tab
function handleLinkClick() {
if (activeView === 'about') {
close();
}
}
</script>
{#if isOpen}
<div class="shortcuts-backdrop" onclick={handleBackdropClick} role="presentation">
<div class="shortcuts-dialog" role="dialog" aria-labelledby="shortcuts-title" aria-modal="true">
<div class="dialog-header">
<h2 id="shortcuts-title">Command Palette</h2>
<div class="dialog-header-main">
<h2 id="shortcuts-title">{dialogTitle}</h2>
<div>
<SegmentedControl
hideLabel={true}
options={viewOptions}
bind:value={activeView}
onchange={(value) => (activeView = value)}
/>
</div>
</div>
<button class="close-btn" onclick={close} aria-label="Close shortcuts">
<Icon name="x" size="sm" />
</button>
</div>
<div class="shortcuts-content">
{#each Object.entries(groupedShortcuts()) as [category, items] (category)}
<div class="shortcuts-category">
<h3>{category}</h3>
<ul>
{#each items as shortcut (shortcut.keys)}
<li>
<kbd>{formatShortcut(shortcut.keys)}</kbd>
<span>{shortcut.description}</span>
</li>
{/each}
</ul>
<!-- Show bookmarked tools if in Bookmarks category -->
{#if category === 'Bookmarks' && $bookmarks.length > 0}
<details class="bookmarks-details">
<summary>Your bookmarked tools ({Math.min($bookmarks.length, 9)})</summary>
<ul class="bookmarks-list">
{#each $bookmarks.slice(0, 10) as bookmark, index (bookmark.href)}
<li>
<kbd>{formatShortcut(`^${index + 1 === 10 ? 0 : index + 1}`)}</kbd>
<span>{bookmark.label}</span>
</li>
{/each}
{#if $bookmarks.length <= 9}
<li>
<kbd>{formatShortcut('^0')}</kbd>
<span>Homepage</span>
</li>
{/if}
{#if activeView === 'keyboard-shortcuts'}
<div class="shortcuts-content">
{#each Object.entries(groupedShortcuts()) as [category, items] (category)}
<div class="shortcuts-category">
<h3>{category}</h3>
<ul>
{#each items as shortcut (shortcut.keys)}
<li>
<kbd>{formatShortcut('^B')}</kbd>
<span>View all Bookmarks</span>
<kbd>{formatShortcut(shortcut.keys)}</kbd>
<span>{shortcut.description}</span>
</li>
</ul>
</details>
{/if}
{/each}
</ul>
{#if category === 'Bookmarks' && $bookmarks.length === 0}
<p class="no-bookmarks-tip">
<i>You don't have any bookmarks yet.</i>
<span>Right-click on a tool to bookmark it for quick access and offline use.</span>
</p>
{/if}
<!-- Show bookmarked tools if in Bookmarks category -->
{#if category === 'Bookmarks' && $bookmarks.length > 0}
<details class="bookmarks-details">
<summary>Your bookmarked tools ({Math.min($bookmarks.length, 9)})</summary>
<ul class="bookmarks-list">
{#each $bookmarks.slice(0, 10) as bookmark, index (bookmark.href)}
<li>
<kbd>{formatShortcut(`^${index + 1 === 10 ? 0 : index + 1}`)}</kbd>
<span>{bookmark.label}</span>
</li>
{/each}
{#if $bookmarks.length <= 9}
<li>
<kbd>{formatShortcut('^0')}</kbd>
<span>Homepage</span>
</li>
{/if}
<li>
<kbd>{formatShortcut('^B')}</kbd>
<span>View all Bookmarks</span>
</li>
</ul>
</details>
{/if}
{#if category === 'Bookmarks' && $bookmarks.length === 0}
<p class="no-bookmarks-tip">
<i>You don't have any bookmarks yet.</i>
<span>Right-click on a tool to bookmark it for quick access and offline use.</span>
</p>
{/if}
</div>
{/each}
</div>
{:else if activeView === 'about'}
<div class="about-content">
<p>
Networking Toolbox is an open-source collection of web-based networking tools designed to make
network-related tasks quicker and easier.
</p>
<p>
With 100+ tools, it's privacy-focused and self-hostable, fully customizable, and includes a free REST API
for automation.
</p>
<ul>
<li><a href="https://github.com/lissy93/networking-toolbox" onclick={handleLinkClick}>GitHub</a></li>
<li><a href="/sitemap" onclick={handleLinkClick}>Page Listing</a></li>
<li><a href="/settings" onclick={handleLinkClick}>App Settings</a></li>
<li><a href="/about" onclick={handleLinkClick}>Documentation</a></li>
<li><a href="/about/support" onclick={handleLinkClick}>Support</a></li>
<li><a href="/about/legal" onclick={handleLinkClick}>Legal</a></li>
</ul>
<p class="sponsor">
<Icon name="heart" size="md" />
<span>
<b>Finding Networking Toolbox useful?</b>
Consider <a href="https://github.com/sponsors/Lissy93">sponsoring us on GitHub</a> to support ongoing development!
</span>
</p>
<div class="about-license-section">
<a
href="https://github.com/lissy93/networking-toolbox"
target="_blank"
rel="noopener"
onclick={handleLinkClick}>Networking Toolbox</a
>
v{import.meta.env.VITE_APP_VERSION}, licensed under
<a href="https://opensource.org/licenses/MIT" target="_blank" rel="noopener" onclick={handleLinkClick}
>MIT</a
>
&copy; {new Date().getFullYear()} Alicia Sykes
</div>
{/each}
</div>
</div>
{/if}
</div>
</div>
{/if}
@@ -197,6 +267,7 @@
display: flex;
flex-direction: column;
animation: slideInScale 0.2s ease-out;
min-height: 548px;
@media (max-width: 768px) {
max-width: 100%;
@@ -207,6 +278,7 @@
border: none;
box-shadow: none;
animation: slideInFromBottom var(--transition-normal);
min-height: auto;
}
}
@@ -216,6 +288,13 @@
justify-content: space-between;
padding: var(--spacing-md) var(--spacing-lg);
border-bottom: 1px solid var(--border-primary);
.dialog-header-main {
display: flex;
width: 100%;
padding-right: var(--spacing-sm);
align-items: center;
justify-content: space-between;
}
@media (max-width: 768px) {
padding: var(--spacing-md);
@@ -397,6 +476,52 @@
}
}
.about-content {
padding: var(--spacing-md) var(--spacing-lg);
p {
color: var(--text-primary);
font-size: var(--font-size-md);
}
.sponsor {
font-size: var(--font-size-xs);
color: var(--color-pink);
background: color-mix(in srgb, var(--color-pink), transparent 90%);
padding: var(--spacing-sm);
border-radius: var(--radius-sm);
border: 2px solid var(--color-pink);
display: flex;
align-items: center;
gap: var(--spacing-sm);
margin: var(--spacing-md) auto;
a {
color: var(--color-pink);
text-decoration: underline;
}
opacity: 0;
animation: fadeIn 1s ease-out 10s forwards;
}
.about-license-section {
font-size: var(--font-size-xs);
text-align: center;
color: var(--text-secondary);
a {
color: var(--text-secondary);
text-decoration: underline;
}
}
ul {
padding-left: var(--spacing-lg);
margin: var(--spacing-lg) 0;
li {
a {
color: var(--color-primary);
text-decoration: underline;
}
}
}
}
@keyframes fadeIn {
from {
opacity: 0;
+1 -1
View File
@@ -18,7 +18,7 @@
xl: 'w-10 h-10',
};
type IconName = keyof typeof iconMap;
export type IconName = keyof typeof iconMap;
/**
* Get SVG content for the given icon name
@@ -0,0 +1,167 @@
<script lang="ts" generics="T extends string">
import { goto } from '$app/navigation';
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip.js';
interface Option {
value: T;
label: string;
icon?: string;
href?: string;
}
interface Props {
options: Option[];
value: T;
onchange?: (value: T) => void;
class?: string;
hideLabel?: boolean;
}
let { options, value = $bindable(), onchange, class: className = '', hideLabel = false }: Props = $props();
let buttonsContainer: HTMLDivElement;
// Track the active indicator position and width
let indicatorStyle = $state('');
// Check if all options have icons
const allHaveIcons = $derived(options.every((opt) => opt.icon));
const shouldHideLabel = $derived(hideLabel && allHaveIcons);
// Update indicator position when value or hideLabel changes
$effect(() => {
if (buttonsContainer && value) {
// Use requestAnimationFrame to ensure DOM has updated after hideLabel changes
requestAnimationFrame(() => {
const buttons = Array.from(buttonsContainer.querySelectorAll('button'));
const activeIndex = options.findIndex((opt) => opt.value === value);
const button = buttons[activeIndex] as HTMLButtonElement | undefined;
if (button) {
updateIndicator(button);
}
});
}
});
function updateIndicator(button: HTMLButtonElement) {
if (!buttonsContainer) return;
const containerRect = buttonsContainer.getBoundingClientRect();
const buttonRect = button.getBoundingClientRect();
const left = buttonRect.left - containerRect.left;
const width = buttonRect.width;
indicatorStyle = `transform: translateX(${left}px); width: ${width}px;`;
}
function handleClick(option: Option) {
value = option.value;
if (option.href) {
goto(option.href);
} else if (onchange) {
onchange(option.value);
}
}
</script>
<div class="segmented-control {className}">
<div class="buttons-container" bind:this={buttonsContainer}>
<div class="active-indicator" style={indicatorStyle}></div>
{#each options as option (option.value)}
<button
class="segment-btn"
class:active={value === option.value}
class:icon-only={shouldHideLabel && option.icon}
onclick={() => handleClick(option)}
aria-pressed={value === option.value}
use:tooltip={shouldHideLabel ? option.label : undefined}
>
{#if option.icon}
<Icon name={option.icon} size="sm" />
{/if}
{#if !shouldHideLabel}
<span class="segment-label">{option.label}</span>
{/if}
</button>
{/each}
</div>
</div>
<style lang="scss">
.segmented-control {
display: inline-flex;
}
.buttons-container {
position: relative;
display: flex;
gap: var(--spacing-xs);
background: var(--bg-secondary);
padding: var(--spacing-xs);
border-radius: var(--radius-md);
border: 1px solid var(--border-primary);
}
.active-indicator {
position: absolute;
top: var(--spacing-xs);
left: var(--spacing-xs);
height: calc(100% - calc(var(--spacing-xs) * 2));
background: var(--color-primary);
border-radius: var(--radius-sm);
transition:
transform 0.3s cubic-bezier(0.4, 0, 0.2, 1),
width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
pointer-events: none;
z-index: 0;
}
.segment-btn {
position: relative;
z-index: 1;
display: flex;
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-xs) var(--spacing-sm);
background: transparent;
color: var(--text-secondary);
font-size: var(--font-size-sm);
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
transition: color var(--transition-fast);
white-space: nowrap;
:global(svg) {
color: var(--text-secondary);
transition: color var(--transition-fast);
}
&:hover {
color: var(--text-primary);
:global(svg) {
color: var(--text-primary);
}
}
&.active {
color: var(--bg-primary);
background: var(--color-primary);
:global(svg) {
color: var(--bg-primary);
}
}
&.icon-only {
padding: var(--spacing-xs);
min-width: 2rem;
justify-content: center;
}
}
</style>
+2 -3
View File
@@ -443,8 +443,6 @@
padding: var(--spacing-sm);
gap: var(--spacing-xs);
text-align: center;
min-height: 5rem;
// max-width: 10rem;
background: linear-gradient(
135deg,
var(--bg-secondary),
@@ -453,12 +451,13 @@
.compact-content {
display: flex;
flex-direction: column;
flex-direction: row;
align-items: center;
gap: var(--spacing-sm);
width: 100%;
position: relative;
z-index: 1;
text-align: left;
}
h3 {
@@ -0,0 +1,78 @@
<script lang="ts" generics="T extends string">
import { onMount } from 'svelte';
import SegmentedControl from '$lib/components/global/SegmentedControl.svelte';
import type { Snippet } from 'svelte';
interface NavOption {
value: T;
label: string;
icon?: string;
href?: string;
}
interface Props {
title: string;
description: string;
navOptions?: NavOption[];
selectedNav?: T;
onNavChange?: (value: T) => void;
contentClass?: string;
children: Snippet;
hideLabels?: boolean;
}
let {
title,
description,
navOptions,
selectedNav = $bindable(),
onNavChange,
contentClass,
children,
hideLabels: propHideLabels = false,
}: Props = $props();
let hideLabels = $state(false);
function updateHideLabels() {
hideLabels = propHideLabels || window.innerWidth < 768;
}
onMount(() => {
updateHideLabels();
window.addEventListener('resize', updateHideLabels);
return () => window.removeEventListener('resize', updateHideLabels);
});
</script>
<div class="card">
<header class="card-header">
<div class="header-content">
<h2>{title}</h2>
<p>{description}</p>
</div>
{#if navOptions && selectedNav !== undefined}
<div class="header-controls">
<SegmentedControl options={navOptions} bind:value={selectedNav} onchange={onNavChange} hideLabel={hideLabels} />
</div>
{/if}
</header>
{#if contentClass}
<div class={contentClass}>
{@render children()}
</div>
{:else}
{@render children()}
{/if}
</div>
<style>
.card-header {
flex-direction: row;
gap: var(--spacing-md);
@media (max-width: 600px) {
flex-direction: column;
}
}
</style>
@@ -41,7 +41,6 @@
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, var(--min-col-width, 280px)), 1fr));
gap: var(--spacing-md);
margin-bottom: var(--spacing-xl);
&.compact {
gap: calc(var(--spacing-md) - 0.25rem);
}
@@ -2,6 +2,7 @@
import { onMount } from 'svelte';
import ToolsGrid from '$lib/components/global/ToolsGrid.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import SegmentedControl from '$lib/components/global/SegmentedControl.svelte';
import { bookmarks } from '$lib/stores/bookmarks';
import { frequentlyUsedTools, recentlyUsedTools } from '$lib/stores/toolUsage';
@@ -12,6 +13,12 @@
type ViewMode = 'bookmarks' | 'most-used' | 'recent';
let activeView = $state<ViewMode>('bookmarks');
const viewOptions = [
{ value: 'bookmarks' as const, label: 'Bookmarks', icon: 'bookmarks' },
{ value: 'most-used' as const, label: 'Most Used', icon: 'frequently-used' },
{ value: 'recent' as const, label: 'Recent', icon: 'clock' },
];
const bookmarkCount = $derived($bookmarks.length);
const mostUsedCount = $derived($frequentlyUsedTools.length);
const recentCount = $derived($recentlyUsedTools.length);
@@ -84,35 +91,7 @@
{/if}
</div>
<div class="view-toggle">
<button
class="toggle-btn"
class:active={activeView === 'bookmarks'}
onclick={() => (activeView = 'bookmarks')}
aria-pressed={activeView === 'bookmarks'}
>
<Icon name="bookmarks" size="sm" />
<span>Bookmarks</span>
</button>
<button
class="toggle-btn"
class:active={activeView === 'most-used'}
onclick={() => (activeView = 'most-used')}
aria-pressed={activeView === 'most-used'}
>
<Icon name="frequently-used" size="sm" />
<span>Most Used</span>
</button>
<button
class="toggle-btn"
class:active={activeView === 'recent'}
onclick={() => (activeView = 'recent')}
aria-pressed={activeView === 'recent'}
>
<Icon name="clock" size="sm" />
<span>Recent</span>
</button>
</div>
<SegmentedControl options={viewOptions} bind:value={activeView} onchange={(value) => (activeView = value)} />
</div>
<div class="bookmarks-grid">
@@ -196,60 +175,6 @@
}
}
.view-toggle {
display: flex;
gap: var(--spacing-xs);
background: var(--bg-secondary);
padding: var(--spacing-xs);
border-radius: var(--radius-md);
border: 1px solid var(--border-primary);
.toggle-btn {
display: flex;
align-items: center;
gap: var(--spacing-xs);
padding: var(--spacing-xs) var(--spacing-sm);
background: transparent;
color: var(--text-secondary);
font-size: var(--font-size-sm);
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
transition: all var(--transition-fast);
white-space: nowrap;
:global(svg) {
color: var(--text-secondary);
transition: color var(--transition-fast);
}
&:hover {
background: var(--bg-tertiary);
color: var(--text-primary);
:global(svg) {
color: var(--text-primary);
}
}
&.active {
background: var(--color-primary);
color: var(--bg-primary);
:global(svg) {
color: var(--bg-primary);
}
}
@media (max-width: 640px) {
span {
display: none;
}
padding: var(--spacing-xs);
}
}
}
.bookmarks-grid {
animation: subtleFadeIn 0.2s ease-out;
}
@@ -9,6 +9,7 @@
import { extractNavItems } from '$lib/utils/nav';
import QuickTips from '$lib/components/furniture/QuickTips.svelte';
import KeyboardShortcutChip from '$lib/components/common/KeyboardShortcutChip.svelte';
import { isStaticDeployment } from '$lib/utils/deployment';
import { onMount, onDestroy } from 'svelte';
import { browser } from '$app/environment';
@@ -36,12 +37,23 @@
'/ip-address-convertor': 'hash',
'/dns': 'server',
'/diagnostics': 'activity',
'/reference': 'book-open',
};
return iconMap[path] || 'folder';
}
// Define desired category order using paths (more maintainable than indexes)
const categoryOrder = ['/diagnostics', '/subnetting', '/dns', '/cidr', '/reference'];
// Memoized categories - computed once at module scope (static data)
const categories: CategorySection[] = TOP_NAV.filter((nav) => nav.href !== '/reference')
const categories: CategorySection[] = categoryOrder
.map((path) => TOP_NAV.find((nav) => nav.href === path))
.filter((nav): nav is NavItem => {
if (!nav) return false;
// Hide diagnostics in static deployments
if (isStaticDeployment && nav.href === '/diagnostics') return false;
return true;
})
.map((nav) => {
const subItems = SUB_NAV[nav.href] || [];
return {
@@ -51,12 +63,6 @@
basePath: nav.href,
items: extractNavItems(subItems),
};
})
.sort((a, b) => {
// Diagnostics first, then others
if (a.id === 'diagnostics') return -1;
if (b.id === 'diagnostics') return 1;
return 0;
});
// Get featured tools (up to 6)
@@ -257,7 +263,7 @@
<div class="categories-grid">
{#each categories as category (category.id)}
{#if category.items.length > 0}
<section class="category-section" class:full-width={category.id === 'diagnostics'}>
<section class="category-section category-{category.id}">
<div class="section-header">
<Icon name={category.icon} size="md" />
<h2>{category.title}</h2>
@@ -267,18 +273,6 @@
</section>
{/if}
{/each}
<!-- Reference Section -->
{#if referencePages.length > 0}
<section class="category-section full-width">
<div class="section-header">
<Icon name="book-open" size="md" />
<h2>Reference</h2>
<span class="count">{referencePages.length}</span>
</div>
<ToolsGrid size="small" idPrefix="reference" tools={referencePages} searchQuery="" />
</section>
{/if}
</div>
</div>
{:else}
@@ -395,17 +389,12 @@
flex-direction: column;
gap: var(--spacing-md);
background: var(--bg-tertiary);
// background: radial-gradient(
// color-mix(in srgb, var(--bg-tertiary), transparent 30%),
// color-mix(in srgb, var(--bg-tertiary), var(--bg-primary) 60%)
// );
padding: var(--spacing-md);
border-radius: var(--radius-md);
border: 1px solid var(--border-primary);
box-shadow: var(--shadow-md);
break-inside: avoid;
page-break-inside: avoid;
max-height: 36rem;
height: 100%;
overflow-y: auto;
animation: slideInFade 0.3s ease-out;
@@ -469,6 +458,10 @@
}
}
.category-diagnostics {
grid-row: span 2;
}
// Full width sections
.full-width {
grid-column: 1 / -1;
@@ -25,7 +25,7 @@
let isSearchOpen: boolean = $state(false);
let searchFilterRef: any = $state();
// Combined filtered list - must be $state for two-way binding with SearchFilter
// Combined filtered list - managed by SearchFilter component
let allFiltered: NavItem[] = $state([...toolPages, ...referencePages]);
// Update filtered items when search changes
@@ -48,8 +48,6 @@
page.keywords?.some((keyword) => keyword.toLowerCase().includes(query)),
);
}
// Update combined list
allFiltered = [...filteredTools, ...filteredReference];
});
// Open shortcuts dialog by dispatching Ctrl+/
@@ -107,9 +107,8 @@
}
.search-container {
max-width: 900px;
max-width: 800px;
margin: 0 auto;
// width: 100%;
// padding: 0 var(--spacing-md);
width: 100%;
}
</style>
+27 -11
View File
@@ -1,5 +1,13 @@
<script lang="ts">
import { TOP_NAV, aboutPages, SUB_NAV, STANDALONE_PAGES, type NavItem, type NavGroup } from '$lib/constants/nav';
import {
TOP_NAV,
aboutPages,
legalPages,
SUB_NAV,
STANDALONE_PAGES,
type NavItem,
type NavGroup,
} from '$lib/constants/nav';
import { resolve } from '$app/paths';
import Icon from '$lib/components/global/Icon.svelte';
@@ -46,16 +54,6 @@
}
return section;
}),
...(aboutPages.length
? [
{
label: 'About',
href: resolve('/about'),
description: 'Information about the project and documentation',
children: aboutPages.map(mapToNode),
},
]
: []),
...(STANDALONE_PAGES.length
? [
{
@@ -66,6 +64,24 @@
},
]
: []),
...(aboutPages.length
? [
{
label: 'About',
href: resolve('/about'),
description: 'Information about the project and documentation',
children: [
...aboutPages.filter((page) => !page.href.includes('/about/legal/')).map(mapToNode),
{
label: 'Legal',
href: resolve('/about/legal'),
description: 'Legal documentation and policies',
children: legalPages.map(mapToNode),
},
],
},
]
: []),
];
</script>
@@ -58,7 +58,7 @@
<div class="avatars-grid">
{#each sponsors.filter((s) => s.login) as sponsor, index (sponsor.login || `sponsor-${index}`)}
<a href="https://github.com/{sponsor.login}" target="_blank" rel="noopener" class="avatar-link">
<img src={sponsor.avatarUrl} alt={sponsor.name || sponsor.login} class="avatar large" />
<img width="72" src={sponsor.avatarUrl} alt={sponsor.name || sponsor.login} class="avatar large" />
<span>{sponsor.name || sponsor.login}</span>
</a>
{/each}
@@ -72,7 +72,7 @@
<div class="avatars-grid">
{#each contributors.filter((c) => c.login) as contributor, index (contributor.login || `contributor-${index}`)}
<a href="https://github.com/{contributor.login}" target="_blank" rel="noopener" class="avatar-link">
<img src={contributor.avatar_url} alt={contributor.login} class="avatar large" />
<img width="72" src={contributor.avatar_url} alt={contributor.login} class="avatar large" />
<span>{contributor.login}</span>
</a>
{/each}
@@ -86,7 +86,7 @@
<div class="avatars-grid small">
{#each stargazers.filter((s) => s.login) as stargazer, index (stargazer.login || `stargazer-${index}`)}
<a href="https://github.com/{stargazer.login}" target="_blank" rel="noopener" class="avatar-link small-link">
<img src={stargazer.avatar_url} alt={stargazer.login} class="avatar small" />
<img width="72" src={stargazer.avatar_url} alt={stargazer.login} class="avatar small" />
<span>{stargazer.login}</span>
</a>
{/each}
@@ -72,7 +72,7 @@
<p>Your only obligations are:</p>
<ul>
<li>
Preserve the MIT license. You can view this on the <a href="/about/license">Licensing Page</a>
Preserve the MIT license. You can view this on the <a href="/about/legal/license">Licensing Page</a>
</li>
<li>
You can not hold the author liable for any damages, and you understand that the software is provided "as is" with
@@ -88,7 +88,7 @@
Beyond that, you're free to use it however you want, for personal or commercial use. You can rebrand it, or use
parts of the code in your own projects and edit anything.
</p>
<p>
<p class="sponsor-section">
If you've found the project helpful, and want to support us, considering <a
href="https://github.com/sponsors/Lissy93">sponsoring us</a
> on GitHub. It always means the world to me, and helps cover ongoing running costs 🩷
@@ -102,4 +102,10 @@
h3 {
margin-top: var(--spacing-lg);
}
.sponsor-section {
background: color-mix(in srgb, var(--color-pink), transparent 40%);
padding: var(--spacing-md);
border-radius: var(--radius-md);
border: 2px solid var(--color-pink);
}
</style>
@@ -0,0 +1,36 @@
<section id="support">
<h2>Support</h2>
<h3>Self-Hosted Users</h3>
<p>
Networking Toolbox is provided "as-is" with no warranty or guarantees.<br />
We cannot offer dedicated support for non-commercial users.
</p>
<ul>
<li>For bugs, open an issue on GitHub with a clear description</li>
<li>We prioritize requests and issues from our GitHub sponsors</li>
<li>
You can also resolve issues yourself in our <a href="https://github.com/Lissy93/networking-toolbox/"
>GitHub source</a
>
</li>
</ul>
<hr />
<h3>Support Packages</h3>
<p>
For support packages, contact us at <code>support@aliciasykes.com</code>
<br />
We offer support packages for businesses, including:
</p>
<ul>
<li>Dedicated or on-prem hosting</li>
<li>Guaranteed SLA</li>
<li>Custom feature development</li>
<li>Own branding</li>
</ul>
</section>
<style>
</style>
@@ -0,0 +1,19 @@
<section id="tips">
<h2>Tips</h2>
<h3>Customize</h3>
<p>
If you use Networking Toolbox a lot, you might want to customize it, so that you feel right at home. Just head to
the <a href="/settings">Settings</a> page, where you can change the branding, colours, layout, behaviour and more.
</p>
<h3>Bookmark</h3>
<p>
Right-click on any tool to bookmark it. This will make it available offline and pin it to the top of your homepage.
</p>
<h3>Shortcuts</h3>
<p>
The app can be easily navigated with the keyboard alone. Use <code>Ctrl + /</code> to view all keybindings.
</p>
</section>
+15 -25
View File
@@ -1,6 +1,8 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import Icon from '$lib/components/global/Icon.svelte';
import { formatNumber } from '$lib/utils/formatters';
import '../../../styles/diagnostics-pages.scss';
let pools = $state(`192.168.0.0/16
10.0.0.0/20`);
@@ -50,7 +52,7 @@
efficiency: number;
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let _selectedExample = $state<string | null>(null);
let selectedExampleIndex = $state<number | null>(null);
let _userModified = $state(false);
@@ -424,18 +426,6 @@
performAllocation();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
async function copyAllAllocations() {
if (!result?.allocations) return;
@@ -443,7 +433,7 @@
if (successful.length === 0) return;
const text = successful.map((a) => `${a.cidr} - ${a.description}`).join('\n');
await copyToClipboard(text, 'all-allocations');
await clipboard.copy(text, 'all-allocations');
}
// Calculate on component load
@@ -559,11 +549,11 @@
<h3 use:tooltip={'Summary of subnet allocation requests and pool utilization'}>Allocation Results</h3>
{#if result.summary.successfulAllocations > 0}
<button
class="copy-all-button {copiedStates['all-allocations'] ? 'copied' : ''}"
class="copy-all-button {clipboard.isCopied('all-allocations') ? 'copied' : ''}"
onclick={copyAllAllocations}
>
<Icon name={copiedStates['all-allocations'] ? 'check' : 'copy'} size="sm" />
{copiedStates['all-allocations'] ? 'Copied!' : 'Copy All'}
<Icon name={clipboard.isCopied('all-allocations') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('all-allocations') ? 'Copied!' : 'Copy All'}
</button>
{/if}
</div>
@@ -604,19 +594,19 @@
<div class="breakdown-item">
<span class="breakdown-label">Total Pool Space:</span>
<span class="breakdown-value">
{result.summary.totalPoolSpace.toLocaleString()} addresses
{formatNumber(result.summary.totalPoolSpace)} addresses
</span>
</div>
<div class="breakdown-item">
<span class="breakdown-label">Allocated:</span>
<span class="breakdown-value allocated">
{result.summary.allocatedSpace.toLocaleString()} addresses
{formatNumber(result.summary.allocatedSpace)} addresses
</span>
</div>
<div class="breakdown-item">
<span class="breakdown-label">Remaining:</span>
<span class="breakdown-value">
{(result.summary.totalPoolSpace - result.summary.allocatedSpace).toLocaleString()} addresses
{formatNumber(result.summary.totalPoolSpace - result.summary.allocatedSpace)} addresses
</span>
</div>
</div>
@@ -650,14 +640,14 @@
<code class="result-cidr">{allocation.cidr}</code>
<span class="result-pool">in {allocation.pool}</span>
<span class="result-size">
({allocation.size.toLocaleString()} addresses)
({formatNumber(allocation.size)} addresses)
</span>
</div>
<button
class="copy-button {copiedStates[`alloc-${allocation.cidr}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(allocation.cidr || '', `alloc-${allocation.cidr}`)}
class="copy-button {clipboard.isCopied(`alloc-${allocation.cidr}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(allocation.cidr || '', `alloc-${allocation.cidr}`)}
>
<Icon name={copiedStates[`alloc-${allocation.cidr}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`alloc-${allocation.cidr}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
{:else if allocation.reason}
@@ -719,7 +709,7 @@
{#each pool.remaining.slice(0, 5) as remaining (remaining.cidr)}
<div class="remaining-block">
<code class="remaining-size">
{remaining.size.toLocaleString()} addresses
{formatNumber(remaining.size)} addresses
</code>
<span class="remaining-range">
{ipToString(remaining.start)} - {ipToString(remaining.start + remaining.size - 1)}
+22 -29
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import Icon from '$lib/components/global/Icon.svelte';
import { SvelteSet } from 'svelte/reactivity';
import '../../../styles/diagnostics-pages.scss';
@@ -27,7 +28,7 @@
unchangedCount: number;
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let _selectedExample = $state<string | null>(null);
let selectedExampleIndex = $state<number | null>(null);
let _userModified = $state(false);
@@ -254,23 +255,11 @@
performComparison();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
async function copyCategory(items: string[], category: string) {
if (!items.length) return;
const text = items.join('\n');
await copyToClipboard(text, `category-${category}`);
await clipboard.copy(text, `category-${category}`);
}
function swapLists() {
@@ -418,10 +407,10 @@
</h4>
{#if result.added.length > 0}
<button
class="copy-category {copiedStates['category-added'] ? 'copied' : ''}"
class="copy-category {clipboard.isCopied('category-added') ? 'copied' : ''}"
onclick={() => result && copyCategory(result.added, 'added')}
>
<Icon name={copiedStates['category-added'] ? 'check-circle' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied('category-added') ? 'check-circle' : 'copy'} size="xs" />
</button>
{/if}
</div>
@@ -432,10 +421,10 @@
<div class="network-item added">
<code class="network-cidr">{network}</code>
<button
class="copy-button {copiedStates[`added-${network}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(network, `added-${network}`)}
class="copy-button {clipboard.isCopied(`added-${network}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(network, `added-${network}`)}
>
<Icon name={copiedStates[`added-${network}`] ? 'check-circle' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`added-${network}`) ? 'check-circle' : 'copy'} size="xs" />
</button>
</div>
{/each}
@@ -457,10 +446,10 @@
</h4>
{#if result.removed.length > 0}
<button
class="copy-category {copiedStates['category-removed'] ? 'copied' : ''}"
class="copy-category {clipboard.isCopied('category-removed') ? 'copied' : ''}"
onclick={() => result && copyCategory(result.removed, 'removed')}
>
<Icon name={copiedStates['category-removed'] ? 'check-circle' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied('category-removed') ? 'check-circle' : 'copy'} size="xs" />
</button>
{/if}
</div>
@@ -471,10 +460,10 @@
<div class="network-item removed">
<code class="network-cidr">{network}</code>
<button
class="copy-button {copiedStates[`removed-${network}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(network, `removed-${network}`)}
class="copy-button {clipboard.isCopied(`removed-${network}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(network, `removed-${network}`)}
>
<Icon name={copiedStates[`removed-${network}`] ? 'check-circle' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`removed-${network}`) ? 'check-circle' : 'copy'} size="xs" />
</button>
</div>
{/each}
@@ -496,10 +485,10 @@
</h4>
{#if result.unchanged.length > 0}
<button
class="copy-category {copiedStates['category-unchanged'] ? 'copied' : ''}"
class="copy-category {clipboard.isCopied('category-unchanged') ? 'copied' : ''}"
onclick={() => copyCategory(result?.unchanged || [], 'unchanged')}
>
<Icon name={copiedStates['category-unchanged'] ? 'check-circle' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied('category-unchanged') ? 'check-circle' : 'copy'} size="xs" />
</button>
{/if}
</div>
@@ -510,10 +499,10 @@
<div class="network-item unchanged">
<code class="network-cidr">{network}</code>
<button
class="copy-button {copiedStates[`unchanged-${network}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(network, `unchanged-${network}`)}
class="copy-button {clipboard.isCopied(`unchanged-${network}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(network, `unchanged-${network}`)}
>
<Icon name={copiedStates[`unchanged-${network}`] ? 'check-circle' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`unchanged-${network}`) ? 'check-circle' : 'copy'} size="xs" />
</button>
</div>
{/each}
@@ -850,4 +839,8 @@
align-items: stretch;
}
}
textarea {
background: var(--bg-primary);
}
</style>
+294 -312
View File
@@ -3,6 +3,8 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let setA = $state(`192.168.0.0/16
10.0.0.0/8`);
@@ -12,7 +14,7 @@
let mergeContainers = $state(true);
let strictEquality = $state(false);
let result = $state<ContainsResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExampleIndex = $state<number | null>(null);
let userModified = $state(false);
@@ -57,17 +59,6 @@
userModified = true;
}
/* Copy to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
/* Export results as CSV */
function exportAsCSV() {
if (!result) return;
@@ -82,7 +73,7 @@
]);
const csv = [headers, ...rows].map((row) => row.join(',')).join('\n');
copyToClipboard(csv, 'csv-export');
clipboard.copy(csv, 'csv-export');
}
/* Export results as JSON */
@@ -96,7 +87,7 @@
};
const json = JSON.stringify(exportData, null, 2);
copyToClipboard(json, 'json-export');
clipboard.copy(json, 'json-export');
}
/* Clear inputs */
@@ -161,7 +152,7 @@
const size = range.end - range.start + 1n;
const label = type === 'candidate' ? 'Candidate' : type === 'container' ? 'Container' : 'Gap';
return `${label}${range.label ? ` (${range.label})` : ''}\nSize: ${size.toLocaleString()}${range.cidr ? `\nCIDR: ${range.cidr}` : ''}`;
return `${label}${range.label ? ` (${range.label})` : ''}\nSize: ${formatNumber(Number(size))}${range.cidr ? `\nCIDR: ${range.cidr}` : ''}`;
}
// Reactive computation
@@ -172,336 +163,326 @@
});
</script>
<div class="card">
<header class="card-header">
<h2>CIDR Containment Checker</h2>
<p>
Check if set A fully contains each item in set B. Supports many-to-many containment analysis with detailed
classification.
</p>
</header>
<!-- Options -->
<div class="options-section">
<h3>Options</h3>
<div class="options-grid">
<label class="checkbox-label">
<input type="checkbox" bind:checked={mergeContainers} />
<span class="checkbox-text">
Merge/normalize containers first
<Tooltip text="Combine overlapping ranges in set A before checking containment">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
<label class="checkbox-label">
<input type="checkbox" bind:checked={strictEquality} />
<span class="checkbox-text">
Strict equality counts as contain
<Tooltip text="Treat exact matches as 'equal' instead of 'inside'">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
</div>
</div>
<!-- Options -->
<div class="options-section">
<h3>Options</h3>
<div class="options-grid">
<label class="checkbox-label">
<input type="checkbox" bind:checked={mergeContainers} />
<span class="checkbox-text">
Merge/normalize containers first
<Tooltip text="Combine overlapping ranges in set A before checking containment">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
<label class="checkbox-label">
<input type="checkbox" bind:checked={strictEquality} />
<span class="checkbox-text">
Strict equality counts as contain
<Tooltip text="Treat exact matches as 'equal' instead of 'inside'">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
<!-- Input Section -->
<div class="input-section">
<div class="input-grid">
<!-- Set A -->
<div class="input-group">
<h3>
Set A (Containers)
<Tooltip text="The containing set - these ranges may contain items from Set B">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setA}
placeholder="192.168.0.0/16&#10;10.0.0.0/8"
class="input-textarea set-a"
rows="6"
oninput={handleInputChange}
></textarea>
</div>
</div>
<!-- Set B -->
<div class="input-group">
<h3>
Set B (Candidates)
<Tooltip text="Items to check for containment within Set A">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setB}
placeholder="192.168.1.0/24&#10;172.16.0.0/24"
class="input-textarea set-b"
rows="6"
oninput={handleInputChange}
></textarea>
</div>
</div>
</div>
<!-- Input Section -->
<div class="input-section">
<div class="input-grid">
<!-- Set A -->
<div class="input-group">
<h3>
Set A (Containers)
<Tooltip text="The containing set - these ranges may contain items from Set B">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setA}
placeholder="192.168.0.0/16&#10;10.0.0.0/8"
class="input-textarea set-a"
rows="6"
oninput={handleInputChange}
></textarea>
</div>
<div class="input-actions">
<button type="button" class="btn btn-secondary btn-sm" onclick={clearInputs}>
<Icon name="trash" size="sm" />
Clear All
</button>
</div>
<!-- Examples -->
<div class="card examples-card">
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h4>Quick Examples</h4>
</summary>
<div class="examples-grid">
{#each examples as example, i (example.label)}
<button
class="example-card"
class:selected={selectedExampleIndex === i && !userModified}
onclick={() => setExample(example, i)}
>
<div class="example-label">{example.label}</div>
<div class="example-preview">
{example.setA.split('\n')[0]}... ⊆ {example.setB.split('\n')[0]}...
</div>
</button>
{/each}
</div>
</details>
</div>
</div>
<!-- Set B -->
<div class="input-group">
<h3>
Set B (Candidates)
<Tooltip text="Items to check for containment within Set A">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setB}
placeholder="192.168.1.0/24&#10;172.16.0.0/24"
class="input-textarea set-b"
rows="6"
oninput={handleInputChange}
></textarea>
</div>
<!-- Results Section -->
{#if result}
<div class="results-section">
{#if result.errors.length > 0}
<div class="info-panel error">
<h3>Parse Errors</h3>
<ul class="error-list">
{#each result.errors as error (error)}
<li>{error}</li>
{/each}
</ul>
</div>
</div>
{/if}
<div class="input-actions">
<button type="button" class="btn btn-secondary btn-sm" onclick={clearInputs}>
<Icon name="trash" size="sm" />
Clear All
</button>
</div>
<!-- Examples -->
<div class="card examples-card">
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h4>Quick Examples</h4>
</summary>
<div class="examples-grid">
{#each examples as example, i (example.label)}
{#if result.checks.length > 0}
<!-- Summary Statistics -->
<div class="stats-section">
<div class="summary-header">
<h3>Containment Analysis</h3>
<div class="export-buttons">
<button
class="example-card"
class:selected={selectedExampleIndex === i && !userModified}
onclick={() => setExample(example, i)}
type="button"
class="btn btn-primary btn-sm"
class:copied={clipboard.isCopied('csv-export')}
onclick={exportAsCSV}
>
<div class="example-label">{example.label}</div>
<div class="example-preview">
{example.setA.split('\n')[0]}... ⊆ {example.setB.split('\n')[0]}...
</div>
<Icon name={clipboard.isCopied('csv-export') ? 'check' : 'csv-file'} size="sm" />
CSV
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={clipboard.isCopied('json-export')}
onclick={exportAsJSON}
>
<Icon name={clipboard.isCopied('json-export') ? 'check' : 'json-file'} size="sm" />
JSON
</button>
</div>
</div>
<div class="stats-grid">
<div class="stat-card containers">
<span class="stat-label">Containers (A)</span>
<span class="stat-value">{result.stats.setA.count} items</span>
<span class="stat-detail">{result.stats.setA.addresses} addresses</span>
</div>
<div class="stat-card candidates">
<span class="stat-label">Candidates (B)</span>
<span class="stat-value">{result.stats.totalChecked} items</span>
<span class="stat-detail">checked for containment</span>
</div>
<div class="stat-card inside">
<span class="stat-label">Inside</span>
<span class="stat-value">{result.stats.inside}</span>
<span class="stat-detail">fully contained</span>
</div>
<div class="stat-card equal">
<span class="stat-label">Equal</span>
<span class="stat-value">{result.stats.equal}</span>
<span class="stat-detail">exact matches</span>
</div>
<div class="stat-card partial">
<span class="stat-label">Partial</span>
<span class="stat-value">{result.stats.partial}</span>
<span class="stat-detail">partial overlap</span>
</div>
<div class="stat-card outside">
<span class="stat-label">Outside</span>
<span class="stat-value">{result.stats.outside}</span>
<span class="stat-detail">no overlap</span>
</div>
</div>
</div>
<!-- Containment Results Table -->
<div class="table-section">
<h4>Containment Results</h4>
<div class="results-table">
<div class="table-header">
<div class="col-input">Candidate</div>
<div class="col-status">Status</div>
<div class="col-coverage">Coverage</div>
<div class="col-containers">Containers</div>
<div class="col-gaps">Gaps</div>
</div>
{#each result.checks as check, index (`${check.input}-${index}`)}
{@const statusInfo = getStatusInfo(check.status)}
<div class="table-row status-{check.status}">
<div class="col-input">
<code class="candidate-input">{check.input}</code>
</div>
<div class="col-status">
<div class="status-badge" style="color: {statusInfo.color}">
<Icon name={statusInfo.icon} size="sm" />
{statusInfo.label}
</div>
</div>
<div class="col-coverage">
<div class="coverage-bar">
<div
class="coverage-fill"
style="width: {check.coverage}%; background-color: {statusInfo.color}"
></div>
<span class="coverage-text">{check.coverage}%</span>
</div>
</div>
<div class="col-containers">
{#if check.matchingContainers.length > 0}
<div class="container-list">
{#each check.matchingContainers as container (container)}
<code class="container-item">{container}</code>
{/each}
</div>
{:else}
<span class="no-containers">-</span>
{/if}
</div>
<div class="col-gaps">
{#if check.gaps.length > 0}
<div class="gaps-list">
{#each check.gaps as gap (gap)}
<code class="gap-item">{gap}</code>
{/each}
</div>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={clipboard.isCopied(`gaps-${check.input}`)}
onclick={() => clipboard.copy(check.gaps.join('\n'), `gaps-${check.input}`)}
>
<Icon name={clipboard.isCopied(`gaps-${check.input}`) ? 'check' : 'copy'} size="xs" />
</button>
{:else}
<span class="no-gaps">-</span>
{/if}
</div>
</div>
{/each}
</div>
</details>
</div>
</div>
</div>
<!-- Results Section -->
{#if result}
<div class="results-section">
{#if result.errors.length > 0}
<div class="info-panel error">
<h3>Parse Errors</h3>
<ul class="error-list">
{#each result.errors as error (error)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
{#if result.checks.length > 0}
<!-- Summary Statistics -->
<div class="stats-section">
<div class="summary-header">
<h3>Containment Analysis</h3>
<div class="export-buttons">
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={copiedStates['csv-export']}
onclick={exportAsCSV}
>
<Icon name={copiedStates['csv-export'] ? 'check' : 'csv-file'} size="sm" />
CSV
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={copiedStates['json-export']}
onclick={exportAsJSON}
>
<Icon name={copiedStates['json-export'] ? 'check' : 'json-file'} size="sm" />
JSON
</button>
<!-- Visualization -->
{#if result.visualization.length > 0}
<div class="visualization-section">
<h4>Containment Visualization</h4>
<div class="viz-legend">
<div class="legend-item">
<div class="legend-color candidate-color"></div>
<span>Candidate Range</span>
</div>
<div class="legend-item">
<div class="legend-color container-color"></div>
<span>Container Coverage</span>
</div>
<div class="legend-item">
<div class="legend-color gap-color"></div>
<span>Uncovered Gaps</span>
</div>
</div>
<div class="stats-grid">
<div class="stat-card containers">
<span class="stat-label">Containers (A)</span>
<span class="stat-value">{result.stats.setA.count} items</span>
<span class="stat-detail">{result.stats.setA.addresses} addresses</span>
</div>
<div class="stat-card candidates">
<span class="stat-label">Candidates (B)</span>
<span class="stat-value">{result.stats.totalChecked} items</span>
<span class="stat-detail">checked for containment</span>
</div>
<div class="stat-card inside">
<span class="stat-label">Inside</span>
<span class="stat-value">{result.stats.inside}</span>
<span class="stat-detail">fully contained</span>
</div>
<div class="stat-card equal">
<span class="stat-label">Equal</span>
<span class="stat-value">{result.stats.equal}</span>
<span class="stat-detail">exact matches</span>
</div>
<div class="stat-card partial">
<span class="stat-label">Partial</span>
<span class="stat-value">{result.stats.partial}</span>
<span class="stat-detail">partial overlap</span>
</div>
<div class="stat-card outside">
<span class="stat-label">Outside</span>
<span class="stat-value">{result.stats.outside}</span>
<span class="stat-detail">no overlap</span>
</div>
</div>
</div>
<!-- Containment Results Table -->
<div class="table-section">
<h4>Containment Results</h4>
<div class="results-table">
<div class="table-header">
<div class="col-input">Candidate</div>
<div class="col-status">Status</div>
<div class="col-coverage">Coverage</div>
<div class="col-containers">Containers</div>
<div class="col-gaps">Gaps</div>
</div>
{#each result.checks as check, index (`${check.input}-${index}`)}
<div class="visualization-list">
{#each result.visualization as viz, index (viz.candidate)}
{@const check = result.checks[index]}
{@const statusInfo = getStatusInfo(check.status)}
<div class="table-row status-{check.status}">
<div class="col-input">
<code class="candidate-input">{check.input}</code>
</div>
<div class="col-status">
<div class="status-badge" style="color: {statusInfo.color}">
<div class="viz-item status-{check.status}">
<div class="viz-header">
<code class="viz-candidate">{viz.candidate}</code>
<div class="viz-status" style="color: {statusInfo.color}">
<Icon name={statusInfo.icon} size="sm" />
{statusInfo.label}
{statusInfo.label} ({check.coverage}%)
</div>
</div>
<div class="col-coverage">
<div class="coverage-bar">
<div class="viz-bar-container">
<!-- Candidate base -->
<div class="viz-bar candidate-bar">
<div
class="coverage-fill"
style="width: {check.coverage}%; background-color: {statusInfo.color}"
class="viz-segment candidate-segment"
style="width: {getBarWidth(viz.candidateRange, viz.totalRange)}%; left: {getBarOffset(
viz.candidateRange,
viz.totalRange,
)}%"
use:tooltip={{ text: getSegmentTooltip(viz.candidateRange, 'candidate'), position: 'top' }}
></div>
<span class="coverage-text">{check.coverage}%</span>
</div>
</div>
<div class="col-containers">
{#if check.matchingContainers.length > 0}
<div class="container-list">
{#each check.matchingContainers as container (container)}
<code class="container-item">{container}</code>
{/each}
</div>
{:else}
<span class="no-containers">-</span>
{/if}
</div>
<div class="col-gaps">
{#if check.gaps.length > 0}
<div class="gaps-list">
{#each check.gaps as gap (gap)}
<code class="gap-item">{gap}</code>
{/each}
</div>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[`gaps-${check.input}`]}
onclick={() => copyToClipboard(check.gaps.join('\n'), `gaps-${check.input}`)}
>
<Icon name={copiedStates[`gaps-${check.input}`] ? 'check' : 'copy'} size="xs" />
</button>
{:else}
<span class="no-gaps">-</span>
{/if}
</div>
</div>
{/each}
</div>
</div>
<!-- Visualization -->
{#if result.visualization.length > 0}
<div class="visualization-section">
<h4>Containment Visualization</h4>
<div class="viz-legend">
<div class="legend-item">
<div class="legend-color candidate-color"></div>
<span>Candidate Range</span>
</div>
<div class="legend-item">
<div class="legend-color container-color"></div>
<span>Container Coverage</span>
</div>
<div class="legend-item">
<div class="legend-color gap-color"></div>
<span>Uncovered Gaps</span>
</div>
</div>
<div class="visualization-list">
{#each result.visualization as viz, index (viz.candidate)}
{@const check = result.checks[index]}
{@const statusInfo = getStatusInfo(check.status)}
<div class="viz-item status-{check.status}">
<div class="viz-header">
<code class="viz-candidate">{viz.candidate}</code>
<div class="viz-status" style="color: {statusInfo.color}">
<Icon name={statusInfo.icon} size="sm" />
{statusInfo.label} ({check.coverage}%)
</div>
</div>
<div class="viz-bar-container">
<!-- Candidate base -->
<div class="viz-bar candidate-bar">
<!-- Container overlays -->
<div class="viz-bar container-bar">
{#each viz.containers as container (`${container.start}-${container.end}`)}
<div
class="viz-segment candidate-segment"
style="width: {getBarWidth(viz.candidateRange, viz.totalRange)}%; left: {getBarOffset(
viz.candidateRange,
class="viz-segment container-segment"
style="width: {getBarWidth(container, viz.totalRange)}%; left: {getBarOffset(
container,
viz.totalRange,
)}%"
use:tooltip={{ text: getSegmentTooltip(viz.candidateRange, 'candidate'), position: 'top' }}
use:tooltip={{ text: getSegmentTooltip(container, 'container'), position: 'top' }}
></div>
</div>
{/each}
</div>
<!-- Container overlays -->
<div class="viz-bar container-bar">
{#each viz.containers as container (`${container.start}-${container.end}`)}
<div
class="viz-segment container-segment"
style="width: {getBarWidth(container, viz.totalRange)}%; left: {getBarOffset(
container,
viz.totalRange,
)}%"
use:tooltip={{ text: getSegmentTooltip(container, 'container'), position: 'top' }}
></div>
{/each}
</div>
<!-- Gap highlights -->
<div class="viz-bar gap-bar">
{#each viz.gaps as gap (`${gap.start}-${gap.end}`)}
<div
class="viz-segment gap-segment"
style="width: {getBarWidth(gap, viz.totalRange)}%; left: {getBarOffset(gap, viz.totalRange)}%"
use:tooltip={{ text: getSegmentTooltip(gap, 'gap'), position: 'bottom' }}
></div>
{/each}
</div>
<!-- Gap highlights -->
<div class="viz-bar gap-bar">
{#each viz.gaps as gap (`${gap.start}-${gap.end}`)}
<div
class="viz-segment gap-segment"
style="width: {getBarWidth(gap, viz.totalRange)}%; left: {getBarOffset(gap, viz.totalRange)}%"
use:tooltip={{ text: getSegmentTooltip(gap, 'gap'), position: 'bottom' }}
></div>
{/each}
</div>
</div>
{/each}
</div>
</div>
{/each}
</div>
{/if}
</div>
{/if}
</div>
{/if}
</div>
{/if}
</div>
{/if}
<style lang="scss">
/* Reuse base styles from previous components */
@@ -562,6 +543,7 @@
height: 140px;
font-family: var(--font-mono);
font-size: var(--font-size-sm);
background: var(--bg-primary);
resize: vertical;
&.set-a {
@@ -694,7 +676,7 @@
/* Stats grid */
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: var(--spacing-md);
margin-bottom: var(--spacing-lg);
}
+27 -29
View File
@@ -1,14 +1,16 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { cidrDeaggregate, getSubnetSize, type DeaggregateResult } from '$lib/utils/cidr-deaggregate.js';
import { formatNumber } from '$lib/utils/formatters';
import '../../../styles/diagnostics-pages.scss';
let input = $state(`192.168.0.0/22
10.0.0.0-10.0.0.255`);
let targetPrefix = $state(24);
let result = $state<DeaggregateResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let _selectedExample = $state<string | null>(null);
let selectedExampleIndex = $state<number | null>(null);
let _userModified = $state(false);
@@ -76,23 +78,11 @@
performDeaggregation();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
async function copyAllSubnets() {
if (!result?.subnets.length) return;
const allText = result.subnets.join('\n');
await copyToClipboard(allText, 'all-subnets');
await clipboard.copy(allText, 'all-subnets');
}
// Calculate on component load
@@ -168,7 +158,7 @@
<div class="prefix-info">
{#if targetPrefix}
{@const addresses = getSubnetSize(targetPrefix)}
Each /{targetPrefix} subnet = {addresses.toLocaleString()} addresses
Each /{targetPrefix} subnet = {formatNumber(addresses)} addresses
{/if}
</div>
</div>
@@ -189,13 +179,16 @@
</span>
<span class="metric">
<Icon name="database" size="sm" />
{result.totalAddresses.toLocaleString()} addresses
{formatNumber(result.totalAddresses)} addresses
</span>
</div>
{#if result.subnets.length > 0}
<button class="copy-all-button {copiedStates['all-subnets'] ? 'copied' : ''}" onclick={copyAllSubnets}>
<Icon name={copiedStates['all-subnets'] ? 'check' : 'copy'} size="sm" />
{copiedStates['all-subnets'] ? 'Copied!' : 'Copy All'}
<button
class="copy-all-button {clipboard.isCopied('all-subnets') ? 'copied' : ''}"
onclick={copyAllSubnets}
>
<Icon name={clipboard.isCopied('all-subnets') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('all-subnets') ? 'Copied!' : 'Copy All'}
</button>
{/if}
</div>
@@ -206,13 +199,13 @@
<div class="summary-item">
<span class="summary-label" use:tooltip={'Original networks, ranges, and addresses provided'}>Input:</span>
<span class="summary-value">
{result.inputSummary.totalInputs} items, {result.inputSummary.totalInputAddresses.toLocaleString()} addresses
{result.inputSummary.totalInputs} items, {formatNumber(result.inputSummary.totalInputAddresses)} addresses
</span>
</div>
<div class="summary-item">
<span class="summary-label" use:tooltip={'Uniform subnets generated from input'}>Output:</span>
<span class="summary-value">
{result.totalSubnets} /{targetPrefix} subnets, {result.totalAddresses.toLocaleString()} addresses
{result.totalSubnets} /{targetPrefix} subnets, {formatNumber(result.totalAddresses)} addresses
</span>
</div>
{#if result.totalAddresses !== result.inputSummary.totalInputAddresses}
@@ -221,9 +214,9 @@
>Note:</span
>
<span class="summary-value address-diff">
{result.totalAddresses > result.inputSummary.totalInputAddresses ? 'Expanded' : 'Reduced'} by {Math.abs(
result.totalAddresses - result.inputSummary.totalInputAddresses,
).toLocaleString()} addresses (due to alignment to /{targetPrefix} boundaries)
{result.totalAddresses > result.inputSummary.totalInputAddresses ? 'Expanded' : 'Reduced'} by {formatNumber(
Math.abs(result.totalAddresses - result.inputSummary.totalInputAddresses),
)} addresses (due to alignment to /{targetPrefix} boundaries)
</span>
</div>
{/if}
@@ -237,16 +230,16 @@
<div class="subnet-header">
<code class="subnet-cidr">{subnet}</code>
<button
class="copy-button {copiedStates[`subnet-${index}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(subnet, `subnet-${index}`)}
class="copy-button {clipboard.isCopied(`subnet-${index}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(subnet, `subnet-${index}`)}
aria-label="Copy CIDR block"
>
<Icon name={copiedStates[`subnet-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`subnet-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
<div class="subnet-info">
<span class="address-count">
{subnetSize.toLocaleString()} addresses
{formatNumber(subnetSize)} addresses
</span>
{#if subnetSize >= 256}
<span class="subnet-size">
@@ -330,7 +323,7 @@
gap: var(--spacing-md);
h3 {
color: var(--color-success-light);
color: var(--color-primary);
margin: 0;
}
}
@@ -553,4 +546,9 @@
justify-content: center;
}
}
input,
textarea {
background: var(--bg-primary);
}
</style>
+284 -308
View File
@@ -1,8 +1,10 @@
<script lang="ts">
import { computeCIDRDifference, type DiffResult, type AlignmentMode } from '$lib/utils/cidr-diff.js';
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import { formatNumber } from '$lib/utils/formatters';
let setA = $state(`192.168.1.0/24
192.168.2.0/24`);
@@ -11,7 +13,7 @@
let alignment = $state<AlignmentMode>('minimal');
let constrainedPrefix = $state(24);
let result = $state<DiffResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let userModified = $state(false);
@@ -64,17 +66,6 @@
performDiff();
}
/* Copy to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
/* Copy all results */
function copyAllResults(format: 'text' | 'json') {
if (!result) return;
@@ -101,7 +92,7 @@
content = sections.join('\n');
}
copyToClipboard(content, `all-${format}`);
clipboard.copy(content, `all-${format}`);
}
/* Clear inputs */
@@ -181,7 +172,7 @@
: 'IPv6';
const size = range.end - range.start + 1n;
return `Set ${type}\nRange: ${startIP} - ${endIP}\nSize: ${size.toLocaleString()}${range.cidr ? `\nCIDR: ${range.cidr}` : ''}`;
return `Set ${type}\nRange: ${startIP} - ${endIP}\nSize: ${formatNumber(Number(size))}${range.cidr ? `\nCIDR: ${range.cidr}` : ''}`;
}
// Track user modifications
@@ -199,327 +190,311 @@
});
</script>
<div class="card">
<header class="card-header">
<h2>CIDR Difference Calculator</h2>
<p>
Compute A - B where A and B are sets of IP addresses, CIDR blocks, or ranges. Shows minimal non-overlapping
results.
</p>
</header>
<!-- Alignment Mode -->
<div class="mode-section">
<h3>Alignment Mode</h3>
<div class="tabs-container">
<div class="tabs">
{#each alignmentModes as mode (mode.value)}
<button
type="button"
class="tab"
class:active={alignment === mode.value}
onclick={() => (alignment = mode.value)}
use:tooltip={{ text: mode.description, position: 'top' }}
>
{mode.label}
</button>
{/each}
</div>
{#if alignment === 'constrained'}
<div class="constraint-input">
<label
for="constrained-prefix"
use:tooltip={{ text: 'Force alignment to this prefix boundary', position: 'top' }}
>
Constrained prefix length
</label>
<input
id="constrained-prefix"
type="number"
bind:value={constrainedPrefix}
oninput={() => (userModified = true)}
min="8"
max="30"
class="input-field constraint-field"
/>
</div>
{/if}
<!-- Alignment Mode -->
<div class="mode-section">
<h3>Alignment Mode</h3>
<div class="tabs-container">
<div class="tabs">
{#each alignmentModes as mode (mode.value)}
<button
type="button"
class="tab"
class:active={alignment === mode.value}
onclick={() => (alignment = mode.value)}
use:tooltip={{ text: mode.description, position: 'top' }}
>
{mode.label}
</button>
{/each}
</div>
{#if alignment === 'constrained'}
<div class="constraint-input">
<label
for="constrained-prefix"
use:tooltip={{ text: 'Force alignment to this prefix boundary', position: 'top' }}
>
Constrained prefix length
</label>
<input
id="constrained-prefix"
type="number"
bind:value={constrainedPrefix}
oninput={() => (userModified = true)}
min="8"
max="30"
class="input-field constraint-field"
/>
</div>
{/if}
</div>
</div>
<!-- Input Section -->
<div class="input-section">
<div class="input-grid">
<!-- Set A -->
<div class="input-group">
<h3 use:tooltip={{ text: 'The base set of IP addresses, CIDR blocks, or ranges', position: 'top' }}>
Set A (Base)
</h3>
<div class="input-wrapper">
<textarea
bind:value={setA}
oninput={() => (userModified = true)}
placeholder="192.168.1.0/24&#10;10.0.0.0-10.0.0.100"
class="input-textarea set-a"
rows="6"
></textarea>
</div>
</div>
<!-- Set B -->
<div class="input-group">
<h3 use:tooltip={{ text: 'The set to subtract from Set A (can be empty)', position: 'top' }}>
Set B (Subtract)
</h3>
<div class="input-wrapper">
<textarea
bind:value={setB}
oninput={() => (userModified = true)}
placeholder="192.168.1.128/25&#10;10.0.0.50-10.0.0.75"
class="input-textarea set-b"
rows="6"
></textarea>
</div>
<!-- Input Section -->
<div class="input-section">
<div class="input-grid">
<!-- Set A -->
<div class="input-group">
<h3 use:tooltip={{ text: 'The base set of IP addresses, CIDR blocks, or ranges', position: 'top' }}>
Set A (Base)
</h3>
<div class="input-wrapper">
<textarea
bind:value={setA}
oninput={() => (userModified = true)}
placeholder="192.168.1.0/24&#10;10.0.0.0-10.0.0.100"
class="input-textarea set-a"
rows="6"
></textarea>
</div>
</div>
<div class="input-actions">
<button
type="button"
class="btn btn-secondary btn-sm"
onclick={clearInputs}
use:tooltip={{ text: 'Clear both input sets', position: 'top' }}
>
<Icon name="trash" size="sm" />
</button>
</div>
<!-- Examples -->
<div class="examples-section">
<h4>
Quick Examples
<Tooltip text="Click any example to load it into the input fields">
<Icon name="help" size="sm" />
</Tooltip>
</h4>
<div class="examples-grid">
{#each examples as example (example.label)}
<button
type="button"
class="example-btn"
class:selected={selectedExample === example.label}
onclick={() => setExample(example)}
>
{example.label}
</button>
{/each}
<!-- Set B -->
<div class="input-group">
<h3 use:tooltip={{ text: 'The set to subtract from Set A (can be empty)', position: 'top' }}>Set B (Subtract)</h3>
<div class="input-wrapper">
<textarea
bind:value={setB}
oninput={() => (userModified = true)}
placeholder="192.168.1.128/25&#10;10.0.0.50-10.0.0.75"
class="input-textarea set-b"
rows="6"
></textarea>
</div>
</div>
</div>
<!-- Results Section -->
{#if result}
<div class="results-section">
{#if result.errors.length > 0}
<div class="info-panel error">
<h3>Parse Errors</h3>
<ul class="error-list">
{#each result.errors as error (error)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
<div class="input-actions">
<button
type="button"
class="btn btn-secondary btn-sm"
onclick={clearInputs}
use:tooltip={{ text: 'Clear both input sets', position: 'top' }}
>
<Icon name="trash" size="sm" />
</button>
</div>
{#if result.ipv4.length > 0 || result.ipv6.length > 0}
<!-- Statistics -->
<div class="stats-section">
<div class="summary-header">
<h3>Difference Results (A - B)</h3>
<div class="export-buttons">
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={copiedStates['all-text']}
onclick={() => copyAllResults('text')}
>
<Icon name={copiedStates['all-text'] ? 'check' : 'copy'} size="sm" />
Text
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={copiedStates['all-json']}
onclick={() => copyAllResults('json')}
>
<Icon name={copiedStates['all-json'] ? 'check' : 'download'} size="sm" />
JSON
</button>
</div>
</div>
<!-- Examples -->
<div class="examples-section">
<h4>
Quick Examples
<Tooltip text="Click any example to load it into the input fields">
<Icon name="help" size="sm" />
</Tooltip>
</h4>
<div class="examples-grid">
{#each examples as example (example.label)}
<button
type="button"
class="example-btn"
class:selected={selectedExample === example.label}
onclick={() => setExample(example)}
>
{example.label}
</button>
{/each}
</div>
</div>
</div>
<div class="stats-grid">
<div class="stat-card input-a">
<span class="stat-label">Set A (Input)</span>
<span class="stat-value">{result.stats.inputA.count} items</span>
<span class="stat-detail">{result.stats.inputA.addresses} addresses</span>
</div>
<div class="stat-card input-b">
<span class="stat-label">Set B (Subtract)</span>
<span class="stat-value">{result.stats.inputB.count} items</span>
<span class="stat-detail">{result.stats.inputB.addresses} addresses</span>
</div>
<div class="stat-card result">
<span class="stat-label">Result (A - B)</span>
<span class="stat-value">{result.stats.output.count} CIDRs</span>
<span class="stat-detail">{result.stats.output.addresses} addresses</span>
</div>
<div
class="stat-card efficiency"
data-efficiency={result.stats.efficiency >= 80
? 'high'
: result.stats.efficiency >= 50
? 'medium'
: 'low'}
<!-- Results Section -->
{#if result}
<div class="results-section">
{#if result.errors.length > 0}
<div class="info-panel error">
<h3>Parse Errors</h3>
<ul class="error-list">
{#each result.errors as error (error)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
{#if result.ipv4.length > 0 || result.ipv6.length > 0}
<!-- Statistics -->
<div class="stats-section">
<div class="summary-header">
<h3>Difference Results (A - B)</h3>
<div class="export-buttons">
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={clipboard.isCopied('all-text')}
onclick={() => copyAllResults('text')}
>
<span class="stat-label">Efficiency</span>
<span class="stat-value">{result.stats.efficiency}%</span>
<span class="stat-detail">{result.stats.removed.addresses} removed</span>
</div>
<Icon name={clipboard.isCopied('all-text') ? 'check' : 'copy'} size="sm" />
Text
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={clipboard.isCopied('all-json')}
onclick={() => copyAllResults('json')}
>
<Icon name={clipboard.isCopied('all-json') ? 'check' : 'download'} size="sm" />
JSON
</button>
</div>
</div>
<!-- Visualization -->
{#if result.visualization.setA.length > 0}
<div class="visualization-section">
<h4>
Set Operation Visualization
<Tooltip text="Visual representation showing the relationship between sets A, B, and the result">
<Icon name="help" size="sm" />
</Tooltip>
</h4>
<div class="viz-legend">
<div class="legend-item">
<div class="legend-color set-a-color"></div>
<span>Set A (Base)</span>
</div>
<div class="legend-item">
<div class="legend-color set-b-color"></div>
<span>Set B (Subtract)</span>
</div>
<div class="legend-item">
<div class="legend-color result-color"></div>
<span>Result (A - B)</span>
</div>
<div class="stats-grid">
<div class="stat-card input-a">
<span class="stat-label">Set A (Input)</span>
<span class="stat-value">{result.stats.inputA.count} items</span>
<span class="stat-detail">{result.stats.inputA.addresses} addresses</span>
</div>
<div class="stat-card input-b">
<span class="stat-label">Set B (Subtract)</span>
<span class="stat-value">{result.stats.inputB.count} items</span>
<span class="stat-detail">{result.stats.inputB.addresses} addresses</span>
</div>
<div class="stat-card result">
<span class="stat-label">Result (A - B)</span>
<span class="stat-value">{result.stats.output.count} CIDRs</span>
<span class="stat-detail">{result.stats.output.addresses} addresses</span>
</div>
<div
class="stat-card efficiency"
data-efficiency={result.stats.efficiency >= 80 ? 'high' : result.stats.efficiency >= 50 ? 'medium' : 'low'}
>
<span class="stat-label">Efficiency</span>
<span class="stat-value">{result.stats.efficiency}%</span>
<span class="stat-detail">{result.stats.removed.addresses} removed</span>
</div>
</div>
</div>
<!-- Visualization -->
{#if result.visualization.setA.length > 0}
<div class="visualization-section">
<h4>
Set Operation Visualization
<Tooltip text="Visual representation showing the relationship between sets A, B, and the result">
<Icon name="help" size="sm" />
</Tooltip>
</h4>
<div class="viz-legend">
<div class="legend-item">
<div class="legend-color set-a-color"></div>
<span>Set A (Base)</span>
</div>
<div class="legend-item">
<div class="legend-color set-b-color"></div>
<span>Set B (Subtract)</span>
</div>
<div class="legend-item">
<div class="legend-color result-color"></div>
<span>Result (A - B)</span>
</div>
</div>
<div class="visualization-bar">
<!-- Set A (background) -->
{#each result.visualization.setA as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-a-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'A'), position: 'top' }}
></div>
{/each}
<div class="visualization-bar">
<!-- Set A (background) -->
{#each result.visualization.setA as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-a-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'A'), position: 'top' }}
></div>
{/each}
<!-- Set B (overlay) -->
{#each result.visualization.setB as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-b-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'B'), position: 'top' }}
></div>
{/each}
<!-- Set B (overlay) -->
{#each result.visualization.setB as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-b-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'B'), position: 'top' }}
></div>
{/each}
<!-- Result (final) -->
{#each result.visualization.result as range (`${range.start}-${range.end}`)}
<div
class="viz-segment result-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'result'), position: 'bottom' }}
></div>
<!-- Result (final) -->
{#each result.visualization.result as range (`${range.start}-${range.end}`)}
<div
class="viz-segment result-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'result'), position: 'bottom' }}
></div>
{/each}
</div>
</div>
{/if}
<!-- Results Grid -->
<div class="results-grid">
<!-- IPv4 Results -->
{#if result.ipv4.length > 0}
<div class="result-panel ipv4">
<div class="panel-header">
<h4>IPv4 Results ({result.ipv4.length})</h4>
<button
type="button"
class="btn btn-icon"
class:copied={clipboard.isCopied('ipv4')}
onclick={() => clipboard.copy((result?.ipv4 || []).join('\n'), 'ipv4')}
>
<Icon name={clipboard.isCopied('ipv4') ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="cidr-list">
{#each result.ipv4 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={clipboard.isCopied(cidr)}
onclick={() => clipboard.copy(cidr, cidr)}
>
<Icon name={clipboard.isCopied(cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
</div>
</div>
{/if}
<!-- Results Grid -->
<div class="results-grid">
<!-- IPv4 Results -->
{#if result.ipv4.length > 0}
<div class="result-panel ipv4">
<div class="panel-header">
<h4>IPv4 Results ({result.ipv4.length})</h4>
<button
type="button"
class="btn btn-icon"
class:copied={copiedStates['ipv4']}
onclick={() => copyToClipboard((result?.ipv4 || []).join('\n'), 'ipv4')}
>
<Icon name={copiedStates['ipv4'] ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="cidr-list">
{#each result.ipv4 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[cidr]}
onclick={() => copyToClipboard(cidr, cidr)}
>
<Icon name={copiedStates[cidr] ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
</div>
<!-- IPv6 Results -->
{#if result.ipv6.length > 0}
<div class="result-panel ipv6">
<div class="panel-header">
<h4>IPv6 Results ({result.ipv6.length})</h4>
<button
type="button"
class="btn btn-icon"
class:copied={clipboard.isCopied('ipv6')}
onclick={() => clipboard.copy((result?.ipv6 || []).join('\n'), 'ipv6')}
>
<Icon name={clipboard.isCopied('ipv6') ? 'check' : 'copy'} size="sm" />
</button>
</div>
{/if}
<!-- IPv6 Results -->
{#if result.ipv6.length > 0}
<div class="result-panel ipv6">
<div class="panel-header">
<h4>IPv6 Results ({result.ipv6.length})</h4>
<button
type="button"
class="btn btn-icon"
class:copied={copiedStates['ipv6']}
onclick={() => copyToClipboard((result?.ipv6 || []).join('\n'), 'ipv6')}
>
<Icon name={copiedStates['ipv6'] ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="cidr-list">
{#each result.ipv6 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[cidr]}
onclick={() => copyToClipboard(cidr, cidr)}
>
<Icon name={copiedStates[cidr] ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
</div>
<div class="cidr-list">
{#each result.ipv6 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={clipboard.isCopied(cidr)}
onclick={() => clipboard.copy(cidr, cidr)}
>
<Icon name={clipboard.isCopied(cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
</div>
{/if}
</div>
{:else}
<div class="info-panel info">
<h3>No Results</h3>
<p>The difference A - B resulted in an empty set. Set B completely contains or covers Set A.</p>
</div>
{/if}
</div>
{/if}
</div>
</div>
{/if}
</div>
{:else}
<div class="info-panel info">
<h3>No Results</h3>
<p>The difference A - B resulted in an empty set. Set B completely contains or covers Set A.</p>
</div>
{/if}
</div>
{/if}
<style lang="scss">
/* Reusable tokens */
@@ -629,6 +604,7 @@
font-family: var(--font-mono);
font-size: var(--font-size-sm);
resize: vertical;
background: var(--bg-primary);
border-left: 4px solid var(--color-primary);
}
+290 -305
View File
@@ -3,6 +3,8 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let setA = $state(`192.168.1.0/24
10.0.0.0/16`);
@@ -11,7 +13,7 @@
let mergeInputs = $state(true);
let showOnlyBoolean = $state(false);
let result = $state<OverlapResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let userModified = $state(false);
@@ -49,17 +51,6 @@
performOverlapCheck();
}
/* Copy to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
/* Copy all results */
function copyAllResults(format: 'text' | 'json') {
if (!result) return;
@@ -87,7 +78,7 @@
content = lines.join('\n');
}
copyToClipboard(content, `all-${format}`);
clipboard.copy(content, `all-${format}`);
}
/* Clear inputs */
@@ -167,7 +158,7 @@
const label = type === 'A' ? 'Set A' : type === 'B' ? 'Set B' : 'Intersection';
return `${label}\nRange: ${startIP} - ${endIP}\nSize: ${size.toLocaleString()}${range.cidr ? `\nCIDR: ${range.cidr}` : ''}`;
return `${label}\nRange: ${startIP} - ${endIP}\nSize: ${formatNumber(Number(size))}${range.cidr ? `\nCIDR: ${range.cidr}` : ''}`;
}
// Track user modifications
@@ -185,321 +176,314 @@
});
</script>
<div class="card">
<header class="card-header">
<h2>CIDR Overlap Checker</h2>
<p>Determine if two sets of IP addresses, CIDR blocks, or ranges intersect and show the overlapping regions.</p>
</header>
<!-- Options -->
<div class="options-section">
<h3>Options</h3>
<div class="options-grid">
<label class="checkbox-label">
<input type="checkbox" bind:checked={mergeInputs} onchange={() => (userModified = true)} />
<span class="checkbox-text">
Merge overlapping inputs first
<Tooltip text="Combine overlapping ranges within each set before comparison">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
<label class="checkbox-label">
<input type="checkbox" bind:checked={showOnlyBoolean} onchange={() => (userModified = true)} />
<span class="checkbox-text">
Show only boolean result
<Tooltip text="Display just yes/no overlap instead of detailed intersection blocks">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
</div>
<!-- Options -->
<div class="options-section">
<h3>Options</h3>
<div class="options-grid">
<label class="checkbox-label">
<input type="checkbox" bind:checked={mergeInputs} onchange={() => (userModified = true)} />
<span class="checkbox-text">
Merge overlapping inputs first
<Tooltip text="Combine overlapping ranges within each set before comparison">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
<label class="checkbox-label">
<input type="checkbox" bind:checked={showOnlyBoolean} onchange={() => (userModified = true)} />
<span class="checkbox-text">
Show only boolean result
<Tooltip text="Display just yes/no overlap instead of detailed intersection blocks">
<Icon name="help" size="sm" />
</Tooltip>
</span>
</label>
</div>
</div>
<!-- Input Section -->
<div class="input-section">
<div class="input-grid">
<!-- Set A -->
<div class="input-group">
<h3>
Set A
<Tooltip text="First set of IP addresses, CIDR blocks, or ranges">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setA}
oninput={() => (userModified = true)}
placeholder="192.168.1.0/24&#10;10.0.0.0-10.0.0.100"
class="input-textarea set-a"
rows="6"
></textarea>
</div>
</div>
<!-- Set B -->
<div class="input-group">
<h3>
Set B
<Tooltip text="Second set of IP addresses, CIDR blocks, or ranges">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setB}
oninput={() => (userModified = true)}
placeholder="192.168.1.128/25&#10;10.0.0.50-10.0.0.150"
class="input-textarea set-b"
rows="6"
></textarea>
</div>
<!-- Input Section -->
<div class="input-section">
<div class="input-grid">
<!-- Set A -->
<div class="input-group">
<h3>
Set A
<Tooltip text="First set of IP addresses, CIDR blocks, or ranges">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setA}
oninput={() => (userModified = true)}
placeholder="192.168.1.0/24&#10;10.0.0.0-10.0.0.100"
class="input-textarea set-a"
rows="6"
></textarea>
</div>
</div>
<div class="input-actions">
<button type="button" class="btn btn-secondary btn-sm" onclick={clearInputs}>
<Icon name="trash" size="sm" />
Clear All
</button>
</div>
<!-- Examples -->
<div class="examples-section">
<h4>Quick Examples</h4>
<div class="examples-grid">
{#each examples as example (example.label)}
<button
type="button"
class="example-btn"
class:selected={selectedExample === example.label}
onclick={() => setExample(example)}
>
{example.label}
</button>
{/each}
<!-- Set B -->
<div class="input-group">
<h3>
Set B
<Tooltip text="Second set of IP addresses, CIDR blocks, or ranges">
<Icon name="help" size="sm" />
</Tooltip>
</h3>
<div class="input-wrapper">
<textarea
bind:value={setB}
oninput={() => (userModified = true)}
placeholder="192.168.1.128/25&#10;10.0.0.50-10.0.0.150"
class="input-textarea set-b"
rows="6"
></textarea>
</div>
</div>
</div>
<!-- Results Section -->
{#if result}
<div class="results-section">
{#if result.errors.length > 0}
<div class="info-panel error">
<h3>Parse Errors</h3>
<ul class="error-list">
{#each result.errors as error (error)}
<li>{error}</li>
{/each}
</ul>
<div class="input-actions">
<button type="button" class="btn btn-secondary btn-sm" onclick={clearInputs}>
<Icon name="trash" size="sm" />
Clear All
</button>
</div>
<!-- Examples -->
<div class="examples-section">
<h4>Quick Examples</h4>
<div class="examples-grid">
{#each examples as example (example.label)}
<button
type="button"
class="example-btn"
class:selected={selectedExample === example.label}
onclick={() => setExample(example)}
>
{example.label}
</button>
{/each}
</div>
</div>
</div>
<!-- Results Section -->
{#if result}
<div class="results-section">
{#if result.errors.length > 0}
<div class="info-panel error">
<h3>Parse Errors</h3>
<ul class="error-list">
{#each result.errors as error (error)}
<li>{error}</li>
{/each}
</ul>
</div>
{/if}
<!-- Overlap Status -->
<div class="status-section">
<div class="status-card {result.hasOverlap ? 'overlap' : 'no-overlap'}">
<div class="status-icon">
<Icon name={result.hasOverlap ? 'check-circle' : 'x-circle'} size="lg" />
</div>
<div class="status-content">
<h3>{result.hasOverlap ? 'Overlap Detected' : 'No Overlap'}</h3>
<p>
{result.hasOverlap
? `Sets A and B have overlapping address ranges (${result.stats.overlapPercent}% of smaller set)`
: 'Sets A and B do not share any common address ranges'}
</p>
</div>
</div>
</div>
{#if !showOnlyBoolean && (result.ipv4.length > 0 || result.ipv6.length > 0)}
<!-- Statistics -->
<div class="stats-section">
<div class="summary-header">
<h3>Intersection Results (A ∩ B)</h3>
<div class="export-buttons">
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={clipboard.isCopied('all-text')}
onclick={() => copyAllResults('text')}
>
<Icon name={clipboard.isCopied('all-text') ? 'check' : 'copy'} size="sm" />
Text
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={clipboard.isCopied('all-json')}
onclick={() => copyAllResults('json')}
>
<Icon name={clipboard.isCopied('all-json') ? 'check' : 'download'} size="sm" />
JSON
</button>
</div>
</div>
<div class="stats-grid">
<div class="stat-card set-a">
<span class="stat-label">Set A</span>
<span class="stat-value">{result.stats.setA.count} items</span>
<span class="stat-detail">{result.stats.setA.addresses} addresses</span>
</div>
<div class="stat-card set-b">
<span class="stat-label">Set B</span>
<span class="stat-value">{result.stats.setB.count} items</span>
<span class="stat-detail">{result.stats.setB.addresses} addresses</span>
</div>
<div class="stat-card intersection">
<span class="stat-label">Intersection</span>
<span class="stat-value">{result.stats.intersection.count} CIDRs</span>
<span class="stat-detail">{result.stats.intersection.addresses} addresses</span>
</div>
<div class="stat-card overlap-percent">
<span class="stat-label">Overlap</span>
<span class="stat-value">{result.stats.overlapPercent}%</span>
<span class="stat-detail">of smaller set</span>
</div>
</div>
</div>
<!-- Visualization -->
{#if result.visualization.setA.length > 0 || result.visualization.setB.length > 0}
<div class="visualization-section">
<h4>Overlap Visualization</h4>
<div class="viz-legend">
<div class="legend-item">
<div class="legend-color set-a-color"></div>
<span>Set A</span>
</div>
<div class="legend-item">
<div class="legend-color set-b-color"></div>
<span>Set B</span>
</div>
<div class="legend-item">
<div class="legend-color intersection-color"></div>
<span>Intersection (A ∩ B)</span>
</div>
</div>
<div class="visualization-stack">
<!-- Set A Bar -->
<div class="viz-bar set-a-bar">
<div class="bar-label">Set A</div>
<div class="bar-segments">
{#each result.visualization.setA as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-a-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'A'), position: 'top' }}
></div>
{/each}
</div>
</div>
<!-- Set B Bar -->
<div class="viz-bar set-b-bar">
<div class="bar-label">Set B</div>
<div class="bar-segments">
{#each result.visualization.setB as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-b-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'B'), position: 'top' }}
></div>
{/each}
</div>
</div>
<!-- Intersection Highlights -->
<div class="viz-bar intersection-bar">
<div class="bar-label">A ∩ B</div>
<div class="bar-segments">
{#each result.visualization.intersection as range (`${range.start}-${range.end}`)}
<div
class="viz-segment intersection-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'intersection'), position: 'bottom' }}
></div>
{/each}
</div>
</div>
</div>
</div>
{/if}
<!-- Overlap Status -->
<div class="status-section">
<div class="status-card {result.hasOverlap ? 'overlap' : 'no-overlap'}">
<div class="status-icon">
<Icon name={result.hasOverlap ? 'check-circle' : 'x-circle'} size="lg" />
</div>
<div class="status-content">
<h3>{result.hasOverlap ? 'Overlap Detected' : 'No Overlap'}</h3>
<p>
{result.hasOverlap
? `Sets A and B have overlapping address ranges (${result.stats.overlapPercent}% of smaller set)`
: 'Sets A and B do not share any common address ranges'}
</p>
</div>
</div>
</div>
{#if !showOnlyBoolean && (result.ipv4.length > 0 || result.ipv6.length > 0)}
<!-- Statistics -->
<div class="stats-section">
<div class="summary-header">
<h3>Intersection Results (A ∩ B)</h3>
<div class="export-buttons">
<!-- Results Grid -->
<div class="results-grid">
<!-- IPv4 Results -->
{#if result.ipv4.length > 0}
<div class="result-panel ipv4">
<div class="panel-header">
<h4>IPv4 Intersection ({result.ipv4.length})</h4>
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={copiedStates['all-text']}
onclick={() => copyAllResults('text')}
class="btn btn-icon"
class:copied={clipboard.isCopied('ipv4')}
onclick={() => clipboard.copy((result?.ipv4 || []).join('\n'), 'ipv4')}
>
<Icon name={copiedStates['all-text'] ? 'check' : 'copy'} size="sm" />
Text
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={copiedStates['all-json']}
onclick={() => copyAllResults('json')}
>
<Icon name={copiedStates['all-json'] ? 'check' : 'download'} size="sm" />
JSON
<Icon name={clipboard.isCopied('ipv4') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
<div class="stats-grid">
<div class="stat-card set-a">
<span class="stat-label">Set A</span>
<span class="stat-value">{result.stats.setA.count} items</span>
<span class="stat-detail">{result.stats.setA.addresses} addresses</span>
</div>
<div class="stat-card set-b">
<span class="stat-label">Set B</span>
<span class="stat-value">{result.stats.setB.count} items</span>
<span class="stat-detail">{result.stats.setB.addresses} addresses</span>
</div>
<div class="stat-card intersection">
<span class="stat-label">Intersection</span>
<span class="stat-value">{result.stats.intersection.count} CIDRs</span>
<span class="stat-detail">{result.stats.intersection.addresses} addresses</span>
</div>
<div class="stat-card overlap-percent">
<span class="stat-label">Overlap</span>
<span class="stat-value">{result.stats.overlapPercent}%</span>
<span class="stat-detail">of smaller set</span>
</div>
</div>
</div>
<!-- Visualization -->
{#if result.visualization.setA.length > 0 || result.visualization.setB.length > 0}
<div class="visualization-section">
<h4>Overlap Visualization</h4>
<div class="viz-legend">
<div class="legend-item">
<div class="legend-color set-a-color"></div>
<span>Set A</span>
</div>
<div class="legend-item">
<div class="legend-color set-b-color"></div>
<span>Set B</span>
</div>
<div class="legend-item">
<div class="legend-color intersection-color"></div>
<span>Intersection (A ∩ B)</span>
</div>
</div>
<div class="visualization-stack">
<!-- Set A Bar -->
<div class="viz-bar set-a-bar">
<div class="bar-label">Set A</div>
<div class="bar-segments">
{#each result.visualization.setA as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-a-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'A'), position: 'top' }}
></div>
{/each}
<div class="cidr-list">
{#each result.ipv4 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={clipboard.isCopied(cidr)}
onclick={() => clipboard.copy(cidr, cidr)}
>
<Icon name={clipboard.isCopied(cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
<!-- Set B Bar -->
<div class="viz-bar set-b-bar">
<div class="bar-label">Set B</div>
<div class="bar-segments">
{#each result.visualization.setB as range (`${range.start}-${range.end}`)}
<div
class="viz-segment set-b-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'B'), position: 'top' }}
></div>
{/each}
</div>
</div>
<!-- Intersection Highlights -->
<div class="viz-bar intersection-bar">
<div class="bar-label">A ∩ B</div>
<div class="bar-segments">
{#each result.visualization.intersection as range (`${range.start}-${range.end}`)}
<div
class="viz-segment intersection-segment"
style="width: {getBarWidth(range)}%; left: {getBarOffset(range)}%"
use:tooltip={{ text: getSegmentTooltip(range, 'intersection'), position: 'bottom' }}
></div>
{/each}
</div>
</div>
{/each}
</div>
</div>
{/if}
<!-- Results Grid -->
<div class="results-grid">
<!-- IPv4 Results -->
{#if result.ipv4.length > 0}
<div class="result-panel ipv4">
<div class="panel-header">
<h4>IPv4 Intersection ({result.ipv4.length})</h4>
<button
type="button"
class="btn btn-icon"
class:copied={copiedStates['ipv4']}
onclick={() => copyToClipboard((result?.ipv4 || []).join('\n'), 'ipv4')}
>
<Icon name={copiedStates['ipv4'] ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="cidr-list">
{#each result.ipv4 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[cidr]}
onclick={() => copyToClipboard(cidr, cidr)}
>
<Icon name={copiedStates[cidr] ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
</div>
<!-- IPv6 Results -->
{#if result.ipv6.length > 0}
<div class="result-panel ipv6">
<div class="panel-header">
<h4>IPv6 Intersection ({result.ipv6.length})</h4>
<button
type="button"
class="btn btn-icon"
class:copied={clipboard.isCopied('ipv6')}
onclick={() => clipboard.copy((result?.ipv6 || []).join('\n'), 'ipv6')}
>
<Icon name={clipboard.isCopied('ipv6') ? 'check' : 'copy'} size="sm" />
</button>
</div>
{/if}
<!-- IPv6 Results -->
{#if result.ipv6.length > 0}
<div class="result-panel ipv6">
<div class="panel-header">
<h4>IPv6 Intersection ({result.ipv6.length})</h4>
<button
type="button"
class="btn btn-icon"
class:copied={copiedStates['ipv6']}
onclick={() => copyToClipboard((result?.ipv6 || []).join('\n'), 'ipv6')}
>
<Icon name={copiedStates['ipv6'] ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="cidr-list">
{#each result.ipv6 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[cidr]}
onclick={() => copyToClipboard(cidr, cidr)}
>
<Icon name={copiedStates[cidr] ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
</div>
<div class="cidr-list">
{#each result.ipv6 as cidr (cidr)}
<div class="cidr-item">
<code class="cidr-block">{cidr}</code>
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={clipboard.isCopied(cidr)}
onclick={() => clipboard.copy(cidr, cidr)}
>
<Icon name={clipboard.isCopied(cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
</div>
{/if}
</div>
{/if}
</div>
{/if}
</div>
</div>
{/if}
</div>
{/if}
</div>
{/if}
<style lang="scss">
/* Reusable tokens */
@@ -588,6 +572,7 @@
height: 140px;
font-family: var(--font-mono);
font-size: var(--font-size-sm);
background: var(--bg-primary);
resize: vertical;
&.set-a {
+8 -18
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { splitCIDRByCount, splitCIDRByPrefix, type SplitResult } from '$lib/utils/cidr-split.js';
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import Icon from '$lib/components/global/Icon.svelte';
import '../../../styles/diagnostics-pages.scss';
@@ -9,7 +10,7 @@
let subnetCount = $state(4);
let targetPrefix = $state(26);
let result = $state<SplitResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExampleIndex = $state<number | null>(null);
const modes = [
@@ -70,22 +71,11 @@
selectedExampleIndex = null;
}
/* Copy to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 1500);
} catch (err) {
console.error('Failed to copy:', err);
}
}
/* Copy all subnets */
function copyAllSubnets() {
if (!result?.subnets) return;
const text = result.subnets.map((s) => s.cidr).join('\n');
copyToClipboard(text, 'all-subnets');
clipboard.copy(text, 'all-subnets');
}
/* Clear input */
@@ -278,10 +268,10 @@
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={copiedStates['all-subnets']}
class:copied={clipboard.isCopied('all-subnets')}
onclick={copyAllSubnets}
>
<Icon name={copiedStates['all-subnets'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('all-subnets') ? 'check' : 'copy'} size="sm" />
Copy All CIDRs
</button>
</div>
@@ -340,10 +330,10 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[subnet.cidr]}
onclick={() => copyToClipboard(subnet.cidr, subnet.cidr)}
class:copied={clipboard.isCopied(subnet.cidr)}
onclick={() => clipboard.copy(subnet.cidr, subnet.cidr)}
>
<Icon name={copiedStates[subnet.cidr] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(subnet.cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
<div class="subnet-details">
+17 -27
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { summarizeCIDRs, type SummarizationResult } from '$lib/utils/cidr-summarization-fixed.js';
import { useClipboard } from '$lib/composables';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import SvgIcon from '$lib/components/global/SvgIcon.svelte';
@@ -11,7 +12,7 @@
2001:db8::/64`);
let mode = $state<'exact-merge' | 'minimal-cover'>('exact-merge');
let result = $state<SummarizationResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
const modes = [
@@ -74,17 +75,6 @@ fe80::/10`,
performSummarization();
}
/* Copy text to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
/* Copy all results */
function copyAllResults() {
if (!result) return;
@@ -97,7 +87,7 @@ fe80::/10`,
sections.push('IPv6:', ...result.ipv6);
}
copyToClipboard(sections.join('\n'), 'all-results');
clipboard.copy(sections.join('\n'), 'all-results');
}
/* Clear input */
@@ -238,10 +228,10 @@ fe80::/10`,
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={copiedStates['all-results']}
class:copied={clipboard.isCopied('all-results')}
onclick={copyAllResults}
>
<SvgIcon icon={copiedStates['all-results'] ? 'check' : 'clipboard'} size="md" />
<SvgIcon icon={clipboard.isCopied('all-results') ? 'check' : 'clipboard'} size="md" />
Copy All
</button>
</Tooltip>
@@ -257,10 +247,10 @@ fe80::/10`,
<button
type="button"
class="btn btn-icon"
class:copied={copiedStates['ipv4']}
onclick={() => copyToClipboard((result?.ipv4 || []).join('\n'), 'ipv4')}
class:copied={clipboard.isCopied('ipv4')}
onclick={() => clipboard.copy((result?.ipv4 || []).join('\n'), 'ipv4')}
>
<SvgIcon icon={copiedStates['ipv4'] ? 'check' : 'clipboard'} size="md" />
<SvgIcon icon={clipboard.isCopied('ipv4') ? 'check' : 'clipboard'} size="md" />
</button>
</Tooltip>
</div>
@@ -272,10 +262,10 @@ fe80::/10`,
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[cidr]}
onclick={() => copyToClipboard(cidr, cidr)}
class:copied={clipboard.isCopied(cidr)}
onclick={() => clipboard.copy(cidr, cidr)}
>
<SvgIcon icon={copiedStates[cidr] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied(cidr) ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -293,10 +283,10 @@ fe80::/10`,
<button
type="button"
class="btn btn-icon"
class:copied={copiedStates['ipv6']}
onclick={() => copyToClipboard((result?.ipv6 || []).join('\n'), 'ipv6')}
class:copied={clipboard.isCopied('ipv6')}
onclick={() => clipboard.copy((result?.ipv6 || []).join('\n'), 'ipv6')}
>
<SvgIcon icon={copiedStates['ipv6'] ? 'check' : 'clipboard'} size="md" />
<SvgIcon icon={clipboard.isCopied('ipv6') ? 'check' : 'clipboard'} size="md" />
</button>
</Tooltip>
</div>
@@ -308,10 +298,10 @@ fe80::/10`,
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[cidr]}
onclick={() => copyToClipboard(cidr, cidr)}
class:copied={clipboard.isCopied(cidr)}
onclick={() => clipboard.copy(cidr, cidr)}
>
<SvgIcon icon={copiedStates[cidr] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied(cidr) ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -2,6 +2,7 @@
import { COMMON_SUBNETS } from '$lib/constants/networks.js';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import SvgIcon from '$lib/components/global/SvgIcon.svelte';
import { formatNumber } from '$lib/utils/formatters';
import '../../styles/converters.scss';
import '../../styles/components.scss';
</script>
@@ -23,7 +24,7 @@
{#each COMMON_SUBNETS as subnet (subnet.cidr)}
<Tooltip
text="/{subnet.cidr} subnet with mask {subnet.mask} supports {subnet.hosts.toLocaleString()} hosts"
text="/{subnet.cidr} subnet with mask {subnet.mask} supports {formatNumber(subnet.hosts)} hosts"
position="top"
>
<div class="table-row">
@@ -34,7 +35,7 @@
{subnet.mask}
</span>
<span class="hosts-cell">
{subnet.hosts.toLocaleString()}
{formatNumber(subnet.hosts)}
</span>
<span class="usage-cell">
{#if subnet.cidr === 8}
@@ -257,7 +257,7 @@
onclick={() => (showPrivateKey = !showPrivateKey)}
use:tooltip={showPrivateKey ? 'Hide private key' : 'Show private key'}
>
<Icon name={showPrivateKey ? 'eye-off' : 'eye'} size="sm" />
<Icon name={showPrivateKey ? 'hide' : 'eye'} size="sm" />
{showPrivateKey ? 'Hide' : 'Show'}
</button>
<button
@@ -281,7 +281,7 @@
</div>
{:else}
<div class="key-hidden">
<Icon name="eye-off" size="sm" />
<Icon name="hide" size="sm" />
Private key hidden for security
</div>
{/if}
+5 -1
View File
@@ -320,6 +320,10 @@ $ORIGIN ${zoneName}.
display: flex;
flex-direction: column;
gap: var(--spacing-md);
textarea {
background: var(--bg-primary);
}
}
.controls-row {
@@ -479,7 +483,7 @@ $ORIGIN ${zoneName}.
.table-header {
display: grid;
grid-template-columns: 2fr 1fr 1fr 2fr;
background: var(--bg-secondary);
background: var(--bg-primary);
font-weight: 600;
font-size: var(--font-size-sm);
@@ -377,6 +377,12 @@
display: flex;
flex-direction: column;
gap: var(--spacing-md);
textarea,
input[type='text'],
input[type='number'] {
background: var(--bg-primary);
}
}
.mode-selector {
@@ -570,7 +576,7 @@
.table-header {
display: grid;
grid-template-columns: 2fr 1fr 1fr 2fr 1.5fr;
background: var(--bg-secondary);
background: var(--bg-primary);
font-weight: 600;
font-size: var(--font-size-sm);
+8 -17
View File
@@ -2,11 +2,12 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { parseDNSKEYRecord, calculateKeyTag, validateDNSKEY, DNSSEC_ALGORITHMS } from '$lib/utils/dnssec';
import { useClipboard } from '$lib/composables';
let dnskeyInput = $state('example.org. 3600 IN DNSKEY 257 3 8 AwEAAag');
let activeExampleIndex = $state<number | null>(null);
let isActiveExample = $state(true);
let copiedState = $state(false);
const clipboard = useClipboard();
const examples = [
{
@@ -69,20 +70,6 @@
}
activeExampleIndex = null;
}
async function copyKeyTag() {
if (result && !result.error && result.keyTag !== undefined) {
try {
await navigator.clipboard.writeText(result.keyTag.toString());
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy key tag:', err);
}
}
}
</script>
<div class="card">
@@ -156,8 +143,12 @@
<div class="card results-card">
<div class="results-header">
<h3>Key Tag Calculation</h3>
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyKeyTag}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
<button
class="copy-button {clipboard.isCopied() ? 'copied' : ''}"
onclick={() =>
result && !result.error && result.keyTag !== undefined && clipboard.copy(result.keyTag.toString())}
>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
Copy Key Tag
</button>
</div>
@@ -1,11 +1,12 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import Icon from '$lib/components/global/Icon.svelte';
import { normalizeLabel, type LabelAnalysis } from '$lib/utils/dns-validation';
let input = $state('');
let results = $state<LabelAnalysis[]>([]);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let activeExampleIndex = $state<number | null>(null);
function normalizeInput() {
@@ -32,18 +33,6 @@
}
});
async function copyToClipboard(text: string, key: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[key] = true;
setTimeout(() => {
copiedStates[key] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
function loadExample(exampleValue: string, index: number) {
input = exampleValue;
activeExampleIndex = index;
@@ -176,10 +165,10 @@ mixed-script-еxample.com"
<span class="label-type">Original:</span>
<code class="label-value">{result.original}</code>
<button
class="copy-button {copiedStates[`orig-${index}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(result.original, `orig-${index}`)}
class="copy-button {clipboard.isCopied(`orig-${index}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(result.original, `orig-${index}`)}
>
<Icon name={copiedStates[`orig-${index}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`orig-${index}`) ? 'check' : 'copy'} size="sm" />
</button>
</div>
@@ -187,10 +176,10 @@ mixed-script-еxample.com"
<span class="label-type">Normalized:</span>
<code class="label-value normalized">{result.normalized}</code>
<button
class="copy-button {copiedStates[`norm-${index}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(result.normalized, `norm-${index}`)}
class="copy-button {clipboard.isCopied(`norm-${index}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(result.normalized, `norm-${index}`)}
>
<Icon name={copiedStates[`norm-${index}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`norm-${index}`) ? 'check' : 'copy'} size="sm" />
</button>
</div>
+6 -1
View File
@@ -393,6 +393,11 @@
display: flex;
flex-direction: column;
gap: var(--spacing-lg);
input[type='text'],
input[type='number'] {
background: var(--bg-primary);
}
}
.domain-config {
@@ -731,7 +736,7 @@
.table-header {
display: grid;
grid-template-columns: 1.5fr 1fr 1fr 1fr 2fr 1fr;
background: var(--bg-secondary);
background: var(--bg-primary);
font-weight: 600;
font-size: var(--font-size-sm);
@@ -11,6 +11,7 @@
validateCAARecord,
type ValidationResult,
} from '$lib/utils/dns-validation.js';
import { useClipboard } from '$lib/composables';
let recordType = $state('A');
let recordName = $state('example.com');
@@ -27,7 +28,7 @@
let tag = $state('issue');
let results = $state<ValidationResult | null>(null);
let copiedState = $state(false);
const clipboard = useClipboard();
const recordTypes = [
{ value: 'A', label: 'A (IPv4 Address)', description: 'Maps domain to IPv4 address' },
@@ -162,18 +163,6 @@
}
}
async function copyRecord() {
try {
await navigator.clipboard.writeText(formatRecord());
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
}
// Validate on component load and when inputs change
function handleInputChange() {
validateRecord();
@@ -427,8 +416,11 @@
<Icon name={results.valid ? 'check-circle' : 'x-circle'} size="sm" />
<span>{results.valid ? 'Valid' : 'Invalid'} DNS Record</span>
</div>
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyRecord}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
<button
class="copy-button {clipboard.isCopied() ? 'copied' : ''}"
onclick={() => clipboard.copy(formatRecord())}
>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
Copy Zone Line
</button>
</div>
@@ -624,7 +616,7 @@
font-weight: 600;
padding: 2px var(--spacing-xs);
background-color: var(--color-primary);
color: white;
color: var(--bg-secondary);
border-radius: var(--radius-sm);
}
@@ -539,6 +539,10 @@
display: flex;
flex-direction: column;
gap: var(--spacing-lg);
input[type='number'] {
background: var(--bg-primary);
}
}
.controls-header {
@@ -859,7 +863,7 @@
.table-header {
display: grid;
grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr 2fr 1fr;
background: var(--bg-secondary);
background: var(--bg-primary);
font-weight: 600;
font-size: var(--font-size-sm);
+9 -3
View File
@@ -349,6 +349,11 @@
<style lang="scss">
.text-input-config {
margin-bottom: var(--spacing-lg);
textarea,
input[type='number'] {
background: var(--bg-primary);
}
}
.config-row {
@@ -377,6 +382,7 @@
display: flex;
flex-direction: column;
gap: var(--spacing-sm);
align-items: baseline;
}
.checkbox-label {
@@ -424,20 +430,20 @@
font-size: var(--font-size-sm);
&.success {
background: var(--color-success-bg);
background: color-mix(in srgb, var(--color-success), transparent 95%);
color: var(--color-success);
border: 1px solid var(--color-success);
}
&.warning {
background: var(--color-warning-bg);
color: var(--color-warning);
background: color-mix(in srgb, var(--color-warning), transparent 95%);
border: 1px solid var(--color-warning);
}
&.error {
background: var(--color-error-bg);
color: var(--color-error);
background: color-mix(in srgb, var(--color-error), transparent 95%);
border: 1px solid var(--color-error);
}
}
+13 -16
View File
@@ -8,6 +8,7 @@
DS_DIGEST_TYPES,
} from '$lib/utils/dnssec';
import type { DSRecord } from '$lib/utils/dnssec';
import { useClipboard } from '$lib/composables';
import Icon from '$lib/components/global/Icon.svelte';
let dnskeyInput = $state('');
@@ -45,6 +46,7 @@
let generatingDS = $state(false);
let dsRecords = $state<DSRecord[]>([]);
let error = $state<string | null>(null);
const clipboard = useClipboard();
async function generateDS() {
error = null;
@@ -114,25 +116,15 @@
}
}
let copiedStates = $state<{ [key: string]: boolean }>({});
function copyDS(ds: DSRecord) {
const formatted = formatDSRecord(ds, ownerName);
navigator.clipboard.writeText(formatted);
const key = `ds-${ds.keyTag}-${ds.digestType}`;
copiedStates[key] = true;
setTimeout(() => {
copiedStates[key] = false;
}, 1500);
clipboard.copy(formatted, key);
}
function copyAllDS() {
const formatted = dsRecords.map((ds) => formatDSRecord(ds, ownerName)).join('\n');
navigator.clipboard.writeText(formatted);
copiedStates['all'] = true;
setTimeout(() => {
copiedStates['all'] = false;
}, 1500);
clipboard.copy(formatted, 'all');
}
</script>
@@ -245,8 +237,13 @@
<Icon name="shield" />
<h3>Generated DS Records</h3>
</div>
<button class="copy-btn" class:copied={copiedStates['all']} onclick={copyAllDS} title="Copy all DS records">
<Icon name={copiedStates['all'] ? 'check' : 'copy'} />
<button
class="copy-btn"
class:copied={clipboard.isCopied('all')}
onclick={copyAllDS}
title="Copy all DS records"
>
<Icon name={clipboard.isCopied('all') ? 'check' : 'copy'} />
Copy All
</button>
</div>
@@ -261,11 +258,11 @@
</div>
<button
class="copy-btn small"
class:copied={copiedStates[`ds-${ds.keyTag}-${ds.digestType}`]}
class:copied={clipboard.isCopied(`ds-${ds.keyTag}-${ds.digestType}`)}
onclick={() => copyDS(ds)}
title="Copy this DS record"
>
<Icon name={copiedStates[`ds-${ds.keyTag}-${ds.digestType}`] ? 'check' : 'copy'} />
<Icon name={clipboard.isCopied(`ds-${ds.keyTag}-${ds.digestType}`) ? 'check' : 'copy'} />
</button>
</div>
@@ -2,6 +2,7 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { estimateEDNSSize, type DNSRecord, type EDNSEstimate } from '$lib/utils/dns-validation.js';
import { useClipboard } from '$lib/composables';
let queryName = $state('example.com');
let queryType = $state('A');
@@ -10,7 +11,7 @@
let records = $state<DNSRecord[]>([{ name: 'example.com', type: 'A', value: '192.0.2.1', ttl: 3600 }]);
let results = $state<EDNSEstimate | null>(null);
let copiedState = $state(false);
const clipboard = useClipboard();
let activeExampleIndex = $state<number | null>(null);
const recordTypes = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'SRV', 'NS', 'SOA', 'CAA', 'DNSKEY', 'RRSIG'];
@@ -178,22 +179,6 @@
return !!(results && results.recommendations && results.recommendations.length > 0);
}
async function copyEstimate() {
try {
const summary = `DNS Message Size Estimate:
Total Size: ${results?.totalSize || 0} bytes
UDP Safe: ${results?.udpSafe ? 'Yes' : 'No'}
Fragmentation Risk: ${results?.fragmentationRisk || 'unknown'}`;
await navigator.clipboard.writeText(summary);
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
}
function handleInputChange() {
estimateSize();
}
@@ -399,8 +384,15 @@ Fragmentation Risk: ${results?.fragmentationRisk || 'unknown'}`;
<Icon name="ruler" size="sm" />
Size Breakdown
</h4>
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyEstimate}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
<button
class="copy-button {clipboard.isCopied() ? 'copied' : ''}"
onclick={() =>
clipboard.copy(`DNS Message Size Estimate:
Total Size: ${results?.totalSize || 0} bytes
UDP Safe: ${results?.udpSafe ? 'Yes' : 'No'}
Fragmentation Risk: ${results?.fragmentationRisk || 'unknown'}`)}
>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
Copy Summary
</button>
</div>
+14 -23
View File
@@ -1,13 +1,14 @@
<script lang="ts">
import { convertEUI64Addresses, type EUI64Result } from '$lib/utils/eui64.js';
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import Icon from '$lib/components/global/Icon.svelte';
let inputText = $state('00:1A:2B:3C:4D:5E\n02:1A:2B:FF:FE:3C:4D:5F\n08:00:27:12:34:56\n0A:00:27:FF:FE:12:34:57');
let globalPrefix = $state('2001:db8::/64');
let result = $state<EUI64Result | null>(null);
let isLoading = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
function convertAddresses() {
if (!inputText.trim()) {
@@ -62,16 +63,6 @@
URL.revokeObjectURL(url);
}
async function copyToClipboard(text: string, id: string = text) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
// Auto-convert when inputs change
$effect(() => {
if (inputText.trim()) {
@@ -236,11 +227,11 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[conversion.macAddress]}
onclick={() => copyToClipboard(conversion.macAddress, conversion.macAddress)}
class:copied={clipboard.isCopied(conversion.macAddress)}
onclick={() => clipboard.copy(conversion.macAddress, conversion.macAddress)}
use:tooltip={{ text: 'Copy to clipboard', position: 'top' }}
>
<Icon name={copiedStates[conversion.macAddress] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(conversion.macAddress) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -252,11 +243,11 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[conversion.eui64Address]}
onclick={() => copyToClipboard(conversion.eui64Address, conversion.eui64Address)}
class:copied={clipboard.isCopied(conversion.eui64Address)}
onclick={() => clipboard.copy(conversion.eui64Address, conversion.eui64Address)}
use:tooltip={{ text: 'Copy to clipboard', position: 'top' }}
>
<Icon name={copiedStates[conversion.eui64Address] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(conversion.eui64Address) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -271,11 +262,11 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[conversion.ipv6LinkLocal]}
onclick={() => copyToClipboard(conversion.ipv6LinkLocal, conversion.ipv6LinkLocal)}
class:copied={clipboard.isCopied(conversion.ipv6LinkLocal)}
onclick={() => clipboard.copy(conversion.ipv6LinkLocal, conversion.ipv6LinkLocal)}
use:tooltip={{ text: 'Copy to clipboard', position: 'top' }}
>
<Icon name={copiedStates[conversion.ipv6LinkLocal] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(conversion.ipv6LinkLocal) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -287,11 +278,11 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[conversion.ipv6Global]}
onclick={() => copyToClipboard(conversion.ipv6Global, conversion.ipv6Global)}
class:copied={clipboard.isCopied(conversion.ipv6Global)}
onclick={() => clipboard.copy(conversion.ipv6Global, conversion.ipv6Global)}
use:tooltip={{ text: 'Copy to clipboard', position: 'top' }}
>
<Icon name={copiedStates[conversion.ipv6Global] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(conversion.ipv6Global) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
+50 -61
View File
@@ -2,6 +2,8 @@
import { computeCIDRDifference, type DiffResult } from '$lib/utils/cidr-diff.js';
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
import '../../../styles/diagnostics-pages.scss';
let pools = $state(`192.168.0.0/16
@@ -19,7 +21,7 @@
stats?: DiffResult['stats'];
visualization?: DiffResult['visualization'];
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let _selectedExample = $state<string | null>(null);
let selectedExampleIndex = $state<number | null>(null);
let _userModified = $state(false);
@@ -161,18 +163,6 @@
calculateGaps();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// Visualization helper functions
function getBlockPosition(start: bigint, totalRange: { start: bigint; end: bigint }): number {
const rangeSize = totalRange.end - totalRange.start;
@@ -316,55 +306,11 @@
</span>
<span class="metric">
<Icon name="network" size="sm" />
{result.totalAddresses.toLocaleString()} addresses
{formatNumber(result.totalAddresses)} addresses
</span>
</div>
</div>
{#if result.availableBlocks.length > 0}
<div class="free-blocks-grid">
{#each result.availableBlocks as block, index (index)}
{@const blockAddresses = (() => {
const match = block.match(/\/(\d+)$/);
if (!match) return 0;
const prefixLength = parseInt(match[1]);
const version = block.includes(':') ? 6 : 4;
const totalBits = version === 4 ? 32 : 128;
return Math.pow(2, totalBits - prefixLength);
})()}
<div class="free-block-card">
<div class="block-header">
<code class="block-cidr">{block}</code>
<button
class="copy-button {copiedStates[`block-${index}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(block, `block-${index}`)}
aria-label="Copy CIDR block"
>
<Icon name={copiedStates[`block-${index}`] ? 'check' : 'copy'} size="xs" />
</button>
</div>
<div class="block-info">
<span class="address-count">
{blockAddresses.toLocaleString()} addresses
</span>
{#if targetPrefix && blockAddresses >= Math.pow(2, 32 - targetPrefix)}
<span class="can-fit">
<Icon name="check-circle" size="xs" />
Can fit /{targetPrefix}
</span>
{/if}
</div>
</div>
{/each}
</div>
{:else}
<div class="no-gaps">
<Icon name="alert-circle" />
<h4>No Available Space</h4>
<p>All address space in the pools is allocated or there are no pools defined.</p>
</div>
{/if}
<!-- Address Space Visualization -->
{#if result.availableBlocks.length > 0 && result.visualization}
<div class="visualization-section">
@@ -438,6 +384,49 @@
</div>
</div>
{/if}
{#if result.availableBlocks.length > 0}
<div class="free-blocks-grid">
{#each result.availableBlocks as block, index (index)}
{@const blockAddresses = (() => {
const match = block.match(/\/(\d+)$/);
if (!match) return 0;
const prefixLength = parseInt(match[1]);
const version = block.includes(':') ? 6 : 4;
const totalBits = version === 4 ? 32 : 128;
return Math.pow(2, totalBits - prefixLength);
})()}
<div class="free-block-card">
<div class="block-header">
<code class="block-cidr">{block}</code>
<button
class="copy-button {clipboard.isCopied(`block-${index}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(block, `block-${index}`)}
aria-label="Copy CIDR block"
>
<Icon name={clipboard.isCopied(`block-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
<div class="block-info">
<span class="address-count">
{formatNumber(blockAddresses)} addresses
</span>
{#if targetPrefix && blockAddresses >= Math.pow(2, 32 - targetPrefix)}
<span class="can-fit">
<Icon name="check-circle" size="xs" />
Can fit /{targetPrefix}
</span>
{/if}
</div>
</div>
{/each}
</div>
{:else}
<div class="no-gaps">
<Icon name="alert-circle" />
<h4>No Available Space</h4>
<p>All address space in the pools is allocated or there are no pools defined.</p>
</div>
{/if}
{:else}
<div class="error-message">
<Icon name="alert-triangle" />
@@ -517,7 +506,7 @@
gap: var(--spacing-md);
h3 {
color: var(--color-success-light);
color: var(--color-primary);
margin: 0;
}
}
@@ -570,7 +559,7 @@
font-family: var(--font-mono);
font-size: var(--font-size-md);
font-weight: 600;
color: var(--color-success-light);
color: var(--color-success);
background-color: var(--bg-tertiary);
padding: var(--spacing-xs);
border-radius: var(--radius-sm);
@@ -666,7 +655,7 @@
border-radius: var(--radius-lg);
h4 {
color: var(--color-info-light);
color: var(--text-primary);
margin-bottom: var(--spacing-md);
text-align: center;
}
@@ -1,12 +1,13 @@
<script lang="ts">
import { Copy, Download, Check, Globe, Type } from 'lucide-svelte';
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
let inputText = $state('');
let mode = $state('unicode-to-punycode');
let showExamples = $state(false);
let buttonStates = $state({} as Record<string, boolean>);
const clipboard = useClipboard();
const domainExamples = [
{ unicode: 'münchen.de', punycode: 'xn--mnchen-3ya.de', description: 'German city domain' },
@@ -231,16 +232,8 @@
return warns;
});
function showButtonSuccess(buttonId: string) {
buttonStates[buttonId] = true;
setTimeout(() => {
buttonStates[buttonId] = false;
}, 2000);
}
function copyToClipboard() {
navigator.clipboard.writeText(result);
showButtonSuccess('copy');
clipboard.copy(result, 'copy');
}
function downloadResult() {
@@ -254,7 +247,7 @@
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showButtonSuccess('download');
clipboard.copy('downloaded', 'download');
}
function loadExample(example: (typeof domainExamples)[0]) {
@@ -406,10 +399,10 @@
<button
onclick={copyToClipboard}
class="btn-secondary"
class:success={buttonStates.copy}
style="transform: {buttonStates.copy ? 'scale(1.05)' : 'scale(1)'}"
class:success={clipboard.isCopied('copy')}
style="transform: {clipboard.isCopied('copy') ? 'scale(1.05)' : 'scale(1)'}"
>
{#if buttonStates.copy}
{#if clipboard.isCopied('copy')}
<Check size="16" />
Copied!
{:else}
@@ -420,10 +413,10 @@
<button
onclick={downloadResult}
class="btn-primary"
class:success={buttonStates.download}
style="transform: {buttonStates.download ? 'scale(1.05)' : 'scale(1)'}"
class:success={clipboard.isCopied('download')}
style="transform: {clipboard.isCopied('download') ? 'scale(1.05)' : 'scale(1)'}"
>
{#if buttonStates.download}
{#if clipboard.isCopied('download')}
<Check size="16" />
Downloaded!
{:else}
@@ -510,6 +503,7 @@
}
.card {
width: 100%;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-lg);
@@ -862,7 +856,7 @@
gap: var(--spacing-xs);
padding: var(--spacing-sm) var(--spacing-md);
background: var(--color-primary-dark);
color: white;
color: var(--bg-secondary);
border: none;
border-radius: var(--radius-md);
cursor: pointer;
+32 -97
View File
@@ -4,6 +4,7 @@
import IPInput from './IPInput.svelte';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '../global/Icon.svelte';
import { useClipboard } from '$lib/composables';
let ipAddress = $state('192.168.1.1');
let formats = $state({
@@ -13,7 +14,7 @@
octal: '',
});
let ipClass = $state({ class: '', type: '', description: '' });
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let formatErrors = $state<Record<string, string>>({});
/**
@@ -171,21 +172,6 @@
console.error('Invalid hex conversion:', err);
}
}
/**
* Copies text to clipboard with visual feedback
*/
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 3000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
</script>
<div class="card">
@@ -234,29 +220,17 @@
class="format-field binary {formatErrors.binary ? 'error' : ''}"
oninput={handleBinaryInput}
/>
<Tooltip text={copiedStates['binary'] ? 'Copied!' : 'Copy binary format to clipboard'} position="left">
<Tooltip
text={clipboard.isCopied('binary') ? 'Copied!' : 'Copy binary format to clipboard'}
position="left"
>
<button
type="button"
class="copy-btn {copiedStates['binary'] ? 'copied' : ''}"
onclick={() => copyToClipboard(formats.binary, 'binary')}
class="copy-btn {clipboard.isCopied('binary') ? 'copied' : ''}"
onclick={() => clipboard.copy(formats.binary, 'binary')}
aria-label="Copy binary format to clipboard"
>
{#if copiedStates['binary']}
<svg fill="currentColor" viewBox="0 0 20 20">
<path
fill-rule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clip-rule="evenodd"
/>
</svg>
{:else}
<svg fill="currentColor" viewBox="0 0 20 20">
<path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" />
<path
d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"
/>
</svg>
{/if}
<Icon name={clipboard.isCopied('binary') ? 'check' : 'copy'} size="sm" />
</button>
</Tooltip>
</div>
@@ -277,29 +251,17 @@
class="format-field decimal {formatErrors.decimal ? 'error' : ''}"
oninput={handleDecimalInput}
/>
<Tooltip text={copiedStates['decimal'] ? 'Copied!' : 'Copy decimal format to clipboard'} position="left">
<Tooltip
text={clipboard.isCopied('decimal') ? 'Copied!' : 'Copy decimal format to clipboard'}
position="left"
>
<button
type="button"
class="copy-btn {copiedStates['decimal'] ? 'copied' : ''}"
onclick={() => copyToClipboard(formats.decimal, 'decimal')}
class="copy-btn {clipboard.isCopied('decimal') ? 'copied' : ''}"
onclick={() => clipboard.copy(formats.decimal, 'decimal')}
aria-label="Copy decimal format to clipboard"
>
{#if copiedStates['decimal']}
<svg fill="currentColor" viewBox="0 0 20 20">
<path
fill-rule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clip-rule="evenodd"
/>
</svg>
{:else}
<svg fill="currentColor" viewBox="0 0 20 20">
<path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" />
<path
d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"
/>
</svg>
{/if}
<Icon name={clipboard.isCopied('decimal') ? 'check' : 'copy'} size="sm" />
</button>
</Tooltip>
</div>
@@ -320,29 +282,17 @@
class="format-field hex {formatErrors.hex ? 'error' : ''}"
oninput={handleHexInput}
/>
<Tooltip text={copiedStates['hex'] ? 'Copied!' : 'Copy hexadecimal format to clipboard'} position="left">
<Tooltip
text={clipboard.isCopied('hex') ? 'Copied!' : 'Copy hexadecimal format to clipboard'}
position="left"
>
<button
type="button"
class="copy-btn {copiedStates['hex'] ? 'copied' : ''}"
onclick={() => copyToClipboard(formats.hex, 'hex')}
class="copy-btn {clipboard.isCopied('hex') ? 'copied' : ''}"
onclick={() => clipboard.copy(formats.hex, 'hex')}
aria-label="Copy hexadecimal format to clipboard"
>
{#if copiedStates['hex']}
<svg fill="currentColor" viewBox="0 0 20 20">
<path
fill-rule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clip-rule="evenodd"
/>
</svg>
{:else}
<svg fill="currentColor" viewBox="0 0 20 20">
<path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" />
<path
d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"
/>
</svg>
{/if}
<Icon name={clipboard.isCopied('hex') ? 'check' : 'copy'} size="sm" />
</button>
</Tooltip>
</div>
@@ -363,29 +313,14 @@
class="format-field octal"
readonly
/>
<Tooltip text={copiedStates['octal'] ? 'Copied!' : 'Copy octal format to clipboard'} position="left">
<Tooltip text={clipboard.isCopied('octal') ? 'Copied!' : 'Copy octal format to clipboard'} position="left">
<button
type="button"
class="copy-btn {copiedStates['octal'] ? 'copied' : ''}"
onclick={() => copyToClipboard(formats.octal, 'octal')}
class="copy-btn {clipboard.isCopied('octal') ? 'copied' : ''}"
onclick={() => clipboard.copy(formats.octal, 'octal')}
aria-label="Copy octal format to clipboard"
>
{#if copiedStates['octal']}
<svg fill="currentColor" viewBox="0 0 20 20">
<path
fill-rule="evenodd"
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
clip-rule="evenodd"
/>
</svg>
{:else}
<svg fill="currentColor" viewBox="0 0 20 20">
<path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" />
<path
d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 3H9a3 3 0 01-3-3z"
/>
</svg>
{/if}
<Icon name={clipboard.isCopied('octal') ? 'check' : 'copy'} size="sm" />
</button>
</Tooltip>
</div>
@@ -626,17 +561,17 @@
transition: all var(--transition-fast);
}
.copy-btn svg {
width: 1rem;
height: 1rem;
}
.copy-btn:hover {
background-color: var(--surface-hover);
color: var(--text-primary);
border-color: var(--color-primary);
}
.copy-btn.copied {
color: var(--color-success);
background-color: rgba(35, 134, 54, 0.1);
}
.format-field.error {
border-color: var(--color-danger) !important;
background-color: rgba(var(--color-danger-rgb), 0.05);
+28 -36
View File
@@ -2,6 +2,8 @@
import { tooltip } from '$lib/actions/tooltip.js';
import { calculateIPDistances, type DistanceResult } from '$lib/utils/ip-distance.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
import '../../../styles/diagnostics-pages.scss';
let inputText = $state('192.168.1.1 -> 192.168.1.100\n10.0.0.1 -> 10.0.0.255\n2001:db8::1 -> 2001:db8::ffff');
@@ -11,7 +13,7 @@
let isLoading = $state(false);
let selectedExampleIndex = $state<number | null>(null);
let userModified = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
const examples = [
{
@@ -116,18 +118,6 @@
selectedExampleIndex = null;
}
async function copyToClipboard(text: string, key: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[key] = true;
setTimeout(() => {
copiedStates[key] = false;
}, 1500);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
}
function formatDirection(direction: 'forward' | 'backward'): string {
return direction === 'forward' ? '→' : '←';
}
@@ -240,7 +230,7 @@
<div class="card loading-card">
<div class="card-content">
<div class="loading">
<Icon name="loader-2" size="sm" animate="spin" />
<Icon name="loader" size="sm" animate="spin" />
Calculating distances...
</div>
</div>
@@ -271,17 +261,17 @@
<h3>Distance Summary</h3>
<button
class="copy-btn"
class:copied={copiedStates['summary']}
class:copied={clipboard.isCopied('summary')}
onclick={() =>
result &&
copyToClipboard(
clipboard.copy(
`Total Pairs: ${result.summary.totalCalculations}\nValid: ${result.summary.validCalculations}\nInvalid: ${result.summary.invalidCalculations}\nTotal Distance: ${result.summary.totalDistance}\nAverage Distance: ${result.summary.averageDistance}`,
'summary',
)}
use:tooltip={'Copy summary to clipboard'}
>
<Icon name={copiedStates['summary'] ? 'check' : 'copy'} size="xs" />
{copiedStates['summary'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('summary') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('summary') ? 'Copied!' : 'Copy'}
</button>
</div>
<div class="card-content">
@@ -338,11 +328,11 @@
<span class="ip-value">{calculation.startIP}</span>
<button
class="copy-btn"
class:copied={copiedStates[`start-${index}`]}
onclick={() => copyToClipboard(calculation.startIP, `start-${index}`)}
class:copied={clipboard.isCopied(`start-${index}`)}
onclick={() => clipboard.copy(calculation.startIP, `start-${index}`)}
use:tooltip={'Copy start IP'}
>
<Icon name={copiedStates[`start-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`start-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -361,11 +351,11 @@
<span class="ip-value">{calculation.endIP}</span>
<button
class="copy-btn"
class:copied={copiedStates[`end-${index}`]}
onclick={() => copyToClipboard(calculation.endIP, `end-${index}`)}
class:copied={clipboard.isCopied(`end-${index}`)}
onclick={() => clipboard.copy(calculation.endIP, `end-${index}`)}
use:tooltip={'Copy end IP'}
>
<Icon name={copiedStates[`end-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`end-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -388,11 +378,11 @@
<span class="distance-number">{calculation.distance}</span>
<button
class="copy-btn"
class:copied={copiedStates[`distance-${index}`]}
onclick={() => copyToClipboard(calculation.distance, `distance-${index}`)}
class:copied={clipboard.isCopied(`distance-${index}`)}
onclick={() => clipboard.copy(calculation.distance, `distance-${index}`)}
use:tooltip={'Copy distance value'}
>
<Icon name={copiedStates[`distance-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`distance-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
<span class="distance-label">
@@ -423,12 +413,12 @@
<h4>Intermediate Addresses</h4>
<button
class="copy-btn"
class:copied={copiedStates[`intermediates-${index}`]}
class:copied={clipboard.isCopied(`intermediates-${index}`)}
onclick={() =>
copyToClipboard(calculation.intermediateAddresses.join('\n'), `intermediates-${index}`)}
clipboard.copy(calculation.intermediateAddresses.join('\n'), `intermediates-${index}`)}
use:tooltip={'Copy all intermediate addresses'}
>
<Icon name={copiedStates[`intermediates-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`intermediates-${index}`) ? 'check' : 'copy'} size="xs" />
Copy All
</button>
</div>
@@ -438,12 +428,12 @@
<span class="ip-value">{ip}</span>
<button
class="copy-btn"
class:copied={copiedStates[`intermediate-${index}-${ipIndex}`]}
onclick={() => copyToClipboard(ip, `intermediate-${index}-${ipIndex}`)}
class:copied={clipboard.isCopied(`intermediate-${index}-${ipIndex}`)}
onclick={() => clipboard.copy(ip, `intermediate-${index}-${ipIndex}`)}
use:tooltip={'Copy this IP address'}
>
<Icon
name={copiedStates[`intermediate-${index}-${ipIndex}`] ? 'check' : 'copy'}
name={clipboard.isCopied(`intermediate-${index}-${ipIndex}`) ? 'check' : 'copy'}
size="xs"
/>
</button>
@@ -451,9 +441,11 @@
{/each}
{#if calculation.distanceNumber > BigInt(calculation.intermediateAddresses.length + 2)}
<span class="more-indicator">
... and {(
calculation.distanceNumber - BigInt(calculation.intermediateAddresses.length + 2)
).toLocaleString()} more
... and {formatNumber(
Number(
calculation.distanceNumber - BigInt(calculation.intermediateAddresses.length + 2),
),
)} more
</span>
{/if}
</div>
+19 -27
View File
@@ -1,6 +1,8 @@
<script lang="ts">
// import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let input = $state('192.168.1.0/28');
let maxDisplayLimit = $state(1000);
@@ -23,7 +25,7 @@
};
} | null>(null);
let isGenerating = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -163,7 +165,7 @@
if (size > BigInt(ABSOLUTE_MAX_GENERATION)) {
throw new Error(
`IPv6 /${prefixLength} would generate ${size.toLocaleString()} addresses. Maximum allowed: ${ABSOLUTE_MAX_GENERATION.toLocaleString()}`,
`IPv6 /${prefixLength} would generate ${formatNumber(Number(size))} addresses. Maximum allowed: ${formatNumber(ABSOLUTE_MAX_GENERATION)}`,
);
}
@@ -185,7 +187,7 @@
if (size > ABSOLUTE_MAX_GENERATION) {
throw new Error(
`/${prefixLength} would generate ${size.toLocaleString()} addresses. Maximum allowed: ${ABSOLUTE_MAX_GENERATION.toLocaleString()}`,
`/${prefixLength} would generate ${formatNumber(size)} addresses. Maximum allowed: ${formatNumber(ABSOLUTE_MAX_GENERATION)}`,
);
}
@@ -219,7 +221,7 @@
if (count > ABSOLUTE_MAX_GENERATION) {
throw new Error(
`Range would generate ${count.toLocaleString()} addresses. Maximum allowed: ${ABSOLUTE_MAX_GENERATION.toLocaleString()}`,
`Range would generate ${formatNumber(count)} addresses. Maximum allowed: ${formatNumber(ABSOLUTE_MAX_GENERATION)}`,
);
}
@@ -273,18 +275,6 @@
enumerateIPs();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
async function exportToCSV() {
if (!result?.addresses.length) return;
@@ -414,7 +404,9 @@
<div class="safety-warning">
<Icon name="alert-triangle" size="sm" />
<div>
<strong>Safety:</strong> Max {ABSOLUTE_MAX_DISPLAY.toLocaleString()} displayed, {ABSOLUTE_MAX_GENERATION.toLocaleString()}
<strong>Safety:</strong> Max {formatNumber(ABSOLUTE_MAX_DISPLAY)} displayed, {formatNumber(
ABSOLUTE_MAX_GENERATION,
)}
generated
</div>
</div>
@@ -453,21 +445,21 @@
CSV
</button>
<button
class="copy-btn {copiedStates['all-addresses'] ? 'copied' : ''}"
onclick={() => copyToClipboard((result?.addresses || []).join('\n'), 'all-addresses')}
class="copy-btn {clipboard.isCopied('all-addresses') ? 'copied' : ''}"
onclick={() => clipboard.copy((result?.addresses || []).join('\n'), 'all-addresses')}
>
<Icon name={copiedStates['all-addresses'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('all-addresses') ? 'check' : 'copy'} size="sm" />
Copy All
</button>
</div>
<div class="summary-stats">
<div class="stat">
<span class="stat-value">{result.totalCount.toLocaleString()}</span>
<span class="stat-value">{formatNumber(result.totalCount)}</span>
<span class="stat-label">Total</span>
</div>
<div class="stat">
<span class="stat-value">{result.displayCount.toLocaleString()}</span>
<span class="stat-value">{formatNumber(result.displayCount)}</span>
<span class="stat-label">Shown</span>
</div>
<div class="stat">
@@ -501,7 +493,7 @@
</h3>
{#if result.truncated}
<span class="truncated-notice"
>Showing {result.displayCount.toLocaleString()} of {result.totalCount.toLocaleString()}</span
>Showing {formatNumber(result.displayCount)} of {formatNumber(result.totalCount)}</span
>
{/if}
</div>
@@ -512,10 +504,10 @@
<span class="address-index">{index + 1}</span>
<code class="address-code">{address}</code>
<button
class="copy-btn-small {copiedStates[address] ? 'copied' : ''}"
onclick={() => copyToClipboard(address, address)}
class="copy-btn-small {clipboard.isCopied(address) ? 'copied' : ''}"
onclick={() => clipboard.copy(address, address)}
>
<Icon name={copiedStates[address] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(address) ? 'check' : 'copy'} size="xs" />
</button>
</div>
{/each}
@@ -669,7 +661,7 @@
&::after {
opacity: 1;
color: white;
color: var(--bg-secondary);
}
}
}
@@ -12,6 +12,7 @@
import IPInput from './IPInput.svelte';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import SvgIcon from '$lib/components/global/SvgIcon.svelte';
import { useClipboard } from '$lib/composables';
interface Props {
direction: 'ipv4-to-ipv6' | 'ipv6-to-ipv4';
@@ -23,7 +24,7 @@
let inputValue = $state('');
let conversionResult = $state<ConversionResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let ipv6Info = $state<Record<string, any> | null>(null);
/**
@@ -65,18 +66,6 @@
/**
* Copy text to clipboard with visual feedback
*/
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 3000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// React to input changes
$effect(() => {
performConversion();
@@ -111,16 +100,16 @@
<div class="result-value-container">
<code class="result-value">{conversionResult.result}</code>
<Tooltip
text={copiedStates['result'] ? 'Copied!' : `Copy ${isIPv4ToIPv6 ? 'IPv6' : 'IPv4'} address`}
text={clipboard.isCopied('result') ? 'Copied!' : `Copy ${isIPv4ToIPv6 ? 'IPv6' : 'IPv4'} address`}
position="left"
>
<button
type="button"
class="copy-btn {copiedStates['result'] ? 'copied' : ''}"
onclick={() => copyToClipboard(conversionResult?.result || '', 'result')}
class="copy-btn {clipboard.isCopied('result') ? 'copied' : ''}"
onclick={() => clipboard.copy(conversionResult?.result || '', 'result')}
aria-label="Copy result to clipboard"
>
<SvgIcon icon={copiedStates['result'] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied('result') ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -145,13 +134,16 @@
<span class="detail-label">Compressed Format</span>
<div class="detail-value-container">
<code class="detail-value">{conversionResult.details.compressed}</code>
<Tooltip text={copiedStates['compressed'] ? 'Copied!' : 'Copy compressed format'} position="left">
<Tooltip
text={clipboard.isCopied('compressed') ? 'Copied!' : 'Copy compressed format'}
position="left"
>
<button
type="button"
class="copy-btn-small {copiedStates['compressed'] ? 'copied' : ''}"
onclick={() => copyToClipboard(conversionResult?.details?.compressed || '', 'compressed')}
class="copy-btn-small {clipboard.isCopied('compressed') ? 'copied' : ''}"
onclick={() => clipboard.copy(conversionResult?.details?.compressed || '', 'compressed')}
>
<SvgIcon icon={copiedStates['compressed'] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied('compressed') ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -161,13 +153,13 @@
<span class="detail-label">Expanded Format</span>
<div class="detail-value-container">
<code class="detail-value">{conversionResult.details.expanded}</code>
<Tooltip text={copiedStates['expanded'] ? 'Copied!' : 'Copy expanded format'} position="left">
<Tooltip text={clipboard.isCopied('expanded') ? 'Copied!' : 'Copy expanded format'} position="left">
<button
type="button"
class="copy-btn-small {copiedStates['expanded'] ? 'copied' : ''}"
onclick={() => copyToClipboard(conversionResult?.details?.expanded || '', 'expanded')}
class="copy-btn-small {clipboard.isCopied('expanded') ? 'copied' : ''}"
onclick={() => clipboard.copy(conversionResult?.details?.expanded || '', 'expanded')}
>
<SvgIcon icon={copiedStates['expanded'] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied('expanded') ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -177,13 +169,13 @@
<span class="detail-label">Dotted Notation</span>
<div class="detail-value-container">
<code class="detail-value">{conversionResult.details.dotted}</code>
<Tooltip text={copiedStates['dotted'] ? 'Copied!' : 'Copy dotted notation'} position="left">
<Tooltip text={clipboard.isCopied('dotted') ? 'Copied!' : 'Copy dotted notation'} position="left">
<button
type="button"
class="copy-btn-small {copiedStates['dotted'] ? 'copied' : ''}"
onclick={() => copyToClipboard(conversionResult?.details?.dotted || '', 'dotted')}
class="copy-btn-small {clipboard.isCopied('dotted') ? 'copied' : ''}"
onclick={() => clipboard.copy(conversionResult?.details?.dotted || '', 'dotted')}
>
<SvgIcon icon={copiedStates['dotted'] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied('dotted') ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -224,13 +216,16 @@
<span class="analysis-label">Expanded Format</span>
<div class="detail-value-container">
<code class="detail-value">{expandIPv6(ipv6Info.cleaned)}</code>
<Tooltip text={copiedStates['ipv6-expanded'] ? 'Copied!' : 'Copy expanded IPv6'} position="left">
<Tooltip
text={clipboard.isCopied('ipv6-expanded') ? 'Copied!' : 'Copy expanded IPv6'}
position="left"
>
<button
type="button"
class="copy-btn-small {copiedStates['ipv6-expanded'] ? 'copied' : ''}"
onclick={() => copyToClipboard(expandIPv6(ipv6Info?.cleaned || ''), 'ipv6-expanded')}
class="copy-btn-small {clipboard.isCopied('ipv6-expanded') ? 'copied' : ''}"
onclick={() => clipboard.copy(expandIPv6(ipv6Info?.cleaned || ''), 'ipv6-expanded')}
>
<SvgIcon icon={copiedStates['ipv6-expanded'] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied('ipv6-expanded') ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -240,13 +235,16 @@
<span class="analysis-label">Compressed Format</span>
<div class="detail-value-container">
<code class="detail-value">{compressIPv6(ipv6Info.cleaned)}</code>
<Tooltip text={copiedStates['ipv6-compressed'] ? 'Copied!' : 'Copy compressed IPv6'} position="left">
<Tooltip
text={clipboard.isCopied('ipv6-compressed') ? 'Copied!' : 'Copy compressed IPv6'}
position="left"
>
<button
type="button"
class="copy-btn-small {copiedStates['ipv6-compressed'] ? 'copied' : ''}"
onclick={() => copyToClipboard(compressIPv6(ipv6Info?.cleaned || ''), 'ipv6-compressed')}
class="copy-btn-small {clipboard.isCopied('ipv6-compressed') ? 'copied' : ''}"
onclick={() => clipboard.copy(compressIPv6(ipv6Info?.cleaned || ''), 'ipv6-compressed')}
>
<SvgIcon icon={copiedStates['ipv6-compressed'] ? 'check' : 'clipboard'} size="sm" />
<SvgIcon icon={clipboard.isCopied('ipv6-compressed') ? 'check' : 'clipboard'} size="sm" />
</button>
</Tooltip>
</div>
@@ -399,7 +397,7 @@
.copy-btn.copied,
.copy-btn-small.copied {
background-color: var(--color-success);
color: white;
color: var(--bg-secondary);
border-color: var(--color-success);
}
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import {
generateRegex,
getLanguageExamples,
@@ -18,7 +19,7 @@
let mode = $state<Mode>('simple');
let regexType = $state<RegexType>('ipv4');
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
// Advanced options
let ipv4Options = $state<IPv4Options>({
@@ -133,18 +134,6 @@
}
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function validateEditableRegex() {
if (!editablePattern) {
regexValidation = { ok: false, error: 'Pattern cannot be empty' };
@@ -562,11 +551,11 @@
Test on RegexR
</a>
<button
class="copy-button {copiedStates['pattern'] ? 'copied' : ''}"
onclick={() => result && copyToClipboard(result.pattern, 'pattern')}
class="copy-button {clipboard.isCopied('pattern') ? 'copied' : ''}"
onclick={() => result && clipboard.copy(result.pattern, 'pattern')}
>
<Icon name={copiedStates['pattern'] ? 'check' : 'copy'} size="sm" />
{copiedStates['pattern'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('pattern') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('pattern') ? 'Copied!' : 'Copy'}
</button>
</div>
</div>
@@ -796,11 +785,11 @@
<div class="language-content" class:open={openLanguageExample === example.name}>
<div class="code-container">
<button
class="copy-code-btn {copiedStates[example.name.toLowerCase()] ? 'copied' : ''}"
onclick={() => copyToClipboard(example.code, example.name.toLowerCase())}
class="copy-code-btn {clipboard.isCopied(example.name.toLowerCase()) ? 'copied' : ''}"
onclick={() => clipboard.copy(example.code, example.name.toLowerCase())}
use:tooltip={'Copy code snippet'}
>
<Icon name={copiedStates[example.name.toLowerCase()] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(example.name.toLowerCase()) ? 'check' : 'copy'} size="xs" />
</button>
<pre class="code-block"><code>{example.code}</code></pre>
</div>
+5 -16
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
let inputAddress = $state('192.168.1.100');
let customPrefix = $state('64:ff9b::/96');
@@ -19,7 +20,7 @@
explanation: string[];
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -401,18 +402,6 @@
translateAddress();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// Translate on component load
translateAddress();
</script>
@@ -571,10 +560,10 @@
<div class="step-content">
<code class="step-value">{result.translatedAddress}</code>
<button
class="copy-button {copiedStates['result'] ? 'copied' : ''}"
onclick={() => result && copyToClipboard(result.translatedAddress, 'result')}
class="copy-button {clipboard.isCopied('result') ? 'copied' : ''}"
onclick={() => result && clipboard.copy(result.translatedAddress, 'result')}
>
<Icon name={copiedStates['result'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('result') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
+11 -24
View File
@@ -1,13 +1,14 @@
<script lang="ts">
import { normalizeIPv6Addresses, type IPv6NormalizeResult } from '$lib/utils/ipv6-normalize.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
let inputText = $state(
'2001:0db8:0000:0000:0000:ff00:0042:8329\n2001:db8:0:0:1:0:0:1\n2001:0db8:0001:0000:0000:0ab9:C0A8:0102\n2001:db8::1\nfe80::1%eth0',
);
let result = $state<IPv6NormalizeResult | null>(null);
let isLoading = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
function normalizeAddresses() {
if (!inputText.trim()) {
@@ -71,27 +72,13 @@
URL.revokeObjectURL(url);
}
async function copyToClipboard(text: string, id?: string) {
try {
await navigator.clipboard.writeText(text);
if (id) {
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
}
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function copyAllNormalized() {
if (result) {
const normalized = result.normalizations
.filter((n) => n.isValid)
.map((n) => n.normalized)
.join('\n');
copyToClipboard(normalized, 'copy-all');
clipboard.copy(normalized, 'copy-all');
}
}
@@ -183,8 +170,8 @@
<div class="normalized-header">
<h3>Normalized Addresses</h3>
<div class="export-buttons">
<button onclick={copyAllNormalized} class:copied={copiedStates['copy-all']}>
<Icon name={copiedStates['copy-all'] ? 'check' : 'copy'} />
<button onclick={copyAllNormalized} class:copied={clipboard.isCopied('copy-all')}>
<Icon name={clipboard.isCopied('copy-all') ? 'check' : 'copy'} />
Copy All
</button>
<button onclick={() => exportResults('txt')}>
@@ -226,7 +213,7 @@
<button
type="button"
class="code-button"
onclick={() => copyToClipboard(normalization.input, `original-${index}`)}
onclick={() => clipboard.copy(normalization.input, `original-${index}`)}
title="Click to copy"
>
{normalization.input}
@@ -240,7 +227,7 @@
<button
type="button"
class="code-button normalized"
onclick={() => copyToClipboard(normalization.normalized, `normalized-${index}`)}
onclick={() => clipboard.copy(normalization.normalized, `normalized-${index}`)}
title="Click to copy"
>
{normalization.normalized}
@@ -248,11 +235,11 @@
<button
type="button"
class="copy-button"
class:copied={copiedStates[`copy-${index}`]}
onclick={() => copyToClipboard(normalization.normalized, `copy-${index}`)}
class:copied={clipboard.isCopied(`copy-${index}`)}
onclick={() => clipboard.copy(normalization.normalized, `copy-${index}`)}
title="Copy normalized address"
>
<Icon name={copiedStates[`copy-${index}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`copy-${index}`) ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -623,7 +610,7 @@
&.copied {
background: var(--color-success);
color: white;
color: var(--bg-secondary);
border-color: var(--color-success);
transform: scale(1.05);
}
@@ -2,19 +2,18 @@
import { expandIPv6, compressIPv6, validateIPv6Address } from '$lib/utils/ipv6-subnet-calculations.js';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
interface Props {
mode: 'expand' | 'compress';
title: string;
description: string;
}
let { mode, title, description }: Props = $props();
let { mode }: Props = $props();
let inputAddress = $state('2001:db8::1');
let outputAddress = $state('');
let conversionError = $state('');
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExampleIndex = $state<number | null>(null);
/* Common IPv6 example addresses for testing */
@@ -49,19 +48,6 @@
performConversion();
}
/* Copy text to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 3000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
/* Perform the conversion based on mode */
function performConversion() {
conversionError = '';
@@ -104,210 +90,132 @@
});
</script>
<div class="card converter-card">
<header class="card-header">
<div class="header-content">
<div class="header-text">
<h2>{title}</h2>
<p>{description}</p>
</div>
<div class="header-actions">
<a
href={mode === 'expand'
? '/ip-address-convertor/notation/ipv6-compress'
: '/ip-address-convertor/notation/ipv6-expand'}
class="mode-switch-btn"
title="Switch to {mode === 'expand' ? 'Compress' : 'Expand'} mode"
<!-- Input Section -->
<div class="converter-section">
<h3>Input IPv6 Address</h3>
<div class="input-group">
<div class="form-group">
<label for="ipv6-input">
IPv6 Address
<Tooltip
text={mode === 'expand'
? 'Enter compressed IPv6 address to expand'
: 'Enter expanded IPv6 address to compress'}
>
<Icon name={mode === 'expand' ? 'ipv6-compress' : 'ipv6-expand'} size="sm" />
<span>{mode === 'expand' ? 'Compress' : 'Expand'}</span>
</a>
</div>
</div>
</header>
<!-- Input Section -->
<div class="converter-section">
<h3>Input IPv6 Address</h3>
<div class="input-group">
<div class="form-group">
<label for="ipv6-input">
IPv6 Address
<Tooltip
text={mode === 'expand'
? 'Enter compressed IPv6 address to expand'
: 'Enter expanded IPv6 address to compress'}
>
<Icon name="help" size="sm" />
</Tooltip>
</label>
<div class="input-wrapper">
<input
id="ipv6-input"
type="text"
bind:value={inputAddress}
oninput={handleInput}
placeholder={mode === 'expand' ? '2001:db8::1' : '2001:0db8:0000:0000:0000:0000:0000:0001'}
class="ipv6-input"
/>
<button type="button" class="btn btn-secondary btn-md" onclick={clearAll}>
<Icon name="trash" size="md" />
</button>
</div>
{#if conversionError}
<p class="error-message">{conversionError}</p>
{/if}
<Icon name="help" size="sm" />
</Tooltip>
</label>
<div class="input-wrapper">
<input
id="ipv6-input"
type="text"
bind:value={inputAddress}
oninput={handleInput}
placeholder={mode === 'expand' ? '2001:db8::1' : '2001:0db8:0000:0000:0000:0000:0000:0001'}
class="ipv6-input"
/>
<button type="button" class="btn btn-secondary btn-md" onclick={clearAll}>
<Icon name="trash" size="md" />
</button>
</div>
{#if conversionError}
<p class="error-message">{conversionError}</p>
{/if}
</div>
</div>
<!-- Examples Section -->
<div class="examples-section">
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h3>Common Examples</h3>
</summary>
<div class="examples-grid">
{#each exampleAddresses as example, index (`example-${index}`)}
<button
type="button"
class="example-btn"
class:selected={selectedExampleIndex === index}
onclick={() => setExample(mode === 'expand' ? example.compressed : example.expanded, index)}
>
<div class="example-label">{example.label}</div>
<code class="example-address">
{mode === 'expand' ? example.compressed : example.expanded}
</code>
</button>
{/each}
</div>
</details>
</div>
<!-- Output Section -->
{#if outputAddress && !conversionError}
<div class="output-section">
<h3>Converted Address</h3>
<div class="conversion-result">
<div class="result-card success">
<div class="result-header">
<h4>
<Icon name={mode === 'expand' ? 'maximize' : 'minimize'} size="sm" />
{mode === 'expand' ? 'Expanded Format' : 'Compressed Format'}
</h4>
</div>
<div class="result-content">
<div class="address-display">
<div class="address-wrapper">
<code class="converted-address">{outputAddress}</code>
<button
type="button"
class="btn btn-icon copy-btn"
class:copied={copiedStates['output']}
onclick={() => copyToClipboard(outputAddress, 'output')}
>
<Icon name={copiedStates['output'] ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
<!-- Comparison View -->
<div class="comparison-view">
<div class="comparison-item">
<span class="comparison-label">Input ({mode === 'expand' ? 'Compressed' : 'Expanded'}):</span>
<code class="comparison-address input">{inputAddress}</code>
</div>
<div class="comparison-item">
<span class="comparison-label">Output ({mode === 'expand' ? 'Expanded' : 'Compressed'}):</span>
<code class="comparison-address output">{outputAddress}</code>
</div>
</div>
<!-- Character Count -->
<div class="stats-grid">
<div class="stat-item">
<span class="stat-label">Input Length</span>
<span class="stat-value">{inputAddress.length} characters</span>
</div>
<div class="stat-item">
<span class="stat-label">Output Length</span>
<span class="stat-value">{outputAddress.length} characters</span>
</div>
<div class="stat-item">
<span class="stat-label">Difference</span>
<span class="stat-value {outputAddress.length > inputAddress.length ? 'expanded' : 'compressed'}">
{outputAddress.length > inputAddress.length ? '+' : ''}{outputAddress.length - inputAddress.length} characters
</span>
</div>
</div>
</div>
</div>
</div>
</div>
{/if}
</div>
<!-- Examples Section -->
<div class="examples-section">
<details class="examples-details">
<summary class="examples-summary">
<Icon name="chevron-right" size="xs" />
<h3>Common Examples</h3>
</summary>
<div class="examples-grid">
{#each exampleAddresses as example, index (`example-${index}`)}
<button
type="button"
class="example-btn"
class:selected={selectedExampleIndex === index}
onclick={() => setExample(mode === 'expand' ? example.compressed : example.expanded, index)}
>
<div class="example-label">{example.label}</div>
<code class="example-address">
{mode === 'expand' ? example.compressed : example.expanded}
</code>
</button>
{/each}
</div>
</details>
</div>
<!-- Output Section -->
{#if outputAddress && !conversionError}
<div class="output-section">
<h3>Converted Address</h3>
<div class="conversion-result">
<div class="result-card success">
<div class="result-header">
<h4>
<Icon name={mode === 'expand' ? 'maximize' : 'minimize'} size="sm" />
{mode === 'expand' ? 'Expanded Format' : 'Compressed Format'}
</h4>
</div>
<div class="result-content">
<div class="address-display">
<div class="address-wrapper">
<code class="converted-address">{outputAddress}</code>
<button
type="button"
class="btn btn-icon copy-btn"
class:copied={clipboard.isCopied('output')}
onclick={() => clipboard.copy(outputAddress, 'output')}
>
<Icon name={clipboard.isCopied('output') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
<!-- Comparison View -->
<div class="comparison-view">
<div class="comparison-item">
<span class="comparison-label">Input ({mode === 'expand' ? 'Compressed' : 'Expanded'}):</span>
<code class="comparison-address input">{inputAddress}</code>
</div>
<div class="comparison-item">
<span class="comparison-label">Output ({mode === 'expand' ? 'Expanded' : 'Compressed'}):</span>
<code class="comparison-address output">{outputAddress}</code>
</div>
</div>
<!-- Character Count -->
<div class="stats-grid">
<div class="stat-item">
<span class="stat-label">Input Length</span>
<span class="stat-value">{inputAddress.length} characters</span>
</div>
<div class="stat-item">
<span class="stat-label">Output Length</span>
<span class="stat-value">{outputAddress.length} characters</span>
</div>
<div class="stat-item">
<span class="stat-label">Difference</span>
<span class="stat-value {outputAddress.length > inputAddress.length ? 'expanded' : 'compressed'}">
{outputAddress.length > inputAddress.length ? '+' : ''}{outputAddress.length - inputAddress.length} characters
</span>
</div>
</div>
</div>
</div>
</div>
</div>
{/if}
<style>
.converter-card {
max-width: none;
}
.header-content {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: var(--spacing-lg);
}
.header-text {
flex: 1;
}
.header-actions {
display: flex;
flex-shrink: 0;
}
.mode-switch-btn {
display: flex;
align-items: center;
gap: var(--spacing-sm);
padding: var(--spacing-sm) var(--spacing-md);
background-color: var(--bg-secondary);
border: 2px solid var(--border-primary);
border-radius: var(--radius-md);
color: var(--text-primary);
text-decoration: none;
font-weight: 600;
font-size: var(--font-size-sm);
transition: all var(--transition-fast);
&:hover {
background-color: var(--surface-hover);
border-color: var(--color-primary);
color: var(--color-primary);
transform: translateY(-2px);
box-shadow: var(--shadow-sm);
}
&:active {
transform: translateY(0);
}
:global(.icon) {
transition: transform var(--transition-fast);
}
&:hover :global(.icon) {
transform: scale(1.1);
}
}
.converter-section,
.examples-section,
.output-section {
@@ -614,22 +522,6 @@
}
@media (max-width: 768px) {
.header-content {
flex-direction: column;
align-items: stretch;
gap: var(--spacing-md);
}
.header-actions {
justify-content: center;
}
.mode-switch-btn {
justify-content: center;
padding: var(--spacing-md);
font-size: var(--font-size-md);
}
.examples-grid {
grid-template-columns: 1fr;
}
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
let input = $state('2001:db8::1234:5678');
let result = $state<{
@@ -15,7 +16,7 @@
explanation: string[];
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -190,18 +191,6 @@
calculateSolicitedNode();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// Calculate on component load
calculateSolicitedNode();
</script>
@@ -304,10 +293,10 @@
<div class="result-content">
<code class="result-value unicast">{result.details.normalizedUnicast}</code>
<button
class="copy-button {copiedStates['unicast'] ? 'copied' : ''}"
onclick={() => result && copyToClipboard(result.details.normalizedUnicast, 'unicast')}
class="copy-button {clipboard.isCopied('unicast') ? 'copied' : ''}"
onclick={() => result && clipboard.copy(result.details.normalizedUnicast, 'unicast')}
>
<Icon name={copiedStates['unicast'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('unicast') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -324,10 +313,10 @@
<div class="result-content">
<code class="result-value multicast">{result.solicitedNodeAddress}</code>
<button
class="copy-button {copiedStates['multicast'] ? 'copied' : ''}"
onclick={() => result && copyToClipboard(result.solicitedNodeAddress, 'multicast')}
class="copy-button {clipboard.isCopied('multicast') ? 'copied' : ''}"
onclick={() => result && clipboard.copy(result.solicitedNodeAddress, 'multicast')}
>
<Icon name={copiedStates['multicast'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('multicast') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -7,11 +7,27 @@
} from '$lib/utils/ipv6-subnet-calculations.js';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import { useClipboard } from '$lib/composables';
import { goto } from '$app/navigation';
const versionOptions = [
{ value: 'ipv4' as const, label: 'IPv4' },
{ value: 'ipv6' as const, label: 'IPv6' },
];
let selectedVersion = $state<'ipv4' | 'ipv6'>('ipv6');
function handleVersionChange(version: 'ipv4' | 'ipv6') {
if (version === 'ipv4') {
goto('/subnetting/ipv4-subnet-calculator');
}
}
let networkAddress = $state('2001:db8::/64');
let prefixLength = $state(64);
let subnetResult = $state<IPv6SubnetResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let showBinaryView = $state(false);
const commonPrefixes = getCommonIPv6Prefixes();
@@ -60,19 +76,6 @@
prefixLength = prefix;
}
/* Copy text to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 3000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
/* Get prefix description */
function getPrefixDescription(prefix: number): string {
const common = commonPrefixes.find((p) => p.prefix === prefix);
@@ -100,12 +103,14 @@
// activePreset is now derived automatically
</script>
<div class="card ipv6-calc-card">
<header class="card-header">
<h2>IPv6 Subnet Calculator</h2>
<p>Calculate IPv6 subnet information with 128-bit addressing and modern network prefix notation.</p>
</header>
<ToolContentContainer
title="IPv6 Subnet Calculator"
description="Calculate IPv6 subnet information with 128-bit addressing and modern network prefix notation."
navOptions={versionOptions}
bind:selectedNav={selectedVersion}
onNavChange={handleVersionChange}
contentClass="ipv6-calc-card"
>
<!-- Input Section -->
<div class="input-section">
<h3>Network Configuration</h3>
@@ -202,15 +207,15 @@
<span class="info-value">{subnetResult.subnet.networkCompressed}/{subnetResult.subnet.prefixLength}</span>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['network']}
class:copied={clipboard.isCopied('network')}
onclick={() =>
subnetResult?.subnet &&
copyToClipboard(
clipboard.copy(
`${subnetResult.subnet.networkCompressed}/${subnetResult.subnet.prefixLength}`,
'network',
)}
>
<Icon name={copiedStates['network'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('network') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -246,11 +251,11 @@
<code class="detail-value">{subnetResult.subnet.networkCompressed}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['compressed']}
class:copied={clipboard.isCopied('compressed')}
onclick={() =>
subnetResult?.subnet && copyToClipboard(subnetResult.subnet.networkCompressed, 'compressed')}
subnetResult?.subnet && clipboard.copy(subnetResult.subnet.networkCompressed, 'compressed')}
>
<Icon name={copiedStates['compressed'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('compressed') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -266,10 +271,10 @@
<code class="detail-value expanded">{subnetResult.subnet.networkExpanded}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['expanded']}
onclick={() => subnetResult?.subnet && copyToClipboard(subnetResult.subnet.networkExpanded, 'expanded')}
class:copied={clipboard.isCopied('expanded')}
onclick={() => subnetResult?.subnet && clipboard.copy(subnetResult.subnet.networkExpanded, 'expanded')}
>
<Icon name={copiedStates['expanded'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('expanded') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -285,10 +290,10 @@
<code class="detail-value">{subnetResult.subnet.subnetMask}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['mask']}
onclick={() => subnetResult?.subnet && copyToClipboard(subnetResult.subnet.subnetMask, 'mask')}
class:copied={clipboard.isCopied('mask')}
onclick={() => subnetResult?.subnet && clipboard.copy(subnetResult.subnet.subnetMask, 'mask')}
>
<Icon name={copiedStates['mask'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('mask') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -306,12 +311,12 @@
</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['range']}
class:copied={clipboard.isCopied('range')}
onclick={() =>
subnetResult?.subnet &&
copyToClipboard(`${subnetResult.subnet.firstAddress} - ${subnetResult.subnet.lastAddress}`, 'range')}
clipboard.copy(`${subnetResult.subnet.firstAddress} - ${subnetResult.subnet.lastAddress}`, 'range')}
>
<Icon name={copiedStates['range'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('range') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -327,11 +332,11 @@
<code class="detail-value">{formatLargeNumber(subnetResult.subnet.assignableAddresses)}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['assignable']}
class:copied={clipboard.isCopied('assignable')}
onclick={() =>
subnetResult?.subnet && copyToClipboard(subnetResult.subnet.assignableAddresses, 'assignable')}
subnetResult?.subnet && clipboard.copy(subnetResult.subnet.assignableAddresses, 'assignable')}
>
<Icon name={copiedStates['assignable'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('assignable') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -347,10 +352,10 @@
<code class="detail-value reverse">{subnetResult.subnet.reverseZone}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['reverse']}
onclick={() => subnetResult?.subnet && copyToClipboard(subnetResult.subnet.reverseZone, 'reverse')}
class:copied={clipboard.isCopied('reverse')}
onclick={() => subnetResult?.subnet && clipboard.copy(subnetResult.subnet.reverseZone, 'reverse')}
>
<Icon name={copiedStates['reverse'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('reverse') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -367,10 +372,10 @@
<code class="detail-value binary-display">{subnetResult.subnet.binaryPrefix}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['binary']}
onclick={() => subnetResult?.subnet && copyToClipboard(subnetResult.subnet.binaryPrefix, 'binary')}
class:copied={clipboard.isCopied('binary')}
onclick={() => subnetResult?.subnet && clipboard.copy(subnetResult.subnet.binaryPrefix, 'binary')}
>
<Icon name={copiedStates['binary'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('binary') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -426,13 +431,13 @@
</div>
</div>
{/if}
</div>
</ToolContentContainer>
<style>
.ipv6-calc-card .btn :global(.icon) {
width: 1rem;
height: 1rem;
.btn {
vertical-align: middle;
display: flex;
gap: var(--spacing-sm);
}
.input-section {
+11 -22
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
let input = $state('2001:0000:4136:e378:8000:63bf:3fff:fdd2');
let result = $state<{
@@ -23,7 +24,7 @@
explanation: string[];
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -257,18 +258,6 @@
parseTeredo();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// Parse on component load
parseTeredo();
</script>
@@ -417,10 +406,10 @@
<div class="component-content">
<code class="component-value">{result.components.serverIPv4}</code>
<button
class="copy-button {copiedStates['server'] ? 'copied' : ''}"
onclick={() => result && copyToClipboard(result.components.serverIPv4, 'server')}
class="copy-button {clipboard.isCopied('server') ? 'copied' : ''}"
onclick={() => result && clipboard.copy(result.components.serverIPv4, 'server')}
>
<Icon name={copiedStates['server'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('server') ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="component-description">The Teredo relay server handling this tunnel</div>
@@ -434,10 +423,10 @@
<div class="component-content">
<code class="component-value">{result.components.clientIPv4}</code>
<button
class="copy-button {copiedStates['client'] ? 'copied' : ''}"
onclick={() => result && copyToClipboard(result.components.clientIPv4, 'client')}
class="copy-button {clipboard.isCopied('client') ? 'copied' : ''}"
onclick={() => result && clipboard.copy(result.components.clientIPv4, 'client')}
>
<Icon name={copiedStates['client'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('client') ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="component-description">The client's external IPv4 address (XOR decoded)</div>
@@ -451,10 +440,10 @@
<div class="component-content">
<code class="component-value">{result.components.clientPort}</code>
<button
class="copy-button {copiedStates['port'] ? 'copied' : ''}"
onclick={() => result && copyToClipboard(result.components.clientPort.toString(), 'port')}
class="copy-button {clipboard.isCopied('port') ? 'copied' : ''}"
onclick={() => result && clipboard.copy(result.components.clientPort.toString(), 'port')}
>
<Icon name={copiedStates['port'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('port') ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="component-description">The client's external port (XOR decoded with FFFF)</div>
+28 -33
View File
@@ -1,11 +1,12 @@
<script lang="ts">
import { processIPv6ZoneIdentifiers, type IPv6ZoneResult } from '$lib/utils/ipv6-zone-id.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
let inputText = $state('fe80::1\nfe80::1%eth0\nfe80::1234:5678:90ab:cdef%wlan0\n::1\n2001:db8::1\nff02::1%eth0');
let result = $state<IPv6ZoneResult | null>(null);
let isLoading = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
function processAddresses() {
if (!inputText.trim()) {
@@ -65,20 +66,6 @@
URL.revokeObjectURL(url);
}
async function copyToClipboard(text: string, id?: string) {
try {
await navigator.clipboard.writeText(text);
if (id) {
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
}
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function getAddressTypeColor(type: string): string {
switch (type) {
case 'link-local':
@@ -242,11 +229,11 @@
<code>{processing.input}</code>
<button
type="button"
class:copied={copiedStates[`input-${processing.input}`]}
onclick={() => copyToClipboard(processing.input, `input-${processing.input}`)}
class:copied={clipboard.isCopied(`input-${processing.input}`)}
onclick={() => clipboard.copy(processing.input, `input-${processing.input}`)}
title="Copy input"
>
<Icon name={copiedStates[`input-${processing.input}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`input-${processing.input}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -270,11 +257,14 @@
<code>{processing.address}</code>
<button
type="button"
class:copied={copiedStates[`address-${processing.address}`]}
onclick={() => copyToClipboard(processing.address, `address-${processing.address}`)}
class:copied={clipboard.isCopied(`address-${processing.address}`)}
onclick={() => clipboard.copy(processing.address, `address-${processing.address}`)}
title="Copy address"
>
<Icon name={copiedStates[`address-${processing.address}`] ? 'check' : 'copy'} size="xs" />
<Icon
name={clipboard.isCopied(`address-${processing.address}`) ? 'check' : 'copy'}
size="xs"
/>
</button>
</div>
</div>
@@ -286,11 +276,14 @@
<code>{processing.zoneId}</code>
<button
type="button"
class:copied={copiedStates[`zone-${processing.zoneId}`]}
onclick={() => copyToClipboard(processing.zoneId, `zone-${processing.zoneId}`)}
class:copied={clipboard.isCopied(`zone-${processing.zoneId}`)}
onclick={() => clipboard.copy(processing.zoneId, `zone-${processing.zoneId}`)}
title="Copy zone ID"
>
<Icon name={copiedStates[`zone-${processing.zoneId}`] ? 'check' : 'copy'} size="xs" />
<Icon
name={clipboard.isCopied(`zone-${processing.zoneId}`) ? 'check' : 'copy'}
size="xs"
/>
</button>
</div>
{#if processing.processing.zoneIdValid}
@@ -345,16 +338,18 @@
<code>{processing.processing.withZone}</code>
<button
type="button"
class:copied={copiedStates[`with-zone-${processing.processing.withZone}`]}
class:copied={clipboard.isCopied(`with-zone-${processing.processing.withZone}`)}
onclick={() =>
copyToClipboard(
clipboard.copy(
processing.processing.withZone,
`with-zone-${processing.processing.withZone}`,
)}
title="Copy with zone"
>
<Icon
name={copiedStates[`with-zone-${processing.processing.withZone}`] ? 'check' : 'copy'}
name={clipboard.isCopied(`with-zone-${processing.processing.withZone}`)
? 'check'
: 'copy'}
size="xs"
/>
</button>
@@ -367,16 +362,16 @@
<code>{processing.processing.withoutZone}</code>
<button
type="button"
class:copied={copiedStates[`without-zone-${processing.processing.withoutZone}`]}
class:copied={clipboard.isCopied(`without-zone-${processing.processing.withoutZone}`)}
onclick={() =>
copyToClipboard(
clipboard.copy(
processing.processing.withoutZone,
`without-zone-${processing.processing.withoutZone}`,
)}
title="Copy without zone"
>
<Icon
name={copiedStates[`without-zone-${processing.processing.withoutZone}`]
name={clipboard.isCopied(`without-zone-${processing.processing.withoutZone}`)
? 'check'
: 'copy'}
size="xs"
@@ -394,12 +389,12 @@
<button
type="button"
class="zone-button"
class:copied={copiedStates[`suggested-${zone}`]}
onclick={() => copyToClipboard(`${processing.address}%${zone}`, `suggested-${zone}`)}
class:copied={clipboard.isCopied(`suggested-${zone}`)}
onclick={() => clipboard.copy(`${processing.address}%${zone}`, `suggested-${zone}`)}
title="Copy full address"
>
<code>{zone}</code>
<Icon name={copiedStates[`suggested-${zone}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`suggested-${zone}`) ? 'check' : 'copy'} size="xs" />
</button>
{/each}
</div>
+11 -17
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip';
import { useClipboard } from '$lib/composables';
let domain = $state('');
let latitude = $state('37.7749');
@@ -14,7 +15,7 @@
let parseMode = $state(false);
let showExamples = $state(false);
let buttonStates = $state({} as Record<string, boolean>);
const clipboard = useClipboard();
const cityExamples = [
{ name: 'San Francisco', lat: 37.7749, lng: -122.4194, alt: 10 },
@@ -114,16 +115,8 @@
}
});
function showButtonSuccess(buttonId: string) {
buttonStates[buttonId] = true;
setTimeout(() => {
buttonStates[buttonId] = false;
}, 2000);
}
function copyToClipboard() {
navigator.clipboard.writeText(locRecord);
showButtonSuccess('copy');
clipboard.copy(locRecord, 'copy');
}
function downloadRecord() {
@@ -136,7 +129,7 @@
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showButtonSuccess('download');
clipboard.copy('', 'download');
}
function loadCity(city: { name: string; lat: number; lng: number; alt: number }) {
@@ -287,13 +280,13 @@
{#if isValid}
<div class="actions">
<button onclick={copyToClipboard} class="btn btn-primary" class:success={buttonStates.copy}>
<Icon name={buttonStates.copy ? 'check' : 'copy'} size="sm" />
{buttonStates.copy ? 'Copied!' : 'Copy Record'}
<button onclick={copyToClipboard} class="btn btn-primary" class:success={clipboard.isCopied('copy')}>
<Icon name={clipboard.isCopied('copy') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('copy') ? 'Copied!' : 'Copy Record'}
</button>
<button onclick={downloadRecord} class="btn btn-success" class:success={buttonStates.download}>
<Icon name={buttonStates.download ? 'check' : 'download'} size="sm" />
{buttonStates.download ? 'Downloaded!' : 'Download'}
<button onclick={downloadRecord} class="btn btn-success" class:success={clipboard.isCopied('download')}>
<Icon name={clipboard.isCopied('download') ? 'check' : 'download'} size="sm" />
{clipboard.isCopied('download') ? 'Downloaded!' : 'Download'}
</button>
</div>
{/if}
@@ -346,6 +339,7 @@
}
.card {
width: 100%;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-lg);
+11 -20
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip';
import { useClipboard } from '$lib/composables';
let domain = $state('');
let order = $state('100');
@@ -10,7 +11,7 @@
let regexp = $state('!^.*$!sip:info@example.com!');
let replacement = $state('.');
let buttonStates = $state({} as Record<string, boolean>);
const clipboard = useClipboard();
let showExamples = $state(false);
const flagOptions = [
@@ -85,19 +86,8 @@
return warns;
});
/**
* @param {string} buttonId
*/
function showButtonSuccess(buttonId: string) {
buttonStates[buttonId] = true;
setTimeout(() => {
buttonStates[buttonId] = false;
}, 2000);
}
function copyToClipboard() {
navigator.clipboard.writeText(naptrRecord);
showButtonSuccess('copy');
clipboard.copy(naptrRecord, 'copy');
}
function downloadRecord() {
@@ -110,7 +100,7 @@
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showButtonSuccess('download');
clipboard.copy('', 'download');
}
function loadExample(exampleType: string) {
@@ -284,13 +274,13 @@
{#if isValid}
<div class="actions">
<button onclick={copyToClipboard} class="btn btn-primary" class:success={buttonStates.copy}>
<Icon name={buttonStates.copy ? 'check' : 'copy'} size="sm" />
{buttonStates.copy ? 'Copied!' : 'Copy Record'}
<button onclick={copyToClipboard} class="btn btn-primary" class:success={clipboard.isCopied('copy')}>
<Icon name={clipboard.isCopied('copy') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('copy') ? 'Copied!' : 'Copy Record'}
</button>
<button onclick={downloadRecord} class="btn btn-success" class:success={buttonStates.download}>
<Icon name={buttonStates.download ? 'check' : 'download'} size="sm" />
{buttonStates.download ? 'Downloaded!' : 'Download'}
<button onclick={downloadRecord} class="btn btn-success" class:success={clipboard.isCopied('download')}>
<Icon name={clipboard.isCopied('download') ? 'check' : 'download'} size="sm" />
{clipboard.isCopied('download') ? 'Downloaded!' : 'Download'}
</button>
</div>
{/if}
@@ -351,6 +341,7 @@
}
.card {
width: 100%;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-lg);
+8 -19
View File
@@ -2,6 +2,7 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { calculateNSEC3Hash, NSEC3_HASH_ALGORITHMS } from '$lib/utils/dnssec';
import { useClipboard } from '$lib/composables';
let domainName = $state('www.example.com.');
let salt = $state('');
@@ -9,7 +10,7 @@
let algorithm = $state(1);
let activeExampleIndex = $state<number | null>(null);
let isActiveExample = $state(true);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
const examples = [
{
@@ -132,28 +133,16 @@
}
}
async function copyToClipboard(text: string, key: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[key] = true;
setTimeout(() => {
copiedStates[key] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
function copyHash() {
if (result?.hash) {
copyToClipboard(result.hash, 'hash');
clipboard.copy(result.hash, 'hash');
}
}
function copyNSEC3Record() {
if (result?.hash && result?.originalName) {
const record = `${result.hash}.example.com. IN NSEC3 1 0 ${iterations} ${salt || '-'} ${result.hash} A RRSIG`;
copyToClipboard(record, 'record');
clipboard.copy(record, 'record');
}
}
@@ -332,12 +321,12 @@
<div class="results-header">
<h3>NSEC3 Hash Result</h3>
<div class="header-actions">
<button class="copy-button {copiedStates.hash ? 'copied' : ''}" onclick={copyHash}>
<Icon name={copiedStates.hash ? 'check' : 'copy'} size="sm" />
<button class="copy-button {clipboard.isCopied('hash') ? 'copied' : ''}" onclick={copyHash}>
<Icon name={clipboard.isCopied('hash') ? 'check' : 'copy'} size="sm" />
Copy Hash
</button>
<button class="copy-button {copiedStates.record ? 'copied' : ''}" onclick={copyNSEC3Record}>
<Icon name={copiedStates.record ? 'check' : 'copy'} size="sm" />
<button class="copy-button {clipboard.isCopied('record') ? 'copied' : ''}" onclick={copyNSEC3Record}>
<Icon name={clipboard.isCopied('record') ? 'check' : 'copy'} size="sm" />
Copy Record
</button>
</div>
@@ -2,6 +2,7 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { parseZoneFile, checkNameLengths, type NameLengthViolation } from '$lib/utils/zone-parser.js';
import { useClipboard } from '$lib/composables';
let zoneInput = $state('');
let results = $state<{
@@ -9,7 +10,7 @@
totalNames: number;
validNames: number;
} | null>(null);
let copiedState = $state(false);
const clipboard = useClipboard();
let activeExampleIndex = $state<number | null>(null);
const examples = [
@@ -84,20 +85,10 @@ very.deep.nested.subdomain.with.lots.of.labels.creating.a.domain.name.that.is.ex
}
}
async function copyResults() {
function copyResults() {
if (!results) return;
const reportText = formatReportForCopy(results);
try {
await navigator.clipboard.writeText(reportText);
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
clipboard.copy(reportText);
}
function formatReportForCopy(data: typeof results): string {
@@ -248,9 +239,9 @@ very-long-subdomain-name.example.com. IN A 192.0.2.2"
<section class="results-section">
<div class="results-header">
<h3>Name Length Validation Results</h3>
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyResults}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
{copiedState ? 'Copied!' : 'Copy Report'}
<button class="copy-button {clipboard.isCopied() ? 'copied' : ''}" onclick={copyResults}>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied() ? 'Copied!' : 'Copy Report'}
</button>
</div>
@@ -1,6 +1,7 @@
<script lang="ts">
import type { SubnetInfo } from '$lib/types/ip.js';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import { formatNumber } from '$lib/utils/formatters';
interface Props {
subnetInfo: SubnetInfo;
@@ -65,7 +66,7 @@
<div class="range-header">
<span class="range-label">Address Range</span>
<span class="range-count">
{subnetInfo.hostCount.toLocaleString()} total addresses
{formatNumber(subnetInfo.hostCount)} total addresses
</span>
</div>
@@ -102,7 +103,7 @@
</div>
<div class="legend-item">
<div class="legend-color usable"></div>
<span>Usable Hosts ({subnetInfo.usableHosts.toLocaleString()})</span>
<span>Usable Hosts ({formatNumber(subnetInfo.usableHosts)})</span>
</div>
{#if subnetInfo.hostCount > 1}
<div class="legend-item">
+13 -22
View File
@@ -8,6 +8,8 @@
import { tooltip } from '$lib/actions/tooltip.js';
import _Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let pools = $state(`192.168.0.0/16
10.0.0.0/8`);
@@ -21,7 +23,7 @@
let policy = $state<AllocationPolicy>('first-fit');
let maxCandidates = $state(5);
let result = $state<NextAvailableResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let userModified = $state(false);
let showVisualization = $state(true);
@@ -85,17 +87,6 @@
performSearch();
}
/* Copy to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
/* Export results */
function exportResults(format: 'csv' | 'json') {
if (!result || result.candidates.length === 0) return;
@@ -128,7 +119,7 @@
content = [headers, ...rows].map((row) => row.join(',')).join('\n');
}
copyToClipboard(content, `export-${format}`);
clipboard.copy(content, `export-${format}`);
}
/* Clear inputs */
@@ -186,7 +177,7 @@
candidate: 'Candidate',
};
const size = range.start && range.end ? (range.end - range.start + 1n).toLocaleString() : 'Unknown';
const size = range.start && range.end ? formatNumber(Number(range.end - range.start + 1n)) : 'Unknown';
return `${labels[type]}\n${range.cidr}\nSize: ${size} addresses`;
}
@@ -437,19 +428,19 @@
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={copiedStates['export-csv']}
class:copied={clipboard.isCopied('export-csv')}
onclick={() => exportResults('csv')}
>
<Icon name={copiedStates['export-csv'] ? 'check' : 'download'} size="sm" />
<Icon name={clipboard.isCopied('export-csv') ? 'check' : 'download'} size="sm" />
CSV
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={copiedStates['export-json']}
class:copied={clipboard.isCopied('export-json')}
onclick={() => exportResults('json')}
>
<Icon name={copiedStates['export-json'] ? 'check' : 'download'} size="sm" />
<Icon name={clipboard.isCopied('export-json') ? 'check' : 'download'} size="sm" />
JSON
</button>
</div>
@@ -489,7 +480,7 @@
class="btn btn-secondary btn-xs"
onclick={() => (showVisualization = !showVisualization)}
>
<Icon name="eye-off" size="sm" />
<Icon name="hide" size="sm" />
Hide
</button>
</div>
@@ -586,10 +577,10 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[candidate.cidr]}
onclick={() => copyToClipboard(candidate.cidr, candidate.cidr)}
class:copied={clipboard.isCopied(candidate.cidr)}
onclick={() => clipboard.copy(candidate.cidr, candidate.cidr)}
>
<Icon name={copiedStates[candidate.cidr] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(candidate.cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
<div class="candidate-details">
+22 -33
View File
@@ -2,6 +2,7 @@
import { tooltip } from '$lib/actions/tooltip.js';
import { calculateNthIPs, type NthIPResult } from '$lib/utils/nth-ip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import '../../../styles/diagnostics-pages.scss';
let inputText = $state('192.168.1.0/24 @ 10\n10.0.0.0-10.0.0.255 [50]\n172.16.0.0/16 100\n2001:db8::/64#1000');
@@ -10,7 +11,7 @@
let isLoading = $state(false);
let selectedExampleIndex = $state<number | null>(null);
let userModified = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
const examples = [
{
@@ -119,18 +120,6 @@
selectedExampleIndex = null;
}
async function copyToClipboard(text: string, key: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[key] = true;
setTimeout(() => {
copiedStates[key] = false;
}, 1500);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
}
// Auto-calculate when inputs change
$effect(() => {
if (inputText.trim()) {
@@ -221,7 +210,7 @@
<div class="card loading-card">
<div class="card-content">
<div class="loading">
<Icon name="loader-2" size="sm" animate="spin" />
<Icon name="loader" size="sm" animate="spin" />
Calculating IPs...
</div>
</div>
@@ -252,18 +241,18 @@
<h3>Calculation Summary</h3>
<button
class="copy-btn"
class:copied={copiedStates['summary']}
class:copied={clipboard.isCopied('summary')}
onclick={() =>
result &&
result.summary &&
copyToClipboard(
clipboard.copy(
`Total: ${result.summary.totalCalculations}\nValid: ${result.summary.validCalculations}\nInvalid: ${result.summary.invalidCalculations}\nOut of Bounds: ${result.summary.outOfBoundsCalculations}`,
'summary',
)}
use:tooltip={'Copy summary to clipboard'}
>
<Icon name={copiedStates['summary'] ? 'check' : 'copy'} size="xs" />
{copiedStates['summary'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('summary') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('summary') ? 'Copied!' : 'Copy'}
</button>
</div>
<div class="card-content">
@@ -321,11 +310,11 @@
<span class="input-text">{calculation.input}</span>
<button
class="copy-btn"
class:copied={copiedStates[`input-${index}`]}
onclick={() => copyToClipboard(calculation.input, `input-${index}`)}
class:copied={clipboard.isCopied(`input-${index}`)}
onclick={() => clipboard.copy(calculation.input, `input-${index}`)}
use:tooltip={'Copy input specification'}
>
<Icon name={copiedStates[`input-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`input-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
<div class="input-meta">
@@ -366,11 +355,11 @@
<span class="result-value">{calculation.resultIP}</span>
<button
class="copy-btn"
class:copied={copiedStates[`result-${index}`]}
onclick={() => copyToClipboard(calculation.resultIP, `result-${index}`)}
class:copied={clipboard.isCopied(`result-${index}`)}
onclick={() => clipboard.copy(calculation.resultIP, `result-${index}`)}
use:tooltip={'Copy result IP address'}
>
<Icon name={copiedStates[`result-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`result-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -394,11 +383,11 @@
<span class="ip-value">{calculation.network}</span>
<button
class="copy-btn"
class:copied={copiedStates[`network-${index}`]}
onclick={() => copyToClipboard(calculation.network, `network-${index}`)}
class:copied={clipboard.isCopied(`network-${index}`)}
onclick={() => clipboard.copy(calculation.network, `network-${index}`)}
use:tooltip={'Copy network address'}
>
<Icon name={copiedStates[`network-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`network-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -437,13 +426,13 @@
<span class="ip-value">{calculation.details.networkStart}</span>
<button
class="copy-btn"
class:copied={copiedStates[`start-${index}`]}
class:copied={clipboard.isCopied(`start-${index}`)}
onclick={() =>
calculation.details &&
copyToClipboard(calculation.details.networkStart, `start-${index}`)}
clipboard.copy(calculation.details.networkStart, `start-${index}`)}
use:tooltip={'Copy network start address'}
>
<Icon name={copiedStates[`start-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`start-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -454,13 +443,13 @@
<span class="ip-value">{calculation.details.networkEnd}</span>
<button
class="copy-btn"
class:copied={copiedStates[`end-${index}`]}
class:copied={clipboard.isCopied(`end-${index}`)}
onclick={() =>
calculation.details &&
copyToClipboard(calculation.details.networkEnd, `end-${index}`)}
clipboard.copy(calculation.details.networkEnd, `end-${index}`)}
use:tooltip={'Copy network end address'}
>
<Icon name={copiedStates[`end-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`end-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
+8 -19
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
let inputValue = $state('192.168.1.100');
let inputType = $state<'single' | 'cidr'>('single');
@@ -25,7 +26,7 @@
uniqueZones: number;
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
let showZoneFiles = $state(true);
@@ -358,18 +359,6 @@ $TTL 86400
generatePTRs();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// Generate on component load
generatePTRs();
</script>
@@ -541,10 +530,10 @@ $TTL 86400
<div class="col-ptr">
<code>{entry.ptrName}</code>
<button
class="copy-button {copiedStates[`ptr-${entry.ip}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(entry.ptrName, `ptr-${entry.ip}`)}
class="copy-button {clipboard.isCopied(`ptr-${entry.ip}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(entry.ptrName, `ptr-${entry.ip}`)}
>
<Icon name={copiedStates[`ptr-${entry.ip}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`ptr-${entry.ip}`) ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="col-type">
@@ -578,10 +567,10 @@ $TTL 86400
<span class="zone-type {zoneFile.type.toLowerCase()}">{zoneFile.type}</span>
</div>
<button
class="copy-button {copiedStates[`zone-${zoneFile.zone}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(zoneFile.content, `zone-${zoneFile.zone}`)}
class="copy-button {clipboard.isCopied(`zone-${zoneFile.zone}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(zoneFile.content, `zone-${zoneFile.zone}`)}
>
<Icon name={copiedStates[`zone-${zoneFile.zone}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`zone-${zoneFile.zone}`) ? 'check' : 'copy'} size="sm" />
Copy Zone File
</button>
</div>
+11 -22
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { analyzePTRCoverage, type PTRCoverageAnalysis } from '$lib/utils/reverse-dns.js';
let cidrInput = $state('192.168.1.0/24');
@@ -16,7 +17,7 @@
analysis: PTRCoverageAnalysis;
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -109,18 +110,6 @@
analyzeCoverage();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function _generateDigCommands(missingPTRs: string[]): string {
return missingPTRs
.slice(0, 20)
@@ -345,10 +334,10 @@
Missing PTR Records ({results.analysis.missingPTRs.length})
</h4>
<button
class="copy-button {copiedStates['missing-ptrs'] ? 'copied' : ''}"
onclick={() => results && copyToClipboard(results.analysis.missingPTRs.join('\n'), 'missing-ptrs')}
class="copy-button {clipboard.isCopied('missing-ptrs') ? 'copied' : ''}"
onclick={() => results && clipboard.copy(results.analysis.missingPTRs.join('\n'), 'missing-ptrs')}
>
<Icon name={copiedStates['missing-ptrs'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('missing-ptrs') ? 'check' : 'copy'} size="sm" />
Copy List
</button>
</div>
@@ -377,10 +366,10 @@
Extra PTR Records ({results.analysis.extraPTRs.length})
</h4>
<button
class="copy-button {copiedStates['extra-ptrs'] ? 'copied' : ''}"
onclick={() => results && copyToClipboard(results.analysis.extraPTRs.join('\n'), 'extra-ptrs')}
class="copy-button {clipboard.isCopied('extra-ptrs') ? 'copied' : ''}"
onclick={() => results && clipboard.copy(results.analysis.extraPTRs.join('\n'), 'extra-ptrs')}
>
<Icon name={copiedStates['extra-ptrs'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('extra-ptrs') ? 'check' : 'copy'} size="sm" />
Copy List
</button>
</div>
@@ -416,12 +405,12 @@
<Icon name="plus" size="sm" />
<span>Create Missing PTR Records</span>
<button
class="copy-button {copiedStates['create-commands'] ? 'copied' : ''}"
class="copy-button {clipboard.isCopied('create-commands') ? 'copied' : ''}"
onclick={() =>
results &&
copyToClipboard(generateCreateCommands(results.analysis.missingPTRs), 'create-commands')}
clipboard.copy(generateCreateCommands(results.analysis.missingPTRs), 'create-commands')}
>
<Icon name={copiedStates['create-commands'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('create-commands') ? 'check' : 'copy'} size="sm" />
Copy Zone Lines
</button>
</div>
+11 -17
View File
@@ -1,13 +1,14 @@
<script lang="ts">
import { Copy, Download, Check, Mail } from 'lucide-svelte';
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
let domain = $state('');
let mailboxDname = $state('admin.example.com.');
let txtDname = $state('admin-info.example.com.');
let showExamples = $state(false);
let buttonStates = $state({} as Record<string, boolean>);
const clipboard = useClipboard();
const roleExamples = [
{
@@ -101,20 +102,12 @@
return infos;
});
function showButtonSuccess(buttonId: string) {
buttonStates[buttonId] = true;
setTimeout(() => {
buttonStates[buttonId] = false;
}, 2000);
}
function copyToClipboard() {
let content = rpRecord;
if (txtRecord) {
content += '\n\n; Suggested TXT record:\n' + txtRecord;
}
navigator.clipboard.writeText(content);
showButtonSuccess('copy');
clipboard.copy(content, 'copy');
}
function downloadRecord() {
@@ -134,7 +127,7 @@
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showButtonSuccess('download');
clipboard.copy('downloaded', 'download');
}
function loadRoleExample(role: { name: string; description: string; mbox: string; txt: string }) {
@@ -306,10 +299,10 @@
<button
onclick={copyToClipboard}
class="btn-secondary"
class:success={buttonStates.copy}
style="transform: {buttonStates.copy ? 'scale(1.05)' : 'scale(1)'}"
class:success={clipboard.isCopied('copy')}
style="transform: {clipboard.isCopied('copy') ? 'scale(1.05)' : 'scale(1)'}"
>
{#if buttonStates.copy}
{#if clipboard.isCopied('copy')}
<Check size="16" />
Copied!
{:else}
@@ -320,10 +313,10 @@
<button
onclick={downloadRecord}
class="btn-primary"
class:success={buttonStates.download}
style="transform: {buttonStates.download ? 'scale(1.05)' : 'scale(1)'}"
class:success={clipboard.isCopied('download')}
style="transform: {clipboard.isCopied('download') ? 'scale(1.05)' : 'scale(1)'}"
>
{#if buttonStates.download}
{#if clipboard.isCopied('download')}
<Check size="16" />
Downloaded!
{:else}
@@ -392,6 +385,7 @@
<style lang="scss">
.card {
width: 100%;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-lg);
+12 -19
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import {
suggestRRSIGWindows,
formatRRSIGDates,
@@ -14,7 +15,7 @@
let clockSkew = $state(1);
let signatureValidityDays = $state(30);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
const planningOptions = $derived({
ttl,
@@ -34,25 +35,13 @@
const currentValidation = $derived(currentWindow ? validateRRSIGTiming(currentWindow, ttl) : null);
async function copyToClipboard(text: string, key: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[key] = true;
setTimeout(() => {
copiedStates[key] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
function copyCurrentWindow() {
if (!currentWindowFormatted) return;
const text = `RRSIG Timing Window:
Inception: ${currentWindowFormatted.inceptionFormatted} (${currentWindowFormatted.inceptionTimestamp})
Expiration: ${currentWindowFormatted.expirationFormatted} (${currentWindowFormatted.expirationTimestamp})
Renewal Time: ${currentWindowFormatted.renewalFormatted}`;
copyToClipboard(text, 'current');
clipboard.copy(text, 'current');
}
function copyBothWindows() {
@@ -68,7 +57,7 @@ Next Window:
Inception: ${nextWindowFormatted.inceptionFormatted} (${nextWindowFormatted.inceptionTimestamp})
Expiration: ${nextWindowFormatted.expirationFormatted} (${nextWindowFormatted.expirationTimestamp})
Renewal Time: ${nextWindowFormatted.renewalFormatted}`;
copyToClipboard(text, 'both');
clipboard.copy(text, 'both');
}
function formatDuration(hours: number): string {
@@ -214,8 +203,8 @@ Renewal Time: ${nextWindowFormatted.renewalFormatted}`;
<div class="card window-card">
<div class="window-header">
<h3>Current Signature Window</h3>
<button class="copy-button {copiedStates.current ? 'copied' : ''}" onclick={copyCurrentWindow}>
<Icon name={copiedStates.current ? 'check' : 'copy'} size="sm" />
<button class="copy-button {clipboard.isCopied('current') ? 'copied' : ''}" onclick={copyCurrentWindow}>
<Icon name={clipboard.isCopied('current') ? 'check' : 'copy'} size="sm" />
Copy
</button>
</div>
@@ -302,8 +291,8 @@ Renewal Time: ${nextWindowFormatted.renewalFormatted}`;
</div>
<div class="copy-schedule-section">
<button class="copy-button {copiedStates.both ? 'copied' : ''}" onclick={copyBothWindows}>
<Icon name={copiedStates.both ? 'check' : 'copy'} size="sm" />
<button class="copy-button {clipboard.isCopied('both') ? 'copied' : ''}" onclick={copyBothWindows}>
<Icon name={clipboard.isCopied('both') ? 'check' : 'copy'} size="sm" />
Copy Full Schedule
</button>
</div>
@@ -379,6 +368,10 @@ Renewal Time: ${nextWindowFormatted.renewalFormatted}`;
</div>
<style lang="scss">
.card {
width: 100%;
}
.input-card {
margin-bottom: var(--spacing-lg);
background: var(--bg-tertiary);
+22 -30
View File
@@ -2,6 +2,7 @@
import { tooltip } from '$lib/actions/tooltip.js';
import { generateRandomIPAddresses, type RandomIPResult } from '$lib/utils/random-ip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import '../../../styles/diagnostics-pages.scss';
let inputText = $state('192.168.1.0/24 x 10\n10.0.0.0-10.0.0.255 5\n172.16.0.0/16 * 3\n2001:db8::/64[15]');
@@ -12,7 +13,7 @@
let isLoading = $state(false);
let selectedExampleIndex = $state<number | null>(null);
let _userModified = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
const examples = [
{
@@ -108,21 +109,9 @@
URL.revokeObjectURL(url);
}
async function copyToClipboard(text: string, key: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[key] = true;
setTimeout(() => {
copiedStates[key] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function copyAllIPs() {
if (result && result.allGeneratedIPs.length > 0) {
copyToClipboard(result.allGeneratedIPs.join('\n'), 'all-ips');
clipboard.copy(result.allGeneratedIPs.join('\n'), 'all-ips');
}
}
@@ -277,18 +266,18 @@
<h3>Generation Summary</h3>
<button
class="copy-btn"
class:copied={copiedStates['summary']}
class:copied={clipboard.isCopied('summary')}
onclick={() =>
result &&
result.summary &&
copyToClipboard(
clipboard.copy(
`Total Networks: ${result.summary.totalNetworks}\nValid: ${result.summary.validNetworks}\nInvalid: ${result.summary.invalidNetworks}\nTotal IPs: ${result.summary.totalIPsGenerated}\nUnique IPs: ${result.summary.uniqueIPsGenerated}`,
'summary',
)}
use:tooltip={'Copy summary to clipboard'}
>
<Icon name={copiedStates['summary'] ? 'check' : 'copy'} size="xs" />
{copiedStates['summary'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('summary') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('summary') ? 'Copied!' : 'Copy'}
</button>
</div>
<div class="card-content">
@@ -323,12 +312,12 @@
<div class="export-buttons">
<button
class="copy-btn"
class:copied={copiedStates['all-ips']}
class:copied={clipboard.isCopied('all-ips')}
onclick={copyAllIPs}
use:tooltip={'Copy all generated IPs to clipboard'}
>
<Icon name={copiedStates['all-ips'] ? 'check' : 'copy'} size="xs" />
{copiedStates['all-ips'] ? 'Copied!' : 'Copy All'}
<Icon name={clipboard.isCopied('all-ips') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('all-ips') ? 'Copied!' : 'Copy All'}
</button>
<button onclick={() => exportResults('txt')} use:tooltip={'Export as plain text file'}>
<Icon name="download" size="xs" />
@@ -351,12 +340,12 @@
<button
type="button"
class="ip-tag"
class:copied={copiedStates[`ip-${index}`]}
onclick={() => copyToClipboard(ip, `ip-${index}`)}
class:copied={clipboard.isCopied(`ip-${index}`)}
onclick={() => clipboard.copy(ip, `ip-${index}`)}
use:tooltip={'Click to copy IP address'}
>
{ip}
<Icon name={copiedStates[`ip-${index}`] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(`ip-${index}`) ? 'check' : 'copy'} size="xs" />
</button>
{/each}
</div>
@@ -413,7 +402,7 @@
<button
type="button"
class="code-button info-code"
onclick={() => copyToClipboard(generation.seed!, 'seed')}
onclick={() => clipboard.copy(generation.seed!, 'seed')}
title="Click to copy"
>
{generation.seed}
@@ -432,7 +421,7 @@
<button
type="button"
class="code-button range-code"
onclick={() => copyToClipboard(generation.networkDetails!.start, 'start')}
onclick={() => clipboard.copy(generation.networkDetails!.start, 'start')}
title="Click to copy"
>
{generation.networkDetails.start}
@@ -444,7 +433,7 @@
<button
type="button"
class="code-button range-code"
onclick={() => copyToClipboard(generation.networkDetails!.end, 'end')}
onclick={() => clipboard.copy(generation.networkDetails!.end, 'end')}
title="Click to copy"
>
{generation.networkDetails.end}
@@ -469,12 +458,15 @@
<button
type="button"
class="ip-tag"
class:copied={copiedStates[`gen-${index}-ip-${ipIndex}`]}
onclick={() => copyToClipboard(ip, `gen-${index}-ip-${ipIndex}`)}
class:copied={clipboard.isCopied(`gen-${index}-ip-${ipIndex}`)}
onclick={() => clipboard.copy(ip, `gen-${index}-ip-${ipIndex}`)}
use:tooltip={'Click to copy IP address'}
>
{ip}
<Icon name={copiedStates[`gen-${index}-ip-${ipIndex}`] ? 'check' : 'copy'} size="xs" />
<Icon
name={clipboard.isCopied(`gen-${index}-ip-${ipIndex}`) ? 'check' : 'copy'}
size="xs"
/>
</button>
{/each}
</div>
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import { generatePTRName, generateCIDRPTRs, type PTRRecord } from '$lib/utils/reverse-dns.js';
let inputValue = $state('192.168.1.100');
@@ -16,7 +17,7 @@
uniqueZones: number;
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -119,18 +120,6 @@
generatePTRs();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// Generate on component load
generatePTRs();
</script>
@@ -290,10 +279,10 @@
<div class="col-ptr">
<code>{entry.ptrName}</code>
<button
class="copy-button {copiedStates[`ptr-${entry.ip}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(entry.ptrName, `ptr-${entry.ip}`)}
class="copy-button {clipboard.isCopied(`ptr-${entry.ip}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(entry.ptrName, `ptr-${entry.ip}`)}
>
<Icon name={copiedStates[`ptr-${entry.ip}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`ptr-${entry.ip}`) ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="col-zone-line">
@@ -304,14 +293,14 @@
{/snippet}
{@render zoneLine()}
<button
class="copy-button {copiedStates[`zone-${entry.ip}`] ? 'copied' : ''}"
class="copy-button {clipboard.isCopied(`zone-${entry.ip}`) ? 'copied' : ''}"
onclick={() => {
const recordName = entry.ptrName.replace(`.${entry.zone}`, '').replace(/\.$/, '');
const hostname = `host-${entry.ip.replace(/[:.]/g, '-')}.example.com.`;
copyToClipboard(`${recordName} IN PTR ${hostname}`, `zone-${entry.ip}`);
clipboard.copy(`${recordName} IN PTR ${hostname}`, `zone-${entry.ip}`);
}}
>
<Icon name={copiedStates[`zone-${entry.ip}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`zone-${entry.ip}`) ? 'check' : 'copy'} size="sm" />
</button>
</div>
<div class="col-type">
@@ -1,6 +1,7 @@
<script lang="ts">
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { useClipboard } from '$lib/composables';
import {
generateCIDRPTRs,
generateReverseZoneFile,
@@ -30,7 +31,7 @@
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -148,18 +149,6 @@
generateZones();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
// Generate on component load
generateZones();
</script>
@@ -361,10 +350,10 @@
</div>
</div>
<button
class="copy-button {copiedStates[`zone-${index}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(zone.content, `zone-${index}`)}
class="copy-button {clipboard.isCopied(`zone-${index}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(zone.content, `zone-${index}`)}
>
<Icon name={copiedStates[`zone-${index}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`zone-${index}`) ? 'check' : 'copy'} size="sm" />
Copy Zone File
</button>
</div>
@@ -2,6 +2,7 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { calculateReverseZones, type ReverseZoneInfo } from '$lib/utils/reverse-dns.js';
import { useClipboard } from '$lib/composables';
let cidrInput = $state('192.168.1.0/24');
let results = $state<{
@@ -16,7 +17,7 @@
};
} | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -116,18 +117,6 @@
calculateZones();
}
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
function generateBindConfig(zones: ReverseZoneInfo[]): string {
return zones
.map(
@@ -269,10 +258,10 @@ chmod 644 /etc/bind/zones/${zone.zone}`;
</div>
</div>
<button
class="copy-button {copiedStates[`zone-${index}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(zone.zone, `zone-${index}`)}
class="copy-button {clipboard.isCopied(`zone-${index}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(zone.zone, `zone-${index}`)}
>
<Icon name={copiedStates[`zone-${index}`] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`zone-${index}`) ? 'check' : 'copy'} size="sm" />
</button>
</div>
@@ -310,10 +299,10 @@ chmod 644 /etc/bind/zones/${zone.zone}`;
<div class="config-header">
<h5>BIND9 Configuration</h5>
<button
class="copy-button {copiedStates['bind-config'] ? 'copied' : ''}"
onclick={() => results && copyToClipboard(generateBindConfig(results.zones), 'bind-config')}
class="copy-button {clipboard.isCopied('bind-config') ? 'copied' : ''}"
onclick={() => results && clipboard.copy(generateBindConfig(results.zones), 'bind-config')}
>
<Icon name={copiedStates['bind-config'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('bind-config') ? 'check' : 'copy'} size="sm" />
Copy Config
</button>
</div>
@@ -325,11 +314,10 @@ chmod 644 /etc/bind/zones/${zone.zone}`;
<div class="config-header">
<h5>Zone File Setup Commands</h5>
<button
class="copy-button {copiedStates['setup-commands'] ? 'copied' : ''}"
onclick={() =>
results && copyToClipboard(generateDelegationCommands(results.zones), 'setup-commands')}
class="copy-button {clipboard.isCopied('setup-commands') ? 'copied' : ''}"
onclick={() => results && clipboard.copy(generateDelegationCommands(results.zones), 'setup-commands')}
>
<Icon name={copiedStates['setup-commands'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('setup-commands') ? 'check' : 'copy'} size="sm" />
Copy Commands
</button>
</div>
+14 -17
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip';
import { useClipboard } from '$lib/composables';
interface _SSHFPRecord {
algorithm: number;
@@ -20,7 +21,7 @@
let selectedExample = $state<string | null>(null);
// Button success states
let buttonStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
const algorithmDescriptions = {
1: 'RSA - Traditional RSA algorithm (most common)',
@@ -121,16 +122,8 @@
};
});
function showButtonSuccess(buttonId: string): void {
buttonStates[buttonId] = true;
setTimeout(() => {
buttonStates[buttonId] = false;
}, 2000);
}
function copyToClipboard(text: string, buttonId: string): void {
navigator.clipboard.writeText(text);
showButtonSuccess(buttonId);
clipboard.copy(text, buttonId);
}
function exportAsZoneFile(): void {
@@ -146,7 +139,7 @@
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showButtonSuccess('export-sshfp');
clipboard.copy('downloaded', 'export-sshfp');
}
// Simulate fingerprint generation from public key
@@ -347,22 +340,22 @@
<button
type="button"
class="copy-btn"
class:success={buttonStates['copy-sshfp']}
class:success={clipboard.isCopied('copy-sshfp')}
onclick={() => copyToClipboard(dnsRecord, 'copy-sshfp')}
use:tooltip={'Copy SSHFP record to clipboard'}
>
<Icon name={buttonStates['copy-sshfp'] ? 'check' : 'copy'} size="sm" />
{buttonStates['copy-sshfp'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('copy-sshfp') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('copy-sshfp') ? 'Copied!' : 'Copy'}
</button>
<button
type="button"
class="export-btn"
class:success={buttonStates['export-sshfp']}
class:success={clipboard.isCopied('export-sshfp')}
onclick={exportAsZoneFile}
use:tooltip={'Download as zone file'}
>
<Icon name={buttonStates['export-sshfp'] ? 'check' : 'download'} size="sm" />
{buttonStates['export-sshfp'] ? 'Downloaded!' : 'Export'}
<Icon name={clipboard.isCopied('export-sshfp') ? 'check' : 'download'} size="sm" />
{clipboard.isCopied('export-sshfp') ? 'Downloaded!' : 'Export'}
</button>
</div>
</div>
@@ -514,6 +507,10 @@
</div>
<style lang="scss">
.card {
width: 100%;
}
.domain-section,
.sshfp-parameters-section,
.input-data-section {
@@ -1,6 +1,7 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip';
import { useClipboard } from '$lib/composables';
interface ServiceParameter {
key: string;
@@ -34,7 +35,7 @@
let selectedExample = $state<string | null>(null);
// Button success states
let buttonStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
const parameterDescriptions = {
mandatory: 'Mandatory parameters that must be understood by the client',
@@ -186,18 +187,6 @@
};
});
function showButtonSuccess(buttonId: string): void {
buttonStates[buttonId] = true;
setTimeout(() => {
buttonStates[buttonId] = false;
}, 2000);
}
function copyToClipboard(text: string, buttonId: string): void {
navigator.clipboard.writeText(text);
showButtonSuccess(buttonId);
}
function exportAsZoneFile(): void {
if (!dnsRecord) return;
@@ -211,7 +200,7 @@
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showButtonSuccess('export-svcb');
clipboard.copy('downloaded', 'export-svcb');
}
function _addParameter(key: string): void {
@@ -401,22 +390,22 @@
<button
type="button"
class="copy-btn"
class:success={buttonStates['copy-svcb']}
onclick={() => copyToClipboard(dnsRecord, 'copy-svcb')}
class:success={clipboard.isCopied('copy-svcb')}
onclick={() => clipboard.copy(dnsRecord, 'copy-svcb')}
use:tooltip={'Copy record to clipboard'}
>
<Icon name={buttonStates['copy-svcb'] ? 'check' : 'copy'} size="sm" />
{buttonStates['copy-svcb'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('copy-svcb') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('copy-svcb') ? 'Copied!' : 'Copy'}
</button>
<button
type="button"
class="export-btn"
class:success={buttonStates['export-svcb']}
class:success={clipboard.isCopied('export-svcb')}
onclick={exportAsZoneFile}
use:tooltip={'Download as zone file'}
>
<Icon name={buttonStates['export-svcb'] ? 'check' : 'download'} size="sm" />
{buttonStates['export-svcb'] ? 'Downloaded!' : 'Export'}
<Icon name={clipboard.isCopied('export-svcb') ? 'check' : 'download'} size="sm" />
{clipboard.isCopied('export-svcb') ? 'Downloaded!' : 'Export'}
</button>
</div>
</div>
@@ -1,13 +1,30 @@
<script lang="ts">
import { calculateSubnet } from '$lib/utils/ip-calculations.js';
import { validateCIDR } from '$lib/utils/ip-validation.js';
import { formatNumber } from '$lib/utils/formatters.js';
import CIDRInput from '$lib/components/tools/CIDRInput.svelte';
import NetworkVisualizer from '$lib/components/tools/NetworkVisualizer.svelte';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import SvgIcon from '$lib/components/global/SvgIcon.svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import { goto } from '$app/navigation';
import type { SubnetInfo } from '$lib/types/ip.js';
const versionOptions = [
{ value: 'ipv4' as const, label: 'IPv4' },
{ value: 'ipv6' as const, label: 'IPv6' },
];
let selectedVersion = $state<'ipv4' | 'ipv6'>('ipv4');
function handleVersionChange(version: 'ipv4' | 'ipv6') {
if (version === 'ipv6') {
goto('/subnetting/ipv6-subnet-calculator');
}
}
let cidrInput = $state('192.168.1.0/24');
let subnetInfo: SubnetInfo | null = $state(null);
let isCalculating = $state(false);
@@ -33,37 +50,16 @@
}
});
/**
* Format large numbers
*/
function formatNumber(num: number): string {
return num.toLocaleString();
}
let copiedStates = $state<Record<string, boolean>>({});
/**
* Copy to clipboard with visual feedback
*/
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
const clipboard = useClipboard();
</script>
<div class="card">
<header class="card-header">
<h2>Subnet Calculator</h2>
<p>Calculate network, broadcast, and host information for any subnet.</p>
</header>
<ToolContentContainer
title="Subnet Calculator"
description="Calculate network, broadcast, and host information for any subnet."
navOptions={versionOptions}
bind:selectedNav={selectedVersion}
onNavChange={handleVersionChange}
>
<!-- Input -->
<div class="form-group">
<CIDRInput bind:value={cidrInput} label="Network Address (CIDR)" placeholder="192.168.1.0/24" />
@@ -85,14 +81,17 @@
<span class="info-label" use:tooltip={'First IP in subnet - identifies the network'}>Network Address</span>
<div class="value-copy">
<code class="ip-value success">{subnetInfo.network.octets.join('.')}</code>
<Tooltip text={copiedStates['network'] ? 'Copied!' : 'Copy network address to clipboard'} position="top">
<Tooltip
text={clipboard.isCopied('network') ? 'Copied!' : 'Copy network address to clipboard'}
position="top"
>
<button
type="button"
class="btn-icon copy-btn {copiedStates['network'] ? 'copied' : ''}"
onclick={() => copyToClipboard(subnetInfo!.network.octets.join('.'), 'network')}
class="btn-icon copy-btn {clipboard.isCopied('network') ? 'copied' : ''}"
onclick={() => clipboard.copy(subnetInfo!.network.octets.join('.'), 'network')}
aria-label="Copy network address"
>
<SvgIcon icon={copiedStates['network'] ? 'check' : 'clipboard'} size="md" />
<SvgIcon icon={clipboard.isCopied('network') ? 'check' : 'clipboard'} size="md" />
</button>
</Tooltip>
</div>
@@ -103,16 +102,16 @@
<div class="value-copy">
<code class="ip-value error">{subnetInfo.broadcast.octets.join('.')}</code>
<Tooltip
text={copiedStates['broadcast'] ? 'Copied!' : 'Copy broadcast address to clipboard'}
text={clipboard.isCopied('broadcast') ? 'Copied!' : 'Copy broadcast address to clipboard'}
position="top"
>
<button
type="button"
class="btn-icon copy-btn {copiedStates['broadcast'] ? 'copied' : ''}"
onclick={() => copyToClipboard(subnetInfo!.broadcast.octets.join('.'), 'broadcast')}
class="btn-icon copy-btn {clipboard.isCopied('broadcast') ? 'copied' : ''}"
onclick={() => clipboard.copy(subnetInfo!.broadcast.octets.join('.'), 'broadcast')}
aria-label="Copy broadcast address"
>
<SvgIcon icon={copiedStates['broadcast'] ? 'check' : 'clipboard'} size="md" />
<SvgIcon icon={clipboard.isCopied('broadcast') ? 'check' : 'clipboard'} size="md" />
</button>
</Tooltip>
</div>
@@ -268,7 +267,7 @@
</ul>
</div>
</section>
</div>
</ToolContentContainer>
<style lang="scss">
.explainer-section {
@@ -300,6 +299,10 @@
}
}
.value-copy {
flex: none;
}
.explainer-card {
cursor: default;
}
+25 -32
View File
@@ -3,12 +3,15 @@
import { tooltip } from '$lib/actions/tooltip.js';
import _Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let parentCIDR = $state('192.168.1.0/24');
let strategy = $state<'preserve-order' | 'fit-best'>('fit-best');
let usableHosts = $state(true);
let result = $state<PlannerResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let showVisualization = $state(true);
let draggedIndex = $state<number | null>(null);
@@ -82,17 +85,6 @@
performPlanning();
}
/* Copy to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
/* Export results */
function exportResults(format: 'csv' | 'json') {
if (!result || result.allocated.length === 0) return;
@@ -125,7 +117,7 @@
content = [headers, ...rows].map((row) => row.join(',')).join('\n');
}
copyToClipboard(content, `export-${format}`);
clipboard.copy(content, `export-${format}`);
}
/* Handle drag and drop reordering */
@@ -203,10 +195,10 @@
type: 'allocated' | 'leftover',
): string {
if (type === 'allocated' && item.name) {
const size = item.start && item.end ? (item.end - item.start + 1n).toLocaleString() : 'Unknown';
const size = item.start && item.end ? formatNumber(Number(item.end - item.start + 1n)) : 'Unknown';
return `${item.name}\n${item.cidr}\nSize: ${size} addresses`;
} else {
const size = item.start && item.end ? (item.end - item.start + 1n).toLocaleString() : 'Unknown';
const size = item.start && item.end ? formatNumber(Number(item.end - item.start + 1n)) : 'Unknown';
return `Leftover Space\n${item.cidr}\nSize: ${size} addresses`;
}
}
@@ -219,12 +211,10 @@
});
</script>
<div class="card">
<header class="card-header">
<h2>Subnet Planner (VLSM)</h2>
<p>Design Variable Length Subnet Mask (VLSM) allocations with drag-and-drop reordering and space optimization.</p>
</header>
<ToolContentContainer
title="Subnet Planner (VLSM)"
description="Design Variable Length Subnet Mask (VLSM) allocations with drag-and-drop reordering and space optimization."
>
<!-- Strategy Selection -->
<div class="strategy-section">
<h3>Allocation Strategy</h3>
@@ -398,19 +388,19 @@
<button
type="button"
class="btn btn-primary btn-sm"
class:copied={copiedStates['export-csv']}
class:copied={clipboard.isCopied('export-csv')}
onclick={() => exportResults('csv')}
>
<Icon name={copiedStates['export-csv'] ? 'check' : 'download'} size="sm" />
<Icon name={clipboard.isCopied('export-csv') ? 'check' : 'download'} size="sm" />
CSV
</button>
<button
type="button"
class="btn btn-secondary btn-sm"
class:copied={copiedStates['export-json']}
class:copied={clipboard.isCopied('export-json')}
onclick={() => exportResults('json')}
>
<Icon name={copiedStates['export-json'] ? 'check' : 'download'} size="sm" />
<Icon name={clipboard.isCopied('export-json') ? 'check' : 'download'} size="sm" />
JSON
</button>
</div>
@@ -456,7 +446,7 @@
class="btn btn-secondary btn-xs"
onclick={() => (showVisualization = !showVisualization)}
>
<Icon name="eye-off" size="xs" />
<Icon name="hide" size="xs" />
Hide
</button>
</div>
@@ -545,10 +535,10 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[subnet.cidr]}
onclick={() => copyToClipboard(subnet.cidr, subnet.cidr)}
class:copied={clipboard.isCopied(subnet.cidr)}
onclick={() => clipboard.copy(subnet.cidr, subnet.cidr)}
>
<Icon name={copiedStates[subnet.cidr] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(subnet.cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -583,7 +573,7 @@
{/if}
</div>
{/if}
</div>
</ToolContentContainer>
<style lang="scss">
/* Reusable tokens */
@@ -636,7 +626,6 @@
.options {
.checkbox-label {
display: flex;
align-items: flex-start;
gap: var(--spacing-sm);
cursor: pointer;
@@ -1162,7 +1151,7 @@
}
/* Responsive */
@media (max-width: 768px) {
@media (max-width: 600px) {
.requests-header {
flex-direction: column;
gap: var(--spacing-sm);
@@ -1171,7 +1160,11 @@
.request-item {
flex-direction: column;
align-items: flex-start;
gap: var(--spacing-sm);
.drag-handle {
display: none;
}
.request-fields {
width: 100%;
@@ -8,11 +8,14 @@
} from '$lib/utils/supernet-calculations.js';
import IPInput from './IPInput.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import { tooltip } from '$lib/actions/tooltip.js';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let networks = $state<NetworkInput[]>([]);
let supernetResult = $state<SupernetResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let showVisualization = $state(false);
let selectedExample = $state<string | null>(null);
let _userModified = $state(false);
@@ -55,22 +58,6 @@
/* Calculate supernet - now handled by reactive effect */
/* Copy text to clipboard */
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
// Force reactivity by creating new object
copiedStates = { ...copiedStates, [id]: true };
setTimeout(() => {
const currentStates = { ...copiedStates };
delete currentStates[id];
copiedStates = currentStates;
}, 1000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
const examples = [
{
label: 'Contiguous Networks',
@@ -178,14 +165,11 @@
});
</script>
<div class="card supernet-calc-car">
<header class="card-header">
<h2>Supernet Calculator</h2>
<p>
Aggregate multiple networks into a single supernet for route summarization and efficient routing table management.
</p>
</header>
<ToolContentContainer
title="Supernet Calculator"
description="Aggregate multiple networks into a single supernet for route summarization and efficient routing table management."
contentClass="supernet-calc-car"
>
<!-- Quick Examples -->
<div class="card examples-card">
<details class="examples-details">
@@ -325,12 +309,12 @@
<span class="ip-value success">{supernetResult.supernet.network}/{supernetResult.supernet.cidr}</span>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['supernet']}
class:copied={clipboard.isCopied('supernet')}
onclick={() =>
supernetResult?.supernet &&
copyToClipboard(`${supernetResult.supernet.network}/${supernetResult.supernet.cidr}`, 'supernet')}
clipboard.copy(`${supernetResult.supernet.network}/${supernetResult.supernet.cidr}`, 'supernet')}
>
<Icon name={copiedStates['supernet'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('supernet') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -338,7 +322,7 @@
<span class="summary-label" use:tooltip={'Total number of host addresses available in the supernet'}
>Total Hosts</span
>
<span class="summary-value">{supernetResult.supernet.totalHosts.toLocaleString()}</span>
<span class="summary-value">{formatNumber(supernetResult.supernet.totalHosts)}</span>
</div>
</div>
</div>
@@ -395,11 +379,10 @@
<code class="detail-value">{supernetResult.supernet.network}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['network']}
onclick={() =>
supernetResult?.supernet && copyToClipboard(supernetResult.supernet.network, 'network')}
class:copied={clipboard.isCopied('network')}
onclick={() => supernetResult?.supernet && clipboard.copy(supernetResult.supernet.network, 'network')}
>
<Icon name={copiedStates['network'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('network') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -416,11 +399,10 @@
<code class="detail-value">{supernetResult.supernet.subnetMask}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['mask']}
onclick={() =>
supernetResult?.supernet && copyToClipboard(supernetResult.supernet.subnetMask, 'mask')}
class:copied={clipboard.isCopied('mask')}
onclick={() => supernetResult?.supernet && clipboard.copy(supernetResult.supernet.subnetMask, 'mask')}
>
<Icon name={copiedStates['mask'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('mask') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -437,11 +419,11 @@
<code class="detail-value">{supernetResult.supernet.wildcardMask}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['wildcard']}
class:copied={clipboard.isCopied('wildcard')}
onclick={() =>
supernetResult?.supernet && copyToClipboard(supernetResult.supernet.wildcardMask, 'wildcard')}
supernetResult?.supernet && clipboard.copy(supernetResult.supernet.wildcardMask, 'wildcard')}
>
<Icon name={copiedStates['wildcard'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('wildcard') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -460,15 +442,15 @@
</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['range']}
class:copied={clipboard.isCopied('range')}
onclick={() =>
supernetResult?.supernet &&
copyToClipboard(
clipboard.copy(
`${supernetResult.supernet.addressRange.first} - ${supernetResult.supernet.addressRange.last}`,
'range',
)}
>
<Icon name={copiedStates['range'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('range') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -485,11 +467,11 @@
<code class="detail-value binary-mask">{supernetResult.supernet.binaryMask}</code>
<button
class="btn btn-icon copy-btn"
class:copied={copiedStates['binary']}
class:copied={clipboard.isCopied('binary')}
onclick={() =>
supernetResult?.supernet && copyToClipboard(supernetResult.supernet.binaryMask, 'binary')}
supernetResult?.supernet && clipboard.copy(supernetResult.supernet.binaryMask, 'binary')}
>
<Icon name={copiedStates['binary'] ? 'check' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied('binary') ? 'check' : 'copy'} size="sm" />
</button>
</div>
</div>
@@ -530,7 +512,7 @@
<h5>Supernet</h5>
<div class="supernet-bar">
<span class="supernet-label">{supernetResult.supernet.network}/{supernetResult.supernet.cidr}</span>
<span class="supernet-hosts">{supernetResult.supernet.totalHosts.toLocaleString()} hosts</span>
<span class="supernet-hosts">{formatNumber(supernetResult.supernet.totalHosts)} hosts</span>
</div>
</div>
</div>
@@ -546,17 +528,9 @@
{/if}
</div>
{/if}
</div>
</ToolContentContainer>
<style>
.supernet-calc-car .btn {
:global(.icon) {
width: 1.2rem;
height: 1.2rem;
vertical-align: middle;
}
}
.examples-card {
margin-bottom: var(--spacing-lg);
}
+11 -17
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import Icon from '$lib/components/global/Icon.svelte';
import { tooltip } from '$lib/actions/tooltip';
import { useClipboard } from '$lib/composables';
let domain = $state('example.com');
let port = $state(443);
@@ -15,7 +16,7 @@
let showExamples = $state(false);
let selectedExample = $state<string | null>(null);
let buttonStates = $state({} as Record<string, boolean>);
const clipboard = useClipboard();
const usageDescriptions = {
0: 'CA Constraint - Certificate must be issued by the CA represented in the TLSA record',
@@ -118,16 +119,8 @@
};
});
function showButtonSuccess(buttonId: string) {
buttonStates[buttonId] = true;
setTimeout(() => {
buttonStates[buttonId] = false;
}, 2000);
}
function copyToClipboard(text: string, buttonId: string) {
navigator.clipboard.writeText(text);
showButtonSuccess(buttonId);
clipboard.copy(text, buttonId);
}
function exportAsZoneFile() {
@@ -143,7 +136,7 @@
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showButtonSuccess('export-tlsa');
clipboard.copy('downloaded', 'export-tlsa');
}
async function generateHashFromInput() {
@@ -380,22 +373,22 @@
<button
type="button"
class="btn btn-primary"
class:success={buttonStates['copy-tlsa']}
class:success={clipboard.isCopied('copy-tlsa')}
onclick={() => copyToClipboard(dnsRecord, 'copy-tlsa')}
use:tooltip={'Copy TLSA record to clipboard'}
>
<Icon name={buttonStates['copy-tlsa'] ? 'check' : 'copy'} size="sm" />
{buttonStates['copy-tlsa'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('copy-tlsa') ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied('copy-tlsa') ? 'Copied!' : 'Copy'}
</button>
<button
type="button"
class="btn btn-success"
class:success={buttonStates['export-tlsa']}
class:success={clipboard.isCopied('export-tlsa')}
onclick={exportAsZoneFile}
use:tooltip={'Download as zone file'}
>
<Icon name={buttonStates['export-tlsa'] ? 'check' : 'download'} size="sm" />
{buttonStates['export-tlsa'] ? 'Downloaded!' : 'Export'}
<Icon name={clipboard.isCopied('export-tlsa') ? 'check' : 'download'} size="sm" />
{clipboard.isCopied('export-tlsa') ? 'Downloaded!' : 'Export'}
</button>
</div>
</div>
@@ -530,6 +523,7 @@
}
.card {
width: 100%;
background: var(--bg-secondary);
border: 1px solid var(--border-primary);
border-radius: var(--radius-lg);
+7 -17
View File
@@ -2,6 +2,8 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { humanizeTTL, calculateCacheExpiry, type TTLInfo } from '$lib/utils/dns-validation.js';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let ttlInput = $state('3600');
let customDate = $state('');
@@ -16,7 +18,7 @@
customDateValid: boolean;
} | null>(null);
let copiedState = $state(false);
const clipboard = useClipboard();
const commonTTLs = [
{ seconds: 60, label: '1 minute', description: 'Very short - high DNS load' },
@@ -128,18 +130,6 @@
}
}
async function copyTTL() {
try {
await navigator.clipboard.writeText(ttlInput);
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
}
function handleInputChange() {
// Clear active states when user manually changes input
activeTTLIndex = null;
@@ -268,8 +258,8 @@
<div class="card results-card">
<div class="results-header">
<h3>TTL Analysis</h3>
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyTTL}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
<button class="copy-button {clipboard.isCopied() ? 'copied' : ''}" onclick={() => clipboard.copy(ttlInput)}>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
Copy TTL
</button>
</div>
@@ -282,7 +272,7 @@
<span class="ttl-category {results.ttlInfo.category}">{results.ttlInfo.category.replace('-', ' ')}</span>
</div>
<div class="ttl-seconds-display">
<span class="seconds-value">{results.ttlInfo.seconds.toLocaleString()}</span>
<span class="seconds-value">{formatNumber(results.ttlInfo.seconds)}</span>
<span class="seconds-label">seconds</span>
</div>
</div>
@@ -607,7 +597,7 @@
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
color: var(--bg-secondary);
font-size: 14px;
font-weight: bold;
line-height: 1;
+16 -27
View File
@@ -10,14 +10,17 @@
import IPInput from './IPInput.svelte';
import Tooltip from '$lib/components/global/Tooltip.svelte';
import Icon from '$lib/components/global/Icon.svelte';
import ToolContentContainer from '$lib/components/global/ToolContentContainer.svelte';
import { useClipboard } from '$lib/composables';
import { tooltip } from '$lib/actions/tooltip.js';
import { SvelteSet } from 'svelte/reactivity';
import { formatNumber } from '$lib/utils/formatters';
let networkIP = $state('192.168.1.0');
let cidr = $state(24);
let subnets = $state<SubnetRequirement[]>([]);
let vlsmResult = $state<VLSMResult | null>(null);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let expandedSubnets = new SvelteSet<string>();
// Add initial subnet requirement
@@ -115,18 +118,6 @@
/**
* Copy text to clipboard
*/
async function copyToClipboard(text: string, id: string) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => {
copiedStates[id] = false;
}, 1000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
}
/**
* Get efficiency color based on waste percentage
*/
@@ -145,12 +136,10 @@
});
</script>
<div class="card">
<header class="card-header">
<h2>VLSM Calculator</h2>
<p>Design efficient subnets with Variable Length Subnet Masking for optimal address space utilization.</p>
</header>
<ToolContentContainer
title="VLSM Calculator"
description="Design efficient subnets with Variable Length Subnet Masking for optimal address space utilization."
>
<!-- Network Configuration -->
<div class="network-config">
<h3>Network Configuration</h3>
@@ -244,15 +233,15 @@
</div>
<div class="stat-item">
<span class="stat-label">Hosts Requested</span>
<span class="stat-value">{vlsmResult.totalHostsRequested.toLocaleString()}</span>
<span class="stat-value">{formatNumber(vlsmResult.totalHostsRequested)}</span>
</div>
<div class="stat-item">
<span class="stat-label">Hosts Provided</span>
<span class="stat-value">{vlsmResult.totalHostsProvided.toLocaleString()}</span>
<span class="stat-value">{formatNumber(vlsmResult.totalHostsProvided)}</span>
</div>
<div class="stat-item">
<span class="stat-label">Wasted Hosts</span>
<span class="stat-value danger">{vlsmResult.totalWastedHosts.toLocaleString()}</span>
<span class="stat-value danger">{formatNumber(vlsmResult.totalWastedHosts)}</span>
</div>
<div class="stat-item">
<span class="stat-label">Efficiency</span>
@@ -265,7 +254,7 @@
</div>
<div class="stat-item">
<span class="stat-label">Remaining Addresses</span>
<span class="stat-value">{vlsmResult.remainingAddresses.toLocaleString()}</span>
<span class="stat-value">{formatNumber(vlsmResult.remainingAddresses)}</span>
</div>
</div>
</div>
@@ -338,10 +327,10 @@
<Tooltip text="Copy network info" position="left">
<button
type="button"
class="btn btn-ghost {copiedStates[`copy-${subnet.id}`] ? 'copied' : ''}"
onclick={() => copyToClipboard(`${subnet.networkAddress}/${subnet.cidr}`, `copy-${subnet.id}`)}
class="btn btn-ghost {clipboard.isCopied(`copy-${subnet.id}`) ? 'copied' : ''}"
onclick={() => clipboard.copy(`${subnet.networkAddress}/${subnet.cidr}`, `copy-${subnet.id}`)}
>
<Icon name={copiedStates[`copy-${subnet.id}`] ? 'tick' : 'copy'} size="sm" />
<Icon name={clipboard.isCopied(`copy-${subnet.id}`) ? 'tick' : 'copy'} size="sm" />
</button>
</Tooltip>
</div>
@@ -424,7 +413,7 @@
{/if}
</div>
{/if}
</div>
</ToolContentContainer>
<style>
.btn {
+23 -31
View File
@@ -3,11 +3,13 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import '../../../styles/diagnostics-pages.scss';
import { useClipboard } from '$lib/composables';
import { formatNumber } from '$lib/utils/formatters';
let inputText = $state('192.168.1.0/24\n10.0.0.0 255.255.255.0\n172.16.0.0 0.0.255.255');
let result = $state<WildcardResult | null>(null);
let isLoading = $state(false);
let copiedStates = $state<Record<string, boolean>>({});
const clipboard = useClipboard();
let _selectedExample = $state<string | null>(null);
let selectedExampleIndex = $state<number | null>(null);
let _userModified = $state(false);
@@ -120,21 +122,11 @@
URL.revokeObjectURL(url);
}
async function copyToClipboard(text: string, id: string = text) {
try {
await navigator.clipboard.writeText(text);
copiedStates[id] = true;
setTimeout(() => (copiedStates[id] = false), 3000);
} catch (err) {
console.error('Failed to copy:', err);
}
}
function copyACLRules(type: 'cisco' | 'juniper' | 'generic') {
if (!result) return;
const rules = result.aclRules[type];
if (rules.length > 0) {
copyToClipboard(rules.join('\n'), `acl-${type}`);
clipboard.copy(rules.join('\n'), `acl-${type}`);
}
}
@@ -341,11 +333,11 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[conversion.cidr]}
onclick={() => copyToClipboard(conversion.cidr, conversion.cidr)}
class:copied={clipboard.isCopied(conversion.cidr)}
onclick={() => clipboard.copy(conversion.cidr, conversion.cidr)}
use:tooltip={{ text: 'Copy to clipboard', position: 'top' }}
>
<Icon name={copiedStates[conversion.cidr] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(conversion.cidr) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -359,11 +351,11 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[conversion.subnetMask]}
onclick={() => copyToClipboard(conversion.subnetMask, conversion.subnetMask)}
class:copied={clipboard.isCopied(conversion.subnetMask)}
onclick={() => clipboard.copy(conversion.subnetMask, conversion.subnetMask)}
use:tooltip={{ text: 'Copy to clipboard', position: 'top' }}
>
<Icon name={copiedStates[conversion.subnetMask] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(conversion.subnetMask) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -377,11 +369,11 @@
<button
type="button"
class="btn btn-icon btn-xs"
class:copied={copiedStates[conversion.wildcardMask]}
onclick={() => copyToClipboard(conversion.wildcardMask, conversion.wildcardMask)}
class:copied={clipboard.isCopied(conversion.wildcardMask)}
onclick={() => clipboard.copy(conversion.wildcardMask, conversion.wildcardMask)}
use:tooltip={{ text: 'Copy to clipboard', position: 'top' }}
>
<Icon name={copiedStates[conversion.wildcardMask] ? 'check' : 'copy'} size="xs" />
<Icon name={clipboard.isCopied(conversion.wildcardMask) ? 'check' : 'copy'} size="xs" />
</button>
</div>
</div>
@@ -408,7 +400,7 @@
use:tooltip={'Total assignable host addresses (excluding network and broadcast)'}
>Usable Hosts:</span
>
<span class="info-value">{conversion.usableHosts.toLocaleString()}</span>
<span class="info-value">{formatNumber(conversion.usableHosts)}</span>
</div>
</div>
</div>
@@ -434,11 +426,11 @@
<h4 use:tooltip={'Cisco IOS access control list format'}>Cisco ACL</h4>
<button
onclick={() => copyACLRules('cisco')}
class="copy-btn {copiedStates['acl-cisco'] ? 'copied' : ''}"
class="copy-btn {clipboard.isCopied('acl-cisco') ? 'copied' : ''}"
use:tooltip={'Copy all Cisco ACL rules to clipboard'}
>
<Icon name={copiedStates['acl-cisco'] ? 'check' : 'copy'} size="xs" />
{copiedStates['acl-cisco'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('acl-cisco') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('acl-cisco') ? 'Copied!' : 'Copy'}
</button>
</div>
<div class="acl-code">
@@ -455,11 +447,11 @@
<h4 use:tooltip={'Juniper JunOS firewall filter format'}>Juniper ACL</h4>
<button
onclick={() => copyACLRules('juniper')}
class="copy-btn {copiedStates['acl-juniper'] ? 'copied' : ''}"
class="copy-btn {clipboard.isCopied('acl-juniper') ? 'copied' : ''}"
use:tooltip={'Copy all Juniper ACL rules to clipboard'}
>
<Icon name={copiedStates['acl-juniper'] ? 'check' : 'copy'} size="xs" />
{copiedStates['acl-juniper'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('acl-juniper') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('acl-juniper') ? 'Copied!' : 'Copy'}
</button>
</div>
<div class="acl-code">
@@ -476,11 +468,11 @@
<h4 use:tooltip={'Generic access control list format'}>Generic ACL</h4>
<button
onclick={() => copyACLRules('generic')}
class="copy-btn {copiedStates['acl-generic'] ? 'copied' : ''}"
class="copy-btn {clipboard.isCopied('acl-generic') ? 'copied' : ''}"
use:tooltip={'Copy all generic ACL rules to clipboard'}
>
<Icon name={copiedStates['acl-generic'] ? 'check' : 'copy'} size="xs" />
{copiedStates['acl-generic'] ? 'Copied!' : 'Copy'}
<Icon name={clipboard.isCopied('acl-generic') ? 'check' : 'copy'} size="xs" />
{clipboard.isCopied('acl-generic') ? 'Copied!' : 'Copy'}
</button>
</div>
<div class="acl-code">
+8 -17
View File
@@ -2,12 +2,13 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { parseZoneFile, compareZones, type ZoneDiff, type ResourceRecord } from '$lib/utils/zone-parser.js';
import { useClipboard } from '$lib/composables';
let oldZoneInput = $state('');
let newZoneInput = $state('');
let results = $state<ZoneDiff | null>(null);
let showUnified = $state(false);
let copiedState = $state(false);
const clipboard = useClipboard();
let activeExampleIndex = $state<number | null>(null);
const examples = [
@@ -124,20 +125,10 @@ mail IN A 203.0.113.10
return [record.owner, ttl, record.class, record.type, record.rdata].filter(Boolean).join('\t');
}
async function copyDiff() {
function copyDiff() {
if (!results) return;
const content = showUnified ? generateUnifiedDiff() : formatStructuredDiff();
try {
await navigator.clipboard.writeText(content);
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
const diffText = showUnified ? generateUnifiedDiff() : formatStructuredDiff();
clipboard.copy(diffText);
}
function formatStructuredDiff(): string {
@@ -274,9 +265,9 @@ mail IN A 203.0.113.10
<input type="checkbox" class="styled-checkbox" bind:checked={showUnified} />
<span class="checkbox-text">Unified diff format</span>
</label>
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyDiff}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
{copiedState ? 'Copied!' : 'Copy Diff'}
<button class="copy-button {clipboard.isCopied() ? 'copied' : ''}" onclick={copyDiff}>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied() ? 'Copied!' : 'Copy Diff'}
</button>
</div>
</div>
+7 -15
View File
@@ -2,13 +2,14 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { parseZoneFile, normalizeZone, formatZoneFile, type ParsedZone } from '$lib/utils/zone-parser.js';
import { useClipboard } from '$lib/composables';
let zoneInput = $state('');
let results = $state<{
normalized: ParsedZone;
formattedZone: string;
} | null>(null);
let copiedState = $state(false);
const clipboard = useClipboard();
let activeExampleIndex = $state<number | null>(null);
const examples = [
@@ -103,18 +104,9 @@ _https._tcp IN SRV 0 5 443 www.example.com.`,
}
}
async function copyZone() {
function copyZone() {
if (!results) return;
try {
await navigator.clipboard.writeText(results.formattedZone);
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
clipboard.copy(results.formattedZone);
}
function handleInputChange() {
@@ -299,9 +291,9 @@ www IN A 192.0.2.1"
Normalized Zone File
</h4>
<div class="output-actions">
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyZone}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
{copiedState ? 'Copied!' : 'Copy'}
<button class="copy-button {clipboard.isCopied() ? 'copied' : ''}" onclick={copyZone}>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied() ? 'Copied!' : 'Copy'}
</button>
<button class="download-button" onclick={downloadZone}>
<Icon name="download" size="sm" />
+8 -20
View File
@@ -2,10 +2,11 @@
import { tooltip } from '$lib/actions/tooltip.js';
import Icon from '$lib/components/global/Icon.svelte';
import { parseZoneFile, generateZoneStats, type ZoneStats } from '$lib/utils/zone-parser.js';
import { useClipboard } from '$lib/composables';
let zoneInput = $state('');
let results = $state<ZoneStats | null>(null);
let copiedState = $state(false);
const clipboard = useClipboard();
let activeExampleIndex = $state<number | null>(null);
const examples = [
@@ -131,22 +132,6 @@ sydney IN A 203.0.113.202`,
}
}
async function copyStats() {
if (!results) return;
const statsText = formatStatsForCopy(results);
try {
await navigator.clipboard.writeText(statsText);
copiedState = true;
setTimeout(() => {
copiedState = false;
}, 2000);
} catch (err) {
console.error('Failed to copy: ', err);
}
}
function formatStatsForCopy(stats: ZoneStats): string {
const lines: string[] = [];
@@ -296,9 +281,12 @@ www IN A 192.0.2.1"
<section class="results-section">
<div class="results-header">
<h3>Zone Analysis Report</h3>
<button class="copy-button {copiedState ? 'copied' : ''}" onclick={copyStats}>
<Icon name={copiedState ? 'check' : 'copy'} size="sm" />
{copiedState ? 'Copied!' : 'Copy Report'}
<button
class="copy-button {clipboard.isCopied() ? 'copied' : ''}"
onclick={() => results && clipboard.copy(formatStatsForCopy(results))}
>
<Icon name={clipboard.isCopied() ? 'check' : 'copy'} size="sm" />
{clipboard.isCopied() ? 'Copied!' : 'Copy Report'}
</button>
</div>
+9
View File
@@ -0,0 +1,9 @@
// Central export file for all composables
export { useClipboard } from './useClipboard.svelte.js';
export { useDiagnosticState } from './useDiagnosticState.svelte.js';
export { useExamples } from './useExamples.svelte.js';
export { useValidation, useSimpleValidation } from './useValidation.svelte.js';
// Re-export types
export type { DiagnosticState } from './useDiagnosticState.svelte.js';
export type { ValidationResult } from './useValidation.svelte.js';
Loaded 100 of 251 files, more files were not shown because too many files have changed in this diff. Show more