TPTIP-83: открыть меню из профиля и дневника
This commit is contained in:
parent
0bcba0be2e
commit
cbc7a62a91
@ -63,3 +63,5 @@
|
||||
|
||||
| Длина пароля | От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль. | сложность пароля | Подсказка под полем пароля |
|
||||
| Ошибка входа | Имя или пароль не подошли. Проверьте их или создайте учётную запись. | имя не существует, неверный пароль | Одинаковое сообщение при неверном имени и пароле |
|
||||
|
||||
| Переход к рассчитанному меню | Открыть меню на день | — | Показывает пример меню с порциями для выбранной цели |
|
||||
|
||||
@ -722,6 +722,7 @@ function viewToday() {
|
||||
return h('div', null, dateNav(),
|
||||
h('div', { class: 'card' }, h('button', { class: 'primary', style: 'width:100%', 'data-plan-open': '', 'aria-describedby': 'planWhat', onclick: openPlan }, planHome.button),
|
||||
h('p', { id: 'planWhat', class: 'small muted', 'data-plan-what': '', style: 'margin:8px 0 0' }, planHome.what),
|
||||
window.TPTProfile ? h('a', { href: '/?lang=' + gymLang + '#daily-menu', 'data-menu-open': '' }, window.TPTMenuText) : null,
|
||||
db.workouts.length ? null : h('p', { class: 'small muted', 'data-plan-start': '', style: 'margin:4px 0 0' }, h('button', { class: 'link-btn', style: 'text-align:left', onclick: openPlan }, planHome.start))),
|
||||
s.normsPending ? h('div', { class: 'card', 'data-norms-pending': '' }, h('b', null, 'Дневные нормы пока не рассчитаны'),
|
||||
h('p', { class: 'small muted', style: 'margin:6px 0 8px' }, 'Сейчас показаны примерные цифры. Укажите возраст, рост и вес в «Настройках» — и нормы станут вашими.'),
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
## 1. Реализация
|
||||
|
||||
- [x] 1.1 Сохранить цель в профиле и применить её к расчёту и дневным нормам.
|
||||
- [ ] 1.2 Добавить переход к меню из профиля и дневника, сохранить переход к плану и перевести подсказку регистрации.
|
||||
- [x] 1.2 Добавить переход к меню из профиля и дневника, сохранить переход к плану и перевести подсказку регистрации.
|
||||
|
||||
## 2. Проверка
|
||||
|
||||
|
||||
@ -37,9 +37,9 @@ export function createApp({database,secure = process.env.NODE_ENV === 'productio
|
||||
try { personal=service.read(token); } catch { res.writeHead(302,{Location:'/'});res.end();return; }
|
||||
const lang = new URL(req.url,'http://localhost').searchParams.get('lang');
|
||||
const dictionaries = JSON.parse(await readFile(resolve(root,'profile/i18n.json'),'utf8'));
|
||||
const text = (dictionaries[lang] || dictionaries.ru).profile;
|
||||
const text = Object.hasOwn(dictionaries,lang) ? dictionaries[lang] : dictionaries.ru;
|
||||
let html = await readFile(resolve(root,'index.html'),'utf8');
|
||||
html = html.replace('<script>',`<script>window.TPTProfile=${JSON.stringify(personal)};window.TPTProfileText=${JSON.stringify(text)};</script><script>`);
|
||||
html = html.replace('<script>',`<script>window.TPTProfile=${JSON.stringify(personal)};window.TPTProfileText=${JSON.stringify(text.profile)};window.TPTMenuText=${JSON.stringify(text.menuOpen)};</script><script>`);
|
||||
html = html.replace('</body>','<script type="module" src="/profile/tracker-guard.js"></script></body>');
|
||||
htmlPolicy(html);res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(html);return;
|
||||
}
|
||||
|
||||
@ -30,6 +30,7 @@ function saveLanguage() {
|
||||
if (supportedLanguage(requestedLanguage)) saveLanguage();
|
||||
let current, mode = 'login', message = '', planOpen = false;
|
||||
let welcomeGoal = 'maintain';
|
||||
const goalOptions = [['lose','goalLose'],['maintain','goalMaintain'],['gain','goalGain']];
|
||||
let welcome = true;
|
||||
try { welcome = sessionStorage.getItem('tpt.welcomeSeen') !== '1'; } catch { /* Storage is optional. */ }
|
||||
function closeWelcome(nextMode) {
|
||||
@ -92,7 +93,7 @@ function field(key,{type='text',min,max,hint}={}) {
|
||||
}
|
||||
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] ?? '';
|
||||
node.value = current?.profile[key] ?? (key==='goal' ? welcomeGoal : '');
|
||||
return el('label',{for:'field-'+key},t(key),node,key==='sex'?el('span',{id:'field-sex-hint',class:'hint'},t('sexHint')):null);
|
||||
}
|
||||
function openPlan() {
|
||||
@ -105,6 +106,7 @@ function planCard() {
|
||||
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('a',{class:'btn',href:'#daily-menu'},t('menuOpen')) : null,
|
||||
!current ? el('p',{class:'hint'},t('planSignin')) : null,
|
||||
!current ? el('button',{type:'button',class:'plan-start','data-plan-start':'',onclick:openPlan},text.start) : null);
|
||||
}
|
||||
@ -138,7 +140,7 @@ function render() {
|
||||
const goalSelect = el('select',{id:'welcome-goal','aria-describedby':'welcome-goal-note',onchange:event=>{
|
||||
welcomeGoal=event.target.value;
|
||||
goalNote.textContent=GymPlan.text(lang).welcomeGoal.replace('{goal}',t('goal'+welcomeGoal[0].toUpperCase()+welcomeGoal.slice(1)));
|
||||
}},...['lose','maintain','gain'].map(value=>el('option',{value},t('goal'+value[0].toUpperCase()+value.slice(1)))));
|
||||
}},...goalOptions.map(([value,label])=>el('option',{value},t(label))));
|
||||
goalSelect.value=welcomeGoal;
|
||||
root.append(el('section',{class:'card welcome','aria-labelledby':'welcome-title'},
|
||||
el('h2',{id:'welcome-title'},t('welcomeTitle')),
|
||||
@ -155,7 +157,7 @@ function render() {
|
||||
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']])] : []));
|
||||
select('sex',[['male','male'],['female','female']]),select('activity',[['1.2','sedentary'],['1.375','light'],['1.55','moderate'],['1.725','high']]),select('goal',goalOptions)] : []));
|
||||
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=>{
|
||||
@ -187,12 +189,13 @@ function render() {
|
||||
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.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',{id:'daily-menu',tabindex:'-1'},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();
|
||||
if (location.hash === '#daily-menu') document.getElementById('daily-menu')?.focus();
|
||||
|
||||
addEventListener('pageshow',event=>{if(event.persisted) location.reload();});
|
||||
addEventListener('focus',async()=>{
|
||||
|
||||
@ -27,6 +27,7 @@
|
||||
"calories": "ккал",
|
||||
"protein": "г белка",
|
||||
"menu": "Пример меню на день",
|
||||
"menuOpen": "Открыть меню на день",
|
||||
"menuHint": "Порции рассчитаны по вашему ориентиру калорий. Состав и пищевая ценность примерные; проверьте продукты на аллергию.",
|
||||
"breakfast": "Завтрак: овсянка с йогуртом",
|
||||
"lunch": "Обед: курица с рисом и овощами",
|
||||
@ -38,6 +39,7 @@
|
||||
"passwordHint": "От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль.",
|
||||
"loading": "Загрузка…",
|
||||
"errors": {
|
||||
"goal": "Не удалось сохранить цель. Выберите цель из списка.",
|
||||
"height": "Рост не подходит. Введите число от 100 до 250 см.",
|
||||
"weight": "Вес не подходит. Введите число от 25 до 350 кг.",
|
||||
"age": "Возраст не подходит. Введите целое число от 18 до 100 лет.",
|
||||
@ -63,7 +65,7 @@
|
||||
"loginHeading": "Войдите в свой профиль",
|
||||
"loginIntro": "Введите имя пользователя и пароль. После входа откроются ваши сохранённые данные и ориентир питания.",
|
||||
"registerHeading": "Создайте учётную запись",
|
||||
"registerIntro": "Выберите имя и пароль, затем заполните данные для расчёта питания. После регистрации откроется ваш профиль.",
|
||||
"registerIntro": "Выберите имя и пароль и заполните данные о себе. После регистрации вы сможете открыть меню на день и план тренировок.",
|
||||
"toRegister": "Впервые здесь? Создать учётную запись",
|
||||
"toLogin": "Уже есть учётная запись? Войти",
|
||||
"sexChoose": "Выберите пол",
|
||||
@ -110,6 +112,7 @@
|
||||
"calories": "ккал",
|
||||
"protein": "г ақуыз",
|
||||
"menu": "Бір күндік мәзір үлгісі",
|
||||
"menuOpen": "Бір күндік мәзірді ашу",
|
||||
"menuHint": "Үлестер калория бағдарыңызға сай есептелді. Құрамы мен тағамдық құндылығы шамамен берілген; аллергияңызды ескеріңіз.",
|
||||
"breakfast": "Таңғы ас: йогурт қосылған сұлы ботқасы",
|
||||
"lunch": "Түскі ас: күріш пен көкөніс қосылған тауық еті",
|
||||
@ -121,6 +124,7 @@
|
||||
"passwordHint": "12–128 таңба. Ұзын құпиясөз профиліңізді қорғауға көмектеседі.",
|
||||
"loading": "Жүктелуде…",
|
||||
"errors": {
|
||||
"goal": "Мақсат сақталмады. Тізімнен мақсатты таңдаңыз.",
|
||||
"height": "Бойыңыз дұрыс емес. 100–250 см аралығындағы санды енгізіңіз.",
|
||||
"weight": "Салмағыңыз дұрыс емес. 25–350 кг аралығындағы санды енгізіңіз.",
|
||||
"age": "Жасыңыз дұрыс емес. 18–100 аралығындағы бүтін санды енгізіңіз.",
|
||||
@ -146,7 +150,7 @@
|
||||
"loginHeading": "Профиліңізге кіріңіз",
|
||||
"loginIntro": "Пайдаланушы аты мен құпиясөзді енгізіңіз. Кіргеннен кейін сақталған деректеріңіз бен тамақтану бағдарыңыз ашылады.",
|
||||
"registerHeading": "Тіркеліңіз",
|
||||
"registerIntro": "Атыңыз бен құпиясөзді таңдаңыз, содан кейін тамақтануды есептеу үшін деректеріңізді толтырыңыз. Тіркелгеннен кейін профиліңіз ашылады.",
|
||||
"registerIntro": "Атыңыз бен құпиясөзді таңдаңыз және өзіңіз туралы деректерді толтырыңыз. Тіркелген соң бір күндік мәзір мен жаттығу жоспарын аша аласыз.",
|
||||
"toRegister": "Алғаш рет келдіңіз бе? Тіркелу",
|
||||
"toLogin": "Тіркелгенсіз бе? Кіру",
|
||||
"sexChoose": "Жынысыңызды таңдаңыз",
|
||||
@ -193,6 +197,7 @@
|
||||
"calories": "kcal",
|
||||
"protein": "g protein",
|
||||
"menu": "Example daily menu",
|
||||
"menuOpen": "Open daily menu",
|
||||
"menuHint": "Portions follow your calorie estimate. Ingredients and nutrition are approximate; check for allergens.",
|
||||
"breakfast": "Breakfast: oatmeal with yogurt",
|
||||
"lunch": "Lunch: chicken with rice and vegetables",
|
||||
@ -204,6 +209,7 @@
|
||||
"passwordHint": "12–128 characters. A long password helps protect your profile.",
|
||||
"loading": "Loading…",
|
||||
"errors": {
|
||||
"goal": "Your goal could not be saved. Choose a goal from the list.",
|
||||
"height": "Height is invalid. Enter a number from 100 to 250 cm.",
|
||||
"weight": "Weight is invalid. Enter a number from 25 to 350 kg.",
|
||||
"age": "Age is invalid. Enter a whole number from 18 to 100.",
|
||||
@ -229,7 +235,7 @@
|
||||
"loginHeading": "Sign in to your profile",
|
||||
"loginIntro": "Enter your username and password. Your saved details and nutrition estimate will open after you sign in.",
|
||||
"registerHeading": "Create your account",
|
||||
"registerIntro": "Choose a username and password, then enter your details for a nutrition estimate. Your profile will open after registration.",
|
||||
"registerIntro": "Choose a username and password and enter your details. After signing up, you can open your daily menu and workout plan.",
|
||||
"toRegister": "New here? Create account",
|
||||
"toLogin": "Already have an account? Sign in",
|
||||
"sexChoose": "Select your sex",
|
||||
|
||||
Loading…
Reference in New Issue
Block a user