dyelight 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,6 +31,7 @@ A lightweight TypeScript React component for highlighting characters in textarea
31
31
  - **Modern UI Friendly**: Optimized for integration with Tailwind CSS and UI libraries like shadcn/ui
32
32
  - **Smart Placeholder**: Placeholders remain visible even with the transparent character-highlighting overlay
33
33
  - **Storybook Playground**: Explore the component interactively with the bundled Storybook setup
34
+ - **AI-Powered Debugging**: Built-in telemetry system for diagnosing sync issues with AI assistance
34
35
 
35
36
  ## Development
36
37
 
@@ -202,6 +203,91 @@ function RefExample() {
202
203
  }
203
204
  ```
204
205
 
206
+ ## AI-Powered Debugging
207
+
208
+ DyeLight includes a built-in telemetry system that can help diagnose synchronization issues between the textarea and React state. This is especially useful for hard-to-reproduce bugs.
209
+
210
+ ### Enabling Debug Mode
211
+
212
+ Simply add the `debug` prop to enable telemetry collection:
213
+
214
+ ```tsx
215
+ import { useRef, useState } from 'react';
216
+ import { DyeLight, type DyeLightRef } from 'dyelight';
217
+
218
+ function DebugExample() {
219
+ const [text, setText] = useState('');
220
+ const dyeLightRef = useRef<DyeLightRef>(null);
221
+
222
+ const handleExportDebug = async () => {
223
+ const report = dyeLightRef.current?.exportForAI();
224
+
225
+ if (report) {
226
+ // Copy to clipboard
227
+ await navigator.clipboard.writeText(report);
228
+ alert('Debug report copied! Paste it into Claude or ChatGPT for analysis.');
229
+ }
230
+ };
231
+
232
+ return (
233
+ <div>
234
+ <DyeLight
235
+ ref={dyeLightRef}
236
+ value={text}
237
+ onChange={setText}
238
+ debug={true}
239
+ rows={10}
240
+ />
241
+
242
+ <button onClick={handleExportDebug}>
243
+ Export Debug Report
244
+ </button>
245
+ </div>
246
+ );
247
+ }
248
+ ```
249
+
250
+ ### Using the Debug Report
251
+
252
+ When you experience sync issues:
253
+
254
+ 1. **Enable debug mode** - Add `debug={true}` to your DyeLight component
255
+ 2. **Reproduce the issue** - Use the component normally until the bug occurs
256
+ 3. **Export the report** - Call `ref.current?.exportForAI()` to get a JSON report
257
+ 4. **Get AI diagnosis**:
258
+ - Go to [claude.ai](https://claude.ai) or [chat.openai.com](https://chat.openai.com)
259
+ - Paste the exported JSON
260
+ - Ask: *"Please analyze this DyeLight debug report and identify the issue"*
261
+ 5. **Get instant diagnosis** - The AI will identify the root cause and suggest fixes
262
+
263
+ ### What's Included in Debug Reports
264
+
265
+ The exported report contains:
266
+
267
+ - **Complete event timeline** - Every onChange, resize, and sync operation
268
+ - **State snapshots** - DOM and React state at each event
269
+ - **Automatic issue detection** - Pre-identified problems like:
270
+ - State mismatches between DOM and React
271
+ - Rapid successive events (race conditions)
272
+ - Excessive resize operations
273
+ - Layout thrashing
274
+ - **Timing information** - Millisecond-precise event timing
275
+ - **Browser metadata** - User agent, platform, React version
276
+ - **AI instructions** - Built-in guidance for AI analysis
277
+
278
+ ### Debug Mode Options
279
+
280
+ ```tsx
281
+ <DyeLight
282
+ debug={true} // Enable telemetry collection
283
+ debugMaxEvents={1000} // Max events to retain (default: 1000)
284
+ value={text}
285
+ onChange={setText}
286
+ />
287
+ ```
288
+
289
+ **Note**: Debug mode has minimal performance impact but should generally be disabled in production unless troubleshooting specific issues.
290
+
205
291
  ## API Reference
206
292
 
207
293
  ### DyeLight Props
@@ -218,6 +304,8 @@ function RefExample() {
218
304
  | `containerClassName` | `string` | `''` | CSS class for the wrapper container |
219
305
  | `dir` | `'ltr' \| 'rtl'` | `'ltr'` | Text direction |
220
306
  | `rows` | `number` | `4` | Number of visible rows |
307
+ | `debug` | `boolean` | `false` | Enable telemetry collection |
308
+ | `debugMaxEvents` | `number` | `1000` | Max telemetry events to retain |
221
309
 
222
310
  All standard textarea HTML attributes are also supported.
223
311
 
@@ -242,6 +330,8 @@ type CharacterRange = {
242
330
  | `setSelectionRange(start, end)` | Set text selection |
243
331
  | `getValue()` | Get current value |
244
332
  | `setValue(value)` | Set value programmatically |
333
+ | `scrollToPosition(pos, offset?, behavior?)` | Scroll to character position |
334
+ | `exportForAI()` | Export debug report (requires `debug={true}`) |
245
335
 
246
336
  ## HighlightBuilder Utilities
247
337
 
@@ -269,6 +359,8 @@ Create a single selection highlight.
269
359
 
270
360
  Create line-level highlights.
271
361
 
362
+ ## Styling
363
+
272
364
  DyeLight uses CSS-in-JS for core functionality but allows complete customization through CSS classes.
273
365
 
274
366
  ### Modern Layout & UI (Tailwind CSS)
package/dist/index.d.mts CHANGED
@@ -7,22 +7,22 @@ import React from "react";
7
7
  */
8
8
  declare const HighlightBuilder: {
9
9
  /**
10
- * Creates highlights for individual characters using absolute positions
11
- * @param chars - Array of character highlight configurations
12
- * @param chars[].index - Zero-based character index in the text
13
- * @param chars[].className - Optional CSS class name to apply
14
- * @param chars[].style - Optional inline styles to apply
15
- * @returns Array of character range highlights
16
- * @example
17
- * ```tsx
18
- * // Highlight characters at positions 5, 10, and 15
19
- * const highlights = HighlightBuilder.characters([
20
- * { index: 5, className: 'highlight-error' },
21
- * { index: 10, className: 'highlight-warning' },
22
- * { index: 15, style: { backgroundColor: 'yellow' } }
23
- * ]);
24
- * ```
25
- */
10
+ * Creates highlights for individual characters using absolute positions
11
+ * @param chars - Array of character highlight configurations
12
+ * @param chars[].index - Zero-based character index in the text
13
+ * @param chars[].className - Optional CSS class name to apply
14
+ * @param chars[].style - Optional inline styles to apply
15
+ * @returns Array of character range highlights
16
+ * @example
17
+ * ```tsx
18
+ * // Highlight characters at positions 5, 10, and 15
19
+ * const highlights = HighlightBuilder.characters([
20
+ * { index: 5, className: 'highlight-error' },
21
+ * { index: 10, className: 'highlight-warning' },
22
+ * { index: 15, style: { backgroundColor: 'yellow' } }
23
+ * ]);
24
+ * ```
25
+ */
26
26
  characters: (chars: Array<{
27
27
  className?: string;
28
28
  index: number;
@@ -34,21 +34,21 @@ declare const HighlightBuilder: {
34
34
  style: React.CSSProperties | undefined;
35
35
  }[];
36
36
  /**
37
- * Creates line highlights for entire lines
38
- * @param lines - Array of line highlight configurations
39
- * @param lines[].line - Zero-based line number
40
- * @param lines[].className - Optional CSS class name to apply to the line
41
- * @param lines[].color - Optional color value (CSS color, hex, rgb, etc.)
42
- * @returns Object mapping line numbers to highlight values
43
- * @example
44
- * ```tsx
45
- * // Highlight lines 0 and 2 with different styles
46
- * const lineHighlights = HighlightBuilder.lines([
47
- * { line: 0, className: 'error-line' },
48
- * { line: 2, color: '#ffff00' }
49
- * ]);
50
- * ```
51
- */
37
+ * Creates line highlights for entire lines
38
+ * @param lines - Array of line highlight configurations
39
+ * @param lines[].line - Zero-based line number
40
+ * @param lines[].className - Optional CSS class name to apply to the line
41
+ * @param lines[].color - Optional color value (CSS color, hex, rgb, etc.)
42
+ * @returns Object mapping line numbers to highlight values
43
+ * @example
44
+ * ```tsx
45
+ * // Highlight lines 0 and 2 with different styles
46
+ * const lineHighlights = HighlightBuilder.lines([
47
+ * { line: 0, className: 'error-line' },
48
+ * { line: 2, color: '#ffff00' }
49
+ * ]);
50
+ * ```
51
+ */
52
52
  lines: (lines: Array<{
53
53
  className?: string;
54
54
  color?: string;
@@ -57,29 +57,29 @@ declare const HighlightBuilder: {
57
57
  [lineNumber: number]: string;
58
58
  };
59
59
  /**
60
- * Highlights text matching a pattern using absolute positions
61
- * @param text - The text to search within
62
- * @param pattern - Regular expression or string pattern to match
63
- * @param className - Optional CSS class name to apply to matches
64
- * @param style - Optional inline styles to apply to matches
65
- * @returns Array of character range highlights for all matches
66
- * @example
67
- * ```tsx
68
- * // Highlight all JavaScript keywords
69
- * const highlights = HighlightBuilder.pattern(
70
- * code,
71
- * /\b(function|const|let|var|if|else|for|while)\b/g,
72
- * 'keyword-highlight'
73
- * );
74
- *
75
- * // Highlight all email addresses
76
- * const emailHighlights = HighlightBuilder.pattern(
77
- * text,
78
- * /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
79
- * 'email-highlight'
80
- * );
81
- * ```
82
- */
60
+ * Highlights text matching a pattern using absolute positions
61
+ * @param text - The text to search within
62
+ * @param pattern - Regular expression or string pattern to match
63
+ * @param className - Optional CSS class name to apply to matches
64
+ * @param style - Optional inline styles to apply to matches
65
+ * @returns Array of character range highlights for all matches
66
+ * @example
67
+ * ```tsx
68
+ * // Highlight all JavaScript keywords
69
+ * const highlights = HighlightBuilder.pattern(
70
+ * code,
71
+ * /\b(function|const|let|var|if|else|for|while)\b/g,
72
+ * 'keyword-highlight'
73
+ * );
74
+ *
75
+ * // Highlight all email addresses
76
+ * const emailHighlights = HighlightBuilder.pattern(
77
+ * text,
78
+ * /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
79
+ * 'email-highlight'
80
+ * );
81
+ * ```
82
+ */
83
83
  pattern: (text: string, pattern: RegExp | string, className?: string, style?: React.CSSProperties) => {
84
84
  className: string | undefined;
85
85
  end: number;
@@ -87,23 +87,23 @@ declare const HighlightBuilder: {
87
87
  style: React.CSSProperties | undefined;
88
88
  }[];
89
89
  /**
90
- * Creates character range highlights using absolute positions
91
- * @param ranges - Array of character range configurations
92
- * @param ranges[].start - Zero-based start index (inclusive)
93
- * @param ranges[].end - Zero-based end index (exclusive)
94
- * @param ranges[].className - Optional CSS class name to apply
95
- * @param ranges[].style - Optional inline styles to apply
96
- * @returns Array of character range highlights
97
- * @example
98
- * ```tsx
99
- * // Highlight specific ranges in the text
100
- * const highlights = HighlightBuilder.ranges([
101
- * { start: 0, end: 5, className: 'title-highlight' },
102
- * { start: 10, end: 20, style: { backgroundColor: 'yellow' } },
103
- * { start: 25, end: 30, className: 'error-highlight' }
104
- * ]);
105
- * ```
106
- */
90
+ * Creates character range highlights using absolute positions
91
+ * @param ranges - Array of character range configurations
92
+ * @param ranges[].start - Zero-based start index (inclusive)
93
+ * @param ranges[].end - Zero-based end index (exclusive)
94
+ * @param ranges[].className - Optional CSS class name to apply
95
+ * @param ranges[].style - Optional inline styles to apply
96
+ * @returns Array of character range highlights
97
+ * @example
98
+ * ```tsx
99
+ * // Highlight specific ranges in the text
100
+ * const highlights = HighlightBuilder.ranges([
101
+ * { start: 0, end: 5, className: 'title-highlight' },
102
+ * { start: 10, end: 20, style: { backgroundColor: 'yellow' } },
103
+ * { start: 25, end: 30, className: 'error-highlight' }
104
+ * ]);
105
+ * ```
106
+ */
107
107
  ranges: (ranges: Array<{
108
108
  className?: string;
109
109
  end: number;
@@ -116,23 +116,23 @@ declare const HighlightBuilder: {
116
116
  style: React.CSSProperties | undefined;
117
117
  }[];
118
118
  /**
119
- * Highlights text between specific start and end positions
120
- * Convenience method for highlighting a single selection range
121
- * @param start - Zero-based start index (inclusive)
122
- * @param end - Zero-based end index (exclusive)
123
- * @param className - Optional CSS class name to apply
124
- * @param style - Optional inline styles to apply
125
- * @returns Array containing a single character range highlight
126
- * @example
127
- * ```tsx
128
- * // Highlight a selection from position 10 to 25
129
- * const selectionHighlight = HighlightBuilder.selection(
130
- * 10,
131
- * 25,
132
- * 'selection-highlight'
133
- * );
134
- * ```
135
- */
119
+ * Highlights text between specific start and end positions
120
+ * Convenience method for highlighting a single selection range
121
+ * @param start - Zero-based start index (inclusive)
122
+ * @param end - Zero-based end index (exclusive)
123
+ * @param className - Optional CSS class name to apply
124
+ * @param style - Optional inline styles to apply
125
+ * @returns Array containing a single character range highlight
126
+ * @example
127
+ * ```tsx
128
+ * // Highlight a selection from position 10 to 25
129
+ * const selectionHighlight = HighlightBuilder.selection(
130
+ * 10,
131
+ * 25,
132
+ * 'selection-highlight'
133
+ * );
134
+ * ```
135
+ */
136
136
  selection: (start: number, end: number, className?: string, style?: React.CSSProperties) => {
137
137
  className: string | undefined;
138
138
  end: number;
@@ -140,30 +140,30 @@ declare const HighlightBuilder: {
140
140
  style: React.CSSProperties | undefined;
141
141
  }[];
142
142
  /**
143
- * Highlights entire words that match specific terms
144
- * @param text - The text to search within
145
- * @param words - Array of words to highlight
146
- * @param className - Optional CSS class name to apply to matched words
147
- * @param style - Optional inline styles to apply to matched words
148
- * @returns Array of character range highlights for all matched words
149
- * @example
150
- * ```tsx
151
- * // Highlight specific programming keywords
152
- * const highlights = HighlightBuilder.words(
153
- * sourceCode,
154
- * ['function', 'const', 'let', 'var', 'return'],
155
- * 'keyword'
156
- * );
157
- *
158
- * // Highlight important terms with custom styling
159
- * const termHighlights = HighlightBuilder.words(
160
- * document,
161
- * ['TODO', 'FIXME', 'NOTE'],
162
- * undefined,
163
- * { backgroundColor: 'orange', fontWeight: 'bold' }
164
- * );
165
- * ```
166
- */
143
+ * Highlights entire words that match specific terms
144
+ * @param text - The text to search within
145
+ * @param words - Array of words to highlight
146
+ * @param className - Optional CSS class name to apply to matched words
147
+ * @param style - Optional inline styles to apply to matched words
148
+ * @returns Array of character range highlights for all matched words
149
+ * @example
150
+ * ```tsx
151
+ * // Highlight specific programming keywords
152
+ * const highlights = HighlightBuilder.words(
153
+ * sourceCode,
154
+ * ['function', 'const', 'let', 'var', 'return'],
155
+ * 'keyword'
156
+ * );
157
+ *
158
+ * // Highlight important terms with custom styling
159
+ * const termHighlights = HighlightBuilder.words(
160
+ * document,
161
+ * ['TODO', 'FIXME', 'NOTE'],
162
+ * undefined,
163
+ * { backgroundColor: 'orange', fontWeight: 'bold' }
164
+ * );
165
+ * ```
166
+ */
167
167
  words: (text: string, words: string[], className?: string, style?: React.CSSProperties) => {
168
168
  className: string | undefined;
169
169
  end: number;
@@ -219,6 +219,7 @@ type CharacterRange = {
219
219
  * rows={10}
220
220
  * className="my-editor"
221
221
  * placeholder="Enter your code here..."
222
+ * debug={true}
222
223
  * />
223
224
  * );
224
225
  * };
@@ -247,10 +248,14 @@ interface DyeLightProps extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaEl
247
248
  rows?: number;
248
249
  /** Controlled value */
249
250
  value?: string;
251
+ /** Enable debug mode to collect telemetry data */
252
+ debug?: boolean;
253
+ /** Maximum number of telemetry events to retain in memory */
254
+ debugMaxEvents?: number;
250
255
  }
251
256
  /**
252
257
  * Methods exposed by the DyeLight component through its ref
253
- * Provides programmatic access to common textarea operations
258
+ * Provides programmatic access to common textarea operations and debug features
254
259
  * @example
255
260
  * ```tsx
256
261
  * const MyComponent = () => {
@@ -265,7 +270,20 @@ interface DyeLightProps extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaEl
265
270
  * console.log('Current value:', value);
266
271
  * };
267
272
  *
268
- * return <DyeLight ref={dyeLightRef} />;
273
+ * const handleExportDebug = async () => {
274
+ * const report = dyeLightRef.current?.exportForAI();
275
+ * if (report) {
276
+ * await navigator.clipboard.writeText(report);
277
+ * alert('Debug report copied to clipboard');
278
+ * }
279
+ * };
280
+ *
281
+ * return (
282
+ * <>
283
+ * <DyeLight ref={dyeLightRef} debug={true} />
284
+ * <button onClick={handleExportDebug}>Export Debug Report</button>
285
+ * </>
286
+ * );
269
287
  * };
