feat(content): add rich content rendering with @mentions and vote segments
Some checks failed
Frontend CI / build-and-push-web (push) Failing after 8m30s
Frontend CI / ota-android (push) Successful in 10m43s
Frontend CI / build-android-apk (push) Successful in 1h24m38s

- Add PostContentRenderer component for rendering posts/comments with segments
- Add PostMentionInput component for @mention support in post/comment creation
- Add VoteSegmentData and vote segment type for unified post creation API
- Update post and comment services to support segments in API requests
- Fix auth service to clear tokens before login/register
- Improve database initialization with proper close/retry logic
- Add verification check before allowing post creation
- Add metro web shims for react-native-webrtc full package and requireNativeComponent
- Update build config with git hash based version numbers
This commit is contained in:
lafay
2026-04-23 22:29:58 +08:00
parent eb4e1c080d
commit b2c3d5e54e
23 changed files with 797 additions and 127 deletions

View File

@@ -0,0 +1,269 @@
/**
* PostMentionInput - 帖子内容输入框(支持 @提及)
* 复用关注列表加载逻辑
* 检测输入中的 @ 字符,弹出关注者列表供选择
*/
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
View,
TextInput,
FlatList,
TouchableOpacity,
StyleSheet,
Platform,
} from 'react-native';
import Text from '../common/Text';
import Avatar from '../common/Avatar';
import { useAppColors, spacing, fontSizes, borderRadius } from '../../theme';
import { useAuthStore } from '../../stores';
import { authService } from '../../services/auth';
import { MessageSegment, AtSegmentData } from '../../types';
interface MentionUser {
id: string;
nickname: string;
avatar: string | null;
}
interface PostMentionInputProps {
value: string;
onChangeText: (text: string) => void;
onSegmentsChange: (segments: MessageSegment[]) => void;
placeholder?: string;
maxLength?: number;
style?: any;
minHeight?: number;
}
const PostMentionInput: React.FC<PostMentionInputProps> = ({
value,
onChangeText,
onSegmentsChange,
placeholder = '说点什么...',
maxLength = 2000,
style,
minHeight = 100,
}) => {
const colors = useAppColors();
const currentUser = useAuthStore(s => s.currentUser);
const [followingUsers, setFollowingUsers] = useState<MentionUser[]>([]);
const [showMentions, setShowMentions] = useState(false);
const [mentionQuery, setMentionQuery] = useState('');
const [mentionStartIndex, setMentionStartIndex] = useState(-1);
const [loaded, setLoaded] = useState(false);
const inputRef = useRef<TextInput>(null);
useEffect(() => {
if (!loaded && currentUser?.id) {
loadFollowing();
setLoaded(true);
}
}, [currentUser?.id, loaded]);
const loadFollowing = async () => {
if (!currentUser?.id) return;
try {
const list = await authService.getFollowingList(currentUser.id, 1, 200);
setFollowingUsers(
list.map(u => ({
id: u.id,
nickname: u.nickname || u.username || '',
avatar: u.avatar || null,
}))
);
} catch (_) {
// ignore
}
};
const filteredUsers = followingUsers.filter(u =>
u.nickname.toLowerCase().includes(mentionQuery.toLowerCase())
);
const activeMentions = useRef(new Map<number, { endIndex: number; userId: string; nickname: string }>());
const segmentsRef = useRef<MessageSegment[]>([]);
const rebuildSegments = useCallback(
(text: string) => {
const mentions = activeMentions.current;
if (mentions.size === 0) {
onSegmentsChange(text.trim() ? [{ type: 'text', data: { text } }] : []);
return;
}
const segments: MessageSegment[] = [];
const sorted = Array.from(mentions.entries()).sort((a, b) => a[0] - b[0]);
let lastEnd = 0;
for (const [startIdx, mention] of sorted) {
if (startIdx > lastEnd) {
segments.push({ type: 'text', data: { text: text.slice(lastEnd, startIdx) } });
}
segments.push({
type: 'at',
data: { user_id: mention.userId, nickname: mention.nickname } as AtSegmentData,
});
lastEnd = mention.endIndex;
}
if (lastEnd < text.length) {
segments.push({ type: 'text', data: { text: text.slice(lastEnd) } });
}
onSegmentsChange(segments);
},
[onSegmentsChange]
);
const handleChangeText = useCallback(
(text: string) => {
onChangeText(text);
const cursorPos = text.length;
let atStart = -1;
for (let i = cursorPos - 1; i >= 0; i--) {
if (text[i] === '@') {
atStart = i;
break;
}
if (text[i] === ' ' || text[i] === '\n') {
break;
}
}
if (atStart >= 0) {
const query = text.slice(atStart + 1, cursorPos);
if (!query.includes(' ') && !query.includes('\n')) {
setMentionQuery(query);
setMentionStartIndex(atStart);
setShowMentions(true);
return;
}
}
setShowMentions(false);
rebuildSegments(text);
},
[onChangeText, rebuildSegments]
);
const handleSelectMention = useCallback(
(mentionUser: MentionUser) => {
if (mentionStartIndex < 0) return;
const before = value.slice(0, mentionStartIndex);
const mentionText = `@${mentionUser.nickname} `;
const newText = before + mentionText;
activeMentions.current.set(mentionStartIndex, {
endIndex: before.length + mentionText.length,
userId: mentionUser.id,
nickname: mentionUser.nickname,
});
onChangeText(newText);
setShowMentions(false);
setMentionQuery('');
setMentionStartIndex(-1);
rebuildSegments(newText);
inputRef.current?.focus();
},
[value, mentionStartIndex, onChangeText, rebuildSegments]
);
const renderMentionItem = ({ item }: { item: MentionUser }) => (
<TouchableOpacity
style={[styles.mentionItem, { borderBottomColor: colors.divider }]}
onPress={() => handleSelectMention(item)}
>
<Avatar source={item.avatar} size={32} name={item.nickname} />
<Text style={[styles.mentionName, { color: colors.text.primary }]}>
{item.nickname}
</Text>
</TouchableOpacity>
);
return (
<View style={style}>
<TextInput
ref={inputRef}
value={value}
onChangeText={handleChangeText}
placeholder={placeholder}
placeholderTextColor={colors.text.hint}
maxLength={maxLength}
multiline
style={[
styles.input,
{
color: colors.text.primary,
backgroundColor: colors.background.default,
},
]}
/>
{showMentions && filteredUsers.length > 0 && (
<View style={[styles.mentionPanel, { backgroundColor: colors.background.paper, borderColor: colors.divider }]}>
<FlatList
data={filteredUsers}
renderItem={renderMentionItem}
keyExtractor={item => item.id}
keyboardShouldPersistTaps="handled"
nestedScrollEnabled
style={styles.mentionList}
/>
</View>
)}
{showMentions && filteredUsers.length === 0 && (
<View style={[styles.mentionPanel, { backgroundColor: colors.background.paper, borderColor: colors.divider }]}>
<Text style={[styles.emptyText, { color: colors.text.hint }]}>
</Text>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
input: {
fontSize: fontSizes.md,
padding: spacing.sm,
borderRadius: borderRadius.md,
minHeight: 100,
textAlignVertical: 'top' as const,
},
mentionPanel: {
borderWidth: 1,
borderRadius: borderRadius.md,
maxHeight: 200,
marginTop: spacing.xs,
},
mentionList: {
maxHeight: 200,
},
mentionItem: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm,
borderBottomWidth: StyleSheet.hairlineWidth,
},
mentionName: {
fontSize: fontSizes.md,
marginLeft: spacing.sm,
},
emptyText: {
fontSize: fontSizes.sm,
padding: spacing.md,
textAlign: 'center',
},
});
export default PostMentionInput;