A modular, Webpack-powered version of the WTR Lab Term Replacer userscript. Features a dual-build system for performance and GreasyFork compliance, hot-reloading for development, and a modern, maintainable JavaScript codebase.
WTR Lab Term Replacer is an advanced userscript that enhances the reading experience on WTR-Lab.com by providing intelligent text replacement functionality. The project has been refactored from a monolithic structure to a modern modular architecture using Webpack 5, enabling better maintainability, testability, and development workflow.
- ποΈ Modular Architecture: Clean separation of concerns with ES6 modules
- β‘ Dual Build System: Optimized builds for performance and GreasyFork compatibility
- π₯ Hot Module Replacement: Real-time development with webpack-dev-server
- π§ Modern JavaScript: ES6+ features with Babel transpilation
- π± Responsive UI: Mobile-first design with Bootstrap CSS variables
- π‘οΈ Robust Error Handling: Comprehensive error recovery and logging
- π Multi-Script Coordination: Intelligent handling of script conflicts
- πΎ Advanced State Management: Persistent storage with session recovery
- Node.js (v14.0.0 or higher)
- npm (v6.0.0 or higher) or yarn
- Modern browser with userscript support
# Clone the repository
git clone https://github.com/MasuRii/wtr-lab-term-replacer-webpack.git
cd wtr-lab-term-replacer-webpack
# Install dependencies
npm install
# Start development server with hot reload
npm run dev
# Build for production
npm run buildsrc/
βββ index.js # Main entry point
βββ modules/
β βββ config.js # Configuration constants
β βββ engine.js # Core replacement engine
β βββ ui.js # User interface management
β βββ handlers.js # Event handlers and utilities
β βββ state.js # Global state management
β βββ storage.js # Data persistence layer
β βββ observer.js # DOM observation and content detection
β βββ duplicates.js # Duplicate detection algorithms
β βββ utils.js # Utility functions
The heart of the replacement system featuring:
- Intelligent text node traversal and aggregation
- Optimized pattern matching with regex compilation
- Conflict resolution for overlapping matches
- Robust error handling with retry mechanisms
Centralized state handling including:
- Global settings and user preferences
- Novel-specific configurations
- Session persistence and recovery
- Inter-module state synchronization
Responsive user interface with:
- Bootstrap-based responsive design
- Dynamic content rendering
- Modal dialogs and floating controls
- Mobile-optimized interactions
Data persistence featuring:
- GM_* API abstraction
- Cross-novel data isolation
- Backup and recovery mechanisms
- Import/export functionality
The project uses a sophisticated webpack configuration with multiple build targets:
# Development with hot reload
npm run dev
# Performance-optimized build
npm run build:performance
# GreasyFork-compatible build
npm run build:greasyfork
# Build all targets
npm run build- Base configuration shared across all builds
- Babel transpilation with
@babel/preset-env - Module resolution and bundling
- Development server with hot module replacement
- Source maps for debugging
- Optimized for rapid development
- Production-optimized bundle
- Minification and tree shaking
- Performance monitoring
- GreasyFork compliance optimizations
- Metadata header injection
- Content policy adherence
- ES6+ Modules: Use modern JavaScript module syntax
- Async/Await: Prefer over callbacks and promises
- Error Handling: Comprehensive try-catch blocks with meaningful messages
- Logging: Structured logging with configurable levels
- Documentation: JSDoc comments for complex functions
// Good: Clear module boundaries
export async function performReplacements(targetElement) {
// Implementation with proper error handling
}
// Good: Comprehensive error handling
try {
const result = await complexOperation();
return result;
} catch (error) {
log(globalSettings, 'Operation failed:', error);
throw new ProcessingError('Failed to perform replacements', error);
}- Immutable Updates: Always create new state objects
- Validation: Validate state transitions
- Persistence: Sync critical state to storage
- Recovery: Implement state recovery mechanisms
- Basic term replacement functionality
- Case-sensitive and case-insensitive matching
- Regular expression pattern support
- Whole word matching
- Import/export operations
- Duplicate detection
- Mobile responsiveness
- Error recovery scenarios
- Cross-novel data isolation
Enable detailed logging through the Tampermonkey menu:
Tampermonkey Menu β Toggle Logging
This provides comprehensive debugging information including:
- DOM manipulation tracking
- State change monitoring
- Performance metrics
- Error stack traces
- Pattern Compilation: Pre-compile regex patterns for repeated use
- Text Node Aggregation: Minimize DOM queries through intelligent batching
- Conflict Resolution: O(n log n) algorithm for overlap resolution
- Caching: Cache processed text nodes to avoid reprocessing
- WeakMap Usage: Leverage WeakMap for automatic garbage collection
- DOM Cleanup: Proper event listener removal
- Processing Queue: Limit concurrent operations to prevent memory bloat
- Lazy Loading: Defer non-critical operations
- Batch Operations: Group multiple storage operations
- Progressive Enhancement: Graceful degradation for slow networks
- Local Storage Only: No external data transmission
- Input Sanitization: Validate all user inputs
- XSS Prevention: Escape output in dynamic content
- CSP Compliance: Compatible with Content Security Policy
- Minimal Permissions: Only request necessary browser permissions
- Safe DOM Manipulation: Avoid dangerous innerHTML usage
- Event Handler Security: Sanitize event data
- Storage Validation: Validate all stored data
- Clean Build: Remove previous build artifacts
- Dependency Check: Verify all dependencies are resolved
- Code Quality: Run linting and type checks
- Bundle Optimization: Apply production optimizations
- Metadata Injection: Add userscript headers
- Validation: Verify build output integrity
- Version Bump: Update version in package.json
- Changelog Update: Document changes in CHANGELOG.md
- Build Verification: Test both build targets
- Documentation Update: Ensure README is current
- Tag Release: Create Git tag for the version
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes following the coding guidelines
- Test thoroughly across different scenarios
- Commit with clear messages:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Submit a pull request
- Clear PR Description: Explain the feature/fix and testing performed
- Code Quality: Follow existing patterns and maintain consistency
- Documentation: Update relevant documentation for new features
- Testing: Include manual testing scenarios in PR description
- Backward Compatibility: Maintain compatibility with existing userscripts
When reporting bugs, include:
- Browser and version information
- Steps to reproduce the issue
- Expected vs actual behavior
- Console error messages (if any)
- Screenshot or screen recording if relevant
Executes term replacement on a DOM element.
// Parameters
targetElement: HTMLElement - The DOM element to process
// Returns
Promise<void> - Resolves when processing is completeInitializes the user interface.
// Returns
void - UI is appended to document bodyProcesses term creation/updates.
// Parameters
None - Reads from form elements
// Returns
Promise<void> - Resolves when term is savedArray of term definitions for the current novel.
Configuration object including:
isDisabled: Boolean - Master enable/disable switch- Other novel-specific settings
Global configuration including:
isLoggingEnabled: Boolean - Enable detailed logging
- Large Novels: Very large term lists (>1000 terms) may experience slower performance
- Mobile Safari: Some users report issues with text selection on iOS Safari
- Multiple Scripts: In rare cases, conflicts with other userscripts may occur
The v5.4 release includes breaking changes:
- Data Format: Updated to v5.4 format for improved compatibility
- Storage Keys: Changed to use novel slug-based isolation
- API Changes: Some internal APIs have been refactored for better performance
- Backup Data: Export all terms before updating
- Clean Install: Remove old script version
- Install v5.4: Install the new version
- Import Data: Use the import feature to restore your terms
This project is licensed under the MIT License - see the LICENSE file for details.
- WTR-Lab.com: The platform that inspired this enhancement
- Webpack Community: For the excellent build tooling
- Contributors: All developers who have contributed to the project
- Users: The community providing feedback and bug reports
- GitHub Issues: Report bugs and request features
- Documentation: This README and inline code comments
- Community: WTR-Lab.com community forums
Happy coding! π
This project is actively maintained and welcomes contributions from the developer community.