97 lines
6.6 KiB
JavaScript
97 lines
6.6 KiB
JavaScript
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);
|
|
}
|
|
}
|
|
|
|
let lang = new URLSearchParams(location.search).get('lang') || navigator.language.slice(0,2);
|
|
if (!translations[lang]) lang = 'ru';
|
|
let current, mode = 'login', message = '';
|
|
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;
|
|
}
|
|
function field(key,{type='text',min,max,hint}={}) {
|
|
const id = 'field-'+key;
|
|
return el('label',{for:id},t(key),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?{'aria-describedby':id+'-hint'}:{})}),hint?el('span',{id:id+'-hint',class:'hint'},t(hint)):null);
|
|
}
|
|
function select(key,options) {
|
|
const node = el('select',{id:'field-'+key,name:key,required:''},el('option',{value:''},t('choose')),options.map(([value,label])=>el('option',{value},t(label))));
|
|
node.value = current?.profile[key] ?? '';
|
|
return el('label',{for:'field-'+key},t(key),node);
|
|
}
|
|
function render() {
|
|
document.documentElement.lang=lang;document.title=t('app');
|
|
const language = el('select',{class:'lang','aria-label':t('language'),onchange:e=>{lang=e.target.value;history.replaceState(null,'','?lang='+lang);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('heading')),el('p',{},current?t('next'):t('intro')));
|
|
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,
|
|
field('height',{type:'number',min:100,max:250}),field('weight',{type:'number',min:25,max:350}),field('age',{type:'number',min:18,max:100}),
|
|
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:''},inputs,error,el('div',{class:'actions'},submit));
|
|
form.addEventListener('submit',async e=>{
|
|
e.preventDefault();
|
|
for (const input of form.querySelectorAll('input,select')) {
|
|
if (!input.checkValidity()) {error.textContent=errorText(input.name);input.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 {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'?'register':'login')));
|
|
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();}}
|
|
});
|