Skip to content

Latest commit

 

History

History
302 lines (243 loc) · 8.65 KB

File metadata and controls

302 lines (243 loc) · 8.65 KB

Architecture

This document describes the internal structure and organization of the rect-utils library.

Project Structure

rect-utils/
├── src/                      # Source code
│   ├── types.ts              # TypeScript type definitions
│   ├── internal/             # Internal utilities (not exported)
│   │   └── helpers.ts        # Helper functions (fromLTRB, getLeft, etc.)
│   ├── ops.ts                # RectOps namespace - creation & validation
│   ├── compare.ts            # RectCompare namespace - comparison operations
│   ├── transform.ts          # RectTransform namespace - transformations
│   ├── geometry.ts           # RectGeometry namespace - geometric calculations
│   ├── border.ts             # RectBorder namespace - border operations
│   ├── split.ts              # RectSplit namespace - splitting operations
│   └── index.ts              # Main entry point (exports all namespaces)
│
├── tests/                    # Test files (Node.js Test Runner)
│   ├── rect-ops.test.ts
│   ├── rect-compare.test.ts
│   ├── rect-transform.test.ts
│   ├── rect-geometry.test.ts
│   ├── rect-border.test.ts
│   └── rect-split.test.ts
│
├── docs/                     # Documentation
│   ├── API.md                # Complete API reference
│   ├── EXAMPLES.md           # Practical usage examples
│   └── ARCHITECTURE.md       # This file
│
├── scripts/                  # Build and utility scripts
│   └── test.sh               # Test runner script
│
├── .github/                  # GitHub configuration
│   ├── workflows/            # CI/CD workflows
│   │   ├── ci.yml            # Continuous integration
│   │   ├── publish.yml       # NPM publishing
│   │   └── codeql.yml        # Security analysis
│   └── ISSUE_TEMPLATE/       # Issue templates
│
├── package.json              # NPM package configuration
├── tsconfig.json             # TypeScript configuration
├── .eslintrc.json            # ESLint configuration
├── .npmrc                    # NPM configuration
├── README.md                 # Main documentation
├── LICENSE                   # MIT License
├── CHANGELOG.md              # Version history
├── CONTRIBUTING.md           # Contribution guidelines
└── example.ts                # Usage examples

Module Organization

The library is organized into focused namespaces, each in its own file:

Core Modules

types.ts

Defines all TypeScript interfaces and enums:

  • Point - 2D point with x, y coordinates
  • Rectangle - Rectangle with position and dimensions
  • Size - Width and height
  • Margins / Padding - Spacing on all sides
  • ContentAlignment - Alignment options enum

internal/helpers.ts

Internal utility functions (not exported publicly):

  • fromLTRB() - Create rectangle from left, top, right, bottom
  • getLeft(), getTop(), getRight(), getBottom() - Extract bounds
  • compareDoubles() - Floating point comparison with epsilon
  • DEFAULT_EPSILON - Default tolerance for comparisons

Namespace Modules

Each namespace is self-contained in its own file:

ops.ts - RectOps

Basic rectangle operations:

  • Creation (create, fromPoints)
  • Validation (validate)
  • Conversion (ceiling, inflateToInteger, snap)

compare.ts - RectCompare

Comparison and containment:

  • Equality checks (equals, isEmpty, isEmptySize)
  • Intersection (intersects, intersect)
  • Containment (contains, containsPoint, containsX, containsY)
  • Set operations (unionNonEmpty, isEqualArray)

transform.ts - RectTransform

Transformation operations:

  • Expansion/contraction (inflate, deflate)
  • Movement (offset, offsetByPoint)
  • Alignment (align)
  • Cropping calculation (calcCropping)

geometry.ts - RectGeometry

Geometric calculations:

  • Center point (center)
  • Corner points (topLeft, topRight, bottomLeft, bottomRight)

border.ts - RectBorder

Border and side operations:

  • Side extraction (getTopSide, getBottomSide, getLeftSide, getRightSide)
  • Boundary modification (setLeft, setRight)
  • Cutting (cutFromTop, cutFromBottom, cutFromLeft, cutFromRight)
  • Expansion (expandToTop, expandToBottom, expandToLeft, expandToRight)

