Compare commits
4
Commits
c93fddc343
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71164657a1 | ||
|
|
af3eae56c8 | ||
|
|
a3ec5477e5 | ||
|
|
07a328245f |
+237
@@ -0,0 +1,237 @@
|
||||
import Wrapper from '@/components/ui/Wrapper';
|
||||
import { useFileSystem } from '@/hooks/useFilesystem';
|
||||
import { CoreBridge, PlaceholderBridge, RichText, TenTapStartKit, Toolbar, useEditorBridge, useEditorContent } from '@10play/tentap-editor';
|
||||
import { useRoute } from '@react-navigation/native';
|
||||
import { format } from 'date-fns';
|
||||
import { StorageAccessFramework } from 'expo-file-system';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { marked } from 'marked';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Keyboard, View } from 'react-native';
|
||||
import { Appbar, Button, Dialog, Menu, Portal, Text, useTheme } from 'react-native-paper';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import turndown from 'turndown-rn';
|
||||
|
||||
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);
|
||||
if (markdownContent == turndownService.turndown(loadedContents)) { console.log("Skipping..."); return; }
|
||||
|
||||
// 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;
|
||||
}
|
||||
`),
|
||||
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>
|
||||
);
|
||||
};
|
||||
+177
-47
@@ -1,37 +1,21 @@
|
||||
import { Image } from 'expo-image';
|
||||
import { Platform, StyleSheet, useColorScheme, View } from 'react-native';
|
||||
import { RefreshControl, StyleSheet, 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 { FAB, IconButton, List, Text, useTheme } from 'react-native-paper';
|
||||
import { useEffect, useState } from 'react';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { DATA_DIRECTORY_URI_KEY } from '@/constants/Settings';
|
||||
import { prettyName, useFileSystem } from '@/hooks/useFilesystem';
|
||||
import { format } from 'date-fns';
|
||||
import { StorageAccessFramework } from 'expo-file-system';
|
||||
import { useNavigation } from 'expo-router';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { FlatList } from 'react-native-gesture-handler';
|
||||
import Markdown from 'react-native-markdown-display';
|
||||
import { ActivityIndicator, FAB, Text, TouchableRipple, useTheme } from 'react-native-paper';
|
||||
import { SafeAreaView } from 'react-native-safe-area-context';
|
||||
|
||||
|
||||
export default function HomeScreen() {
|
||||
const [dataDirectoryUri, setDirectoryUri] = useState<string | null>(null);
|
||||
const navigation = useNavigation();
|
||||
useEffect(() => {
|
||||
const loadDirectoryUri = async () => {
|
||||
try {
|
||||
const savedUri = await AsyncStorage.getItem(DATA_DIRECTORY_URI_KEY);
|
||||
if (savedUri) {
|
||||
setDirectoryUri(savedUri);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading directory URI:', error);
|
||||
}
|
||||
};
|
||||
|
||||
loadDirectoryUri();
|
||||
}, []);
|
||||
|
||||
const theme = useTheme();
|
||||
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
fab: {
|
||||
position: 'absolute',
|
||||
@@ -40,23 +24,7 @@ export default function HomeScreen() {
|
||||
bottom: 0,
|
||||
backgroundColor: theme.colors.primary, // Use your theme's primary color
|
||||
},
|
||||
stepContainer: {
|
||||
gap: 8,
|
||||
marginBottom: 8,
|
||||
},
|
||||
headerImage: {
|
||||
width: 200,
|
||||
height: 200,
|
||||
bottom: 0,
|
||||
left: 20,
|
||||
position: 'absolute',
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
return (
|
||||
<ThemedView style={{ flex: 1, padding: 16 }}>
|
||||
<View style={{
|
||||
container: {
|
||||
backgroundColor: theme.colors.primary,
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
@@ -64,12 +32,174 @@ export default function HomeScreen() {
|
||||
right: 0,
|
||||
height: 100,
|
||||
zIndex: 1000,
|
||||
}} />
|
||||
<ThemedText>Directory: {dataDirectoryUri} </ThemedText>
|
||||
},
|
||||
safeArea: {
|
||||
flex: 1,
|
||||
marginTop: 100,
|
||||
backgroundColor: theme.colors.surface,
|
||||
// padding: 10
|
||||
},
|
||||
entryCard: {
|
||||
backgroundColor: theme.colors.surface,
|
||||
height: 150
|
||||
,
|
||||
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 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
|
||||
const content = await StorageAccessFramework.readAsStringAsync(fileUri);
|
||||
setLoadedContents(prev => new Map(prev).set(fileUri, content));
|
||||
} catch (error) {
|
||||
console.error('Error loading file content:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const onViewableItemsChanged = useCallback(({ viewableItems }: { viewableItems: ViewToken[] }) => {
|
||||
setLastViewableItems(viewableItems); // Track visible items
|
||||
viewableItems.forEach(({ item }) => {
|
||||
loadFileContent(item.uri);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const entryPreview = (fileUri: string) => {
|
||||
if (!loadedContents.has(fileUri)) return null;
|
||||
const preview = loadedContents.get(fileUri)?.slice(0, 200);
|
||||
if (!preview) return null; // No content to show
|
||||
const extra = loadedContents.get(fileUri)?.slice(200);
|
||||
if (!extra) return preview; // No extra content to show
|
||||
|
||||
const extraLength = extra.trim().split(/\s+/).filter(Boolean).length;
|
||||
return preview! + (extra ?
|
||||
` *[... ${extraLength} words]*`
|
||||
:
|
||||
'');
|
||||
};
|
||||
|
||||
const renderFileItem = ({ item: f }: { item: typeof files[0] }) => (
|
||||
<TouchableRipple key={f.uri} style={styles.entryCard}
|
||||
onPress={() => {
|
||||
navigation.navigate('Editor', {
|
||||
fileUri: f.uri, fileDatetime: f.datetime
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<View style={{
|
||||
width: '90%',
|
||||
height: '100%',
|
||||
paddingTop: 10,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.background,
|
||||
}}>
|
||||
<ThemedText style={{ fontWeight: "bold" }}>
|
||||
{format(f.datetime, "hh:mm aaa")}
|
||||
</ThemedText>
|
||||
{loadedContents.has(f.uri) && (
|
||||
<Markdown
|
||||
style={{
|
||||
body: {
|
||||
color: theme.colors.onSurface,
|
||||
fontSize: 13,
|
||||
marginTop: 10,
|
||||
},
|
||||
paragraph: {
|
||||
marginTop: 0,
|
||||
marginBottom: 10,
|
||||
},
|
||||
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,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{entryPreview(f.uri)
|
||||
||
|
||||
<ActivityIndicator />
|
||||
}
|
||||
</Markdown>
|
||||
)}
|
||||
</View>
|
||||
</TouchableRipple>
|
||||
);
|
||||
|
||||
return (
|
||||
<ThemedView style={{ flex: 1 }}>
|
||||
<View style={styles.container} />
|
||||
<SafeAreaView edges={['left', 'right']} style={styles.safeArea}>
|
||||
<FlatList
|
||||
data={files}
|
||||
renderItem={renderFileItem}
|
||||
keyExtractor={(item) => item.uri}
|
||||
onViewableItemsChanged={onViewableItemsChanged}
|
||||
viewabilityConfig={{ itemVisiblePercentThreshold: 50 }}
|
||||
refreshControl={
|
||||
<RefreshControl
|
||||
refreshing={refreshing}
|
||||
onRefresh={onRefresh}
|
||||
tintColor={theme.colors.primary}
|
||||
colors={[theme.colors.primary]}
|
||||
/>
|
||||
}
|
||||
ListHeaderComponent={
|
||||
<View style={{
|
||||
marginBottom: 16,
|
||||
backgroundColor: theme.colors.secondary,
|
||||
padding: 2,
|
||||
paddingLeft: 10
|
||||
}}>
|
||||
<Text style={{ color: theme.colors.surface, fontSize: 10 }}>
|
||||
<Text style={{ fontWeight: "bold" }}>
|
||||
{prettyName(dataDirectoryUri, { pathContext: 'full' })}:
|
||||
</Text>
|
||||
{' '}{files.length} {files.length == 1 ? "entry" : "entries"}, {directorySize} MB
|
||||
</Text>
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
<FAB icon="plus" color={theme.colors.onPrimary} style={styles.fab} onPress={() => {
|
||||
console.log('New entry pressed');
|
||||
navigation.navigate('NewEntry' as never);
|
||||
navigation.navigate('Editor' as never);
|
||||
}} />
|
||||
</SafeAreaView>
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { StyleSheet, ScrollView, View, TextInput, KeyboardAvoidingView, Platform, Keyboard } from 'react-native';
|
||||
import { Button, Text, useTheme, Appbar, IconButton, Chip, Surface } from 'react-native-paper';
|
||||
import { ThemedView } from '@/components/ThemedView';
|
||||
import { ThemedText } from '@/components/ThemedText';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import Wrapper from '@/components/ui/Wrapper';
|
||||
import { format } from 'date-fns';
|
||||
import { useEditor, EditorContent } 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 [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 inputRef = React.useRef<TextInput>(null) as React.RefObject<TextInput>;
|
||||
const editor = useEditor({
|
||||
enableCoreExtensions: true,
|
||||
onUpdate(props) {
|
||||
const newText = props.editor.getNativeText();
|
||||
setEntryText(newText);
|
||||
}, // Add these properties to improve compatibility
|
||||
|
||||
});
|
||||
|
||||
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();
|
||||
};
|
||||
}, []);
|
||||
|
||||
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}
|
||||
placeholder="Write something..."
|
||||
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,
|
||||
left: 0,
|
||||
right: 0,
|
||||
flexDirection: 'row',
|
||||
}}>
|
||||
<View
|
||||
pointerEvents='box-none'
|
||||
style={{
|
||||
borderColor: theme.colors.primary,
|
||||
borderWidth: 1,
|
||||
borderRadius: 24,
|
||||
margin: 5,
|
||||
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,
|
||||
},
|
||||
});
|
||||
+6
-48
@@ -6,67 +6,25 @@ import { Directory, Paths } from 'expo-file-system/next';
|
||||
import { StorageAccessFramework } from 'expo-file-system';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { DATA_DIRECTORY_URI_KEY } from '@/constants/Settings';
|
||||
import { useFileSystem, prettyName } from '@/hooks/useFilesystem';
|
||||
|
||||
|
||||
const prettyName = (uri: string | null) => {
|
||||
if (!uri) return null;
|
||||
const decodedUri = decodeURIComponent(uri);
|
||||
const match = decodedUri.match(/.*\/primary:(.+)/);
|
||||
|
||||
if (match) {
|
||||
return match[1];
|
||||
}
|
||||
|
||||
// Fallback to your original logic
|
||||
return uri.split('%3A').pop() || "Unknown";
|
||||
|
||||
}
|
||||
|
||||
export default function SettingsScreen() {
|
||||
const [directoryUri, setDirectoryUri] = useState<string | null>(null);
|
||||
// Load saved directory URI on component mount
|
||||
useEffect(() => {
|
||||
const loadDirectoryUri = async () => {
|
||||
try {
|
||||
const savedUri = await AsyncStorage.getItem(DATA_DIRECTORY_URI_KEY);
|
||||
if (savedUri) {
|
||||
setDirectoryUri(savedUri);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading directory URI:', error);
|
||||
}
|
||||
};
|
||||
|
||||
loadDirectoryUri();
|
||||
}, []);
|
||||
|
||||
// Save directory URI whenever it changes
|
||||
const saveDirectoryUri = async (uri: string | null) => {
|
||||
try {
|
||||
if (uri) {
|
||||
await AsyncStorage.setItem(DATA_DIRECTORY_URI_KEY, uri);
|
||||
} else {
|
||||
await AsyncStorage.removeItem(DATA_DIRECTORY_URI_KEY);
|
||||
}
|
||||
setDirectoryUri(uri);
|
||||
} catch (error) {
|
||||
console.error('Error saving directory URI:', error);
|
||||
}
|
||||
};
|
||||
const { dataDirectoryUri, isLoading, files, hasDirectory, saveDataDirectoryUri } = useFileSystem();
|
||||
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 16, backgroundColor: 'white' }}>
|
||||
<List.Section title="Data" style={{ backgroundColor: 'white', }} titleStyle={{ fontSize: 24, fontWeight: 'bold' }}>
|
||||
<List.Item
|
||||
left={props => <List.Icon {...props} icon="folder" />}
|
||||
title={prettyName(directoryUri) ?? "No directory selected. Tap to select."}
|
||||
title={prettyName(dataDirectoryUri) ?? "No directory selected. Tap to select."}
|
||||
right={props => <List.Icon {...props} icon="chevron-right" />}
|
||||
|
||||
onPress={async () => {
|
||||
try {
|
||||
const permissions = await StorageAccessFramework.requestDirectoryPermissionsAsync();
|
||||
if (permissions.granted) {
|
||||
await saveDirectoryUri(permissions.directoryUri);
|
||||
await saveDataDirectoryUri(permissions.directoryUri);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@@ -75,12 +33,12 @@ export default function SettingsScreen() {
|
||||
/>
|
||||
</List.Section>
|
||||
<Button title="Debug: List Files" onPress={async () => {
|
||||
if (!directoryUri) {
|
||||
if (!dataDirectoryUri) {
|
||||
console.warn("No directory set.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const dir = await StorageAccessFramework.readDirectoryAsync(directoryUri);
|
||||
const dir = await StorageAccessFramework.readDirectoryAsync(dataDirectoryUri);
|
||||
console.log("Directory contents:", dir.map((file, i) => prettyName(file)));
|
||||
} catch (error) {
|
||||
console.error("Error reading directory:", error);
|
||||
|
||||
+3
-3
@@ -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,
|
||||
}}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,81 @@
|
||||
import React, { Fragment, useEffect, useState } from 'react';
|
||||
import { View } from 'react-native';
|
||||
import { Divider } from 'react-native-paper';
|
||||
import { type Editor } from 'rn-text-editor';
|
||||
import MenuButton from './EditorMenuButton';
|
||||
interface EditorMenuProps {
|
||||
editor: Editor;
|
||||
}
|
||||
const EditorMenu = ({ editor }: EditorMenuProps) => {
|
||||
const [_, setForceUpdate] = useState(false);
|
||||
useEffect(() => {
|
||||
// force the ui to update when the editor updates
|
||||
editor.on('update', () => {
|
||||
setForceUpdate((prev) => !prev);
|
||||
});
|
||||
}, []);
|
||||
const actions = [
|
||||
{
|
||||
icon: 'format-bold',
|
||||
isActive: editor.isActive('bold'),
|
||||
disabled: !editor.commandManager.createCan().toggleBold(),
|
||||
onPress() {
|
||||
if (editor.commandManager.createCan().toggleBold()) {
|
||||
editor.commandManager
|
||||
.createChain(undefined, true)
|
||||
.toggleBold()
|
||||
.run();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
icon: 'format-italic',
|
||||
isActive: editor.isActive('italic'),
|
||||
disabled: !editor.commandManager.createCan().toggleItalic(),
|
||||
onPress() {
|
||||
if (editor.commandManager.createCan().toggleItalic()) {
|
||||
editor.commandManager
|
||||
.createChain(undefined, true)
|
||||
.toggleItalic()
|
||||
.run();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
icon: 'format-color-highlight',
|
||||
isActive: editor.isActive('highlight'),
|
||||
disabled: !editor.commandManager.createCan().toggleHighlight(),
|
||||
onPress() {
|
||||
if (editor.commandManager.createCan().toggleHighlight()) {
|
||||
editor.commandManager
|
||||
.createChain(undefined, true)
|
||||
.toggleHighlight()
|
||||
.run();
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<View style={{ flexDirection: 'row', justifyContent: "space-between" }}>
|
||||
<View style={{ flexDirection: "row", justifyContent: "flex-start", alignItems: "center", flex: 1 }}>
|
||||
{actions.map((action, index) => (
|
||||
<Fragment key={index}>
|
||||
<MenuButton
|
||||
key={action.icon}
|
||||
icon={action.icon}
|
||||
isActive={action.isActive}
|
||||
disabled={action.disabled}
|
||||
onPress={action.onPress}
|
||||
/>
|
||||
{index < actions.length - 1 && (
|
||||
<Divider />
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditorMenu;
|
||||
@@ -0,0 +1,16 @@
|
||||
import React from 'react';
|
||||
import { IconButton, type IconButtonProps } from 'react-native-paper';
|
||||
interface MenuButtonProps extends IconButtonProps {
|
||||
isActive?: boolean;
|
||||
}
|
||||
const MenuButton = ({ isActive, ...props }: MenuButtonProps) => {
|
||||
return (
|
||||
<IconButton
|
||||
size={18}
|
||||
mode={isActive ? 'contained' : 'outlined'}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default MenuButton;
|
||||
@@ -41,8 +41,8 @@ export function ThemedText({
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
default: {
|
||||
fontSize: 16,
|
||||
lineHeight: 24,
|
||||
fontSize: 12,
|
||||
lineHeight: 16,
|
||||
},
|
||||
defaultSemiBold: {
|
||||
fontSize: 16,
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ import { MD3LightTheme, MD3DarkTheme } from 'react-native-paper';
|
||||
const brandColors = {
|
||||
primary: '#35C4E5',
|
||||
primaryVariant: '#0051D5',
|
||||
secondary: '#34C759',
|
||||
secondary: '#278CA2',
|
||||
secondaryVariant: '#248A3D',
|
||||
background: '#F2F2F7',
|
||||
surface: '#FFFFFF',
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { DATA_DIRECTORY_URI_KEY } from '@/constants/Settings';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { format } from 'date-fns';
|
||||
import * as FileSystem from 'expo-file-system';
|
||||
import { StorageAccessFramework } from 'expo-file-system';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
interface FileEntry {
|
||||
name: string;
|
||||
uri: string;
|
||||
datetime: Date;
|
||||
size: number;
|
||||
}
|
||||
interface PrettyNameOptions {
|
||||
pathContext?: 'full' | 'short';
|
||||
}
|
||||
interface FileInfoWithSize {
|
||||
uri: string;
|
||||
exists: boolean;
|
||||
isDirectory: boolean | null;
|
||||
modificationTime: number | null;
|
||||
size: number;
|
||||
}
|
||||
|
||||
function datetimeFromFilename(filename: string): Date {
|
||||
const match = filename.match(/(\d+)-(\d+)-(\d+)-(\d+)-(\d+)-(\d+)\.md$/);
|
||||
if (match) {
|
||||
const [_, year, month, day, hour, minute, second] = match;
|
||||
return new Date(
|
||||
parseInt(year),
|
||||
parseInt(month) - 1,
|
||||
parseInt(day),
|
||||
parseInt(hour),
|
||||
parseInt(minute),
|
||||
parseInt(second)
|
||||
);
|
||||
}
|
||||
return new Date();
|
||||
}
|
||||
|
||||
export function prettyName(uri: string | null, options: PrettyNameOptions = {}) {
|
||||
if (!uri) return null;
|
||||
const { pathContext = 'short' } = options;
|
||||
|
||||
var returnString = "";
|
||||
if (pathContext === 'full') {
|
||||
returnString = "/";
|
||||
}
|
||||
|
||||
const decodedUri = decodeURIComponent(uri);
|
||||
const match = decodedUri.match(/.*\/primary:(.+)/);
|
||||
|
||||
if (match) {
|
||||
if (pathContext === 'short') {
|
||||
const filename = match[1].split('/').pop() || "Unknown";
|
||||
returnString = returnString.concat(filename);
|
||||
}
|
||||
else {
|
||||
returnString = returnString.concat(match[1]);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Fallback to your original logic
|
||||
returnString = returnString.concat(uri.split('%3A').pop() || "Unknown");
|
||||
}
|
||||
return returnString;
|
||||
}
|
||||
|
||||
export function useFileSystem() {
|
||||
const [dataDirectoryUri, setDataDirectoryUri] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [files, setFiles] = useState<FileEntry[]>([]);
|
||||
const [directorySize, setDirectorySize] = useState<number>(0);
|
||||
|
||||
// Load saved directory URI
|
||||
useEffect(() => {
|
||||
const loadDirectoryUri = async () => {
|
||||
try {
|
||||
const savedUri = await AsyncStorage.getItem(DATA_DIRECTORY_URI_KEY);
|
||||
if (savedUri) {
|
||||
setDataDirectoryUri(savedUri);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading directory URI:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadDirectoryUri();
|
||||
}, []);
|
||||
|
||||
// Load files when directory changes
|
||||
const loadFiles = useCallback(async () => {
|
||||
if (!dataDirectoryUri) return;
|
||||
|
||||
|
||||
try {
|
||||
const dirContents = await StorageAccessFramework.readDirectoryAsync(dataDirectoryUri);
|
||||
const markdownFiles = [];
|
||||
let totalSize = 0;
|
||||
|
||||
for (const fileName of dirContents.filter(name => name.endsWith('.md'))) {
|
||||
try {
|
||||
const fileInfo = await FileSystem.getInfoAsync(fileName) as FileInfoWithSize;
|
||||
const fileEntry = {
|
||||
name: prettyName(fileName) ?? "",
|
||||
uri: fileInfo.uri,
|
||||
datetime: datetimeFromFilename(fileName),
|
||||
size: fileInfo.size,
|
||||
};
|
||||
|
||||
markdownFiles.push(fileEntry);
|
||||
totalSize += fileEntry.size;
|
||||
} catch (error) {
|
||||
console.warn(`Error getting info for file ${fileName}:`, error);
|
||||
}
|
||||
}
|
||||
markdownFiles.sort((a, b) => b.datetime.getTime() - a.datetime.getTime()); // Sort by datetime descending
|
||||
setFiles(markdownFiles);
|
||||
setDirectorySize(Math.round((totalSize / 1024 / 1024) * 1000) / 1000); // Convert to MB
|
||||
} catch (error) {
|
||||
console.error('Error loading files:', error);
|
||||
}
|
||||
}, [dataDirectoryUri]);
|
||||
|
||||
useEffect(() => {
|
||||
loadFiles();
|
||||
}, [loadFiles]);
|
||||
|
||||
const writeFile = useCallback(async (fileUriOrDatetime: string, content: string) => {
|
||||
if (!dataDirectoryUri) throw new Error('No directory selected');
|
||||
const fileUriDatetime = new Date(parseInt(fileUriOrDatetime) * 1000);
|
||||
let fileUri = fileUriOrDatetime;
|
||||
if (parseInt(fileUriOrDatetime)) { // If it's a datetime in seconds
|
||||
const filename = format(fileUriDatetime, 'yyyy-MM-dd-HH-mm-ss');
|
||||
fileUri = await StorageAccessFramework.createFileAsync(
|
||||
dataDirectoryUri,
|
||||
`${filename}.md`,
|
||||
'text/markdown'
|
||||
);
|
||||
}
|
||||
// const fileUri = `${dataDirectoryUri}/${filename}`;
|
||||
await FileSystem.writeAsStringAsync(fileUri, content);
|
||||
await loadFiles(); // Refresh file list
|
||||
}, [dataDirectoryUri, loadFiles]);
|
||||
|
||||
const readFile = useCallback(async (filename: string): Promise<string> => {
|
||||
if (!dataDirectoryUri) throw new Error('No directory selected');
|
||||
|
||||
const fileUri = `${dataDirectoryUri}/${filename}`;
|
||||
return await FileSystem.readAsStringAsync(fileUri);
|
||||
}, [dataDirectoryUri]);
|
||||
|
||||
const deleteFile = useCallback(async (filename: string): Promise<void> => {
|
||||
return await FileSystem.deleteAsync(filename, { idempotent: true });
|
||||
}
|
||||
, []);
|
||||
|
||||
const saveDataDirectoryUri = useCallback(async (uri: string | null) => {
|
||||
try {
|
||||
if (uri) {
|
||||
await AsyncStorage.setItem(DATA_DIRECTORY_URI_KEY, uri);
|
||||
} else {
|
||||
await AsyncStorage.removeItem(DATA_DIRECTORY_URI_KEY);
|
||||
}
|
||||
setDataDirectoryUri(uri);
|
||||
// Refresh files when directory changes
|
||||
if (uri) {
|
||||
await loadFiles();
|
||||
} else {
|
||||
setFiles([]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating directory URI:', error);
|
||||
}
|
||||
}, [loadFiles]);
|
||||
|
||||
return {
|
||||
dataDirectoryUri,
|
||||
saveDataDirectoryUri,
|
||||
isLoading,
|
||||
files,
|
||||
writeFile,
|
||||
readFile,
|
||||
deleteFile,
|
||||
loadFiles,
|
||||
hasDirectory: !!dataDirectoryUri,
|
||||
directorySize,
|
||||
};
|
||||
}
|
||||
Generated
+898
-12
File diff suppressed because it is too large
Load Diff
+4
-1
@@ -11,6 +11,7 @@
|
||||
"lint": "expo lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@10play/tentap-editor": "0.7.0",
|
||||
"@expo/ngrok": "^4.1.3",
|
||||
"@expo/vector-icons": "^14.1.0",
|
||||
"@react-native-async-storage/async-storage": "2.1.2",
|
||||
@@ -21,6 +22,7 @@
|
||||
"@react-navigation/drawer": "^7.4.2",
|
||||
"@react-navigation/elements": "^2.3.8",
|
||||
"@react-navigation/native": "^7.1.6",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"date-fns": "^4.1.0",
|
||||
"expo": "~53.0.11",
|
||||
"expo-blur": "~14.1.5",
|
||||
@@ -44,6 +46,7 @@
|
||||
"react-native": "0.79.3",
|
||||
"react-native-edge-to-edge": "1.6.0",
|
||||
"react-native-gesture-handler": "~2.24.0",
|
||||
"react-native-markdown-display": "^7.0.2",
|
||||
"react-native-paper": "^5.14.5",
|
||||
"react-native-pell-rich-editor": "^1.9.0",
|
||||
"react-native-reanimated": "~3.17.4",
|
||||
@@ -53,7 +56,7 @@
|
||||
"react-native-web": "~0.20.0",
|
||||
"react-native-webview": "13.13.5",
|
||||
"rn-text-editor": "^0.2.0",
|
||||
"turndown": "^7.2.0"
|
||||
"turndown-rn": "^6.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.25.2",
|
||||
|
||||
Reference in New Issue
Block a user