fix: Formatting IPv6 display #84

Wraps IPv6 host in square brackets, returns as-is for domain names
or IPv4 addresses.
This commit is contained in:
Christian Ditaputratama 2024-09-09 19:50:30 +07:00
parent 61cc98e378
commit 0e3dc04af8
No known key found for this signature in database
GPG key ID: 31D3D06D77950979
3 changed files with 27 additions and 3 deletions

View file

@ -1,5 +1,6 @@
<script>
import { getModalStore } from '@skeletonlabs/skeleton';
import { formatHostname } from '$lib/utils/strings';
const modalStore = getModalStore();
@ -41,7 +42,7 @@
</button><br />.onion:<span class="text-indigo-800 dark:text-indigo-400">{port}</span>
<span class="text-gray-700 dark:text-gray-400">(TOR)</span>
{:else}
{hostname}:<span class="text-indigo-800 dark:text-indigo-400">{port}</span><br />
{formatHostname(hostname)}:<span class="text-indigo-800 dark:text-indigo-400">{port}</span><br />
{#if ipv6_only}
<span class="text-rose-800 dark:text-rose-400">(IPv6 only)</span>
{/if}

View file

@ -1,3 +1,26 @@
/**
* Modifies the input string based on whether it is an IPv6 address.
* If the input is an IPv6 address, it wraps it in square brackets `[ ]`.
* Otherwise, it returns the input string as-is (for domain names or
* IPv4 addresses). AND I'M SORRY USING REGEX FOR THIS!
*
* @param {string} hostname
* @returns {string} - The modified string, IPv6 addresses wrapped in `[ ]`.
*/
export const formatHostname = (hostname) => {
// const ipv6Pattern = /^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/; // full
// pattern for both full and compressed IPv6 addresses.
// source: https://regex101.com/library/cP9mH9?filterFlavors=dotnet&filterFlavors=javascript&orderBy=RELEVANCE&search=ip
// This may be incorrect, but let's assume it's correct. xD
const ipv6Pattern =
/^(([0-9A-Fa-f]{1,4}:){7})([0-9A-Fa-f]{1,4})$|(([0-9A-Fa-f]{1,4}:){1,6}:)(([0-9A-Fa-f]{1,4}:){0,4})([0-9A-Fa-f]{1,4})$/;
if (ipv6Pattern.test(hostname)) {
return `[${hostname}]`;
}
return hostname;
};
/**
* @param {number} bytes
* @param {number} decimals

View file

@ -3,7 +3,7 @@
import { format, formatDistance } from 'date-fns';
import { loadData, loadNodeInfo } from './api-handler';
import { onMount } from 'svelte';
import { formatHashes, formatBytes } from '$lib/utils/strings';
import { formatHostname, formatHashes, formatBytes } from '$lib/utils/strings';
import {
DtSrRowsPerPage,
DtSrThSort,
@ -71,7 +71,7 @@
<tbody>
<tr>
<td class="font-bold">Hostname:Port</td>
<td>{nodeInfo?.hostname}:{nodeInfo?.port}</td>
<td>{formatHostname(nodeInfo?.hostname)}:{nodeInfo?.port}</td>
</tr>
<tr>
<td class="font-bold">Public IP</td>