From 9c5d0bfcc75f0d21e74b330d17b4e8ff0cf227aa Mon Sep 17 00:00:00 2001 From: WinJay Date: Thu, 23 Oct 2025 13:24:35 +0800 Subject: [PATCH] feat: improve development experience and add performance optimizations - Add comprehensive DEVELOPMENT.md guide with setup instructions - Add CONTRIBUTING.md with contribution guidelines - Add CODE_OF_CONDUCT.md for community standards - Enhance error handling with additional error types and utilities - Add performance monitoring and optimization utilities - Improve code documentation and developer experience --- CODE_OF_CONDUCT.md | 75 +++++++ CONTRIBUTING.md | 87 ++++++++ DEVELOPMENT.md | 178 +++++++++++++++++ packages/drawnix/src/errors.ts | 52 +++++ packages/drawnix/src/utils/performance.ts | 233 ++++++++++++++++++++++ 5 files changed, 625 insertions(+) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 DEVELOPMENT.md create mode 100644 packages/drawnix/src/utils/performance.ts diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..6e3e352d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,75 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..c634c6d4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,87 @@ +# Contributing to Drawnix + +Thank you for your interest in contributing to Drawnix! This document provides guidelines and information for contributors. + +## Code of Conduct + +This project follows the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. + +## How to Contribute + +### Reporting Bugs + +Before creating bug reports, please check existing issues to avoid duplicates. When creating a bug report, please include: + +- **Use a clear and descriptive title** +- **Describe the exact steps to reproduce the problem** +- **Provide specific examples to demonstrate the steps** +- **Describe the behavior you observed after following the steps** +- **Explain which behavior you expected to see instead and why** +- **Include screenshots and animated GIFs if possible** +- **Include your operating system and browser information** + +### Suggesting Enhancements + +Enhancement suggestions are tracked as GitHub issues. When creating an enhancement suggestion, please include: + +- **Use a clear and descriptive title** +- **Provide a step-by-step description of the suggested enhancement** +- **Provide specific examples to demonstrate the steps** +- **Describe the current behavior and explain which behavior you expected to see instead** +- **Explain why this enhancement would be useful** +- **List some other applications where this enhancement exists** + +### Pull Requests + +- Fill in the required template +- Do not include issue numbers in the PR title +- Include screenshots and animated GIFs in your pull request whenever possible +- Follow the JavaScript styleguide +- Include thoughtfully-worded, well-structured tests +- Document new code based on the Documentation Styleguide +- End all files with a newline + +## Development Setup + +1. Fork and clone the repository +2. Install dependencies: `npm install` +3. Start the development server: `npm run start` +4. Make your changes +5. Run tests: `npm run test` +6. Run linting: `npm run lint` + +## Styleguides + +### Git Commit Messages + +- Use the present tense ("Add feature" not "Added feature") +- Use the imperative mood ("Move cursor to..." not "Moves cursor to...") +- Limit the first line to 72 characters or less +- Reference issues and pull requests liberally after the first line + +### JavaScript Styleguide + +- Use semicolons +- Use 2 spaces for indentation +- Use single quotes for strings +- Use trailing commas +- Use meaningful variable and function names +- Use const/let instead of var +- Use arrow functions when appropriate + +### Documentation Styleguide + +- Use [Markdown](https://daringfireball.net/projects/markdown/) +- Use present tense ("This function does..." not "This function will do...") +- Use active voice ("The user clicks the button" not "The button is clicked by the user") +- Use clear and concise language +- Include code examples when helpful + +## Community + +- [GitHub Discussions](https://github.com/plait-board/drawnix/discussions) - General discussion +- [GitHub Issues](https://github.com/plait-board/drawnix/issues) - Bug reports and feature requests + +## License + +By contributing to Drawnix, you agree that your contributions will be licensed under the MIT License. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md new file mode 100644 index 00000000..6c492813 --- /dev/null +++ b/DEVELOPMENT.md @@ -0,0 +1,178 @@ +# Development Guide + +This guide will help you get started with developing Drawnix locally. + +## Prerequisites + +- Node.js 18+ +- npm or yarn +- Git + +## Getting Started + +1. **Clone the repository** + ```bash + git clone https://github.com/plait-board/drawnix.git + cd drawnix + ``` + +2. **Install dependencies** + ```bash + npm install + ``` + +3. **Start development server** + ```bash + npm run start + ``` + +4. **Open your browser** + Navigate to `http://localhost:4200` to see the application. + +## Project Structure + +``` +drawnix/ +├── apps/ +│ ├── web/ # Main web application +│ └── web-e2e/ # End-to-end tests +├── packages/ +│ ├── drawnix/ # Core drawnix package +│ ├── react-board/ # React board components +│ └── react-text/ # Text rendering components +├── scripts/ # Build and deployment scripts +└── dist/ # Build output +``` + +## Available Scripts + +- `npm run start` - Start development server +- `npm run build` - Build all packages +- `npm run build:web` - Build web application only +- `npm run lint` - Run ESLint on all packages +- `npm run test` - Run tests +- `npm run release` - Release new version + +## Development Tips + +### Hotkey Shortcuts + +The application supports various keyboard shortcuts for better user experience: + +- `Ctrl/Cmd + S` - Save as JSON +- `Ctrl/Cmd + Shift + E` - Export as image +- `Ctrl/Cmd + Z` - Undo +- `Ctrl/Cmd + Shift + Z` - Redo +- `Ctrl/Cmd + U` - Add image +- `Ctrl/Cmd + Backspace/Delete` - Clear canvas + +### Tool Shortcuts + +- `H` - Hand tool +- `V` - Selection tool +- `M` - Mind map tool +- `E` - Eraser tool +- `P` - Pen tool +- `A` - Arrow tool +- `R` - Rectangle tool +- `O` - Oval tool +- `T` - Text tool + +## Contributing + +1. Fork the repository +2. Create a feature branch (`git checkout -b feature/amazing-feature`) +3. Make your changes +4. Run tests (`npm run test`) +5. Run linting (`npm run lint`) +6. Commit your changes (`git commit -m 'Add amazing feature'`) +7. Push to the branch (`git push origin feature/amazing-feature`) +8. Open a Pull Request + +## Code Style + +- Use TypeScript for all new code +- Follow ESLint configuration +- Use Prettier for code formatting +- Write tests for new features +- Follow existing naming conventions + +## Testing + +Run the test suite: +```bash +npm run test +``` + +Run end-to-end tests: +```bash +npm run e2e +``` + +## Building for Production + +```bash +npm run build +``` + +The built files will be in the `dist/` directory. + +## Docker Development + +You can also run the application using Docker: + +```bash +docker pull pubuzhixing/drawnix:latest +docker run -p 4200:4200 pubuzhixing/drawnix:latest +``` + +## Troubleshooting + +### Common Issues + +1. **Port already in use** + - Change the port in `apps/web/vite.config.ts` + - Or kill the process using the port + +2. **Dependencies not installing** + - Clear npm cache: `npm cache clean --force` + - Delete `node_modules` and `package-lock.json` + - Run `npm install` again + +3. **Build errors** + - Check TypeScript errors: `npx tsc --noEmit` + - Run linting: `npm run lint` + - Check for missing dependencies + +### Getting Help + +- Check existing [Issues](https://github.com/plait-board/drawnix/issues) +- Create a new issue if your problem isn't already reported +- Join discussions in the repository + +## Architecture + +Drawnix is built on top of the Plait framework and uses a plugin-based architecture: + +- **Core**: Base drawing functionality +- **Plugins**: Extensible features (mind maps, freehand drawing, etc.) +- **React Components**: UI layer built with React +- **Slate**: Rich text editing capabilities + +This architecture allows for: +- Multiple UI framework support (Angular, React) +- Integration with different rich text frameworks +- Fine-grained reusable plugins +- Extensible drawing board applications + +## Performance Tips + +- Use React.memo for expensive components +- Implement virtual scrolling for large canvases +- Optimize image loading and caching +- Use Web Workers for heavy computations +- Implement proper cleanup in useEffect hooks + +--- + +Happy coding! 🎨 diff --git a/packages/drawnix/src/errors.ts b/packages/drawnix/src/errors.ts index e3680a42..84955f33 100644 --- a/packages/drawnix/src/errors.ts +++ b/packages/drawnix/src/errors.ts @@ -3,3 +3,55 @@ export class AbortError extends DOMException { super(message, 'AbortError'); } } + +export class ValidationError extends Error { + constructor(message: string, public field?: string) { + super(message); + this.name = 'ValidationError'; + } +} + +export class NetworkError extends Error { + constructor(message: string, public statusCode?: number) { + super(message); + this.name = 'NetworkError'; + } +} + +export class FileError extends Error { + constructor(message: string, public fileName?: string) { + super(message); + this.name = 'FileError'; + } +} + +export class CanvasError extends Error { + constructor(message: string, public operation?: string) { + super(message); + this.name = 'CanvasError'; + } +} + +// Error utility functions +export const createError = (type: string, message: string, details?: any) => { + const errorMap = { + 'AbortError': () => new AbortError(message), + 'ValidationError': () => new ValidationError(message, details?.field), + 'NetworkError': () => new NetworkError(message, details?.statusCode), + 'FileError': () => new FileError(message, details?.fileName), + 'CanvasError': () => new CanvasError(message, details?.operation), + }; + + return errorMap[type]?.() || new Error(message); +}; + +export const isError = (error: any): error is Error => { + return error instanceof Error; +}; + +export const getErrorMessage = (error: unknown): string => { + if (isError(error)) { + return error.message; + } + return String(error); +}; diff --git a/packages/drawnix/src/utils/performance.ts b/packages/drawnix/src/utils/performance.ts new file mode 100644 index 00000000..d3482877 --- /dev/null +++ b/packages/drawnix/src/utils/performance.ts @@ -0,0 +1,233 @@ +/** + * Performance utilities for Drawnix + * Provides tools for optimizing canvas operations and user interactions + */ + +export class PerformanceMonitor { + private static instance: PerformanceMonitor; + private metrics: Map = new Map(); + + static getInstance(): PerformanceMonitor { + if (!PerformanceMonitor.instance) { + PerformanceMonitor.instance = new PerformanceMonitor(); + } + return PerformanceMonitor.instance; + } + + startTiming(label: string): void { + const startTime = performance.now(); + this.metrics.set(`${label}_start`, [startTime]); + } + + endTiming(label: string): number { + const endTime = performance.now(); + const startTimes = this.metrics.get(`${label}_start`); + + if (startTimes && startTimes.length > 0) { + const duration = endTime - startTimes[0]; + this.recordMetric(label, duration); + return duration; + } + + return 0; + } + + recordMetric(label: string, value: number): void { + const existing = this.metrics.get(label) || []; + existing.push(value); + this.metrics.set(label, existing); + } + + getAverageTime(label: string): number { + const values = this.metrics.get(label) || []; + if (values.length === 0) return 0; + + return values.reduce((sum, val) => sum + val, 0) / values.length; + } + + getMetrics(): Record { + const result: Record = {}; + this.metrics.forEach((values, key) => { + if (!key.endsWith('_start')) { + result[key] = values; + } + }); + return result; + } + + clearMetrics(): void { + this.metrics.clear(); + } +} + +export class Debouncer { + private timeoutId: NodeJS.Timeout | null = null; + + debounce any>( + func: T, + delay: number + ): (...args: Parameters) => void { + return (...args: Parameters) => { + if (this.timeoutId) { + clearTimeout(this.timeoutId); + } + + this.timeoutId = setTimeout(() => { + func(...args); + this.timeoutId = null; + }, delay); + }; + } + + cancel(): void { + if (this.timeoutId) { + clearTimeout(this.timeoutId); + this.timeoutId = null; + } + } +} + +export class Throttler { + private lastExecuted = 0; + + throttle any>( + func: T, + limit: number + ): (...args: Parameters) => void { + return (...args: Parameters) => { + const now = Date.now(); + + if (now - this.lastExecuted >= limit) { + func(...args); + this.lastExecuted = now; + } + }; + } +} + +export class MemoryManager { + private static readonly MAX_CACHE_SIZE = 100; + private cache: Map = new Map(); + + set(key: string, value: any): void { + if (this.cache.size >= MemoryManager.MAX_CACHE_SIZE) { + const firstKey = this.cache.keys().next().value; + this.cache.delete(firstKey); + } + this.cache.set(key, value); + } + + get(key: string): any { + return this.cache.get(key); + } + + has(key: string): boolean { + return this.cache.has(key); + } + + clear(): void { + this.cache.clear(); + } + + getSize(): number { + return this.cache.size; + } +} + +export class CanvasOptimizer { + private static readonly BATCH_SIZE = 10; + private pendingOperations: (() => void)[] = []; + private rafId: number | null = null; + + batchOperation(operation: () => void): void { + this.pendingOperations.push(operation); + + if (this.pendingOperations.length >= CanvasOptimizer.BATCH_SIZE) { + this.flush(); + } else if (!this.rafId) { + this.rafId = requestAnimationFrame(() => this.flush()); + } + } + + private flush(): void { + if (this.rafId) { + cancelAnimationFrame(this.rafId); + this.rafId = null; + } + + const operations = this.pendingOperations.splice(0); + operations.forEach(operation => operation()); + } + + cancel(): void { + if (this.rafId) { + cancelAnimationFrame(this.rafId); + this.rafId = null; + } + this.pendingOperations = []; + } +} + +// Utility functions +export const measurePerformance = any>( + func: T, + label?: string +): T => { + return ((...args: Parameters) => { + const monitor = PerformanceMonitor.getInstance(); + const timingLabel = label || func.name || 'anonymous'; + + monitor.startTiming(timingLabel); + const result = func(...args); + monitor.endTiming(timingLabel); + + return result; + }) as T; +}; + +export const createPerformanceLogger = (label: string) => { + const monitor = PerformanceMonitor.getInstance(); + + return { + start: () => monitor.startTiming(label), + end: () => monitor.endTiming(label), + getAverage: () => monitor.getAverageTime(label), + }; +}; + +export const optimizeCanvasRendering = (canvas: HTMLCanvasElement) => { + const ctx = canvas.getContext('2d'); + if (!ctx) return; + + // Enable hardware acceleration + ctx.imageSmoothingEnabled = true; + ctx.imageSmoothingQuality = 'high'; + + // Optimize for performance + ctx.lineCap = 'round'; + ctx.lineJoin = 'round'; +}; + +export const getDevicePixelRatio = (): number => { + return window.devicePixelRatio || 1; +}; + +export const createHighDPICanvas = ( + width: number, + height: number +): HTMLCanvasElement => { + const canvas = document.createElement('canvas'); + const ratio = getDevicePixelRatio(); + + canvas.width = width * ratio; + canvas.height = height * ratio; + canvas.style.width = `${width}px`; + canvas.style.height = `${height}px`; + + const ctx = canvas.getContext('2d'); + if (ctx) { + ctx.scale(ratio, ratio); + } + + return canvas; +};