SHA256
Связи: список, поиск, фильтры со счётчиками, понятные состояния
- «Списком / На карте»: тот же состав людей списком – по близости (Близкие, Друзья, Контакты, Друзья друзей) или по алфавиту, «Написать» и меню у каждой строки; сотни строк без тормозов (content-visibility); - чипы фильтров вместо вкладок: один выбор, у каждого число людей, пустые скрыты; «Добавили вас» – связи только с той стороны («хочет дружить», «вас добавили»), в карточке – «Дружить в ответ» / «Добавить в ответ»; - поиск в шапке: сначала люди на карте (выбор – показать на карте), затем вся сеть (выбор – открыть его связи); - карточка человека: аватар, кто он вам («Друг · взаимно»), не прячется под карточкой; - чужая карта: в шапке аватар, имя и число связей, стрелка – к своей карте; - загрузка – спиннер с задержкой вместо текста, ошибка – с «Повторить», пустая карта – с подсказкой и действием; лишние панели в это время скрыты. Общие компоненты: feedback.js (спиннер, загрузка, пусто, ошибка), person-row.js (строка человека как в списке чатов), createSearchTopBar (шапка-поиск; поиск в чате переведён на неё).
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
// Общие состояния экрана: загрузка, «пусто» и ошибка – один вид на всё приложение.
|
||||
// Индикатор загрузки появляется с задержкой (CSS): если данные пришли быстро, его не видно
|
||||
// вовсе, и экран не мелькает.
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
export function createSpinner({ size = 'md', label = 'Загрузка' } = {}) {
|
||||
const el = document.createElement('span');
|
||||
el.className = `spinner spinner--${size}`;
|
||||
el.setAttribute('role', 'status');
|
||||
el.setAttribute('aria-label', label);
|
||||
return el;
|
||||
}
|
||||
|
||||
export function createLoadingState({ label = 'Загрузка', delayMs = 350, className = '' } = {}) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `loading-state${className ? ` ${className}` : ''}`;
|
||||
el.style.setProperty('--loading-delay', `${Math.max(0, Number(delayMs) || 0)}ms`);
|
||||
el.append(createSpinner({ label }));
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сообщение вместо содержимого: пусто или ошибка, с необязательным действием.
|
||||
* @param {{ kind?: 'empty'|'error', icon?: string, title?: string, text?: string,
|
||||
* actionLabel?: string, onAction?: Function, className?: string }} opts
|
||||
*/
|
||||
export function createStateMessage({
|
||||
kind = 'empty', icon = '', title = '', text = '', actionLabel = '', onAction = null, className = '',
|
||||
} = {}) {
|
||||
const el = document.createElement('div');
|
||||
el.className = `state-message state-message--${kind}${className ? ` ${className}` : ''}`;
|
||||
if (kind === 'error') el.setAttribute('role', 'alert');
|
||||
if (icon) {
|
||||
const badge = document.createElement('span');
|
||||
badge.className = 'state-message__icon';
|
||||
badge.innerHTML = iconHtml(icon);
|
||||
el.append(badge);
|
||||
}
|
||||
if (title) {
|
||||
const heading = document.createElement('p');
|
||||
heading.className = 'state-message__title';
|
||||
heading.textContent = title;
|
||||
el.append(heading);
|
||||
}
|
||||
if (text) {
|
||||
const body = document.createElement('p');
|
||||
body.className = 'state-message__text';
|
||||
body.textContent = text;
|
||||
el.append(body);
|
||||
}
|
||||
if (actionLabel && typeof onAction === 'function') {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = `${kind === 'error' ? 'secondary-btn' : 'primary-btn'} state-message__action`;
|
||||
button.textContent = actionLabel;
|
||||
button.addEventListener('click', onAction);
|
||||
el.append(button);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
export function createErrorState({
|
||||
title = 'Не удалось загрузить',
|
||||
text = 'Проверьте соединение и попробуйте ещё раз.',
|
||||
onRetry = null,
|
||||
className = '',
|
||||
} = {}) {
|
||||
return createStateMessage({
|
||||
kind: 'error', icon: 'alert', title, text, actionLabel: onRetry ? 'Повторить' : '', onAction: onRetry, className,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Строка человека в списках (связи, поиск людей, списки профиля): аватар, имя, строка под
|
||||
// ним и действия справа. Вид совпадает со строками списка чатов.
|
||||
import { renderUserAvatar } from './avatar-image.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
/**
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.login
|
||||
* @param {string} [opts.name] – как показывать (по умолчанию логин)
|
||||
* @param {string} [opts.firstName] [opts.lastName] – для инициалов
|
||||
* @param {Object|null} [opts.avatar]
|
||||
* @param {string} [opts.sub] – строка под именем
|
||||
* @param {string} [opts.note] – личная заметка (третья строка, курсивом)
|
||||
* @param {string} [opts.markColor] – метка заметки: green/yellow/red/blue/violet, 'note' – без цвета, '' – нет
|
||||
* @param {'close'|'shining'|''} [opts.ring] – цветное кольцо вокруг аватара
|
||||
* @param {boolean} [opts.official]
|
||||
* @param {string} [opts.tag] – короткая пометка цветом в начале второй строки («ждёт ответа»)
|
||||
* @param {Function} [opts.onClick]
|
||||
* @param {Array<{icon:string,label:string,onClick:Function}>} [opts.actions]
|
||||
*/
|
||||
export function createPersonRow({
|
||||
login, name = '', firstName = '', lastName = '', avatar = null, sub = '', note = '', markColor = '',
|
||||
ring = '', official = false, tag = '', onClick = null, actions = [],
|
||||
} = {}) {
|
||||
const row = document.createElement('div');
|
||||
row.className = `person-row${ring ? ` person-row--${ring}` : ''}`;
|
||||
row.dataset.login = String(login || '');
|
||||
|
||||
const main = document.createElement('button');
|
||||
main.type = 'button';
|
||||
main.className = 'person-row__main';
|
||||
const avatarWrap = document.createElement('span');
|
||||
avatarWrap.className = 'person-row__avatar';
|
||||
avatarWrap.append(renderUserAvatar({ login, firstName, lastName, avatar, size: 'md', official }));
|
||||
if (markColor) {
|
||||
// Метка заметки – та же цветная точка, что на карте связей; 'note' – заметка без цвета.
|
||||
const mark = document.createElement('span');
|
||||
mark.className = 'person-row__mark';
|
||||
mark.dataset.mark = markColor;
|
||||
mark.setAttribute('aria-hidden', 'true');
|
||||
avatarWrap.append(mark);
|
||||
}
|
||||
const text = document.createElement('span');
|
||||
text.className = 'person-row__text';
|
||||
const title = document.createElement('span');
|
||||
title.className = 'person-row__name';
|
||||
const titleText = document.createElement('span');
|
||||
titleText.className = 'person-row__name-text';
|
||||
titleText.textContent = name || login;
|
||||
title.append(titleText);
|
||||
text.append(title);
|
||||
if (sub || tag) {
|
||||
// Пометка («ждёт ответа») – в начале второй строки, чтобы не съедать место у имени.
|
||||
const subEl = document.createElement('span');
|
||||
subEl.className = 'person-row__sub';
|
||||
if (tag) {
|
||||
const tagEl = document.createElement('span');
|
||||
tagEl.className = 'person-row__tag';
|
||||
tagEl.textContent = tag;
|
||||
subEl.append(tagEl);
|
||||
if (sub) subEl.append(' · ');
|
||||
}
|
||||
if (sub) subEl.append(sub);
|
||||
text.append(subEl);
|
||||
}
|
||||
if (note) {
|
||||
const noteEl = document.createElement('span');
|
||||
noteEl.className = 'person-row__note';
|
||||
noteEl.textContent = note;
|
||||
text.append(noteEl);
|
||||
}
|
||||
main.append(avatarWrap, text);
|
||||
if (typeof onClick === 'function') main.addEventListener('click', onClick);
|
||||
row.append(main);
|
||||
|
||||
for (const action of actions) {
|
||||
if (!action) continue;
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'icon-btn person-row__action';
|
||||
button.innerHTML = iconHtml(action.icon);
|
||||
button.setAttribute('aria-label', action.label);
|
||||
button.title = action.label;
|
||||
button.addEventListener('click', (event) => action.onClick?.(event, button));
|
||||
row.append(button);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
// Заголовок группы в списке («Друзья · 58», «А»).
|
||||
export function createListSection(text) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'person-list-section';
|
||||
el.textContent = text;
|
||||
return el;
|
||||
}
|
||||
@@ -116,3 +116,67 @@ export function createTopBar({
|
||||
|
||||
return topbar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Шапка-строка поиска (поиск по переписке, по связям и т. п.): «назад» закрывает поиск,
|
||||
* крестик очищает поле, Enter – onSubmit, Escape – onClose.
|
||||
* trailing – узел справа внутри поля (например, счётчик «3 из 12»).
|
||||
*/
|
||||
export function createSearchTopBar({
|
||||
placeholder = 'Поиск',
|
||||
value = '',
|
||||
onInput = null,
|
||||
onSubmit = null,
|
||||
onClose = null,
|
||||
trailing = null,
|
||||
actions = [],
|
||||
className = '',
|
||||
} = {}) {
|
||||
const field = document.createElement('label');
|
||||
field.className = 'topbar-search';
|
||||
field.innerHTML = `
|
||||
<span class="topbar-search__icon" aria-hidden="true">${iconHtml('search')}</span>
|
||||
<input class="topbar-search__input" type="search" autocomplete="off" autocapitalize="off" spellcheck="false" enterkeyhint="search" />
|
||||
`;
|
||||
const input = field.querySelector('input');
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute('aria-label', placeholder);
|
||||
input.value = value;
|
||||
if (trailing instanceof Node) field.append(trailing);
|
||||
const clear = document.createElement('button');
|
||||
clear.type = 'button';
|
||||
clear.className = 'topbar-search__clear';
|
||||
clear.innerHTML = iconHtml('close');
|
||||
clear.setAttribute('aria-label', 'Очистить');
|
||||
clear.title = 'Очистить';
|
||||
clear.hidden = !value;
|
||||
clear.addEventListener('click', (event) => {
|
||||
event.preventDefault();
|
||||
input.value = '';
|
||||
clear.hidden = true;
|
||||
input.focus();
|
||||
onInput?.('');
|
||||
});
|
||||
field.append(clear);
|
||||
input.addEventListener('input', () => {
|
||||
clear.hidden = !input.value;
|
||||
onInput?.(input.value);
|
||||
});
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
onSubmit?.(input.value, event);
|
||||
} else if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
onClose?.();
|
||||
}
|
||||
});
|
||||
const topbar = createTopBar({
|
||||
center: field,
|
||||
className: `topbar--search${className ? ` ${className}` : ''}`,
|
||||
back: { onClick: () => onClose?.(), ariaLabel: 'Закрыть поиск', title: 'Закрыть поиск' },
|
||||
actions,
|
||||
});
|
||||
topbar.searchInput = input;
|
||||
return topbar;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user