Start from scratch

This commit is contained in:
Schluffe committed 2026-10-21 20:57:44 +02:00
1 parent 9f3f21884f
commit 24307eb96a
61 files changed
+906 -8959

No files matched your search

+5 -228
View File
@@ -1,233 +1,10 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import ConnectionWorkspace from './components/ConnectionWorkspace.vue';
import AppDialog from './components/AppDialog.vue';
import { addConnection, CONNECTION_LIMIT, emptyConnection, loadConnections, removeConnection, saveConnection, updateConnection, type ConnectionUpdate, type SavedConnection } from './lib/connections.ts';
import type { ReconnectPairing } from './lib/reconnect.ts';
import { asError } from './lib/validation.ts';
const logoUrl = `${import.meta.env.BASE_URL}HellNet_alt.png`;
const giteaIconUrl = `${import.meta.env.BASE_URL}gitea.svg`;
const connections = ref<SavedConnection[]>([]), selected = ref('');
const states = ref<Record<string, 'ready' | 'connecting' | 'connected'>>({});
const current = computed(() => connections.value.find(item => item.id === selected.value));
const sidebarOpen = ref(false), adding = ref(false);
const confirmingRemoval = ref(false), removing = ref(false), removalId = ref('');
const renamingId = ref(''), renameDraft = ref('');
let renameContainer: HTMLElement | null = null;
const removalTarget = computed(() => connections.value.find(item => item.id === removalId.value));
const error = ref(''), removalError = ref('');
const heading = ref<HTMLElement | null>(null);
let persistent = true, pending = 0, writes = Promise.resolve(), refreshRequested = false;
let updates: BroadcastChannel | undefined;
function select(id: string) {
selected.value = id; confirmingRemoval.value = false; sidebarOpen.value = false;
void nextTick(() => heading.value?.focus());
}
function startRename(item: SavedConnection, opener: HTMLButtonElement) {
renameContainer = opener.closest<HTMLElement>('.connection-item');
renamingId.value = item.id;
renameDraft.value = item.name;
void nextTick(() => { const input = document.querySelector<HTMLInputElement>('.connection-rename-input'); input?.focus(); input?.select(); });
}
function saveRename() {
const id = renamingId.value;
if (!id) return;
renamingId.value = '';
const name = renameDraft.value.trim();
const item = connections.value.find(record => record.id === id);
if (name && item && name !== item.name) update(id, { name });
}
function focusRenameAction() { void nextTick(() => renameContainer?.querySelector<HTMLButtonElement>('.edit-action')?.focus()); }
function cancelRename() { renamingId.value = ''; focusRenameAction(); }
function finishRename(event: KeyboardEvent) { (event.target as HTMLInputElement).blur(); focusRenameAction(); }
function confirmRemove(id: string) { removalId.value = id; removalError.value = ''; confirmingRemoval.value = true; }
function applyRecords(records: SavedConnection[]) {
connections.value = records;
for (const id of Object.keys(states.value)) if (!records.some(item => item.id === id)) delete states.value[id];
if (!records.some(item => item.id === renamingId.value)) renamingId.value = '';
// Close a removal prompt whose connection another tab already removed.
if (!removing.value && !records.some(item => item.id === removalId.value)) confirmingRemoval.value = false;
if (!records.some(item => item.id === selected.value)) select(records[0]!.id);
}
function setStatus(id: string, state: 'ready' | 'connecting' | 'connected') {
if (connections.value.some(item => item.id === id)) states.value[id] = state;
}
function statusLabel(id: string) { return states.value[id] === 'connected' ? 'Connected' : states.value[id] === 'connecting' ? 'Connecting' : 'Ready to connect'; }
async function refresh() {
if (!persistent) return;
if (pending || removing.value) { refreshRequested = true; return; }
refreshRequested = false;
try { const records = await loadConnections(); if (!pending && !removing.value) applyRecords(records); else refreshRequested = true; }
catch (err) { error.value = asError(err).message; }
}
onMounted(async () => {
try { connections.value = await loadConnections(); }
catch (err) {
persistent = false; connections.value = [emptyConnection()];
error.value = `${asError(err).message} Connections will only last for this tab.`;
}
selected.value = connections.value[0]!.id;
if (typeof BroadcastChannel !== 'undefined') {
updates = new BroadcastChannel('hellcon-connections');
updates.onmessage = () => { void refresh(); };
}
window.addEventListener('focus', refresh);
});
onBeforeUnmount(() => { updates?.close(); window.removeEventListener('focus', refresh); });
async function add() {
if (adding.value || removing.value || connections.value.length >= CONNECTION_LIMIT) return;
adding.value = true;
try {
await writes;
if (persistent) connections.value = await addConnection();
else connections.value.push(emptyConnection(Math.max(...connections.value.map(item => item.number)) + 1));
select(connections.value.at(-1)!.id); updates?.postMessage('changed');
} catch (err) { error.value = asError(err).message; }
finally { adding.value = false; }
}
function update(id: string, change: ConnectionUpdate) {
const index = connections.value.findIndex(item => item.id === id);
if (index < 0) return;
try { connections.value[index] = updateConnection(connections.value[index]!, change); }
catch (err) { error.value = asError(err).message; return; }
if (!persistent) return;
pending++;
writes = writes.then(async () => {
try {
const records = await saveConnection(id, change);
if (pending === 1) applyRecords(records);
updates?.postMessage('changed');
} catch (err) {
// Keep this tab usable without pretending the change reached storage.
error.value = `${asError(err).message} Your latest changes may be lost when this tab closes.`;
refreshRequested = true;
} finally { pending--; if (!pending && refreshRequested) void refresh(); }
});
}
// Pairing setup needs the committed write, rather than the optimistic update
// used by ordinary settings, before either browser reports success. null
// removes a pairing the peer could not store or does not share.
function saveReconnect(id: string, reconnect: ReconnectPairing | null): Promise<void> {
if (!persistent) {
if (reconnect) return Promise.reject(new Error('Reconnect needs saved connection storage in this browser.'));
update(id, { reconnect }); return Promise.resolve();
}
pending++;
const operation = writes.then(async () => {
try {
const records = await saveConnection(id, { reconnect });
if (pending === 1) applyRecords(records);
updates?.postMessage('changed');
} catch (err) {
refreshRequested = true;
throw err;
} finally { pending--; if (!pending && refreshRequested) void refresh(); }
});
writes = operation.catch(() => {});
return operation;
}
// Connection setup re-reads the record so trust forgotten in another tab is
// never reused from this tab's copy. A failed read stops setup.
async function trust(id: string) {
await writes;
const records = persistent ? await loadConnections() : connections.value;
const record = records.find(item => item.id === id);
if (!record) throw new Error('This connection is no longer saved. Reload the page.');
if (persistent && !pending && !removing.value) applyRecords(records);
return record;
}
async function remove() {
if (!removalTarget.value || removing.value || adding.value) return;
const id = removalTarget.value.id, wasSelected = id === selected.value;
const index = connections.value.findIndex(item => item.id === id);
removing.value = true; removalError.value = '';
try {
await writes;
const records = persistent ? await removeConnection(id) : connections.value.filter(item => item.id !== id);
applyRecords(records.length ? records : [emptyConnection()]);
confirmingRemoval.value = false;
await nextTick();
// Focus the newly opened row, or the row that took the removed row's place.
const row = wasSelected ? document.querySelector('.connection-item.selected') : document.querySelectorAll('.connection-item')[Math.min(index, connections.value.length - 1)];
const link = row?.querySelector<HTMLButtonElement>('.connection-link');
if (link?.offsetParent) link.focus();
else heading.value?.focus();
updates?.postMessage('changed');
} catch (err) { removalError.value = asError(err).message; }
finally { removing.value = false; if (refreshRequested) void refresh(); }
}
const message = 'Hello, world!';
</script>
<template>
<a class="skip-link" href="#main-content">Skip to main content</a>
<div class="app-shell" :class="{ 'sidebar-open': sidebarOpen }">
<aside id="connections-sidebar" class="sidebar" aria-label="Connections sidebar">
<header class="brand">
<img :src="logoUrl" width="38" height="38" alt="" />
<div><span class="brand-name">HellCon</span><p>Direct file sharing</p></div>
</header>
<div class="sidebar-section-heading"><h2>Connections</h2><span>{{ connections.length }}</span></div>
<nav class="connection-nav" aria-label="Connections">
<div v-for="item in connections" :key="item.id" class="connection-item" :class="{ selected: selected === item.id }">
<button v-if="renamingId !== item.id" class="connection-link" :aria-current="selected === item.id ? 'page' : undefined" @click="select(item.id)">
<span class="connection-name">{{ item.name }}</span>
<span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
</button>
<div v-else class="connection-edit">
<input v-model="renameDraft" class="connection-rename-input" :aria-label="`New name for ${item.name}`" aria-describedby="rename-hint" maxlength="80" autocomplete="off" spellcheck="false"
@blur="saveRename" @keydown.enter.prevent="finishRename" @keydown.esc.prevent="cancelRename" />
<span class="connection-status-line"><span class="connection-dot" :class="states[item.id] || 'ready'" aria-hidden="true"></span><span class="connection-status">{{ statusLabel(item.id) }}</span></span>
</div>
<button v-if="renamingId !== item.id" class="connection-action edit-action" :aria-label="`Rename ${item.name}`" :title="`Rename ${item.name}`" :disabled="removing" @click="startRename(item, $event.currentTarget as HTMLButtonElement)"><span aria-hidden="true">✎</span></button>
<button class="connection-action remove-action" :aria-label="`Remove ${item.name}`" :title="`Remove ${item.name}`" :disabled="adding || removing" @click="confirmRemove(item.id)"><span aria-hidden="true">✕</span></button>
</div>
<span id="rename-hint" class="sr-only">Press Enter or leave the field to save. Press Escape to cancel.</span>
</nav>
<button class="add-connection" :disabled="adding || removing || !connections.length || connections.length >= CONNECTION_LIMIT" @click="add"><span aria-hidden="true">+</span> Add connection</button>
<footer class="sidebar-footer">
<span class="sidebar-tag">Browser to browser</span>
<p>No accounts. Your connections stay on this device.</p>
<details class="privacy-details">
<summary>About privacy &amp; connections</summary>
<p>Files travel over encrypted WebRTC data channels. Compare full fingerprints on first pairing, or let a connection authenticate its remembered device. Reconnect by exchanging fresh codes.</p>
<p>Trust your browser and the app’s host: its code can read selected files and use your device identity. HTTPS protects delivery. A TURN relay is used only after opt-in.</p>
<p>Clearing site data removes saved connections and identities.</p>
</details>
<a class="source-link" href="https://gitea.pagequit.net/Schluffe/HellCon" target="_blank" rel="noopener noreferrer" aria-label="View HellCon source code on Gitea">
<img :src="giteaIconUrl" width="20" height="20" alt="" />
<span>Source code</span>
</a>
</footer>
</aside>
<main id="main-content" class="main-pane" tabindex="-1">
<h1 v-if="current" ref="heading" class="sr-only" tabindex="-1">{{ current.name }}</h1>
<div class="mobile-bar">
<div v-if="current" class="mobile-current">
<span class="mobile-current-name" aria-hidden="true">{{ current.name }}</span>
<span class="connection-status-line"><span class="connection-dot" :class="states[current.id] || 'ready'" aria-hidden="true"></span><span class="mobile-current-status">{{ statusLabel(current.id) }}</span></span>
</div>
<button class="sidebar-toggle" :aria-expanded="sidebarOpen" aria-controls="connections-sidebar" @click="sidebarOpen = !sidebarOpen">{{ sidebarOpen ? 'Hide connections' : 'Show connections' }}</button>
</div>
<div class="workspace-scroll">
<p v-if="error" class="storage-error" role="alert">{{ error }}</p>
<template v-for="item in connections" :key="item.id">
<KeepAlive>
<ConnectionWorkspace v-if="selected === item.id" :connection="item" :load-trust="trust" :save-reconnect="saveReconnect"
@status="setStatus" @update="update" />
</KeepAlive>
</template>
<p v-if="!current" class="status">Opening your connections…</p>
</div>
</main>
</div>
<AppDialog v-model="confirmingRemoval" :title="`Remove ${removalTarget?.name || 'connection'}?`" :busy="removing">
<p>This ends its session and forgets its remembered device. Saved files and your device identity are kept.</p>
<p v-if="connections.length === 1">A fresh Con 1 will replace your last connection.</p>
<p v-if="removalError" class="error" role="alert">{{ removalError }}</p>
<template #actions="{ close }">
<button :disabled="removing" autofocus @click="close">Keep connection</button>
<button class="danger" :disabled="removing" @click="remove">{{ removing ? 'Removing…' : 'Remove connection' }}</button>
</template>
</AppDialog>
<main>
<h1>HellCon</h1>
<p>{{ message }}</p>
</main>
</template>