Dynamic RTL/LTR Direction

Dynamically set text direction for Deepseek chat elements based on content

  1. // ==UserScript==
  2. // @name Dynamic RTL/LTR Direction
  3. // @namespace http://tampermonkey.net/
  4. // @version V4
  5. // @description Dynamically set text direction for Deepseek chat elements based on content
  6. // @author Reda Elsayed
  7. // @match https://chat.deepseek.com/
  8. // @match https://chat.deepseek.com/*
  9. // @match https://chat.deepseek.com/*/chat/*/*
  10. // @icon https://www.deepseek.com/path/to/icon.png
  11. // @grant none
  12. // ==/UserScript==
  13.  
  14. (function () {
  15. "use strict";
  16.  
  17. const textareaClass = "c92459f0";
  18. const targetClass = "ds-markdown ds-markdown--block";
  19. const codeClass = "md-code-block";
  20.  
  21. function isRTL(text) {
  22. const rtlPattern = /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/;
  23. return rtlPattern.test(text);
  24. }
  25.  
  26. function updateDirection() {
  27. const targetElements = document.getElementsByClassName(targetClass);
  28. const codeElements = document.getElementsByClassName(codeClass);
  29.  
  30. Array.from(targetElements).forEach((element) => {
  31. const textContent = element.textContent.trim();
  32. const newDirection = isRTL(textContent) ? "rtl" : "ltr";
  33.  
  34. if (textContent.length > 0 && element.style.direction !== newDirection) {
  35. element.style.direction = newDirection;
  36. element.style.textAlign = newDirection === "rtl" ? "right" : "left";
  37. }
  38. });
  39.  
  40. Array.from(codeElements).forEach((element) => {
  41. element.style.direction = "ltr";
  42. element.style.textAlign = "left";
  43. });
  44. }
  45.  
  46. function observeChanges() {
  47. const observer = new MutationObserver(() => {
  48. updateDirection();
  49. });
  50.  
  51. observer.observe(document.body, { childList: true, subtree: true });
  52. }
  53.  
  54. function observeTextArea() {
  55. const textAreaElements = document.getElementsByClassName(textareaClass);
  56. Array.from(textAreaElements).forEach((textArea) => {
  57. textArea.addEventListener("input", () => {
  58. const text = textArea.value.trim();
  59. const direction = isRTL(text) ? "rtl" : "ltr";
  60. textArea.style.direction = direction;
  61. textArea.style.textAlign = direction === "rtl" ? "right" : "left";
  62. });
  63. });
  64. }
  65.  
  66. function applyToExistingMessages() {
  67. // Ensure all existing messages have the correct direction on load
  68. updateDirection();
  69. }
  70.  
  71. // Initialize the script
  72. applyToExistingMessages();
  73. observeChanges();
  74. observeTextArea();
  75. })();