185 lines
12 KiB
JavaScript
185 lines
12 KiB
JavaScript
/* global GymPlan */
|
|
import { initTelemetry } from '/profile/telemetry.js';
|
|
initTelemetry().catch(() => {});
|
|
const translations = await fetch('/profile/i18n.json').then(r=>r.json());
|
|
// Activate the network-only policy before any request for personal information.
|
|
let privateStorageReady = true;
|
|
if ('serviceWorker' in navigator) {
|
|
try {
|
|
const registration = await navigator.serviceWorker.register('/sw.js',{updateViaCache:'none'});
|
|
await registration.update();
|
|
const worker = registration.installing || registration.waiting;
|
|
if (worker && worker.state !== 'activated') await new Promise((resolve,reject)=>{
|
|
worker.addEventListener('statechange',()=>{if(worker.state==='activated')resolve();if(worker.state==='redundant')reject(new Error());});
|
|
});
|
|
} catch {
|
|
privateStorageReady = false;
|
|
if ('caches' in window) for (const key of await caches.keys()) await caches.delete(key);
|
|
}
|
|
}
|
|
|
|
const languageKey = 'tpt.language';
|
|
const supportedLanguage = value => Object.hasOwn(translations, value);
|
|
let savedLanguage;
|
|
try { savedLanguage = localStorage.getItem(languageKey); } catch { /* Storage may be disabled. */ }
|
|
const requestedLanguage = new URLSearchParams(location.search).get('lang');
|
|
let lang = supportedLanguage(requestedLanguage) ? requestedLanguage : supportedLanguage(savedLanguage) ? savedLanguage : 'ru';
|
|
function saveLanguage() {
|
|
try { localStorage.setItem(languageKey, lang); } catch { /* Keep the page usable without storage. */ }
|
|
}
|
|
if (supportedLanguage(requestedLanguage)) saveLanguage();
|
|
let current, mode = 'login', message = '', planOpen = false;
|
|
let welcome = true;
|
|
try { welcome = sessionStorage.getItem('tpt.welcomeSeen') !== '1'; } catch { /* Storage is optional. */ }
|
|
function closeWelcome(nextMode) {
|
|
welcome = false; mode = nextMode;
|
|
try { sessionStorage.setItem('tpt.welcomeSeen','1'); } catch { /* Continue in memory. */ }
|
|
render();
|
|
}
|
|
const root = document.querySelector('#app');
|
|
const t = key=>translations[lang][key];
|
|
function el(tag,attrs={},...children) {
|
|
const node = document.createElement(tag);
|
|
for (const [key,value] of Object.entries(attrs)) {
|
|
if (key.startsWith('on')) node.addEventListener(key.slice(2),value);
|
|
else if (key === 'value') node.value = value;
|
|
else node.setAttribute(key,value);
|
|
}
|
|
for (const child of children.flat()) if (child != null) node.append(child);
|
|
return node;
|
|
}
|
|
function errorText(key) { return translations[lang].errors[key] || translations[lang].errors.server; }
|
|
async function api(path,method='GET',body) {
|
|
const response = await fetch('/api/'+path,{method,headers:{'Content-Type':'application/json'},body:body === undefined ? undefined : JSON.stringify(body)});
|
|
const data = await response.json();
|
|
if (!response.ok) {const error = new Error(data.error);error.status=response.status;throw error;}
|
|
return data;
|
|
}
|
|
const measurements = ['height','weight','age'];
|
|
function showFieldError(input, text) {
|
|
const output = document.getElementById(input.id+'-error');
|
|
if (!output) return;
|
|
output.textContent = text;
|
|
output.hidden = !text;
|
|
input.setAttribute('aria-invalid',String(!!text));
|
|
}
|
|
function validateMeasurement(input) {
|
|
const valid = input.checkValidity();
|
|
const key = input.validity.valueMissing && !input.validity.badInput ? input.name+'Required' : input.name;
|
|
showFieldError(input,valid ? '' : errorText(key));
|
|
return valid;
|
|
}
|
|
function field(key,{type='text',min,max,hint}={}) {
|
|
const id = 'field-'+key;
|
|
const measurement = measurements.includes(key);
|
|
const input = el('input',{id,name:key,type,required:'',value:current?.profile[key] ?? '',...(min ? {min,max,step:key==='age'?'1':'any'} : {}),...(key==='username'?{autocomplete:'username',pattern:'[a-zA-Z0-9_-]{3,40}',minlength:3,maxlength:40}:{}),...(key==='password'?{autocomplete:mode==='register'?'new-password':'current-password',minlength:12,maxlength:128}:{}),...((hint || measurement)?{'aria-describedby':[hint?id+'-hint':null,measurement?id+'-error':null].filter(Boolean).join(' ')}:{})});
|
|
if (measurement) {
|
|
input.addEventListener('blur',()=>validateMeasurement(input));
|
|
input.addEventListener('input',()=>validateMeasurement(input));
|
|
}
|
|
return el('label',{for:id},t(key),input,hint?el('span',{id:id+'-hint',class:'hint'},t(hint)):null,measurement?el('span',{id:id+'-error',class:'field-error',hidden:'','aria-live':'polite'}):null);
|
|
}
|
|
function select(key,options) {
|
|
const node = el('select',{id:'field-'+key,name:key,required:'',...(key==='sex'?{'aria-describedby':'field-sex-hint'}:{})},el('option',{value:''},t(key+'Choose')),options.map(([value,label])=>el('option',{value},t(label))));
|
|
node.value = current?.profile[key] ?? '';
|
|
return el('label',{for:'field-'+key},t(key),node,key==='sex'?el('span',{id:'field-sex-hint',class:'hint'},t('sexHint')):null);
|
|
}
|
|
function openPlan() {
|
|
if (current) { location.href='/tracker?lang='+lang+'&plan=1'; return; }
|
|
planOpen=true; render(); window.scrollTo(0,0);
|
|
root.querySelector('h1').focus();
|
|
}
|
|
function planCard() {
|
|
const text=GymPlan.text(lang).planHome;
|
|
return el('section',{class:'card','data-plan-card':''},
|
|
el('button',{type:'button',class:'primary','data-plan-open':'','aria-describedby':'plan-what',onclick:openPlan},text.button),
|
|
el('p',{id:'plan-what','data-plan-what':''},text.what),
|
|
!current ? el('p',{class:'hint'},t('planSignin')) : null,
|
|
!current ? el('button',{type:'button',class:'plan-start','data-plan-start':'',onclick:openPlan},text.start) : null);
|
|
}
|
|
function renderPublicPlan() {
|
|
const text=GymPlan.text(lang);
|
|
root.querySelector('h1').textContent=text.title;
|
|
root.querySelector('h1').tabIndex=-1;
|
|
root.querySelector('p').textContent=text.intro;
|
|
root.append(el('button',{type:'button',onclick:()=>{planOpen=false;render();root.querySelector('[data-plan-open]').focus();}},text.back),
|
|
el('p',{},text.hint),el('p',{class:'notice'},t('planSignin')),
|
|
...GymPlan.days(lang).map(day=>el('section',{class:'card','data-plan-day':''},
|
|
el('h2',{},day.name),el('p',{},text.duration),el('p',{},text.warmup),el('p',{},text.strength),
|
|
el('ul',{},...day.exercises.map(ex=>el('li',{},ex.name+' — '+text.dose.replace('{reps}',ex.reps)))),
|
|
el('p',{},day.cardio),el('p',{},text.stretch),
|
|
el('button',{type:'button',class:'primary',onclick:()=>{
|
|
planOpen=false;mode='login';message=t('planSignin');render();
|
|
root.querySelector('#field-username').focus();
|
|
}},text.record))));
|
|
}
|
|
function render() {
|
|
document.documentElement.lang=lang;document.title=t('app');
|
|
root.classList.toggle('auth-login', !current && !welcome && mode==='login');
|
|
root.classList.toggle('auth-form', !current && !welcome && !planOpen);
|
|
const language = el('select',{class:'lang','aria-label':t('language'),onchange:e=>{lang=e.target.value;saveLanguage();const url=new URL(location.href);url.searchParams.set('lang',lang);history.replaceState(null,'',url);message='';render();}},...['ru','kk','en'].map(code=>el('option',{value:code},code.toUpperCase())));
|
|
language.value=lang;
|
|
root.replaceChildren(el('header',{},el('span',{class:'eyebrow'},t('brand')),language),el('h1',{},current?t('profile'):t(mode+'Heading')),el('p',{},current?t('next'):t(mode+'Intro')));
|
|
if (!current && welcome) {
|
|
root.querySelector('h1').textContent=t('welcomeHeading');
|
|
root.querySelector('p').textContent=t('welcomeIntro');
|
|
root.append(el('section',{class:'card welcome','aria-labelledby':'welcome-title'},
|
|
el('h2',{id:'welcome-title'},t('welcomeTitle')),
|
|
el('p',{},t('welcomeHint')),
|
|
el('div',{class:'actions'},
|
|
el('button',{type:'button','data-welcome-skip':'',onclick:()=>closeWelcome('login')},t('welcomeSkip')),
|
|
el('button',{type:'button',class:'primary','data-welcome-next':'',onclick:()=>closeWelcome('register')},t('welcomeNext')))));
|
|
return;
|
|
}
|
|
if (planOpen && !current) { renderPublicPlan(); return; }
|
|
root.append(planCard());
|
|
const error = el('p',{class:'error',role:'alert','aria-live':'polite'},message);
|
|
const inputs = el('div',{class:'grid'},
|
|
!current?field('username',{hint:'usernameHint'}):null,!current?field('password',{type:'password',hint:'passwordHint'}):null,
|
|
...(current || mode==='register' ? [field('height',{type:'number',min:100,max:250,hint:'heightHint'}),field('weight',{type:'number',min:25,max:350,hint:'weightHint'}),field('age',{type:'number',min:18,max:100,hint:'ageHint'}),
|
|
select('sex',[['male','male'],['female','female']]),select('activity',[['1.2','sedentary'],['1.375','light'],['1.55','moderate'],['1.725','high']])] : []));
|
|
const submit = el('button',{class:'primary',type:'submit'},t(current?'save':mode));
|
|
const form = el('form',{class:'card',novalidate:''},!current?el('p',{class:'hint','data-auth-guidance':''},t('authGuidance')):null,inputs,error,el('div',{class:'actions'},submit));
|
|
form.addEventListener('submit',async e=>{
|
|
e.preventDefault();
|
|
error.textContent='';
|
|
let firstInvalid;
|
|
for (const input of form.querySelectorAll('input,select')) {
|
|
const measurement = measurements.includes(input.name);
|
|
const valid = measurement ? validateMeasurement(input) : input.checkValidity();
|
|
if (!valid) {
|
|
firstInvalid ||= input;
|
|
if (!measurement && !error.textContent) error.textContent=errorText(input.name);
|
|
}
|
|
}
|
|
if (firstInvalid) {firstInvalid.focus();return;}
|
|
const body = Object.fromEntries(new FormData(form));
|
|
form.setAttribute('aria-busy','true');for (const b of form.querySelectorAll('button')) b.disabled=true;
|
|
try { const wasSignedIn=!!current; current=await api(current?'profile':mode,current?'PUT':'POST',body);message=wasSignedIn?t('saved'):'';render(); }
|
|
catch(err) {
|
|
if (err.status===401 && current) {current=undefined;message=errorText('signin');render();}
|
|
else {if (measurements.includes(err.message)) showFieldError(form.elements.namedItem(err.message),errorText(err.message));else error.textContent=errorText(err.message);form.querySelector('[name="'+(Object.hasOwn(body,err.message)?err.message:'username')+'"]')?.focus();}
|
|
}
|
|
finally {form.removeAttribute('aria-busy');for (const b of form.querySelectorAll('button')) b.disabled=false;}
|
|
});
|
|
if (!current) form.querySelector('.actions').append(el('button',{type:'button',onclick:()=>{mode=mode==='login'?'register':'login';message='';render();}},t(mode==='login'?'toRegister':'toLogin')));
|
|
else form.querySelector('.actions').append(el('a',{class:'btn',href:'/tracker?lang='+lang},t('tracker')),el('button',{type:'button',onclick:async()=>{
|
|
try{await api('logout','POST',{});current=undefined;message='';render();}catch(err){error.textContent=errorText(err.message);}
|
|
}},t('logout')));
|
|
root.append(form,el('p',{class:'hint'},t('privacy')));
|
|
if (current) {
|
|
const n=current.nutrition;
|
|
root.append(el('section',{class:'card'},el('h2',{},t('norm')),el('div',{class:'stats'},el('div',{class:'stat'},el('strong',{},String(n.calories)),t('calories')),el('div',{class:'stat'},el('strong',{},String(n.protein)),t('protein')))),el('section',{class:'card'},el('h2',{},t('menu')),el('p',{},t('menuHint')),n.menu.map(m=>el('article',{class:'meal'},el('h3',{},t(m.name)),el('span',{},`${m.grams} ${t('grams')} · ${m.calories} ${t('calories')} · ${m.protein} ${t('protein')}`)))),el('p',{class:'notice'},t('notice')));
|
|
}
|
|
}
|
|
root.textContent=t('loading');
|
|
try {if (!privateStorageReady) throw new Error('server'); current=await api('profile');}catch(error){if(error.status!==401)message=errorText('server');}
|
|
render();
|
|
|
|
addEventListener('pageshow',event=>{if(event.persisted) location.reload();});
|
|
addEventListener('focus',async()=>{
|
|
if (!current) return;
|
|
try {current=await api('profile');render();}
|
|
catch(error){if(error.status===401){current=undefined;message=errorText('signin');render();}}
|
|
});
|