Browse Source

JavaScript Highlighter: Throttle rehighlighting to improve performance

while typing
master
Shadowfacts 2 months ago
parent
commit
4c65ff612d
Signed by: Shadowfacts <me@shadowfacts.net> GPG Key ID: 94A5AB95422746E5
1 changed files with 13 additions and 2 deletions
  1. 13
    2
      MongoView/Views/JavaScriptEditorView.swift

+ 13
- 2
MongoView/Views/JavaScriptEditorView.swift View File

@@ -7,12 +7,13 @@
7 7
 //
8 8
 
9 9
 import AppKit
10
+import Combine
10 11
 
11 12
 class JavaScriptEditorView: NSTextView {
12 13
     
13 14
     var highlighter = JavaScriptHighlighter()
14 15
     private var isRehighlighting = false
15
-    
16
+
16 17
     override var string: String {
17 18
         get {
18 19
             super.string
@@ -23,6 +24,9 @@ class JavaScriptEditorView: NSTextView {
23 24
             rehighlight()
24 25
         }
25 26
     }
27
+    
28
+    private let rehighlightSubject = PassthroughSubject<Void, Never>()
29
+    private var debouncedRehighlightCancellable: AnyCancellable!
26 30
 
27 31
     func rehighlight() {
28 32
         isRehighlighting = true
@@ -34,6 +38,13 @@ class JavaScriptEditorView: NSTextView {
34 38
         super.awakeFromNib()
35 39
         
36 40
         textStorage!.delegate = self
41
+        
42
+        typingAttributes = [
43
+            .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular),
44
+            .foregroundColor: NSColor.textColor
45
+        ]
46
+        
47
+        debouncedRehighlightCancellable = rehighlightSubject.throttle(for: .milliseconds(40), scheduler: RunLoop.main, latest: false).sink(receiveValue: rehighlight)
37 48
     }
38 49
     
39 50
     override func shouldChangeText(in affectedCharRange: NSRange, replacementString: String?) -> Bool {
@@ -117,6 +128,6 @@ extension JavaScriptEditorView: NSTextStorageDelegate {
117 128
             }
118 129
         }
119 130
         
120
-        rehighlight()
131
+        rehighlightSubject.send()
121 132
     }
122 133
 }

Loading…
Cancel
Save