brackets on both sides

add brackets at both sides of highlighted text when select some text and typing brackets. just like some texteditor

  1. // ==UserScript==
  2. // @name brackets on both sides
  3. // @namespace http://tampermonkey.net/
  4. // @version 2024-05-19
  5. // @description add brackets at both sides of highlighted text when select some text and typing brackets. just like some texteditor
  6. // @author linche0502
  7. // @match *://*/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Your code here...
  16. // 選取文字後, 輸入括號改為在選取範圍左右新增括號
  17. function autoBrackets(targets){
  18. // targets是query selector text的話就直接搜尋, 尋找元素
  19. if(typeof(targets) == "string"){
  20. targets= document.querySelectorAll(targets);
  21. // 如果targets是單一元素的話, 就加到一個新的array裡, 以便使用forEach(我就懶)
  22. }else if(Node.prototype.isPrototypeOf(targets)){
  23. targets=[targets];
  24. }
  25. targets.forEach(target => {
  26. target.addEventListener("keydown", (event) => {
  27. const BRACKETS= {
  28. "Digit9": {true:"()"},
  29. "BracketLeft": {true:"{}", false:"[]"},
  30. "Quote": {true:'""', false:"''"},
  31. "Comma": {true:"<>"}
  32. };
  33. // 確認新輸入的內容是括號
  34. // if(!Object.keys(BRACKETS).includes(event.data)) // input event無法取消預設行為
  35. if(!(BRACKETS[event.code] && BRACKETS[event.code][event.shiftKey])){
  36. return
  37. }
  38. // 判斷反白區域是在(input/textarea)或是(contentEditable="false")的元素
  39. let focusElement= document.activeElement;
  40. let offset;
  41. // 反白區域是在(input/textarea)時
  42. if(["INPUT","TEXTAREA"].includes(focusElement.tagName)){
  43. offset= [focusElement.selectionStart, focusElement.selectionEnd];
  44. // 先尋找是否有反白的區域
  45. if(offset[0] == offset[1]){
  46. return;
  47. }
  48. focusElement.value= focusElement.value.slice(0,offset[0])+
  49. BRACKETS[event.code][event.shiftKey][0]+
  50. focusElement.value.slice(offset[0],offset[1])+
  51. BRACKETS[event.code][event.shiftKey][1]+
  52. focusElement.value.slice(offset[1]);
  53. // 在更改文字內容後, 反白範圍會自動取消選取, 重新選取
  54. offset[0]++; offset[1]++;
  55. focusElement.setSelectionRange(offset[0], offset[1]);
  56. }
  57. // 反白區域是在(contentEditable="false")的元素時
  58. else{
  59. const selection = window.getSelection()
  60. let selectNodes= [selection.anchorNode, selection.focusNode];
  61. offset= [selection.anchorOffset, selection.focusOffset];
  62. // 先尋找是否有反白的區域
  63. if(selectNodes[0]===selectNodes[1] && offset[0]===offset[1]){
  64. return;
  65. }
  66. // 確認開始和結束的點沒有超出target的範圍
  67. if (!target.contains(selectNodes[0]) || !target.contains(selectNodes[1])) {
  68. return
  69. }
  70. // 確認anchorNode和focusNode在document中的順序, 以避免從後向前反白時會出錯
  71. if((selectNodes[0]===selectNodes[1] && offset[1]<offset[0]) || (selectNodes[0].compareDocumentPosition(selectNodes[1]) & Node.DOCUMENT_POSITION_PRECEDING)){
  72. selectNodes= selectNodes.reverse()
  73. offset= offset.reverse()
  74. }
  75. // 尋找兩者所在的共同父元素
  76. let checkNode= selectNodes[0];
  77. while(true){
  78. // 如果現在的checkNode不包含(或不等於)focusNode, 則再向上尋找, 最後checkNode即為anchorNode與focus的共同父元素
  79. if(!checkNode.contains(selectNodes[1])){
  80. checkNode= checkNode.parentNode;
  81. continue;
  82. }
  83. break;
  84. }
  85. // 如果共同父元素並不是一個可供編輯或輸入的元素, 或者不在一個可供編輯或輸入的元素之內, 則不進行動作
  86. while(true){
  87. if(checkNode.contentEditable == "true"){
  88. // 將focusElement改為共同父元素, 在之後要處理中文bug的時候會比較快, (即使target設定為整個html, 檢查內容是否有跑掉時, 也只要檢查共同父元素的textContent就好, 不需要檢查整個html)
  89. focusElement= checkNode;
  90. break
  91. }
  92. // 多加這一次判斷, 避免在contentEditable=="true"的元素裡面又有contentEditable=="false"的元素時會誤觸
  93. if(checkNode.contentEditable == "false"){
  94. return
  95. }
  96. // 向上尋找是否為可供編輯或輸入的元素時, 找到target為止, 不再向上尋找
  97. if(target.contains(checkNode) && !target.isEqualNode(checkNode)){
  98. checkNode= checkNode.parentNode;
  99. continue;
  100. }
  101. return;
  102. }
  103. // 在前後插入相對應的括號, 前括號和後括號分兩次個別加入, 以避免分別處在不同元素中時會發生錯誤
  104. selectNodes[0].textContent= selectNodes[0].textContent.slice(0,offset[0])+ BRACKETS[event.code][event.shiftKey][0]+ selectNodes[0].textContent.slice(offset[0])
  105. offset[0]+= 1;
  106. // 在前括號加上去後, 如果後括號的位置也在同一元素之中, 則也會向後偏移
  107. offset[1]+= (selectNodes[0].isEqualNode(selectNodes[1]))? 1: 0;
  108. selectNodes[1].textContent= selectNodes[1].textContent.slice(0,offset[1])+ BRACKETS[event.code][event.shiftKey][1]+ selectNodes[1].textContent.slice(offset[1])
  109. // 在更改文字內容後, 反白範圍會亂掉, 重新選取
  110. selection.collapse(selectNodes[0], offset[0]);
  111. selection.extend(selectNodes[1], offset[1]);
  112. }
  113. event.preventDefault();
  114.  
  115. // 中文輸入法時會出錯, ex: a|bc|d +[(] -> a(|bc|)d -> a(()d, 反白的區域也會變成前括號
  116. if(event.key == "Process"){
  117. if(["INPUT","TEXTAREA"].includes(focusElement.tagName)){
  118. let newContent= focusElement.value;
  119. setTimeout(() => {
  120. if(focusElement.value != newContent){
  121. document.execCommand('undo');
  122. focusElement.setSelectionRange(offset[0], offset[1]);
  123. }
  124. }, 10)
  125. }else{
  126. const selection = window.getSelection()
  127. let selectNodes = [selection.anchorNode, selection.focusNode];
  128. // 這邊的focusElement是反白內容前後錨點的共同父元素, 而不是單純的focusNode了
  129. let newContent= focusElement.textContent;
  130. setTimeout(() => {
  131. if(focusElement.textContent != newContent){
  132. document.execCommand('undo');
  133. selection.collapse(selectNodes[0], offset[0]);
  134. selection.extend(selectNodes[1], offset[1]);
  135. }
  136. }, 10)
  137. }
  138. }
  139.  
  140. })
  141. })
  142. }
  143. autoBrackets("html");
  144. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址