SHA256
Добавлена «Отправить через» в Android
This commit is contained in:
+1
-1
@@ -1,2 +1,2 @@
|
||||
client.version=1.20.74
|
||||
client.version=1.20.75
|
||||
server.version=1.16.43
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { saveShare } from './js/services/share-inbox.js';
|
||||
import { resolveDmPushPreview } from './js/services/dm-preview-worker.js';
|
||||
import { isDmPreviewHidden, saveDmPreviewDiagnostics, getDmPreviewSession } from './js/services/dm-preview-settings.js';
|
||||
|
||||
@@ -6,6 +7,21 @@ self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim(
|
||||
self.__shineStoppedCalls = self.__shineStoppedCalls || new Map();
|
||||
self.__shineDmPushQueues = self.__shineDmPushQueues || new Map();
|
||||
|
||||
// A manifest share POST is consumed locally; never fall back to uploading it.
|
||||
self.addEventListener('fetch', event => {
|
||||
const url = new URL(event.request.url);
|
||||
if (event.request.method !== 'POST' || url.origin !== new URL(self.registration.scope).origin || url.pathname !== '/share-target') return;
|
||||
event.respondWith((async () => {
|
||||
try {
|
||||
const id = await saveShare(await event.request.formData());
|
||||
return Response.redirect(new URL(`/contacts?shine-share=${encodeURIComponent(id)}`, url.origin).href, 303);
|
||||
} catch (error) {
|
||||
const code = ['empty', 'limit'].includes(error?.message) ? error.message : 'storage';
|
||||
return Response.redirect(new URL(`/contacts?shine-share-error=${code}`, url.origin).href, 303);
|
||||
}
|
||||
})());
|
||||
});
|
||||
|
||||
self.addEventListener('message', (event) => {
|
||||
const data = event?.data || {};
|
||||
if (data.type === 'SKIP_WAITING') {
|
||||
|
||||
+19
-2
@@ -1,3 +1,4 @@
|
||||
import { restoreShare, activateShare, allowShareNavigation, restoreSharePath, checkShareOwner, getPendingShare, finishShare, isShareSending } from './services/share-flow.js';
|
||||
import { isDmPreviewHidden } from './services/dm-preview-settings.js';
|
||||
import { dmPreviewTarget, dmPreviewText, fetchDmPreview } from './services/dm-preview.js';
|
||||
import { initI18n, onLanguageChange, t } from './i18n/index.js';
|
||||
@@ -1117,7 +1118,7 @@ function scheduleUiReload({
|
||||
delayMs = 700,
|
||||
activateWaitingWorker = true,
|
||||
} = {}) {
|
||||
if (uiUpdateReloadScheduled) return;
|
||||
if (uiUpdateReloadScheduled || getPendingShare()) return;
|
||||
uiUpdateReloadScheduled = true;
|
||||
addAppLogEntry({
|
||||
level: 'info',
|
||||
@@ -1496,7 +1497,14 @@ async function redirectToActiveKeyRotationIfNeeded() {
|
||||
}
|
||||
|
||||
function renderApp() {
|
||||
// Avoid remounting the composer while an encrypted share upload is in progress.
|
||||
if (state.session.isAuthorized && isShareSending()) return;
|
||||
if (state.session.isAuthorized && !keyRotationRouteLock) {
|
||||
checkShareOwner(state.session.login);
|
||||
if (activateShare(state.session.login) && window.location.pathname !== '/contacts') { navigate('contacts'); return; }
|
||||
}
|
||||
if (keyRotationRouteLock && state.session.isAuthorized && getRoute().pageId !== 'key-rotation-view') {
|
||||
if (getPendingShare()) finishShare();
|
||||
// Нельзя покинуть начатую ротацию через browser back, прямую ссылку или меню.
|
||||
navigate('key-rotation-view');
|
||||
return;
|
||||
@@ -1505,7 +1513,7 @@ function renderApp() {
|
||||
const route = getRoute();
|
||||
if (state.session.isAuthorized) {
|
||||
const returnPath = window.sessionStorage.getItem('shine-public-return-path');
|
||||
if (returnPath && returnPath.startsWith('/SHiNE/')) {
|
||||
if (!getPendingShare() && returnPath && returnPath.startsWith('/SHiNE/')) {
|
||||
window.sessionStorage.removeItem('shine-public-return-path');
|
||||
navigate(returnPath);
|
||||
return;
|
||||
@@ -1666,6 +1674,7 @@ async function ensureSessionRuntimeStarted() {
|
||||
}
|
||||
|
||||
async function init() {
|
||||
const shareReady = restoreShare();
|
||||
const languageReady = initI18n();
|
||||
// App остаётся единственным владельцем полного mount/unmount страниц.
|
||||
onLanguageChange(() => {
|
||||
@@ -1688,6 +1697,8 @@ async function init() {
|
||||
});
|
||||
|
||||
setSessionResetHandler(() => {
|
||||
// Keep an incoming share during initial sign-in, but discard a draft bound to a logged-out user.
|
||||
checkShareOwner('');
|
||||
keyRotationRouteLock = false;
|
||||
sessionRuntimeStarted = false;
|
||||
stopChannelsPrefetch();
|
||||
@@ -2092,6 +2103,11 @@ async function init() {
|
||||
|
||||
// Словари загружаются до первого экрана, без вспышки неправильного языка.
|
||||
await languageReady;
|
||||
const shareError = await shareReady;
|
||||
if (shareError) showToast(t(`remaining.share.error_${shareError}`), { kind: 'error' });
|
||||
if ('serviceWorker' in navigator && !isLocalPreviewHost()) {
|
||||
void navigator.serviceWorker.register('/firebase-messaging-sw.js', { scope: '/', type: 'module', updateViaCache: 'none' }).catch(error => console.warn('Share worker registration failed', error));
|
||||
}
|
||||
|
||||
// Важно: сначала всегда отрисовываем UI (чтобы не было "чёрного экрана"),
|
||||
// а сетевые/авторизационные шаги выполняем фоном.
|
||||
@@ -2140,6 +2156,7 @@ async function init() {
|
||||
|
||||
window.addEventListener('popstate', (event) => {
|
||||
if (event.isTrusted && consumeHistoryLayerPop()) return;
|
||||
if (!allowShareNavigation(window.location.pathname)) { restoreSharePath(); return; }
|
||||
renderApp();
|
||||
});
|
||||
document.addEventListener('pointerdown', () => {
|
||||
|
||||
@@ -111,7 +111,10 @@ export function profileCardHtml({ card, login = '', tilesHtml = '', tilesWrapCla
|
||||
</div>
|
||||
|
||||
<div class="pf-stats">
|
||||
${statHtml({ kind: 'friends', label: t('screens.profile_card.text_003'), valueHtml: closeFriends ? `${friends}<small> · ${closeFriends}${th('remaining.html_profile_card.close')}</small>` : String(friends), ariaLabel: t('screens.profile_card.text_014', { value1: friends, value2: closeFriends }) })}
|
||||
<button type="button" class="pf-stat pf-stat--relations" data-profile-list="friends" aria-label="${esc(t('screens.profile_card.text_014', { value1: friends, value2: closeFriends }))}">
|
||||
<span class="pf-stat-relation"><strong class="pf-stat-value">${closeFriends}</strong><span class="pf-stat-label">${esc(t('remaining.share.close_friends'))}</span></span>
|
||||
<span class="pf-stat-relation"><strong class="pf-stat-value">${friends}</strong><span class="pf-stat-label">${esc(t('screens.profile_card.text_003'))}</span></span>
|
||||
</button>
|
||||
${statHtml({ kind: 'channels_owned', label: t('screens.profile_card.text_004'), valueHtml: String(Number(stats.ownedPublicChannelsCount || 0)), ariaLabel: t('screens.profile_card.text_015', { value1: Number(stats.ownedPublicChannelsCount || 0) }) })}
|
||||
${statHtml({ kind: 'channels_following', label: t('screens.profile_card.text_005'), valueHtml: String(Number(stats.followingChannelsCount || 0)), ariaLabel: t('screens.profile_card.text_016', { value1: Number(stats.followingChannelsCount || 0) }) })}
|
||||
</div>
|
||||
|
||||
@@ -4389,6 +4389,20 @@
|
||||
"dm_unread_few": "{count} unread messages"
|
||||
},
|
||||
"remaining": {
|
||||
"share": {
|
||||
"error_session": "Session changed. Sending cancelled.",
|
||||
"choose": "Choose recipient",
|
||||
"cancel_confirm": "Cancel sharing? The prepared message will be discarded.",
|
||||
"error_empty": "No content to share.",
|
||||
"error_limit": "Share up to 10 files, 500 MB total.",
|
||||
"error_storage": "Could not save shared content.",
|
||||
"error_expired": "The prepared message has expired.",
|
||||
"files": "Attachments: {count}",
|
||||
"user_channels": "User channels",
|
||||
"user_publications": "User publications",
|
||||
"close_friends": "Close friends",
|
||||
"busy": "Sending is already in progress."
|
||||
},
|
||||
"theme": {
|
||||
"background": "Background",
|
||||
"surfaces_inputs_menus_cards": "Surfaces: inputs, menus, cards",
|
||||
|
||||
@@ -4389,6 +4389,20 @@
|
||||
"dm_unread_many": "{count} непрочитанных сообщений"
|
||||
},
|
||||
"remaining": {
|
||||
"share": {
|
||||
"error_session": "Сессия изменилась. Отправка отменена.",
|
||||
"choose": "Выберите получателя",
|
||||
"cancel_confirm": "Отменить отправку? Подготовленное сообщение будет удалено.",
|
||||
"error_empty": "Нет содержимого для отправки.",
|
||||
"error_limit": "Можно передать до 10 файлов общим размером до 500 МБ.",
|
||||
"error_storage": "Не удалось сохранить полученное содержимое.",
|
||||
"error_expired": "Срок хранения подготовленного сообщения истёк.",
|
||||
"files": "Вложения: {count}",
|
||||
"user_channels": "Каналы пользователя",
|
||||
"user_publications": "Публикации пользователя",
|
||||
"close_friends": "Близкие",
|
||||
"busy": "Отправка уже выполняется."
|
||||
},
|
||||
"theme": {
|
||||
"background": "Фон",
|
||||
"surfaces_inputs_menus_cards": "Поверхности: поля, меню, карточки",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { shareForChat, finishShare, isShareSending, setShareSending } from '../services/share-flow.js';
|
||||
import { formatDate, formatDateTime } from '../i18n/format.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
@@ -1448,6 +1449,7 @@ function preserveComposerSelection(input, callback) {
|
||||
export function render({ navigate, route, chrome }) {
|
||||
const routeChatId = route.params.chatId || 'u1';
|
||||
const chatId = normalizeDmChatId(routeChatId) || 'u1';
|
||||
let shared = shareForChat(chatId);
|
||||
const contact = directMessages.find((d) => normalizeDmChatId(d.id) === chatId) || {
|
||||
id: chatId,
|
||||
name: String(routeChatId || chatId),
|
||||
@@ -1952,6 +1954,19 @@ export function render({ navigate, route, chrome }) {
|
||||
`;
|
||||
|
||||
const input = form.elements.message;
|
||||
const sharedBanner = document.createElement('div');
|
||||
sharedBanner.className = 'dm-edit-banner';
|
||||
sharedBanner.hidden = !shared?.files.length;
|
||||
if (shared) {
|
||||
input.value = shared.text;
|
||||
if (shared.files.length) {
|
||||
const description = document.createElement('div');
|
||||
description.className = 'dm-edit-banner__text';
|
||||
description.textContent = t('remaining.share.files', { count: shared.files.length }) + ': ' + shared.files.map(file => file.name).join(', ');
|
||||
sharedBanner.append(description);
|
||||
}
|
||||
}
|
||||
form.prepend(sharedBanner);
|
||||
const emojiSlot = form.querySelector('#chat-emoji-picker-slot');
|
||||
const emojiToggle = form.querySelector('#chat-emoji-toggle');
|
||||
const fileToggle = form.querySelector('#chat-file-toggle');
|
||||
@@ -2100,13 +2115,13 @@ export function render({ navigate, route, chrome }) {
|
||||
if (voiceBusy) mode = 'busy';
|
||||
else if (recording && voiceLocked) mode = 'stop';
|
||||
else if (recording) mode = 'voice';
|
||||
else if (activeEdit || String(input?.value || '').trim()) mode = 'send';
|
||||
else if (activeEdit || shared || String(input?.value || '').trim()) mode = 'send';
|
||||
|
||||
sendBtn.dataset.mode = mode;
|
||||
sendBtn.innerHTML = sendIconMarkup(mode);
|
||||
sendBtn.classList.toggle('is-recording', recording);
|
||||
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
|
||||
sendBtn.disabled = voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
|
||||
sendBtn.disabled = isShareSending() || voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
|
||||
if (mode === 'send') {
|
||||
sendBtn.title = t('screens.chat_view.text_029');
|
||||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029'));
|
||||
@@ -2347,6 +2362,7 @@ export function render({ navigate, route, chrome }) {
|
||||
};
|
||||
|
||||
const startEditMode = (msg) => {
|
||||
if (shared) return;
|
||||
const base = parseBaseKey(msg?.baseKey);
|
||||
if (!base || msg?.from !== 'out') return;
|
||||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||||
@@ -2371,6 +2387,7 @@ export function render({ navigate, route, chrome }) {
|
||||
};
|
||||
|
||||
const startReplyMode = (msg) => {
|
||||
if (shared) return;
|
||||
const base = parseBaseKey(msg?.baseKey);
|
||||
if (!base) return;
|
||||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||||
@@ -2493,6 +2510,7 @@ export function render({ navigate, route, chrome }) {
|
||||
text: finalText,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
if (shared && shareForChat(chatId) === shared) completeSharedDraft();
|
||||
markOutgoingSent(tempId, {
|
||||
messageKey: result?.outgoingKey || '',
|
||||
baseKey: result?.baseKey || result?.localBaseKey || '',
|
||||
@@ -2551,7 +2569,7 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
showToast(actionErrorText(activeEdit ? t('screens.chat_view.text_070') : t('screens.chat_view.text_071'), e), {
|
||||
kind: 'error',
|
||||
action: { label: t('screens.chat_view.text_033'), onClick: () => { if (!disposed) form.requestSubmit(); } },
|
||||
action: { label: t('screens.chat_view.text_033'), onClick: () => { if (!disposed && !isShareSending()) form.requestSubmit(); } },
|
||||
});
|
||||
addAppLogEntry({
|
||||
level: 'warn',
|
||||
@@ -2566,7 +2584,7 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
};
|
||||
|
||||
const sendFileAttachmentMessage = async (attachmentsInput) => {
|
||||
const sendFileAttachmentMessage = async (attachmentsInput, caption = '', onAccepted = null) => {
|
||||
const attachments = (Array.isArray(attachmentsInput) ? attachmentsInput : [attachmentsInput]).filter(Boolean);
|
||||
if (!attachments.length) return;
|
||||
if (attachments.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
|
||||
@@ -2581,7 +2599,7 @@ export function render({ navigate, route, chrome }) {
|
||||
: (attachments.length === 1
|
||||
? `📎 ${String(attachments[0]?.name || 'file')}`
|
||||
: t('screens.chat_view.text_097', { value1: attachments.length }));
|
||||
const finalText = `${replyBlock}${fileBlocks}${fallbackText}`;
|
||||
const finalText = `${replyBlock}${fileBlocks}${sanitizeUserDmTextForSend(String(caption || '').trim()) || fallbackText}`;
|
||||
|
||||
hideUnreadSeparator({ rerender: false });
|
||||
const tempId = addOutgoingPendingMessage(chatId, finalText);
|
||||
@@ -2595,6 +2613,7 @@ export function render({ navigate, route, chrome }) {
|
||||
text: finalText,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
onAccepted?.();
|
||||
markOutgoingSent(tempId, {
|
||||
messageKey: result?.outgoingKey || '',
|
||||
baseKey: result?.baseKey || result?.localBaseKey || '',
|
||||
@@ -2663,7 +2682,64 @@ export function render({ navigate, route, chrome }) {
|
||||
});
|
||||
};
|
||||
|
||||
function completeSharedDraft() {
|
||||
finishShare();
|
||||
shared = null;
|
||||
sharedBanner.hidden = true;
|
||||
input.value = '';
|
||||
input.readOnly = false;
|
||||
attachButtons.forEach(button => { button.disabled = false; });
|
||||
autoResizeComposer(input);
|
||||
syncComposerLayout();
|
||||
updateSendButtonMode();
|
||||
}
|
||||
|
||||
const sendSharedDraft = async (text) => {
|
||||
if (!shared || isShareSending()) return;
|
||||
const item = shared;
|
||||
const senderLogin = state.session.login;
|
||||
const senderSessionId = state.session.sessionId;
|
||||
const ensureSameSender = () => {
|
||||
if (!state.session.isAuthorized || senderLogin !== state.session.login || senderSessionId !== state.session.sessionId || shareForChat(chatId) !== item) throw new Error(t('remaining.share.error_session'));
|
||||
};
|
||||
if (item.files.length && !fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_054'), { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
item.text = text;
|
||||
setShareSending(true);
|
||||
input.readOnly = true;
|
||||
attachButtons.forEach(button => { button.disabled = true; });
|
||||
updateSendButtonMode();
|
||||
try {
|
||||
ensureSameSender();
|
||||
if (!item.files.length) {
|
||||
await sendTextMessage(text);
|
||||
} else {
|
||||
// Retry only the not-yet-uploaded files; keep the draft until the DM is accepted.
|
||||
item.uploaded ||= [];
|
||||
for (let index = item.uploaded.length; index < item.files.length; index += 1) {
|
||||
ensureSameSender();
|
||||
const file = item.files[index];
|
||||
showToast(t('screens.chat_view.text_102', { value1: index + 1, value2: item.files.length, value3: file.name }), { kind: 'info', timeoutMs: 1200 });
|
||||
const attachment = await encryptAndUploadDmFile({ file, login: state.session.login, sessionId: state.session.sessionId, wsUrl: authService.serverUrl });
|
||||
item.uploaded.push(attachment);
|
||||
}
|
||||
ensureSameSender();
|
||||
await sendFileAttachmentMessage(item.uploaded, text, () => { if (shareForChat(chatId) === item) completeSharedDraft(); });
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_080'), error), { kind: 'error' });
|
||||
} finally {
|
||||
setShareSending(false);
|
||||
input.readOnly = false;
|
||||
attachButtons.forEach(button => { button.disabled = Boolean(shared); });
|
||||
updateSendButtonMode();
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectedFiles = async (fileList) => {
|
||||
if (shared) return;
|
||||
if (!fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
|
||||
return;
|
||||
@@ -2908,10 +2984,15 @@ export function render({ navigate, route, chrome }) {
|
||||
cancelReplyMode({ restoreDraft: true });
|
||||
});
|
||||
|
||||
if (shared) {
|
||||
attachButtons.forEach(button => { button.disabled = true; });
|
||||
input.readOnly = isShareSending();
|
||||
}
|
||||
autoResizeComposer(input);
|
||||
syncComposerLayout();
|
||||
updateSendButtonMode();
|
||||
input?.addEventListener('input', () => {
|
||||
if (shared) shared.text = input.value;
|
||||
rememberEmojiSelection();
|
||||
autoResizeComposer(input);
|
||||
syncComposerLayout();
|
||||
@@ -3057,12 +3138,16 @@ export function render({ navigate, route, chrome }) {
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (!isDmSendEnter(event)) return;
|
||||
event.preventDefault();
|
||||
if (String(input.value || '').trim()) form.requestSubmit();
|
||||
if (shared?.files.length || String(input.value || '').trim()) form.requestSubmit();
|
||||
});
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const text = String(input.value || '').trim();
|
||||
if (shared) {
|
||||
if (text || shared.files.length) await sendSharedDraft(text);
|
||||
return;
|
||||
}
|
||||
if (!text) return;
|
||||
input.value = '';
|
||||
autoResizeComposer(input);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isShareChoosing, chooseShareRecipient } from '../services/share-flow.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
// «Новый чат»: выбрать, кому написать. Пока поле пустое – свои близкие и друзья; при вводе –
|
||||
// сначала свои (мгновенно, на устройстве), затем вся сеть (по имени и логину). Нажатие
|
||||
@@ -28,6 +29,7 @@ function displayName(person) {
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack dm-screen dm-search-screen';
|
||||
const sharing = isShareChoosing();
|
||||
let disposed = false;
|
||||
let searchTimer = 0;
|
||||
let searchSeq = 0;
|
||||
@@ -50,7 +52,12 @@ export function render({ navigate, chrome }) {
|
||||
const results = document.createElement('div');
|
||||
results.className = 'contact-search-results';
|
||||
|
||||
const openChat = (login) => navigate(`chat/${encodeURIComponent(normalizeDmChatId(login))}`);
|
||||
const openChat = (login) => {
|
||||
const chatId = normalizeDmChatId(login);
|
||||
const path = `chat/${encodeURIComponent(chatId).replace(/%40/gi, '@')}`;
|
||||
if (sharing) chooseShareRecipient(chatId, `/${path}`);
|
||||
navigate(path);
|
||||
};
|
||||
|
||||
function personRow(person, sub) {
|
||||
return createPersonRow({
|
||||
@@ -73,10 +80,10 @@ export function render({ navigate, chrome }) {
|
||||
const frag = document.createDocumentFragment();
|
||||
const ownMatches = mine.filter((person) => !query
|
||||
|| matchesPeopleQuery(`${displayName(person)} ${person.login} ${person.firstName} ${person.lastName}`, query));
|
||||
const ownShown = query ? ownMatches : ownMatches.filter((person) => person.relationFlag !== 'contact');
|
||||
const ownShown = query || sharing ? ownMatches : ownMatches.filter((person) => person.relationFlag !== 'contact');
|
||||
if (ownShown.length) {
|
||||
frag.append(createListSection(query ? t('screens.contact_search_view.text_015', { value1: ownShown.length }) : t('screens.contact_search_view.text_010')));
|
||||
ownShown.slice(0, query ? 50 : 40).forEach((person) => {
|
||||
ownShown.slice(0, sharing ? ownShown.length : (query ? 50 : 40)).forEach((person) => {
|
||||
const sub = [displayName(person) !== person.login ? `${person.login}` : '', RELATION_TEXT[person.relationFlag] || ''].filter(Boolean).join(' · ');
|
||||
frag.append(personRow(person, sub));
|
||||
});
|
||||
@@ -151,7 +158,7 @@ export function render({ navigate, chrome }) {
|
||||
for (const dialog of Array.isArray(payload?.dialogs) ? payload.dialogs : []) {
|
||||
const login = String(dialog?.peerLogin || '').trim();
|
||||
const relationFlag = String(dialog?.relationFlag || '').trim().toLowerCase();
|
||||
if (!login || !RELATION_TEXT[relationFlag] || byLogin.has(login.toLowerCase())) continue;
|
||||
if (!login || (!sharing && !RELATION_TEXT[relationFlag]) || byLogin.has(login.toLowerCase())) continue;
|
||||
byLogin.set(login.toLowerCase(), {
|
||||
login,
|
||||
relationFlag,
|
||||
@@ -160,7 +167,7 @@ export function render({ navigate, chrome }) {
|
||||
avatar: dialog?.avatar && typeof dialog.avatar === 'object' ? dialog.avatar : null,
|
||||
});
|
||||
}
|
||||
mine = [...byLogin.values()].sort((a, b) => (RELATION_ORDER[a.relationFlag] - RELATION_ORDER[b.relationFlag])
|
||||
mine = [...byLogin.values()].sort((a, b) => ((RELATION_ORDER[a.relationFlag] ?? 3) - (RELATION_ORDER[b.relationFlag] ?? 3))
|
||||
|| displayName(a).localeCompare(displayName(b), 'ru'));
|
||||
} catch {
|
||||
mine = [];
|
||||
@@ -169,7 +176,7 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: t('screens.contact_search_view.text_006'),
|
||||
title: sharing ? t('remaining.share.choose') : t('screens.contact_search_view.text_006'),
|
||||
back: { onClick: () => navigate('messages-list') },
|
||||
}));
|
||||
screen.append(field, results);
|
||||
|
||||
@@ -58,7 +58,6 @@ export function render({ navigate, chrome }) {
|
||||
card,
|
||||
login,
|
||||
tilesHtml: [
|
||||
profileTileHtml({ icon: 'channels', label: t('remaining.channels.my_publications'), attrs: 'data-self-profile-action="publications"' }),
|
||||
profileTileHtml({ icon: 'edit', label: t('screens.profile_view.text_007'), attrs: 'data-self-profile-action="edit"' }),
|
||||
profileTileHtml({ icon: 'wallet', label: t('screens.profile_view.text_008'), attrs: 'data-self-profile-action="wallet"' }),
|
||||
profileTileHtml({ icon: 'settings', label: t('screens.profile_view.text_009'), attrs: 'data-self-profile-action="settings"' }),
|
||||
@@ -84,7 +83,6 @@ export function render({ navigate, chrome }) {
|
||||
const actionButton = event.target.closest('[data-self-profile-action]');
|
||||
if (actionButton) {
|
||||
const action = actionButton.dataset.selfProfileAction;
|
||||
if (action === 'publications') navigate(`SHiNE/${encodeURIComponent(card.login)}/stories`);
|
||||
if (action === 'edit') navigate('profile-edit-view');
|
||||
if (action === 'wallet') navigate('wallet-view');
|
||||
if (action === 'settings') navigate('settings-view');
|
||||
|
||||
@@ -29,10 +29,10 @@ import {
|
||||
} from '../services/solana-register-service.js';
|
||||
import { defaultServerLogin } from '../deploy-config.js';
|
||||
import { getNamespace, normalizeFullLogin } from '../services/shine-namespace-service.js';
|
||||
import { calculateRegistrationFunding, USER_PDA_SPACE, solFromLamports } from '../services/registration-upgrade-helpers.js';
|
||||
import { calculateRegistrationFunding, USER_PDA_SPACE, solFromLamports, UPGRADE_TEST_TOPUP_SOL } from '../services/registration-upgrade-helpers.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-payment-view', get title() { return t('screens.registration_payment_view.text_001'); }, showAppChrome: false };
|
||||
const TEST_TOPUP_AMOUNT_SOL = 0.032;
|
||||
const TEST_TOPUP_AMOUNT_SOL = UPGRADE_TEST_TOPUP_SOL;
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
||||
@@ -758,7 +758,7 @@ function renderSolanaDoneStage({ navigate, status, keyBundle, registrationTxId =
|
||||
}, AUTO_LOGIN_INITIAL_DELAY_MS);
|
||||
}
|
||||
|
||||
/** Тот же тестовый источник +0.032 devnet SOL, что используется обычной регистрацией.
|
||||
/** Тот же тестовый источник +0.4 devnet SOL, что используется обычной регистрацией.
|
||||
* Экспорт добавлен для FREE_CERT → Solana upgrade; поведение обычной регистрации не изменяется.
|
||||
* Никогда не используйте этот встроенный devnet-кошелёк для реальных средств.
|
||||
*/
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { formatChannelAddress } from '../services/shine-routes.js';
|
||||
import { t, th } from '../i18n/index.js';
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
@@ -48,6 +49,7 @@ export function render({ navigate, route, chrome }) {
|
||||
let activeKind = initialKind;
|
||||
const isFriendsScreen = initialKind === 'friends' || initialKind === 'close_friends';
|
||||
const isChannelsScreen = initialKind === 'channels_owned' || initialKind === 'channels_following';
|
||||
const isOwnedChannels = initialKind === 'channels_owned';
|
||||
let includeDeleted = false;
|
||||
let disposed = false;
|
||||
let rows = [];
|
||||
@@ -59,10 +61,22 @@ export function render({ navigate, route, chrome }) {
|
||||
body.className = 'profile-list-body';
|
||||
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: TITLES[initialKind] || t('screens.user_profile_list_view.text_015'),
|
||||
title: isOwnedChannels ? t('remaining.share.user_channels') : TITLES[initialKind] || t('screens.user_profile_list_view.text_015'),
|
||||
back: { onClick: () => navigateBack() },
|
||||
}));
|
||||
|
||||
if (isOwnedChannels) {
|
||||
const owner = document.createElement('div');
|
||||
owner.className = 'stack';
|
||||
const name = document.createElement('b'); name.textContent = login;
|
||||
const address = document.createElement('small'); address.className = 'meta-muted';
|
||||
owner.append(name, address); screen.append(owner);
|
||||
void loadUserProfileCard(login).then(card => {
|
||||
if (disposed) return;
|
||||
name.textContent = userDisplayName(card);
|
||||
address.textContent = name.textContent === login ? '' : login;
|
||||
}).catch(() => {});
|
||||
}
|
||||
if (isFriendsScreen) {
|
||||
const tabs = document.createElement('div');
|
||||
tabs.className = 'tabs profile-list-kind';
|
||||
@@ -148,19 +162,23 @@ export function render({ navigate, route, chrome }) {
|
||||
const text = document.createElement('div');
|
||||
text.className = 'profile-list-row-text';
|
||||
const title = document.createElement('b');
|
||||
title.textContent = `${String(row.displayName || row.slug || '')}${row.deleted ? t('screens.user_profile_list_view.text_013') : ''}`;
|
||||
title.textContent = `${isOwnedChannels && Number(row.rootBlockNumber) === 0 ? t('remaining.share.user_publications') : String(row.displayName || row.slug || '')}${row.deleted ? t('screens.user_profile_list_view.text_013') : ''}`;
|
||||
const sub = document.createElement('small');
|
||||
sub.textContent = formatChannelAddress({ ownerLogin: row.ownerLogin, channelName: row.slug, channelRootBlockNumber: Number(row.rootBlockNumber) });
|
||||
text.append(title, sub);
|
||||
el.append(text);
|
||||
el.addEventListener('click', () => navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`));
|
||||
el.addEventListener('click', () => {
|
||||
// Virtual root rows do not carry a root hash in this API. Resolve by the reserved slug.
|
||||
if (Number(row.rootBlockNumber) === 0) { navigate(`SHiNE/${encodeURIComponent(row.ownerLogin)}/stories`); return; }
|
||||
navigate(`channel/${encodeURIComponent(row.ownerBlockchainName)}/${Number(row.rootBlockNumber || 0)}/${encodeURIComponent(row.rootBlockHashHex || '')}/about`);
|
||||
});
|
||||
return el;
|
||||
}
|
||||
|
||||
function renderRows() {
|
||||
body.replaceChildren();
|
||||
const matches = (row) => (isChannelsScreen
|
||||
? !query || searchText(`${row.displayName} ${row.slug} ${row.ownerLogin}`).includes(query)
|
||||
? !query || searchText(`${row.displayName} ${row.slug} ${row.ownerLogin} ${isOwnedChannels && Number(row.rootBlockNumber) === 0 ? t('remaining.share.user_publications') : ''}`).includes(query)
|
||||
: matchesPeopleQuery(`${userDisplayName(row)} ${row.login}`, query));
|
||||
const visible = rows.filter(matches);
|
||||
if (!rows.length) {
|
||||
@@ -185,6 +203,7 @@ export function render({ navigate, route, chrome }) {
|
||||
: await authService.listUserProfileRelations(login, kind, 200, 0);
|
||||
if (disposed || generation !== loadGeneration) return;
|
||||
rows = Array.isArray(isChannelsScreen ? payload?.channels : payload?.users) ? (isChannelsScreen ? payload.channels : payload.users) : [];
|
||||
if (isOwnedChannels) rows.sort((a, b) => Number(Number(b.rootBlockNumber) === 0) - Number(Number(a.rootBlockNumber) === 0));
|
||||
searchWrap.hidden = rows.length < SEARCH_FROM;
|
||||
renderRows();
|
||||
} catch (error) {
|
||||
|
||||
@@ -60,8 +60,11 @@ export function render({ navigate, route, chrome }) {
|
||||
login: requestedLogin,
|
||||
isSelf,
|
||||
tilesHtml: [
|
||||
profileTileHtml({ icon: 'channels', label: t('remaining.channels.publications'), attrs: 'data-profile-action="publications"' }),
|
||||
...(isSelf ? [] : [
|
||||
...(isSelf ? [
|
||||
profileTileHtml({ icon: 'edit', label: t('screens.profile_view.text_007'), attrs: 'data-profile-action="edit"' }),
|
||||
profileTileHtml({ icon: 'wallet', label: t('screens.profile_view.text_008'), attrs: 'data-profile-action="wallet"' }),
|
||||
profileTileHtml({ icon: 'settings', label: t('screens.profile_view.text_009'), attrs: 'data-profile-action="settings"' }),
|
||||
] : [
|
||||
profileTileHtml({ icon: 'user-plus', label: t('screens.user_profile_view.text_004'), attrs: 'data-profile-action="add"' }),
|
||||
profileTileHtml({ label: t('screens.user_profile_view.text_005'), attrs: 'data-profile-action="links"', iconMarkup: `<img class="pf-tile-mandala" src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true">` }),
|
||||
profileTileHtml({ icon: 'message', label: t('screens.user_profile_view.text_006'), attrs: 'data-profile-action="chat"' }),
|
||||
@@ -119,7 +122,9 @@ export function render({ navigate, route, chrome }) {
|
||||
|
||||
const actionButton = event.target.closest('[data-profile-action]');
|
||||
const action = actionButton?.dataset.profileAction;
|
||||
if (action === 'publications') { navigate(`SHiNE/${encodeURIComponent(card.login)}/stories`); return; }
|
||||
if (action === 'edit') { navigate('profile-edit-view'); return; }
|
||||
if (action === 'wallet') { navigate('wallet-view'); return; }
|
||||
if (action === 'settings') { navigate('settings-view'); return; }
|
||||
if (action === 'add') {
|
||||
navigate(`SHiNE/${encodeURIComponent(card.login)}/manage`);
|
||||
return;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { allowShareNavigation } from './services/share-flow.js';
|
||||
import { parseShineRouteParts } from './services/shine-routes.js';
|
||||
|
||||
let previousTrackedPath = '';
|
||||
@@ -509,6 +510,7 @@ export function navigate(path) {
|
||||
const cleanPath = toPrettyPath(path);
|
||||
const nextPath = cleanPath ? `/${cleanPath}` : '/';
|
||||
const fromPath = window.location.pathname;
|
||||
if (!allowShareNavigation(nextPath)) return;
|
||||
if (fromPath !== nextPath) {
|
||||
previousTrackedPath = currentTrackedPath;
|
||||
currentTrackedPath = nextPath;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { t } from '../i18n/index.js';
|
||||
export const USER_PDA_SPACE = 768; // shine-solana/shine/programs/shine_users/src/settings.rs
|
||||
// Запас для предварительной проверки баланса; сеть списывает фактическую комиссию.
|
||||
export const REGISTRATION_NETWORK_RESERVE_LAMPORTS = 100_000n;
|
||||
export const UPGRADE_TEST_TOPUP_SOL = 0.032;
|
||||
export const UPGRADE_TEST_TOPUP_SOL = 0.4;
|
||||
export const LAMPORTS_PER_SOL = 1_000_000_000;
|
||||
|
||||
export function calculateRegistrationFunding({ namespaceFeeLamports, rentLamports }) {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { readShare, deleteShare } from './share-inbox.js';
|
||||
const KEY = 'shine-share-pending-id';
|
||||
let pending = null;
|
||||
let activePath = '';
|
||||
let permittedPath = '';
|
||||
let owner = '';
|
||||
let sending = false;
|
||||
export const getPendingShare = () => pending;
|
||||
export const isShareSending = () => sending;
|
||||
export const setShareSending = value => { sending = Boolean(value); };
|
||||
export const isShareChoosing = () => Boolean(pending && activePath === '/contacts');
|
||||
export const shareForChat = chatId => pending && pending.recipient === chatId ? pending : null;
|
||||
export async function restoreShare() {
|
||||
const url = new URL(location.href);
|
||||
let id = url.searchParams.get('shine-share');
|
||||
try { id ||= sessionStorage.getItem(KEY); } catch { if (!id) return ''; }
|
||||
const error = url.searchParams.get('shine-share-error');
|
||||
if (url.searchParams.has('shine-share') || error) {
|
||||
url.searchParams.delete('shine-share'); url.searchParams.delete('shine-share-error');
|
||||
history.replaceState(history.state, '', url.pathname + url.search + url.hash);
|
||||
}
|
||||
if (error) { try { sessionStorage.removeItem(KEY); } catch {} return ['limit', 'empty', 'storage'].includes(error) ? error : 'storage'; }
|
||||
if (!id) return '';
|
||||
try {
|
||||
pending = await readShare(id);
|
||||
if (!pending) { sessionStorage.removeItem(KEY); return 'expired'; }
|
||||
try { sessionStorage.setItem(KEY, id); } catch {}
|
||||
return '';
|
||||
} catch { return 'storage'; }
|
||||
}
|
||||
export function activateShare(login) {
|
||||
if (!pending || activePath) return false;
|
||||
owner = String(login || '');
|
||||
activePath = '/contacts';
|
||||
permittedPath = '/contacts';
|
||||
return true;
|
||||
}
|
||||
export function chooseShareRecipient(chatId, path) {
|
||||
if (!isShareChoosing()) return;
|
||||
pending.recipient = chatId;
|
||||
permittedPath = path;
|
||||
}
|
||||
export function finishShare() {
|
||||
const id = pending?.id;
|
||||
pending = null; activePath = ''; permittedPath = ''; owner = ''; sending = false;
|
||||
try { sessionStorage.removeItem(KEY); } catch {}
|
||||
if (id) void deleteShare(id).catch(() => {});
|
||||
}
|
||||
export function checkShareOwner(login) {
|
||||
if (owner && owner !== String(login || '')) finishShare();
|
||||
}
|
||||
// All SPA navigation, including browser Back, goes through the same cancellation rule.
|
||||
export function allowShareNavigation(path) {
|
||||
if (!pending || !activePath || path === activePath) return true;
|
||||
if (path === permittedPath && !sending) { activePath = path; permittedPath = ''; return true; }
|
||||
if (sending) return false;
|
||||
if (!window.confirm(t('remaining.share.cancel_confirm'))) return false;
|
||||
finishShare();
|
||||
return true;
|
||||
}
|
||||
export function restoreSharePath() {
|
||||
if (activePath) history.pushState({ shineFrom: '/messages' }, '', activePath);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Shared by the service worker and the window. No content is sent over the network.
|
||||
const DB = 'shine-share-inbox-v1';
|
||||
const STORE = 'items';
|
||||
const TTL = 24 * 60 * 60 * 1000;
|
||||
export const MAX_SHARE_FILES = 10;
|
||||
export const MAX_SHARE_BYTES = 500 * 1024 * 1024;
|
||||
export function shareText({ title = '', text = '', url = '' } = {}) {
|
||||
const body = String(text).trim();
|
||||
const link = String(url).trim();
|
||||
const heading = String(title).trim();
|
||||
const result = [body, link && !body.includes(link) ? link : ''].filter(Boolean).join('\n');
|
||||
return [heading && !result.includes(heading) ? heading : '', result].filter(Boolean).join('\n');
|
||||
}
|
||||
function openDb() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB, 1);
|
||||
request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: 'id' });
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
async function transaction(mode, action) {
|
||||
const db = await openDb();
|
||||
try {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE, mode);
|
||||
let result;
|
||||
tx.oncomplete = () => resolve(result);
|
||||
tx.onabort = tx.onerror = () => reject(tx.error || new Error('share storage failed'));
|
||||
action(tx.objectStore(STORE), value => { result = value; });
|
||||
});
|
||||
} finally { db.close(); }
|
||||
}
|
||||
export function pruneShares(now = Date.now()) {
|
||||
return transaction('readwrite', store => {
|
||||
const cursor = store.openCursor();
|
||||
cursor.onsuccess = () => {
|
||||
const row = cursor.result;
|
||||
if (!row) return;
|
||||
if (row.value.createdAt < now - TTL) row.delete();
|
||||
row.continue();
|
||||
};
|
||||
});
|
||||
}
|
||||
export async function saveShare(form) {
|
||||
const files = form.getAll('files').filter(file => typeof file !== 'string' && (file.name || file.size));
|
||||
if (files.length > MAX_SHARE_FILES || files.reduce((total, file) => total + file.size, 0) > MAX_SHARE_BYTES) throw new Error('limit');
|
||||
const text = shareText({ title: form.get('title') || '', text: form.get('text') || '', url: form.get('url') || '' });
|
||||
if (!text && !files.length) throw new Error('empty');
|
||||
const id = crypto.randomUUID();
|
||||
await pruneShares();
|
||||
await transaction('readwrite', store => store.put({ id, text, files, createdAt: Date.now() }));
|
||||
return id;
|
||||
}
|
||||
export async function readShare(id) {
|
||||
await pruneShares();
|
||||
return transaction('readonly', (store, set) => {
|
||||
const req = store.get(id);
|
||||
req.onsuccess = () => set(req.result || null);
|
||||
});
|
||||
}
|
||||
export const deleteShare = id => transaction('readwrite', store => store.delete(id));
|
||||
@@ -29,5 +29,23 @@
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
]
|
||||
],
|
||||
"share_target": {
|
||||
"action": "/share-target",
|
||||
"method": "POST",
|
||||
"enctype": "multipart/form-data",
|
||||
"params": {
|
||||
"title": "title",
|
||||
"text": "text",
|
||||
"url": "url",
|
||||
"files": [
|
||||
{
|
||||
"name": "files",
|
||||
"accept": [
|
||||
"*/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,3 +219,6 @@
|
||||
.profile-consent-sheet .sheet__card { width: min(100%, 470px); }
|
||||
.profile-consent-flow .form-actions-grid { margin-top: 4px; }
|
||||
.profile-consent-flow .primary-btn:disabled { opacity: .45; cursor: not-allowed; }
|
||||
|
||||
.user-profile-screen .pf-stat--relations { gap: 2px; }
|
||||
.user-profile-screen .pf-stat-relation { display: flex; align-items: baseline; justify-content: center; gap: 5px; }
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import { shareText, MAX_SHARE_BYTES, MAX_SHARE_FILES } from '../js/services/share-inbox.js';
|
||||
import { UPGRADE_TEST_TOPUP_SOL } from '../js/services/registration-upgrade-helpers.js';
|
||||
import { profileCardHtml } from '../js/components/profile-card.js';
|
||||
const read = path => fs.readFileSync(new URL('../' + path, import.meta.url), 'utf8');
|
||||
|
||||
test('Android shares text, URL and any file through a local POST', () => {
|
||||
const target = JSON.parse(read('manifest.webmanifest')).share_target;
|
||||
assert.equal(target.action, '/share-target');
|
||||
assert.equal(target.method, 'POST');
|
||||
assert.equal(target.enctype, 'multipart/form-data');
|
||||
assert.deepEqual(target.params.files, [{ name: 'files', accept: ['*/*'] }]);
|
||||
assert.equal(shareText({title:'Example',text:'https://example.com',url:'https://example.com'}),'Example\nhttps://example.com');
|
||||
assert.equal(shareText({text:'note',url:'https://example.com'}),'note\nhttps://example.com');
|
||||
assert.equal(MAX_SHARE_FILES, 10);
|
||||
assert.equal(MAX_SHARE_BYTES, 500*1024*1024);
|
||||
});
|
||||
|
||||
test('worker consumes share POST and redirects to contact picker without network fetch', async () => {
|
||||
const events = {};
|
||||
let received;
|
||||
const source = read('firebase-messaging-sw.js').replace(/^import .*;\n/gm,'');
|
||||
vm.runInNewContext(source, { URL, Response, self:{registration:{scope:'https://t2.shineup.me/'},addEventListener:(name,fn)=>events[name]=fn},saveShare:async form=>{received=form; return 'local-id';} });
|
||||
const payload = new FormData(); payload.set('text','hello'); payload.append('files',new Blob(['abc']), 'file.txt');
|
||||
let response;
|
||||
events.fetch({request:{method:'POST',url:'https://t2.shineup.me/share-target',formData:async()=>payload},respondWith:p=>{response=p;}});
|
||||
const result=await response;
|
||||
assert.equal(received,payload);
|
||||
assert.equal(result.status,303);
|
||||
assert.equal(result.headers.get('location'),'https://t2.shineup.me/contacts?shine-share=local-id');
|
||||
response=null;
|
||||
events.fetch({request:{method:'GET',url:'https://t2.shineup.me/share-target'},respondWith:p=>{response=p;}});
|
||||
assert.equal(response,null);
|
||||
});
|
||||
|
||||
test('share flow allows recipient selection but asks before leaving, and blocks navigation during sending', async () => {
|
||||
const source = read('js/services/share-flow.js').replace(/^import .*;\n/gm,'').replace(/^export /gm,'');
|
||||
const deleted=[]; const store=new Map(); let confirm=false; let asks=0;
|
||||
const location=new URL('https://t2.shineup.me/contacts?shine-share=local-id');
|
||||
const history={replaceState(_,__,url){location.href=new URL(url,location).href;},pushState(_,__,url){location.href=new URL(url,location).href;}};
|
||||
const flow=vm.runInNewContext(source+'\n({restoreShare,activateShare,chooseShareRecipient,allowShareNavigation,shareForChat,setShareSending,getPendingShare,restoreSharePath})',{URL,location,history,sessionStorage:{getItem:k=>store.get(k),setItem:(k,v)=>store.set(k,v),removeItem:k=>store.delete(k)},readShare:async id=>({id,text:'test',files:[]}),deleteShare:async id=>deleted.push(id),t:k=>k,window:{confirm(){asks++;return confirm;}}});
|
||||
assert.equal(await flow.restoreShare(),''); assert.equal(location.search,'');
|
||||
assert.equal(flow.activateShare('alice'),true);
|
||||
assert.equal(flow.allowShareNavigation('/channels'),false); assert.equal(asks,1);
|
||||
flow.chooseShareRecipient('bob@free','/chat/bob@free'); assert.equal(flow.allowShareNavigation('/chat/bob@free'),true);
|
||||
assert.equal(flow.shareForChat('bob@free').text,'test');
|
||||
flow.setShareSending(true); assert.equal(flow.allowShareNavigation('/profile'),false); assert.equal(asks,1);
|
||||
flow.setShareSending(false); confirm=true; assert.equal(flow.allowShareNavigation('/profile'),true);
|
||||
assert.equal(flow.getPendingShare(),null); assert.deepEqual(deleted,['local-id']);
|
||||
});
|
||||
|
||||
test('profile has two equally styled friend counts and no standalone publications tile', () => {
|
||||
const html=profileCardHtml({card:{login:'test@free',stats:{friendsCount:12,closeFriendsCount:3}}});
|
||||
assert.match(html,/pf-stat-relation"><strong class="pf-stat-value">3<\/strong>/);
|
||||
assert.match(html,/pf-stat-relation"><strong class="pf-stat-value">12<\/strong>/);
|
||||
assert.doesNotMatch(read('js/pages/profile-view.js'),/data-self-profile-action="publications"/);
|
||||
assert.doesNotMatch(read('js/pages/user-profile-view.js'),/data-profile-action="publications"/);
|
||||
assert.match(read('js/pages/user-profile-list-view.js'),/remaining\.share\.user_publications/);
|
||||
});
|
||||
|
||||
test('both devnet topups use 0.4 SOL from a shared constant',()=>{
|
||||
assert.equal(UPGRADE_TEST_TOPUP_SOL,0.4);
|
||||
assert.match(read('js/pages/registration-payment-view.js'),/TEST_TOPUP_AMOUNT_SOL = UPGRADE_TEST_TOPUP_SOL/);
|
||||
assert.match(read('js/pages/registration-upgrade-view.js'),/UPGRADE_TEST_TOPUP_SOL/);
|
||||
});
|
||||
@@ -7,7 +7,7 @@ function setup(path) {
|
||||
const url = new URL(path, 'https://t2.shineup.me');
|
||||
const calls = [];
|
||||
const window = { location: url, history: { state: { shineFrom: '/messages' }, replaceState(state, _, value) { calls.push([state, value]); url.href = new URL(value, url).href; }, pushState(state, _, value) { url.href = new URL(value, url).href; } }, dispatchEvent() {} };
|
||||
const router = vm.runInNewContext(source + '\n({toPrettyPath,getRoute,navigate})', { window, PopStateEvent: class {}, parseShineRouteParts: () => null });
|
||||
const router = vm.runInNewContext(source + '\n({toPrettyPath,getRoute,navigate})', { window, PopStateEvent: class {}, parseShineRouteParts: () => null, allowShareNavigation: () => true });
|
||||
return { router, window, calls };
|
||||
}
|
||||
test('chat navigation keeps @ visible; other escapes unchanged', () => {
|
||||
|
||||
Reference in New Issue
Block a user