Work on Editor and HomeScreen

This commit is contained in:
2025-06-24 13:05:25 -07:00
parent a3ec5477e5
commit af3eae56c8
8 changed files with 624 additions and 330 deletions
+240
View File
@@ -0,0 +1,240 @@
import { format } from 'date-fns';
import { Appbar, Button, Dialog, Menu, Portal, Text, useTheme } from 'react-native-paper';
import { marked } from 'marked';
import turndown from 'turndown-rn';
import Wrapper from '@/components/ui/Wrapper';
import { CoreBridge, PlaceholderBridge, RichText, TenTapStartKit, Toolbar, useEditorBridge, useEditorContent } from '@10play/tentap-editor';
import { useRouter } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { Keyboard, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useRoute } from '@react-navigation/native';
import { StorageAccessFramework } from 'expo-file-system';
import { useFileSystem } from '@/hooks/useFilesystem';
export default function EditorScreen() {
const [entryText, setEntryText] = useState<string>('');
const [stats, setStats] = useState<{ words: number; characters: number }>({
words: 0,
characters: 0,
});
useEffect(() => {
const words = entryText.trim().split(/\s+/).filter(Boolean).length;
const characters = entryText.length;
setStats({ words, characters });
}
, [entryText]);
const navigation = useRouter();
const route = useRoute();
const { writeFile, deleteFile } = useFileSystem();
const { fileUri, fileDatetime } = route.params as { fileUri: string | undefined, fileDatetime: Date } || { fileUri: undefined, fileDatetime: new Date() };
const [loadedContents, setLoadedContents] = useState<string>("");
const [menuVisible, setMenuVisible] = useState<boolean>(false);
const [dialogVisible, setDialogVisible] = useState<boolean>(false);
const openMenu = () => { setMenuVisible(true); };
const closeMenu = () => { setMenuVisible(false); };
const openDialog = () => { setDialogVisible(true); };
const closeDialog = () => { setDialogVisible(false); };
const loadFileContent = async (fileUri: string, forceReload = false) => {
try {
// Replace with your actual file reading logic
const content = await StorageAccessFramework.readAsStringAsync(fileUri);
setLoadedContents(await marked.parse(content));
return (await marked.parse(content));
} catch (error) {
console.error('Error loading file content:', error);
}
};
const saveFileContent = async () => {
console.log("Begin Save");
// try{
// }
// catch (error) {
// console.error("Error creating file:", error);
// return;
// }
try {
if (!content.html) return;
// Convert HTML back to markdown
const turndownService = new turndown({
headingStyle: 'atx',
hr: '---',
bulletListMarker: '-',
codeBlockStyle: 'fenced',
fence: '```',
emDelimiter: '*',
strongDelimiter: '**',
linkStyle: 'inlined',
linkReferenceStyle: 'full',
});
// Optional: Add custom rules for better conversion
turndownService.addRule('strikethrough', {
filter: ['del', 's'],
replacement: (content: string) => `~~${content}~~`
});
turndownService.addRule('underline', {
filter: ['u', 'ins'],
replacement: (content: string) => `<u>${content}</u>`
});
const markdownContent = turndownService.turndown(content.html);
console.log(markdownContent);
// Save the markdown content
await writeFile(fileUri ?? format(fileDatetime, 't'), markdownContent);
console.log(`${fileDatetime} saved successfully`);
} catch (error) {
console.error(`Error saving ${fileUri}:`, error);
}
};
useEffect(() => {
if (fileUri) {
loadFileContent(fileUri);
}
}, [fileUri]);
useEffect(() => {
editor.setContent(loadedContents);
}, [loadedContents]);
const theme = useTheme();
const entryDate = format(fileDatetime, 'LLL d, h:mm aaa');
const insets = useSafeAreaInsets();
const [keyboardHeight, setKeyboardHeight] = useState(0);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
setKeyboardHeight(Keyboard.metrics()?.height || 0);
});
const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
setKeyboardHeight(0);
});
return () => {
keyboardDidShowListener.remove();
keyboardDidHideListener.remove();
};
}, []);
const editor = useEditorBridge({
autofocus: true,
avoidIosKeyboard: true,
theme: {
webviewContainer: {
paddingLeft: 15,
backgroundColor: theme.colors.surface,
},
},
bridgeExtensions: [
...TenTapStartKit,
CoreBridge.configureCSS(`
* {
font-size: 14px;
}
p {
margin: 0; padding: 0;
}
`),
PlaceholderBridge.configureExtension({
placeholder: '',
}),
],
initialContent: loadedContents,
});
const content = {
html: useEditorContent(editor, { type: 'html' }),
text: useEditorContent(editor, { type: 'text' }),
};
useEffect(() => {
content.text && setEntryText(content.text ?? 'Nothing loaded.');
}, [content]);
return (
<Wrapper>
<Appbar.Header style={{
backgroundColor: theme.colors.primary,
borderBottomWidth: 2,
borderBottomColor: theme.colors.backdrop,
}}>
{
content.text && content.text != loadedContents ?
<Appbar.Action icon="check" onPress={() => {
saveFileContent();
navigation.back();
}} />
:
<Appbar.BackAction onPress={() => {
navigation.back();
}} />
}
<Appbar.Content title={entryDate}
titleStyle={{
fontSize: 16, fontWeight: 'bold',
}}
/>
<Appbar.Action icon="calendar" onPress={() => { }} />
<Appbar.Action icon="tag" onPress={() => { }} />
<Menu
visible={menuVisible}
onDismiss={closeMenu}
anchor={<Appbar.Action icon="dots-vertical" onPress={() => {
openMenu();
}} />}>
<Menu.Item onPress={() => {
navigation.back();
closeMenu();
}} title="Cancel" />
<Menu.Item onPress={() => {
openDialog();
closeMenu();
}} title="Delete" />
</Menu>
</Appbar.Header>
<Portal>
<Dialog visible={dialogVisible} onDismiss={closeDialog}>
<Dialog.Title>Delete file?</Dialog.Title>
<Dialog.Content>
<Text>Entry for
{' '}
<Text style={{ fontWeight: 'bold' }}>
{format(fileDatetime, "MMM dd, yyyy, HH:mm:ss")}</Text> will be permanently deleted.</Text>
</Dialog.Content>
<Dialog.Actions>
<Button onPress={() => {
closeDialog()
}}>Cancel</Button>
<Button onPress={() => {
if (fileUri) { deleteFile(fileUri); }
navigation.back();
closeDialog()
}}>Done</Button>
</Dialog.Actions>
</Dialog>
</Portal>
{/* <SafeAreaView style={{ flex: 1, backgroundColor: theme.colors.background }}> */}
<RichText editor={editor} style={{ marginTop: 10, }} />
<View
// horizontal={true}
// keyboardShouldPersistTaps="always"
style={{
position: 'absolute',
bottom: keyboardHeight + insets.bottom,
left: 10,
right: 0,
flexDirection: 'row',
}}>
<Toolbar editor={editor} hidden={false} />
</View>
{/* </SafeAreaView> */}
</Wrapper>
);
};
+75 -26
View File
@@ -1,11 +1,11 @@
import { Image } from 'expo-image';
import { Platform, RefreshControl, ScrollView, StyleSheet, useColorScheme, View, ViewToken } from 'react-native';
import { Platform, Pressable, RefreshControl, ScrollView, StyleSheet, TouchableOpacity, useColorScheme, View, ViewToken } from 'react-native';
import { HelloWave } from '@/components/HelloWave';
import ParallaxScrollView from '@/components/ParallaxScrollView';
import { ThemedText } from '@/components/ThemedText';
import { ThemedView } from '@/components/ThemedView';
import { Card, FAB, IconButton, List, Surface, Text, useTheme } from 'react-native-paper';
import { ActivityIndicator, Card, FAB, IconButton, List, Surface, Text, TouchableRipple, useTheme } from 'react-native-paper';
import { useCallback, useEffect, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DATA_DIRECTORY_URI_KEY } from '@/constants/Settings';
@@ -15,19 +15,12 @@ import { useFileSystem, prettyName } from '@/hooks/useFilesystem';
import { format } from 'date-fns';
import { StorageAccessFramework } from 'expo-file-system';
import { FlatList } from 'react-native-gesture-handler';
import Markdown from 'react-native-markdown-display';
export default function HomeScreen() {
const navigation = useNavigation();
const theme = useTheme();
const { dataDirectoryUri, loadFiles, files, directorySize } = useFileSystem();
const [refreshing, setRefreshing] = useState(false);
const onRefresh = async () => {
setRefreshing(true);
await loadFiles();
setRefreshing(false);
};
const styles = StyleSheet.create({
fab: {
position: 'absolute',
@@ -58,10 +51,26 @@ export default function HomeScreen() {
alignItems: 'center',
},
});
const { dataDirectoryUri, loadFiles, files, directorySize } = useFileSystem();
const [refreshing, setRefreshing] = useState(false);
const [loadedContents, setLoadedContents] = useState<Map<string, string>>(new Map());
const [lastViewableItems, setLastViewableItems] = useState<ViewToken[]>([]);
const loadFileContent = async (fileUri: string) => {
if (loadedContents.has(fileUri)) return; // Already loaded
const onRefresh = async () => {
setRefreshing(true);
setLoadedContents(new Map()); // Clear cached content
await loadFiles();
// Reload content for currently visible items
lastViewableItems.forEach(({ item }) => {
loadFileContent(item.uri, true); // Force reload
});
setRefreshing(false);
};
const loadFileContent = async (fileUri: string, forceReload = false) => {
if (loadedContents.has(fileUri) && !forceReload) return; // Already loaded
try {
// Replace with your actual file reading logic
@@ -73,17 +82,21 @@ export default function HomeScreen() {
};
const onViewableItemsChanged = useCallback(({ viewableItems }: { viewableItems: ViewToken[] }) => {
setLastViewableItems(viewableItems); // Track visible items
viewableItems.forEach(({ item }) => {
loadFileContent(item.uri);
});
}, []);
const viewabilityConfig = {
itemVisiblePercentThreshold: 50, // Load when 50% visible
};
const renderFileItem = ({ item: f }: { item: typeof files[0] }) => (
<View key={f.uri} style={styles.entryCard}>
<TouchableRipple key={f.uri} style={styles.entryCard}
onPress={() => {
navigation.navigate('Editor', {
fileUri: f.uri, fileDatetime: f.datetime
},
);
}}
>
<View style={{
width: '90%',
height: '100%',
@@ -91,16 +104,52 @@ export default function HomeScreen() {
borderBottomWidth: 1,
borderBottomColor: theme.colors.background,
}}>
<ThemedText style={{ fontWeight: "bold", marginBottom: 4 }}>
<ThemedText style={{ fontWeight: "bold" }}>
{format(f.datetime, "hh:mm aaa")}
</ThemedText>
{loadedContents.has(f.uri) && (
<ThemedText numberOfLines={3}>
{loadedContents.get(f.uri)}
</ThemedText>
<Markdown
style={{
body: {
color: theme.colors.onSurface,
fontSize: 13,
marginTop: 10,
},
paragraph: {
marginTop: 0,
marginBottom: 0,
},
heading1: {
color: theme.colors.primary,
fontSize: 18,
fontWeight: 'bold',
},
heading2: {
color: theme.colors.primary,
fontSize: 16,
fontWeight: 'bold',
},
strong: {
fontWeight: 'bold',
color: theme.colors.onSurface,
},
em: {
fontStyle: 'italic',
},
code_inline: {
backgroundColor: theme.colors.surfaceVariant,
padding: 2,
borderRadius: 3,
},
}}
>
{loadedContents.get(f.uri) ||
<ActivityIndicator />
}
</Markdown>
)}
</View>
</View>
</TouchableRipple>
);
return (
@@ -112,7 +161,7 @@ export default function HomeScreen() {
renderItem={renderFileItem}
keyExtractor={(item) => item.uri}
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={viewabilityConfig}
viewabilityConfig={{ itemVisiblePercentThreshold: 50 }}
refreshControl={
<RefreshControl
refreshing={refreshing}
@@ -124,7 +173,7 @@ export default function HomeScreen() {
ListHeaderComponent={
<View style={{
marginBottom: 16,
backgroundColor: theme.colors.accent,
backgroundColor: theme.colors.secondary,
padding: 2,
paddingLeft: 10
}}>
@@ -138,7 +187,7 @@ export default function HomeScreen() {
}
/>
<FAB icon="plus" color={theme.colors.onPrimary} style={styles.fab} onPress={() => {
navigation.navigate('NewEntry' as never);
navigation.navigate('Editor' as never);
}} />
</SafeAreaView>
</ThemedView>
-276
View File
@@ -1,276 +0,0 @@
// import EditorMenu from '@/components/EditorMenu';
import { format } from 'date-fns';
// import { useRouter } from 'expo-router';
// import React, { useEffect, useState } from 'react';
// import { Keyboard, ScrollView, StyleSheet, TextInput } from 'react-native';
import { Appbar, useTheme } from 'react-native-paper';
// import { useSafeAreaInsets } from 'react-native-safe-area-context';
// import { EditorContent, useEditor } from 'rn-text-editor';
// export default function NewEntryScreen() {
// const navigation = useRouter();
// const theme = useTheme();
// const entryDate = format(new Date(), 'LLL d, h:mm aaa');
// const editor = useEditor({
// enableCoreExtensions: true,
// onUpdate(props) {
// const newText = props.editor.getNativeText();
// // setEntryText(newText);
// },
// });
// return (
// <Wrapper>
// <Appbar.Header style={{
// backgroundColor: theme.colors.primary,
// borderBottomWidth: 2,
// borderBottomColor: theme.colors.backdrop,
// }}>
// {
// stats['characters'] === 0 ?
// <Appbar.BackAction onPress={() => {
// navigation.back();
// }} />
// :
// <Appbar.Action icon="check" onPress={() => {
// navigation.back();
// }} />
// }
// <Appbar.Content title={entryDate}
// titleStyle={{
// fontSize: 16, fontWeight: 'bold',
// }}
// />
// <Appbar.Action icon="calendar" onPress={() => { }} />
// <Appbar.Action icon="tag" onPress={() => { }} />
// </Appbar.Header>
// <Text
// style={{
// fontSize: 10,
// backgroundColor: theme.colors.accent,
// color: theme.colors.onTertiary,
// paddingVertical: 2,
// textAlign: 'center',
// }}>
// {stats.words} words · {stats.characters} characters
// </Text>
// <EditorContent
// editor={editor}
// style={{
// paddingHorizontal: 15,
// }}
// inputRef={inputRef}
// autoFocus
// />
// {/*
// <TextInput
// ref={inputRef}
// style={{
// flex: 1,
// fontSize: 14,
// color: theme.colors.onSurface,
// backgroundColor: theme.colors.surface,
// padding: 10,
// textAlignVertical: 'top',
// }}
// cursorColor={theme.colors.primary}
// multiline
// autoFocus
// autoCapitalize='none'
// placeholder="Write your entry here..."
// value={entryText}
// onChangeText={setEntryText}
// /> */}
// <ScrollView
// horizontal={true}
// keyboardShouldPersistTaps="always"
// style={{
// position: 'absolute',
// bottom: keyboardHeight + insets.bottom + 10,
// left: 10,
// right: 0,
// flexDirection: 'row',
// }}>
// <EditorMenu editor={editor} />
// {/* <View
// pointerEvents='box-none'
// style={{
// borderColor: theme.colors.primary,
// borderWidth: 1,
// borderRadius: 24,
// flexDirection: 'row',
// alignItems: 'center',
// justifyContent: 'space-around',
// backgroundColor: theme.colors.surface,
// shadowColor: '#000',
// shadowOffset: {
// width: 0,
// height: 2,
// },
// shadowOpacity: 0.1,
// shadowRadius: 8,
// elevation: 4,
// }}>
// < IconButton
// icon="format-bold"
// size={24} accessible={false}
// onPress={() => {
// console.log('Bold button pressed'); inputRef.current?.focus();
// }}
// />
// <IconButton
// icon="format-italic"
// size={24}
// onPress={() => {
// console.log('Italic button pressed');
// }}
// />
// <IconButton
// icon="format-underline"
// size={24}
// onPress={() => {
// console.log('Underline button pressed');
// }}
// />
// </View> */}
// </ScrollView>
// </Wrapper >
// );
// }
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// justifyContent: 'center',
// paddingHorizontal: 1,
// },
// editorContainer: {
// paddingHorizontal: 5,
// flex: 1
// },
// box: {
// width: 60,
// height: 60,
// marginVertical: 20,
// },
// });
import Wrapper from '@/components/ui/Wrapper';
import { CoreBridge, RichText, TenTapStartKit, Toolbar, useEditorBridge, useEditorContent } from '@10play/tentap-editor';
import { useRouter } from 'expo-router';
import React, { useEffect, useState } from 'react';
import { Keyboard, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
export default function NewEntryScreen() {
const [entryText, setEntryText] = useState<string>('');
const [stats, setStats] = useState<{ words: number; characters: number }>({
words: 0,
characters: 0,
});
useEffect(() => {
const words = entryText.trim().split(/\s+/).filter(Boolean).length;
const characters = entryText.length;
setStats({ words, characters });
console.log('Entry text updated:', entryText);
}
, [entryText]);
const navigation = useRouter();
const theme = useTheme();
const entryDate = format(new Date(), 'LLL d, h:mm aaa');
const insets = useSafeAreaInsets();
const [keyboardHeight, setKeyboardHeight] = useState(0);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
setKeyboardHeight(Keyboard.metrics()?.height || 0);
});
const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
setKeyboardHeight(0);
});
return () => {
keyboardDidShowListener.remove();
keyboardDidHideListener.remove();
};
}, []);
const editor = useEditorBridge({
autofocus: true,
avoidIosKeyboard: true,
theme: {
webviewContainer: {
paddingLeft: 15,
backgroundColor: theme.colors.surface,
},
},
bridgeExtensions: [
...TenTapStartKit,
CoreBridge.configureCSS(`
* {
font-size: 12px;
}
`), // Custom font
],
});
const content = {
html: useEditorContent(editor, { type: 'html' }),
text: useEditorContent(editor, { type: 'text' }),
};
useEffect(() => {
content && setEntryText(content.text ?? '');
}, [content]);
return (
<Wrapper>
<Appbar.Header style={{
backgroundColor: theme.colors.primary,
borderBottomWidth: 2,
borderBottomColor: theme.colors.backdrop,
}}>
{
stats['characters'] === 0 ?
<Appbar.BackAction onPress={() => {
navigation.back();
}} />
:
<Appbar.Action icon="check" onPress={() => {
navigation.back();
}} />
}
<Appbar.Content title={entryDate}
titleStyle={{
fontSize: 16, fontWeight: 'bold',
}}
/>
<Appbar.Action icon="calendar" onPress={() => { }} />
<Appbar.Action icon="tag" onPress={() => { }} />
</Appbar.Header>
{/* <SafeAreaView style={{ flex: 1, backgroundColor: theme.colors.background }}> */}
<RichText editor={editor} />
<View
// horizontal={true}
// keyboardShouldPersistTaps="always"
style={{
position: 'absolute',
bottom: keyboardHeight + insets.bottom,
left: 10,
right: 0,
flexDirection: 'row',
}}>
<Toolbar editor={editor} hidden={false} />
</View>
{/* </SafeAreaView> */}
</Wrapper>
);
};
+3 -3
View File
@@ -14,7 +14,7 @@ import { IconSymbol } from '@/components/ui/IconSymbol';
import { TouchableOpacity, View } from 'react-native';
import NullComponent from '@/components/NullComponent';
import { useEffect } from 'react';
import NewEntryScreen from './NewEntry';
import EditorScreen from './Editor';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
// Import your tab screens directly
@@ -226,8 +226,8 @@ export default function RootLayout() {
})}
/>
<RootStack.Screen
name="NewEntry"
component={NewEntryScreen}
name="Editor"
component={EditorScreen}
options={{
headerShown: false,
}}