Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Pagthon Project Guidelines
- ## Code Structure and Style Guidelines
- ### 1. TypeScript Type Definitions
- When writing or changing TypeScript code always follow these rules strictly:
- - Add explicit type definitions for:
- - Component props (use interfaces)
- - Function parameters
- - Function return types
- - Variable declarations
- - Avoid suggesting code with `any` type
- - Recommend type improvements when reviewing code that lacks proper typing
- **Preferred Pattern:**
- ```typescript jsx
- interface ComponentProps {
- item: ItemType;
- onAction: (item: ItemType) => void;
- }
- export function Component({
- item,
- onAction
- }: ComponentProps): ReactElement {
- // Implementation
- }
- ```
- ### 2. String Management
- When working with string literals:
- - Suggest extracting repeated strings into constants or enums
- - Use route path constants from the utils/routes.ts file
- - Recommend creating new constants for any string that appears multiple times
- **Preferred Pattern:**
- ```typescript jsx
- // Recommend this approach
- export const ROUTE_NAMES = {
- PROJECT_MODAL: (projectId: string) => `/modal/project/${projectId}`
- };
- // Usage
- router.replace({
- pathname: ROUTE_NAMES.PROJECT_MODAL(project.id),
- });
- ```
- ### 3. Internationalization (i18n)
- When working with user-facing strings:
- - **ALWAYS** use the `t` function from `@/localization/i18n.ts` for any string that will be displayed to the user
- - **NEVER** use raw string literals in UI components
- - If an appropriate translation key doesn't exist in `en.ts`, add a new one
- - Group related translation keys in appropriate sections in the locale files
- - Use the `StringKey` type to ensure type safety when using translation keys
- **Preferred Pattern:**
- ```typescript jsx
- // Import the t function
- import t from '@/localization/i18n';
- // Use t function for all user-facing strings
- <ThemedText>{t('not_set')}</ThemedText>
- <Button
- title={t('save')}
- onPress={handleSave}/>
- <TextInput placeholder={t('notes_placeholder')}/>
- // For strings with variables, use the options parameter
- <ThemedText>{t('greeting', {name: userName})}</ThemedText>
- ```
- **Adding New Translation Keys:**
- When a needed translation key doesn't exist:
- 1. Add the key to the appropriate section in `src/localization/locales/en.ts`
- 2. Use descriptive, lowercase keys with underscores for spaces
- 3. Ensure the key is exported through the `StringKey` type
- ```typescript jsx
- // In en.ts
- const buttons = {
- save: "Save",
- cancel: "Cancel",
- new_key: "New Button Text", // Add your new key here
- }
- // In your component
- <Button title={t('new_key')} onPress={handleAction} />
- ```
- **Incorrect Patterns to Avoid:**
- ```typescript jsx
- // DON'T do this - using raw strings
- <ThemedText>Not set</ThemedText>
- <Button
- title="Save"
- onPress={handleSave}/>
- // DON'T do this - concatenating strings
- <ThemedText>{t('greeting') + ' ' + userName}</ThemedText>
- // DON'T do this - using string literals for placeholders
- <TextInput placeholder="Enter your name..."/>
- ```
- ### 4. Code Nesting and Function Responsibility
- When suggesting code structure:
- - Keep nesting levels to a minimum (no more than 2-3 levels deep)
- - Recommend early returns to reduce nesting
- - Suggest guard clauses to simplify complex conditionals
- - Propose component composition instead of deeply nested JSX
- - Keep functions small and focused on a single responsibility
- - Extract complex logic into helper functions with descriptive names
- - Separate concerns: detection/validation logic should be separate from creation/transformation logic
- **Preferred Patterns:**
- Early returns:
- ```typescript jsx
- if (!project) {
- return <ErrorComponent message="Project not found"/>;
- }
- // Main component logic with less nesting
- ```
- Guard clauses:
- ```typescript jsx
- const handleAction = () => {
- if (!isValid) return;
- // Main function logic without nesting
- };
- ```
- Extracting complex logic:
- ```typescript jsx
- // DON'T do this - complex nested logic in one function
- function processData(data) {
- const results = [];
- data.forEach(item => {
- if (item.isActive) {
- if (item.value > 10) {
- results.push({
- id: item.id,
- processedValue: item.value * 2,
- formattedLabel: `Item ${item.id}: ${item.value * 2}`,
- timestamp: Date.now()
- });
- }
- }
- });
- return results;
- }
- // DO this instead - extract complex logic into helper functions
- function processData(data) {
- return data
- .filter(isActiveItemWithHighValue)
- .map(createProcessedItem);
- }
- function isActiveItemWithHighValue(item) {
- return item.isActive && item.value > 10;
- }
- function createProcessedItem(item) {
- const processedValue = item.value * 2;
- return {
- id: item.id,
- processedValue,
- formattedLabel: formatItemLabel(item.id, processedValue),
- timestamp: Date.now()
- };
- }
- function formatItemLabel(id,
- value) {
- return `Item ${id}: ${value}`;
- }
- ```
- ### 5. Component Structure
- When helping with component organization:
- - Suggest breaking down large components (>200 lines) into smaller ones
- - Recommend extracting complex logic into helper functions
- - Propose custom hooks for reusable stateful logic
- - Follow the project's component structure patterns
- ### 6. Styling Approach
- When assisting with component styling:
- - Place style definitions in the same file as the component
- - Create a getStyle function that accepts ThemeColors
- - Use `useThemedStyle(getStyle)` to get the style in your component
- - Ensure the style variable is named `styles` consistently
- **Preferred Pattern:**
- ```typescript jsx
- export function MyComponent() {
- const themeColors = useThemeColorScheme();
- const styles = useThemedStyle(getStyle);
- return (<View style={styles.container}>
- {/* Component content */}
- < /View>);
- }
- const getStyle = (colors: ThemeColors) => {
- const styles = StyleSheet.create({
- container: {
- backgroundColor: colors.background,
- // Other styles
- },
- });
- return styles;
- };
- ```
- ### 7. React Native Best Practices
- When suggesting React Native code:
- - Recommend `Pressable` instead of `TouchableOpacity` for interactive elements
- - Suggest performance optimizations like memoization where appropriate
- - Follow platform-specific guidelines when applicable
- ### 8. Patterns to use
- #### 8.1 Optional function call
- When working with optional functions like callbacks use the optional chaining operator (`?.`) rather than a single line
- if block.
- ````typescript
- // Do NOT do this:
- if (onAction) {
- onAction();
- }
- // Instead do this:
- onAction?.();
- ````
- #### 8.2 Colors
- When working with colors in the application:
- - NEVER use string literals as colors (e.g., 'red', '#FF0000', 'rgba(255,0,0,1)') directly in components or styles
- - NEVER use fallback colors with the OR operator (e.g., `colors.error || 'red'`)
- - ALWAYS use the theme colors from the ThemeColors interface
- - Use `useThemeColors` to access colors in components
- - Use `useThemedStyle(getStyle)` to access colors in stylesheets
- - If a color you need doesn't exist in the ThemeColors interface:
- 1. Add the new color property to the ThemeColors interface in Colors.ts with appropriate documentation
- 2. Add appropriate color values for BOTH light and dark themes
- 3. Use the new color property in your component
- **Correct Pattern:**
- ```typescript jsx
- // In Colors.ts
- export type ThemeColors = {
- // Existing colors...
- /**
- * Color for error messages and indicators
- */
- error: ColorString,
- }
- const lightTheme = {
- // Existing colors...
- error: '#D32F2F',
- }
- const darkTheme = {
- // Existing colors...
- error: '#FF6B6B',
- }
- // In your component
- const getStyle = (colors: ThemeColors) => {
- const styles = StyleSheet.create({
- errorText: {
- color: colors.error,
- },
- });
- return styles;
- };
- ```
- **Incorrect Patterns to Avoid:**
- ```typescript jsx
- // DON'T do this - using string literals
- const styles = StyleSheet.create({
- errorText: {
- color: 'red',
- },
- });
- // DON'T do this - using fallbacks
- const getStyle = (colors: ThemeColors) => {
- const styles = StyleSheet.create({
- errorText: {
- color: colors.error || 'red',
- },
- });
- return styles;
- };
- ```
- ### 9. React Performance Optimization
- When writing React components, use memoization techniques to prevent unnecessary re-renders and optimize performance:
- #### 9.1 Using `useCallback`
- Always use `useCallback` for:
- - Event handlers passed to child components
- - Functions used as dependencies in other hooks
- - Callback functions passed as props to memoized components
- **Preferred Pattern:**
- ```typescript jsx
- // Always wrap event handlers with useCallback
- const handleSubmit = useCallback((data: FormData) => {
- dispatch(submitForm(data));
- }, [dispatch]);
- // Always wrap functions passed as props
- const handleItemSelect = useCallback((item: Item) => {
- setSelectedItem(item);
- }, [setSelectedItem]);
- // Always wrap functions used in dependency arrays
- const fetchData = useCallback(async () => {
- const response = await api.getData();
- setData(response);
- }, [api]);
- useEffect(() => {
- fetchData();
- }, [fetchData]); // fetchData is stable between renders
- ```
- #### 9.2 Using `useMemo`
- Always use `useMemo` for:
- - Expensive calculations or transformations
- - Derived data that depends on props or state
- - Objects or arrays that are used as dependencies in other hooks
- - Complex JSX structures that don't need to re-render often
- **Preferred Pattern:**
- ```typescript jsx
- // Memoize expensive calculations
- const sortedItems = useMemo(() => {
- return items.slice()
- .sort((a,
- b) => a.name.localeCompare(b.name));
- }, [items]);
- // Memoize derived data
- const filteredUsers = useMemo(() => {
- return users.filter(user => user.status === 'active');
- }, [users]);
- // Memoize objects used in dependency arrays
- const options = useMemo(() => ({
- threshold: 0.5,
- rootMargin: '0px',
- }), []); // Empty dependency array for static objects
- useEffect(() => {
- const observer = new IntersectionObserver(callback, options);
- // ...
- }, [callback, options]); // options is stable between renders
- // Memoize complex JSX structures
- const renderHeader = useMemo(() => (
- <Header
- title={title}
- subtitle={subtitle}
- actions={headerActions}
- />
- ), [title, subtitle, headerActions]);
- ```
- #### 9.3 Component Memoization
- Use React.memo for components that:
- - Receive the same props frequently
- - Are expensive to render
- - Don't need to re-render when parent re-renders
- **Preferred Pattern:**
- ```typescript jsx
- // Define component with proper typing
- interface ItemProps {
- item: Item;
- onSelect: (item: Item) => void;
- }
- // Memoize component to prevent unnecessary re-renders
- const ItemComponent = React.memo(({
- item,
- onSelect
- }: ItemProps) => {
- return (
- <Pressable onPress={() => onSelect(item)}>
- <Text>{item.name}</Text>
- </Pressable>
- );
- });
- ```
- #### 9.4 Memoization Best Practices
- When implementing memoization:
- - Include all dependencies in the dependency array
- - Don't overuse memoization for simple calculations or components
- - Use dependency arrays correctly to avoid stale closures
- - Consider using the React DevTools Profiler to identify unnecessary re-renders
- - Ensure memoized functions have stable dependencies
- **Example of Proper Dependency Management:**
- ```typescript jsx
- // Component with proper memoization
- export function OptimizedComponent({
- items,
- onItemSelect
- }) {
- const [filter, setFilter] = useState('');
- // Memoize filtered items
- const filteredItems = useMemo(() => {
- return items.filter(item => item.name.includes(filter));
- }, [items, filter]);
- // Memoize item selection handler
- const handleSelect = useCallback((item) => {
- onItemSelect(item);
- }, [onItemSelect]);
- // Memoize render function for list items
- const renderItem = useCallback(({item}) => (
- <ItemComponent
- item={item}
- onSelect={handleSelect}
- />
- ), [handleSelect]);
- return (
- <FlatList
- data={filteredItems}
- renderItem={renderItem}
- keyExtractor={item => item.id}
- />
- );
- }
- ```
- ## Documentation and Comment Guidelines
- ### 1. Comment Philosophy
- When writing, reviewing, or changing code follow these rules exactly:
- - **NEVER ADD INLINE COMMENTS DESCRIBING WHAT THE CODE DOES** - This is a strict rule with no exceptions
- - **NEVER** write trivial comments that merely restate what the function or variable name already clearly indicates
- - **NEVER** add comments like "// Handle navigation actions" or "// Dispatch Redux action" that add no value
- - Function and variable names should be self-explanatory, making such comments redundant
- - Prioritize self-explanatory code over excessive comments
- - Focus comments on explaining "why" rather than "how" or "what"
- - Suggest removing redundant comments that merely restate the code
- - Recommend updating comments when code changes
- **Examples of Trivial Comments to Avoid:**
- ```typescript jsx
- // Reset form
- const resetForm = () => {
- setTitle('');
- setDescription('');
- setActions([]);
- };
- // Update user name
- function updateUserName(name) {
- user.name = name;
- }
- // Check if user is admin
- const isAdmin = user.role === 'admin';
- // state for input form
- const [feedbackType, setFeedbackType] = useState<'suggestion' | 'bug' | 'other'>('suggestion');
- const [feedbackText, setFeedbackText] = useState('');
- const [submitted, setSubmitted] = useState(false);
- ```
- These comments add no value as the function and variable names already clearly describe what the code does.
- ### 2. Appropriate Comment Usage
- Suggest comments only for:
- - Non-obvious implementations or workarounds
- - Complex business logic explanations
- - Temporary solutions (with TODO markers)
- **Good Comment Examples:**
- ```typescript jsx
- // This is a workaround for React Native bug #1234
- const adjustedValue = value + 1;
- // TODO: Replace with API call when backend is ready
- const mockData = [];
- ```
- ### 3. Code Clarity Over Comments
- When reviewing code with explanatory comments:
- - Suggest refactoring the code to be self-explanatory
- - Recommend extracting complex expressions into named variables
- - Propose function extraction for commented blocks of code
- **Example Transformation:**
- ```typescript jsx
- // From:
- // Check if all actions are completed
- const isCompleted = actions.length > 0 && actions.every(a => a.isCompleted);
- // To:
- const hasActions = actions.length > 0;
- const allActionsCompleted = actions.every(action => action.isCompleted);
- const isCompleted = hasActions && allActionsCompleted;
- ```
- ### 4. Documentation Structure
- When helping with code documentation:
- - Suggest JSDoc comments for file-level documentation
- - Recommend documenting interfaces and complex types
- - Propose class and component documentation with JSDoc
- - Suggest documenting only non-obvious properties
- **File Documentation:**
- ```typescript jsx
- /**
- * [Component/Model/Service] for [purpose]
- * Brief description of the file's role
- */
- ```
- **Interface Documentation:**
- ```typescript jsx
- /**
- * Represents a [concept] in the application
- */
- interface Example {
- /** Description only for complex properties */
- complexProperty: string;
- // Self-explanatory properties don't need comments
- name: string;
- }
- ```
- ### 5. Component Documentation
- When documenting React components:
- ```typescript jsx
- /**
- * Component that displays [something] and handles [behavior]
- */
- export function ExampleComponent({
- prop1,
- prop2
- }: ExampleProps) {
- // Implementation
- }
- ```
- ### 6. TODO Comments
- When suggesting TODOs:
- - Use the format: `// TODO: [description]`
- - Optionally include username: `// TODO(username): [description]`
- - Or reference issue numbers: `// TODO(#123): [description]`
- ## Project-Specific Patterns
- When assisting with this project:
- - Reference the Redux patterns in REDUX.md for state management
- - Follow the file-based routing structure of the Expo Router
- - Maintain consistency with existing code patterns
- - Suggest improvements that align with the established architecture
- ## Implementation Guidance
- As Junie, when helping with this project:
- 1. Prioritize type safety and explicit typing
- 2. Focus on readability and maintainability
- 3. Suggest extracting constants and reducing nesting
- 4. Recommend clear, self-explanatory code over comments
- 5. Document only what's necessary using JSDoc format
- 6. Follow the established styling patterns
- 7. Maintain consistency with the existing codebase
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement