Added DocStrings

This commit is contained in:
AlexKucera committed 2025-10-24 13:09:10 +02:00
1 parent 03d2b1c93d
commit e96ef65200
8 files changed
+797 -17

No files matched your search

+88
View File
@@ -5,11 +5,46 @@ import { App, Editor, MarkdownView, Notice } from 'obsidian';
import { PromptGeneratorService } from '../services/promptGenerator';
import { FreewritingPromptsSettings } from '../types';
/**
* Command handler for inserting writing prompts directly into notes.
*
* This command generates prompts and inserts them at the cursor position in
* the active note as formatted markdown. Unlike timed prompts, these are
* persistent and remain in the note for reference.
*
* Key responsibilities:
* - Validates editor and view state before execution
* - Generates prompts via the prompt service
* - Formats prompts with timestamp and numbering
* - Inserts at cursor with intelligent newline handling
* - Positions cursor after inserted content
*
* The formatting includes a timestamp to help users track when prompts were
* added, and numbered list format for easy reference.
*/
export class NotePromptsCommand {
/**
* Creates a new note prompts command handler.
*
* @param promptGenerator - Service for generating prompts from the API
*/
constructor(private promptGenerator: PromptGeneratorService) {}
// MARK: - Public Methods
/**
* Executes the note prompts insertion.
*
* This method:
* 1. Validates that editor and view are available
* 2. Generates prompts through the service
* 3. Formats and inserts prompts at the cursor position
* 4. Shows success feedback to the user
*
* @param settings - Current plugin settings for generation parameters
* @param editor - Active editor instance for text insertion
* @param view - Active markdown view for context
*/
async execute(
settings: FreewritingPromptsSettings,
editor: Editor,
@@ -42,6 +77,20 @@ export class NotePromptsCommand {
// MARK: - Private Methods
/**
* Inserts formatted prompts into the note at the cursor position.
*
* This method handles several edge cases:
* - Adds newline before if cursor is on a line with content
* - Adds newline after if cursor is not at end of document
* - Positions cursor at the end of inserted content
*
* The intelligent newline handling ensures prompts don't run into existing
* text and maintains proper spacing in the document.
*
* @param editor - Editor instance for text manipulation
* @param prompts - Array of prompt strings to insert
*/
private insertPromptsIntoNote(editor: Editor, prompts: string[]): void {
const cursor = editor.getCursor();
const currentLine = editor.getLine(cursor.line);
@@ -78,6 +127,24 @@ export class NotePromptsCommand {
editor.setCursor(newCursorLine, newCursorCh);
}
/**
* Formats prompts as markdown with timestamp header and numbered list.
*
* The format is:
* ```
* ## Writing Prompts (Jan 15, 2025, 02:30 PM)
*
* 1. [First prompt]
*
* 2. [Second prompt]
* ```
*
* The timestamp helps users track when prompts were generated, and the
* numbered list makes it easy to reference specific prompts.
*
* @param prompts - Array of prompt strings to format
* @returns Formatted markdown string ready for insertion
*/
private formatPrompts(prompts: string[]): string {
const timestamp = new Date().toLocaleDateString('en-US', {
year: 'numeric',
@@ -98,10 +165,31 @@ export class NotePromptsCommand {
// MARK: - Utility Methods
/**
* Checks whether the command can be executed in the current context.
*
* Validates that:
* - Editor instance exists
* - Markdown view exists
* - An actual file is open (not just an empty pane)
*
* @param editor - Editor instance to validate
* @param view - Markdown view to validate
* @returns true if command can execute, false otherwise
*/
static canExecute(editor: Editor, view: MarkdownView): boolean {
return !!(editor && view && view.file);
}
/**
* Retrieves the current execution context from the app.
*
* Helper method for getting the active editor and view without having
* them explicitly passed. Useful for manual command invocation.
*
* @param app - Obsidian app instance
* @returns Object containing editor and view, or nulls if not available
*/
static getExecutionContext(app: App): { editor: Editor | null; view: MarkdownView | null } {
const activeView = app.workspace.getActiveViewOfType(MarkdownView);
+90
View File
@@ -5,16 +5,57 @@ import { Notice } from 'obsidian';
import { PromptGeneratorService } from '../services/promptGenerator';
import { FreewritingPromptsSettings } from '../types';
/**
* Command handler for displaying timed writing prompts as notifications.
*
* This command manages a sequence of prompts shown at regular intervals, useful
* for freewriting sessions where the writer wants periodic prompts to maintain
* creative flow.
*
* Key responsibilities:
* - Generates a queue of prompts upfront (prevents race conditions)
* - Displays prompts as timed Obsidian notifications
* - Manages window.setInterval for timed display
* - Prevents concurrent executions with inProgress flag
* - Provides proper cleanup to prevent memory leaks
*
* The notification duration is calibrated to avoid overlap - each notification
* disappears 500ms before the next one appears for a clean transition.
*/
export class TimedPromptsCommand {
/** Active interval ID from window.setInterval, null when not running */
private activeInterval: number | null = null;
/** Queue of prompts to display, loaded at command start */
private promptQueue: string[] = [];
/** Index of the currently displayed or next-to-display prompt */
private currentIndex = 0;
/** Flag preventing concurrent command execution */
private inProgress = false;
/**
* Creates a new timed prompts command handler.
*
* @param promptGenerator - Service for generating prompts from the API
*/
constructor(private promptGenerator: PromptGeneratorService) {}
// MARK: - Public Methods
/**
* Executes the timed prompts sequence.
*
* This method:
* 1. Prevents race conditions by checking inProgress flag
* 2. Stops any existing timed sequence
* 3. Generates all prompts upfront to avoid async issues during intervals
* 4. Shows the first prompt immediately
* 5. Starts an interval to show remaining prompts
*
* The inProgress flag prevents issues if the user triggers the command
* multiple times quickly while prompt generation is in progress.
*
* @param settings - Current plugin settings for generation parameters
*/
async execute(settings: FreewritingPromptsSettings): Promise<void> {
// Check if already in progress to prevent race conditions
if (this.inProgress) {
@@ -57,6 +98,13 @@ export class TimedPromptsCommand {
}
}
/**
* Stops the currently running timed prompts sequence.
*
* Cleans up the interval timer and resets all state. This is important
* for preventing memory leaks and ensuring the next execution starts fresh.
* Safe to call even when no sequence is running.
*/
stop(): void {
if (this.activeInterval !== null) {
clearInterval(this.activeInterval);
@@ -67,12 +115,26 @@ export class TimedPromptsCommand {
this.inProgress = false;
}
/**
* Checks whether a timed prompts sequence is currently running.
*
* @returns true if prompts are being displayed on an interval, false otherwise
*/
isRunning(): boolean {
return this.activeInterval !== null;
}
// MARK: - Private Methods
/**
* Starts the interval timer for displaying subsequent prompts.
*
* The timer increments the current index and displays the next prompt
* until the queue is exhausted. Automatically stops and shows a completion
* notice when all prompts have been displayed.
*
* @param delaySeconds - Seconds to wait between each prompt display
*/
private startInterval(delaySeconds: number): void {
this.activeInterval = window.setInterval(() => {
this.currentIndex++;
@@ -87,6 +149,19 @@ export class TimedPromptsCommand {
}, delaySeconds * 1000);
}
/**
* Displays the current prompt as an Obsidian notice.
*
* The notification includes:
* - Current position in sequence (e.g., "3/10")
* - The prompt text
* - Custom CSS class for potential styling
*
* Notification duration is calibrated to avoid overlap with the next prompt,
* disappearing 500ms before the next one arrives for smooth transitions.
*
* @param delaySeconds - Delay setting used to calculate notification duration
*/
private showCurrentPrompt(delaySeconds: number): void {
if (this.currentIndex < this.promptQueue.length) {
const prompt = this.promptQueue[this.currentIndex];
@@ -112,6 +187,14 @@ export class TimedPromptsCommand {
// MARK: - Status Methods
/**
* Retrieves the current status of the timed prompts sequence.
*
* Provides information for UI feedback (like status bar displays) about
* the current state of the prompt sequence.
*
* @returns Object containing running state and progress information
*/
getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
const totalPrompts = this.promptQueue.length;
const currentPrompt = totalPrompts === 0 ? 0 : Math.min(this.currentIndex + 1, totalPrompts);
@@ -123,6 +206,13 @@ export class TimedPromptsCommand {
};
}
/**
* Gets the prompts that haven't been displayed yet.
*
* Useful for debugging or if users want to preview upcoming prompts.
*
* @returns Array of remaining prompt strings, empty if sequence is complete
*/
getRemainingPrompts(): string[] {
if (this.currentIndex >= this.promptQueue.length) {
return [];