PageSourceSearch

https://www.paragraphrewriter.net/web_assets/frontend/script/home.js?v4.02

js paragraphrewriter.net collected 2026-10-02 00:12:25 UTC 31,647 bytes, 912 lines download raw bytes

1let customModeSpan = $("#custom_mode");
2let customModePopupContainer = $(".popup-container");
3let customModeCategory = $(".custom-popup .category");
4let customModeInput = $(".custom-mode");
5let customModeSubmitBtn = $(".custom-popup").find(".CustomMode-submit");
6let defaultText = "Custom";
7const CUSTOM_MODE_MAX_LEN = 25;
8let custom_image = $("#custom_image").prop("outerHTML");
9let mode6Element = $('[data-mode="1"]');
10let $bottomBar = $(".bottom-bar");
11let initialActive = $(".menu-item:first");
12let initialLeftPos = initialActive.position().left;
13let initialWidth = initialActive.outerWidth();
14let activeMode = 1;
15let formattedResponse = "";
16let hasSentInitialRequest = false; // New flag
17let requestCache = []; // New cache array
18let isRequestInFlight = false;
19
20let recentModes = JSON.parse(localStorage.getItem("recent_modes")) || [];
21$(document).ready(function () {
22    const rewriterTool = new WriterToolBase({
23        inputSelector: "#middleContent",
24        outputSelector: "#count_text",
25        cache: requestCache,
26    });
27    $bottomBar.css({ left: initialLeftPos, width: initialWidth });
28    let mode_value = $(".menu-item.active").text().trim();
29
30    
31    function syncActiveToLastCached() {
32    var $activeItem = $(".menu-item.active");
33    var activeItemMode = $activeItem.data("mode");
34
35    var activeIsCached = requestCache.some(function (entry) {
36        return entry.mode == activeItemMode;
37    });
38
39    if (activeIsCached) return; // current active mode already has a result — leave it alone
40
41    var lastEntry = requestCache[requestCache.length - 1];
42    if (!lastEntry) return; // nothing cached yet at all — nothing to fall back to
43
44    $(".menu-item").removeClass("active");
45
46    if (lastEntry.mode === 7) {
47        var customVal = (lastEntry.mode_value || "").trim();
48        customModeSpan
49            .html(`${custom_image} ${escapeHtml(customVal)}`)
50            .addClass("active")
51            .show();
52        customModeInput.val(customVal);
53        activeMode = 7;
54        mode_value = customVal;
55        $("#selected_mode").text(customVal);
56    } else {
57        var $target = $(`.menu-item[data-mode="${lastEntry.mode}"]`);
58        $target.addClass("active");
59        activeMode = lastEntry.mode;
60        mode_value = $target.text().trim();
61        $("#selected_mode").text(mode_value);
62    }
63
64    var $newActive = $(".menu-item.active");
65    if ($newActive.length > 0) {
66        $bottomBar.css({
67            left: $newActive.position().left,
68            width: $newActive.outerWidth(),
69        });
70    }
71}
72    
73
74    function findCachedByMode(mode, modeValue) {
75        rewriterTool.cache = requestCache;
76        return rewriterTool.findCached(mode, modeValue, mode === 7);
77    }
78
79    function showCachedResponse(cachedResponse) {
80        $("#loader").hide();
81        $("#mobile_loader").hide();
82        $("#collaps-container").show();
83        $("#count_text").removeClass("d-none");
84        $("#toHide").addClass("d-none");
85        $(".output-bottom").css("visibility", "visible");
86        $(".last-box").show();
87        $("#disabled").attr("disabled", false);
88
89        $("#count_text")
90            .html(cachedResponse.response)
91            .attr("contenteditable", true);
92
93        const text = $("#count_text").text();
94        $(".bottom-left-left .bottom-text")
95            .eq(0)
96            .text(sentenceCount(text) + " Sentences");
97        $(".bottom-left-right .bottom-text")
98            .eq(0)
99            .text(textWordCounter(text.trim()) + ` ${wordCountText}`);
100
101        rewriterTool.syncScroll();
102
103        if ($(window).width() < 769) {
104            $("html, body").animate(
105                {
106                    scrollTop: $("#last-box").offset().top - 100,
107                },
108                500,
109            );
110        }
111    }
112
113    function getNormalizedInputText() {
114        return rewriterTool.inputText();
115    }
116
117    function triggerRewriteRequest(isRewrite = false) {
118        if (isRequestInFlight) return;
119
120       
121
122        let fileText = getNormalizedInputText();
123        if (textWordCounter(fileText, "wordCounter") < 10) {
124            if (!isRewrite) {
125                const cachedForMode = findCachedByMode(activeMode, mode_value);
126                if (cachedForMode) {
127                    showCachedResponse(cachedForMode);
128                    
129                    return;
130                }
131            }
132            alert_box(
133                BASE_URL + "web_assets/frontend/images/not_text.svg",
134                noTextHeading,
135                noTextContent,
136                "",
137                noTextCancelBtn,
138            );
139            $("#disabled").attr("disabled", false);
140           
141            return;
142        }
143
144        const validate = validation(textWordCounter(fileText));
145        if (!validate) {
146            $("#loader").hide();
147            $("#mobile_loader").hide();
148            $("#toHide").addClass("d-none");
149            $("#disabled").attr("disabled", false);
150            
151            return;
152        }
153
154        // Check cache for existing response
155
156        rewriterTool.cache = requestCache;
157        const cachedResponse = rewriterTool.findExactCached(
158            fileText,
159            activeMode,
160            mode_value,
161            activeMode === 7,
162        );
163        if (activeMode === 7 && (!mode_value || mode_value === defaultText)) {
164                // show error
165                alert_box(
166                    BASE_URL + "web_assets/frontend/images/not_text.svg",
167                    noCustomModeTextHeading,
168                    noCustomModeTextContent,
169                    "",
170                    noTextCancelBtn,
171                );
172                $("#disabled").attr("disabled", false);
173                customModeSpan.addClass("active");
174                
175                return;
176            }
177
178        if (cachedResponse) {
179            showCachedResponse(cachedResponse);
180           
181
182            if (!isRewrite) {
183                return;
184            }
185        }
186        isRequestInFlight = true;
187        $("#middleContent").scrollTop(0);
188        $("#count_text").scrollTop(0);
189        $("#count_text").css("overflow", "hidden");
190
191        customModePopupContainer.addClass("d-none");
192        $("#loader").css("display", "flex");
193        $(".mobile_modes_dropdown").attr("overflow", "auto");
194        with_cloudflare_captcha(
195            false,
196            Date.now() / 1000,
197            sendAjaxRequest,
198            "light",
199            "#cloud_flare_captcha",
200            {
201                data: fileText,
202                mode: activeMode,
203                mode_value: mode_value,
204            },
205        );
206    }
207    const setCustomMode = function (e) {
208    e.stopPropagation();
209    var mode = $(this).text().trim().slice(0, CUSTOM_MODE_MAX_LEN);
210    $(".CustomMode-submit").removeClass("d-none");
211    customModeInput.val(mode);
212     submitCustomMode(mode);
213};
214    $(document).on("click", ".custom-popup .category", setCustomMode);
215    $(".sidebar-box").on("click", ".menu-item", function (event) {
216        // if(stoprequest){
217        //     return;
218        // }
219        const $this = $(this);
220        const isCustomMode = $this.attr("id") === "custom_mode";
221        const currentWordCount = textWordCounter(getNormalizedInputText());
222    
223        if (!isCustomMode && currentWordCount < 1) {
224            event.stopPropagation();
225            alert_box(
226                BASE_URL + "web_assets/frontend/images/not_text.svg",
227                noTextHeading,
228                noTextContent,
229                "",
230                noTextCancelBtn,
231            );
232            return;
233        }
234        if (hasSentInitialRequest && !isCustomMode) {
235            const wordCount = textWordCounter(getNormalizedInputText());
236            if (wordCount > wordLimit) {
237                event.stopPropagation();
238                validation(wordCount); // shows the limit-exceeded alert
239                return;
240            }
241        }
242        if ($("#collaps-container").hasClass("rotate_active")) {
243            $("#collaps-container").trigger("click");
244        }
245
246        $(".menu-item").removeClass("active"); // Remove active from all
247
248        if (!isCustomMode) {
249            resetToDefaultMode($this);
250        }
251        let leftPos = $this.position().left;
252
253        let width = $this.outerWidth();
254        $bottomBar.css({ left: leftPos, width: width });
255        activeMode = $this.data("mode");
256        mode_value = $this.text().trim();
257
258    
259        hasSentInitialRequest = true;
260        if (hasSentInitialRequest && !isCustomMode) {
261            triggerRewriteRequest();
262        }
263        if (textWordCounter($("#count_text").text()) < 1 && isCustomMode) {
264            $(".output-bottom").css("visibility", "hidden");
265        }
266    });
267    
268    $(".btn-box").on("click", function () {
269        triggerRewriteRequest(true);
270    });
271    
272    function handleCtrlEnterSubmit(e) {
273        if (e.repeat) return;
274        if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "a") {
275        e.preventDefault();
276        const $middleContent = $("#middleContent");
277        const range = document.createRange();
278        range.selectNodeContents($middleContent[0]);
279
280        const selection = window.getSelection();
281        selection.removeAllRanges();
282        selection.addRange(range);
283        setTimeout(() => {
284            $middleContent.trigger("blur");
285            $middleContent[0].blur();
286        }, 0);
287
288        return;
289       }
290
291        if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
292            e.preventDefault();
293            
294            if ($(".btn-box").prop("disabled")) return;
295
296            $(".btn-box").trigger("click");
297           
298        }
299    }
300    $(document).on("keydown", handleCtrlEnterSubmit);
301    $(document).on("paste", ".top-section-div", function (e) {
302        e.preventDefault();
303        var text = (e.originalEvent || e).clipboardData.getData("text/plain");
304        document.execCommand("insertText", false, text);
305    });
306    function formatDashBulletsAsList(text) {
307        let normalized = text
308            .replace(/<br\s*\/?>/gi, "\n")
309            .replace(/\r/g, "");
310        if (/^\s*-\s+/.test(normalized)) {
311            normalized = normalized.replace(/\s+-\s+/g, "\n- ");
312        }
313
314        const lines = normalized.split("\n");
315        const isBulletLine = (line) => /^\s*-\s+/.test(line);
316        if (!lines.some(isBulletLine)) return null;
317
318        let html = "";
319        let listOpen = false;
320        lines.forEach(function (line) {
321            if (isBulletLine(line)) {
322                if (!listOpen) {
323                    html += "<ul class='custom-mode-list'>";
324                    listOpen = true;
325                }
326                html += "<li>" + line.replace(/^\s*-\s+/, "").trim() + "</li>";
327            } else {
328                if (listOpen) {
329                    html += "</ul>";
330                    listOpen = false;
331                }
332                if (line.trim() !== "") {
333                    html += line + "<br>";
334                }
335            }
336        });
337        if (listOpen) html += "</ul>";
338        return html;
339    }
340
341    function sendAjaxRequest(hash, token, body) {
342        centralAjaxFunction(
343            BASE_URL + "paragraph-rewriter",
344            "POST",
345            headers,
346            {
347                emd_captcha_hash: hash,
348                emd_captcha_token: token,
349                req_key: emdGenerateReqKey(),
350                emd_is_tool_premium: emd_is_tool_premium,
351                input_text: body.data, // Convert <br> to \n for backend
352                tool_lang: dlang,
353                mode: body.mode,
354                mode_value: body.mode_value,
355                input_count: textWordCounter(body.data, "wordCounter"),
356                e_track_key: getETrackKey(),
357            },
358            function (response) {
359                isRequestInFlight = false;
360                $("#loader").hide();
361                $("#mobile_loader").hide();
362                $(".mobile_modes_dropdown").attr("id", "toggle_modes");
363
364                $("#collaps-container").show();
365                $("#count_text").removeClass("d-none");
366                $("#count_text").css("overflow-y", "auto");
367                $("#toHide").addClass("d-none");
368
369                if (response) {
370                
371                    $(".output-bottom").css("visibility", "visible");
372                    $(".last-box").show();
373                    $("#disabled").attr("disabled", false);
374
375                    // Render the response with preserved formatting
376                    let cleanAndFormattedResponse = cleanText(
377                        response.output_text_result,
378                    );
379                       
380                    const customBulletList =
381                        body.mode === 7
382                            ? formatDashBulletsAsList(cleanAndFormattedResponse)
383                            : null;
384
385                    formattedResponse =
386                        customBulletList ??
387                        boldNewWords(body.data, cleanAndFormattedResponse, true);
388
389                    $("#count_text").html(formattedResponse).attr("contenteditable", true);
390                    $(".bottom-section").css('display', 'flex');
391
392                    const text = $("#count_text").text();
393                    
394                    $(".bottom-left-left .bottom-text")
395                        .eq(0)
396                        .text(sentenceCount(text) + " Sentences");
397                    $(".bottom-left-right .bottom-text")
398                        .eq(0)
399                        .text(
400                            textWordCounter(text.trim()) + ` ${wordCountText}`,
401                        );
402
403                    // Synchronize scrolling
404                    rewriterTool.syncScroll();
405
406                    if ($(window).width() < 769) {
407                        $("html, body").animate(
408                            {
409                                scrollTop: $("#last-box").offset().top - 100,
410                            },
411                            500,
412                        );
413                    }
414                    localStorage.removeItem("synonymsCache");
415                }
416                hasSentInitialRequest = true; // Set flag after a successful request
417                // Store the request and response in cache
418                let obj = {
419                    text: body.data,
420                    mode: body.mode,
421                    response: $("#count_text").html(),
422                };
423                if (body.mode === 7) {
424                    obj.mode_value = body.mode_value;
425                }
426                requestCache.push(obj);
427
428                
429            },
430            function (xhr, status, error) {
431                isRequestInFlight = false;
432                res = xhr.responseJSON;
433                $("#loader").hide();
434                $("#mobile_loader").hide();
435                
436                syncActiveToLastCached();
437                if (xhr.status === 429) {
438                    alert_box(
439                       BASE_URL + "web_assets/frontend/images/not_text.svg",
440                        "Per Day Limit Reached",
441                        "Please try again after 24 hours",
442                        "",
443                        "Cancel",
444                    );
445                    return;
446                }
447                if (xhr.status === 401 || xhr.status === 419) {
448                    alert_box(
449                       BASE_URL + "web_assets/frontend/images/not_text.svg",
450                        "Session Expired",
451                        "Please try again",
452                        "",
453                        "Cancel",
454                    );
455                    return;
456                }
457            },
458        );
459    }
460
461    $("#count_text").on("input change", function () {
462        const updatedHtml = $(this).html().trim();
463        const updatedText = $(this).text().trim();
464
465        // ---- Update sentence & word counters ---- //
466        $(".bottom-left-left .bottom-text")
467            .eq(0)
468            .text(sentenceCount(updatedText) + " Sentences");
469        $(".bottom-left-right .bottom-text")
470            .eq(0)
471            .text(textWordCounter(updatedText) + ` ${wordCountText}`);
472
473        // ---- Update request cache so switching mode loads new edited text ---- //
474        const originalInput = getNormalizedInputText();
475        const currentMode = activeMode;
476
477        // Find item in request cache
478        const cacheIndex = requestCache.findIndex(function (item) {
479            return (
480                item.text === originalInput &&
481                item.mode === currentMode &&
482                (currentMode !== 7 || item.mode_value === mode_value)
483            );
484        });
485
486        // If found, update cached response with the user's edited output
487        if (cacheIndex !== -1) {
488            requestCache[cacheIndex].response = updatedHtml;
489        }
490        //---- Hide bottom bar if no text ---- //
491        if (textWordCounter($("#count_text").text().trim())  < 1) {
492            $(".output-bottom").css("visibility", "hidden");
493            $(".bottom-section").css("display", "none");
494
495            $(".synonyms-container").addClass("d-none");
496        } else {
497            $(".output-bottom").css("visibility", "visible");
498            $(".bottom-section").css("display", "flex");
499
500        }
501    });
502
503    $(document).on("click", "#custom_image", function (event) {
504        event.stopPropagation();
505        customModePopupContainer.removeClass("d-none");
506        if(window.innerWidth < 769){
507            $(".modes-bar").css("display", "none");
508        }
509    });
510
511function truncateTone(text, limit = CUSTOM_MODE_MAX_LEN) {
512    text = String(text).trim();
513    return text.length > limit ? text.slice(0, limit) + "..." : text;
514}
515
516function escapeHtml(str) {
517    return $("<div>").text(str).html();
518}
519    customModeSpan.on("click", function () {
520        customModePopupContainer.removeClass("d-none");
521        customModeInput.focus();
522        if (customModeInput.val().length > 0) {
523            $(".CustomMode-submit").removeClass("d-none");
524 
525        }
526        ///////------- Set recently used custom modes -------///////
527        if (recentModes.length > 0) {
528            $(".recent-tone").removeClass("d-none");
529            const container = $(".recent-tone .categories-container").empty();
530
531            recentModes.forEach((el) => {
532            const safe = escapeHtml(el);
533            container.append(
534                `<div class='category' data-full="${safe}">${escapeHtml(truncateTone(el))}</div>`
535            );
536            });
537        } else {
538            $(".recent-tone").addClass("d-none");
539        }
540
541
542        let fileText = $("#middleContent").html().trim();
543        fileText = fileText
544            .replace(/<div><br><\/div>/g, "<br>")
545            .replace(/<div>/g, "<br>")
546            .replace(/<\/div>/g, "")
547            .replace(/<br\s*\/?>/gi, "\n")
548            .replace(/&nbsp;/g, " ");
549        const customEntries = requestCache.filter(
550            (entry) => entry.text === fileText && entry.mode === 7,
551        );
552        const cachedResponse = customEntries[customEntries.length - 1];
553        if (cachedResponse) {
554            $("#count_text").html(cachedResponse.response);
555        }
556    });
557    function closeCustomModePopup() {
558        customModePopupContainer.addClass("d-none");
559
560        // If the custom input is empty when closing, skip mode=7 entries
561        const inputIsEmpty = customModeInput.val().trim() === "";
562
563        let validLastResult = null;
564        for (let i = requestCache.length - 1; i >= 0; i--) {
565            let entry = requestCache[i];
566            if (entry.mode === 7) {
567                // Skip mode=7 entirely if input was cleared
568                if (inputIsEmpty) continue;
569                let val = (entry.mode_value || "").trim();
570                if (val !== "" && val !== defaultText) {
571                    validLastResult = entry;
572                    break;
573                }
574            } else if (entry.mode) {
575                validLastResult = entry;
576                break;
577            }
578        }
579
580        $(".menu-item").removeClass("active");
581
582        if (validLastResult) {
583            if (validLastResult.mode === 7) {
584                let customVal = validLastResult.mode_value.trim();
585                customModeSpan
586                    .html(`${custom_image} ${escapeHtml(customVal)}`)
587                    .addClass("menu-item active")
588                    .show();
589                customModeInput.val(customVal);
590                activeMode = 7;
591                mode_value = customVal;
592                $("#selected_mode").text(customVal);
593            } else {
594                let $targetMode = $(`.menu-item[data-mode="${validLastResult.mode}"]`);
595                if ($targetMode.length > 0) {
596                    $targetMode.addClass("active");
597                    activeMode = validLastResult.mode;
598                    mode_value = $targetMode.text().trim();
599                    $("#selected_mode").text(mode_value);
600                } else {
601                    let $firstMode = $(".menu-item").first();
602                    $firstMode.addClass("active");
603                    activeMode = $firstMode.data("mode") || 1;
604                    mode_value = $firstMode.text().trim();
605                    $("#selected_mode").text(mode_value);
606                }
607            }
608        } else {
609            // No valid result: fall back to first mode
610            let $firstMode = $(".menu-item").first();
611            $firstMode.addClass("active");
612            activeMode = $firstMode.data("mode") || 1;
613            mode_value = $firstMode.text().trim();
614            $("#selected_mode").text(mode_value);
615        }
616
617        let $activeItem = $(".menu-item.active");
618        if ($activeItem.length > 0) {
619            $bottomBar.css({
620                left: $activeItem.position().left,
621                width: $activeItem.outerWidth()
622            });
623        }
624    }
625
626    $(".popup-close").click(function (e) {
627        closeCustomModePopup();
628    });
629
630    customModePopupContainer.on("click", function (event) {
631        if (event.target === this) {
632            closeCustomModePopup();
633        }
634    });
635
636    $(document).on("click", function (event) {
637        if (
638            $(event.target).closest($(".custom-popup")).length === 0 &&
639            $(event.target).closest($("#custom_mode")).length === 0 &&
640            !customModePopupContainer.hasClass("d-none")
641        ) {
642            closeCustomModePopup();
643        }
644    });
645
646    // When the custom-mode value is removed, show the custom_mode in its default set
647 customModeInput.on("input", function () {
648    const $this = $(this);
649    if ($this.val().length > CUSTOM_MODE_MAX_LEN) {
650        // $this.val($this.val().slice(0, CUSTOM_MODE_MAX_LEN));
651       $(".error-message").show();
652       
653    }
654    else{
655        $(".error-message").hide();
656    }
657    if ($this.val().trim() === "") {
658        customModeSpan.html(`${custom_image} ${defaultText}`);
659        $(".CustomMode-submit").addClass("d-none");
660        
661    } else {
662        $(".CustomMode-submit").removeClass("d-none");
663    }
664
665});
666    function makeCustomModeLive() {
667        ``;
668        let modeText = customModeInput.val().trim();
669        if (modeText !== "") {
670            $(".sidebar-box .menu-item").removeClass("active");
671            customModeSpan
672                .html(`${custom_image} ${modeText}`)
673                .addClass("menu-item active")
674                .show();
675            $("#selected_mode").text(modeText);
676            activeMode = 7;
676 // custom mode — needed so the result is cached/retrieved correctly
677            mode_value = modeText;
678            if ($(window).width() < 769) {
679                $(".modes-bar").css("display", "none");
680            }
681        }
682    }
683
684
685    function checkMiddleContent() {
686    const text = $("#middleContent").text().replace(/\u00A0/g, " ").trim();
687    const html = $("#middleContent").html().trim();
688
689    const $trashDesktop = $("#trash-container");
690    const $trashMobile = $("#trash-container-mobile");
691
692    if (text.length === 0) {
693        $trashDesktop.addClass("d-none");
694        $trashMobile.addClass("d-none");
695        $("#wordCounter").addClass("d-none");
696        $("#mid-id").css("display","flex");
697
698    } else {
699        $trashDesktop.removeClass("d-none");
700        $trashMobile.removeClass("d-none");
701          $("#wordCounter").removeClass("d-none");
702           $("#mid-id").css("display","none");
703    }
704}
705
706    // ✅ Add this at the bottom
707    $("#middleContent").on("input", function () {
708        checkMiddleContent();
709        if (lockKeyboardUntilManualTap) {
710            lockMobileKeyboardUntilClick();
711        }
712    });
713
714    checkMiddleContent(); // Run once on page load
715    $(document).on("paste", "#middleContent", function () {
716        lockMobileKeyboardUntilClick();
717    });
718
719    // Only explicit user tap should re-enable editing/keyboard on mobile
720    $("#middleContent").on("touchstart mousedown click", function () {
721        unlockMobileKeyboardOnUserTap();
722    });
723
724    function resetToDefaultMode(elementToActive) {
725        let currentText = customModeSpan.text().trim();
726        if (currentText !== defaultText) {
727            customModeSpan
728                .html(`${custom_image} ${currentText}`)
729                .removeClass("active");
730        }
731        // customModeInput.val("").hide();
732        customModeSpan.show();
733
734        customModeSpan.removeClass("active");
735        if (elementToActive) {
736            elementToActive.addClass("active");
737        }
738    }
739
740    // Replace the existing .trash click handler
741    $(".trash, #resetButton").on("click", function (e) {
742        e.preventDefault(); // Prevent any default behavior
743        e.stopPropagation(); // Prevent bubbling to parent elements
744
745        //--- cleare Cached data ---//
746        hasSentInitialRequest = false;
747        requestCache = [];
748
749        // Clear input and output content
750        $("#middleContent").empty();
751        $("#count_text").empty().addClass("d-none");
752        $("#count").text("0").css("color", ""); // Reset word count and color
753        $("#fileInput").val(""); // Clear file input
754        $(".tooltip-container").addClass("d-none");
755
756        // Reset UI elements
757        $("#feedbackPopup").removeClass("active");
758        $("#mid-id").removeClass("d-none");
759        $(".mid-id").css("display", "flex");
760        $("#wordCounter").addClass("d-none");
761        $("#trash-container").addClass("d-none");
762        $("#toHide").removeClass("d-none");
763        $("#last-box").removeClass("expanded collapsed");
764        $(".middle-box").removeClass("expanded collapsed");
765        $("#collaps-container").removeClass("rotate_active").hide();
766        $(".output-bottom").css("visibility", "hidden");
767        $("#last-box").css("border", "1px solid #E9ECEE");
768        $(".file-update-section").show();
769        $(".menu-item").removeClass("active");
770        $(".menu-item").first().addClass("active");
771        activeMode = $(".menu-item").first().data("mode");
772        mode_value = $(".menu-item").first().text().trim();
773        $("#selected_mode").text(mode_value);
774
775        // Reset mode selection
776
777        resetToDefaultMode(null);
778        customModeSpan.html(`${custom_image} ${defaultText}`);
779
780        // Reset counters
781        $(".bottom-left-left .bottom-text").eq(0).text("0 Sentences");
782        $(".bottom-left-right .bottom-text").eq(0).text(`0  ${wordCountText}`);
783        if ($(window).width() < 769) {
784            $(".last-box").hide();
785        }
786        // Focus on input
787        $("#middleContent").focus();
788        removeSynonymsContainer();
789    });
790
791    function boldNewWords(p1, p2, breakPlaceholder = false) {
792    if (breakPlaceholder) {
793        p1 = p1.trim().replace(/(?:<br\s*\/?>|\n)/g, " linebreakisplacedhere ");
794        p2 = p2.trim().replace(/(?:<br\s*\/?>|\n)/g, " linebreakisplacedhere ");
795    }
796    const differences = Diff?.diffWords(p1, p2);
797    let formattedHTML = "";
798    differences.forEach((part) => {
799        if (part.added && part.value.endsWith("linebreakisplacedhere")) {
800            formattedHTML += `<b>${part.value.replaceAll(
801                "linebreakisplacedhere",
802                ""
803            )}</b>linebreakisplacedhere`;
804        } else if (
805            part.added &&
806            part.value.startsWith("linebreakisplacedhere")
807        ) {
808            formattedHTML += `linebreakisplacedhere<b>${part.value.replaceAll(
809                "linebreakisplacedhere",
810                ""
811            )}</b>`;
812        } else if (part.added && part.value.includes("linebreakisplacedhere")) {
813            formattedHTML += `<b>${part.value.replaceAll(
814                "linebreakisplacedhere",
815                "</b>linebreakisplacedhere<b>"
816            )}</b>`;
817        } else if (part.added) {
818            // Wrap each word in its own <b> so multiple added words
819            // become separate tags instead of one combined tag.
820            formattedHTML += part.value.replace(
821                /\S+/g,
822                (word) => `<b class="pr_o_word">${word}</b>`
823            );
824        } else if (!part.removed) {
825            formattedHTML += `${part.value}`;
826        }
827    });
828    // Turn the line-break placeholders back into real <br> tags
829    formattedHTML = formattedHTML.replace(
830        /\s*linebreakisplacedhere\s*/g,
831        "<br>",
832    );
833    return formattedHTML;
834}
835
836    // Remove or update the #trash_main_container handler to avoid duplication
837    $("#trash_main_container").off("click"); // Unbind any existing handler
838    const paraInput = document.getElementById("middleContent");
839
840    function checkPlaceholder() {
841        if (paraInput && !paraInput.textContent.trim()) {
842            paraInput.innerHTML = "";
843            paraInput.classList.add("empty");
844        } else if (paraInput) {
845            paraInput.classList.remove("empty");
846        }
847    }
848
849    if (paraInput) {
850        paraInput.addEventListener("input", checkPlaceholder);
851        paraInput.addEventListener("blur", checkPlaceholder);
852        checkPlaceholder();
853    } else {
854        console.warn("Element with ID 'middleContent' not found in the DOM.");
855    }
856    function cleanText(text) {
857        return text.replace(/\*/g, "");
858    }
859
860
861
862function submitCustomMode(rawVal) {
863        const val = String(rawVal ?? "").trim().slice(0, CUSTOM_MODE_MAX_LEN);
864        customModePopupContainer.addClass("d-none");
865         let fileText = getNormalizedInputText();
866        
867      
868       
869        if (val === "") {
870            alert_box(
871                BASE_URL + "web_assets/frontend/images/not_text.svg",
872                noCustomModeTextHeading,
873                noCustomModeTextContent,
874                "",
875                "Cancel",
876            );
877            customModeSpan.addClass("active");
878            $("#selected_mode").text($("#custom_mode").text().trim());
879            return;
880        }
881
882        customModeInput.val(val);
883
884        if (val &&  !recentModes.includes(val)) {
885            recentModes.push(val);
886            if (recentModes.length > 10) {
887                recentModes.shift();
888            }
889            localStorage.setItem("recent_modes", JSON.stringify(recentModes));
890        }
891
892        makeCustomModeLive();
893          if (val !== "" && textWordCounter(fileText, "wordCounter") < 10) {
894            $("#middleContent").focus();
895                return;
896        }
897        triggerRewriteRequest();
898    }
899
900   
901    customModeSubmitBtn.on("click", function (event) {
902        
903        if (customModeInput.val().length > CUSTOM_MODE_MAX_LEN) {
904            $(".error-message").show();
905            return; 
906        }
907        submitCustomMode(customModeInput.val());
908    });
909
910    
911
912    });

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.