Skip to content

Latest commit

 

History

History
382 lines (304 loc) · 9.55 KB

File metadata and controls

382 lines (304 loc) · 9.55 KB

Code Comments Documentation Guide

Overview

This document explains the inline comments added to index.html for new developer onboarding. Comments follow enterprise standards for clarity, maintainability, and team collaboration.


Comment Structure Standards

1. Major Section Headers

/* ============================================================================
 * SECTION TITLE
 * ============================================================================
 * Brief description of what this section does and why it exists.
 * 
 * Additional implementation details, gotchas, or important notes.
 * ========================================================================= */

Used for:

  • State variable declarations
  • Major function groups
  • Critical subsystems

2. Function Documentation Blocks

/* ============================================================================
 * FUNCTION NAME: Purpose
 * ============================================================================
 * Detailed explanation of what the function does.
 * 
 * @param {type} paramName - Parameter description
 * @returns {type} - Return value description
 * 
 * Implementation Details:
 * - Key point 1
 * - Key point 2
 * 
 * Called by: FunctionA(), FunctionB()
 * Calls: FunctionC(), FunctionD()
 * ========================================================================= */

3. Inline Explanatory Comments

seconds = workerSeconds;  // Update global seconds variable
updateDisplay();          // Update UI with new time

Used for:

  • Non-obvious variable assignments
  • Important function calls
  • State changes

4. Decision Point Comments

// PREVENT starting new task if timer is already running
if (isTimerRunning) {
  return alert("Timer is already running!");
}

Used for:

  • Validation checks
  • Guard clauses
  • Business logic decisions

Comment Locations in Code

Lines 363-389: State Variables

