@@ -507,3 +507,70 @@ function clearAndReload() {
507
507
sessionStorage . clear ( ) ;
508
508
window . location . reload ( ) ;
509
509
}
510
+
511
+ async function improveText ( textareaId ) {
512
+ const textarea = document . getElementById ( textareaId ) ;
513
+ const suggestionBox = document . getElementById ( `suggestion-${ textareaId } ` ) ;
514
+ let text = textarea . value ;
515
+
516
+ // Show loading state
517
+ suggestionBox . classList . add ( "loading" ) ;
518
+ suggestionBox . style . display = "block" ;
519
+ suggestionBox . innerText = "Checking for improvements..." ;
520
+
521
+ try {
522
+ let improved = text ;
523
+ let hasMoreErrors = true ;
524
+ let safetyCounter = 0 ; // Avoid infinite loop
525
+
526
+ while ( hasMoreErrors && safetyCounter < 5 ) {
527
+ const response = await fetch ( "https://api.languagetool.org/v2/check" , {
528
+ method : "POST" ,
529
+ headers : {
530
+ "Content-Type" : "application/x-www-form-urlencoded"
531
+ } ,
532
+ body : new URLSearchParams ( {
533
+ text : improved ,
534
+ language : "en-US"
535
+ } )
536
+ } ) ;
537
+
538
+ const data = await response . json ( ) ;
539
+ const matches = data . matches ;
540
+
541
+ if ( matches . length === 0 ) {
542
+ hasMoreErrors = false ;
543
+ break ;
544
+ }
545
+
546
+ // Fix matches from last to first
547
+ matches
548
+ . sort ( ( a , b ) => b . offset - a . offset )
549
+ . forEach ( match => {
550
+ if ( match . replacements . length > 0 ) {
551
+ const replacement = match . replacements [ 0 ] . value ;
552
+ improved =
553
+ improved . slice ( 0 , match . offset ) +
554
+ replacement +
555
+ improved . slice ( match . offset + match . length ) ;
556
+ }
557
+ } ) ;
558
+
559
+ safetyCounter ++ ;
560
+ }
561
+
562
+ suggestionBox . classList . remove ( "loading" ) ;
563
+
564
+ if ( improved !== text ) {
565
+ suggestionBox . innerHTML = `✨ <strong>Suggested:</strong> "${ improved } "` ;
566
+ } else {
567
+ suggestionBox . innerText = "✅ Your text looks good!" ;
568
+ }
569
+
570
+ } catch ( error ) {
571
+ suggestionBox . classList . remove ( "loading" ) ;
572
+ suggestionBox . innerText = "❌ Error checking grammar." ;
573
+ console . error ( error ) ;
574
+ }
575
+ }
576
+
0 commit comments