### React Integration Example for Pixel Editor Source: https://context7.com/curtishughes/pixel-editor/llms.txt This example demonstrates how to integrate the PixelEditor library into a React application using hooks. It initializes the editor, manages tool selection, color changes, and undo/redo functionality. ```tsx import React, { useRef, useEffect, useState } from 'react'; import { PixelEditor, Pencil, Rectangle, Line, Tool } from '@curtishughes/pixel-editor'; function PixelEditorApp() { const canvasRef = useRef(null); const [editor, setEditor] = useState(null); const [currentColor, setCurrentColor] = useState('black'); useEffect(() => { if (canvasRef.current && !editor) { const newEditor = new PixelEditor( canvasRef.current, 64, 64, new Pencil('black') ); setEditor(newEditor); } }, [editor]); const selectTool = (ToolClass: new (color: string) => Tool) => { if (editor) { editor.tool = new ToolClass(currentColor); } }; return (
{ setCurrentColor(e.target.value); if (editor) editor.tool = new Pencil(e.target.value); }} />
); } export default PixelEditorApp; ``` -------------------------------- ### Set Up Pixel Editor Project with Yarn Source: https://github.com/curtishughes/pixel-editor/blob/master/CONTRIBUTING.md Instructions for cloning the Pixel Editor repository, setting up remotes, and installing project dependencies using Yarn. This is a foundational step for development. ```bash # Clone your fork of the repo into the current directory $ git clone https://github.com//pixel-editor # Navigate to the newly cloned directory $ cd pixel-editor # Assign the original repo to a remote called "upstream" $ git remote add upstream https://github.com/CurtisHughes/pixel-editor # Install the dependencies $ yarn ``` -------------------------------- ### Install Pixel Editor with Yarn Source: https://github.com/curtishughes/pixel-editor/blob/master/README.md Installs the Pixel Editor package using the Yarn package manager. This is a common method for adding project dependencies in Node.js environments. ```bash yarn add @curtishughes/pixel-editor ``` -------------------------------- ### Tool Interface: Creating Custom Drawing Tools Source: https://context7.com/curtishughes/pixel-editor/llms.txt Shows how to implement the Tool interface to create custom drawing tools for the Pixel Editor. The example demonstrates a Flood Fill tool, including its constructor and the required event handler methods (handlePointerDown, handlePointerMove, handlePointerUp). ```typescript import { Tool, Point, Color, Pixel } from '@curtishughes/pixel-editor'; import PixelEditor from '@curtishughes/pixel-editor'; // Custom flood fill tool example class FloodFill implements Tool { constructor(private fillColor: Color) {} handlePointerDown(position: Point, editor: PixelEditor): void { const targetPixel = editor.get(position.x, position.y); const targetColor = targetPixel.color; if (targetColor === this.fillColor) return; const pixelsToFill: Pixel[] = []; const visited = new Set(); const stack: Point[] = [position]; while (stack.length > 0) { const { x, y } = stack.pop()!; const key = `${x},${y}`; if (visited.has(key)) continue; if (x < 0 || x >= editor.width || y < 0 || y >= editor.height) continue; const current = editor.get(x, y); if (current.color !== targetColor) continue; visited.add(key); pixelsToFill.push({ x, y, color: this.fillColor }); stack.push({ x: x + 1, y }); stack.push({ x: x - 1, y }); stack.push({ x, y: y + 1 }); stack.push({ x, y: y - 1 }); } editor.set(pixelsToFill); } handlePointerMove(position: Point, editor: PixelEditor): void { // No action on move for flood fill } handlePointerUp(position: Point, editor: PixelEditor): void { // No action on up for flood fill } } // Use the custom tool const canvas = document.getElementById('editor') as HTMLCanvasElement; const editor = new PixelEditor(canvas, 64, 64, new FloodFill('red')); ``` -------------------------------- ### Install Pixel Editor with NPM Source: https://github.com/curtishughes/pixel-editor/blob/master/README.md Installs the Pixel Editor package using the NPM package manager. This command is used to add the package as a dependency to your project. ```bash npm install @curtishughes/pixel-editor ``` -------------------------------- ### Utility Functions: getLine and getLineWithColor Source: https://context7.com/curtishughes/pixel-editor/llms.txt Demonstrates the use of utility functions getLine and getLineWithColor, which implement Bresenham's line algorithm to generate pixel coordinates. Examples show generating lines with and without color, and a custom pixel generation function. ```typescript import { getLine, getLineWithColor } from '@curtishughes/pixel-editor'; // Generate line coordinates without color const linePixels = getLine(0, 0, 10, 5); // Returns: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 1 }, ...] // Generate line coordinates with color const coloredLine = getLineWithColor(0, 0, 10, 5, 'blue'); // Returns: [{ x: 0, y: 0, color: 'blue' }, { x: 1, y: 0, color: 'blue' }, ...] // Custom pixel generation function const customLine = getLine(0, 0, 10, 10, (x, y) => ({ x, y, color: x % 2 === 0 ? 'red' : 'blue' // Alternating colors })); ``` -------------------------------- ### PixelCollection Class: Efficient Pixel Data Storage Source: https://context7.com/curtishughes/pixel-editor/llms.txt Illustrates the usage of the PixelCollection class for efficient storage and retrieval of pixel data. It covers creating a collection, setting and getting pixel colors, clearing pixels, and iterating over all stored pixels. ```typescript import { PixelCollection } from '@curtishughes/pixel-editor'; // Create a collection with width for index calculation const pixels = new PixelCollection(64); // Set a pixel pixels.set({ x: 10, y: 5, color: 'red' }); // Get a pixel's color (returns undefined if not set) const color = pixels.get(10, 5); // 'red' const empty = pixels.get(0, 0); // undefined // Clear a pixel by setting without color pixels.set({ x: 10, y: 5 }); // Removes the pixel // Iterate over all pixels for (const pixel of pixels) { console.log(`Pixel at (${pixel.x}, ${pixel.y}): ${pixel.color}`); } ``` -------------------------------- ### Use Line Tool for Drawing Straight Lines Source: https://context7.com/curtishughes/pixel-editor/llms.txt Describes the Line tool, which draws straight lines between two points. It supports setting a start point, dragging for a preview, and finalizing the line. The tool utilizes Bresenham's line algorithm for precise rendering. It can also function as an eraser line. ```typescript import { PixelEditor, Line } from '@curtishughes/pixel-editor'; const canvas = document.getElementById('editor') as HTMLCanvasElement; const lineTool = new Line('black'); const editor = new PixelEditor(canvas, 64, 64, lineTool); // Create lines with different colors editor.tool = new Line('red'); editor.tool = new Line('#0000ff'); // Line tool without color acts as an eraser line editor.tool = new Line(); ``` -------------------------------- ### Get Line Utility Function Source: https://github.com/curtishughes/pixel-editor/blob/master/docs/index.html Generates a list of pixels representing a line between two points. It accepts optional parameters for custom pixel generation. ```TypeScript /** * Generates a list of pixels representing a line between two points. * @param x0 The starting x-coordinate. * @param y0 The starting y-coordinate. * @param x1 The ending x-coordinate. * @param y1 The ending y-coordinate. * @param fn Optional function to generate each pixel. Defaults to creating a Pixel object with x and y coordinates. * @returns An array of Pixel objects representing the line. */ const getLine = (x0: number, y0: number, x1: number, y1: number, fn: (x: number, y: number) => Pixel = (x, y) => ({ x, y })): Pixel[] => { // Implementation details for line generation const pixels: Pixel[] = []; const dx = Math.abs(x1 - x0); const dy = Math.abs(y1 - y0); const sx = x0 < x1 ? 1 : -1; const sy = y0 < y1 ? 1 : -1; let err = dx - dy; let x = x0; let y = y0; while (true) { pixels.push(fn(x, y)); if (x === x1 && y === y1) break; const e2 = 2 * err; if (e2 > -dy) { err -= dy; x += sx; } if (e2 < dx) { err += dx; y += sy; } } return pixels; }; ``` -------------------------------- ### Get Line With Color Utility Function Source: https://github.com/curtishughes/pixel-editor/blob/master/docs/index.html Generates a list of pixels representing a line between two points, with an optional specified color. If no color is provided, pixels will have an undefined color. ```TypeScript /** * Generates a list of pixels representing a line between two points, with an optional specified color. * @param x0 The starting x-coordinate. * @param y0 The starting y-coordinate. * @param x1 The ending x-coordinate. * @param y1 The ending y-coordinate. * @param color Optional color for the pixels. * @returns An array of Pixel objects representing the line with the specified color. */ const getLineWithColor = (x0: number, y0: number, x1: number, y1: number, color?: Color): Pixel[] => { // Reuses getLine to generate pixels and applies the color return getLine(x0, y0, x1, y1, (x, y) => ({ x, y, color })); }; ``` -------------------------------- ### Initialize PixelEditor and Manage Pixels Source: https://context7.com/curtishughes/pixel-editor/llms.txt Demonstrates how to initialize the main PixelEditor class with a canvas element, dimensions, and a default tool. Shows how to access pixel data, programmatically set pixels, and switch drawing tools. Includes basic undo/redo and clear operations. ```typescript import { PixelEditor, Pencil, Rectangle, Line } from '@curtishughes/pixel-editor'; // Create a canvas element and initialize the editor const canvas = document.getElementById('editor') as HTMLCanvasElement; const pencilTool = new Pencil('black'); const editor = new PixelEditor(canvas, 64, 64, pencilTool); // Access editor properties console.log(editor.width); // 64 console.log(editor.height); // 64 // Get all current pixels on the canvas const allPixels = editor.pixels; // Returns: [{ x: 10, y: 5, color: 'black' }, { x: 11, y: 5, color: 'black' }, ...] // Get a specific pixel const pixel = editor.get(10, 5); // Returns: { x: 10, y: 5, color: 'black' } or { x: 10, y: 5, color: undefined } // Programmatically set pixels editor.set([ { x: 0, y: 0, color: 'red' }, { x: 1, y: 0, color: 'green' }, { x: 2, y: 0, color: 'blue' } ]); // Set pixels without logging to history (useful for custom tools) editor.set([{ x: 5, y: 5, color: 'purple' }], false); // Switch tools dynamically editor.tool = new Rectangle('blue'); editor.tool = new Line('green'); editor.tool = new Pencil(); // No color = eraser mode // Undo/Redo operations editor.undo(); editor.redo(); // Clear all pixels from the canvas editor.clear(); ``` -------------------------------- ### Run Project Linting with Yarn Source: https://github.com/curtishughes/pixel-editor/blob/master/CONTRIBUTING.md Command to execute the linting process for the Pixel Editor project using Yarn. Linting helps maintain code quality and consistency. ```bash yarn lint ``` -------------------------------- ### Run Project Tests with Yarn Source: https://github.com/curtishughes/pixel-editor/blob/master/CONTRIBUTING.md Command to execute the test suite for the Pixel Editor project using Yarn. Running tests ensures the project's functionality and stability. ```bash yarn test ``` -------------------------------- ### Build Project with Yarn Source: https://github.com/curtishughes/pixel-editor/blob/master/CONTRIBUTING.md Command to build the Pixel Editor project using Yarn. This command compiles the project's code for deployment or distribution. ```bash yarn build ``` -------------------------------- ### Tool Interface Methods Source: https://github.com/curtishughes/pixel-editor/blob/master/docs/interfaces/tool.html Documentation for the methods available in the Tool interface, used for handling user interactions within the pixel editor. ```APIDOC ## Tool Interface ### Description The Tool interface defines the core methods for handling user input events like pointer down, move, and up within the Pixel Editor. ### Methods #### handlePointerDown ##### Description Handles the pointer down event, initiating an action based on the current tool. ##### Method (Implicitly called by the editor) ##### Parameters - **position** (Point) - The coordinates where the pointer event occurred. - **editor** (PixelEditor) - The PixelEditor instance to interact with. ##### Returns void #### handlePointerMove ##### Description Handles the pointer move event, typically used for drawing or dragging operations. ##### Method (Implicitly called by the editor) ##### Parameters - **position** (Point) - The current coordinates of the pointer. - **editor** (PixelEditor) - The PixelEditor instance to interact with. ##### Returns void #### handlePointerUp ##### Description Handles the pointer up event, finalizing an action or tool usage. ##### Method (Implicitly called by the editor) ##### Parameters - **position** (Point) - The coordinates where the pointer event was released. - **editor** (PixelEditor) - The PixelEditor instance to interact with. ##### Returns void ``` -------------------------------- ### Initialize Pixel Editor in Vue Source: https://github.com/curtishughes/pixel-editor/blob/master/README.md Shows how to integrate the Pixel Editor into a Vue.js application using the Vue property decorator. It initializes the editor in the `mounted` hook and provides basic controls for tool selection and history management. ```vue ``` -------------------------------- ### Initialize Pixel Editor in React Source: https://github.com/curtishughes/pixel-editor/blob/master/README.md Demonstrates how to initialize and use the Pixel Editor within a React application. It utilizes `useRef` for canvas access and `useState` to manage the editor instance, allowing for dynamic tool changes and history manipulation. ```tsx import React, { useRef, useEffect, useState } from 'react'; import { PixelEditor, Pencil } from '@curtishughes/pixel-editor'; function App() { const editorRef = useRef(null); const [editor, setEditor] = useState(); useEffect(() => { if (editorRef.current) { setEditor(new PixelEditor(editorRef.current, 64, 64, new Pencil('black'))); } }, []); return ( <> ); } export default App; ``` -------------------------------- ### Rectangle Tool API Source: https://github.com/curtishughes/pixel-editor/blob/master/docs/classes/rectangle.html This section details the Rectangle tool, including its constructor, properties, and methods for handling pointer interactions. ```APIDOC ## Rectangle Tool Documentation ### Description The Rectangle tool allows users to draw rectangles on the pixel editor canvas. It manages the drawing state, including color, starting position, and dragging status. ### Class `Rectangle` ### Implements `Tool` ### Constructors #### constructor * **Description**: Initializes a new instance of the Rectangle tool. * **Method**: `new Rectangle(color: Color)` * **Parameters**: * `color` (Color) - The color to be used for drawing rectangles. * **Returns**: `Rectangle` - A new instance of the Rectangle tool. ### Properties #### color * **Description**: The color of the rectangle being drawn. * **Type**: `Color` * **Access**: Private #### dragging * **Description**: Indicates whether the user is currently dragging to draw a rectangle. * **Type**: `boolean` * **Default**: `false` * **Access**: Private #### startPosition * **Description**: The starting point of the rectangle drawing interaction. * **Type**: `Point` * **Access**: Private ### Methods #### handlePointerDown * **Description**: Handles the pointer down event to initiate rectangle drawing. * **Method**: `handlePointerDown(position: Point, editor: PixelEditor): void` * **Parameters**: * `position` (Point) - The coordinates where the pointer went down. * `editor` (PixelEditor) - The PixelEditor instance. * **Returns**: `void` #### handlePointerMove * **Description**: Handles the pointer move event to update the rectangle shape while drawing. * **Method**: `handlePointerMove(position: Point, editor: PixelEditor): void` * **Parameters**: * `position` (Point) - The current coordinates of the pointer. * `editor` (PixelEditor) - The PixelEditor instance. * **Returns**: `void` #### handlePointerUp * **Description**: Handles the pointer up event to finalize the rectangle drawing. * **Method**: `handlePointerUp(): void` * **Returns**: `void` ### Source Location * `tools/Rectangle.ts` ``` -------------------------------- ### Link Pixel Editor Locally to UI Project Source: https://github.com/curtishughes/pixel-editor/blob/master/CONTRIBUTING.md Commands to link the local Pixel Editor package into a separate UI project using Yarn's link functionality. This allows for seamless local development and testing between the library and its consumers. ```bash # from @curtishughes/pixel-editor yarn link ``` ```bash # from UI project yarn link @curtishughes/pixel-editor ``` -------------------------------- ### Enable Automatic Rebuilds with Yarn Watch Source: https://github.com/curtishughes/pixel-editor/blob/master/CONTRIBUTING.md Command to run the Pixel Editor project in watch mode using Yarn. This automatically rebuilds the project whenever file changes are detected, streamlining the development workflow. ```bash yarn watch ``` -------------------------------- ### Assigning a Custom Tool Source: https://github.com/curtishughes/pixel-editor/blob/master/README.md Illustrates how to assign a custom tool to the Pixel Editor. After implementing the `Tool` interface, an instance of the custom tool can be directly assigned to the `editor.tool` property. ```typescript editor.tool = new CustomTool(); ``` -------------------------------- ### Pencil Tool API Source: https://github.com/curtishughes/pixel-editor/blob/master/docs/classes/pencil.html Documentation for the Pencil class, which implements the Tool interface for drawing pixels. ```APIDOC ## Class Pencil ### Description Represents a Pencil tool for drawing pixels in the Pixel Editor. ### Implements * [Tool](../interfaces/tool.html) ### Constructors #### constructor * `new Pencil(color?: Color): Pencil` * Initializes a new instance of the Pencil class. * **Parameters** * `color` (Color) - Optional. The color to be used by the pencil. * **Returns** `Pencil` ### Properties #### color * `color: Color` * The current color of the pencil. * **Visibility**: Private Optional #### dragging * `dragging: boolean` * Indicates whether the pencil is currently being dragged. * **Default value**: `false` * **Visibility**: Private #### prevPosition * `prevPosition: Point` * Stores the previous position of the pointer. * **Visibility**: Private ### Methods #### handlePointerDown * `handlePointerDown(position: Point, editor: PixelEditor): void` * Handles the pointer down event to start drawing. * **Parameters** * `position` (Point) - The starting position of the pointer. * `editor` (PixelEditor) - The PixelEditor instance. * **Returns** `void` #### handlePointerMove * `handlePointerMove(position: Point, editor: PixelEditor): void` * Handles the pointer move event to draw lines. * **Parameters** * `position` (Point) - The current position of the pointer. * `editor` (PixelEditor) - The PixelEditor instance. * **Returns** `void` #### handlePointerUp * `handlePointerUp(): void` * Handles the pointer up event to stop drawing. * **Returns** `void` ``` -------------------------------- ### Tool Interface - Creating Custom Tools Source: https://context7.com/curtishughes/pixel-editor/llms.txt Implement the Tool interface to create custom drawing tools. Each tool must handle pointer down, move, and up events. ```APIDOC ## Tool Interface Implement the `Tool` interface to create custom drawing tools. Each tool must handle pointer down, move, and up events. ### Interface Methods - `handlePointerDown(position: Point, editor: PixelEditor): void`: Called when the pointer button is pressed down. - `handlePointerMove(position: Point, editor: PixelEditor): void`: Called when the pointer is moved while the button is pressed. - `handlePointerUp(position: Point, editor: PixelEditor): void`: Called when the pointer button is released. ### Example: Flood Fill Tool ```typescript import { Tool, Point, Color, Pixel } from '@curtishughes/pixel-editor'; import PixelEditor from '@curtishughes/pixel-editor'; class FloodFill implements Tool { constructor(private fillColor: Color) {} handlePointerDown(position: Point, editor: PixelEditor): void { const targetPixel = editor.get(position.x, position.y); const targetColor = targetPixel.color; if (targetColor === this.fillColor) return; const pixelsToFill: Pixel[] = []; const visited = new Set(); const stack: Point[] = [position]; while (stack.length > 0) { const { x, y } = stack.pop()!; const key = `${x},${y}`; if (visited.has(key)) continue; if (x < 0 || x >= editor.width || y < 0 || y >= editor.height) continue; const current = editor.get(x, y); if (current.color !== targetColor) continue; visited.add(key); pixelsToFill.push({ x, y, color: this.fillColor }); stack.push({ x: x + 1, y }); stack.push({ x: x - 1, y }); stack.push({ x, y: y + 1 }); stack.push({ x, y: y - 1 }); } editor.set(pixelsToFill); } handlePointerMove(position: Point, editor: PixelEditor): void { // No action on move for flood fill } handlePointerUp(position: Point, editor: PixelEditor): void { // No action on up for flood fill } } // Use the custom tool const canvas = document.getElementById('editor') as HTMLCanvasElement; const editor = new PixelEditor(canvas, 64, 64, new FloodFill('red')); ``` ``` -------------------------------- ### PixelEditor Touch Events Source: https://github.com/curtishughes/pixel-editor/blob/master/docs/classes/pixeleditor.html Handles touch events for the Pixel Editor, including touchstart, touchmove, and touchPosition. ```APIDOC ## Private touchmove ### Description Handles touch movement events within the pixel editor. ### Method `touchmove` ### Endpoint N/A (Internal method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "e": "TouchEvent" } ``` ### Response #### Success Response (200) Void #### Response Example None ## Private touchstart ### Description Handles the beginning of a touch interaction within the pixel editor. ### Method `touchstart` ### Endpoint N/A (Internal method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "e": "TouchEvent" } ``` ### Response #### Success Response (200) Void #### Response Example None ``` -------------------------------- ### Standard Git Commit Message Format Source: https://github.com/curtishughes/pixel-editor/blob/master/CONTRIBUTING.md Defines the structured format for Git commit messages used in the Pixel Editor project. This format, including type, scope, subject, body, and footer, is crucial for automated versioning and release management via semantic-release. ```git ():