/* ============================================================================
 * APPLICATION STATE VARIABLES
 * ============================================================================

Documents:

  • All global state variables
  • Purpose of each variable
  • Expected values/ranges
  • Relationship to other variables

Example:

let seconds = 900;          // Current countdown seconds (15 min = 900 sec)
let completedSessions = 0;  // Number of completed sessions (0-4)

Lines 391-412: isTaskAlreadyCompleted()

/* ============================================================================
 * HELPER FUNCTION: Duplicate Task Detection
 * ============================================================================

Documents:

  • Function purpose
  • Parameter types
  • Return value
  • Implementation approach (case-insensitive, etc.)
  • Edge cases handled

Lines 414-435: unlockAudio()

/* ============================================================================
 * AUDIO CONTEXT UNLOCKING
 * ============================================================================

Documents:

  • Why audio unlocking is needed (browser autoplay policies)
  • When it's called
  • How it works (play → pause immediately)

Lines 437-467: initWorker()

/* ============================================================================
 * WEB WORKER INITIALIZATION
 * ============================================================================

Documents:

  • Purpose of Web Worker
  • Message types handled
  • Fallback behavior

Lines 483-512: saveTimerState()

/* ============================================================================
 * STATE PERSISTENCE: Save to LocalStorage
 * ============================================================================

Documents:

  • When function is called
  • What data is saved
  • Why each field is important
  • State structure

Comment Principles

DO ✅

  1. Explain WHY, not just WHAT

    // GOOD
    isTimerRunning = true;  // Prevent starting multiple timers simultaneously
    
    // BAD
    isTimerRunning = true;  // Set flag to true
  2. Document Business Logic

    // GOOD
    if (completedSessions >= 4) {
      // ENFORCE break: 4 sessions = 1 hour work → mandatory 10-min break
    }
    
    // BAD
    if (completedSessions >= 4) {
      // Show modal
    }
  3. Clarify Non-Obvious Code

    // GOOD
    audio.pause();        // Immediately pause to avoid actual playback
    audio.currentTime = 0; // Reset to beginning for next use
    
    // BAD
    audio.pause();
    audio.currentTime = 0;
  4. Link Related Functions

    // Called by: startTimer(), extendTask(), onTimerComplete()

DON'T ❌

  1. State the Obvious

    // BAD
    let x = 5;  // Set x to 5
  2. Redundant Comments

    // BAD
    // Increment counter
    counter++;
  3. Outdated Comments

    // BAD (if code changed but comment didn't)
    // Check if count is less than 5
    if (count >= 10) { ... }

Key Functions Commented

Timer Management

  • startTimer() - Initiates 15-minute countdown
  • startFallbackTimer() - Backup timer using setInterval
  • onTimerComplete() - Handles timer completion logic

State Management

  • saveTimerState() - Persists state to localStorage
  • restoreTimerState() - Recovers state after reload
  • clearTimerState() - Removes saved state

Pomodoro Cycle

  • updateSessionCounter() - Updates progress display
  • showBreakModal() - Displays break prompt
  • startBreak() - Initiates 10-minute break

Task Tracking

  • addActiveTaskToLog() - Adds task to history
  • updateActiveTaskStatus() - Updates task status
  • isTaskAlreadyCompleted() - Checks for duplicates

Extension Warnings

  • extendTask() - Handles task extensions
  • showFocusWarning() - Displays warning modals

Variable Naming Conventions

Boolean Flags

let isTimerRunning = false;   // "is" prefix for boolean
let audioUnlocked = false;    // Past tense for state flags
let isBreakMode = false;      // "is" prefix for mode flags

Counts/Tracking

let completedSessions = 0;    // Clear noun describing what's counted
let consecutiveExtensions = 0; // Adjective + noun for specificity
let iterationCount = 0;       // Counter noun

References

let currentActiveRow = null;   // "current" prefix for active reference
let timerWorker = null;        // Type suffix for clarity
let startTime = null;          // Action + type naming

LocalStorage Keys Used

State Persistence

'timerState'          // Complete timer state object
'completedSessions'   // Pomodoro cycle progress
'theme'               // User theme preference
'focusLog'            // Task history array

Common Patterns Explained

Guard Clauses

// Validate input before proceeding
if (!task) return alert("Please enter your focus task.");

// Prevent duplicate actions
if (isTimerRunning) {
  return alert("Timer is already running!");
}

State Transitions

// Work → Break transition
isBreakMode = true;
completedSessions = 0;  // Reset cycle
updateSessionCounter();

Error Handling

try {
  // Attempt Web Worker initialization
  timerWorker = new Worker('timer-worker.js');
} catch (error) {
  // Fallback to setInterval
  console.warn('Web Worker not available, using fallback timer');
}

For New Developers

Quick Start Checklist

  1. ✅ Read through state variable comments (lines 363-389)
  2. ✅ Understand timer flow: startTimer()onTimerComplete()
  3. ✅ Study Pomodoro cycle: completedSessions tracking
  4. ✅ Review state persistence: saveTimerState() / restoreTimerState()
  5. ✅ Examine validation: isTaskAlreadyCompleted(), timer lock logic

Key Files to Review

  • index.html - Main application (single-file architecture)
  • timer-worker.js - Background timer thread
  • README.md - Feature overview and usage
  • IMPLEMENTATION_SUMMARY.md - Technical documentation

Testing Your Understanding

Can you answer these questions after reading the comments?

  1. Why do we use Web Workers instead of setInterval?
  2. What happens if user reloads page during timer?
  3. When does the break modal appear?
  4. How are duplicate tasks prevented?
  5. Why is audio unlocking needed?

Maintaining Comments

When to Update Comments

MUST Update:

  • When changing function behavior
  • When modifying state logic
  • When adding new parameters
  • When changing business rules

SHOULD Update:

  • When renaming variables
  • When adding edge cases
  • When improving error handling

Example:

// BEFORE
// Check if sessions done
if (completedSessions === 4) { ... }

// AFTER (code changed to >=)
// Check if break is needed (after 4+ sessions)
if (completedSessions >= 4) { ... }

Comment Review Checklist

  • Comments match actual code behavior
  • No outdated function/variable names
  • Business logic clearly explained
  • Edge cases documented
  • Related functions cross-referenced

Best Practices Summary

  1. Clarity Over Brevity - Better to over-explain than under-explain
  2. Consistency - Follow established comment patterns
  3. Context - Explain the "why" behind decisions
  4. Maintenance - Update comments when code changes
  5. Cross-References - Link related functions/sections

Comments are code documentation—treat them as first-class citizens!