Files
dchain/client-app/app/(app)/compose.tsx
vsecoder 5b64ef2560 feat(client): Twitter-style social feed UI (Phase C of v2.0.0)
Ships the client side of the v2.0.0 feed feature. Folds client-app/
into the monorepo (was previously .gitignored as "tracked separately"
but no separate repo ever existed — for v2.0.0 the client is
first-class).

Feed screens

  app/(app)/feed.tsx — Feed tab
    - Three-way tab strip: Подписки / Для вас / В тренде backed by
      /feed/timeline, /feed/foryou, /feed/trending respectively
    - Default landing tab is "Для вас" — surfaces discovery without
      requiring the user to follow anyone first
    - FlatList with pull-to-refresh + viewability-driven view counter
      bump (posts visible ≥ 60% for ≥ 1s trigger POST /feed/post/…/view)
    - Floating blue compose button → /compose
    - Per-post liked_by_me fetched in batches of 6 after list load

  app/(app)/compose.tsx — post composer modal
    - Fullscreen, Twitter-like header (✕ left, Опубликовать right)
    - Auto-focused multiline TextInput, 4000 char cap
    - Hashtag preview chips that auto-update as you type
    - expo-image-picker + expo-image-manipulator pipeline: resize to
      1080px max-dim, JPEG Q=50 (client-side first-pass compression
      before the mandatory server-side scrub)
    - Live fee estimate + balance guard with a confirmation modal
      ("Опубликовать пост? Цена: 0.00X T · Размер: N KB")
    - Exif: false passed to ImagePicker as an extra privacy layer

  app/(app)/feed/[id].tsx — post detail
    - Full PostCard rendering + detailed info panel (views, likes,
      size, fee, hosting relay, hashtags as tappable chips)
    - Triggers bumpView on mount
    - 410 (on-chain soft-delete) routes back to the feed

  app/(app)/feed/tag/[tag].tsx — hashtag feed

  app/(app)/profile/[address].tsx — rebuilt
    - Twitter-ish profile: avatar, name, address short-form, post count
    - Posts | Инфо tab strip
    - Follow / Unfollow button for non-self profiles (optimistic UI)
    - Edit button on self profile → settings
    - Secondary actions (chat, copy address) when viewing a known contact

