Translate everything to typescript
This commit is contained in:
1 parent
c3ca3e1752
commit
e9818aaeda
27 files changed
+901
-552
No files matched your search
@@ -1,29 +1,42 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import { asError } from '../lib/validation.ts';
|
||||
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
|
||||
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts';
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
import NetworkSettings from './NetworkSettings.vue';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.js';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
|
||||
|
||||
const props = defineProps({ sending: Boolean });
|
||||
const file = ref(null);
|
||||
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
||||
interface Session {
|
||||
pc: RTCPeerConnection;
|
||||
options: IceOptions;
|
||||
file: File | null;
|
||||
controller: AbortController;
|
||||
transfer: Transfer | null;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const props = defineProps<{ sending?: boolean }>();
|
||||
const file = ref<File | null>(null);
|
||||
const inputCode = ref('');
|
||||
const outputCode = ref('');
|
||||
const step = ref('idle');
|
||||
const step = ref<Step>('idle');
|
||||
const error = ref('');
|
||||
const copied = ref(false);
|
||||
const fps = ref(null);
|
||||
const fps = ref<Fingerprints | null>(null);
|
||||
const verified = ref(false);
|
||||
const progress = ref(0);
|
||||
const incoming = ref(null);
|
||||
const incoming = ref<FileMetadata | null>(null);
|
||||
const downloadUrl = ref('');
|
||||
const choosing = ref(false);
|
||||
const dragover = ref(false);
|
||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
const defaultStun = import.meta.env.VITE_STUN_URL || '';
|
||||
const settings = ref({ stunChoice: defaultStun ? 'custom' : 'google', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'google', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
||||
let active = null;
|
||||
let copyTimer;
|
||||
let active: Session | null = null;
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
|
||||
const status = computed(() => ({
|
||||
idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
|
||||
@@ -63,22 +76,23 @@ function reset(keepNetwork = false) {
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; step.value = 'idle';
|
||||
}
|
||||
function fail(session, err) {
|
||||
function fail(session: Session, err: unknown) {
|
||||
if (active !== session) return;
|
||||
dispose(); revokeDownload();
|
||||
fps.value = incoming.value = null;
|
||||
outputCode.value = ''; verified.value = false;
|
||||
settings.value.allowTurn = false;
|
||||
error.value = err.message || 'Connection failed.'; step.value = 'closed';
|
||||
error.value = asError(err).message; step.value = 'closed';
|
||||
}
|
||||
function pickFiles(event) {
|
||||
const selected = event.target?.files?.[0] ?? event.dataTransfer?.files?.[0];
|
||||
function pickFiles(event: Event) {
|
||||
const selected = event.target instanceof HTMLInputElement ? event.target.files?.[0]
|
||||
: event instanceof DragEvent ? event.dataTransfer?.files[0] : undefined;
|
||||
if (!selected) return;
|
||||
reset();
|
||||
if (selected.size > FILE_LIMIT) { file.value = null; error.value = 'The maximum file size is 64 GiB.'; return; }
|
||||
file.value = selected;
|
||||
}
|
||||
function attach(session, channel) {
|
||||
function attach(session: Session, channel: RTCDataChannel) {
|
||||
if (active !== session) { channel.close(); return; }
|
||||
if (session.transfer || channel.label !== 'hellcon-v2' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
|
||||
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
|
||||
@@ -113,7 +127,7 @@ function start() {
|
||||
};
|
||||
// Fetch managed credentials before gathering, while retaining normal cancellation.
|
||||
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
|
||||
const session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||
active = session;
|
||||
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
|
||||
pc.ondatachannel = event => attach(session, event.channel);
|
||||
@@ -129,7 +143,7 @@ function start() {
|
||||
async function createCode() {
|
||||
const pasted = inputCode.value;
|
||||
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
|
||||
let session;
|
||||
let session: Session | undefined;
|
||||
try {
|
||||
if (props.sending) {
|
||||
if (!file.value) throw new Error('Choose a file first.');
|
||||
@@ -148,7 +162,7 @@ async function createCode() {
|
||||
step.value = props.sending ? 'offer-ready' : 'answer-ready';
|
||||
} catch (err) {
|
||||
if (session) fail(session, err);
|
||||
else { settings.value.allowTurn = false; error.value = err.message; step.value = 'closed'; }
|
||||
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
|
||||
}
|
||||
}
|
||||
async function useAnswer() {
|
||||
@@ -165,7 +179,7 @@ async function useAnswer() {
|
||||
// A rejected answer does not consume a valid local offer. Let the user
|
||||
// correct a paste error instead of silently invalidating both peers' codes.
|
||||
if (session.pc.signalingState === 'have-local-offer') {
|
||||
error.value = `${err.message || 'Invalid answer.'} Correct the answer and connect again; your offer is still valid.`;
|
||||
error.value = `${asError(err, 'Invalid answer.').message} Correct the answer and connect again; your offer is still valid.`;
|
||||
step.value = 'offer-ready';
|
||||
} else fail(session, err);
|
||||
}
|
||||
@@ -179,13 +193,14 @@ function verify() {
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
async function acceptFile(toDisk) {
|
||||
async function acceptFile(toDisk: boolean) {
|
||||
const session = active;
|
||||
if (!session?.transfer || choosing.value || step.value !== 'choose-storage') return;
|
||||
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable;
|
||||
let writable: FileDestination | undefined;
|
||||
try {
|
||||
if (toDisk) {
|
||||
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
|
||||
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
|
||||
if (active !== session) return;
|
||||
writable = await handle.createWritable();
|
||||
@@ -194,7 +209,7 @@ async function acceptFile(toDisk) {
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
if (writable) await writable.abort().catch(() => {});
|
||||
if (active === session && err.name !== 'AbortError') error.value = err.message || 'Could not open the destination file.';
|
||||
if (active === session && asError(err).name !== 'AbortError') error.value = asError(err, 'Could not open the destination file.').message;
|
||||
} finally { if (active === session) choosing.value = false; }
|
||||
}
|
||||
async function copy() {
|
||||
@@ -206,11 +221,14 @@ async function copy() {
|
||||
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
|
||||
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
|
||||
}
|
||||
function formatBytes(bytes) {
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const index = Math.min(3, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB'][index]}`;
|
||||
}
|
||||
function selectCode(event: FocusEvent) {
|
||||
if (event.target instanceof HTMLTextAreaElement) event.target.select();
|
||||
}
|
||||
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
</script>
|
||||
|
||||
@@ -233,7 +251,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<button class="primary" :disabled="busy || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
|
||||
<template v-if="outputCode">
|
||||
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="$event.target.select()" />
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
|
||||
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
|
||||
</template>
|
||||
<template v-if="sending && outputCode">
|
||||
@@ -258,7 +276,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
|
||||
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
|
||||
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
|
||||
<p class="status">Switching tabs cancels an active transfer. Keep this tab open until receipt is confirmed.</p>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user