split.ts - RectSplit

Rectangle division:

  • Horizontal splitting (horizontal)
  • Vertical splitting (vertical)

Design Principles

1. Functional Programming

All functions are pure - they don't modify input parameters and always return new objects.

// ✅ Good - returns new rectangle
const moved = RectTransform.offset(rect, 10, 20);

// ❌ Bad - would modify original (not used in this library)
rect.offset(10, 20);

2. Namespace Organization

Functions are grouped into logical namespaces similar to lodash:

import { RectOps, RectCompare } from 'rect-utils';

const rect = RectOps.create(0, 0, 100, 100);
const isEmpty = RectCompare.isEmpty(rect);

3. Type Safety

Full TypeScript support with strict typing:

interface Rectangle {
  x: number;
  y: number;
  width: number;
  height: number;
}

4. Tree-Shaking Support

Modular structure allows bundlers to eliminate unused code:

// Only imports RectOps module
import { RectOps } from 'rect-utils';

5. Zero Dependencies

No runtime dependencies - only dev dependencies for building and testing.

Testing Strategy

Test Framework

Uses Node.js built-in Test Runner (Node 18+) with TypeScript support via tsx:

  • No external test framework dependencies
  • Native Node.js testing capabilities
  • Fast execution

Test Organization

Each namespace has its own test file:

  • tests/rect-ops.test.ts
  • tests/rect-compare.test.ts
  • tests/rect-transform.test.ts
  • tests/rect-geometry.test.ts
  • tests/rect-border.test.ts
  • tests/rect-split.test.ts

Running Tests

npm test              # Run all tests
npm run test:single   # Run specific test file

Build Process

TypeScript Compilation

npm run build

Compiles TypeScript to JavaScript with:

  • ES2020 target
  • CommonJS modules
  • Type declarations (.d.ts files)
  • Output to dist/ directory

Linting

npm run lint          # Check for issues
npm run lint:fix      # Auto-fix issues

Uses ESLint with TypeScript support.

CI/CD Pipeline

Continuous Integration (.github/workflows/ci.yml)

Runs on every push and pull request:

  1. Install dependencies
  2. Run linter
  3. Build project
  4. Run tests
  5. Test on Node.js 16, 18, 20

Publishing (.github/workflows/publish.yml)

Automatically publishes to NPM on release:

  1. Run CI checks
  2. Build project
  3. Publish to NPM registry

Security (.github/workflows/codeql.yml)

Weekly CodeQL security analysis.

Import Patterns

For Library Users

// Import everything from main entry
import { RectOps, RectCompare, Rectangle } from 'rect-utils';

// Or import specific namespaces
import { RectOps } from 'rect-utils';

For Development

// Import from specific modules
import { RectOps } from './src/ops';
import { RectCompare } from './src/compare';

Adding New Features

1. Add to Appropriate Namespace

Choose the correct module based on functionality:

  • Creation/validation → ops.ts
  • Comparison → compare.ts
  • Transformation → transform.ts
  • Geometry → geometry.ts
  • Borders → border.ts
  • Splitting → split.ts

2. Add Tests

Create tests in corresponding test file:

describe('NewFeature', () => {
  it('should do something', () => {
    // Test implementation
  });
});

3. Update Documentation

  • Add to API.md
  • Add example to EXAMPLES.md if applicable
  • Update README.md if it's a major feature

4. Export from index.ts

Ensure the namespace is exported from src/index.ts.

Performance Considerations

Immutability

All operations return new objects, which:

  • ✅ Prevents bugs from shared state
  • ✅ Enables functional composition
  • ⚠️ Creates garbage for GC (minimal impact for typical use)

Epsilon Comparisons

Floating-point comparisons use epsilon tolerance:

const DEFAULT_EPSILON = 1e-10;

This prevents issues with floating-point precision.

No Dependencies

Zero runtime dependencies means:

  • Smaller bundle size
  • Faster installation
  • No security vulnerabilities from dependencies
  • Better tree-shaking

Version History

See CHANGELOG.md for detailed version history.

Contributing

See CONTRIBUTING.md for contribution guidelines.