import {createClient} from '/account-base.js'; import {DEFAULT_FRAME,clampFrame,applyFrame,bindFrameEditor,renderBadgeIcons} from './profile-customization.js'; const $ = id => document.getElementById(id); const BUCKET = 'community-media'; const LIMITS = {avatar: 2 * 1024 * 1024, banner: 5 * 1024 * 1024}; const FORMATS = {'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp'}; const ownPage = ['/profile', '/profile.html', '/profile/'].includes(location.pathname); const match = location.pathname.match(/^\/users\/([^/]+)\/?$/i); let db, viewer, target, currentProfile, isSaving = false; let framing={avatar:{...DEFAULT_FRAME},banner:{...DEFAULT_FRAME}}; const framingEditors={}; const objectUrls = new Map(); function showStatus(message, error = false) { $('status').textContent = message; $('status').dataset.error = String(error); $('status').dataset.tone = error ? 'error' : message === 'Profile loaded.' ? 'hidden' : message.includes('Loading') ? 'loading' : 'quiet'; } function validUrl(url) { try { return !!url && new URL(url).protocol === 'https:'; } catch { return false; } } function mediaPath(url) { if (!validUrl(url) || !viewer) return null; const u = new URL(url); const prefix = '/storage/v1/object/public/' + BUCKET + '/' + viewer.id + '/'; if (u.origin !== new URL(db.supabaseUrl).origin || !u.pathname.startsWith(prefix)) return null; return viewer.id + '/' + decodeURIComponent(u.pathname.slice(prefix.length)); } function loadFraming(row) { framing={ avatar:clampFrame({x:row?.avatar_x,y:row?.avatar_y,zoom:row?.avatar_zoom}), banner:clampFrame({x:row?.banner_x,y:row?.banner_y,zoom:row?.banner_zoom}) }; } async function fetchFraming(username) { const rows=await rpc('community_profile_framing',{p_username:username}); loadFraming(rows?.[0]); } async function rpc(name, args = {}) { const {data, error} = await db.rpc(name, args); if (error) throw new Error(error.message); return data; } function setImage(id, fallbackId, url) { const img = $(id); const fallback = $(fallbackId); const valid = validUrl(url); img.hidden = !valid; fallback.hidden = valid; if (valid) img.src = url; else img.removeAttribute('src'); } function render(row) { target = row; $('public-profile').hidden = false; $('profile-name').textContent = row.display_name; $('page-title').textContent = ownPage ? 'Profile' : row.display_name + "'s profile"; $('profile-handle').textContent = '@' + row.username; $('profile-bio').textContent = row.bio || 'No bio yet.'; $('profile-joined').textContent = new Date(row.joined_at).toLocaleDateString(undefined, {month:'long', year:'numeric'}); $('profile-avatar-fallback').textContent = (row.display_name || row.username || '?').trim().charAt(0).toUpperCase(); setImage('profile-avatar', 'profile-avatar-fallback', row.avatar_url); const bannerImage=$('profile-banner-image'); bannerImage.hidden=!validUrl(row.banner_url); if(!bannerImage.hidden)bannerImage.src=row.banner_url; else bannerImage.removeAttribute('src'); const avatarImage=$('profile-avatar'); avatarImage.onload=()=>applyFrame(avatarImage,framing.avatar); bannerImage.onload=()=>applyFrame(bannerImage,framing.banner); applyFrame(avatarImage,framing.avatar); applyFrame(bannerImage,framing.banner); if(!render.profileResizeObserver && typeof ResizeObserver!=='undefined'){ render.profileResizeObserver=new ResizeObserver(()=>{ applyFrame(avatarImage,framing.avatar); applyFrame(bannerImage,framing.banner); }); render.profileResizeObserver.observe($('profile-banner')); render.profileResizeObserver.observe(avatarImage.parentElement); } renderBadgeIcons($('profile-badges'),row.badges); const mine = viewer?.id === row.user_id; $('edit-link').hidden = !mine; $('profile-visibility').hidden = !mine || !!currentProfile?.public_profile; $('report-open').hidden = !viewer || mine; if(viewer&&!mine&&new URL(location.href).searchParams.get('report')==='1'&&!render.reportOpened){render.reportOpened=true;$('report-dialog').showModal();} } function previewChoice(kind, file) { const img = $(kind + '-preview'); const placeholder = $(kind + '-placeholder'); if (objectUrls.has(kind)) URL.revokeObjectURL(objectUrls.get(kind)); objectUrls.delete(kind); const persistedUrl = currentProfile?.[kind === 'avatar' ? 'avatar_url' : 'banner_url']; const url = file ? URL.createObjectURL(file) : persistedUrl; if (file) objectUrls.set(kind, url); img.hidden = !validUrl(url) && !file; placeholder.hidden = !img.hidden; if (!img.hidden) img.src = url; else img.removeAttribute('src'); } function validateFile(kind, file) { if (!file) return; if (!Object.hasOwn(FORMATS, file.type)) throw new Error('Use a PNG, JPG or WebP ' + kind + '.'); if (file.size === 0 || file.size > LIMITS[kind]) { throw new Error((kind === 'avatar' ? 'Avatar' : 'Banner') + ' must be smaller than ' + (LIMITS[kind] / 1024 / 1024) + ' MB.'); } } async function upload(kind, file) { if (!file) return null; validateFile(kind, file); const name = viewer.id + '/' + kind + '-' + crypto.randomUUID() + '.' + FORMATS[file.type]; const {error} = await db.storage.from(BUCKET).upload(name, file, { cacheControl: '3600', contentType: file.type, upsert: false }); if (error) throw new Error(kind + ' upload failed: ' + error.message); const {data} = db.storage.from(BUCKET).getPublicUrl(name); return {path: name, url: data.publicUrl}; } async function save(event) { event.preventDefault(); if (isSaving) return; isSaving = true; $('save-profile').disabled = true; const uploaded = []; let profileCommitted = false; const previous = currentProfile || {}; try { const username = $('username').value.trim().toLowerCase(); if (!/^[a-z0-9_]{3,24}$/.test(username)) throw new Error('Username must be 3–24 letters, numbers, or underscores.'); const display = $('display-name').value.trim(); if (display.length < 1 || display.length > 60) throw new Error('Display name must be 1–60 characters.'); const avatarFile = $('avatar-file').files[0]; const bannerFile = $('banner-file').files[0]; validateFile('avatar', avatarFile); validateFile('banner', bannerFile); showStatus('Saving profile and uploading images…'); const avatarUpload = await upload('avatar', avatarFile); if (avatarUpload) uploaded.push(avatarUpload.path); const bannerUpload = await upload('banner', bannerFile); if (bannerUpload) uploaded.push(bannerUpload.path); await rpc('community_save_profile', { p_username: username, p_display_name: display, p_bio: $('bio').value, p_avatar_url: avatarUpload?.url || previous.avatar_url || null, p_banner_url: bannerUpload?.url || previous.banner_url || null, p_public_profile: $('is-public').checked }); profileCommitted = true; const avatar=framingEditors.avatar.get(),banner=framingEditors.banner.get(); await rpc('community_save_framing',{ p_avatar_x:avatar.x,p_avatar_y:avatar.y,p_avatar_zoom:avatar.zoom, p_banner_x:banner.x,p_banner_y:banner.y,p_banner_zoom:banner.zoom }); for (const [kind, replacement] of [['avatar', avatarUpload], ['banner', bannerUpload]]) { if (!replacement) continue; const old = mediaPath(previous[kind + '_url']); if (old && old !== replacement.path) { db.storage.from(BUCKET).remove([old]).catch(() => {}); } } location.assign('/users/' + encodeURIComponent(username)); } catch (error) { if (!profileCommitted && uploaded.length) await db.storage.from(BUCKET).remove(uploaded).catch(() => {}); showStatus((profileCommitted ? 'Profile saved but image positioning could not be saved: ' : '')+ (error.message || 'Unable to save profile.'), true); } finally { isSaving = false; $('save-profile').disabled = false; } } function setupEditor(row) { currentProfile = row || {}; $('editor').hidden = false; if (row) { $('username').value = row.username; $('display-name').value = row.display_name; $('bio').value = row.bio || ''; $('is-public').checked = !!row.public_profile; } $('bio-count').textContent = String($('bio').value.length); $('bio').addEventListener('input', () => $('bio-count').textContent = String($('bio').value.length)); $('username').addEventListener('blur', () => $('username').value = $('username').value.trim().toLowerCase()); for (const kind of ['avatar', 'banner']) { const input = $(kind + '-file'); input.addEventListener('change', () => { const file = input.files?.[0]; try { validateFile(kind, file); if(file)framingEditors[kind].set(DEFAULT_FRAME); previewChoice(kind, file); } catch (error) { input.value = ''; previewChoice(kind, null); showStatus(error.message, true); } }); previewChoice(kind, null); framingEditors[kind]=bindFrameEditor(kind,$(kind+'-crop'),$(kind+'-preview'), $(kind+'-zoom'),$(kind+'-reset'),framing[kind]); } $('profile-form').addEventListener('submit', save); } async function start() { const response = await fetch('/api/account/config', {cache:'no-store'}); if (!response.ok) throw new Error('Could not load account settings.'); const config = await response.json(); if (!config.enabled) throw new Error('Profiles require account mode.'); db = createClient(config.url, config.key, {auth:{ flowType:'pkce', detectSessionInUrl:false, persistSession:true, autoRefreshToken:true }}); const {data, error} = await db.auth.getSession(); if (error) throw error; viewer = data.session?.user; $('report-open').addEventListener('click', () => $('report-dialog').showModal()); $('report-cancel').addEventListener('click', () => $('report-dialog').close()); $('report-form').addEventListener('submit', async event => { event.preventDefault(); if (!viewer || !target) return; const submit=$('report-form').querySelector('[type="submit"]'); if(submit.disabled)return; submit.disabled=true; try { const id=await rpc('community_report', { p_target:target.user_id, p_category:$('report-category').value, p_details:$('report-details').value.trim() }); $('report-form').reset(); $('report-dialog').close(); showStatus('Report #'+id+' submitted. You can check its status under People → Submitted reports.'); } catch (error) {showStatus(error.message, true);} finally{submit.disabled=false;} }); if (ownPage) { if (!viewer) { location.replace('/signin'); return; } const rows = await rpc('community_my_profile'); const row = rows?.[0]; if(row)await fetchFraming(row.username); setupEditor(row); if (row) { const publicRows = await rpc('community_profile', {p_username:row.username}); if (publicRows?.[0]) render(publicRows[0]); } showStatus(row ? 'Profile loaded.' : 'The profile will be available after account approval.'); } else { if (!match) throw new Error('Invalid profile address.'); const username = decodeURIComponent(match[1]).toLowerCase(); if (!/^[a-z0-9_]{3,24}$/.test(username)) throw new Error('Invalid username.'); const rows = await rpc('community_profile', {p_username:username}); if (!rows?.length) throw new Error('This profile is private or does not exist.'); await fetchFraming(username); render(rows[0]); showStatus('Profile loaded.'); } } start().catch(error => showStatus(error.message || 'Profile unavailable.', true));