Supporting library

  lib/feed.ts — HTTP wrappers + tx builders for every /feed/* endpoint:
    - publishPost (POST /feed/publish, signed)
    - publishAndCommit (publish → on-chain CREATE_POST)
    - fetchPost / fetchStats / bumpView
    - fetchAuthorPosts / fetchTimeline / fetchForYou / fetchTrending /
      fetchHashtag
    - buildCreatePostTx / buildDeletePostTx
    - buildFollowTx / buildUnfollowTx
    - buildLikePostTx / buildUnlikePostTx
    - likePost / unlikePost / followUser / unfollowUser / deletePost
      (high-level helpers that bundle build + submitTx)
    - formatFee, formatRelativeTime, formatCount — Twitter-like display
      helpers

  components/feed/PostCard.tsx — core card component
    - Memoised for performance (N-row re-render on every like elsewhere
      would cost a lot otherwise)
    - Optimistic like toggle with heart-bounce spring animation
    - Hashtag highlighting in body text (tappable → hashtag feed)
    - Long-press context menu (Delete, owner-only)
    - Views / likes / share-link / reply icons in footer row

Navigation cleanup

  - NavBar: removed the SOON pill on the Feed tab (it's shipped now)
  - (app)/_layout: hide NavBar on /compose and /feed/* sub-routes
  - AnimatedSlot: treat /feed/<id>, /feed/tag/<t>, /compose as
    sub-routes so back-swipe-right closes them

Channel removal (client side)

  - lib/types.ts: ContactKind stripped to 'direct' | 'group'; legacy
    'channel' flag removed. `kind` field kept for backward compat with
    existing AsyncStorage records.
  - lib/devSeed.ts: dropped the 5 channel seed contacts.
  - components/ChatTile.tsx: removed channel kindIcon branch.

Dependencies

  - expo-image-manipulator added for client-side image compression.
  - expo-file-system/legacy used for readAsStringAsync (SDK 54 moved
    that API to the legacy sub-path; the new streaming API isn't yet
    stable).

Type check

  - npx tsc --noEmit — clean, 0 errors.

Next (not in this commit)

  - Direct attachment-bytes endpoint on the server so post-detail can
    actually render the image (currently shows placeholder with URL)
  - Cross-relay body fetch via /api/relays + hosting_relay pubkey
  - Mentions (@username) with notifications
  - Full-text search

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 19:43:55 +03:00

391 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Post composer — full-screen modal for writing a new post.
*
* Twitter-style layout:
* Header: [✕] (draft-ish) [Опубликовать button]
* Body: [avatar] [multiline TextInput autogrow]
* [hashtags preview chips]
* [attachment preview + remove button]
* Footer: [📷 attach] ··· [<count / 4000>] [~fee estimate]
*
* The flow:
* 1. User types content; hashtags auto-parse for preview
* 2. (Optional) pick image — client-side compression (expo-image-manipulator)
* → resize to 1080px max, JPEG quality 50
* 3. Tap "Опубликовать" → confirmation modal with fee
* 4. Confirm → publishAndCommit() → navigate to post detail
*
* Failure modes:
* - Size overflow (>256 KiB): blocked client-side with hint to compress
* further or drop attachment
* - Insufficient balance: show humanised error from submitTx
* - Network down: toast "нет связи, попробуйте снова"
*/
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
View, Text, TextInput, Pressable, Alert, Image, KeyboardAvoidingView,
Platform, ActivityIndicator, ScrollView, Linking,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { router } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import * as ImagePicker from 'expo-image-picker';
import * as ImageManipulator from 'expo-image-manipulator';
import * as FileSystem from 'expo-file-system/legacy';
import { useStore } from '@/lib/store';
import { Avatar } from '@/components/Avatar';
import { publishAndCommit, formatFee } from '@/lib/feed';
import { humanizeTxError, getBalance } from '@/lib/api';
const MAX_CONTENT_LENGTH = 4000;
const MAX_POST_BYTES = 256 * 1024; // must match server's MaxPostSize
const IMAGE_MAX_DIM = 1080;
const IMAGE_QUALITY = 0.5; // JPEG Q=50 — small, still readable
interface Attachment {
uri: string;
mime: string;
size: number;
bytes: Uint8Array;
width?: number;
height?: number;
}
export default function ComposeScreen() {
const insets = useSafeAreaInsets();
const keyFile = useStore(s => s.keyFile);
const username = useStore(s => s.username);
const [content, setContent] = useState('');
const [attach, setAttach] = useState<Attachment | null>(null);
const [busy, setBusy] = useState(false);
const [picking, setPicking] = useState(false);
const [balance, setBalance] = useState<number | null>(null);
// Fetch balance once so we can warn before publishing.
useEffect(() => {
if (!keyFile) return;
getBalance(keyFile.pub_key).then(setBalance).catch(() => setBalance(null));
}, [keyFile]);
// Estimated fee mirrors server's formula exactly. Displayed to the user
// so they aren't surprised by a debit.
const estimatedFee = useMemo(() => {
const size = (new TextEncoder().encode(content)).length + (attach?.size ?? 0) + 128;
return 1000 + size; // base 1000 + 1 µT/byte (matches blockchain constants)
}, [content, attach]);
const totalBytes = useMemo(() => {
return (new TextEncoder().encode(content)).length + (attach?.size ?? 0) + 128;
}, [content, attach]);
const hashtags = useMemo(() => {
const matches = content.match(/#[A-Za-z0-9_\u0400-\u04FF]{1,40}/g) || [];
const seen = new Set<string>();
return matches
.map(m => m.slice(1).toLowerCase())
.filter(t => !seen.has(t) && seen.add(t));
}, [content]);
const canPublish = !busy && (content.trim().length > 0 || attach !== null)
&& totalBytes <= MAX_POST_BYTES;
const onPickImage = async () => {
if (picking) return;
setPicking(true);
try {
const perm = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (!perm.granted) {
Alert.alert(
'Нужен доступ к фото',
'Откройте настройки и разрешите доступ к галерее.',
[
{ text: 'Отмена' },
{ text: 'Настройки', onPress: () => Linking.openSettings() },
],
);
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
quality: 1,
exif: false, // privacy: ask picker not to return EXIF
});
if (result.canceled || !result.assets[0]) return;
const asset = result.assets[0];
// Client-side compression: resize + re-encode. This is the FIRST
// scrub pass — server will do another one (mandatory) before storing.
const manipulated = await ImageManipulator.manipulateAsync(
asset.uri,
[{ resize: { width: IMAGE_MAX_DIM } }],
{ compress: IMAGE_QUALITY, format: ImageManipulator.SaveFormat.JPEG },
);
// Read the compressed bytes.
const b64 = await FileSystem.readAsStringAsync(manipulated.uri, {
encoding: FileSystem.EncodingType.Base64,
});
const bytes = base64ToBytes(b64);
if (bytes.length > MAX_POST_BYTES - 512) {
Alert.alert(
'Слишком большое',
`Картинка ${Math.round(bytes.length / 1024)} KB — лимит ${MAX_POST_BYTES / 1024} KB. Попробуйте выбрать поменьше.`,
);
return;
}
setAttach({
uri: manipulated.uri,
mime: 'image/jpeg',
size: bytes.length,
bytes,
width: manipulated.width,
height: manipulated.height,
});
} catch (e: any) {
Alert.alert('Не удалось', String(e?.message ?? e));
} finally {
setPicking(false);
}
};
const onPublish = async () => {
if (!keyFile || !canPublish) return;
// Balance guard.
if (balance !== null && balance < estimatedFee) {
Alert.alert(
'Недостаточно средств',
`Нужно ${formatFee(estimatedFee)}, на балансе ${formatFee(balance)}.`,
);
return;
}
Alert.alert(
'Опубликовать пост?',
`Цена: ${formatFee(estimatedFee)}\nРазмер: ${Math.round(totalBytes / 1024 * 10) / 10} KB`,
[
{ text: 'Отмена', style: 'cancel' },
{
text: 'Опубликовать',
onPress: async () => {
setBusy(true);
try {
const postID = await publishAndCommit({
author: keyFile.pub_key,
privKey: keyFile.priv_key,
content: content.trim(),
attachment: attach?.bytes,
attachmentMIME: attach?.mime,
});
// Close composer and open the new post.
router.replace(`/(app)/feed/${postID}` as never);
} catch (e: any) {
Alert.alert('Не удалось опубликовать', humanizeTxError(e));
} finally {
setBusy(false);
}
},
},
],
);
};
return (
<KeyboardAvoidingView
style={{ flex: 1, backgroundColor: '#000000' }}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
>
{/* Header */}
<View
style={{
paddingTop: insets.top + 8,
paddingBottom: 12,
paddingHorizontal: 14,
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: '#141414',
}}
>
<Pressable onPress={() => router.back()} hitSlop={8}>
<Ionicons name="close" size={26} color="#ffffff" />
</Pressable>
<View style={{ flex: 1 }} />
<Pressable
onPress={onPublish}
disabled={!canPublish}
style={({ pressed }) => ({
paddingHorizontal: 18, paddingVertical: 9,
borderRadius: 999,
backgroundColor: canPublish ? (pressed ? '#1a8cd8' : '#1d9bf0') : '#1f1f1f',
})}
>
{busy ? (
<ActivityIndicator color="#ffffff" size="small" />
) : (
<Text
style={{
color: canPublish ? '#ffffff' : '#5a5a5a',
fontWeight: '700',
fontSize: 14,
}}
>
Опубликовать
</Text>
)}
</Pressable>
</View>
<ScrollView
keyboardShouldPersistTaps="handled"
contentContainerStyle={{ paddingHorizontal: 14, paddingTop: 12, paddingBottom: 80 }}
>
{/* Avatar + TextInput row */}
<View style={{ flexDirection: 'row' }}>
<Avatar name={username ?? '?'} address={keyFile?.pub_key} size={40} />
<TextInput
value={content}
onChangeText={setContent}
placeholder="Что происходит?"
placeholderTextColor="#5a5a5a"
multiline
maxLength={MAX_CONTENT_LENGTH}
autoFocus
style={{
flex: 1,
marginLeft: 10,
color: '#ffffff',
fontSize: 17,
lineHeight: 22,
minHeight: 120,
paddingTop: 4,
textAlignVertical: 'top',
}}
/>
</View>
{/* Hashtag preview */}
{hashtags.length > 0 && (
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6, marginTop: 14, marginLeft: 50 }}>
{hashtags.map(tag => (
<View
key={tag}
style={{
paddingHorizontal: 10, paddingVertical: 4,
borderRadius: 999,
backgroundColor: '#081a2a',
borderWidth: 1, borderColor: '#11385a',
}}
>
<Text style={{ color: '#1d9bf0', fontSize: 12, fontWeight: '600' }}>
#{tag}
</Text>
</View>
))}
</View>
)}
{/* Attachment preview */}
{attach && (
<View style={{ marginTop: 14, marginLeft: 50 }}>
<View
style={{
position: 'relative',
borderRadius: 16,
overflow: 'hidden',
borderWidth: 1,
borderColor: '#1f1f1f',
}}
>
<Image
source={{ uri: attach.uri }}
style={{
width: '100%',
aspectRatio: attach.width && attach.height
? attach.width / attach.height
: 4 / 3,
backgroundColor: '#0a0a0a',
}}
resizeMode="cover"
/>
<Pressable
onPress={() => setAttach(null)}
hitSlop={8}
style={({ pressed }) => ({
position: 'absolute',
top: 8, right: 8,
width: 28, height: 28, borderRadius: 14,
backgroundColor: pressed ? 'rgba(0,0,0,0.9)' : 'rgba(0,0,0,0.75)',
alignItems: 'center', justifyContent: 'center',
})}
>
<Ionicons name="close" size={16} color="#ffffff" />
</Pressable>
</View>
<Text style={{ color: '#6a6a6a', fontSize: 11, marginTop: 6 }}>
{Math.round(attach.size / 1024)} KB · метаданные удалят на сервере
</Text>
</View>
)}
</ScrollView>
{/* Footer: attach / counter / fee */}
<View
style={{
paddingHorizontal: 14,
paddingVertical: 10,
paddingBottom: Math.max(insets.bottom, 10),
borderTopWidth: 1,
borderTopColor: '#141414',
flexDirection: 'row',
alignItems: 'center',
gap: 14,
}}
>
<Pressable
onPress={onPickImage}
disabled={picking || !!attach}
hitSlop={8}
style={({ pressed }) => ({
opacity: pressed || picking || attach ? 0.5 : 1,
})}
>
{picking
? <ActivityIndicator color="#1d9bf0" size="small" />
: <Ionicons name="image-outline" size={22} color="#1d9bf0" />}
</Pressable>
<View style={{ flex: 1 }} />
<Text
style={{
color: totalBytes > MAX_POST_BYTES ? '#f4212e'
: totalBytes > MAX_POST_BYTES * 0.85 ? '#f0b35a'
: '#6a6a6a',
fontSize: 12,
fontWeight: '600',
}}
>
{Math.round(totalBytes / 1024 * 10) / 10} / {MAX_POST_BYTES / 1024} KB
</Text>
<View style={{ width: 1, height: 14, backgroundColor: '#1f1f1f' }} />
<Text style={{ color: '#6a6a6a', fontSize: 12 }}>
{formatFee(estimatedFee)}
</Text>
</View>
</KeyboardAvoidingView>
);
}
// ── Helpers ────────────────────────────────────────────────────────────
function base64ToBytes(b64: string): Uint8Array {
const binary = atob(b64.replace(/-/g, '+').replace(/_/g, '/'));
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
return out;
}