[UserScript] Advanced Context Sentence

Sounds good to me!

I don’t think it is, but I would have to take a closer look to be sure, haha. I’ll have a look at both things tomorrwo

1 Like

It was not! Thanks for noticing. There was a silent error for items not in the data set and it never got to the return statement for those items. Just had to insert a conditional.

1 Like

Thanks @Kumirei for the silent fix.
It works fine here now.

3 Likes

Any idea why this becomes broken when using Stroke Order Diagram?

Is anyone else seeing a resource leak when using this script in lessons?

  1. Set lesson batch size to 6.
  2. Do two batches of 6 vocab lessons each directly back to back without going to the review summary page in between.
  3. About halfway through the second batch, memory usage starts to climb by an additional 25-100mb and the webpage becomes much less responsive

This happens reliably for me even if this is the only script enabled, and does not happen when I disable this script, no matter what other scripts I have running.

other possibly relevant details: I use the keyboard for navigation in lessons. This issue only happens with vocab lessons, not kanji / radicals.

1 Like

I found the issue and have put a patch below. @abdullahalt could you incorporate the fix?

The main cause seems to be that after finishing the lesson quiz, there will always be context sentences from the quiz info box still present but hidden. These sentences are repeatedly parsed and rewritten by Advanced Context Sentence. Also, there was an issue with tippy instances not being destroyed in certain scenarios and parseHTML being used which seemed to contribute to the problem. The patch below fixes these issues and an issue with JLPT filters not being detected due to a change in the JLPT filters script.

@@ -3,15 +3,15 @@
 // ==UserScript==
 // @name         Advanced Context Sentence
 // @namespace    https://openuserjs.org/users/abdullahalt
-// @version      1.40
+// @version      1.41
 // @description  Enhance the context sentence section, highlighting kanji and adding audio
 // @author       abdullahalt
 // @match        https://www.wanikani.com/lesson/session
 // @match        https://www.wanikani.com/review/session
 // @match        https://www.wanikani.com/vocabulary/*
+// @require      https://unpkg.com/@popperjs/core@2.5.4/dist/umd/popper.min.js
+// @require      https://unpkg.com/tippy.js@6.2.7/dist/tippy-bundle.umd.min.js
 // @grant        none
-// @require      https://unpkg.com/popper.js@1/dist/umd/popper.min.js
-// @require      https://unpkg.com/tippy.js@4
 // @copyright    2019, abdullahalt (https://openuserjs.org//users/abdullahalt)
 // @license MIT
 // ==/UserScript==
@@ -162,21 +162,23 @@

     if (wkof) evolveHeader(getHeader(sentences));

