Добавлен канал личных публикаций

This commit is contained in:
AidarKC
2026-11-28 01:18:53 +03:00
parent 7d3f5db206
commit d1ca64d1c1
28 changed files with 325 additions and 473 deletions
+14 -366
View File
@@ -86,14 +86,6 @@ function normalizeHash(hash) {
return normalized || '0';
}
function encodeRoutePart(value = '') {
return encodeURIComponent(String(value));
}
function normalizeLoginInput(value) {
return String(value || '').trim().replace(/^@+/, '');
}
function buildChannelRouteFromSummary(summary, fallbackId) {
const ownerBch = String(summary?.channel?.ownerBlockchainName || '').trim();
const ownerLogin = String(summary?.channel?.ownerLogin || '').trim();
@@ -107,14 +99,13 @@ function buildChannelRouteFromSummary(summary, fallbackId) {
function isStoriesChannel(summaryOrChannel = null) {
const typeCode = Number(summaryOrChannel?.channel?.channelTypeCode ?? summaryOrChannel?.channelTypeCode ?? 1);
const channelName = String(summaryOrChannel?.channel?.channelName || summaryOrChannel?.channelName || '').trim().toLowerCase();
return typeCode === CHANNEL_TYPE_STORIES || channelName === 'stories';
return typeCode === CHANNEL_TYPE_STORIES;
}
function isVisibleChannelSummary(summary) {
if (!summary?.channel) return false;
if (isStoriesChannel(summary)) return false;
if (summary?.channel?.deleted) return false;
if (!isStoriesChannel(summary) && String(summary.channel.channelName || '').toLowerCase() === 'stories') return false;
const ownerLogin = String(summary.channel.ownerLogin || '').trim();
const channelName = String(summary.channel.channelName || '').trim();
return !!ownerLogin && !!channelName;
@@ -137,148 +128,6 @@ function createChannelAvatar(channel = {}) {
});
}
function allFeedSummaries() {
const feed = state.channelsFeed || {};
return [
...(feed.ownedChannels || []),
...(feed.followedUsersChannels || []),
...(feed.followedChannels || []),
].filter(isVisibleChannelSummary);
}
function uniqueBy(items, keySelector) {
const seen = new Set();
const out = [];
for (const item of items) {
const key = keySelector(item);
if (!key || seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}
function createDebounced(fn, delayMs = 250) {
let timer = null;
return (...args) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
fn(...args);
}, delayMs);
};
}
async function resolveChannelTargetFromInput(rawInput) {
const input = String(rawInput || '').trim();
if (!input) throw new Error(t('screens.channels_list.text_028'));
const byOwnerAndName = input.match(/^@?([^/#\s]+)\s*\/\s*#?(.+)$/);
if (byOwnerAndName) {
const ownerLogin = normalizeLoginInput(byOwnerAndName[1]);
const channelName = String(byOwnerAndName[2] || '').trim().toLowerCase();
if (!ownerLogin || !channelName) {
throw new Error(t('screens.channels_list.text_029'));
}
const user = await authService.getUser(ownerLogin);
if (!user?.exists || !user?.blockchainName) {
throw new Error(t('screens.channels_list.text_030'));
}
const ownerFeed = await authService.listSubscriptionsFeed(ownerLogin, 500);
const ownChannels = Array.isArray(ownerFeed?.ownedChannels) ? ownerFeed.ownedChannels.filter(isVisibleChannelSummary) : [];
const matches = ownChannels.filter((item) => (
String(item?.channel?.channelName || '').trim().toLowerCase() === channelName
));
if (!matches.length) {
throw new Error(t('screens.channels_list.text_031'));
}
const primaryMatches = matches.filter((item) => (
String(item?.channel?.ownerBlockchainName || '') === String(user.blockchainName || '')
));
const pool = primaryMatches.length ? primaryMatches : matches;
const match = [...pool].sort((a, b) => (
Number(b?.channel?.channelRoot?.blockNumber || -1) - Number(a?.channel?.channelRoot?.blockNumber || -1)
))[0];
return {
ownerBlockchainName: String(match?.channel?.ownerBlockchainName || user.blockchainName),
rootBlockNumber: Number(match?.channel?.channelRoot?.blockNumber),
rootBlockHash: normalizeHash(match?.channel?.channelRoot?.blockHash),
};
}
const byNameOnly = input.replace(/^#/, '').trim().toLowerCase();
const summaries = allFeedSummaries();
const matches = summaries.filter((summary) => (
String(summary?.channel?.channelName || '').trim().toLowerCase() === byNameOnly
));
if (!matches.length) {
throw new Error(t('screens.channels_list.text_032'));
}
if (matches.length > 1) {
throw new Error(t('screens.channels_list.text_033'));
}
const one = matches[0];
return {
ownerBlockchainName: String(one?.channel?.ownerBlockchainName || ''),
rootBlockNumber: Number(one?.channel?.channelRoot?.blockNumber),
rootBlockHash: normalizeHash(one?.channel?.channelRoot?.blockHash),
};
}
function channelSuggestionsByInput(rawInput) {
const q = String(rawInput || '').trim().toLowerCase();
if (q.length < 1) return [];
const rows = allFeedSummaries().map((summary) => {
const owner = String(summary?.channel?.ownerLogin || '').trim();
const channel = String(summary?.channel?.channelName || '').trim();
if (!owner || !channel) return null;
return {
key: `${owner.toLowerCase()}/${channel.toLowerCase()}`,
label: formatChannelAddress({ ownerLogin: owner, channelName: channel }),
owner,
channel,
};
}).filter(Boolean);
return uniqueBy(rows, (it) => it.key)
.filter((it) => (
it.channel.toLowerCase().includes(q) ||
formatChannelAddress({ ownerLogin: it.owner.toLowerCase(), channelName: it.channel.toLowerCase() }).includes(normalizeLoginInput(q))
))
.slice(0, 7)
.map((it) => it.label);
}
function renderSuggestions(container, values, onPick) {
container.innerHTML = '';
if (!values.length) {
container.style.display = 'none';
return;
}
container.style.display = '';
values.forEach((value) => {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'ui-button channel-search-item';
btn.textContent = value;
btn.addEventListener('click', () => onPick(value));
container.append(btn);
});
}
function normalizeComparableLogin(value) {
return normalizeLoginInput(value).toLowerCase();
}
function normalizeChannelsViewMode(route = null) {
const mode = String(route?.params?.mode || '').trim().toLowerCase();
const scope = String(route?.params?.scope || '').trim().toLowerCase();
@@ -302,211 +151,6 @@ const CHANNEL_FILTERS = () => [
[CHANNELS_VIEW_DELETED, t('screens.channels_list.text_045')],
];
function isFollowedUserVisible(targetLogin) {
const expected = normalizeComparableLogin(targetLogin);
if (!expected) return false;
const rows = Array.isArray(state.channelsFeed?.followedUsersChannels)
? state.channelsFeed.followedUsersChannels
: [];
return rows
.filter(isVisibleChannelSummary)
.some((row) => normalizeComparableLogin(row?.channel?.ownerLogin) === expected);
}
function isFollowedChannelVisible(target) {
const rows = Array.isArray(state.channelsFeed?.followedChannels)
? state.channelsFeed.followedChannels
: [];
const expectedBch = String(target?.ownerBlockchainName || '');
const expectedNo = Number(target?.rootBlockNumber);
const expectedHash = normalizeHash(target?.rootBlockHash);
if (!expectedBch || !Number.isFinite(expectedNo)) return false;
return rows.filter(isVisibleChannelSummary).some((row) => {
const rowBch = String(row?.channel?.ownerBlockchainName || '');
const rowNo = Number(row?.channel?.channelRoot?.blockNumber);
const rowHash = normalizeHash(row?.channel?.channelRoot?.blockHash);
return rowBch === expectedBch && rowNo === expectedNo && rowHash === expectedHash;
});
}
function openSimpleSubscribeModal({ kind, kindLabel, submitLabel, unfollow = false, onSuccess }) {
const targetHint = kind === 'channel'
? `<p class="meta-muted">${t('dialogs.remaining.pages.channels_list.markup.kanal_alice_free_channel_ili_imya_kanala')}</p>`
: `<p class="meta-muted">${t('dialogs.remaining.pages.channels_list.markup.avtor_alice_free_staryy_vvod_s_tozhe_prinimaetsya')}</p>`;
const submitText = submitLabel || (unfollow ? t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.otpisatsya') : t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.podpisatsya'));
const placeholder = kind === 'channel' ? 'Alice@free/channel' : 'Alice@free';
const root = document.getElementById('modal-root');
root.innerHTML = `
<div class="modal" id="channels-subscribe-modal">
<div class="modal-card stack">
<h3 class="modal-title">${kindLabel}</h3>
${targetHint}
<label class="meta-muted" for="subscribe-input">${t('dialogs.modals.channels_list.label_001')}</label>
<input id="subscribe-input" class="input" placeholder="${placeholder}" autocomplete="off" />
<div id="subscribe-suggest" class="channels-search-suggest" style="display:none"></div>
<div id="subscribe-error" class="meta-muted inline-error"></div>
<div class="form-actions-grid">
<button class="secondary-btn" id="sub-cancel" type="button">${t('dialogs.modals.channels_list.label_002')}</button>
<button class="primary-btn" id="sub-submit" type="button">${submitText}</button>
</div>
</div>
</div>
`;
const inputEl = root.querySelector('#subscribe-input');
const suggestEl = root.querySelector('#subscribe-suggest');
const errorEl = root.querySelector('#subscribe-error');
const submitEl = root.querySelector('#sub-submit');
let inFlight = false;
const setBusy = (busy) => {
inFlight = !!busy;
submitEl.disabled = inFlight;
if (inputEl) inputEl.disabled = inFlight;
submitEl.textContent = inFlight ? t('dialogs.modals.channels_list.label_003') : submitText;
};
const close = () => {
root.innerHTML = '';
};
const applySuggestion = (value) => {
if (!inputEl) return;
inputEl.value = value;
if (suggestEl) suggestEl.style.display = 'none';
inputEl.focus();
};
const refreshSuggestions = createDebounced(async () => {
if (!inputEl || !suggestEl || inFlight) return;
const raw = String(inputEl.value || '').trim();
if (!raw) {
suggestEl.style.display = 'none';
suggestEl.innerHTML = '';
return;
}
try {
if (kind === 'user') {
const prefix = normalizeLoginInput(raw);
if (prefix.length < 2) {
suggestEl.style.display = 'none';
suggestEl.innerHTML = '';
return;
}
const logins = await authService.searchUsers(prefix);
const suggestions = (Array.isArray(logins) ? logins : []).slice(0, 8).map((login) => normalizeLoginInput(login));
renderSuggestions(suggestEl, suggestions, applySuggestion);
return;
}
const suggestions = channelSuggestionsByInput(raw);
renderSuggestions(suggestEl, suggestions, applySuggestion);
} catch {
suggestEl.style.display = 'none';
suggestEl.innerHTML = '';
}
}, 240);
root.querySelector('#sub-cancel')?.addEventListener('click', close);
inputEl?.addEventListener('input', () => {
if (!errorEl) return;
errorEl.textContent = '';
refreshSuggestions();
});
submitEl?.addEventListener('click', async () => {
if (inFlight) return;
const login = state.session.login;
const storagePwd = state.session.storagePwdInMemory;
const value = String(inputEl?.value || '').trim();
if (!login || !storagePwd) {
errorEl.textContent = t('dialogs.modals.channels_list.label_004');
return;
}
if (!value) {
errorEl.textContent = t('dialogs.modals.channels_list.label_005');
return;
}
setBusy(true);
errorEl.textContent = '';
try {
let channelTarget = null;
let userTargetLogin = '';
if (kind === 'user') {
userTargetLogin = normalizeLoginInput(value);
await authService.addBlockFollowUser({
login,
targetLogin: userTargetLogin,
storagePwd,
unfollow,
});
} else if (kind === 'channel') {
channelTarget = await resolveChannelTargetFromInput(value);
if (!channelTarget?.ownerBlockchainName || !Number.isFinite(channelTarget.rootBlockNumber)) {
throw new Error(t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.kanal_ne_nayden'));
}
await authService.addBlockFollowChannel({
login,
storagePwd,
targetBlockchainName: channelTarget.ownerBlockchainName,
targetBlockNumber: channelTarget.rootBlockNumber,
targetBlockHashHex: channelTarget.rootBlockHash,
unfollow,
});
} else {
throw new Error(t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.nepodderzhivaemyy_tip_podpiski'));
}
if (typeof onSuccess === 'function') {
await onSuccess();
}
if (kind === 'user') {
const visible = isFollowedUserVisible(userTargetLogin);
if (!unfollow && !visible) {
throw new Error(t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.podpiska_ne_podtverdilas_posle_obnovleniya_spiska'));
}
if (unfollow && visible) {
throw new Error(t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.otpiska_ne_podtverdilas_posle_obnovleniya_spiska'));
}
}
if (kind === 'channel') {
const visible = isFollowedChannelVisible(channelTarget);
if (!unfollow && !visible) {
throw new Error(t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.podpiska_na_kanal_ne_podtverdilas_posle_obnovleniya_sp'));
}
if (unfollow && visible) {
throw new Error(t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.otpiska_ot_kanala_ne_podtverdilas_posle_obnovleniya_sp'));
}
}
softHaptic(15);
showToast(unfollow ? t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.otpiska_vypolnena') : t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.podpiska_vypolnena'));
close();
} catch (error) {
errorEl.textContent = toUserMessage(error, t('dialogs.remaining.pages.channels_list.opensimplesubscribemodal.value1_ne_udalos', { value1: submitText }));
setBusy(false);
}
});
if (inputEl) inputEl.focus();
}
function mapMockGroups() {
const mapRow = (channel) => ({
...channel,
@@ -551,18 +195,18 @@ function mapMockGroups() {
}
function mapApiChannelRow(summary, bucketKey, idx, index, notificationsState) {
const rowId = `${bucketKey}-${idx}`;
const rowId = isStoriesChannel(summary) ? `${bucketKey}-publications-${String(summary?.channel?.ownerLogin || '').toLowerCase()}` : `${bucketKey}-${idx}`;
index[rowId] = summary;
const ownerLogin = summary?.channel?.ownerLogin || t('screens.channels_list.text_035');
const channelName = summary?.channel?.channelName || t('screens.channels_list.text_036');
const displayTitle = String(summary?.channel?.displayName || channelName).trim();
const displayTitle = isStoriesChannel(summary) && bucketKey === 'own' ? t('remaining.channels.my_publications') : String(summary?.channel?.displayName || channelName).trim();
const channelDescription = String(summary?.channel?.channelDescription || '').trim();
const channelTypeCode = Number(summary?.channel?.channelTypeCode ?? 1);
const channelTypeVersion = Number(summary?.channel?.channelTypeVersion ?? 1);
const isOwn = bucketKey === 'own';
const title = displayTitle || channelName;
const technicalLabel = formatChannelAddress({ ownerLogin, channelName });
const technicalLabel = formatChannelAddress({ ownerLogin, channelName, channelRootBlockNumber: Number(summary?.channel?.channelRoot?.blockNumber) });
const lastMessage = resolveChannelLastMessage(summary);
return {
@@ -698,15 +342,19 @@ function buildDiaryChannelRow(diaryPayload, ownRows = [], notificationsState = {
function mapApiFeed(feed, notificationsState, diaryPayload = null) {
const index = {};
const ownChannels = (feed?.ownedChannels || [])
.filter(isVisibleChannelSummary)
.map((it, idx) => mapApiChannelRow(it, 'own', idx, index, notificationsState));
const ownRows = (feed?.ownedChannels || []).filter(isVisibleChannelSummary);
const ownChannels = [
...ownRows.filter(isStoriesChannel).map(it => mapApiChannelRow(it, 'own', 0, index, notificationsState)),
...ownRows.filter(it => !isStoriesChannel(it)).map((it, idx) => mapApiChannelRow(it, 'own', idx, index, notificationsState)),
];
const diaryChannel = diaryPayload
? buildDiaryChannelRow(diaryPayload, feed?.ownedChannels || [], notificationsState, index)
: null;
if (diaryChannel) ownChannels.unshift(diaryChannel);
if (diaryChannel) ownChannels.splice(ownChannels[0]?.channelTypeCode === 0 ? 1 : 0, 0, diaryChannel);
const seenRoots = new Set();
const followedUserChannels = (feed?.followedUsersChannels || [])
.filter(isVisibleChannelSummary)
.filter(it => { const key = String(it.channel.ownerLogin).toLowerCase(); if (seenRoots.has(key)) return false; seenRoots.add(key); return true; })
.map((it, idx) => mapApiChannelRow(it, 'followedUsers', idx, index, notificationsState));
const subscribedChannels = (feed?.followedChannels || [])
.filter(isVisibleChannelSummary)
@@ -887,7 +535,7 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
const allChannels = listState.channels || [];
const filtered = allChannels.filter((channel) => {
if (listState.viewMode === CHANNELS_VIEW_OWNED) return channel.isOwnChannel === true && channel.isDeleted !== true;
if (listState.viewMode === CHANNELS_VIEW_FOLLOWING) return channel.sourceBucket === 'followedChannels';
if (listState.viewMode === CHANNELS_VIEW_FOLLOWING) return channel.isSubscribed === true && !channel.isOwnChannel;
if (listState.viewMode === CHANNELS_VIEW_DELETED) return channel.isDeleted === true;
return channel.isDeleted !== true;
}).filter((channel) => {