270
288
  * ```
271
289
  */
@@ -276,7 +294,8 @@ type DyeLightRef = {
276
294
  select: () => void; /** Sets the selection range in the textarea */
277
295
  setSelectionRange: (start: number, end: number) => void; /** Sets the value of the textarea programmatically */
278
296
  setValue: (value: string) => void; /** Scrolls the character position into view with an optional pixel offset */
279
- scrollToPosition: (pos: number, offset?: number, behavior?: ScrollBehavior) => void;
297
+ scrollToPosition: (pos: number, offset?: number, behavior?: ScrollBehavior) => void; /** Exports AI-optimized debug report as JSON string (requires debug mode) */
298
+ exportForAI: () => string;
280
299
  };
281
300
  //#endregion
282
301
  //#region src/DyeLight.d.ts
@@ -344,5 +363,155 @@ declare const DyeLight: React.ForwardRefExoticComponent<DyeLightProps & React.Re
344
363
  */
345
364
  declare const autoResize: (textArea: HTMLTextAreaElement) => void;
346
365
  //#endregion
347
- export { CharacterRange, DyeLight, DyeLightProps, DyeLightRef, HighlightBuilder, autoResize, createLineElement, renderHighlightedLine };
366
+ //#region src/telemetry.d.ts
367
+ /**
368
+ * Represents a single telemetry event with full context
369
+ */
370
+ type AITelemetryEvent = {
371
+ /** Unix timestamp in milliseconds */timestamp: number; /** ISO 8601 formatted timestamp */
372
+ timestampISO: string; /** Milliseconds since the last event, or null for first event */
373
+ timeSinceLastEvent: number | null; /** Event type identifier */
374
+ type: string; /** Event category for grouping and analysis */
375
+ category: 'state' | 'dom' | 'sync' | 'user' | 'system'; /** Human-readable description of the event */
376
+ description: string; /** Event-specific data payload */
377
+ data: Record<string, unknown>; /** Complete state snapshot at the time of this event */
378
+ stateSnapshot: {
379
+ /** Actual value in the textarea DOM element */textareaValue: string; /** Value in React state */
380
+ reactValue: string; /** Whether DOM and React state are synchronized */
381
+ valuesMatch: boolean; /** Current height of the textarea in pixels */
382
+ textareaHeight: number | undefined; /** Whether the component is in controlled mode */
383
+ isControlled: boolean;
384
+ }; /** Detected anomalies or issues at this event */
385
+ anomalies: string[];
386
+ };
387
+ /**
388
+ * Complete AI-readable debug report structure
389
+ */
390
+ type AIDebugReport = {
391
+ /** Metadata about the report and environment */metadata: {
392
+ /** When this report was generated */generatedAt: string; /** DyeLight version */
393
+ componentVersion: string; /** Total number of events recorded */
394
+ totalEvents: number; /** Time range covered by events */
395
+ timespan: {
396
+ /** ISO timestamp of first event */start: string; /** ISO timestamp of last event */
397
+ end: string; /** Duration in milliseconds */
398
+ durationMs: number;
399
+ }; /** Browser user agent string */
400
+ browser: string; /** Platform identifier */
401
+ platform: string; /** React version */
402
+ reactVersion: string;
403
+ }; /** Analysis summary with detected issues */
404
+ summary: {
405
+ /** High-level description of findings */description: string; /** List of detected issues sorted by severity */
406
+ detectedIssues: Array<{
407
+ /** Issue severity level */severity: 'critical' | 'warning' | 'info'; /** Issue description */
408
+ issue: string; /** When this issue first occurred */
409
+ firstOccurrence: string; /** How many times this issue occurred */
410
+ occurrenceCount: number; /** Event indices where this issue occurred */
411
+ relatedEvents: number[];
412
+ }>; /** Suspicious patterns detected in event sequences */
413
+ suspiciousPatterns: string[]; /** Recommended actions to resolve issues */
414
+ recommendations: string[];
415
+ }; /** Different views of the event timeline */
416
+ timeline: {
417
+ /** User interactions and their impacts */userActions: Array<{
418
+ /** When the action occurred */timestamp: string; /** What the user did */
419
+ action: string; /** Number of state changes triggered */
420
+ resultingStateChanges: number;
421
+ }>; /** All state mutations in chronological order */
422
+ stateChanges: Array<{
423
+ /** When the change occurred */timestamp: string; /** Type of state change */
424
+ type: string; /** Previous value */
425
+ before: unknown; /** New value */
426
+ after: unknown; /** Whether this change was unexpected */
427
+ unexpected: boolean;
428
+ }>; /** Synchronization operations between textarea and overlay */
429
+ syncOperations: Array<{
430
+ /** When the sync occurred */timestamp: string; /** Type of synchronization */
431
+ operation: string; /** Whether sync was successful */
432
+ success: boolean; /** Additional sync details */
433
+ details: Record<string, unknown>;
434
+ }>;
435
+ }; /** Complete chronological list of all events */
436
+ events: AITelemetryEvent[]; /** Final state at time of export */
437
+ finalState: {
438
+ /** Current textarea DOM value */textareaValue: string; /** Current React state value */
439
+ reactValue: string; /** Whether values are synchronized */
440
+ inSync: boolean; /** Current height in pixels */
441
+ height: number | undefined; /** Current scroll position */
442
+ scrollPosition: {
443
+ top: number;
444
+ left: number;
445
+ }; /** Current highlights configuration */
446
+ highlights: unknown[];
447
+ };
448
+ };
449
+ /**
450
+ * AI-optimized telemetry collector for the DyeLight component.
451
+ * Records events with full context and generates comprehensive debug reports
452
+ * that can be analyzed by AI language models.
453
+ */
454
+ declare class AIOptimizedTelemetry {
455
+ private events;
456
+ private maxEvents;
457
+ private enabled;
458
+ private lastEventTimestamp;
459
+ private issueRegistry;
460
+ /**
461
+ * Creates a new telemetry instance
462
+ * @param enabled Whether telemetry collection is initially enabled
463
+ * @param maxEvents Maximum number of events to retain in memory
464
+ */
465
+ constructor(enabled?: boolean, maxEvents?: number);
466
+ /**
467
+ * Enable or disable telemetry collection
468
+ * @param enabled Whether to enable telemetry
469
+ */
470
+ setEnabled(enabled: boolean): void;
471
+ /**
472
+ * Records an event with full context for AI analysis
473
+ * @param type Event type identifier
474
+ * @param category Event category for grouping
475
+ * @param data Event-specific data
476
+ * @param textareaRef Reference to the textarea element
477
+ * @param currentValue Current React state value
478
+ * @param textareaHeight Current textarea height
479
+ * @param isControlled Whether component is in controlled mode
480
+ */
481
+ record(type: string, category: 'state' | 'dom' | 'sync' | 'user' | 'system', data: Record<string, unknown>, textareaRef: React.RefObject<HTMLTextAreaElement | null>, currentValue: string | undefined, textareaHeight: number | undefined, isControlled: boolean): void;
482
+ /**
483
+ * Generates a human-readable description for an event
484
+ * @param type Event type
485
+ * @param category Event category
486
+ * @param data Event data
487
+ * @returns Human-readable description
488
+ */
489
+ private generateDescription;
490
+ /**
491
+ * Generates a comprehensive AI-readable debug report
492
+ * @param textareaRef Reference to the textarea element
493
+ * @param currentValue Current React state value
494
+ * @param textareaHeight Current textarea height
495
+ * @param highlights Current highlights configuration
496
+ * @param lineHighlights Current line highlights configuration
497
+ * @returns Complete debug report
498
+ */
499
+ generateAIReport(textareaRef: React.RefObject<HTMLTextAreaElement | null>, currentValue: string | undefined, textareaHeight: number | undefined, highlights: unknown[], lineHighlights: Record<number, string>): AIDebugReport;
500
+ /**
501
+ * Exports telemetry data in AI-optimized format with instructions
502
+ * @param textareaRef Reference to the textarea element
503
+ * @param currentValue Current React state value
504
+ * @param textareaHeight Current textarea height
505
+ * @param highlights Current highlights configuration
506
+ * @param lineHighlights Current line highlights configuration
507
+ * @returns JSON string containing debug report and AI instructions
508
+ */
509
+ exportForAI(textareaRef: React.RefObject<HTMLTextAreaElement | null>, currentValue: string | undefined, textareaHeight: number | undefined, highlights: unknown[], lineHighlights: Record<number, string>): string;
510
+ /**
511
+ * Clears all recorded events and issue registry
512
+ */
513
+ clear(): void;
514
+ }
515
+ //#endregion
516
+ export { AIDebugReport, AIOptimizedTelemetry, AITelemetryEvent, CharacterRange, DyeLight, DyeLightProps, DyeLightRef, HighlightBuilder, autoResize, createLineElement, renderHighlightedLine };
348
517
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/builder.ts","../src/types.ts","../src/DyeLight.tsx","../src/domUt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Aa,KAAA,CAAM,SAAA,CAAU,mBAAA,UAC7B,YAAA,sBACA,cAAA,sBACA,UAAA,aACA,cAAA,EAAgB,MAAA,mBACjB,aAAA;EF9Oe;;;;;;;AAkEtB;;EE0UI,WAAA,CACI,WAAA,EAAa,KAAA,CAAM,SAAA,CAAU,mBAAA,UAC7B,YAAA,sBACA,cAAA,sBACA,UAAA,aACA,cAAA,EAAgB,MAAA;EF/UH;;;EEwXjB,KAAA,CAAA;AAAA"}
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import{forwardRef as e,useCallback as t,useEffect as n,useImperativeHandle as r,useMemo as i,useRef as a,useState as o}from"react";import{jsx as s,jsxs as c}from"react/jsx-runtime";const l={characters:e=>e.map(({className:e,index:t,style:n})=>({className:e,end:t+1,start:t,style:n})),lines:e=>{let t={};return e.forEach(({className:e,color:n,line:r})=>{t[r]=e||n||``}),t},pattern:(e,t,n,r)=>{let i=typeof t==`string`?new RegExp(t,`g`):new RegExp(t.source,`g`);return Array.from(e.matchAll(i)).map(e=>({className:n,end:e.index+e[0].length,start:e.index,style:r}))},ranges:e=>e.map(({className:e,end:t,start:n,style:r})=>({className:e,end:t,start:n,style:r})),selection:(e,t,n,r)=>[{className:n,end:t,start:e,style:r}],words:(e,t,n,r)=>{let i=RegExp(`\\b(${t.join(`|`)})\\b`,`g`);return l.pattern(e,i,n,r)}},u=e=>{let t=getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,r=parseFloat(t.borderBottomWidth)||0;e.style.height=`auto`;let i=e.scrollHeight,a=n+r,o=a>2?i+a:i;e.style.height=`${o}px`},d=e=>{let[n,r]=o();return{handleAutoResize:t(t=>{e&&(u(t),r(t.scrollHeight))},[e]),textareaHeight:n}},f=e=>{let t=e.split(`
2
- `),n=[],r=0;return t.forEach((e,i)=>{n.push(r),r+=e.length+(i<t.length-1?1:0)}),{lineStarts:n,lines:t}},p=(e,t)=>{for(let n=t.length-1;n>=0;n--)if(e>=t[n])return{char:e-t[n],line:n};return{char:0,line:0}},m=e=>/^(#|rgb|hsl|var\(--.*?\)|transparent|currentColor|inherit|initial|unset)/i.test(e)||/^[a-z]+$/i.test(e),h=(e,t,n,r)=>{let{lines:i,lineStarts:a}=f(e),o={};return t.forEach(e=>{let t=p(e.start,a),n=p(e.end-1,a);for(let r=t.line;r<=n.line;r++){o[r]||(o[r]=[]);let t=a[r],n=Math.max(e.start-t,0),s=Math.min(e.end-t,i[r].length);s>n&&o[r].push({absoluteStart:e.start,className:e.className,end:s,start:n,style:e.style})}}),i.map((e,t)=>{let i=n[t];return r(e,t,o[t]||[],i)})},g=(e,t,n,r)=>i(()=>h(e,t,n,r),[e,t,n,r]),_=(e,t)=>{if(!e||!t)return;let{scrollLeft:n,scrollTop:r}=e;t.scrollTop=r,t.scrollLeft=n},v=(e,t,n=getComputedStyle)=>{if(!e||!t)return;let r=n(e);t.style.padding=r.padding,t.style.fontSize=r.fontSize,t.style.fontFamily=r.fontFamily,t.style.lineHeight=r.lineHeight,t.style.letterSpacing=r.letterSpacing,t.style.wordSpacing=r.wordSpacing,t.style.textIndent=r.textIndent,t.style.whiteSpace=r.whiteSpace,t.style.wordBreak=r.wordBreak,t.style.overflowWrap=r.overflowWrap,t.style.tabSize=r.tabSize,t.style.borderTopWidth=r.borderTopWidth,t.style.borderRightWidth=r.borderRightWidth,t.style.borderBottomWidth=r.borderBottomWidth,t.style.borderLeftWidth=r.borderLeftWidth,t.style.borderTopStyle=r.borderTopStyle,t.style.borderRightStyle=r.borderRightStyle,t.style.borderBottomStyle=r.borderBottomStyle,t.style.borderLeftStyle=r.borderLeftStyle,t.style.borderColor=`transparent`;let i=parseFloat(r.borderLeftWidth)||0,a=parseFloat(r.borderRightWidth)||0,o=e.offsetWidth-e.clientWidth-i-a;if(o>0)if(r.direction===`rtl`){let e=parseFloat(r.paddingLeft)||0;t.style.paddingLeft=`${e+o}px`}else{let e=parseFloat(r.paddingRight)||0;t.style.paddingRight=`${e+o}px`}},y=()=>{let e=a(null);return{highlightLayerRef:e,syncScroll:t(t=>{_(t.current,e.current)},[]),syncStyles:t(t=>{v(t.current,e.current)},[])}},b=(e,t,n,r,i)=>{if(!e)return;let a=e.value;a!==t&&(n||r(a),i?.(a))},x=(e,t,n,r,i)=>{e!==t&&(n||r(e),i?.(e))},S=(e,t,n,r,i)=>{e&&(e.value=t,n||r(t),i?.(t))},C=(e,r=``,i)=>{let s=a(null),[c,l]=o(e??r),u=e!==void 0,d=u?e:c,f=t(()=>{b(s.current,d,u,l,i)},[d,u,i]),p=t(e=>{x(e.target.value,d,u,l,i)},[d,u,i]),m=t(e=>{S(s.current,e,u,l,i)},[u,i]);return n(()=>{f()},[f]),n(()=>{u&&s.current&&s.current.value!==e&&(s.current.value=e)},[u,e]),{currentValue:d,handleChange:p,setValue:m,textareaRef:s}},w={display:`block`,position:`relative`,width:`100%`},T={background:`transparent`,boxSizing:`border-box`,caretColor:`#000000`,color:`transparent`,minHeight:`auto`,position:`relative`,width:`100%`,zIndex:2},E={border:`0px none transparent`,bottom:0,boxSizing:`border-box`,color:`inherit`,fontFamily:`inherit`,fontSize:`inherit`,left:0,lineHeight:`inherit`,margin:0,overflow:`hidden`,pointerEvents:`none`,position:`absolute`,right:0,top:0,whiteSpace:`pre-wrap`,wordWrap:`break-word`,zIndex:1},D=(e,t,n)=>{if(!n)return s(`div`,{children:e},t);let r=m(n);return s(`div`,{className:r?void 0:n,style:r?{backgroundColor:n}:void 0,children:e},t)},O=(e,t,n,r)=>{if(n.length===0)return D(e||`\xA0`,t,r);let i=n.toSorted((e,t)=>e.start-t.start),a=[],o=0;if(i.forEach((n,r)=>{let{className:i,end:c,start:l,style:u}=n,d=Math.max(0,Math.min(l,e.length)),f=Math.max(d,Math.min(c,e.length));if(d>o){let t=e.slice(o,d);t&&a.push(t)}if(f>d){let o=e.slice(d,f);a.push(s(`span`,{className:i,style:u,"data-range-start":n.absoluteStart,children:o},`highlight-${t}-${r.toString()}`))}o=Math.max(o,f)}),o<e.length){let t=e.slice(o);t&&a.push(t)}return D(a.length===0?`\xA0`:a,t,r)},k=e(({className:e=``,containerClassName:i=``,defaultValue:o=``,dir:l=`ltr`,enableAutoResize:u=!0,highlights:f=[],lineHighlights:p={},onChange:m,rows:h=4,style:_,value:v,...b},x)=>{let S=a(null),{currentValue:D,handleChange:k,setValue:A,textareaRef:j}=C(v,o,m),{handleAutoResize:M,textareaHeight:N}=d(u),{highlightLayerRef:P,syncScroll:F,syncStyles:I}=y(),L=g(D,f,p,O),R=t(e=>{k(e),M(e.target)},[k,M]),z=t(e=>{A(e),j.current&&M(j.current)},[A,M,j]);n(()=>{},[]);let B=t(()=>{F(j)},[F,j]);r(x,()=>({blur:()=>j.current?.blur(),focus:()=>j.current?.focus(),getValue:()=>D,scrollToPosition:(e,t=40,n=`auto`)=>{if(P.current&&j.current){let r=P.current.querySelector(`[data-range-start="${e.toString()}"]`);if(r instanceof HTMLElement){let e=j.current,i=r.offsetTop;n===`smooth`?e.scrollTo({behavior:`smooth`,top:i-t}):e.scrollTop=i-t}}},select:()=>j.current?.select(),setSelectionRange:(e,t)=>j.current?.setSelectionRange(e,t),setValue:z}),[D,z,P,j]),n(()=>{j.current&&u&&M(j.current),I(j)},[D,M,u,I,j]),n(()=>{if(!j.current)return;let e=j.current,t,n=new ResizeObserver(()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>{I(j),u&&M(e)})});return n.observe(e),()=>{n.disconnect(),cancelAnimationFrame(t)}},[j,I,M,u]);let V={...T,color:D?`transparent`:`inherit`,height:N?`${N}px`:void 0,resize:u?`none`:`vertical`},H={...E,direction:l,height:N?`${N}px`:void 0,padding:j.current?getComputedStyle(j.current).padding:`8px 12px`};return c(`div`,{className:i,ref:S,style:{...w,..._},children:[s(`div`,{"aria-hidden":`true`,ref:P,style:H,children:L}),s(`textarea`,{className:e,dir:l,onChange:R,onScroll:B,ref:j,rows:h,style:V,value:D,...b})]})});k.displayName=`DyeLight`;export{k as DyeLight,l as HighlightBuilder,u as autoResize,D as createLineElement,O as renderHighlightedLine};
1
+ import e,{forwardRef as t,useCallback as n,useEffect as r,useImperativeHandle as i,useMemo as a,useRef as o,useState as s}from"react";import{jsx as c,jsxs as l}from"react/jsx-runtime";const u={characters:e=>e.map(({className:e,index:t,style:n})=>({className:e,end:t+1,start:t,style:n})),lines:e=>{let t={};return e.forEach(({className:e,color:n,line:r})=>{t[r]=e||n||``}),t},pattern:(e,t,n,r)=>{let i=typeof t==`string`?new RegExp(t,`g`):new RegExp(t.source,`g`);return Array.from(e.matchAll(i)).map(e=>({className:n,end:e.index+e[0].length,start:e.index,style:r}))},ranges:e=>e.map(({className:e,end:t,start:n,style:r})=>({className:e,end:t,start:n,style:r})),selection:(e,t,n,r)=>[{className:n,end:t,start:e,style:r}],words:(e,t,n,r)=>{let i=RegExp(`\\b(${t.join(`|`)})\\b`,`g`);return u.pattern(e,i,n,r)}},d=e=>{let t=getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,r=parseFloat(t.borderBottomWidth)||0;e.style.height=`auto`;let i=e.scrollHeight,a=n+r,o=a>2?i+a:i;e.style.height=`${o}px`},f=(e,t,r,i,a)=>{let[o,c]=s();return{handleAutoResize:n(n=>{if(!e)return;let o=n.scrollHeight;d(n);let s=n.scrollHeight;t?.record(`autoResize`,`system`,{afterHeight:s,beforeHeight:o,changed:o!==s,textLength:n.value.length},r??{current:n},i?.()??n.value,s,a??!1),c(n.scrollHeight)},[e,t,r,i,a]),textareaHeight:o}},p=e=>{let t=e.split(`
2
+ `),n=[],r=0;return t.forEach((e,i)=>{n.push(r),r+=e.length+(i<t.length-1?1:0)}),{lineStarts:n,lines:t}},m=(e,t)=>{for(let n=t.length-1;n>=0;n--)if(e>=t[n])return{char:e-t[n],line:n};return{char:0,line:0}},h=e=>/^(#|rgb|hsl|var\(--.*?\)|transparent|currentColor|inherit|initial|unset)/i.test(e)||/^[a-z]+$/i.test(e),g=(e,t,n,r)=>{let{lines:i,lineStarts:a}=p(e),o={};return t.forEach(e=>{let t=m(e.start,a),n=m(e.end-1,a);for(let r=t.line;r<=n.line;r++){o[r]||(o[r]=[]);let t=a[r],n=Math.max(e.start-t,0),s=Math.min(e.end-t,i[r].length);s>n&&o[r].push({absoluteStart:e.start,className:e.className,end:s,start:n,style:e.style})}}),i.map((e,t)=>{let i=n[t];return r(e,t,o[t]||[],i)})},_=(e,t,n,r)=>a(()=>g(e,t,n,r),[e,t,n,r]),v=(e,t)=>{if(!e||!t)return;let{scrollLeft:n,scrollTop:r}=e;t.scrollTop=r,t.scrollLeft=n},y=(e,t,n=getComputedStyle)=>{if(!e||!t)return;let r=n(e);t.style.padding=r.padding,t.style.fontSize=r.fontSize,t.style.fontFamily=r.fontFamily,t.style.lineHeight=r.lineHeight,t.style.letterSpacing=r.letterSpacing,t.style.wordSpacing=r.wordSpacing,t.style.textIndent=r.textIndent,t.style.whiteSpace=r.whiteSpace,t.style.wordBreak=r.wordBreak,t.style.overflowWrap=r.overflowWrap,t.style.tabSize=r.tabSize,t.style.borderTopWidth=r.borderTopWidth,t.style.borderRightWidth=r.borderRightWidth,t.style.borderBottomWidth=r.borderBottomWidth,t.style.borderLeftWidth=r.borderLeftWidth,t.style.borderTopStyle=r.borderTopStyle,t.style.borderRightStyle=r.borderRightStyle,t.style.borderBottomStyle=r.borderBottomStyle,t.style.borderLeftStyle=r.borderLeftStyle,t.style.borderColor=`transparent`;let i=parseFloat(r.borderLeftWidth)||0,a=parseFloat(r.borderRightWidth)||0,o=e.offsetWidth-e.clientWidth-i-a;if(o>0)if(r.direction===`rtl`){let e=parseFloat(r.paddingLeft)||0;t.style.paddingLeft=`${e+o}px`}else{let e=parseFloat(r.paddingRight)||0;t.style.paddingRight=`${e+o}px`}},b=(e,t,r,i,a)=>{let s=o(null);return{highlightLayerRef:s,syncScroll:n(n=>{let o={scrollLeft:s.current?.scrollLeft,scrollTop:s.current?.scrollTop};v(n.current,s.current);let c={scrollLeft:s.current?.scrollLeft,scrollTop:s.current?.scrollTop};e?.record(`syncScroll`,`sync`,{after:c,before:o,changed:o.scrollTop!==c.scrollTop||o.scrollLeft!==c.scrollLeft},t??n,r?.()??``,i?.(),a??!1)},[e,t,r,i,a]),syncStyles:n(n=>{if(!n.current||!s.current)return;let o=getComputedStyle(n.current),c=n.current.offsetWidth-n.current.clientWidth-(parseFloat(o.borderLeftWidth)||0)-(parseFloat(o.borderRightWidth)||0);y(n.current,s.current),e?.record(`syncStyles`,`sync`,{direction:o.direction,fontSize:o.fontSize,padding:o.padding,scrollbarWidth:c},t??n,r?.()??``,i?.(),a??!1)},[e,t,r,i,a])}},x=(e,t,n,r,i)=>{if(!e)return;let a=e.value;a!==t&&(n||r(a),i?.(a))},S=(e,t,n,r,i)=>{e!==t&&(n||r(e),i?.(e))},C=(e,t,n,r,i)=>{e&&(e.value=t,n||r(t),i?.(t))},w=(e,t=``,i,a,c,l)=>{let u=o(null),[d,f]=s(e??t),p=e!==void 0,m=p?e??``:d,h=c??u,g=n(()=>{x(h.current,m,p,f,i)},[m,p,i,h]),_=n(e=>{let t=e.target.value;a?.record(`onChange`,`user`,{lengthDelta:t.length-m.length,newValue:t,previousValue:m,valueLength:t.length},h,m,l?.(),p),S(t,m,p,f,i)},[m,p,i,a,h,l]),v=n(e=>{a?.record(`setValue`,`state`,{newValue:e,previousValue:m},h,m,l?.(),p),C(h.current,e,p,f,i)},[p,i,a,h,l,m]);return r(()=>{g()},[g]),r(()=>{p&&h.current&&h.current.value!==m&&(h.current.value=m)},[p,m,h]),r(()=>{h.current&&h.current.value!==m&&a?.record(`valueMismatch`,`state`,{domValue:h.current.value,stateValue:m},h,m,l?.(),p)},[m,p,a,h,l]),{currentValue:m,handleChange:_,setValue:v,textareaRef:h}},T={display:`block`,position:`relative`,width:`100%`},E={background:`transparent`,boxSizing:`border-box`,caretColor:`#000000`,color:`transparent`,minHeight:`auto`,position:`relative`,width:`100%`,zIndex:2},D={border:`0px none transparent`,bottom:0,boxSizing:`border-box`,color:`inherit`,fontFamily:`inherit`,fontSize:`inherit`,left:0,lineHeight:`inherit`,margin:0,overflow:`hidden`,pointerEvents:`none`,position:`absolute`,right:0,top:0,whiteSpace:`pre-wrap`,wordWrap:`break-word`,zIndex:1};var O=class{events=[];maxEvents=1e3;enabled=!1;lastEventTimestamp=null;issueRegistry=new Map;constructor(e=!1,t=1e3){this.enabled=e,this.maxEvents=t}setEnabled(e){this.enabled=e}record(e,t,n,r,i,a,o){if(!this.enabled)return;let s=Date.now(),c=this.lastEventTimestamp?s-this.lastEventTimestamp:null,l=r.current?.value??``,u=i??``,d=l===u,f=[];if(d||(f.push(`State mismatch: DOM="${l}" vs React="${u}"`),this.issueRegistry.set(`state_mismatch`,(this.issueRegistry.get(`state_mismatch`)??0)+1)),c!==null&&c<5&&(f.push(`Rapid event: ${c}ms since last event`),this.issueRegistry.set(`rapid_events`,(this.issueRegistry.get(`rapid_events`)??0)+1)),t===`user`&&e===`onChange`){let e=Math.abs(l.length-u.length);e>100&&(f.push(`Large paste detected: ${e} characters changed`),this.issueRegistry.set(`large_paste`,(this.issueRegistry.get(`large_paste`)??0)+1))}let p={anomalies:f,category:t,data:n,description:this.generateDescription(e,t,n),stateSnapshot:{isControlled:o,reactValue:u,textareaHeight:a,textareaValue:l,valuesMatch:d},timeSinceLastEvent:c,timestamp:s,timestampISO:new Date(s).toISOString(),type:e};this.events.push(p),this.lastEventTimestamp=s,this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents))}generateDescription(e,t,n){switch(e){case`onChange`:return`User typed/pasted text. New length: ${n.valueLength}`;case`autoResize`:return`Textarea auto-resized from ${n.beforeHeight}px to ${n.afterHeight}px`;case`syncScroll`:return`Synchronized scroll position to top:${n.after?.scrollTop??0}`;case`syncStyles`:return`Synchronized styles (padding, font, borders) between textarea and overlay`;case`valueMismatch`:return`CRITICAL: DOM value differs from React state`;case`setValue`:return`Programmatic value change via ref.setValue()`;case`snapshot`:return`Periodic state snapshot for debugging`;default:return`${t} event: ${e}`}}generateAIReport(t,n,r,i,a){let o=this.events[0],s=this.events[this.events.length-1],c=s&&o?s.timestamp-o.timestamp:0,l=[];for(let[e,t]of this.issueRegistry.entries()){let n=this.events.map((t,n)=>t.anomalies.some(t=>t.includes(e))?n:-1).filter(e=>e!==-1),r=n.length>0?this.events[n[0]].timestampISO:``,i=`info`,a=e;e===`state_mismatch`?(i=`critical`,a=`State desynchronization between DOM and React detected`):e===`rapid_events`?(i=t>10?`warning`:`info`,a=`Rapid successive events detected (possible race condition)`):e===`large_paste`&&(i=`warning`,a=`Large paste operations detected (may trigger sync issues)`),l.push({firstOccurrence:r,issue:a,occurrenceCount:t,relatedEvents:n,severity:i})}l.sort((e,t)=>{let n={critical:0,info:2,warning:1};return n[e.severity]-n[t.severity]});let u=[],d=this.events.filter(e=>e.type===`autoResize`),f=this.events.filter(e=>e.type===`onChange`);d.length>f.length*2&&u.push(`Excessive resize operations (${d.length} resizes vs ${f.length} value changes). May indicate infinite ResizeObserver loop.`);let p=this.events.filter(e=>e.category===`sync`);p.length>this.events.length*.3&&u.push(`High frequency of sync operations (${p.length}/${this.events.length} events). May indicate layout thrashing.`);let m=[];l.some(e=>e.issue.includes(`desynchronization`))&&m.push(`State desynchronization detected. Check if multiple onChange handlers are bound or if external code is modifying the textarea DOM directly.`),u.some(e=>e.includes(`ResizeObserver`))&&m.push(`Possible infinite ResizeObserver loop. Ensure resize operations are debounced with requestAnimationFrame.`),l.some(e=>e.issue.includes(`race condition`))&&m.push(`Rapid events detected. Consider debouncing onChange handlers or checking for double-bound event listeners.`);let h={stateChanges:this.events.filter(e=>e.category===`state`).map(e=>({after:e.data.newValue,before:e.data.previousValue,timestamp:e.timestampISO,type:e.type,unexpected:e.anomalies.length>0})),syncOperations:this.events.filter(e=>e.category===`sync`).map(e=>({details:e.data,operation:e.type,success:!e.anomalies.length,timestamp:e.timestampISO})),userActions:this.events.filter(e=>e.category===`user`).map(e=>({action:e.description,resultingStateChanges:this.events.filter(t=>t.timestamp>e.timestamp&&t.timestamp<e.timestamp+100&&t.category===`state`).length,timestamp:e.timestampISO}))};return{events:this.events,finalState:{height:r,highlights:i,inSync:(t.current?.value??``)===(n??``),reactValue:n??``,scrollPosition:{left:t.current?.scrollLeft??0,top:t.current?.scrollTop??0},textareaValue:t.current?.value??``},metadata:{browser:navigator.userAgent,componentVersion:`1.1.3`,generatedAt:new Date().toISOString(),platform:navigator.platform,reactVersion:e.version??`unknown`,timespan:{durationMs:c,end:s?.timestampISO??``,start:o?.timestampISO??``},totalEvents:this.events.length},summary:{description:l.length>0?`Found ${l.length} issue(s) during ${this.events.length} recorded events over ${(c/1e3).toFixed(1)}s`:`No issues detected during ${this.events.length} events over ${(c/1e3).toFixed(1)}s`,detectedIssues:l,recommendations:m,suspiciousPatterns:u},timeline:h}}exportForAI(e,t,n,r,i){let a=this.generateAIReport(e,t,n,r,i);return JSON.stringify({aiInstructions:{commonIssues:{rapidEvents:`Events firing <5ms apart - possible race condition or double-bound handlers`,resizeLoop:`Excessive resize operations - likely infinite ResizeObserver loop`,stateMismatch:`DOM value differs from React state - likely caused by multiple onChange handlers or direct DOM manipulation`},keyFields:{"events[].anomalies":`Issues detected at each event`,"events[].stateSnapshot":`Full state at each event for comparison`,finalState:`Current state at time of export`,"summary.detectedIssues":`Automatically detected problems, sorted by severity`,"timeline.stateChanges":`Chronological view of all state mutations`},purpose:`This is a debug report from the DyeLight React component. A textarea with highlighting overlay is experiencing synchronization issues.`,yourTask:[`1. Review the summary.detectedIssues for critical problems`,`2. Examine timeline.stateChanges for unexpected state transitions`,`3. Look for patterns in events where stateSnapshot.valuesMatch is false`,`4. Check for rapid events (<5ms apart) that might indicate race conditions`,`5. Identify the root cause and suggest specific code fixes`]},debugReport:a},null,2)}clear(){this.events=[],this.issueRegistry.clear(),this.lastEventTimestamp=null}};const k=(e,t,n)=>{if(!n)return c(`div`,{children:e},t);let r=h(n);return c(`div`,{className:r?void 0:n,style:r?{backgroundColor:n}:void 0,children:e},t)},A=(e,t,n,r)=>{if(n.length===0)return k(e||`\xA0`,t,r);let i=n.toSorted((e,t)=>e.start-t.start),a=[],o=0;if(i.forEach((n,r)=>{let{className:i,end:s,start:l,style:u}=n,d=Math.max(0,Math.min(l,e.length)),f=Math.max(d,Math.min(s,e.length));if(f<=o)return;let p=Math.max(d,o);if(p>o){let t=e.slice(o,p);t&&a.push(t)}if(f>p){let o=e.slice(p,f);a.push(c(`span`,{className:i,style:u,"data-range-start":n.absoluteStart,children:o},`highlight-${t}-${r.toString()}`))}o=Math.max(o,f)}),o<e.length){let t=e.slice(o);t&&a.push(t)}return k(a.length===0?`\xA0`:a,t,r)},j=t(({className:e=``,containerClassName:t=``,defaultValue:s=``,dir:u=`ltr`,enableAutoResize:d=!0,highlights:p=[],lineHighlights:m={},onChange:h,rows:g=4,style:v,value:y,debug:x=!1,debugMaxEvents:S=1e3,...C},k)=>{let j=o(null),M=o(void 0),N=a(()=>new O(x,S),[x,S]);r(()=>{N.setEnabled(x)},[x,N]);let P=y!==void 0,F=n(()=>M.current,[]),{currentValue:I,handleChange:L,setValue:R,textareaRef:z}=w(y,s,h,N,void 0,F),B=n(()=>I,[I]),{handleAutoResize:V,textareaHeight:H}=f(d,N,z,B,P);r(()=>{M.current=H},[H]);let{highlightLayerRef:U,syncScroll:W,syncStyles:G}=b(N,z,B,F,P),K=_(I,p,m,A),q=n(e=>{L(e),V(e.target)},[L,V]),J=n(e=>{R(e),z.current&&V(z.current)},[R,V,z]);r(()=>{},[]);let Y=n(()=>{W(z)},[W,z]);r(()=>{if(!x)return;let e=setInterval(()=>{N.record(`snapshot`,`system`,{},z,I,H,P)},1e3);return()=>clearInterval(e)},[x,N,z,I,H,P]),i(k,()=>({blur:()=>z.current?.blur(),exportForAI:()=>N.exportForAI(z,I,H,p,m),focus:()=>z.current?.focus(),getValue:()=>I,scrollToPosition:(e,t=40,n=`auto`)=>{if(U.current&&z.current){let r=U.current.querySelector(`[data-range-start="${e.toString()}"]`);if(r instanceof HTMLElement){let e=z.current,i=r.offsetTop;n===`smooth`?e.scrollTo({behavior:`smooth`,top:i-t}):e.scrollTop=i-t}}},select:()=>z.current?.select(),setSelectionRange:(e,t)=>z.current?.setSelectionRange(e,t),setValue:J}),[I,J,U,z,N,H,p,m]),r(()=>{z.current&&d&&V(z.current),G(z)},[I,V,d,G,z]),r(()=>{if(!z.current)return;let e=z.current,t,n=new ResizeObserver(()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>{G(z),d&&V(e)})});return n.observe(e),()=>{n.disconnect(),cancelAnimationFrame(t)}},[z,G,V,d]);let X={...E,color:I?`transparent`:`inherit`,height:H?`${H}px`:void 0,resize:d?`none`:`vertical`},Z={...D,direction:u,height:H?`${H}px`:void 0,padding:z.current?getComputedStyle(z.current).padding:`8px 12px`};return l(`div`,{className:t,ref:j,style:{...T,...v},children:[c(`div`,{"aria-hidden":`true`,ref:U,style:Z,children:K}),c(`textarea`,{className:e,dir:u,onChange:q,onScroll:Y,ref:z,rows:g,style:X,value:I,...C})]})});j.displayName=`DyeLight`;export{O as AIOptimizedTelemetry,j as DyeLight,u as HighlightBuilder,d as autoResize,k as createLineElement,A as renderHighlightedLine};
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["renderHighlightedLine"],"sources":["../src/builder.ts","../src/domUtils.ts","../src/hooks/useAutoResize.ts","../src/textUtils.ts","../src/hooks/useHighlightedContent.ts","../src/hooks/useHighlightSync.ts","../src/hooks/useTextareaValue.ts","../src/styles.ts","../src/DyeLight.tsx"],"sourcesContent":["/**\n * @fileoverview HighlightBuilder - Utility functions for creating highlight objects\n *\n * This module provides a convenient API for building highlight configurations\n * for the DyeLight component. It includes methods for creating character-level\n * highlights, line-level highlights, pattern-based highlights, and more.\n */\n\nimport type React from 'react';\n\n/**\n * Utility functions for building highlight objects for the DyeLight component\n * Provides a fluent API for creating various types of text highlights\n */\nexport const HighlightBuilder = {\n /**\n * Creates highlights for individual characters using absolute positions\n * @param chars - Array of character highlight configurations\n * @param chars[].index - Zero-based character index in the text\n * @param chars[].className - Optional CSS class name to apply\n * @param chars[].style - Optional inline styles to apply\n * @returns Array of character range highlights\n * @example\n * ```tsx\n * // Highlight characters at positions 5, 10, and 15\n * const highlights = HighlightBuilder.characters([\n * { index: 5, className: 'highlight-error' },\n * { index: 10, className: 'highlight-warning' },\n * { index: 15, style: { backgroundColor: 'yellow' } }\n * ]);\n * ```\n */\n characters: (chars: Array<{ className?: string; index: number; style?: React.CSSProperties }>) => {\n return chars.map(({ className, index, style }) => ({ className, end: index + 1, start: index, style }));\n },\n\n /**\n * Creates line highlights for entire lines\n * @param lines - Array of line highlight configurations\n * @param lines[].line - Zero-based line number\n * @param lines[].className - Optional CSS class name to apply to the line\n * @param lines[].color - Optional color value (CSS color, hex, rgb, etc.)\n * @returns Object mapping line numbers to highlight values\n * @example\n * ```tsx\n * // Highlight lines 0 and 2 with different styles\n * const lineHighlights = HighlightBuilder.lines([\n * { line: 0, className: 'error-line' },\n * { line: 2, color: '#ffff00' }\n * ]);\n * ```\n */\n lines: (lines: Array<{ className?: string; color?: string; line: number }>) => {\n const result: { [lineNumber: number]: string } = {};\n lines.forEach(({ className, color, line }) => {\n result[line] = className || color || '';\n });\n return result;\n },\n\n /**\n * Highlights text matching a pattern using absolute positions\n * @param text - The text to search within\n * @param pattern - Regular expression or string pattern to match\n * @param className - Optional CSS class name to apply to matches\n * @param style - Optional inline styles to apply to matches\n * @returns Array of character range highlights for all matches\n * @example\n * ```tsx\n * // Highlight all JavaScript keywords\n * const highlights = HighlightBuilder.pattern(\n * code,\n * /\\b(function|const|let|var|if|else|for|while)\\b/g,\n * 'keyword-highlight'\n * );\n *\n * // Highlight all email addresses\n * const emailHighlights = HighlightBuilder.pattern(\n * text,\n * /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b/g,\n * 'email-highlight'\n * );\n * ```\n */\n pattern: (text: string, pattern: RegExp | string, className?: string, style?: React.CSSProperties) => {\n const regex = typeof pattern === 'string' ? new RegExp(pattern, 'g') : new RegExp(pattern.source, 'g');\n const matches = Array.from(text.matchAll(regex));\n\n return matches.map((match) => ({ className, end: match.index! + match[0].length, start: match.index!, style }));\n },\n\n /**\n * Creates character range highlights using absolute positions\n * @param ranges - Array of character range configurations\n * @param ranges[].start - Zero-based start index (inclusive)\n * @param ranges[].end - Zero-based end index (exclusive)\n * @param ranges[].className - Optional CSS class name to apply\n * @param ranges[].style - Optional inline styles to apply\n * @returns Array of character range highlights\n * @example\n * ```tsx\n * // Highlight specific ranges in the text\n * const highlights = HighlightBuilder.ranges([\n * { start: 0, end: 5, className: 'title-highlight' },\n * { start: 10, end: 20, style: { backgroundColor: 'yellow' } },\n * { start: 25, end: 30, className: 'error-highlight' }\n * ]);\n * ```\n */\n ranges: (ranges: Array<{ className?: string; end: number; start: number; style?: React.CSSProperties }>) => {\n return ranges.map(({ className, end, start, style }) => ({ className, end, start, style }));\n },\n\n /**\n * Highlights text between specific start and end positions\n * Convenience method for highlighting a single selection range\n * @param start - Zero-based start index (inclusive)\n * @param end - Zero-based end index (exclusive)\n * @param className - Optional CSS class name to apply\n * @param style - Optional inline styles to apply\n * @returns Array containing a single character range highlight\n * @example\n * ```tsx\n * // Highlight a selection from position 10 to 25\n * const selectionHighlight = HighlightBuilder.selection(\n * 10,\n * 25,\n * 'selection-highlight'\n * );\n * ```\n */\n selection: (start: number, end: number, className?: string, style?: React.CSSProperties) => {\n return [{ className, end, start, style }];\n },\n\n /**\n * Highlights entire words that match specific terms\n * @param text - The text to search within\n * @param words - Array of words to highlight\n * @param className - Optional CSS class name to apply to matched words\n * @param style - Optional inline styles to apply to matched words\n * @returns Array of character range highlights for all matched words\n * @example\n * ```tsx\n * // Highlight specific programming keywords\n * const highlights = HighlightBuilder.words(\n * sourceCode,\n * ['function', 'const', 'let', 'var', 'return'],\n * 'keyword'\n * );\n *\n * // Highlight important terms with custom styling\n * const termHighlights = HighlightBuilder.words(\n * document,\n * ['TODO', 'FIXME', 'NOTE'],\n * undefined,\n * { backgroundColor: 'orange', fontWeight: 'bold' }\n * );\n * ```\n */\n words: (text: string, words: string[], className?: string, style?: React.CSSProperties) => {\n const pattern = new RegExp(`\\\\b(${words.join('|')})\\\\b`, 'g');\n return HighlightBuilder.pattern(text, pattern, className, style);\n },\n};\n","/**\n * @fileoverview DOM utility functions for textarea manipulation\n *\n * This module provides utility functions for working with DOM elements,\n * specifically focused on textarea auto-resizing functionality used by\n * the DyeLight component.\n */\n\n/**\n * Automatically resizes a textarea element to fit its content\n *\n * This function adjusts the textarea height to match its scroll height,\n * effectively removing scrollbars when the content fits and expanding\n * the textarea as content is added. The height is first set to 'auto'\n * to allow the element to shrink if content is removed.\n *\n * @param textArea - The HTML textarea element to resize\n * @example\n * ```ts\n * const textarea = document.querySelector('textarea');\n * if (textarea) {\n * autoResize(textarea);\n * }\n *\n * // Or in an event handler:\n * const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n * autoResize(e.target);\n * };\n * ```\n */\nexport const autoResize = (textArea: HTMLTextAreaElement) => {\n const computedStyle = getComputedStyle(textArea);\n const borderTop = parseFloat(computedStyle.borderTopWidth) || 0;\n const borderBottom = parseFloat(computedStyle.borderBottomWidth) || 0;\n\n // Reset height to auto to force accurate scrollHeight calculation (shrink if needed)\n textArea.style.height = 'auto';\n\n const scrollHeight = textArea.scrollHeight;\n const totalBorderHeight = borderTop + borderBottom;\n\n // Only add border compensation if borders are significant (> 2px), otherwise trust scrollHeight\n // This handles browser differences in how scrollHeight reports when box-sizing is border-box\n const finalHeight = totalBorderHeight > 2 ? scrollHeight + totalBorderHeight : scrollHeight;\n\n // Set height including borders for border-box\n textArea.style.height = `${finalHeight}px`;\n};\n","import { useCallback, useState } from 'react';\n\nimport { autoResize } from '@/domUtils';\n\nexport const createAutoResizeHandler = (\n enableAutoResize: boolean,\n setTextareaHeight: (height: number | undefined) => void,\n resize: (element: HTMLTextAreaElement) => void = autoResize,\n) => {\n return (element: HTMLTextAreaElement) => {\n if (!enableAutoResize) {\n return;\n }\n\n resize(element);\n setTextareaHeight(element.scrollHeight);\n };\n};\n\n/**\n * Hook for managing textarea auto-resize functionality\n */\nexport const useAutoResize = (enableAutoResize: boolean) => {\n const [textareaHeight, setTextareaHeight] = useState<number | undefined>();\n\n /**\n * Handles automatic resizing of the textarea based on content\n */\n const handleAutoResize = useCallback(\n (element: HTMLTextAreaElement) => {\n if (!enableAutoResize) {\n return;\n }\n autoResize(element);\n setTextareaHeight(element.scrollHeight);\n },\n [enableAutoResize],\n );\n\n return { handleAutoResize, textareaHeight };\n};\n","/**\n * @fileoverview Text utility functions for position calculations and text processing\n *\n * This module provides utilities for converting between absolute text positions\n * and line-relative positions, as well as other text processing functions used\n * by the DyeLight component for highlight positioning.\n */\n\n/**\n * Analyzes text content and returns line information with position mappings\n * @param text - The text content to analyze\n * @returns Object containing lines array and line start positions\n * @returns returns.lines - Array of individual lines (without newline characters)\n * @returns returns.lineStarts - Array of absolute positions where each line starts\n * @example\n * ```ts\n * const text = \"Hello\\nWorld\\nTest\";\n * const { lines, lineStarts } = getLinePositions(text);\n * // lines: [\"Hello\", \"World\", \"Test\"]\n * // lineStarts: [0, 6, 12]\n * ```\n */\nexport const getLinePositions = (text: string) => {\n const lines = text.split('\\n');\n const lineStarts: number[] = [];\n let position = 0;\n\n lines.forEach((line, index) => {\n lineStarts.push(position);\n position += line.length + (index < lines.length - 1 ? 1 : 0); // +1 for \\n except last line\n });\n\n return { lineStarts, lines };\n};\n\n/**\n * Converts an absolute text position to line-relative coordinates\n * @param absolutePos - Zero-based absolute position in the entire text\n * @param lineStarts - Array of line start positions (from getLinePositions)\n * @returns Object containing line number and character position within that line\n * @returns returns.line - Zero-based line number\n * @returns returns.char - Zero-based character position within the line\n * @example\n * ```ts\n * const text = \"Hello\\nWorld\\nTest\";\n * const { lineStarts } = getLinePositions(text);\n * const pos = absoluteToLinePos(8, lineStarts);\n * // pos: { line: 1, char: 2 } (the 'r' in \"World\")\n * ```\n */\nexport const absoluteToLinePos = (absolutePos: number, lineStarts: number[]) => {\n for (let i = lineStarts.length - 1; i >= 0; i--) {\n if (absolutePos >= lineStarts[i]) {\n return { char: absolutePos - lineStarts[i], line: i };\n }\n }\n return { char: 0, line: 0 };\n};\n\n/**\n * Determines if a string value represents a CSS color value\n * @param value - The string value to test\n * @returns True if the value appears to be a color value, false otherwise\n * @example\n * ```ts\n * isColorValue('#ff0000'); // true\n * isColorValue('rgb(255, 0, 0)'); // true\n * isColorValue('red'); // true\n * isColorValue('my-css-class'); // false (contains hyphens)\n * isColorValue('transparent'); // true\n * isColorValue('var(--primary-color)'); // true\n * ```\n */\nexport const isColorValue = (value: string): boolean => {\n return (\n /^(#|rgb|hsl|var\\(--.*?\\)|transparent|currentColor|inherit|initial|unset)/i.test(value) ||\n /^[a-z]+$/i.test(value)\n );\n};\n","import { useMemo } from 'react';\nimport { absoluteToLinePos, getLinePositions } from '@/textUtils';\nimport type { CharacterRange } from '@/types';\n\nexport const computeHighlightedContent = (\n text: string,\n highlights: CharacterRange[],\n lineHighlights: { [lineNumber: number]: string },\n renderHighlightedLine: (\n line: string,\n lineIndex: number,\n ranges: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>,\n lineHighlight?: string,\n ) => React.ReactElement,\n) => {\n const { lines, lineStarts } = getLinePositions(text);\n\n const highlightsByLine: {\n [lineIndex: number]: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>;\n } = {};\n\n highlights.forEach((highlight) => {\n const startPos = absoluteToLinePos(highlight.start, lineStarts);\n const endPos = absoluteToLinePos(highlight.end - 1, lineStarts);\n\n for (let lineIndex = startPos.line; lineIndex <= endPos.line; lineIndex++) {\n if (!highlightsByLine[lineIndex]) {\n highlightsByLine[lineIndex] = [];\n }\n\n const lineStart = lineStarts[lineIndex];\n\n const rangeStart = Math.max(highlight.start - lineStart, 0);\n const rangeEnd = Math.min(highlight.end - lineStart, lines[lineIndex].length);\n\n if (rangeEnd > rangeStart) {\n highlightsByLine[lineIndex].push({\n absoluteStart: highlight.start,\n className: highlight.className,\n end: rangeEnd,\n start: rangeStart,\n style: highlight.style,\n });\n }\n }\n });\n\n return lines.map((line, lineIndex) => {\n const lineHighlight = lineHighlights[lineIndex];\n const ranges = highlightsByLine[lineIndex] || [];\n\n return renderHighlightedLine(line, lineIndex, ranges, lineHighlight);\n });\n};\n\n/**\n * Hook for computing highlighted content from text and highlight ranges\n */\nexport const useHighlightedContent = (\n text: string,\n highlights: CharacterRange[],\n lineHighlights: { [lineNumber: number]: string },\n renderHighlightedLine: (\n line: string,\n lineIndex: number,\n ranges: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>,\n lineHighlight?: string,\n ) => React.ReactElement,\n) => {\n /**\n * Computes the highlighted content by processing text and highlight ranges\n * Groups highlights by line and renders each line with appropriate highlighting\n */\n const highlightedContent = useMemo(\n () => computeHighlightedContent(text, highlights, lineHighlights, renderHighlightedLine),\n [text, highlights, lineHighlights, renderHighlightedLine],\n );\n\n return highlightedContent;\n};\n","import { useCallback, useRef } from 'react';\n\nexport const syncScrollPositions = (\n textarea: Pick<HTMLTextAreaElement, 'scrollLeft' | 'scrollTop'> | null,\n highlightLayer: Pick<HTMLDivElement, 'scrollLeft' | 'scrollTop'> | null,\n) => {\n if (!textarea || !highlightLayer) {\n return;\n }\n\n const { scrollLeft, scrollTop } = textarea;\n highlightLayer.scrollTop = scrollTop;\n highlightLayer.scrollLeft = scrollLeft;\n};\n\nexport const syncHighlightStyles = (\n textarea: HTMLTextAreaElement | null,\n highlightLayer: HTMLDivElement | null,\n computeStyle: (element: Element) => CSSStyleDeclaration = getComputedStyle,\n) => {\n if (!textarea || !highlightLayer) {\n return;\n }\n\n const computedStyle = computeStyle(textarea);\n\n highlightLayer.style.padding = computedStyle.padding;\n highlightLayer.style.fontSize = computedStyle.fontSize;\n highlightLayer.style.fontFamily = computedStyle.fontFamily;\n highlightLayer.style.lineHeight = computedStyle.lineHeight;\n highlightLayer.style.letterSpacing = computedStyle.letterSpacing;\n highlightLayer.style.wordSpacing = computedStyle.wordSpacing;\n highlightLayer.style.textIndent = computedStyle.textIndent;\n\n // Sync wrapping strategies to ensure identical layout\n highlightLayer.style.whiteSpace = computedStyle.whiteSpace;\n highlightLayer.style.wordBreak = computedStyle.wordBreak;\n highlightLayer.style.overflowWrap = computedStyle.overflowWrap;\n highlightLayer.style.tabSize = computedStyle.tabSize;\n\n // Sync border width and style to ensure box-model matches, but keep transparent\n highlightLayer.style.borderTopWidth = computedStyle.borderTopWidth;\n highlightLayer.style.borderRightWidth = computedStyle.borderRightWidth;\n highlightLayer.style.borderBottomWidth = computedStyle.borderBottomWidth;\n highlightLayer.style.borderLeftWidth = computedStyle.borderLeftWidth;\n highlightLayer.style.borderTopStyle = computedStyle.borderTopStyle;\n highlightLayer.style.borderRightStyle = computedStyle.borderRightStyle;\n highlightLayer.style.borderBottomStyle = computedStyle.borderBottomStyle;\n highlightLayer.style.borderLeftStyle = computedStyle.borderLeftStyle;\n highlightLayer.style.borderColor = 'transparent';\n\n // Calculate scrollbar width to ensure content width is identical\n // offsetWidth includes borders, padding, and scrollbar\n // clientWidth includes padding but excludes borders and scrollbar\n // scrollbarWidth = offsetWidth - clientWidth - (borderLeft + borderRight)\n const borderLeft = parseFloat(computedStyle.borderLeftWidth) || 0;\n const borderRight = parseFloat(computedStyle.borderRightWidth) || 0;\n const scrollbarWidth = textarea.offsetWidth - textarea.clientWidth - borderLeft - borderRight;\n\n if (scrollbarWidth > 0) {\n const isRTL = computedStyle.direction === 'rtl';\n if (isRTL) {\n const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;\n highlightLayer.style.paddingLeft = `${paddingLeft + scrollbarWidth}px`;\n } else {\n const paddingRight = parseFloat(computedStyle.paddingRight) || 0;\n highlightLayer.style.paddingRight = `${paddingRight + scrollbarWidth}px`;\n }\n }\n};\n\n/**\n * Hook for managing highlight layer synchronization\n */\nexport const useHighlightSync = () => {\n const highlightLayerRef = useRef<HTMLDivElement>(null);\n\n const syncScroll = useCallback((textareaRef: React.RefObject<HTMLTextAreaElement | null>) => {\n syncScrollPositions(textareaRef.current, highlightLayerRef.current);\n }, []);\n\n const syncStyles = useCallback((textareaRef: React.RefObject<HTMLTextAreaElement | null>) => {\n syncHighlightStyles(textareaRef.current, highlightLayerRef.current);\n }, []);\n\n return { highlightLayerRef, syncScroll, syncStyles };\n};\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nexport const syncValueWithDOM = (\n textarea: HTMLTextAreaElement | null,\n currentValue: string,\n isControlled: boolean,\n setInternalValue: (value: string) => void,\n onChange?: (value: string) => void,\n) => {\n if (!textarea) {\n return;\n }\n\n const domValue = textarea.value;\n if (domValue !== currentValue) {\n if (!isControlled) {\n setInternalValue(domValue);\n }\n onChange?.(domValue);\n }\n};\n\nexport const handleChangeValue = (\n newValue: string,\n currentValue: string,\n isControlled: boolean,\n setInternalValue: (value: string) => void,\n onChange?: (value: string) => void,\n) => {\n if (newValue === currentValue) {\n return;\n }\n\n if (!isControlled) {\n setInternalValue(newValue);\n }\n\n onChange?.(newValue);\n};\n\nexport const applySetValue = (\n textarea: HTMLTextAreaElement | null,\n newValue: string,\n isControlled: boolean,\n setInternalValue: (value: string) => void,\n onChange?: (value: string) => void,\n) => {\n if (!textarea) {\n return;\n }\n\n textarea.value = newValue;\n\n if (!isControlled) {\n setInternalValue(newValue);\n }\n\n onChange?.(newValue);\n};\n\n/**\n * Hook for managing textarea value state and synchronization\n * Handles both controlled and uncontrolled modes, plus programmatic changes\n */\nexport const useTextareaValue = (value?: string, defaultValue = '', onChange?: (value: string) => void) => {\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const [internalValue, setInternalValue] = useState(value ?? defaultValue);\n\n const isControlled = value !== undefined;\n const currentValue = isControlled ? value : internalValue;\n\n const syncValueWithDOMCallback = useCallback(() => {\n syncValueWithDOM(textareaRef.current, currentValue, isControlled, setInternalValue, onChange);\n }, [currentValue, isControlled, onChange]);\n\n const handleChange = useCallback(\n (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n handleChangeValue(e.target.value, currentValue, isControlled, setInternalValue, onChange);\n },\n [currentValue, isControlled, onChange],\n );\n\n const setValue = useCallback(\n (newValue: string) => {\n applySetValue(textareaRef.current, newValue, isControlled, setInternalValue, onChange);\n },\n [isControlled, onChange],\n );\n\n useEffect(() => {\n syncValueWithDOMCallback();\n }, [syncValueWithDOMCallback]);\n\n useEffect(() => {\n if (isControlled && textareaRef.current && textareaRef.current.value !== value) {\n textareaRef.current.value = value;\n }\n }, [isControlled, value]);\n\n return { currentValue, handleChange, setValue, textareaRef };\n};\n","/**\n * @fileoverview Default styles for DyeLight component elements\n *\n * This module contains the default CSS-in-JS styles used by the DyeLight component\n * for its container, textarea, and highlight layer elements. These styles ensure\n * proper layering, positioning, and visual alignment between the textarea and\n * its highlight overlay.\n */\n\nimport type React from 'react';\n\n/**\n * Default styles for the main container element that wraps the entire component\n * Creates a positioned container that serves as the reference for absolutely positioned children\n */\nexport const DEFAULT_CONTAINER_STYLE: React.CSSProperties = {\n /** Ensures the container behaves as a block-level element */\n display: 'block',\n /** Enables absolute positioning for child elements */\n position: 'relative',\n /** Takes full width of parent container */\n width: '100%',\n};\n\n/**\n * Default styles for the textarea element\n * Makes the textarea transparent while maintaining its functionality and positioning\n */\nexport const DEFAULT_BASE_STYLE: React.CSSProperties = {\n /** Transparent background to show highlights underneath */\n background: 'transparent',\n /** Ensures consistent box model calculations */\n boxSizing: 'border-box',\n /** Maintains visible text cursor */\n caretColor: '#000000',\n /** Transparent text to reveal highlights while keeping cursor and selection */\n color: 'transparent',\n /** Prevents unwanted height constraints */\n minHeight: 'auto',\n /** Positioned above the highlight layer */\n position: 'relative',\n /** Takes full width of container */\n width: '100%',\n /** Ensures textarea appears above highlight layer */\n zIndex: 2,\n};\n\n/**\n * Default styles for the highlight layer that renders behind the textarea\n * Positioned absolutely to overlay perfectly with the textarea content\n */\nexport const DEFAULT_HIGHLIGHT_LAYER_STYLE: React.CSSProperties = {\n /** Transparent border to match textarea default border - now synced dynamically */\n border: '0px none transparent',\n /** Stretch to fill container bottom */\n bottom: 0,\n /** Consistent box model with textarea */\n boxSizing: 'border-box',\n /** Inherit text color from parent */\n color: 'inherit',\n /** Match textarea font family */\n fontFamily: 'inherit',\n /** Match textarea font size */\n fontSize: 'inherit',\n /** Stretch to fill container left */\n left: 0,\n /** Match textarea line height */\n lineHeight: 'inherit',\n /** Remove default margins */\n margin: 0,\n /** Hide scrollbars on highlight layer */\n overflow: 'hidden',\n /** Prevent highlight layer from capturing mouse events */\n pointerEvents: 'none',\n /** Positioned absolutely within container */\n position: 'absolute',\n /** Stretch to fill container right */\n right: 0,\n /** Stretch to fill container top */\n top: 0,\n /** Preserve whitespace and line breaks like textarea */\n whiteSpace: 'pre-wrap',\n /** Break long words like textarea */\n wordWrap: 'break-word',\n /** Ensure highlight layer appears behind textarea */\n zIndex: 1,\n};\n","import type React from 'react';\nimport { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react';\nimport { useAutoResize } from './hooks/useAutoResize';\nimport { useHighlightedContent } from './hooks/useHighlightedContent';\nimport { useHighlightSync } from './hooks/useHighlightSync';\nimport { useTextareaValue } from './hooks/useTextareaValue';\nimport { DEFAULT_BASE_STYLE, DEFAULT_CONTAINER_STYLE, DEFAULT_HIGHLIGHT_LAYER_STYLE } from './styles';\nimport { isColorValue } from './textUtils';\nimport type { DyeLightProps, DyeLightRef } from './types';\n\n/**\n * @fileoverview DyeLight - A React textarea component with advanced text highlighting capabilities\n *\n * This component provides a textarea with overlay-based text highlighting that supports:\n * - Character-level highlighting using absolute text positions\n * - Line-level highlighting with CSS classes or color values\n * - Automatic height adjustment based on content\n * - Synchronized scrolling between textarea and highlight layer\n * - Both controlled and uncontrolled usage patterns\n * - RTL text direction support\n */\n\n/**\n * Creates a line element with optional highlighting\n */\nexport const createLineElement = (\n content: React.ReactNode,\n lineIndex: number,\n lineHighlight?: string,\n): React.ReactElement => {\n if (!lineHighlight) {\n return <div key={lineIndex}>{content}</div>;\n }\n\n const isColor = isColorValue(lineHighlight);\n return (\n <div\n className={isColor ? undefined : lineHighlight}\n key={lineIndex}\n style={isColor ? { backgroundColor: lineHighlight } : undefined}\n >\n {content}\n </div>\n );\n};\n\n/**\n * Renders a single line with character-level highlights and optional line-level highlighting\n */\nexport const renderHighlightedLine = (\n line: string,\n lineIndex: number,\n ranges: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>,\n lineHighlight?: string,\n): React.ReactElement => {\n if (ranges.length === 0) {\n const content = line || '\\u00A0';\n return createLineElement(content, lineIndex, lineHighlight);\n }\n\n // Sort ranges by start position\n const sortedRanges = ranges.toSorted((a, b) => a.start - b.start);\n\n const result: React.ReactNode[] = [];\n let lastIndex = 0;\n\n sortedRanges.forEach((range, idx) => {\n const { className, end, start, style: rangeStyle } = range;\n\n // Clamp range to line bounds\n const clampedStart = Math.max(0, Math.min(start, line.length));\n const clampedEnd = Math.max(clampedStart, Math.min(end, line.length));\n\n // Add text before highlight\n if (clampedStart > lastIndex) {\n const textBefore = line.slice(lastIndex, clampedStart);\n if (textBefore) {\n result.push(textBefore);\n }\n }\n\n // Add highlighted text\n if (clampedEnd > clampedStart) {\n const highlightedText = line.slice(clampedStart, clampedEnd);\n result.push(\n <span\n className={className}\n key={`highlight-${lineIndex}-${idx.toString()}`}\n style={rangeStyle}\n data-range-start={range.absoluteStart}\n >\n {highlightedText}\n </span>,\n );\n }\n\n lastIndex = Math.max(lastIndex, clampedEnd);\n });\n\n // Add remaining text\n if (lastIndex < line.length) {\n const textAfter = line.slice(lastIndex);\n if (textAfter) {\n result.push(textAfter);\n }\n }\n\n const content = result.length === 0 ? '\\u00A0' : result;\n return createLineElement(content, lineIndex, lineHighlight);\n};\n\n/**\n * A textarea component with support for highlighting character ranges using absolute positions\n * and optional line-level highlighting. Perfect for syntax highlighting, error indication,\n * and text annotation without the complexity of line-based positioning.\n */\nexport const DyeLight = forwardRef<DyeLightRef, DyeLightProps>(\n (\n {\n className = '',\n containerClassName = '',\n defaultValue = '',\n dir = 'ltr',\n enableAutoResize = true,\n highlights = [],\n lineHighlights = {},\n onChange,\n rows = 4,\n style,\n value,\n ...props\n },\n ref,\n ) => {\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Custom hooks for managing component logic\n const { currentValue, handleChange, setValue, textareaRef } = useTextareaValue(value, defaultValue, onChange);\n\n const { handleAutoResize, textareaHeight } = useAutoResize(enableAutoResize);\n\n const { highlightLayerRef, syncScroll, syncStyles } = useHighlightSync();\n\n const highlightedContent = useHighlightedContent(\n currentValue,\n highlights,\n lineHighlights,\n renderHighlightedLine,\n );\n\n // Enhanced change handler that includes auto-resize\n const handleChangeWithResize = useCallback(\n (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n handleChange(e);\n handleAutoResize(e.target);\n },\n [handleChange, handleAutoResize],\n );\n\n // Enhanced setValue that includes auto-resize\n const setValueWithResize = useCallback(\n (newValue: string) => {\n setValue(newValue);\n if (textareaRef.current) {\n handleAutoResize(textareaRef.current);\n }\n },\n [setValue, handleAutoResize, textareaRef],\n );\n\n // Scroll handler with ref binding\n useEffect(() => {}, []);\n\n const handleScroll = useCallback(() => {\n syncScroll(textareaRef);\n }, [syncScroll, textareaRef]);\n\n // Expose ref methods\n useImperativeHandle(\n ref,\n () => ({\n blur: () => textareaRef.current?.blur(),\n focus: () => textareaRef.current?.focus(),\n getValue: () => currentValue,\n scrollToPosition: (pos: number, offset = 40, behavior: ScrollBehavior = 'auto') => {\n if (highlightLayerRef.current && textareaRef.current) {\n const span = highlightLayerRef.current.querySelector(`[data-range-start=\"${pos.toString()}\"]`);\n if (span instanceof HTMLElement) {\n const textarea = textareaRef.current;\n const spanTop = span.offsetTop;\n if (behavior === 'smooth') {\n textarea.scrollTo({ behavior: 'smooth', top: spanTop - offset });\n } else {\n textarea.scrollTop = spanTop - offset;\n }\n }\n }\n },\n select: () => textareaRef.current?.select(),\n setSelectionRange: (start: number, end: number) => textareaRef.current?.setSelectionRange(start, end),\n setValue: setValueWithResize,\n }),\n [currentValue, setValueWithResize, highlightLayerRef, textareaRef],\n );\n\n // Sync styles and handle auto-resize on value changes\n // 'currentValue' is a dependency to ensure we trigger resize/sync when the value prop changes programmatically\n useEffect(() => {\n if (textareaRef.current && enableAutoResize) {\n handleAutoResize(textareaRef.current);\n }\n syncStyles(textareaRef);\n }, [currentValue, handleAutoResize, enableAutoResize, syncStyles, textareaRef]);\n\n // Use ResizeObserver to handle structural changes (e.g. container resize, scrollbar appearance)\n useEffect(() => {\n if (!textareaRef.current) {\n return;\n }\n\n const textarea = textareaRef.current;\n let rafId: number;\n\n const observer = new ResizeObserver(() => {\n cancelAnimationFrame(rafId);\n rafId = requestAnimationFrame(() => {\n syncStyles(textareaRef);\n // We re-trigger auto-resize in case width changed and text wrapped\n if (enableAutoResize) {\n handleAutoResize(textarea);\n }\n });\n });\n\n observer.observe(textarea);\n return () => {\n observer.disconnect();\n cancelAnimationFrame(rafId);\n };\n }, [textareaRef, syncStyles, handleAutoResize, enableAutoResize]);\n\n // Compute styles\n const baseTextareaStyle: React.CSSProperties = {\n ...DEFAULT_BASE_STYLE,\n color: currentValue ? 'transparent' : 'inherit',\n height: textareaHeight ? `${textareaHeight}px` : undefined,\n resize: enableAutoResize ? 'none' : 'vertical',\n };\n\n const highlightLayerStyle: React.CSSProperties = {\n ...DEFAULT_HIGHLIGHT_LAYER_STYLE,\n direction: dir,\n height: textareaHeight ? `${textareaHeight}px` : undefined,\n padding: textareaRef.current ? getComputedStyle(textareaRef.current).padding : '8px 12px',\n };\n\n return (\n <div className={containerClassName} ref={containerRef} style={{ ...DEFAULT_CONTAINER_STYLE, ...style }}>\n <div aria-hidden=\"true\" ref={highlightLayerRef} style={highlightLayerStyle}>\n {highlightedContent}\n </div>\n\n <textarea\n className={className}\n dir={dir}\n onChange={handleChangeWithResize}\n onScroll={handleScroll}\n ref={textareaRef}\n rows={rows}\n style={baseTextareaStyle}\n value={currentValue}\n {...props}\n />\n </div>\n );\n },\n);\n\nDyeLight.displayName = 'DyeLight';\n"],"mappings":"qLAcA,MAAa,EAAmB,CAkB5B,WAAa,GACF,EAAM,KAAK,CAAE,YAAW,QAAO,YAAa,CAAE,YAAW,IAAK,EAAQ,EAAG,MAAO,EAAO,QAAO,EAAE,CAmB3G,MAAQ,GAAuE,CAC3E,IAAM,EAA2C,EAAE,CAInD,OAHA,EAAM,SAAS,CAAE,YAAW,QAAO,UAAW,CAC1C,EAAO,GAAQ,GAAa,GAAS,IACvC,CACK,GA2BX,SAAU,EAAc,EAA0B,EAAoB,IAAgC,CAClG,IAAM,EAAQ,OAAO,GAAY,SAAW,IAAI,OAAO,EAAS,IAAI,CAAG,IAAI,OAAO,EAAQ,OAAQ,IAAI,CAGtG,OAFgB,MAAM,KAAK,EAAK,SAAS,EAAM,CAAC,CAEjC,IAAK,IAAW,CAAE,YAAW,IAAK,EAAM,MAAS,EAAM,GAAG,OAAQ,MAAO,EAAM,MAAQ,QAAO,EAAE,EAqBnH,OAAS,GACE,EAAO,KAAK,CAAE,YAAW,MAAK,QAAO,YAAa,CAAE,YAAW,MAAK,QAAO,QAAO,EAAE,CAqB/F,WAAY,EAAe,EAAa,EAAoB,IACjD,CAAC,CAAE,YAAW,MAAK,QAAO,QAAO,CAAC,CA4B7C,OAAQ,EAAc,EAAiB,EAAoB,IAAgC,CACvF,IAAM,EAAc,OAAO,OAAO,EAAM,KAAK,IAAI,CAAC,MAAO,IAAI,CAC7D,OAAO,EAAiB,QAAQ,EAAM,EAAS,EAAW,EAAM,EAEvE,CCtIY,EAAc,GAAkC,CACzD,IAAM,EAAgB,iBAAiB,EAAS,CAC1C,EAAY,WAAW,EAAc,eAAe,EAAI,EACxD,EAAe,WAAW,EAAc,kBAAkB,EAAI,EAGpE,EAAS,MAAM,OAAS,OAExB,IAAM,EA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,GAEhC,CAAC,EAAa,EAAY,EAAkB,EAAiB,CAAC,CAGjE,IAAM,EAAyC,CAC3C,GAAG,EACH,MAAO,EAAe,cAAgB,UACtC,OAAQ,EAAiB,GAAG,EAAe,IAAM,IAAA,GACjD,OAAQ,EAAmB,OAAS,WACvC,CAEK,EAA2C,CAC7C,GAAG,EACH,UAAW,EACX,OAAQ,EAAiB,GAAG,EAAe,IAAM,IAAA,GACjD,QAAS,EAAY,QAAU,iBAAiB,EAAY,QAAQ,CAAC,QAAU,WAClF,CAED,OACI,EAAC,MAAA,CAAI,UAAW,EAAoB,IAAK,EAAc,MAAO,CAAE,GAAG,EAAyB,GAAG,EAAO,WAClG,EAAC,MAAA,CAAI,cAAY,OAAO,IAAK,EAAmB,MAAO,WAClD,GACC,CAEN,EAAC,WAAA,CACc,YACN,MACL,SAAU,EACV,SAAU,EACV,IAAK,EACC,OACN,MAAO,EACP,MAAO,EACP,GAAI,GACN,CAAA,EACA,EAGjB,CAED,EAAS,YAAc"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/builder.ts","../src/domUtils.ts","../src/hooks/useAutoResize.ts","../src/textUtils.ts","../src/hooks/useHighlightedContent.ts","../src/hooks/useHighlightSync.ts","../src/hooks/useTextareaValue.ts","../src/styles.ts","../src/telemetry.ts","../src/DyeLight.tsx"],"sourcesContent":["/**\n * @fileoverview HighlightBuilder - Utility functions for creating highlight objects\n *\n * This module provides a convenient API for building highlight configurations\n * for the DyeLight component. It includes methods for creating character-level\n * highlights, line-level highlights, pattern-based highlights, and more.\n */\n\nimport type React from 'react';\n\n/**\n * Utility functions for building highlight objects for the DyeLight component\n * Provides a fluent API for creating various types of text highlights\n */\nexport const HighlightBuilder = {\n /**\n * Creates highlights for individual characters using absolute positions\n * @param chars - Array of character highlight configurations\n * @param chars[].index - Zero-based character index in the text\n * @param chars[].className - Optional CSS class name to apply\n * @param chars[].style - Optional inline styles to apply\n * @returns Array of character range highlights\n * @example\n * ```tsx\n * // Highlight characters at positions 5, 10, and 15\n * const highlights = HighlightBuilder.characters([\n * { index: 5, className: 'highlight-error' },\n * { index: 10, className: 'highlight-warning' },\n * { index: 15, style: { backgroundColor: 'yellow' } }\n * ]);\n * ```\n */\n characters: (chars: Array<{ className?: string; index: number; style?: React.CSSProperties }>) => {\n return chars.map(({ className, index, style }) => ({ className, end: index + 1, start: index, style }));\n },\n\n /**\n * Creates line highlights for entire lines\n * @param lines - Array of line highlight configurations\n * @param lines[].line - Zero-based line number\n * @param lines[].className - Optional CSS class name to apply to the line\n * @param lines[].color - Optional color value (CSS color, hex, rgb, etc.)\n * @returns Object mapping line numbers to highlight values\n * @example\n * ```tsx\n * // Highlight lines 0 and 2 with different styles\n * const lineHighlights = HighlightBuilder.lines([\n * { line: 0, className: 'error-line' },\n * { line: 2, color: '#ffff00' }\n * ]);\n * ```\n */\n lines: (lines: Array<{ className?: string; color?: string; line: number }>) => {\n const result: { [lineNumber: number]: string } = {};\n lines.forEach(({ className, color, line }) => {\n result[line] = className || color || '';\n });\n return result;\n },\n\n /**\n * Highlights text matching a pattern using absolute positions\n * @param text - The text to search within\n * @param pattern - Regular expression or string pattern to match\n * @param className - Optional CSS class name to apply to matches\n * @param style - Optional inline styles to apply to matches\n * @returns Array of character range highlights for all matches\n * @example\n * ```tsx\n * // Highlight all JavaScript keywords\n * const highlights = HighlightBuilder.pattern(\n * code,\n * /\\b(function|const|let|var|if|else|for|while)\\b/g,\n * 'keyword-highlight'\n * );\n *\n * // Highlight all email addresses\n * const emailHighlights = HighlightBuilder.pattern(\n * text,\n * /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b/g,\n * 'email-highlight'\n * );\n * ```\n */\n pattern: (text: string, pattern: RegExp | string, className?: string, style?: React.CSSProperties) => {\n const regex = typeof pattern === 'string' ? new RegExp(pattern, 'g') : new RegExp(pattern.source, 'g');\n const matches = Array.from(text.matchAll(regex));\n\n return matches.map((match) => ({ className, end: match.index! + match[0].length, start: match.index!, style }));\n },\n\n /**\n * Creates character range highlights using absolute positions\n * @param ranges - Array of character range configurations\n * @param ranges[].start - Zero-based start index (inclusive)\n * @param ranges[].end - Zero-based end index (exclusive)\n * @param ranges[].className - Optional CSS class name to apply\n * @param ranges[].style - Optional inline styles to apply\n * @returns Array of character range highlights\n * @example\n * ```tsx\n * // Highlight specific ranges in the text\n * const highlights = HighlightBuilder.ranges([\n * { start: 0, end: 5, className: 'title-highlight' },\n * { start: 10, end: 20, style: { backgroundColor: 'yellow' } },\n * { start: 25, end: 30, className: 'error-highlight' }\n * ]);\n * ```\n */\n ranges: (ranges: Array<{ className?: string; end: number; start: number; style?: React.CSSProperties }>) => {\n return ranges.map(({ className, end, start, style }) => ({ className, end, start, style }));\n },\n\n /**\n * Highlights text between specific start and end positions\n * Convenience method for highlighting a single selection range\n * @param start - Zero-based start index (inclusive)\n * @param end - Zero-based end index (exclusive)\n * @param className - Optional CSS class name to apply\n * @param style - Optional inline styles to apply\n * @returns Array containing a single character range highlight\n * @example\n * ```tsx\n * // Highlight a selection from position 10 to 25\n * const selectionHighlight = HighlightBuilder.selection(\n * 10,\n * 25,\n * 'selection-highlight'\n * );\n * ```\n */\n selection: (start: number, end: number, className?: string, style?: React.CSSProperties) => {\n return [{ className, end, start, style }];\n },\n\n /**\n * Highlights entire words that match specific terms\n * @param text - The text to search within\n * @param words - Array of words to highlight\n * @param className - Optional CSS class name to apply to matched words\n * @param style - Optional inline styles to apply to matched words\n * @returns Array of character range highlights for all matched words\n * @example\n * ```tsx\n * // Highlight specific programming keywords\n * const highlights = HighlightBuilder.words(\n * sourceCode,\n * ['function', 'const', 'let', 'var', 'return'],\n * 'keyword'\n * );\n *\n * // Highlight important terms with custom styling\n * const termHighlights = HighlightBuilder.words(\n * document,\n * ['TODO', 'FIXME', 'NOTE'],\n * undefined,\n * { backgroundColor: 'orange', fontWeight: 'bold' }\n * );\n * ```\n */\n words: (text: string, words: string[], className?: string, style?: React.CSSProperties) => {\n const pattern = new RegExp(`\\\\b(${words.join('|')})\\\\b`, 'g');\n return HighlightBuilder.pattern(text, pattern, className, style);\n },\n};\n","/**\n * @fileoverview DOM utility functions for textarea manipulation\n *\n * This module provides utility functions for working with DOM elements,\n * specifically focused on textarea auto-resizing functionality used by\n * the DyeLight component.\n */\n\n/**\n * Automatically resizes a textarea element to fit its content\n *\n * This function adjusts the textarea height to match its scroll height,\n * effectively removing scrollbars when the content fits and expanding\n * the textarea as content is added. The height is first set to 'auto'\n * to allow the element to shrink if content is removed.\n *\n * @param textArea - The HTML textarea element to resize\n * @example\n * ```ts\n * const textarea = document.querySelector('textarea');\n * if (textarea) {\n * autoResize(textarea);\n * }\n *\n * // Or in an event handler:\n * const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n * autoResize(e.target);\n * };\n * ```\n */\nexport const autoResize = (textArea: HTMLTextAreaElement) => {\n const computedStyle = getComputedStyle(textArea);\n const borderTop = parseFloat(computedStyle.borderTopWidth) || 0;\n const borderBottom = parseFloat(computedStyle.borderBottomWidth) || 0;\n\n // Reset height to auto to force accurate scrollHeight calculation (shrink if needed)\n textArea.style.height = 'auto';\n\n const scrollHeight = textArea.scrollHeight;\n const totalBorderHeight = borderTop + borderBottom;\n\n // Only add border compensation if borders are significant (> 2px), otherwise trust scrollHeight\n // This handles browser differences in how scrollHeight reports when box-sizing is border-box\n const finalHeight = totalBorderHeight > 2 ? scrollHeight + totalBorderHeight : scrollHeight;\n\n // Set height including borders for border-box\n textArea.style.height = `${finalHeight}px`;\n};\n","/**\n * @fileoverview Hook for managing textarea auto-resize functionality\n */\n\nimport { useCallback, useState } from 'react';\nimport { autoResize } from '@/domUtils';\nimport type { AIOptimizedTelemetry } from '../telemetry';\n\n/**\n * Creates an auto-resize handler function\n * @param enableAutoResize Whether auto-resize is enabled\n * @param setTextareaHeight Function to update textarea height state\n * @param resize The resize function to use (defaults to autoResize)\n * @returns Handler function that resizes the textarea\n */\nexport const createAutoResizeHandler = (\n enableAutoResize: boolean,\n setTextareaHeight: (height: number | undefined) => void,\n resize: (element: HTMLTextAreaElement) => void = autoResize,\n) => {\n return (element: HTMLTextAreaElement) => {\n if (!enableAutoResize) {\n return;\n }\n\n resize(element);\n setTextareaHeight(element.scrollHeight);\n };\n};\n\n/**\n * Hook for managing textarea auto-resize functionality\n * Automatically adjusts textarea height based on content\n *\n * @param enableAutoResize Whether to enable automatic resizing\n * @param telemetry Optional telemetry collector for debugging\n * @param textareaRef Optional textarea reference for telemetry\n * @param getCurrentValue Optional function to get current value for telemetry\n * @param isControlled Whether the component is in controlled mode\n * @returns Object containing resize handler and current height\n */\nexport const useAutoResize = (\n enableAutoResize: boolean,\n telemetry?: AIOptimizedTelemetry,\n textareaRef?: React.RefObject<HTMLTextAreaElement>,\n getCurrentValue?: () => string,\n isControlled?: boolean,\n) => {\n const [textareaHeight, setTextareaHeight] = useState<number | undefined>();\n\n /**\n * Handles automatic resizing of the textarea based on content\n * Records telemetry data if telemetry is enabled\n */\n const handleAutoResize = useCallback(\n (element: HTMLTextAreaElement) => {\n if (!enableAutoResize) {\n return;\n }\n\n const beforeHeight = element.scrollHeight;\n\n autoResize(element);\n\n const afterHeight = element.scrollHeight;\n\n telemetry?.record(\n 'autoResize',\n 'system',\n { afterHeight, beforeHeight, changed: beforeHeight !== afterHeight, textLength: element.value.length },\n textareaRef ?? { current: element },\n getCurrentValue?.() ?? element.value,\n afterHeight,\n isControlled ?? false,\n );\n\n setTextareaHeight(element.scrollHeight);\n },\n [enableAutoResize, telemetry, textareaRef, getCurrentValue, isControlled],\n );\n\n return { handleAutoResize, textareaHeight };\n};\n","/**\n * @fileoverview Text utility functions for position calculations and text processing\n *\n * This module provides utilities for converting between absolute text positions\n * and line-relative positions, as well as other text processing functions used\n * by the DyeLight component for highlight positioning.\n */\n\n/**\n * Analyzes text content and returns line information with position mappings\n * @param text - The text content to analyze\n * @returns Object containing lines array and line start positions\n * @returns returns.lines - Array of individual lines (without newline characters)\n * @returns returns.lineStarts - Array of absolute positions where each line starts\n * @example\n * ```ts\n * const text = \"Hello\\nWorld\\nTest\";\n * const { lines, lineStarts } = getLinePositions(text);\n * // lines: [\"Hello\", \"World\", \"Test\"]\n * // lineStarts: [0, 6, 12]\n * ```\n */\nexport const getLinePositions = (text: string) => {\n const lines = text.split('\\n');\n const lineStarts: number[] = [];\n let position = 0;\n\n lines.forEach((line, index) => {\n lineStarts.push(position);\n position += line.length + (index < lines.length - 1 ? 1 : 0); // +1 for \\n except last line\n });\n\n return { lineStarts, lines };\n};\n\n/**\n * Converts an absolute text position to line-relative coordinates\n * @param absolutePos - Zero-based absolute position in the entire text\n * @param lineStarts - Array of line start positions (from getLinePositions)\n * @returns Object containing line number and character position within that line\n * @returns returns.line - Zero-based line number\n * @returns returns.char - Zero-based character position within the line\n * @example\n * ```ts\n * const text = \"Hello\\nWorld\\nTest\";\n * const { lineStarts } = getLinePositions(text);\n * const pos = absoluteToLinePos(8, lineStarts);\n * // pos: { line: 1, char: 2 } (the 'r' in \"World\")\n * ```\n */\nexport const absoluteToLinePos = (absolutePos: number, lineStarts: number[]) => {\n for (let i = lineStarts.length - 1; i >= 0; i--) {\n if (absolutePos >= lineStarts[i]) {\n return { char: absolutePos - lineStarts[i], line: i };\n }\n }\n return { char: 0, line: 0 };\n};\n\n/**\n * Determines if a string value represents a CSS color value\n * @param value - The string value to test\n * @returns True if the value appears to be a color value, false otherwise\n * @example\n * ```ts\n * isColorValue('#ff0000'); // true\n * isColorValue('rgb(255, 0, 0)'); // true\n * isColorValue('red'); // true\n * isColorValue('my-css-class'); // false (contains hyphens)\n * isColorValue('transparent'); // true\n * isColorValue('var(--primary-color)'); // true\n * ```\n */\nexport const isColorValue = (value: string): boolean => {\n return (\n /^(#|rgb|hsl|var\\(--.*?\\)|transparent|currentColor|inherit|initial|unset)/i.test(value) ||\n /^[a-z]+$/i.test(value)\n );\n};\n","import { useMemo } from 'react';\nimport { absoluteToLinePos, getLinePositions } from '@/textUtils';\nimport type { CharacterRange } from '@/types';\n\nexport const computeHighlightedContent = (\n text: string,\n highlights: CharacterRange[],\n lineHighlights: { [lineNumber: number]: string },\n renderHighlightedLine: (\n line: string,\n lineIndex: number,\n ranges: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>,\n lineHighlight?: string,\n ) => React.ReactElement,\n) => {\n const { lines, lineStarts } = getLinePositions(text);\n\n const highlightsByLine: {\n [lineIndex: number]: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>;\n } = {};\n\n highlights.forEach((highlight) => {\n const startPos = absoluteToLinePos(highlight.start, lineStarts);\n const endPos = absoluteToLinePos(highlight.end - 1, lineStarts);\n\n for (let lineIndex = startPos.line; lineIndex <= endPos.line; lineIndex++) {\n if (!highlightsByLine[lineIndex]) {\n highlightsByLine[lineIndex] = [];\n }\n\n const lineStart = lineStarts[lineIndex];\n\n const rangeStart = Math.max(highlight.start - lineStart, 0);\n const rangeEnd = Math.min(highlight.end - lineStart, lines[lineIndex].length);\n\n if (rangeEnd > rangeStart) {\n highlightsByLine[lineIndex].push({\n absoluteStart: highlight.start,\n className: highlight.className,\n end: rangeEnd,\n start: rangeStart,\n style: highlight.style,\n });\n }\n }\n });\n\n return lines.map((line, lineIndex) => {\n const lineHighlight = lineHighlights[lineIndex];\n const ranges = highlightsByLine[lineIndex] || [];\n\n return renderHighlightedLine(line, lineIndex, ranges, lineHighlight);\n });\n};\n\n/**\n * Hook for computing highlighted content from text and highlight ranges\n */\nexport const useHighlightedContent = (\n text: string,\n highlights: CharacterRange[],\n lineHighlights: { [lineNumber: number]: string },\n renderHighlightedLine: (\n line: string,\n lineIndex: number,\n ranges: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>,\n lineHighlight?: string,\n ) => React.ReactElement,\n) => {\n /**\n * Computes the highlighted content by processing text and highlight ranges\n * Groups highlights by line and renders each line with appropriate highlighting\n */\n const highlightedContent = useMemo(\n () => computeHighlightedContent(text, highlights, lineHighlights, renderHighlightedLine),\n [text, highlights, lineHighlights, renderHighlightedLine],\n );\n\n return highlightedContent;\n};\n","/**\n * @fileoverview Hook for managing highlight layer synchronization\n */\n\nimport { useCallback, useRef } from 'react';\nimport type { AIOptimizedTelemetry } from '../telemetry';\n\n/**\n * Synchronizes scroll positions between textarea and highlight layer\n * @param textarea The textarea element\n * @param highlightLayer The highlight overlay element\n */\nexport const syncScrollPositions = (\n textarea: Pick<HTMLTextAreaElement, 'scrollLeft' | 'scrollTop'> | null,\n highlightLayer: Pick<HTMLDivElement, 'scrollLeft' | 'scrollTop'> | null,\n) => {\n if (!textarea || !highlightLayer) {\n return;\n }\n\n const { scrollLeft, scrollTop } = textarea;\n highlightLayer.scrollTop = scrollTop;\n highlightLayer.scrollLeft = scrollLeft;\n};\n\n/**\n * Synchronizes styles between textarea and highlight layer for pixel-perfect alignment\n * @param textarea The textarea element\n * @param highlightLayer The highlight overlay element\n * @param computeStyle Function to compute styles (defaults to getComputedStyle)\n */\nexport const syncHighlightStyles = (\n textarea: HTMLTextAreaElement | null,\n highlightLayer: HTMLDivElement | null,\n computeStyle: (element: Element) => CSSStyleDeclaration = getComputedStyle,\n) => {\n if (!textarea || !highlightLayer) {\n return;\n }\n\n const computedStyle = computeStyle(textarea);\n\n highlightLayer.style.padding = computedStyle.padding;\n highlightLayer.style.fontSize = computedStyle.fontSize;\n highlightLayer.style.fontFamily = computedStyle.fontFamily;\n highlightLayer.style.lineHeight = computedStyle.lineHeight;\n highlightLayer.style.letterSpacing = computedStyle.letterSpacing;\n highlightLayer.style.wordSpacing = computedStyle.wordSpacing;\n highlightLayer.style.textIndent = computedStyle.textIndent;\n\n highlightLayer.style.whiteSpace = computedStyle.whiteSpace;\n highlightLayer.style.wordBreak = computedStyle.wordBreak;\n highlightLayer.style.overflowWrap = computedStyle.overflowWrap;\n highlightLayer.style.tabSize = computedStyle.tabSize;\n\n highlightLayer.style.borderTopWidth = computedStyle.borderTopWidth;\n highlightLayer.style.borderRightWidth = computedStyle.borderRightWidth;\n highlightLayer.style.borderBottomWidth = computedStyle.borderBottomWidth;\n highlightLayer.style.borderLeftWidth = computedStyle.borderLeftWidth;\n highlightLayer.style.borderTopStyle = computedStyle.borderTopStyle;\n highlightLayer.style.borderRightStyle = computedStyle.borderRightStyle;\n highlightLayer.style.borderBottomStyle = computedStyle.borderBottomStyle;\n highlightLayer.style.borderLeftStyle = computedStyle.borderLeftStyle;\n highlightLayer.style.borderColor = 'transparent';\n\n const borderLeft = parseFloat(computedStyle.borderLeftWidth) || 0;\n const borderRight = parseFloat(computedStyle.borderRightWidth) || 0;\n const scrollbarWidth = textarea.offsetWidth - textarea.clientWidth - borderLeft - borderRight;\n\n if (scrollbarWidth > 0) {\n const isRTL = computedStyle.direction === 'rtl';\n if (isRTL) {\n const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;\n highlightLayer.style.paddingLeft = `${paddingLeft + scrollbarWidth}px`;\n } else {\n const paddingRight = parseFloat(computedStyle.paddingRight) || 0;\n highlightLayer.style.paddingRight = `${paddingRight + scrollbarWidth}px`;\n }\n }\n};\n\n/**\n * Hook for managing highlight layer synchronization\n * Provides functions to sync scroll and styles between textarea and overlay\n *\n * @param telemetry Optional telemetry collector for debugging\n * @param textareaRef Optional textarea reference for telemetry\n * @param getCurrentValue Optional function to get current value for telemetry\n * @param getHeight Optional function to get current height for telemetry\n * @param isControlled Whether the component is in controlled mode\n * @returns Object containing highlight layer ref and sync functions\n */\nexport const useHighlightSync = (\n telemetry?: AIOptimizedTelemetry,\n textareaRef?: React.RefObject<HTMLTextAreaElement>,\n getCurrentValue?: () => string,\n getHeight?: () => number | undefined,\n isControlled?: boolean,\n) => {\n const highlightLayerRef = useRef<HTMLDivElement>(null);\n\n /**\n * Synchronizes scroll position between textarea and highlight layer\n * @param textareaRefParam The textarea ref to sync from\n */\n const syncScroll = useCallback(\n (textareaRefParam: React.RefObject<HTMLTextAreaElement | null>) => {\n const before = {\n scrollLeft: highlightLayerRef.current?.scrollLeft,\n scrollTop: highlightLayerRef.current?.scrollTop,\n };\n\n syncScrollPositions(textareaRefParam.current, highlightLayerRef.current);\n\n const after = {\n scrollLeft: highlightLayerRef.current?.scrollLeft,\n scrollTop: highlightLayerRef.current?.scrollTop,\n };\n\n telemetry?.record(\n 'syncScroll',\n 'sync',\n {\n after,\n before,\n changed: before.scrollTop !== after.scrollTop || before.scrollLeft !== after.scrollLeft,\n },\n textareaRef ?? textareaRefParam,\n getCurrentValue?.() ?? '',\n getHeight?.(),\n isControlled ?? false,\n );\n },\n [telemetry, textareaRef, getCurrentValue, getHeight, isControlled],\n );\n\n /**\n * Synchronizes styles between textarea and highlight layer\n * @param textareaRefParam The textarea ref to sync from\n */\n const syncStyles = useCallback(\n (textareaRefParam: React.RefObject<HTMLTextAreaElement | null>) => {\n if (!textareaRefParam.current || !highlightLayerRef.current) {\n return;\n }\n\n const computedStyle = getComputedStyle(textareaRefParam.current);\n const scrollbarWidth =\n textareaRefParam.current.offsetWidth -\n textareaRefParam.current.clientWidth -\n (parseFloat(computedStyle.borderLeftWidth) || 0) -\n (parseFloat(computedStyle.borderRightWidth) || 0);\n\n syncHighlightStyles(textareaRefParam.current, highlightLayerRef.current);\n\n telemetry?.record(\n 'syncStyles',\n 'sync',\n {\n direction: computedStyle.direction,\n fontSize: computedStyle.fontSize,\n padding: computedStyle.padding,\n scrollbarWidth,\n },\n textareaRef ?? textareaRefParam,\n getCurrentValue?.() ?? '',\n getHeight?.(),\n isControlled ?? false,\n );\n },\n [telemetry, textareaRef, getCurrentValue, getHeight, isControlled],\n );\n\n return { highlightLayerRef, syncScroll, syncStyles };\n};\n","/**\n * @fileoverview Hook for managing textarea value state and synchronization\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { AIOptimizedTelemetry } from '../telemetry';\n\n/**\n * Synchronizes the textarea DOM value with React state\n * @param textarea The textarea DOM element\n * @param currentValue Current React state value\n * @param isControlled Whether the component is in controlled mode\n * @param setInternalValue Function to update internal state\n * @param onChange Optional onChange callback\n */\nexport const syncValueWithDOM = (\n textarea: HTMLTextAreaElement | null,\n currentValue: string,\n isControlled: boolean,\n setInternalValue: (value: string) => void,\n onChange?: (value: string) => void,\n) => {\n if (!textarea) {\n return;\n }\n\n const domValue = textarea.value;\n if (domValue !== currentValue) {\n if (!isControlled) {\n setInternalValue(domValue);\n }\n onChange?.(domValue);\n }\n};\n\n/**\n * Handles value changes from user input\n * @param newValue New value from user input\n * @param currentValue Current React state value\n * @param isControlled Whether the component is in controlled mode\n * @param setInternalValue Function to update internal state\n * @param onChange Optional onChange callback\n */\nexport const handleChangeValue = (\n newValue: string,\n currentValue: string,\n isControlled: boolean,\n setInternalValue: (value: string) => void,\n onChange?: (value: string) => void,\n) => {\n if (newValue === currentValue) {\n return;\n }\n\n if (!isControlled) {\n setInternalValue(newValue);\n }\n\n onChange?.(newValue);\n};\n\n/**\n * Applies a programmatic value change via setValue\n * @param textarea The textarea DOM element\n * @param newValue New value to set\n * @param isControlled Whether the component is in controlled mode\n * @param setInternalValue Function to update internal state\n * @param onChange Optional onChange callback\n */\nexport const applySetValue = (\n textarea: HTMLTextAreaElement | null,\n newValue: string,\n isControlled: boolean,\n setInternalValue: (value: string) => void,\n onChange?: (value: string) => void,\n) => {\n if (!textarea) {\n return;\n }\n\n textarea.value = newValue;\n\n if (!isControlled) {\n setInternalValue(newValue);\n }\n\n onChange?.(newValue);\n};\n\n/**\n * Hook for managing textarea value state and synchronization\n * Handles both controlled and uncontrolled modes, plus programmatic changes\n *\n * @param value Controlled value (optional)\n * @param defaultValue Default value for uncontrolled mode\n * @param onChange Callback when value changes\n * @param telemetry Optional telemetry collector for debugging\n * @param textareaRef Optional external textarea ref\n * @param getHeight Optional function to get current textarea height\n * @returns Object containing current value, change handler, setValue function, and textarea ref\n */\nexport const useTextareaValue = (\n value?: string,\n defaultValue = '',\n onChange?: (value: string) => void,\n telemetry?: AIOptimizedTelemetry,\n textareaRef?: React.RefObject<HTMLTextAreaElement>,\n getHeight?: () => number | undefined,\n) => {\n const internalTextareaRef = useRef<HTMLTextAreaElement>(null);\n const [internalValue, setInternalValue] = useState(value ?? defaultValue);\n\n const isControlled = value !== undefined;\n const currentValue = isControlled ? (value ?? '') : internalValue;\n const actualTextareaRef = textareaRef ?? internalTextareaRef;\n\n const syncValueWithDOMCallback = useCallback(() => {\n syncValueWithDOM(actualTextareaRef.current, currentValue, isControlled, setInternalValue, onChange);\n }, [currentValue, isControlled, onChange, actualTextareaRef]);\n\n const handleChange = useCallback(\n (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n const newValue = e.target.value;\n\n telemetry?.record(\n 'onChange',\n 'user',\n {\n lengthDelta: newValue.length - currentValue.length,\n newValue,\n previousValue: currentValue,\n valueLength: newValue.length,\n },\n actualTextareaRef,\n currentValue,\n getHeight?.(),\n isControlled,\n );\n\n handleChangeValue(newValue, currentValue, isControlled, setInternalValue, onChange);\n },\n [currentValue, isControlled, onChange, telemetry, actualTextareaRef, getHeight],\n );\n\n const setValue = useCallback(\n (newValue: string) => {\n telemetry?.record(\n 'setValue',\n 'state',\n { newValue, previousValue: currentValue },\n actualTextareaRef,\n currentValue,\n getHeight?.(),\n isControlled,\n );\n\n applySetValue(actualTextareaRef.current, newValue, isControlled, setInternalValue, onChange);\n },\n [isControlled, onChange, telemetry, actualTextareaRef, getHeight, currentValue],\n );\n\n useEffect(() => {\n syncValueWithDOMCallback();\n }, [syncValueWithDOMCallback]);\n\n useEffect(() => {\n if (isControlled && actualTextareaRef.current && actualTextareaRef.current.value !== currentValue) {\n actualTextareaRef.current.value = currentValue;\n }\n }, [isControlled, currentValue, actualTextareaRef]);\n\n useEffect(() => {\n if (actualTextareaRef.current && actualTextareaRef.current.value !== currentValue) {\n telemetry?.record(\n 'valueMismatch',\n 'state',\n { domValue: actualTextareaRef.current.value, stateValue: currentValue },\n actualTextareaRef,\n currentValue,\n getHeight?.(),\n isControlled,\n );\n }\n }, [currentValue, isControlled, telemetry, actualTextareaRef, getHeight]);\n\n return { currentValue, handleChange, setValue, textareaRef: actualTextareaRef };\n};\n","/**\n * @fileoverview Default styles for DyeLight component elements\n *\n * This module contains the default CSS-in-JS styles used by the DyeLight component\n * for its container, textarea, and highlight layer elements. These styles ensure\n * proper layering, positioning, and visual alignment between the textarea and\n * its highlight overlay.\n */\n\nimport type React from 'react';\n\n/**\n * Default styles for the main container element that wraps the entire component\n * Creates a positioned container that serves as the reference for absolutely positioned children\n */\nexport const DEFAULT_CONTAINER_STYLE: React.CSSProperties = {\n /** Ensures the container behaves as a block-level element */\n display: 'block',\n /** Enables absolute positioning for child elements */\n position: 'relative',\n /** Takes full width of parent container */\n width: '100%',\n};\n\n/**\n * Default styles for the textarea element\n * Makes the textarea transparent while maintaining its functionality and positioning\n */\nexport const DEFAULT_BASE_STYLE: React.CSSProperties = {\n /** Transparent background to show highlights underneath */\n background: 'transparent',\n /** Ensures consistent box model calculations */\n boxSizing: 'border-box',\n /** Maintains visible text cursor */\n caretColor: '#000000',\n /** Transparent text to reveal highlights while keeping cursor and selection */\n color: 'transparent',\n /** Prevents unwanted height constraints */\n minHeight: 'auto',\n /** Positioned above the highlight layer */\n position: 'relative',\n /** Takes full width of container */\n width: '100%',\n /** Ensures textarea appears above highlight layer */\n zIndex: 2,\n};\n\n/**\n * Default styles for the highlight layer that renders behind the textarea\n * Positioned absolutely to overlay perfectly with the textarea content\n */\nexport const DEFAULT_HIGHLIGHT_LAYER_STYLE: React.CSSProperties = {\n /** Transparent border to match textarea default border - now synced dynamically */\n border: '0px none transparent',\n /** Stretch to fill container bottom */\n bottom: 0,\n /** Consistent box model with textarea */\n boxSizing: 'border-box',\n /** Inherit text color from parent */\n color: 'inherit',\n /** Match textarea font family */\n fontFamily: 'inherit',\n /** Match textarea font size */\n fontSize: 'inherit',\n /** Stretch to fill container left */\n left: 0,\n /** Match textarea line height */\n lineHeight: 'inherit',\n /** Remove default margins */\n margin: 0,\n /** Hide scrollbars on highlight layer */\n overflow: 'hidden',\n /** Prevent highlight layer from capturing mouse events */\n pointerEvents: 'none',\n /** Positioned absolutely within container */\n position: 'absolute',\n /** Stretch to fill container right */\n right: 0,\n /** Stretch to fill container top */\n top: 0,\n /** Preserve whitespace and line breaks like textarea */\n whiteSpace: 'pre-wrap',\n /** Break long words like textarea */\n wordWrap: 'break-word',\n /** Ensure highlight layer appears behind textarea */\n zIndex: 1,\n};\n","/**\n * @fileoverview AI-Optimized Telemetry System for DyeLight\n *\n * This format is specifically designed to be parsed by LLMs for debugging.\n * It includes rich context, clear narratives, and structured anomaly detection.\n */\n\nimport React from 'react';\n\n/**\n * Represents a single telemetry event with full context\n */\nexport type AITelemetryEvent = {\n /** Unix timestamp in milliseconds */\n timestamp: number;\n /** ISO 8601 formatted timestamp */\n timestampISO: string;\n /** Milliseconds since the last event, or null for first event */\n timeSinceLastEvent: number | null;\n /** Event type identifier */\n type: string;\n /** Event category for grouping and analysis */\n category: 'state' | 'dom' | 'sync' | 'user' | 'system';\n /** Human-readable description of the event */\n description: string;\n /** Event-specific data payload */\n data: Record<string, unknown>;\n /** Complete state snapshot at the time of this event */\n stateSnapshot: {\n /** Actual value in the textarea DOM element */\n textareaValue: string;\n /** Value in React state */\n reactValue: string;\n /** Whether DOM and React state are synchronized */\n valuesMatch: boolean;\n /** Current height of the textarea in pixels */\n textareaHeight: number | undefined;\n /** Whether the component is in controlled mode */\n isControlled: boolean;\n };\n /** Detected anomalies or issues at this event */\n anomalies: string[];\n};\n\n/**\n * Complete AI-readable debug report structure\n */\nexport type AIDebugReport = {\n /** Metadata about the report and environment */\n metadata: {\n /** When this report was generated */\n generatedAt: string;\n /** DyeLight version */\n componentVersion: string;\n /** Total number of events recorded */\n totalEvents: number;\n /** Time range covered by events */\n timespan: {\n /** ISO timestamp of first event */\n start: string;\n /** ISO timestamp of last event */\n end: string;\n /** Duration in milliseconds */\n durationMs: number;\n };\n /** Browser user agent string */\n browser: string;\n /** Platform identifier */\n platform: string;\n /** React version */\n reactVersion: string;\n };\n\n /** Analysis summary with detected issues */\n summary: {\n /** High-level description of findings */\n description: string;\n /** List of detected issues sorted by severity */\n detectedIssues: Array<{\n /** Issue severity level */\n severity: 'critical' | 'warning' | 'info';\n /** Issue description */\n issue: string;\n /** When this issue first occurred */\n firstOccurrence: string;\n /** How many times this issue occurred */\n occurrenceCount: number;\n /** Event indices where this issue occurred */\n relatedEvents: number[];\n }>;\n /** Suspicious patterns detected in event sequences */\n suspiciousPatterns: string[];\n /** Recommended actions to resolve issues */\n recommendations: string[];\n };\n\n /** Different views of the event timeline */\n timeline: {\n /** User interactions and their impacts */\n userActions: Array<{\n /** When the action occurred */\n timestamp: string;\n /** What the user did */\n action: string;\n /** Number of state changes triggered */\n resultingStateChanges: number;\n }>;\n /** All state mutations in chronological order */\n stateChanges: Array<{\n /** When the change occurred */\n timestamp: string;\n /** Type of state change */\n type: string;\n /** Previous value */\n before: unknown;\n /** New value */\n after: unknown;\n /** Whether this change was unexpected */\n unexpected: boolean;\n }>;\n /** Synchronization operations between textarea and overlay */\n syncOperations: Array<{\n /** When the sync occurred */\n timestamp: string;\n /** Type of synchronization */\n operation: string;\n /** Whether sync was successful */\n success: boolean;\n /** Additional sync details */\n details: Record<string, unknown>;\n }>;\n };\n\n /** Complete chronological list of all events */\n events: AITelemetryEvent[];\n\n /** Final state at time of export */\n finalState: {\n /** Current textarea DOM value */\n textareaValue: string;\n /** Current React state value */\n reactValue: string;\n /** Whether values are synchronized */\n inSync: boolean;\n /** Current height in pixels */\n height: number | undefined;\n /** Current scroll position */\n scrollPosition: { top: number; left: number };\n /** Current highlights configuration */\n highlights: unknown[];\n };\n};\n\n/**\n * AI-optimized telemetry collector for the DyeLight component.\n * Records events with full context and generates comprehensive debug reports\n * that can be analyzed by AI language models.\n */\nexport class AIOptimizedTelemetry {\n private events: AITelemetryEvent[] = [];\n private maxEvents = 1000;\n private enabled = false;\n private lastEventTimestamp: number | null = null;\n private issueRegistry = new Map<string, number>();\n\n /**\n * Creates a new telemetry instance\n * @param enabled Whether telemetry collection is initially enabled\n * @param maxEvents Maximum number of events to retain in memory\n */\n constructor(enabled = false, maxEvents = 1000) {\n this.enabled = enabled;\n this.maxEvents = maxEvents;\n }\n\n /**\n * Enable or disable telemetry collection\n * @param enabled Whether to enable telemetry\n */\n setEnabled(enabled: boolean) {\n this.enabled = enabled;\n }\n\n /**\n * Records an event with full context for AI analysis\n * @param type Event type identifier\n * @param category Event category for grouping\n * @param data Event-specific data\n * @param textareaRef Reference to the textarea element\n * @param currentValue Current React state value\n * @param textareaHeight Current textarea height\n * @param isControlled Whether component is in controlled mode\n */\n record(\n type: string,\n category: 'state' | 'dom' | 'sync' | 'user' | 'system',\n data: Record<string, unknown>,\n textareaRef: React.RefObject<HTMLTextAreaElement | null>,\n currentValue: string | undefined,\n textareaHeight: number | undefined,\n isControlled: boolean,\n ) {\n if (!this.enabled) {\n return;\n }\n\n const now = Date.now();\n const timeSinceLastEvent = this.lastEventTimestamp ? now - this.lastEventTimestamp : null;\n\n const textareaValue = textareaRef.current?.value ?? '';\n const reactValue = currentValue ?? '';\n const valuesMatch = textareaValue === reactValue;\n\n const anomalies: string[] = [];\n\n if (!valuesMatch) {\n anomalies.push(`State mismatch: DOM=\"${textareaValue}\" vs React=\"${reactValue}\"`);\n this.issueRegistry.set('state_mismatch', (this.issueRegistry.get('state_mismatch') ?? 0) + 1);\n }\n\n if (timeSinceLastEvent !== null && timeSinceLastEvent < 5) {\n anomalies.push(`Rapid event: ${timeSinceLastEvent}ms since last event`);\n this.issueRegistry.set('rapid_events', (this.issueRegistry.get('rapid_events') ?? 0) + 1);\n }\n\n if (category === 'user' && type === 'onChange') {\n const lengthDelta = Math.abs(textareaValue.length - reactValue.length);\n if (lengthDelta > 100) {\n anomalies.push(`Large paste detected: ${lengthDelta} characters changed`);\n this.issueRegistry.set('large_paste', (this.issueRegistry.get('large_paste') ?? 0) + 1);\n }\n }\n\n const event: AITelemetryEvent = {\n anomalies,\n category,\n data,\n description: this.generateDescription(type, category, data),\n stateSnapshot: { isControlled, reactValue, textareaHeight, textareaValue, valuesMatch },\n timeSinceLastEvent,\n timestamp: now,\n timestampISO: new Date(now).toISOString(),\n type,\n };\n\n this.events.push(event);\n this.lastEventTimestamp = now;\n\n if (this.events.length > this.maxEvents) {\n this.events = this.events.slice(-this.maxEvents);\n }\n }\n\n /**\n * Generates a human-readable description for an event\n * @param type Event type\n * @param category Event category\n * @param data Event data\n * @returns Human-readable description\n */\n private generateDescription(type: string, category: string, data: Record<string, unknown>): string {\n switch (type) {\n case 'onChange':\n return `User typed/pasted text. New length: ${data.valueLength}`;\n case 'autoResize':\n return `Textarea auto-resized from ${data.beforeHeight}px to ${data.afterHeight}px`;\n case 'syncScroll':\n return `Synchronized scroll position to top:${(data as any).after?.scrollTop ?? 0}`;\n case 'syncStyles':\n return `Synchronized styles (padding, font, borders) between textarea and overlay`;\n case 'valueMismatch':\n return `CRITICAL: DOM value differs from React state`;\n case 'setValue':\n return `Programmatic value change via ref.setValue()`;\n case 'snapshot':\n return `Periodic state snapshot for debugging`;\n default:\n return `${category} event: ${type}`;\n }\n }\n\n /**\n * Generates a comprehensive AI-readable debug report\n * @param textareaRef Reference to the textarea element\n * @param currentValue Current React state value\n * @param textareaHeight Current textarea height\n * @param highlights Current highlights configuration\n * @param lineHighlights Current line highlights configuration\n * @returns Complete debug report\n */\n generateAIReport(\n textareaRef: React.RefObject<HTMLTextAreaElement | null>,\n currentValue: string | undefined,\n textareaHeight: number | undefined,\n highlights: unknown[],\n lineHighlights: Record<number, string>,\n ): AIDebugReport {\n const firstEvent = this.events[0];\n const lastEvent = this.events[this.events.length - 1];\n const timespan = lastEvent && firstEvent ? lastEvent.timestamp - firstEvent.timestamp : 0;\n\n const detectedIssues: AIDebugReport['summary']['detectedIssues'] = [];\n\n for (const [issueType, count] of this.issueRegistry.entries()) {\n const relatedEvents = this.events\n .map((e, i) => (e.anomalies.some((a) => a.includes(issueType)) ? i : -1))\n .filter((i) => i !== -1);\n\n const firstOccurrence = relatedEvents.length > 0 ? this.events[relatedEvents[0]].timestampISO : '';\n\n let severity: 'critical' | 'warning' | 'info' = 'info';\n let issue = issueType;\n\n if (issueType === 'state_mismatch') {\n severity = 'critical';\n issue = 'State desynchronization between DOM and React detected';\n } else if (issueType === 'rapid_events') {\n severity = count > 10 ? 'warning' : 'info';\n issue = 'Rapid successive events detected (possible race condition)';\n } else if (issueType === 'large_paste') {\n severity = 'warning';\n issue = 'Large paste operations detected (may trigger sync issues)';\n }\n\n detectedIssues.push({ firstOccurrence, issue, occurrenceCount: count, relatedEvents, severity });\n }\n\n detectedIssues.sort((a, b) => {\n const severityOrder = { critical: 0, info: 2, warning: 1 };\n return severityOrder[a.severity] - severityOrder[b.severity];\n });\n\n const suspiciousPatterns: string[] = [];\n\n const resizeEvents = this.events.filter((e) => e.type === 'autoResize');\n const valueChanges = this.events.filter((e) => e.type === 'onChange');\n if (resizeEvents.length > valueChanges.length * 2) {\n suspiciousPatterns.push(\n `Excessive resize operations (${resizeEvents.length} resizes vs ${valueChanges.length} value changes). ` +\n `May indicate infinite ResizeObserver loop.`,\n );\n }\n\n const syncEvents = this.events.filter((e) => e.category === 'sync');\n if (syncEvents.length > this.events.length * 0.3) {\n suspiciousPatterns.push(\n `High frequency of sync operations (${syncEvents.length}/${this.events.length} events). ` +\n `May indicate layout thrashing.`,\n );\n }\n\n const recommendations: string[] = [];\n\n if (detectedIssues.some((i) => i.issue.includes('desynchronization'))) {\n recommendations.push(\n 'State desynchronization detected. Check if multiple onChange handlers are bound or ' +\n 'if external code is modifying the textarea DOM directly.',\n );\n }\n\n if (suspiciousPatterns.some((p) => p.includes('ResizeObserver'))) {\n recommendations.push(\n 'Possible infinite ResizeObserver loop. Ensure resize operations are debounced with requestAnimationFrame.',\n );\n }\n\n if (detectedIssues.some((i) => i.issue.includes('race condition'))) {\n recommendations.push(\n 'Rapid events detected. Consider debouncing onChange handlers or checking for double-bound event listeners.',\n );\n }\n\n const timeline = {\n stateChanges: this.events\n .filter((e) => e.category === 'state')\n .map((e) => ({\n after: e.data.newValue,\n before: e.data.previousValue,\n timestamp: e.timestampISO,\n type: e.type,\n unexpected: e.anomalies.length > 0,\n })),\n\n syncOperations: this.events\n .filter((e) => e.category === 'sync')\n .map((e) => ({\n details: e.data,\n operation: e.type,\n success: !e.anomalies.length,\n timestamp: e.timestampISO,\n })),\n userActions: this.events\n .filter((e) => e.category === 'user')\n .map((e) => ({\n action: e.description,\n resultingStateChanges: this.events.filter(\n (se) =>\n se.timestamp > e.timestamp && se.timestamp < e.timestamp + 100 && se.category === 'state',\n ).length,\n timestamp: e.timestampISO,\n })),\n };\n\n return {\n events: this.events,\n\n finalState: {\n height: textareaHeight,\n highlights,\n inSync: (textareaRef.current?.value ?? '') === (currentValue ?? ''),\n reactValue: currentValue ?? '',\n scrollPosition: {\n left: textareaRef.current?.scrollLeft ?? 0,\n top: textareaRef.current?.scrollTop ?? 0,\n },\n textareaValue: textareaRef.current?.value ?? '',\n },\n metadata: {\n browser: navigator.userAgent,\n componentVersion: '1.1.3',\n generatedAt: new Date().toISOString(),\n platform: navigator.platform,\n reactVersion: (React as any).version ?? 'unknown',\n timespan: {\n durationMs: timespan,\n end: lastEvent?.timestampISO ?? '',\n start: firstEvent?.timestampISO ?? '',\n },\n totalEvents: this.events.length,\n },\n\n summary: {\n description:\n detectedIssues.length > 0\n ? `Found ${detectedIssues.length} issue(s) during ${this.events.length} recorded events over ${(timespan / 1000).toFixed(1)}s`\n : `No issues detected during ${this.events.length} events over ${(timespan / 1000).toFixed(1)}s`,\n detectedIssues,\n recommendations,\n suspiciousPatterns,\n },\n\n timeline,\n };\n }\n\n /**\n * Exports telemetry data in AI-optimized format with instructions\n * @param textareaRef Reference to the textarea element\n * @param currentValue Current React state value\n * @param textareaHeight Current textarea height\n * @param highlights Current highlights configuration\n * @param lineHighlights Current line highlights configuration\n * @returns JSON string containing debug report and AI instructions\n */\n exportForAI(\n textareaRef: React.RefObject<HTMLTextAreaElement | null>,\n currentValue: string | undefined,\n textareaHeight: number | undefined,\n highlights: unknown[],\n lineHighlights: Record<number, string>,\n ): string {\n const report = this.generateAIReport(textareaRef, currentValue, textareaHeight, highlights, lineHighlights);\n\n return JSON.stringify(\n {\n aiInstructions: {\n commonIssues: {\n rapidEvents: 'Events firing <5ms apart - possible race condition or double-bound handlers',\n resizeLoop: 'Excessive resize operations - likely infinite ResizeObserver loop',\n stateMismatch:\n 'DOM value differs from React state - likely caused by multiple onChange handlers or direct DOM manipulation',\n },\n keyFields: {\n 'events[].anomalies': 'Issues detected at each event',\n 'events[].stateSnapshot': 'Full state at each event for comparison',\n finalState: 'Current state at time of export',\n 'summary.detectedIssues': 'Automatically detected problems, sorted by severity',\n 'timeline.stateChanges': 'Chronological view of all state mutations',\n },\n purpose:\n 'This is a debug report from the DyeLight React component. ' +\n 'A textarea with highlighting overlay is experiencing synchronization issues.',\n yourTask: [\n '1. Review the summary.detectedIssues for critical problems',\n '2. Examine timeline.stateChanges for unexpected state transitions',\n '3. Look for patterns in events where stateSnapshot.valuesMatch is false',\n '4. Check for rapid events (<5ms apart) that might indicate race conditions',\n '5. Identify the root cause and suggest specific code fixes',\n ],\n },\n debugReport: report,\n },\n null,\n 2,\n );\n }\n\n /**\n * Clears all recorded events and issue registry\n */\n clear() {\n this.events = [];\n this.issueRegistry.clear();\n this.lastEventTimestamp = null;\n }\n}\n","import type React from 'react';\nimport { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from 'react';\nimport { useAutoResize } from './hooks/useAutoResize';\nimport { useHighlightedContent } from './hooks/useHighlightedContent';\nimport { useHighlightSync } from './hooks/useHighlightSync';\nimport { useTextareaValue } from './hooks/useTextareaValue';\nimport { DEFAULT_BASE_STYLE, DEFAULT_CONTAINER_STYLE, DEFAULT_HIGHLIGHT_LAYER_STYLE } from './styles';\nimport { AIOptimizedTelemetry } from './telemetry';\nimport { isColorValue } from './textUtils';\nimport type { DyeLightProps, DyeLightRef } from './types';\n\n/**\n * @fileoverview DyeLight - A React textarea component with advanced text highlighting capabilities\n *\n * This component provides a textarea with overlay-based text highlighting that supports:\n * - Character-level highlighting using absolute text positions\n * - Line-level highlighting with CSS classes or color values\n * - Automatic height adjustment based on content\n * - Synchronized scrolling between textarea and highlight layer\n * - Both controlled and uncontrolled usage patterns\n * - RTL text direction support\n */\n\n/**\n * Creates a line element with optional highlighting\n */\nexport const createLineElement = (\n content: React.ReactNode,\n lineIndex: number,\n lineHighlight?: string,\n): React.ReactElement => {\n if (!lineHighlight) {\n return <div key={lineIndex}>{content}</div>;\n }\n\n const isColor = isColorValue(lineHighlight);\n return (\n <div\n className={isColor ? undefined : lineHighlight}\n key={lineIndex}\n style={isColor ? { backgroundColor: lineHighlight } : undefined}\n >\n {content}\n </div>\n );\n};\n\n/**\n * Renders a single line with character-level highlights and optional line-level highlighting\n */\nexport const renderHighlightedLine = (\n line: string,\n lineIndex: number,\n ranges: Array<{\n absoluteStart: number;\n className?: string;\n end: number;\n start: number;\n style?: React.CSSProperties;\n }>,\n lineHighlight?: string,\n): React.ReactElement => {\n if (ranges.length === 0) {\n const content = line || '\\u00A0';\n return createLineElement(content, lineIndex, lineHighlight);\n }\n\n const sortedRanges = ranges.toSorted((a, b) => a.start - b.start);\n\n const result: React.ReactNode[] = [];\n let lastIndex = 0;\n\n sortedRanges.forEach((range, idx) => {\n const { className, end, start, style: rangeStyle } = range;\n\n const clampedStart = Math.max(0, Math.min(start, line.length));\n const clampedEnd = Math.max(clampedStart, Math.min(end, line.length));\n\n if (clampedEnd <= lastIndex) {\n return;\n }\n\n const effectiveStart = Math.max(clampedStart, lastIndex);\n\n if (effectiveStart > lastIndex) {\n const textBefore = line.slice(lastIndex, effectiveStart);\n if (textBefore) {\n result.push(textBefore);\n }\n }\n\n if (clampedEnd > effectiveStart) {\n const highlightedText = line.slice(effectiveStart, clampedEnd);\n result.push(\n <span\n className={className}\n key={`highlight-${lineIndex}-${idx.toString()}`}\n style={rangeStyle}\n data-range-start={range.absoluteStart}\n >\n {highlightedText}\n </span>,\n );\n }\n\n lastIndex = Math.max(lastIndex, clampedEnd);\n });\n\n if (lastIndex < line.length) {\n const textAfter = line.slice(lastIndex);\n if (textAfter) {\n result.push(textAfter);\n }\n }\n\n const content = result.length === 0 ? '\\u00A0' : result;\n return createLineElement(content, lineIndex, lineHighlight);\n};\n\n/**\n * A textarea component with support for highlighting character ranges using absolute positions\n * and optional line-level highlighting. Perfect for syntax highlighting, error indication,\n * and text annotation without the complexity of line-based positioning.\n */\nexport const DyeLight = forwardRef<DyeLightRef, DyeLightProps>(\n (\n {\n className = '',\n containerClassName = '',\n defaultValue = '',\n dir = 'ltr',\n enableAutoResize = true,\n highlights = [],\n lineHighlights = {},\n onChange,\n rows = 4,\n style,\n value,\n debug = false,\n debugMaxEvents = 1000,\n ...props\n },\n ref,\n ) => {\n const containerRef = useRef<HTMLDivElement>(null);\n const textareaHeightRef = useRef<number | undefined>(undefined);\n\n const telemetry = useMemo(() => new AIOptimizedTelemetry(debug, debugMaxEvents), [debug, debugMaxEvents]);\n\n useEffect(() => {\n telemetry.setEnabled(debug);\n }, [debug, telemetry]);\n\n const isControlled = value !== undefined;\n const getHeight = useCallback(() => textareaHeightRef.current, []);\n\n const { currentValue, handleChange, setValue, textareaRef } = useTextareaValue(\n value,\n defaultValue,\n onChange,\n telemetry,\n undefined,\n getHeight,\n );\n\n const getCurrentValue = useCallback(() => currentValue, [currentValue]);\n\n const { handleAutoResize, textareaHeight } = useAutoResize(\n enableAutoResize,\n telemetry,\n textareaRef,\n getCurrentValue,\n isControlled,\n );\n\n useEffect(() => {\n textareaHeightRef.current = textareaHeight;\n }, [textareaHeight]);\n\n const { highlightLayerRef, syncScroll, syncStyles } = useHighlightSync(\n telemetry,\n textareaRef,\n getCurrentValue,\n getHeight,\n isControlled,\n );\n\n const highlightedContent = useHighlightedContent(\n currentValue,\n highlights,\n lineHighlights,\n renderHighlightedLine,\n );\n\n const handleChangeWithResize = useCallback(\n (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n handleChange(e);\n handleAutoResize(e.target);\n },\n [handleChange, handleAutoResize],\n );\n\n const setValueWithResize = useCallback(\n (newValue: string) => {\n setValue(newValue);\n if (textareaRef.current) {\n handleAutoResize(textareaRef.current);\n }\n },\n [setValue, handleAutoResize, textareaRef],\n );\n\n useEffect(() => {}, []);\n\n const handleScroll = useCallback(() => {\n syncScroll(textareaRef);\n }, [syncScroll, textareaRef]);\n\n useEffect(() => {\n if (!debug) {\n return;\n }\n\n const intervalId = setInterval(() => {\n telemetry.record('snapshot', 'system', {}, textareaRef, currentValue, textareaHeight, isControlled);\n }, 1000);\n\n return () => clearInterval(intervalId);\n }, [debug, telemetry, textareaRef, currentValue, textareaHeight, isControlled]);\n\n useImperativeHandle(\n ref,\n () => ({\n blur: () => textareaRef.current?.blur(),\n exportForAI: () => {\n return telemetry.exportForAI(textareaRef, currentValue, textareaHeight, highlights, lineHighlights);\n },\n focus: () => textareaRef.current?.focus(),\n getValue: () => currentValue,\n scrollToPosition: (pos: number, offset = 40, behavior: ScrollBehavior = 'auto') => {\n if (highlightLayerRef.current && textareaRef.current) {\n const span = highlightLayerRef.current.querySelector(`[data-range-start=\"${pos.toString()}\"]`);\n if (span instanceof HTMLElement) {\n const textarea = textareaRef.current;\n const spanTop = span.offsetTop;\n if (behavior === 'smooth') {\n textarea.scrollTo({ behavior: 'smooth', top: spanTop - offset });\n } else {\n textarea.scrollTop = spanTop - offset;\n }\n }\n }\n },\n select: () => textareaRef.current?.select(),\n setSelectionRange: (start: number, end: number) => textareaRef.current?.setSelectionRange(start, end),\n setValue: setValueWithResize,\n }),\n [\n currentValue,\n setValueWithResize,\n highlightLayerRef,\n textareaRef,\n telemetry,\n textareaHeight,\n highlights,\n lineHighlights,\n ],\n );\n\n useEffect(() => {\n if (textareaRef.current && enableAutoResize) {\n handleAutoResize(textareaRef.current);\n }\n syncStyles(textareaRef);\n }, [currentValue, handleAutoResize, enableAutoResize, syncStyles, textareaRef]);\n\n useEffect(() => {\n if (!textareaRef.current) {\n return;\n }\n\n const textarea = textareaRef.current;\n let rafId: number;\n\n const observer = new ResizeObserver(() => {\n cancelAnimationFrame(rafId);\n rafId = requestAnimationFrame(() => {\n syncStyles(textareaRef);\n if (enableAutoResize) {\n handleAutoResize(textarea);\n }\n });\n });\n\n observer.observe(textarea);\n return () => {\n observer.disconnect();\n cancelAnimationFrame(rafId);\n };\n }, [textareaRef, syncStyles, handleAutoResize, enableAutoResize]);\n\n const baseTextareaStyle: React.CSSProperties = {\n ...DEFAULT_BASE_STYLE,\n color: currentValue ? 'transparent' : 'inherit',\n height: textareaHeight ? `${textareaHeight}px` : undefined,\n resize: enableAutoResize ? 'none' : 'vertical',\n };\n\n const highlightLayerStyle: React.CSSProperties = {\n ...DEFAULT_HIGHLIGHT_LAYER_STYLE,\n direction: dir,\n height: textareaHeight ? `${textareaHeight}px` : undefined,\n padding: textareaRef.current ? getComputedStyle(textareaRef.current).padding : '8px 12px',\n };\n\n return (\n <div className={containerClassName} ref={containerRef} style={{ ...DEFAULT_CONTAINER_STYLE, ...style }}>\n <div aria-hidden=\"true\" ref={highlightLayerRef} style={highlightLayerStyle}>\n {highlightedContent}\n </div>\n\n <textarea\n className={className}\n dir={dir}\n onChange={handleChangeWithResize}\n onScroll={handleScroll}\n ref={textareaRef}\n rows={rows}\n style={baseTextareaStyle}\n value={currentValue}\n {...props}\n />\n </div>\n );\n },\n);\n\nDyeLight.displayName = 'DyeLight';\n"],"mappings":"wLAcA,MAAa,EAAmB,CAkB5B,WAAa,GACF,EAAM,KAAK,CAAE,YAAW,QAAO,YAAa,CAAE,YAAW,IAAK,EAAQ,EAAG,MAAO,EAAO,QAAO,EAAE,CAmB3G,MAAQ,GAAuE,CAC3E,IAAM,EAA2C,EAAE,CAInD,OAHA,EAAM,SAAS,CAAE,YAAW,QAAO,UAAW,CAC1C,EAAO,GAAQ,GAAa,GAAS,IACvC,CACK,GA2BX,SAAU,EAAc,EAA0B,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P,GAAI,GACN,CAAA,EACA,EAGjB,CAED,EAAS,YAAc"}
package/package.json CHANGED
@@ -4,18 +4,18 @@
4
4
  },
5
5
  "description": "A lightweight TypeScript React component to allow highlighting characters in textareas.",
6
6
  "devDependencies": {
7
- "@biomejs/biome": "^2.3.11",
8
- "@storybook/addon-docs": "^10.1.11",
9
- "@storybook/react-vite": "^10.1.11",
7
+ "@biomejs/biome": "^2.3.13",
8
+ "@storybook/addon-docs": "^10.2.0",
9
+ "@storybook/react-vite": "^10.2.0",
10
10
  "@testing-library/dom": "^10.4.1",
11
- "@testing-library/react": "^16.3.1",
11
+ "@testing-library/react": "^16.3.2",
12
12
  "@types/bun": "^1.3.6",
13
- "@types/react": "^19.2.8",
13
+ "@types/react": "^19.2.9",
14
14
  "@types/react-dom": "^19.2.3",
15
15
  "semantic-release": "^25.0.2",
16
- "storybook": "^10.1.11",
17
- "tsdown": "^0.20.0-beta.3",
18
- "vite-tsconfig-paths": "^6.0.4"
16
+ "storybook": "^10.2.0",
17
+ "tsdown": "^0.20.1",
18
+ "vite-tsconfig-paths": "^6.0.5"
19
19
  },
20
20
  "engines": {
21
21
  "bun": ">=1.3.6",
@@ -45,8 +45,8 @@
45
45
  "name": "dyelight",
46
46
  "packageManager": "bun@1.3.6",
47
47
  "peerDependencies": {
48
- "react": "^19.2.3",
49
- "react-dom": "^19.2.3"
48
+ "react": "^19.2.4",
49
+ "react-dom": "^19.2.4"
50
50
  },
51
51
  "repository": {
52
52
  "type": "git",
@@ -61,5 +61,5 @@
61
61
  },
62
62
  "type": "module",
63
63
  "types": "./dist/index.d.mts",
64
- "version": "1.1.2"
64
+ "version": "1.2.0"
65
65
  }