staging-tester / ocean-landing-serve / src/ lib/ live/ profile.svelte.ts

import type { Profile } from '../profile-types.js';
import { ApiFailure, request } from './http.js';

const sunday = () => {
	const d = new Date();
	d.setUTCDate(d.getUTCDate() - d.getUTCDay());
	return d.toISOString().slice(0, 10);
};

// Valid but empty, so a component that renders before the first load still has something to read.
const empty = (): Profile => ({
	name: '',
	handle: '',
	bio: '',
	location: '',
	joined: new Date().toISOString().slice(0, 10),
	files: { repo: '', readme: null, llms: null },
	weekOf: sunday(),
	timeZone: 'UTC',
	tide: Array.from({ length: 7 }, () => Array<number>(52).fill(0)),
	activity: [],
	pinned: []
});

export const profile = $state<Profile>(empty());

// `owner/name` of the signed-in user's private repositories, for hiding their activity in the outside preview.
export const privateRepos = $state<{ names: string[] }>({ names: [] });

// Every repository the signed-in user can push to: their own and their orgs', newest first.
export const myRepos = $state<{ list: { owner: string; name: string; visibility: string }[] }>({ list: [] });

// The server keeps the person's work and the crew's apart; the screen draws one tide of everything.
type ServerProfile = Omit<Profile, 'tide'> & { tide: { human: number[][]; crew: number[][] } };

// The signed-in user's profile while the shared store shows someone else's.
let own: Profile | null = null;

// Shows another person's profile in the shared store; leaveProfile puts the signed-in user's back, so settings and
// the boot copy never pick up someone else's.
export async function visitProfile(handle: string) {
	own ??= $state.snapshot(profile);
	await loadProfile(handle);
}

export function leaveProfile() {
	if (own) Object.assign(profile, own);
	own = null;
}

export async function loadProfile(handle: string) {
	const { tide, ...rest } = await request<ServerProfile>('GET', `/api/users/${encodeURIComponent(handle)}`);
	Object.assign(profile, rest, {
		tide: tide.human.map((row, d) => row.map((v, w) => v + (tide.crew[d]?.[w] ?? 0)))
	});
	try {
		const mine = await request<{ owner: string; name: string; visibility: string }[]>('GET', '/api/repos');
		privateRepos.names = mine.filter((r) => r.visibility === 'private').map((r) => `${r.owner}/${r.name}`);
		myRepos.list = mine.map(({ owner, name, visibility }) => ({ owner, name, visibility }));
	} catch (err) {
		if (!(err instanceof ApiFailure)) throw err;
	}
}