-    sentences.forEach(sentence => {
+    sentences.forEach(function(sentence) {
       const japaneseSentence = sentence.querySelector('p[lang="ja"]');
-      const audioButton = createAudioButton(japaneseSentence.innerHTML);
+      // without below, it might try to evolve hidden context sentences from quiz during a second lesson batch causing
+      // resource leak
+      if (japaneseSentence.childNodes.length != 1 || japaneseSentence.childNodes[0].nodeType != Node.TEXT_NODE) {
+          return;
+      }
+      let sentenceText = japaneseSentence.childNodes[0].nodeValue;
+      const audioButton = createAudioButton(sentenceText);
       //let advancedExampleSentence = "";
-      const chars = japaneseSentence.innerHTML.split("");
-      japaneseSentence.innerHTML = "";
-      chars.forEach(char => {
-        japaneseSentence.innerHTML =
-          japaneseSentence.innerHTML + tagAndLinkKanji(char).trim();
-      });
-
-      highlightKanji();
-
+      const chars = sentenceText.split("");
+      let newNodes = chars.map(char => tagAndLinkKanji(char));
+      japaneseSentence.replaceChildren(...newNodes);
       japaneseSentence.append(audioButton);
     });
+
+    highlightKanji();
   }

   function evolveHeader(header) {
@@ -383,7 +385,7 @@
   }

   function tagAndLinkKanji(char) {
-    return isKanji(char) ? wrapInAnchor(char).outerHTML : char;
+    return isKanji(char) ? wrapInAnchor(char) : document.createTextNode(char);
   }

   /**
@@ -528,7 +530,7 @@
       item_type: ["kan"]
     };

-    if (wkof.get_state("wkof.Kumirei.JJFFilters") === "ready") {
+    if (wkof.get_state("JJFFilters") === "ready") {
       state.jiff = true;
       filters.include_frequency_data = true;
       filters.include_jlpt_data = true;
@@ -590,6 +592,7 @@
     return source;
   }

+  let tippys = new Set();
   function highlightKanji() {
     const rules = document.querySelector("#acs-style").sheet.cssRules;
     rules[0].style.color = state.settings.recognizedKanjiColor;
@@ -597,6 +600,9 @@

     if (!wkof) return;

+    tippys.forEach(t => t.destroy());
+    tippys = new Set();
+
     const anchors = document.querySelectorAll(".context-sentence-group a");
     anchors.forEach(anchor => {
       const srs = anchor.getAttribute("data-srs");
@@ -604,22 +610,21 @@

       if (srs >= state.settings.recognitionLevel)
         anchor.setAttribute("class", "recognized");
-      else {
+      else
         anchor.setAttribute("class", "unrecognized");
-      }

-      if (anchor._tippy) anchor._tippy.destroy();
       if (state.settings.tooltip.show) {
         const kanji = state.kanjis.find(item => item.char == char);
         const tooltip = createTooltip(kanji);

         tippy(anchor, {
-          content: tooltip.outerHTML,
+          content: tooltip,
           size: "small",
           arrow: true,
           placement: state.settings.tooltip.position,
           delay: [state.settings.tooltip.delay, 20]
         });
+        tippys.add(anchor._tippy);
       }
     });
   }
1 Like

I don’t know if anyone is having the same issue but about 2 days ago the script doesn’t seem to work when I’m doing lessons and on the context tab.

It does work when I’m doing reviews and checking the sentences there. Is it because the sentences are displayed on the same screen unlike the lessons which are now in 4 different tabs?

1 Like

Yeah, I’m having the same issue. It’s not just you. :slight_smile:

1 Like

Yes, I’ve been experiencing this issue as well. Can anyone help?

Same here!

I was thinking about how terrible the context sentences overflowing with hiragana are. Glad to have found this script.

Same with me :frowning_face:

I saw someone also commented the issue on the GreasyFork page.

Hopefully the author @abdullahalt sees it. I do find this script so useful when learning vocab. I think the problem must be due to the context sentences moving to their own page in Lessons.

Thank you for the scripts. It has been an integral part of my learning.
I also faced a similar issue as previous posters, in the lesson section, the script stop working.

I don’t how to create a pull request at Greasyfork, so I’ll put my workaround here instead while waiting for the author to patch it. In this patch, you will update the code manually. If it breaks, you can uninstall and then reinstall it.


Step 1: Go to Tampermonkey extension > open Dashboard
Step 2: Find this Advance Context Script and click edit


Step 3: Find this section, I’m using Advanced Context Sentence version 1.4.0

    {
      page: "/lesson/session",
      mount: "#supplement-voc-context-sentence",
      loading: "#loading-screen",
      getHeader: sentences => {
        return sentences[0].parentElement.previousElementSibling;
      }
    }

Replace it with

    {
      page: "/lesson/session",
      mount: "#supplement-voc-context-sentence",
      loading: "#loading-screen",
      getHeader: sentences => {
        return sentences[0].previousElementSibling;
      }
    }

Hope it can make the script usable on lesson section until the proper fix integrated to the original script.

12 Likes

:raised_hands: It worked for me! Excellent, thank you so much.

I think if you post a new version to GreasyFork it’s automatically recognized as a fork

Thank you, it’s working again!

I wouldn’t be expecting much from the original author, he hasn’t posted since September 2019. @rklie’s patch helps. Is there any way to update the script without the author’s approval?

Anyone else getting a problem on this now where the audio won’t play? Or just me? :confused:

The loudspeaker symbol is there but when I click it no sound comes out. The normal WK word vocab pronunciation is still working fine. And I also tried pasting the direct link to the Google TTS that’s in this script into my browser address bar and it plays there as well.

@rklie ?

No replies to this ^ :no_mouth: Can anyone who uses this just confirm if the audio is still working for them so I can tell if the issue is widespread or just affecting me? I’m running WaniKani in Firefox - haven’t tried in another browser.

@tatihirata @rklie @rever4217 ?

I know the text-to-speech isn’t perfect and misreads a few things but it’s a good guideline to get started with, particularly in the early stages of learning Japanese. So I’m missing it!