Split Long Paragraphs

Splits long paragraphs at the period nearest to the split point.

  1. // ==UserScript==
  2. // @name Split Long Paragraphs
  3. // @namespace http://tampermonkey.net/
  4. // @version 3
  5. // @description Splits long paragraphs at the period nearest to the split point.
  6. // @match *://ranobes.top/*
  7. // @match *://ranobes.net/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=ranobes.top
  9. // @license MIT
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. function ellipsize(s) {
  17. return s.substring(0, 64).trim().replace(/[^\w\s\d]+$/, "") + "...";
  18. }
  19.  
  20. function log(text) {
  21. console.log(`Split Long Paragraphs: ${text}`);
  22. }
  23.  
  24. const MAX_WORD_COUNT = 80;
  25. const section = document.querySelector(".story #arrticle");
  26.  
  27. if (!section) {
  28. return;
  29. }
  30.  
  31. const nodes = Array.from(section.querySelectorAll('p'));
  32.  
  33. section.childNodes.forEach(child => {
  34. if (child.nodeType === Node.TEXT_NODE) {
  35. nodes.push(child);
  36. }
  37. })
  38.  
  39. for (let i = 0; i < nodes.length; i++) {
  40. const node = nodes[i];
  41. const text = node.textContent.trim();
  42. const words = text.split(/\s+/);
  43.  
  44. // Max word count before splitting
  45. if (words.length > MAX_WORD_COUNT + Math.floor(MAX_WORD_COUNT / 2)) {
  46. // Find closest split point to MAX_WORD_COUNT at a period
  47. const sentences = text.split(/(?<=[^\.]\.)\s+/);
  48. let sentenceIndex = 0;
  49. let wordCount = 0;
  50.  
  51. for (const sentence of sentences) {
  52. wordCount += sentence.split(/\s+/).length;
  53. // log(`${ellipsize(sentence)} totalWordCount:${wordCount}`);
  54.  
  55. if (wordCount >= MAX_WORD_COUNT) {
  56. break;
  57. }
  58.  
  59. sentenceIndex += 1;
  60. }
  61.  
  62. if (wordCount !== 0) {
  63. log(`Splitting... \`${ellipsize(text)}\` wordCount:${words.length} sentenceIndex:${sentenceIndex} totalSentences:${sentences.length}`);
  64.  
  65. node.textContent = '';
  66.  
  67. let p = document.createElement('p');
  68. p.textContent = sentences.slice(0, sentenceIndex + 1).join(" ").trim();
  69. node.parentNode.insertBefore(p, node);
  70.  
  71. p = document.createElement('p');
  72. p.textContent = sentences.slice(sentenceIndex + 1).join(" ").trim();
  73. node.parentNode.insertBefore(p, node);
  74.  
  75. nodes.push(p);
  76. node.remove();
  77. }
  78. }
  79. }
  80. })();