@aabdelmonaem/core-lib
v1.0.13
Published
A library providing essential functions for building web applications.
Downloads
77
Maintainers
Readme
core-lib
This README file provides an overview of the functions available in the Core-Lib library. Core-Lib is a Typescript library that offers essential functions for building web applications. Below, you will find descriptions of the following functions:
Table of Contents
1. useConfig
- Description: The useConfig function is designed to manage configuration settings in your web application. It allows you to access and modify various configuration options that can be used to customize the behavior of your application.
ConfigProvider Props
In the useConfig function, the following props are available for configuration:
1. isAuth (Boolean):
- Description: This prop determines whether the user is authenticated or not. It is used to conditionally load configuration settings based on the user's authentication status.
- Example Usage:
const isUserAuthenticated = auth.user !== null;
<ConfigProvider isAuth={isUserAuthenticated} ...otherProps />
2. configLocal (Object or Function):
Description: The configLocal prop represents a local configuration object or a function that returns a local configuration object. This local configuration can be used when the user is not authenticated (e.g., for default settings).
Example Usage:
const defaultConfig = { theme: 'light',language: 'en'};
<ConfigProvider configLocal={defaultConfig} ...otherProps />
3. configService (Function) (optional):
- Description: The
configService
prop is a function that retrieves configuration settings from an external service when the user is authenticated. It should return a Promise that resolves to the user-specific configuration object. - Example Usage:
const getConfigFromService = () => {
// Make an API call to fetch user-specific configuration
return ConfigService.getAllConfig()
};
<ConfigProvider configService={getConfigFromService} ...otherProps />
useConfig Usage
To get a configuration value by key:
const {getConfig} = useConfigContext()
{getConfig(key)}
To add or modify a configuration value at runtime:
const {addConfig} = useConfigContext()
addConfig(key, value)
2. useAuth
- Description: The useAuth function is a fundamental component for managing authentication and user-related functionalities in your web application. It provides methods for user authentication, role-based permissions, and user state management.
AuthProvider Props
In the AuthProvider component, you can configure the authentication provider with the following props:
1. localRoles (Object)
Description: localRoles represents local role definitions or permissions that are used for role-based access control (RBAC) within your application.
Example Usage:
<AuthProvider localRoles={localRoles} ...otherProps />
2. signinService (Function)
Description: signinService is a function responsible for handling user sign-in/authentication. It should return a Promise that resolves to the user object upon successful authentication or null if authentication fails.
Example Usage:
const handleSignIn = async (username, password) => {
// Perform authentication logic here and return the user object if successful
};
<AuthProvider signinService={handleSignIn} ...otherProps />
3. signoutService (Function)
Description: signoutService is a function that handles user sign-out or session termination.
Example Usage:
const handleSignOut = () => {
// Perform sign-out logic here
};
<AuthProvider signoutService={handleSignOut} ...otherProps />
4. onLogin (Function, optional)
- Description: onLogin is an optional callback function that is executed after a user successfully logs in. It can be used for additional actions or redirections upon login.
5. onLogout (Function, optional)
- Description: onLogout is an optional callback function that is executed after a user logs out. It can be used for additional actions upon logout. useAuth Usage
useAuth Usage
To interact with authentication-related functionalities, you can use the following hooks provided by useAuth:
1. useAuthContext
Description: useAuthContext is a hook that allows you to access the authentication context, including the user object, authentication functions, and role-based permission checks.
Example Usage:
const auth = useAuthContext();
// Access user properties, authentication functions, and role-based permissions
2. RequireAuth Component
Description: The RequireAuth component is used for conditional rendering based on user authentication and role-based permissions. It renders its children only if the user is authenticated and has the required permissions.
Example Usage:
<RequireAuth permissions={['admin', 'editor']}>
{/* Content visible to authenticated users with specified permissions */}
</RequireAuth>
3. PrivateControl Component
Description: The PrivateControl component is used for conditional rendering based on user authentication and role-based permissions. It renders its children only if the user is authenticated and has the required permissions, but unlike RequireAuth, it renders nothing if the conditions are not met.
Example Usage:
<PrivateControl permissions={['admin', 'editor']}>
{/* Content visible to authenticated users with specified permissions */}
</PrivateControl>
4. authHeader Function
Description: authHeader is a utility function for generating HTTP headers containing authentication information. It retrieves the user's access token from session storage and constructs the header.
Example Usage:
const headers = authHeader();
// Use the headers for authenticated API requests
3. useLanguage
- Description: The useLanguage module is designed to facilitate multi-language support in your web application. It provides functionality for language switching and translation management. Below, you will find details on how to configure and use this module.
Languages
You can define your supported languages in the languages object. Each language is represented by a key-value pair, where the key is a unique identifier for the language, and the value is its human-readable name.
- Example Usage:
export const languages = {
en: 'en',
ar: 'ar',
};
LanguageContext Props
In the LanguageContext, the following props are available for language management and translation:
1. lang (String | null)
- Description: lang represents the currently selected language. It is a string that corresponds to one of the language keys defined in the languages object.
2. defaultLang (String | null)
- Description: defaultLang is the default language used when the application loads or when the selected language is not explicitly set. It is also a string corresponding to one of the language keys defined in the languages object.
3. changeLanguage (Function)
- Description: changeLanguage is a function that allows you to change the currently selected language. It accepts a language key as a parameter and updates the lang prop accordingly.
4. isEnglish (Function)
- Description: isEnglish is a function that returns true if the currently selected language is English and false otherwise. It can be used for conditional rendering based on language.
5. t (Function)
- Description: t is a translation function that accepts a translation key as a parameter and returns the translated string. It uses the translation provided by the translator prop.
LanguageProvider Props
In the LanguageProvider component, you can configure the language provider with the following props:
1. translator (Function)
- Description: translator is a function responsible for translating text based on the provided translation key. It should return the translated string.
2. i18n (Object)
- Description: i18n is an object used for configuring internationalization settings, such as text direction (LTR or RTL). It is typically associated with internationalization libraries like i18next.
LanguageProvider Usage
To configure language settings and enable multi-language support, you can use the LanguageProvider component as follows:
<LanguageProvider translator={translateFunction} i18n={i18nConfig}>
{/* Your application components and content */}
</LanguageProvider>
Replace translateFunction with your actual translation function and i18nConfig with your internationalization configuration.
ToggleLanguage Component
The ToggleLanguage component provides a UI element for toggling between supported languages. It allows users to switch between languages by clicking on a button or flag icon.
<ToggleLanguage />
SelectLanguage Component
The SelectLanguage component provides a dropdown menu for selecting the preferred language from the list of supported languages. Users can choose their preferred language from the dropdown.
<SelectLanguage />
4. useTheme
- Description: The useTheme module provides the capability to manage and switch between different themes within your web application. Themes, such as "dark" and "light," can be configured and selected, allowing for a customized user experience. This module offers functionality to access the current theme, change themes, and determine whether the dark theme is currently active.
Themes
The themes object defines the supported themes in your application. Each theme is represented by a key-value pair, where the key serves as a unique identifier, and the value is a human-readable name or label.
export const themes = {
dark: "Dark",
light: "Light",
};
ThemeContext Props
The ThemeContext provides the following props for theme management:
1. theme (String | null)
Description: theme represents the currently selected theme. It is a string corresponding to one of the theme keys defined in the themes object.
2. changeTheme (Function)
Description: changeTheme is a function that enables you to change the active theme. It accepts a theme key as a parameter and updates the theme prop accordingly.
3. defaultTheme (String | null)
Description: defaultTheme is the default theme used when the application loads or when no specific theme is set. It is also a string corresponding to one of the theme keys defined in the themes object.
4. isDark (Function)
Description: isDark is a function that returns true if the currently selected theme is the dark theme and false otherwise. It can be used for conditional rendering based on the active theme.
ThemeProvider Props
In the ThemeProvider component, you can configure the theme provider with the following props:
1. children (ReactNode)
Description: children is a ReactNode that represents the child components within the ThemeProvider. This is where your application's content and components should be wrapped.
useThemeContext
The useThemeContext hook allows you to access the theme context, including the currently selected theme, theme-changing functionality, and theme-specific utility functions. It should be used within a component wrapped by the ThemeProvider.
ThemeProvider Usage
To configure theme settings and enable theme switching in your application, you can use the ThemeProvider component as follows:
<ThemeProvider>
{/* Your application components and content */}
</ThemeProvider>
ToggleTheme Component
The ToggleTheme component provides a UI element for toggling between supported themes. It allows users to switch between themes by clicking on a button or flag icon.
<ToggleTheme />
5. useDateTimeConverter
- Description: The useDateTimeConverter Provide utilities for converting between Date objects and formatted date/time strings, allowing for flexible handling of date and time data within React applications.
dateToString(date: Date | null, format: DateTimeFormat): string
Converts a Date object to a formatted date and time string according to the specified format.
date: The Date object to convert. If null, an empty string is returned. format: An object specifying the format for date and time components (e.g., { date: 'YYYY-MM-DD', time: 'HH:mm:ss' }). Returns: A string representing the formatted date and time.
stringToDate(dateTimeString: string, format: DateTimeFormat): Date | null
Parses a formatted date and time string and returns a corresponding Date object.
dateTimeString: The formatted date and time string to parse. format: An object specifying the format for date and time components (e.g., { date: 'YYYY-MM-DD', time: 'HH:mm:ss' }). Returns: A Date object representing the parsed date and time, or null if the input string is empty.
formatDate(date: Date, format: string): string
Formats the date portion of a Date object according to the specified format.
date: The Date object to format. format: A string specifying the format for the date components (e.g., 'YYYY-MM-DD'). Returns: A string representing the formatted date.
formatTime(date: Date, format: string): string
Formats the time portion of a Date object according to the specified format.
date: The Date object to format. format: A string specifying the format for the time components (e.g., 'HH:mm:ss'). Returns: A string representing the formatted time.
parseTime(timeString: string, format: string): Date | null
Parses a time string according to the specified format and constructs a Date object representing the time.
timeString: The time string to parse. format: A string specifying the format for the time components (e.g., 'HH:mm:ss'). Returns: A Date object representing the parsed time, or null if parsing fails.
parseDate(dateString: string, format: string): Date | null
Parses a date string according to the specified format and constructs a Date object representing the date.
dateString: The date string to parse. format: A string specifying the format for the date components (e.g., 'YYYY-MM-DD'). Returns: A Date object representing the parsed date, or null if parsing fails.
6. useModal
- Description: This hook provides utilities for managing modals within a React application. It includes components for rendering modal content and a context for controlling modal visibility.
ModalProvider
The ModalProvider component is used to manage the display of modals within the application. It should be placed at the root of your component tree to provide modal functionality throughout the application.
<ModalProvider>
{/* Your application content */}
</ModalProvider>
useModalContext
The useModalContext hook is used to manage modal context within functional components. It returns functions to show and hide modals.
const [showModal, hideModal] = useModalContext(() => (
<div role="dialog" className="modal">
<p>This is a modal window</p>
<button onClick={hideModal}>Close</button>
</div>
));
return (
<button onClick={showModal}>Show Modal</button>
);
7. useNotification
- Description: useNotification is a React hook that enables you to easily manage and display notifications within your React applications. It provides a flexible and customizable way to show various types of notifications to users.
NotificationProvider
The NotificationProvider component is used to manage the display of notification within the application. It should be placed at the root of your component tree to provide notification functionality throughout the application.
<NotificationProvider>
{/* Your application components */}
</NotificationProvider>
Configuration
The Notification Provider component allows you to customize various aspects of notifications, including:
- Position of notifications
- Duration of notifications
- Styling of notifications
- Default colors and icons for different notification variants You can pass a configuration object to the NotificationProvider component to customize these settings.
<NotificationProvider
config={
{
position: 'top-center',
isCloseable: false,
showTitle: true,
showIcon: true,
duration: 10,
animationDuration: 600,
}
}
>
<App />
</NotificationProvider>
useNotification
Use the useNotification hook to show notifications in your components
const notification = useNotification();
const handleShow = (variant) => {
notification.show({
message: 'This is a sample Notification content displayed',
variant,
});
};
<button className='button' onClick={() => handleShow('error')}>
Show Error
</button>
<button className='button' onClick={() => handleShow('success')}>
Show Success
</button>
<button className='button' onClick={() => handleShow('info')}>
Show Info
</button>