Skip to content

Refactor: Extract constants, improve code quality, and fix bugs#2

Open
duxor wants to merge 3 commits intomasterfrom
claude/application-audit-9Slrk
Open

Refactor: Extract constants, improve code quality, and fix bugs#2
duxor wants to merge 3 commits intomasterfrom
claude/application-audit-9Slrk

Conversation

@duxor
Copy link
Copy Markdown
Owner

@duxor duxor commented Mar 22, 2026

Summary

This PR refactors the codebase to improve maintainability, fix several bugs, and enhance code quality through constant extraction, code deduplication, and better error handling.

Key Changes

Constants & Configuration

  • Extracted 20+ magic numbers and regex patterns into named module-level constants (MIN_DRAFT_TEXT_LENGTH, DEBOUNCE_DELAY_MS, SCHEDULE_TIME_PATTERNS, etc.)
  • Created shared day/month name arrays and pattern builders to eliminate duplication between hasScheduleableContent() and extractScheduledTime()
  • Added DRAFTCRAFT_DEBUG and BG_DEBUG flags for conditional logging

Bug Fixes

  • Fixed scheduled drafts count in popup: Now correctly displays stats.scheduledDrafts instead of stats.totalDrafts
  • Fixed MutationObserver memory leak: Added proper disconnect() method and cleanup on observer lifecycle
  • Improved debouncing: Added _debounceTimer to prevent excessive DOM processing during rapid mutations
  • Removed duplicate initialization: Eliminated redundant handleInstallation() call in background script constructor

Code Quality Improvements

  • Reduced duplication in popup.js: Created generic _toggleSetting() and _sendToActiveTab() helper methods to consolidate 6 nearly-identical toggle handlers
  • Extracted helper methods: Added _to24Hour() and _daysUntilDay() for time conversion logic
  • Improved DOM selector robustness: Removed fragile auto-generated class selectors (.x1n2onr6), now relies on semantic [role="dialog"] attributes
  • Moved styles to CSS: Replaced inline style attributes with CSS classes (.threads-draftcraft-status-label, .threads-draftcraft-time-info, etc.)
  • Removed console logging: Replaced verbose console.log() calls with conditional debugLog() and bgLog() functions

Accessibility Enhancements

  • Added role="region" and aria-label attributes to popup sections
  • Added role="status" to draft statistics elements
  • Added CSS classes for better styling control and dark mode support

Security & Manifest

  • Removed overly-permissive web_accessible_resources declaration (was exposing entire content/* directory)
  • Simplified manifest to only declare necessary resources

Performance

  • Added debouncing to MutationObserver callbacks (150ms delay) to reduce excessive DOM queries
  • Optimized dialog mutation detection to skip extension-generated elements more efficiently

Implementation Details

  • Constants are defined at module level for easy maintenance and reuse
  • Helper methods use underscore prefix convention (_to24Hour, _daysUntilDay) to indicate internal use
  • Debouncing uses clearTimeout() before setting new timer to prevent race conditions
  • CSS classes follow existing naming convention: .threads-draftcraft-*

https://claude.ai/code/session_01Na7TPMpUpohXy29azuD8fD

claude added 3 commits March 21, 2026 22:42
Detailed security, performance, code quality, and architecture audit
covering all 3,830 lines of the Threads DraftCraft Chrome extension.

https://claude.ai/code/session_01Na7TPMpUpohXy29azuD8fD
Security:
- Replace all innerHTML usage with safe DOM API (createElement/textContent)
- Remove web_accessible_resources exposing content/ directory
- Replace console.log/error with debug-flag-guarded logging

Bugs:
- Fix random-based scheduling causing unstable sort (now deterministic)
- Fix scheduledDrafts count showing totalDrafts instead of scheduled count
- Fix MutationObserver never disconnecting (memory leak)
- Fix daysUntil=0 edge case (same day now maps to next week)
- Fix double initialization in background.js (remove redundant handleInstallation)
- Fix collectScheduledByDate() called inside loop (compute once outside)

Performance:
- Add debounce to MutationObserver processing (150ms)
- Remove fragile .x1n2onr6 CSS selector, use only [role="dialog"]
- Simplify extension mutation detection with className.includes()

Code quality:
- Extract shared regex patterns to module-level constants
- Extract magic numbers into named constants
- Refactor 6 duplicated toggle handlers into generic _toggleSetting()
- Move all inline styles to CSS classes
- Add _to24Hour() and _daysUntilDay() helper methods
- Add _matchesDayNamePattern() shared helper

Accessibility:
- Add aria-label to all toggle inputs and select
- Add role="alert" to error messages, role="status" to success/stats
- Add aria-label to close buttons
- Add role="region" with aria-label to sections
- Add aria-hidden to decorative icons

https://claude.ai/code/session_01Na7TPMpUpohXy29azuD8fD
Bugs fixed:
- Add return true to message listener for async response support
- Add ping handler for background script content script detection
- Fix index=-1 producing wrong scheduling times (new _safeElementIndex helper)
- Fix unstable sort for equal timestamps (tiebreaker by originalOrder)
- Add missing showDateDivider to background.js getSettings() defaults
- Add Date validity check (isNaN) after Date construction
- Fix logError missing .catch() on promise chain, simplify with slice(-50)
- Add _daysUntilDay input validation for out-of-range day indices

Performance:
- Combine 4 querySelectorAll calls into single selector in removeExistingEnhancements
- Reuse getDateKey() in addDateDividers instead of inline string construction

Code quality:
- Remove dead code: unreachable m===60 check, commented-out console.log block
- Simplify randomNonZeroMinute to one-liner

Robustness:
- Add document.contains() check before DOM operations in reorderDraftElements
- Add ARIA labels to dynamically created time indicators
- Add tabindex and aria-live to popup error/success messages for focus management
- Add focus() call on error message display

https://claude.ai/code/session_01Na7TPMpUpohXy29azuD8fD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants