Advertisement
Guest User

Untitled

a guest
Jul 4th, 2025
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.21 KB | None | 0 0
  1. # Pagthon Project Guidelines
  2.  
  3. ## Code Structure and Style Guidelines
  4.  
  5. ### 1. TypeScript Type Definitions
  6.  
  7. When writing or changing TypeScript code always follow these rules strictly:
  8.  
  9. - Add explicit type definitions for:
  10. - Component props (use interfaces)
  11. - Function parameters
  12. - Function return types
  13. - Variable declarations
  14. - Avoid suggesting code with `any` type
  15. - Recommend type improvements when reviewing code that lacks proper typing
  16.  
  17. **Preferred Pattern:**
  18.  
  19. ```typescript jsx
  20. interface ComponentProps {
  21. item: ItemType;
  22. onAction: (item: ItemType) => void;
  23. }
  24.  
  25. export function Component({
  26. item,
  27. onAction
  28. }: ComponentProps): ReactElement {
  29. // Implementation
  30. }
  31. ```
  32.  
  33. ### 2. String Management
  34.  
  35. When working with string literals:
  36.  
  37. - Suggest extracting repeated strings into constants or enums
  38. - Use route path constants from the utils/routes.ts file
  39. - Recommend creating new constants for any string that appears multiple times
  40.  
  41. **Preferred Pattern:**
  42.  
  43. ```typescript jsx
  44. // Recommend this approach
  45. export const ROUTE_NAMES = {
  46. PROJECT_MODAL: (projectId: string) => `/modal/project/${projectId}`
  47. };
  48.  
  49. // Usage
  50. router.replace({
  51. pathname: ROUTE_NAMES.PROJECT_MODAL(project.id),
  52. });
  53. ```
  54.  
  55. ### 3. Internationalization (i18n)
  56.  
  57. When working with user-facing strings:
  58.  
  59. - **ALWAYS** use the `t` function from `@/localization/i18n.ts` for any string that will be displayed to the user
  60. - **NEVER** use raw string literals in UI components
  61. - If an appropriate translation key doesn't exist in `en.ts`, add a new one
  62. - Group related translation keys in appropriate sections in the locale files
  63. - Use the `StringKey` type to ensure type safety when using translation keys
  64.  
  65. **Preferred Pattern:**
  66.  
  67. ```typescript jsx
  68. // Import the t function
  69. import t from '@/localization/i18n';
  70.  
  71. // Use t function for all user-facing strings
  72. <ThemedText>{t('not_set')}</ThemedText>
  73. <Button
  74. title={t('save')}
  75. onPress={handleSave}/>
  76. <TextInput placeholder={t('notes_placeholder')}/>
  77.  
  78. // For strings with variables, use the options parameter
  79. <ThemedText>{t('greeting', {name: userName})}</ThemedText>
  80. ```
  81.  
  82. **Adding New Translation Keys:**
  83.  
  84. When a needed translation key doesn't exist:
  85.  
  86. 1. Add the key to the appropriate section in `src/localization/locales/en.ts`
  87. 2. Use descriptive, lowercase keys with underscores for spaces
  88. 3. Ensure the key is exported through the `StringKey` type
  89.  
  90. ```typescript jsx
  91. // In en.ts
  92. const buttons = {
  93. save: "Save",
  94. cancel: "Cancel",
  95. new_key: "New Button Text", // Add your new key here
  96. }
  97.  
  98. // In your component
  99. <Button title={t('new_key')} onPress={handleAction} />
  100. ```
  101.  
  102. **Incorrect Patterns to Avoid:**
  103.  
  104. ```typescript jsx
  105. // DON'T do this - using raw strings
  106. <ThemedText>Not set</ThemedText>
  107. <Button
  108. title="Save"
  109. onPress={handleSave}/>
  110.  
  111. // DON'T do this - concatenating strings
  112. <ThemedText>{t('greeting') + ' ' + userName}</ThemedText>
  113.  
  114. // DON'T do this - using string literals for placeholders
  115. <TextInput placeholder="Enter your name..."/>
  116. ```
  117.  
  118. ### 4. Code Nesting and Function Responsibility
  119.  
  120. When suggesting code structure:
  121.  
  122. - Keep nesting levels to a minimum (no more than 2-3 levels deep)
  123. - Recommend early returns to reduce nesting
  124. - Suggest guard clauses to simplify complex conditionals
  125. - Propose component composition instead of deeply nested JSX
  126. - Keep functions small and focused on a single responsibility
  127. - Extract complex logic into helper functions with descriptive names
  128. - Separate concerns: detection/validation logic should be separate from creation/transformation logic
  129.  
  130. **Preferred Patterns:**
  131.  
  132. Early returns:
  133.  
  134. ```typescript jsx
  135. if (!project) {
  136. return <ErrorComponent message="Project not found"/>;
  137. }
  138.  
  139. // Main component logic with less nesting
  140. ```
  141.  
  142. Guard clauses:
  143.  
  144. ```typescript jsx
  145. const handleAction = () => {
  146. if (!isValid) return;
  147.  
  148. // Main function logic without nesting
  149. };
  150. ```
  151.  
  152. Extracting complex logic:
  153.  
  154. ```typescript jsx
  155. // DON'T do this - complex nested logic in one function
  156. function processData(data) {
  157. const results = [];
  158. data.forEach(item => {
  159. if (item.isActive) {
  160. if (item.value > 10) {
  161. results.push({
  162. id: item.id,
  163. processedValue: item.value * 2,
  164. formattedLabel: `Item ${item.id}: ${item.value * 2}`,
  165. timestamp: Date.now()
  166. });
  167. }
  168. }
  169. });
  170. return results;
  171. }
  172.  
  173. // DO this instead - extract complex logic into helper functions
  174. function processData(data) {
  175. return data
  176. .filter(isActiveItemWithHighValue)
  177. .map(createProcessedItem);
  178. }
  179.  
  180. function isActiveItemWithHighValue(item) {
  181. return item.isActive && item.value > 10;
  182. }
  183.  
  184. function createProcessedItem(item) {
  185. const processedValue = item.value * 2;
  186. return {
  187. id: item.id,
  188. processedValue,
  189. formattedLabel: formatItemLabel(item.id, processedValue),
  190. timestamp: Date.now()
  191. };
  192. }
  193.  
  194. function formatItemLabel(id,
  195. value) {
  196. return `Item ${id}: ${value}`;
  197. }
  198. ```
  199.  
  200. ### 5. Component Structure
  201.  
  202. When helping with component organization:
  203.  
  204. - Suggest breaking down large components (>200 lines) into smaller ones
  205. - Recommend extracting complex logic into helper functions
  206. - Propose custom hooks for reusable stateful logic
  207. - Follow the project's component structure patterns
  208.  
  209. ### 6. Styling Approach
  210.  
  211. When assisting with component styling:
  212.  
  213. - Place style definitions in the same file as the component
  214. - Create a getStyle function that accepts ThemeColors
  215. - Use `useThemedStyle(getStyle)` to get the style in your component
  216. - Ensure the style variable is named `styles` consistently
  217.  
  218. **Preferred Pattern:**
  219.  
  220. ```typescript jsx
  221. export function MyComponent() {
  222. const themeColors = useThemeColorScheme();
  223. const styles = useThemedStyle(getStyle);
  224.  
  225. return (<View style={styles.container}>
  226. {/* Component content */}
  227. < /View>);
  228. }
  229.  
  230. const getStyle = (colors: ThemeColors) => {
  231. const styles = StyleSheet.create({
  232. container: {
  233. backgroundColor: colors.background,
  234. // Other styles
  235. },
  236. });
  237. return styles;
  238. };
  239. ```
  240.  
  241. ### 7. React Native Best Practices
  242.  
  243. When suggesting React Native code:
  244.  
  245. - Recommend `Pressable` instead of `TouchableOpacity` for interactive elements
  246. - Suggest performance optimizations like memoization where appropriate
  247. - Follow platform-specific guidelines when applicable
  248.  
  249. ### 8. Patterns to use
  250.  
  251. #### 8.1 Optional function call
  252. When working with optional functions like callbacks use the optional chaining operator (`?.`) rather than a single line
  253. if block.
  254.  
  255. ````typescript
  256. // Do NOT do this:
  257. if (onAction) {
  258. onAction();
  259. }
  260.  
  261. // Instead do this:
  262. onAction?.();
  263. ````
  264.  
  265. #### 8.2 Colors
  266.  
  267. When working with colors in the application:
  268.  
  269. - NEVER use string literals as colors (e.g., 'red', '#FF0000', 'rgba(255,0,0,1)') directly in components or styles
  270. - NEVER use fallback colors with the OR operator (e.g., `colors.error || 'red'`)
  271. - ALWAYS use the theme colors from the ThemeColors interface
  272. - Use `useThemeColors` to access colors in components
  273. - Use `useThemedStyle(getStyle)` to access colors in stylesheets
  274. - If a color you need doesn't exist in the ThemeColors interface:
  275. 1. Add the new color property to the ThemeColors interface in Colors.ts with appropriate documentation
  276. 2. Add appropriate color values for BOTH light and dark themes
  277. 3. Use the new color property in your component
  278.  
  279. **Correct Pattern:**
  280.  
  281. ```typescript jsx
  282. // In Colors.ts
  283. export type ThemeColors = {
  284. // Existing colors...
  285.  
  286. /**
  287. * Color for error messages and indicators
  288. */
  289. error: ColorString,
  290. }
  291.  
  292. const lightTheme = {
  293. // Existing colors...
  294. error: '#D32F2F',
  295. }
  296.  
  297. const darkTheme = {
  298. // Existing colors...
  299. error: '#FF6B6B',
  300. }
  301.  
  302. // In your component
  303. const getStyle = (colors: ThemeColors) => {
  304. const styles = StyleSheet.create({
  305. errorText: {
  306. color: colors.error,
  307. },
  308. });
  309. return styles;
  310. };
  311. ```
  312.  
  313. **Incorrect Patterns to Avoid:**
  314.  
  315. ```typescript jsx
  316. // DON'T do this - using string literals
  317. const styles = StyleSheet.create({
  318. errorText: {
  319. color: 'red',
  320. },
  321. });
  322.  
  323. // DON'T do this - using fallbacks
  324. const getStyle = (colors: ThemeColors) => {
  325. const styles = StyleSheet.create({
  326. errorText: {
  327. color: colors.error || 'red',
  328. },
  329. });
  330. return styles;
  331. };
  332. ```
  333.  
  334. ### 9. React Performance Optimization
  335.  
  336. When writing React components, use memoization techniques to prevent unnecessary re-renders and optimize performance:
  337.  
  338. #### 9.1 Using `useCallback`
  339.  
  340. Always use `useCallback` for:
  341.  
  342. - Event handlers passed to child components
  343. - Functions used as dependencies in other hooks
  344. - Callback functions passed as props to memoized components
  345.  
  346. **Preferred Pattern:**
  347.  
  348. ```typescript jsx
  349. // Always wrap event handlers with useCallback
  350. const handleSubmit = useCallback((data: FormData) => {
  351. dispatch(submitForm(data));
  352. }, [dispatch]);
  353.  
  354. // Always wrap functions passed as props
  355. const handleItemSelect = useCallback((item: Item) => {
  356. setSelectedItem(item);
  357. }, [setSelectedItem]);
  358.  
  359. // Always wrap functions used in dependency arrays
  360. const fetchData = useCallback(async () => {
  361. const response = await api.getData();
  362. setData(response);
  363. }, [api]);
  364.  
  365. useEffect(() => {
  366. fetchData();
  367. }, [fetchData]); // fetchData is stable between renders
  368. ```
  369.  
  370. #### 9.2 Using `useMemo`
  371.  
  372. Always use `useMemo` for:
  373.  
  374. - Expensive calculations or transformations
  375. - Derived data that depends on props or state
  376. - Objects or arrays that are used as dependencies in other hooks
  377. - Complex JSX structures that don't need to re-render often
  378.  
  379. **Preferred Pattern:**
  380.  
  381. ```typescript jsx
  382. // Memoize expensive calculations
  383. const sortedItems = useMemo(() => {
  384. return items.slice()
  385. .sort((a,
  386. b) => a.name.localeCompare(b.name));
  387. }, [items]);
  388.  
  389. // Memoize derived data
  390. const filteredUsers = useMemo(() => {
  391. return users.filter(user => user.status === 'active');
  392. }, [users]);
  393.  
  394. // Memoize objects used in dependency arrays
  395. const options = useMemo(() => ({
  396. threshold: 0.5,
  397. rootMargin: '0px',
  398. }), []); // Empty dependency array for static objects
  399.  
  400. useEffect(() => {
  401. const observer = new IntersectionObserver(callback, options);
  402. // ...
  403. }, [callback, options]); // options is stable between renders
  404.  
  405. // Memoize complex JSX structures
  406. const renderHeader = useMemo(() => (
  407. <Header
  408. title={title}
  409. subtitle={subtitle}
  410. actions={headerActions}
  411. />
  412. ), [title, subtitle, headerActions]);
  413. ```
  414.  
  415. #### 9.3 Component Memoization
  416.  
  417. Use React.memo for components that:
  418.  
  419. - Receive the same props frequently
  420. - Are expensive to render
  421. - Don't need to re-render when parent re-renders
  422.  
  423. **Preferred Pattern:**
  424.  
  425. ```typescript jsx
  426. // Define component with proper typing
  427. interface ItemProps {
  428. item: Item;
  429. onSelect: (item: Item) => void;
  430. }
  431.  
  432. // Memoize component to prevent unnecessary re-renders
  433. const ItemComponent = React.memo(({
  434. item,
  435. onSelect
  436. }: ItemProps) => {
  437. return (
  438. <Pressable onPress={() => onSelect(item)}>
  439. <Text>{item.name}</Text>
  440. </Pressable>
  441. );
  442. });
  443. ```
  444.  
  445. #### 9.4 Memoization Best Practices
  446.  
  447. When implementing memoization:
  448.  
  449. - Include all dependencies in the dependency array
  450. - Don't overuse memoization for simple calculations or components
  451. - Use dependency arrays correctly to avoid stale closures
  452. - Consider using the React DevTools Profiler to identify unnecessary re-renders
  453. - Ensure memoized functions have stable dependencies
  454.  
  455. **Example of Proper Dependency Management:**
  456.  
  457. ```typescript jsx
  458. // Component with proper memoization
  459. export function OptimizedComponent({
  460. items,
  461. onItemSelect
  462. }) {
  463. const [filter, setFilter] = useState('');
  464.  
  465. // Memoize filtered items
  466. const filteredItems = useMemo(() => {
  467. return items.filter(item => item.name.includes(filter));
  468. }, [items, filter]);
  469.  
  470. // Memoize item selection handler
  471. const handleSelect = useCallback((item) => {
  472. onItemSelect(item);
  473. }, [onItemSelect]);
  474.  
  475. // Memoize render function for list items
  476. const renderItem = useCallback(({item}) => (
  477. <ItemComponent
  478. item={item}
  479. onSelect={handleSelect}
  480. />
  481. ), [handleSelect]);
  482.  
  483. return (
  484. <FlatList
  485. data={filteredItems}
  486. renderItem={renderItem}
  487. keyExtractor={item => item.id}
  488. />
  489. );
  490. }
  491. ```
  492.  
  493. ## Documentation and Comment Guidelines
  494.  
  495. ### 1. Comment Philosophy
  496.  
  497. When writing, reviewing, or changing code follow these rules exactly:
  498.  
  499. - **NEVER ADD INLINE COMMENTS DESCRIBING WHAT THE CODE DOES** - This is a strict rule with no exceptions
  500. - **NEVER** write trivial comments that merely restate what the function or variable name already clearly indicates
  501. - **NEVER** add comments like "// Handle navigation actions" or "// Dispatch Redux action" that add no value
  502. - Function and variable names should be self-explanatory, making such comments redundant
  503. - Prioritize self-explanatory code over excessive comments
  504. - Focus comments on explaining "why" rather than "how" or "what"
  505. - Suggest removing redundant comments that merely restate the code
  506. - Recommend updating comments when code changes
  507.  
  508. **Examples of Trivial Comments to Avoid:**
  509.  
  510. ```typescript jsx
  511. // Reset form
  512. const resetForm = () => {
  513. setTitle('');
  514. setDescription('');
  515. setActions([]);
  516. };
  517.  
  518. // Update user name
  519. function updateUserName(name) {
  520. user.name = name;
  521. }
  522.  
  523. // Check if user is admin
  524. const isAdmin = user.role === 'admin';
  525.  
  526. // state for input form
  527. const [feedbackType, setFeedbackType] = useState<'suggestion' | 'bug' | 'other'>('suggestion');
  528. const [feedbackText, setFeedbackText] = useState('');
  529. const [submitted, setSubmitted] = useState(false);
  530.  
  531. ```
  532.  
  533. These comments add no value as the function and variable names already clearly describe what the code does.
  534.  
  535. ### 2. Appropriate Comment Usage
  536.  
  537. Suggest comments only for:
  538.  
  539. - Non-obvious implementations or workarounds
  540. - Complex business logic explanations
  541. - Temporary solutions (with TODO markers)
  542.  
  543. **Good Comment Examples:**
  544.  
  545. ```typescript jsx
  546. // This is a workaround for React Native bug #1234
  547. const adjustedValue = value + 1;
  548.  
  549. // TODO: Replace with API call when backend is ready
  550. const mockData = [];
  551. ```
  552.  
  553. ### 3. Code Clarity Over Comments
  554.  
  555. When reviewing code with explanatory comments:
  556.  
  557. - Suggest refactoring the code to be self-explanatory
  558. - Recommend extracting complex expressions into named variables
  559. - Propose function extraction for commented blocks of code
  560.  
  561. **Example Transformation:**
  562.  
  563. ```typescript jsx
  564. // From:
  565. // Check if all actions are completed
  566. const isCompleted = actions.length > 0 && actions.every(a => a.isCompleted);
  567.  
  568. // To:
  569. const hasActions = actions.length > 0;
  570. const allActionsCompleted = actions.every(action => action.isCompleted);
  571. const isCompleted = hasActions && allActionsCompleted;
  572. ```
  573.  
  574. ### 4. Documentation Structure
  575.  
  576. When helping with code documentation:
  577.  
  578. - Suggest JSDoc comments for file-level documentation
  579. - Recommend documenting interfaces and complex types
  580. - Propose class and component documentation with JSDoc
  581. - Suggest documenting only non-obvious properties
  582.  
  583. **File Documentation:**
  584.  
  585. ```typescript jsx
  586. /**
  587. * [Component/Model/Service] for [purpose]
  588. * Brief description of the file's role
  589. */
  590. ```
  591.  
  592. **Interface Documentation:**
  593.  
  594. ```typescript jsx
  595. /**
  596. * Represents a [concept] in the application
  597. */
  598. interface Example {
  599. /** Description only for complex properties */
  600. complexProperty: string;
  601.  
  602. // Self-explanatory properties don't need comments
  603. name: string;
  604. }
  605. ```
  606.  
  607. ### 5. Component Documentation
  608.  
  609. When documenting React components:
  610.  
  611. ```typescript jsx
  612. /**
  613. * Component that displays [something] and handles [behavior]
  614. */
  615. export function ExampleComponent({
  616. prop1,
  617. prop2
  618. }: ExampleProps) {
  619. // Implementation
  620. }
  621. ```
  622.  
  623. ### 6. TODO Comments
  624.  
  625. When suggesting TODOs:
  626.  
  627. - Use the format: `// TODO: [description]`
  628. - Optionally include username: `// TODO(username): [description]`
  629. - Or reference issue numbers: `// TODO(#123): [description]`
  630.  
  631. ## Project-Specific Patterns
  632.  
  633. When assisting with this project:
  634.  
  635. - Reference the Redux patterns in REDUX.md for state management
  636. - Follow the file-based routing structure of the Expo Router
  637. - Maintain consistency with existing code patterns
  638. - Suggest improvements that align with the established architecture
  639.  
  640. ## Implementation Guidance
  641.  
  642. As Junie, when helping with this project:
  643.  
  644. 1. Prioritize type safety and explicit typing
  645. 2. Focus on readability and maintainability
  646. 3. Suggest extracting constants and reducing nesting
  647. 4. Recommend clear, self-explanatory code over comments
  648. 5. Document only what's necessary using JSDoc format
  649. 6. Follow the established styling patterns
  650. 7. Maintain consistency with the existing codebase
  651.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement