SHA256
211 lines
8.7 KiB
JavaScript
211 lines
8.7 KiB
JavaScript
import { renderHeader } from '../components/header.js';
|
||
import { authService, state } from '../state.js';
|
||
import { toUserMessage } from '../services/ui-error-texts.js';
|
||
import {
|
||
channelNameErrorText,
|
||
normalizeChannelDisplayName,
|
||
validateChannelDisplayName,
|
||
} from '../services/channel-name-rules.js';
|
||
import { openArweaveAttachmentManager, markArweaveAttachmentPlaced } from '../components/arweave-attachment-manager.js';
|
||
import { buildArweaveDataUrl } from '../services/arweave-file-service.js';
|
||
|
||
export const pageMeta = { id: 'add-channel-view', title: 'Создать канал' };
|
||
|
||
const CREATE_CHANNEL_FLASH_KEY = 'shine-channels-create-success';
|
||
const CHANNEL_TYPE_PUBLIC = 1;
|
||
|
||
function persistCreateSuccessFlash(message) {
|
||
try {
|
||
sessionStorage.setItem(CREATE_CHANNEL_FLASH_KEY, String(message || '').trim());
|
||
} catch {
|
||
// ignore storage errors
|
||
}
|
||
}
|
||
|
||
function normalizeMetaText(value, max, label) {
|
||
const normalized = String(value || '').trim();
|
||
const length = Array.from(normalized).length;
|
||
if (length > max) {
|
||
return { ok: false, normalized, length, error: `${label}: максимум ${max} символов.` };
|
||
}
|
||
return { ok: true, normalized, length, error: '' };
|
||
}
|
||
|
||
function renderAvatarPreview(slot, avatar, title) {
|
||
if (!slot) return;
|
||
slot.innerHTML = '';
|
||
const wrap = document.createElement('div');
|
||
wrap.className = 'channel-profile-avatar';
|
||
wrap.style.setProperty('--channel-avatar-size', '104px');
|
||
if (avatar?.ar) {
|
||
const img = document.createElement('img');
|
||
img.alt = 'Аватар канала';
|
||
img.src = buildArweaveDataUrl({ gateway: state.entrySettings.arweaveServer, txId: avatar.ar });
|
||
wrap.append(img);
|
||
} else {
|
||
wrap.textContent = String(title || 'К').trim().slice(0, 1).toUpperCase() || 'К';
|
||
}
|
||
slot.append(wrap);
|
||
}
|
||
|
||
export function render({ navigate }) {
|
||
const screen = document.createElement('section');
|
||
screen.className = 'stack channels-screen channels-screen--add';
|
||
|
||
screen.append(
|
||
renderHeader({
|
||
title: 'Создать канал',
|
||
leftAction: { label: '<', onClick: () => navigate('channels-list') },
|
||
}),
|
||
);
|
||
|
||
const form = document.createElement('form');
|
||
form.className = 'card stack';
|
||
form.innerHTML = `
|
||
<strong class="channel-head-title">Создание канала</strong>
|
||
<p class="channel-head-meta">Разрешены только латинские буквы, цифры, _ и -.</p>
|
||
<p class="channel-head-meta">Длина названия: от 3 до 32 символов. Название не должно состоять только из цифр.</p>
|
||
<p class="channel-head-meta">Можно использовать большие и маленькие буквы, но уникальность проверяется без учёта регистра.</p>
|
||
<div class="meta-muted">Тип канала фиксирован: публичный (1).</div>
|
||
|
||
<label for="channel-name">Техническое имя канала</label>
|
||
<input id="channel-name" class="input" maxlength="32" placeholder="Например: My-Channel_1" required />
|
||
<div id="channel-name-error" class="meta-muted inline-error"></div>
|
||
|
||
<label for="channel-title">Человекочитаемое имя</label>
|
||
<input id="channel-title" class="input" maxlength="50" placeholder="Например: Мой красивый канал" />
|
||
<div class="meta-muted" id="channel-title-counter">0 / 50 символов</div>
|
||
<div id="channel-title-error" class="meta-muted inline-error"></div>
|
||
|
||
<div id="channel-avatar-preview"></div>
|
||
<button type="button" class="secondary-btn" id="channel-avatar-btn">Выбрать аватар</button>
|
||
|
||
<label for="channel-description">Описание канала (необязательно)</label>
|
||
<textarea id="channel-description" class="input" rows="4" maxlength="250" placeholder="Коротко о канале, до 250 символов"></textarea>
|
||
<div class="meta-muted" id="channel-description-counter">0 / 250 символов</div>
|
||
<div id="channel-description-error" class="meta-muted inline-error"></div>
|
||
|
||
<div id="channel-create-error" class="meta-muted inline-error"></div>
|
||
<div class="form-actions-grid">
|
||
<button type="button" class="secondary-btn" id="cancel-create-channel">Отмена</button>
|
||
<button type="submit" class="primary-btn" id="submit-create-channel">Создать</button>
|
||
</div>
|
||
`;
|
||
|
||
const nameEl = form.querySelector('#channel-name');
|
||
const titleEl = form.querySelector('#channel-title');
|
||
const descriptionEl = form.querySelector('#channel-description');
|
||
const avatarPreviewEl = form.querySelector('#channel-avatar-preview');
|
||
const avatarBtn = form.querySelector('#channel-avatar-btn');
|
||
const nameErrorEl = form.querySelector('#channel-name-error');
|
||
const titleErrorEl = form.querySelector('#channel-title-error');
|
||
const titleCounterEl = form.querySelector('#channel-title-counter');
|
||
const descriptionErrorEl = form.querySelector('#channel-description-error');
|
||
const descriptionCounterEl = form.querySelector('#channel-description-counter');
|
||
const errorEl = form.querySelector('#channel-create-error');
|
||
const submitEl = form.querySelector('#submit-create-channel');
|
||
const cancelEl = form.querySelector('#cancel-create-channel');
|
||
|
||
let submitInFlight = false;
|
||
let selectedAvatar = null;
|
||
|
||
const setBusy = (busy) => {
|
||
submitInFlight = !!busy;
|
||
submitEl.disabled = submitInFlight;
|
||
cancelEl.disabled = submitInFlight;
|
||
nameEl.disabled = submitInFlight;
|
||
titleEl.disabled = submitInFlight;
|
||
descriptionEl.disabled = submitInFlight;
|
||
avatarBtn.disabled = submitInFlight;
|
||
submitEl.textContent = submitInFlight ? 'Создаём...' : 'Создать';
|
||
};
|
||
|
||
const updateValidation = () => {
|
||
const nameCheck = validateChannelDisplayName(nameEl.value);
|
||
const titleCheck = normalizeMetaText(titleEl.value, 50, 'Название');
|
||
const descriptionCheck = normalizeMetaText(descriptionEl.value, 250, 'Описание');
|
||
|
||
nameErrorEl.textContent = nameCheck.ok ? '' : channelNameErrorText(nameCheck.code);
|
||
titleErrorEl.textContent = titleCheck.error;
|
||
descriptionErrorEl.textContent = descriptionCheck.error;
|
||
|
||
titleCounterEl.textContent = `${Number(titleCheck.length || 0)} / 50 символов`;
|
||
descriptionCounterEl.textContent = `${Number(descriptionCheck.length || 0)} / 250 символов`;
|
||
|
||
const ok = nameCheck.ok && titleCheck.ok && descriptionCheck.ok;
|
||
submitEl.disabled = submitInFlight || !ok;
|
||
renderAvatarPreview(avatarPreviewEl, selectedAvatar, titleCheck.normalized || nameCheck.normalized);
|
||
|
||
return {
|
||
ok,
|
||
name: nameCheck.normalized,
|
||
title: titleCheck.normalized,
|
||
description: descriptionCheck.normalized,
|
||
};
|
||
};
|
||
|
||
nameEl.addEventListener('input', updateValidation);
|
||
titleEl.addEventListener('input', updateValidation);
|
||
descriptionEl.addEventListener('input', updateValidation);
|
||
avatarBtn.addEventListener('click', async () => {
|
||
try {
|
||
selectedAvatar = await openArweaveAttachmentManager({
|
||
login: state.session.login,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
gateway: state.entrySettings.arweaveServer,
|
||
mode: 'avatar',
|
||
historyPurpose: 'avatar',
|
||
});
|
||
updateValidation();
|
||
} catch (error) {
|
||
errorEl.textContent = toUserMessage(error, 'Не удалось выбрать аватар.');
|
||
}
|
||
});
|
||
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
if (submitInFlight) return;
|
||
|
||
const login = state.session.login;
|
||
const storagePwd = state.session.storagePwdInMemory;
|
||
if (!login || !storagePwd) {
|
||
errorEl.textContent = 'Сессия недействительна. Выполните вход заново.';
|
||
return;
|
||
}
|
||
|
||
const check = updateValidation();
|
||
if (!check.ok) return;
|
||
|
||
setBusy(true);
|
||
errorEl.textContent = '';
|
||
|
||
try {
|
||
await authService.addBlockCreateChannel({
|
||
login,
|
||
storagePwd,
|
||
channelName: normalizeChannelDisplayName(check.name),
|
||
channelDescription: check.description,
|
||
channelProfileTitle: check.title,
|
||
channelAvatar: selectedAvatar,
|
||
channelType: CHANNEL_TYPE_PUBLIC,
|
||
channelTypeVersion: 1,
|
||
});
|
||
if (selectedAvatar?.ar) markArweaveAttachmentPlaced(login, selectedAvatar);
|
||
|
||
persistCreateSuccessFlash(`Канал "${normalizeChannelDisplayName(check.name)}" создан.`);
|
||
navigate('channels-list');
|
||
} catch (error) {
|
||
errorEl.textContent = toUserMessage(error, 'Не удалось создать канал.');
|
||
setBusy(false);
|
||
updateValidation();
|
||
}
|
||
});
|
||
|
||
cancelEl.addEventListener('click', () => navigate('channels-list'));
|
||
|
||
screen.append(form);
|
||
nameEl.focus();
|
||
updateValidation();
|
||
return screen;
|
||
}
|