Skip to content

Commit cb2fe2e

Browse files
committed
[LG-5128] feat(code-editor): add code formatting functionality with multi-language support (#3058)
* feat(CodeEditor): integrate code formatting functionality with Prettier and WASM support - Added support for code formatting in the CodeEditor component using Prettier-based and WASM-based formatters. - Introduced `useCodeFormatter` and `useFormattingModuleLoaders` hooks for dynamic loading of formatting modules based on the selected language. - Updated the CodeEditor context to include formatting capabilities, allowing users to format code directly within the editor. - Enhanced the README to document the new formatting features and supported languages. - Added new dependencies for Prettier plugins and WASM formatters in the package configuration. * refactor(CodeEditor): update imports for CodeEditorModules type - Changed imports of `CodeEditorModules` from `useModuleLoaders` to `moduleLoaders.types` across various hooks for improved clarity and consistency. - Updated the export statement for `CodeEditorModules` in the hooks index file to align with the new import structure. * feat(Panel): enhance rendering with code formatting capabilities - Updated the `CodeEditorProvider` in the `Panel` component to include `formatCode` and `isFormattingAvailable` properties, enabling code formatting features. - Added a mock for `formatCode` in the test suite to ensure proper testing of the new functionality. - Ensured that `mockGetContents` returns the expected content during tests for consistent behavior. * feat(CodeEditor): add comprehensive tests for code formatting and module loaders - Introduced unit tests for the `useCodeFormatter` hook, covering various programming languages and formatting scenarios, including error handling and custom options. - Added tests for the `useFormattingModuleLoaders` hook to ensure correct loading of formatting modules for supported languages. - Enhanced test coverage for edge cases, such as unsupported languages and missing modules, ensuring robust functionality of the formatting features. * test(CodeEditor): suppress console warnings and errors in tests - Mocked console.warn and console.error methods in the test suite to suppress expected warnings related to missing formatting modules and React testing library deprecation notices. - This enhancement improves test output clarity and focuses on relevant test results without unnecessary console noise. * feat(CodeEditor): update code formatting support and integrate new plugins - Removed external Prettier plugin support for Java, Kotlin, PHP, and Ruby due to browser compatibility issues, transitioning to WASM-based formatting for Java and C++. - Added type declarations for Kotlin and Ruby Prettier plugins to enhance type safety. - Updated the `useCodeFormatter` and `useFormattingModuleLoaders` hooks to reflect the changes in formatting capabilities and module loading logic. - Enhanced the `CodeEditor` stories to demonstrate the new formatting features with updated language settings. * refactor(CodeEditor): clean up useFormattingModuleLoaders hook - Removed commented-out code related to Node.js environment checks and external Prettier plugin support for Java, enhancing code clarity and maintainability. - Streamlined the logic within the `useFormattingModuleLoaders` hook to focus on active functionality. * fix(CodeEditor): update language handling and import logic - Changed the default language in the CodeEditor stories from Java to C++, ensuring the correct language is displayed in the example. - Refactored the `useFormattingModuleLoaders` and `useModuleLoaders` hooks to define stable import functions outside the hooks, preventing infinite re-renders and improving performance. - Updated the logic for loading language-specific modules, enhancing clarity and maintainability of the code. * refactor(CodeEditor): remove unsupported Prettier plugins and clean up code - Eliminated support for Kotlin, PHP, Ruby, and Rust Prettier plugins due to browser compatibility issues, streamlining the codebase. - Removed related type declarations and test cases for these plugins, enhancing clarity and maintainability. - Updated the `useFormattingModuleLoaders` hook to reflect the removal of unsupported languages, ensuring a more focused implementation. * test(CodeEditor): enhance unit tests for useCodeFormatter hook - Added comprehensive tests for various programming languages, ensuring correct formatting behavior for JavaScript, TypeScript, JSON, CSS, HTML, Java, C++, C#, Go, and Python. - Implemented checks for unsupported languages, confirming that appropriate warnings are issued and original code is returned. - Enhanced error handling tests to verify graceful handling of missing modules and formatting errors. - Updated the `useCodeFormatter` hook to enforce multi-line formatting for JSON by adjusting the default print width. * feat(CodeEditor): add JSX and TSX support in stories and code snippets - Introduced new story exports for JSX and TSX languages in CodeEditor stories, enhancing the demonstration of language support. - Added corresponding code snippets for JSX and TSX to the testing module, providing examples for users and improving test coverage. * fix(CodeEditor): update language handling and formatting for C# support - Changed the default language in the CodeEditor stories from C++ to C#, ensuring accurate representation in the example. - Enhanced the formatting logic in the `useCodeFormatter` hook to apply Microsoft style settings for C#. - Updated test cases to reflect the new formatting expectations for C#, improving overall test coverage and accuracy. * refactor(CodeEditor): streamline formatting options in useCodeFormatter hook - Removed direct tabWidth and useTabs options from the FormattingOptions interface, deriving them from CodeEditor props instead. - Updated the useCodeFormatter hook to consistently apply editor configuration for tab width and tab usage across various formatting functions. - Enhanced code clarity by centralizing formatting option logic, improving maintainability and reducing redundancy. * feat(CodeEditor): enhance formatting capabilities and modularize code - Introduced a new `formatters.ts` file to centralize formatting logic for various languages, improving code organization and maintainability. - Added `useFormattingModuleLoaders` hook to dynamically load formatting modules based on the selected language, enhancing flexibility. - Updated `useCodeFormatter` to utilize the new formatting functions and options, ensuring consistent behavior across different languages. - Removed the deprecated `useCodeFormatter` implementation, streamlining the codebase and reducing redundancy. - Added comprehensive tests for the new formatting logic, ensuring correct behavior across supported languages and handling of edge cases. * feat(CodeEditor): modularize formatting functions for improved code organization - Introduced helper functions `formatWithPrettier` and `formatWithWasm` to encapsulate formatting logic for Prettier and WASM-based formatters, enhancing code clarity and reusability. - Updated the `formatCode` function to utilize these new helpers, streamlining the formatting process for JavaScript, TypeScript, JSON, CSS, HTML, and other languages. - Improved error handling by providing consistent warning messages when required modules are not loaded, ensuring better user feedback during formatting operations. * chore(typings): remove deprecated prettier-plugins type declaration file - Deleted the `prettier-plugins.d.ts` file as it is no longer needed, streamlining the typings and improving code organization. * refactor(CodeEditor): improve code organization and clarity in CodeEditor component - Updated comments for better clarity and understanding of the code structure, including loading core modules, formatting functionality, and custom extensions. - Removed outdated comments to streamline the code and enhance readability. - Ensured consistent documentation style throughout the CodeEditor component for improved maintainability. * refactor(Panel): remove outdated comments for improved clarity - Deleted unnecessary comments in the Panel component to enhance code readability and maintainability. - Streamlined the code by removing comments that no longer provide value, ensuring a cleaner codebase. * feat(CodeEditor): add FormattingOptions type to enhance formatting capabilities - Introduced the `FormattingOptions` type to the CodeEditor module, improving type safety and clarity for formatting configurations. - This addition supports ongoing enhancements to the formatting logic and options within the CodeEditor component. * refactor(CodeEditor): streamline code formatting documentation and functionality - Updated the README to clarify the integration of code formatting with the `Panel` component and the `useCodeFormatter` hook. - Simplified the list of supported languages and removed outdated details regarding formatting backends. - Enhanced the `useCodeFormatter` hook to derive formatting options directly from the CodeEditor props, improving usability and consistency. - Removed unnecessary module loading logic from the `CodeEditor` component, ensuring a cleaner implementation. - Improved test coverage for the `useCodeFormatter` hook by removing redundant module dependencies in tests. * docs(CodeEditor): enhance README with detailed code formatting methods - Expanded the documentation to outline three distinct methods for formatting code: via the Panel component, programmatically using the CodeEditor ref, and through the standalone useCodeFormatter hook. - Included code examples for each method to improve clarity and usability for developers. - Updated the section on FormattingOptions to reflect comprehensive support for various languages, enhancing the overall understanding of formatting capabilities. * Passing tests - but not testing correctly * test(CodeEditor): enhance unit tests for useCodeFormatter hook - Updated tests to mock WASM formatters for better compatibility with Jest, ensuring accurate testing of formatting functionality across multiple languages. - Simplified test cases by removing conditional checks for module availability, directly asserting expected outcomes for formatted code. - Improved coverage for various languages including Java, C++, C#, Go, and Python, ensuring consistent behavior and correctness in formatting operations. * feat(CodeEditor): introduce comprehensive code formatting system - Added a powerful code formatting functionality supporting multiple languages, including JavaScript, TypeScript, CSS, HTML, JSON, Java, C++, C#, Go, and Python. - Integrated a format button in the Panel component with automatic language detection and introduced a `formatCode` method for programmatic use. - Created a standalone `useCodeFormatter` hook for independent formatting capabilities. - Enhanced the Panel and CodeEditor components with new context integrations and formatting options. - Introduced new dependencies including `prettier` and WASM-based formatters for various languages. - Automatically manages dependencies and provides fallback behavior for unsupported languages. * chore(CodeEditor): remove prettier-plugin-java references and clean up dependencies - Removed `prettier-plugin-java` from the package.json and pnpm-lock.yaml files as it is no longer needed. - Updated tests and type definitions to eliminate references to `prettier-plugin-java`, ensuring a cleaner codebase. - Streamlined the CodeEditor module by focusing on essential dependencies for formatting functionality. * fix(Panel): update grid-template-areas for consistency - Changed the grid-template-areas property in Panel.styles.ts from 'title innerContent buttons' to 'title inner-content buttons' for improved consistency in naming conventions. * fix(CodeEditor): update language in WithPanel story from HTML to TSX - Changed the language in the WithPanel story from LanguageName.html to LanguageName.tsx to reflect the correct code snippet usage. * refactor(Panel): simplify IconButton component in format trigger - Removed unnecessary props from the IconButton in the Panel component's format trigger, enhancing code readability and maintainability. * refactor(Panel): remove unused isFormattingAvailable from context - Eliminated the unused `isFormattingAvailable` property from the `useCodeEditorContext` in the Panel component, streamlining the code and improving clarity. * docs(CodeEditor): update README and code structure for module loading - Enhanced the README to include detailed instructions on module loading requirements for code formatting, emphasizing the use of `useFormattingModuleLoaders` and `useLazyModules`. - Updated the `CodeEditor` component to integrate formatting module loaders, ensuring that necessary modules are loaded based on the selected language. - Refined the `useCodeFormatter` hook to utilize pre-loaded modules, improving the overall formatting functionality and user experience. * refactor(useCodeFormatter): rename state variable for clarity - Updated the state variable from `isFormattingReady` to `isFormattingAvailable` in the `useCodeFormatter` hook for improved clarity and consistency in naming conventions. - Adjusted the corresponding useEffect to reflect the new variable name, enhancing code readability. * docs(README): streamline module loading instructions for formatting - Removed references to `useFormattingModuleLoaders` and `useLazyModules` from the README to simplify the example for the `useCodeFormatter` hook. - Added a comment to clarify the need for language-specific modules in the formatting process, enhancing the documentation's clarity and usability. * docs(README): simplify code formatting example by removing module loader references - Streamlined the README example for the `useCodeFormatter` hook by removing references to `useFormattingModuleLoaders` and `useLazyModules`, enhancing clarity and usability for users. * docs(README): update code formatting instructions to clarify module loading - Revised the README to emphasize that consumers must load and provide the required modules for code formatting, removing references to `useFormattingModuleLoaders` and `useLazyModules`. - Updated code examples to reflect the new approach, enhancing clarity and usability for users. * refactor(CodeEditor): optimize module loading with useMemo - Introduced useMemo to combine core and formatting module loaders in the CodeEditor component, improving performance by memoizing the merged loaders. - Updated the useLazyModules call to utilize the memoized loaders, enhancing the efficiency of module loading during rendering. * test(CodeEditor): enhance unit tests for useCodeFormatter with mock modules - Refactored unit tests for the `useCodeFormatter` hook to utilize a new `createMockModules` function, simplifying the setup of mock modules for various languages. - Updated tests to verify that formatting functions are called correctly and return expected results, ensuring robust coverage for JavaScript, TypeScript, JSON, CSS, HTML, Java, C++, C#, Go, and Python. - Improved error handling tests to ensure original code is returned when formatting fails, enhancing the reliability of the formatter. * refactor(CodeEditor): enhance type safety and structure in formatting functions - Introduced improved type definitions for Prettier and WASM formatter configurations, enhancing type safety and flexibility. - Refactored formatting functions to use destructured parameters, improving readability and maintainability. - Updated the `formatCode` function to accept an object for parameters, streamlining the function signature and enhancing clarity. - Adjusted related utility functions to align with the new type definitions, ensuring consistency across the formatting module. * refactor(CodeEditor): simplify formatting options and streamline code formatting functionality - Removed the `FormattingOptions` type and associated options from the `formatCode` function, adopting opinionated defaults for consistency across languages. - Updated README documentation to reflect the changes in formatting options and usage examples. - Refactored related formatting functions to eliminate unnecessary parameters, enhancing clarity and maintainability. * refactor(CodeEditor): enhance type safety in update listener - Updated the type definition for the update listener in the CodeEditor component to include `ViewUpdate`, improving type safety and clarity in the handling of editor updates. - This change ensures better integration with the CodeMirror library and enhances maintainability of the code. * refactor(CodeEditor): improve configuration structure and type safety in formatting functions - Refactored the `createPrettierConfig` and `createJavaScriptConfig` functions to use destructured parameters, enhancing readability and maintainability. - Updated the `formatCode` function to align with the new configuration structure, improving clarity in the formatting process. - Enhanced type safety in the `areModulesLoaded` function by adopting a destructured parameter approach, ensuring better integration with the modules. - Adjusted related utility functions to maintain consistency across the formatting module. * refactor(CodeEditor): streamline change handling in editor updates - Added a call to `onChangeProp` after dispatching the transaction in the CodeEditor component, ensuring that changes are communicated immediately. - Removed the redundant `onChangeProp` call within the controlled value update block, simplifying the change handling logic and improving code clarity. * docs(README): enhance clarity and structure in code editor documentation - Updated section headers for consistency and improved readability. - Removed outdated module loading requirements and examples, streamlining the documentation. - Added detailed notes on required props and modules for various extensions, enhancing user understanding. - Clarified usage examples and parameters for better guidance on implementing the CodeEditor features. * refactor(CodeEditor): add FormattingOptions type to formatting module - Introduced the `FormattingOptions` type to enhance type safety and flexibility in the formatting module. - Updated exports in the formatting index to include the new type, ensuring better integration with formatting functions. * docs(README): update link formatting for clarity in code editor documentation - Changed the link to MongoDB.design to a header format for improved visibility and consistency. - This adjustment enhances the overall structure of the README, aligning with recent documentation updates. * refactor(CodeEditor): separate core and formatting module loading for improved clarity - Refactored the CodeEditor component to distinctly load core and formatting modules, enhancing code organization and readability. - Updated the handling of module loading states to reflect the separation, ensuring better management of loading indicators. - Adjusted the usage of modules in various functionalities to align with the new loading structure, improving maintainability.
1 parent ff5976a commit cb2fe2e

38 files changed

+1978
-218
lines changed

.changeset/violet-queens-train.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
---
2+
'@leafygreen-ui/code-editor': minor
3+
---
4+
5+
Adds comprehensive code formatting functionality to CodeEditor
6+
7+
This release introduces a powerful code formatting system that supports multiple programming languages:
8+
9+
**New Features:**
10+
11+
- **Panel Integration**: Format button in Panel component with automatic language detection
12+
- **Programmatic Formatting**: `formatCode` method available via CodeEditor ref and context
13+
- **Standalone Hook**: `useCodeFormatter` hook for independent formatting functionality
14+
- **Multi-language Support**: JavaScript/JSX, TypeScript/TSX, CSS, HTML, JSON, Java, C++, C#, Go, and Python
15+
- **Configurable Options**: Support for formatting options like semicolons, quotes, line width, and more
16+
17+
**Supported Languages:**
18+
19+
- **Prettier-based**: JavaScript, JSX, TypeScript, TSX, CSS, HTML, JSON
20+
- **WASM-based**: Java (clang-format), C++ (clang-format), C# (clang-format), Go (gofmt), Python (ruff)
21+
22+
**New Dependencies:**
23+
24+
- `prettier` (2.8.8) - Core formatting engine
25+
- `@wasm-fmt/clang-format` (^20.1.7) - C++/C# formatting via WASM
26+
- `@wasm-fmt/gofmt` (^0.4.9) - Go formatting via WASM
27+
- `@wasm-fmt/ruff_fmt` (^0.10.0) - Python formatting via WASM
28+
29+
**New Exports:**
30+
31+
- `useCodeFormatter` - Standalone formatting hook
32+
- `FormattingOptions` - TypeScript interface for formatting configuration
33+
34+
**Enhanced Components:**
35+
36+
- **Panel**: New `isFormattingAvailable` context integration and intelligent format button state
37+
- **CodeEditor**: Enhanced context with formatting capabilities and ref methods
38+
39+
The formatting system automatically loads required dependencies and provides fallback behavior for unsupported languages. Format button is automatically disabled when formatting is not available for the current language.

0 commit comments

Comments
 (0)