Move files to lib folder

This commit is contained in:
Maarten 2024-08-08 14:22:02 +02:00
parent d8d8ac35f8
commit cec664c8d0
26 changed files with 58 additions and 59 deletions

View file

@ -0,0 +1,148 @@
import React, { useEffect, useState } from 'react';
import {
TextInput,
TouchableOpacity,
StyleSheet,
} from 'react-native';
import Modal from "react-native-modal";
import { Colors } from '@/constants/Colors';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { useColorScheme } from '@/hooks/useColorScheme';
interface Field {
name: string;
title?: string;
placeholder: string;
defaultValue?: string;
}
interface EditModalProps {
title?: string;
visible: boolean;
onClose?: () => void;
onSave: (inputValues: Record<string, string>) => void;
fields: Field[];
}
const CustomModal: React.FC<EditModalProps> = ({ title, visible, onClose, onSave, fields }) => {
const colorScheme = useColorScheme() ?? 'light';
const [ inputValues, setInputValues ] = useState<Record<string, string>>( {} );
useEffect( () => {
const initialValues: Record<string, string> = {};
fields.forEach( field => {
if (field.defaultValue) {
initialValues[ field.name ] = field.defaultValue;
}
} );
setInputValues( initialValues );
}, [ fields ] );
const handleInputChange = (name: string, value: string) => {
setInputValues( { ...inputValues, [ name ]: value } );
};
const handleSave = () => {
onSave( inputValues );
if (onClose) onClose();
};
return (
<Modal isVisible={visible}>
<ThemedView style={{ ...styles.view, backgroundColor: Colors[ colorScheme ].background }}>
<ThemedText style={styles.text}>{title ? title : 'Pas je gegevens aan:'}</ThemedText>
{fields.map( (field, index) => (
<ThemedView key={index} style={styles.inputContainer}>
{field.title && <ThemedText style={styles.inputTitle}>{field.title}</ThemedText>}
<TextInput
style={styles.input}
placeholder={field.placeholder}
onChangeText={(text) => handleInputChange( field.name, text )}
value={inputValues[ field.name ] || ''}
/>
</ThemedView>
) )}
<ThemedView style={styles.buttonContainer}>
<TouchableOpacity onPress={onClose || ( () => {
} )}>
<ThemedText style={[ styles.textStyle, styles.buttonClose ]}>Annuleren</ThemedText>
</TouchableOpacity>
<TouchableOpacity style={styles.buttonSave} onPress={handleSave}>
<ThemedText style={styles.textStyle}>Opslaan</ThemedText>
</TouchableOpacity>
</ThemedView>
</ThemedView>
</Modal>
);
};
const styles = StyleSheet.create( {
view: {
margin: 25,
borderRadius: 10,
paddingTop: 30,
paddingBottom: 30,
paddingLeft: 35,
paddingRight: 35,
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
},
text: {
marginBottom: 15,
textAlign: 'center',
},
inputContainer: {
width: '100%',
marginBottom: 15,
},
inputTitle: {
fontSize: 16,
marginBottom: 5,
},
input: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
width: '100%',
paddingHorizontal: 10,
borderRadius: 5,
},
buttonContainer: {
marginTop: 20,
flexDirection: 'row',
justifyContent: 'space-between',
width: '100%',
},
buttonClose: {
color: Colors.red,
paddingTop: 8,
},
buttonSave: {
backgroundColor: Colors.tint,
borderRadius: 5,
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 40,
paddingRight: 40,
},
textStyle: {
color: 'white',
fontWeight: 'bold',
textAlign: 'center',
},
} );
export default CustomModal;

31
lib/components/List.tsx Normal file
View file

@ -0,0 +1,31 @@
import React from 'react';
import {ViewStyle} from 'react-native';
import {ThemedView} from '@/components/ThemedView';
interface ListProps {
data: any;
renderItem: Function;
viewStyle?: ViewStyle;
}
const CustomList: React.FC<ListProps> = ({ data, renderItem, viewStyle }) => {
const renderList = () => {
let list: any[] = [];
for (let i = 0; i < data.length; i++) {
const item = data[i];
list[i] = renderItem(item, i);
}
return list;
};
return (
<ThemedView style={viewStyle ? viewStyle : undefined}>
{renderList()}
</ThemedView>
);
};
export default CustomList;

View file

@ -0,0 +1,60 @@
import { Text, type TextProps, StyleSheet } from 'react-native';
import { useThemeColor } from '@/hooks/useThemeColor';
export type ThemedTextProps = TextProps & {
lightColor?: string;
darkColor?: string;
type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
};
export function ThemedText({
style,
lightColor,
darkColor,
type = 'default',
...rest
}: ThemedTextProps) {
const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text');
return (
<Text
style={[
{ color },
type === 'default' ? styles.default : undefined,
type === 'title' ? styles.title : undefined,
type === 'defaultSemiBold' ? styles.defaultSemiBold : undefined,
type === 'subtitle' ? styles.subtitle : undefined,
type === 'link' ? styles.link : undefined,
style,
]}
{...rest}
/>
);
}
const styles = StyleSheet.create({
default: {
fontSize: 16,
lineHeight: 24,
},
defaultSemiBold: {
fontSize: 16,
lineHeight: 24,
fontWeight: '600',
},
title: {
fontSize: 32,
fontWeight: 'bold',
lineHeight: 32,
},
subtitle: {
fontSize: 20,
fontWeight: 'bold',
},
link: {
lineHeight: 30,
fontSize: 16,
color: '#0a7ea4',
},
});

View file

@ -0,0 +1,14 @@
import { View, type ViewProps } from 'react-native';
import { useThemeColor } from '@/hooks/useThemeColor';
export type ThemedViewProps = ViewProps & {
lightColor?: string;
darkColor?: string;
};
export function ThemedView({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) {
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
}

View file

@ -0,0 +1,10 @@
import * as React from 'react';
import renderer from 'react-test-renderer';
import { ThemedText } from '../ThemedText';
it(`renders correctly`, () => {
const tree = renderer.create(<ThemedText>Snapshot test!</ThemedText>).toJSON();
expect(tree).toMatchSnapshot();
});

View file

@ -0,0 +1,24 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders correctly 1`] = `
<Text
style={
[
{
"color": "#11181C",
},
{
"fontSize": 16,
"lineHeight": 24,
},
undefined,
undefined,
undefined,
undefined,
undefined,
]
}
>
Snapshot test!
</Text>
`;

View file

@ -0,0 +1,9 @@
// You can (explore) the built-in icon families and icons on the web at https://icons.expo.fyi/
import Ionicons from '@expo/vector-icons/Ionicons';
import { type IconProps } from '@expo/vector-icons/build/createIconSet';
import { type ComponentProps } from 'react';
export function TabBarIcon({ style, ...rest }: IconProps<ComponentProps<typeof Ionicons>['name']>) {
return <Ionicons size={28} style={[style]} {...rest} />;
}

62
lib/constants/Colors.ts Normal file
View file

@ -0,0 +1,62 @@
/**
* Below are the colors that are used in the app. The colors are defined in the light and dark mode.
* There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc.
*/
const tintColorLight = '#76af2a';
const tintColorDark = '#76af2a';
export const Colors = {
// Base
tint: tintColorLight,
black: '#000',
white: '#fff',
red: '#ff0000',
light: {
// Main
text: '#11181C',
background: '#fff',
tint: tintColorLight,
// Icons
icon: '#687076',
tabIconDefault: '#11181C',
tabIconSelected: tintColorLight,
// Types
green: '#3c8840',
paper: '#0071ce',
packages: '#f36c21',
grey: '#64666a',
// Buttons
buttonBackground: '#f5f5f5',
// Border
borderColor: '#f2f2f2',
},
dark: {
// Main
text: '#ECEDEE',
background: '#151718',
tint: tintColorDark,
// Icons
icon: '#9BA1A6',
tabIconDefault: '#9BA1A6',
tabIconSelected: tintColorDark,
// Types
green: '#3c8840',
paper: '#0071ce',
packages: '#f36c21',
grey: '#64666a',
// Buttons
buttonBackground: '#f5f5f5',
// Border
borderColor: '#f2f2f2',
},
};

View file

@ -0,0 +1,31 @@
import {createContext, PropsWithChildren, useContext} from "react";
import {useStorageState} from '@/context/UseStorageState';
type TokenType = {
token: string | null;
setToken: (token: string | null) => void;
isLoading: boolean;
}
const TokenContext = createContext<TokenType>({
setToken: () => {
},
token: null,
isLoading: true,
});
export const useToken = () => useContext(TokenContext);
export function AppProvider({ children }: PropsWithChildren) {
const [[isLoading, token], setSession] = useStorageState('appToken');
const tokenContext: TokenType = {
token,
setToken: (token) => {
setSession(token);
},
isLoading,
};
return <TokenContext.Provider value={tokenContext}>{children}</TokenContext.Provider>;
}

View file

@ -0,0 +1,67 @@
import * as SecureStore from 'expo-secure-store';
import * as React from 'react';
import { Platform } from 'react-native';
type UseStateHook<T> = [[boolean, T | null], (value: T | null) => void];
function useAsyncState<T>(
initialValue: [boolean, T | null] = [true, null],
): UseStateHook<T> {
return React.useReducer(
(state: [boolean, T | null], action: T | null = null): [boolean, T | null] => [false, action],
initialValue
) as UseStateHook<T>;
}
export async function setStorageItemAsync(key: string, value: string | null) {
if (Platform.OS === 'web') {
try {
if (value === null) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, value);
}
} catch (e) {
console.error('Local storage is unavailable:', e);
}
} else {
if (value == null) {
await SecureStore.deleteItemAsync(key);
} else {
await SecureStore.setItemAsync(key, value);
}
}
}
export function useStorageState(key: string): UseStateHook<string> {
// Public
const [state, setState] = useAsyncState<string>();
// Get
React.useEffect(() => {
if (Platform.OS === 'web') {
try {
if (typeof localStorage !== 'undefined') {
setState(localStorage.getItem(key));
}
} catch (e) {
console.error('Local storage is unavailable:', e);
}
} else {
SecureStore.getItemAsync(key).then((value: string | null) => {
setState(value);
});
}
}, [key]);
// Set
const setValue = React.useCallback(
(value: string | null) => {
setState(value);
setStorageItemAsync(key, value);
},
[key]
);
return [state, setValue];
}

View file

@ -0,0 +1 @@
export { useColorScheme } from 'react-native';

View file

@ -0,0 +1,8 @@
// NOTE: The default React Native styling doesn't support server rendering.
// Server rendered styles should not change between the first render of the HTML
// and the first render on the client. Typically, web developers will use CSS media queries
// to render different styles on the client and server, these aren't directly supported in React Native
// but can be achieved using a styling library like Nativewind.
export function useColorScheme() {
return 'light';
}

View file

@ -0,0 +1,22 @@
/**
* Learn more about light and dark modes:
* https://docs.expo.dev/guides/color-schemes/
*/
import { useColorScheme } from 'react-native';
import { Colors } from '@/constants/Colors';
export function useThemeColor(
props: { light?: string; dark?: string },
colorName: keyof typeof Colors.light & keyof typeof Colors.dark
) {
const theme = useColorScheme() ?? 'light';
const colorFromProps = props[theme];
if (colorFromProps) {
return colorFromProps;
} else {
return Colors[theme][colorName];
}
}

47
lib/services/message.tsx Normal file
View file

@ -0,0 +1,47 @@
import Toast from 'react-native-toast-message';
export class Message {
/**
* Set success message
*
* @param message
*/
static success(message: string) {
Message.send('success', message);
}
/**
* Send error message
*
* @param message
*/
static error(message: string) {
Message.send('error', message);
}
/**
* Send info message
*
* @param message
*/
static info(message: string) {
Message.send('info', message);
}
/**
* Send message
*
* @param type
* @param message
*/
static send(type: string, message: string) {
Toast.show({
type: type,
text1: message,
position: 'bottom',
visibilityTime: 2000,
autoHide: true,
})
}
}

71
lib/services/request.tsx Normal file
View file

@ -0,0 +1,71 @@
import axios from 'axios';
const API_URL = 'https://kliko.maartenvr98.nl/api/v1/';
const CONFIG = {
timeout: 30000,
};
export class Request {
/**
* Send GET request to API
*
* @param url
* @param headers
* @returns {Promise<AxiosResponse<any>>}
*/
static get(url: string, headers = {}) {
return axios
.get(API_URL + url, {
...CONFIG,
...headers,
})
.then(response => response.data)
.catch(error => {
// Handle error
throw error;
});
}
/**
* Send POST request to API
*
* @param url
* @param body
* @param headers
* @returns {Promise<AxiosResponse<any>>}
*/
static post(url: string, body = {}, headers = {}) {
return axios
.post(API_URL + url, body, {
...CONFIG,
...headers,
})
.then(response => response.data)
.catch(error => {
// Handle error
throw error;
});
}
/**
* Send PUT request to API
*
* @param url
* @param body
* @param headers
* @returns {Promise<AxiosResponse<any>>}
*/
static put(url: string, body = {}, headers = {}) {
return axios
.put(API_URL + url, body, {
...CONFIG,
...headers,
})
.then(response => response.data)
.catch(error => {
// Handle error
throw error;
});
}
}

43
lib/store/dataStore.tsx Normal file
View file

@ -0,0 +1,43 @@
// dataStore.js
import { createSlice } from '@reduxjs/toolkit';
const dataStore = createSlice( {
name: 'data',
initialState: {
session: {
token: '',
name: '',
device: '',
address: {
id: 0,
zipcode: '',
houseNumber: '',
street: '',
city: '',
},
coordinates: {
latitude: '',
longitude: '',
},
},
reloadCalendar: true,
viewCategory: null,
},
reducers: {
setSession: (state, action) => {
state.session = action.payload;
},
setReloadCalendar: (state, action) => {
state.reloadCalendar = action.payload;
},
setViewCategory: (state, action) => {
state.viewCategory = action.payload;
},
},
} );
export const { setSession } = dataStore.actions;
export const { setReloadCalendar } = dataStore.actions;
export const { setViewCategory } = dataStore.actions;
export default dataStore.reducer;

8
lib/store/store.tsx Normal file
View file

@ -0,0 +1,8 @@
import { configureStore } from '@reduxjs/toolkit';
import dataReducer from './dataStore';
export const store = configureStore({
reducer: {
data: dataReducer,
},
});