aboutsummaryrefslogtreecommitdiffstats
path: root/content_scripts/mode_visual_edit.coffee
blob: e98fe5f216d9dc6b568a9b309fd8735f136f8716 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# Todo:
# Konami code?
# Use find as a mode.
# Refactor visual/movement modes.

# This prevents printable characters from being passed through to the underlying page.  It should, however,
# allow through chrome keyboard shortcuts.  It's a keyboard-event backstop for visual mode and edit mode.
class SuppressPrintable extends Mode
  constructor: (options = {}) ->
    handler = (event) =>
      if KeyboardUtils.isPrintable event
        if event.type == "keydown"
          # Completely suppress Backspace and Delete.
          if event.keyCode in [ 8, 46 ]
            @suppressEvent
          else
            DomUtils.suppressPropagation
            @stopBubblingAndFalse
        else
          @suppressEvent
      else
        @stopBubblingAndTrue

    super extend options,
      keydown: handler
      keypress: handler
      keyup: handler

# This watches keyboard events and maintains @countPrefix as number keys and other keys are pressed.
class MaintainCount extends SuppressPrintable
  constructor: (options) ->
    super options

    @countPrefix = ""
    @countPrefixFactor = 1
    @countPrefixFactor = @getCountPrefix options.initialCountPrefix if options.initialCountPrefix

    @push
      _name: "#{@id}/maintain-count"
      keypress: (event) =>
        @alwaysContinueBubbling =>
          unless event.metaKey or event.ctrlKey or event.altKey
            keyChar = String.fromCharCode event.charCode
            @countPrefix =
              if keyChar?.length == 1 and "0" <= keyChar <= "9" and @countPrefix + keyChar != "0"
                @countPrefix + keyChar
              else
                ""

  # This handles both "d3w" and "3dw". Also, "3d2w" deletes six words.
  getCountPrefix: (prefix = @countPrefix) ->
    prefix = prefix.toString() if typeof prefix == "number"
    count = @countPrefixFactor * if 0 < prefix?.length then parseInt prefix else 1
    @countPrefix = ""
    @countPrefixFactor = 1
    count

# Some symbolic names for widely-used strings.
forward = "forward"
backward = "backward"
character = "character"

# This implements movement commands with count prefixes (using MaintainCount) for both visual mode and edit
# mode.
class Movement extends MaintainCount
  opposite: forward: backward, backward: forward

  copy: (text) ->
    chrome.runtime.sendMessage handler: "copyToClipboard", data: text if text

  paste: (callback) ->
    chrome.runtime.sendMessage handler: "pasteFromClipboard", (response) -> callback response

  # Return a value which changes whenever the selection changes, regardless of whether the selection is
  # collapsed.
  hashSelection: ->
    [ @element?.selectionStart, @selection.toString().length ].join "/"

  # Call a function; return true if the selection changed.
  selectionChanged: (func) ->
    before = @hashSelection(); func(); @hashSelection() != before

  # Run a movement.  The arguments can be one of the following forms:
  #   - "forward word" (one argument, a string)
  #   - [ "forward", "word" ] (one argument, not a string)
  #   - "forward", "word" (two arguments)
  runMovement: (args...) ->
    movement =
      if typeof(args[0]) == "string" and args.length == 1
        args[0].trim().split /\s+/
      else
        if args.length == 1 then args[0] else args[...2]
    @selection.modify @alterMethod, movement...

  # Run a sequence of movements, stopping if a movement fails to change the selection.
  runMovements: (movements...) ->
    for movement in movements
      return false unless @selectionChanged => @runMovement movement
    true

  # Swap the anchor node/offset and the focus node/offset.
  reverseSelection: ->
    element = document.activeElement
    if element and DomUtils.isEditable(element) and not element.isContentEditable
      # Note(smblott). This implementation is unacceptably inefficient if the selection is large.  We only use
      # it if we have to.  However, the normal method (below) does not work for input elements.
      direction = @getDirection()
      length = @selection.toString().length
      @collapseSelectionToFocus()
      @runMovement @opposite[direction], character for [0...length]
    else
      # Normal method.
      direction = @getDirection()
      original = @selection.getRangeAt(0).cloneRange()
      range = original.cloneRange()
      range.collapse direction == backward
      @selection.removeAllRanges()
      @selection.addRange range
      which = if direction == forward then "start" else "end"
      @selection.extend original["#{which}Container"], original["#{which}Offset"]

  # Try to extend the selection one character in "direction".  Return 1, -1 or 0, indicating whether the
  # selection got bigger, or smaller, or is unchanged.
  extendByOneCharacter: (direction) ->
    length = @selection.toString().length
    @selection.modify "extend", direction, character
    @selection.toString().length - length

  # Get the direction of the selection.  The selection is "forward" if the focus is at or after the anchor,
  # and "backward" otherwise.
  # NOTE(smblott). Could be better, see: https://dom.spec.whatwg.org/#interface-range.
  getDirection: ->
    # Try to move the selection forward or backward, check whether it got bigger or smaller (then restore it).
    for direction in [ forward, backward ]
      if change = @extendByOneCharacter direction
        @extendByOneCharacter @opposite[direction]
        return if 0 < change then direction else @opposite[direction]
    forward

  # An approximation of the vim "w" movement; only ever used in the forward direction.  The last two character
  # movements allow us to also get to the end of the very-last word.
  moveForwardWord: () ->
    # First, move to the end of the preceding word...
    if @runMovements "forward character", "backward word", "forward word"
      # And then to the start of the following word...
      @runMovements "forward word", "forward character", "backward character", "backward word"

  collapseSelectionToAnchor: ->
    if 0 < @selection.toString().length
      @selection[if @getDirection() == backward then "collapseToEnd" else "collapseToStart"]()

  collapseSelectionToFocus: ->
    if 0 < @selection.toString().length
      @selection[if @getDirection() == forward then "collapseToEnd" else "collapseToStart"]()

  movements:
    "l": "forward character"
    "h": "backward character"
    "j": "forward line"
    "k": "backward line"
    "e": "forward word"
    "b": "backward word"
    ")": "forward sentence"
    "(": "backward sentence"
    "}": "forward paragraph"
    "{": "backward paragraph"
    "$": "forward lineboundary"
    "0": "backward lineboundary"
    "G": "forward documentboundary"
    "g": "backward documentboundary"
    "w": -> @moveForwardWord()
    "Y": -> @selectLexicalEntity "lineboundary"
    "o": -> @reverseSelection()

  constructor: (options) ->
    @selection = window.getSelection()
    @movements = extend {}, @movements
    @commands = {}
    @keyQueue = ""
    @keypressCount = 0
    @yankedText = ""
    super options

    # Aliases.
    @movements.B = @movements.b
    @movements.W = @movements.w

    if @options.singleMovementOnly
      # This instance has been created just to run a single movement only and then yank the result.
      @handleMovementKeyChar @options.singleMovementOnly
      @yank()
      return

    @push
      _name: "#{@id}/keypress"
      keypress: (event) =>
        @keypressCount += 1
        unless event.metaKey or event.ctrlKey or event.altKey
          @keyQueue += String.fromCharCode event.charCode
          # We allow at most three characters for a command or movement mapping.
          @keyQueue = @keyQueue.slice Math.max 0, @keyQueue.length - 3
          # Try each possible multi-character keyChar sequence, from longest to shortest (e.g. with "abc", we
          # try "abc", "bc" and "c").
          for command in (@keyQueue[i..] for i in [0...@keyQueue.length])
            if @movements[command] or @commands[command]
              @selection = window.getSelection()
              @keyQueue = ""

              if @commands[command]
                @commands[command].call @
                @scrollIntoView()
                return @suppressEvent

              else if @movements[command]
                @handleMovementKeyChar command
                break unless @options.oneMovementOnly
                @yank()
                return @suppressEvent

        @continueBubbling

  handleMovementKeyChar: (keyChar) ->
    count = @getCountPrefix()
    if @movements[keyChar]
      @protectClipboard =>
        for [0...count]
          switch typeof @movements[keyChar]
            when "string" then @runMovement @movements[keyChar]
            when "function" then @movements[keyChar].call @
        @scrollIntoView()

  # Yank the selection; always exits; returns the yanked text.
  yank: (args = {}) ->
    @yankedText = @selection.toString()
    @selection.deleteFromDocument() if args.deleteFromDocument or @options.deleteFromDocument
    console.log "yank:", @yankedText if @debug

    message = @yankedText.replace /\s+/g, " "
    length = @yankedText.length
    message = message[...12] + "..." if 15 < length
    plural = if length == 1 then "" else "s"
    HUD.showForDuration "Yanked #{length} character#{plural}: \"#{message}\".", 2500

    @options.onYank.call @, @yankedText if @options.onYank
    @exit()
    @yankedText

  # Select a lexical entity, such as a word, a line, or a sentence. The entity should be a Chrome movement
  # type, such as "word" or "lineboundary".  This assumes that the selection is initially collapsed.
  selectLexicalEntity: (entity) ->
    @runMovement forward, entity
    @selection.collapseToEnd()
    @runMovement backward, entity
    # Move the end of the preceding entity.
    @runMovements [ backward, entity ], [ forward, entity ]

  # Try to scroll the focus into view.
  scrollIntoView: ->
    @protectClipboard =>
      if @element and DomUtils.isEditable @element
        if @element.clientHeight < @element.scrollHeight
          if @element.isContentEditable
            # How do we do this?  This case matters for gmail and Google's inbox.
          else
            position = if @getDirection() == backward then @element.selectionStart else @element.selectionEnd
            coords = DomUtils.getCaretCoordinates @element, position
            Scroller.scrollToPosition @element, coords.top, coords.left
      else
        elementWithFocus = @getElementWithFocus @selection
        Scroller.scrollIntoView elementWithFocus if elementWithFocus

  # Adapted from: http://roysharon.com/blog/37.
  # I have no idea how this works (smblott, 2015/1/22).
  # The intention is to find the element containing the focus.  That's the element we need to scroll into
  # view.
  getElementWithFocus: (selection) ->
    r = t = selection.getRangeAt 0
    if selection.type == "Range"
      r = t.cloneRange()
      r.collapse @getDirection() == backward
    t = r.startContainer
    t = t.childNodes[r.startOffset] if t.nodeType == 1
    o = t
    o = o.previousSibling while o and o.nodeType != 1
    t = o || t?.parentNode
    t

class VisualMode extends Movement
  constructor: (options = {}) ->
    @selection = window.getSelection()
    @alterMethod = "extend"

    switch @selection.type
      when "None"
        unless @establishInitialSelection()
          HUD.showForDuration "Create a selection before entering visual mode.", 2500
          return
      when "Caret"
        # Try to start with a visible selection.
        @extendByOneCharacter(forward) or @extendByOneCharacter backward unless options.editModeParent
        @scrollIntoView() if @selection.type == "Range"

    defaults =
      name: "visual"
      badge: "V"
      singleton: VisualMode
      exitOnEscape: true
    super extend defaults, options

    unless @options.oneMovementOnly
      extend @commands,
        "V": -> new VisualLineMode
        "y": -> @yank()

    # "P" and "p" to copy-and-go (but not under edit mode).
    unless @options.editModeParent
      do =>
        yankAndOpenAsUrl = (handler) =>
          chrome.runtime.sendMessage handler: handler, url: @yank()

        extend @commands,
          "p": -> yankAndOpenAsUrl "openUrlInCurrentTab"
          "P": -> yankAndOpenAsUrl "openUrlInNewTab"

    # Additional commands when run under edit mode.
    if @options.editModeParent and not @options.oneMovementOnly
      extend @commands,
        "c": -> @yank deleteFromDocument: true; @options.editModeParent.enterInsertMode()
        "x": -> @yank deleteFromDocument: true
        "d": -> @yank deleteFromDocument: true

    # For "yy".
    if @options.yYanksLine
      @commands.y = ->
        if @keypressCount == 1
          @selectLexicalEntity "lineboundary"
          @yank()

    # For "dd".
    if @options.dYanksLine
      @commands.d = ->
        if @keypressCount == 1
          @selectLexicalEntity "lineboundary"
          @yank deleteFromDocument: true

    # For "daw", "das", "dap", "caw", "cas", "cap".
    if @options.oneMovementOnly
      @commands.a = ->
        if @keypressCount == 1
          for entity in [ "word", "sentence", "paragraph" ]
            do (entity) => @movements[entity.charAt 0] = -> @selectLexicalEntity entity

    unless @options.editModeParent
      @installFindMode()

    # Grab the initial clipboard contents.  We'll try to keep them intact until we get an explicit yank.
    @clipboardContents = ""
    @paste (text) =>
      @clipboardContents = text if text
    #
    # End of VisualMode constructor.

  protectClipboard: (func) ->
    func()
    @copy @clipboardContents if @clipboardContents

  copy: (text) ->
    super @clipboardContents = text

  exit: (event, target) ->
    @collapseSelectionToAnchor() if @yankedText or @options.editModeParent

    unless @options.editModeParent
      # Don't leave the user in insert mode just because they happen to have selected text within an input
      # element.
      if document.activeElement and DomUtils.isEditable document.activeElement
        document.activeElement.blur()

    super event, target
    # Copying the yanked text to the clipboard must be the very last thing we do, because other operations
    # (like collapsing the selection) interfere with the clipboard.
    @copy @yankedText if @yankedText


  installFindMode: ->
    previousFindRange = null

    executeFind = (findBackwards) =>
      query = getFindModeQuery()
      if query
        caseSensitive = Utils.hasUpperCase query
        @protectClipboard =>
          initialRange = @selection.getRangeAt(0).cloneRange()
          direction = @getDirection()

          # Start by re-selecting the previous match, if any.  This tells Chrome where to start from.
          if previousFindRange
            @selection.removeAllRanges()
            @selection.addRange previousFindRange

          window.find query, caseSensitive, findBackwards, true, false, true, false
          previousFindRange = newFindRange = @selection.getRangeAt(0).cloneRange()
          # FIXME(smblott).  What if there were no matches?

          # Now, install a range from the original selection to the new match.
          range = document.createRange()
          which = if direction == forward then "start" else "end"
          range.setStart initialRange["#{which}Container"], initialRange["#{which}Offset"]
          range.setEnd newFindRange.endContainer, newFindRange.endOffset
          @selection.removeAllRanges()
          @selection.addRange range

          # If we're going backwards (or if the election ended up empty), then extend the selection again,
          # this time to include the match itself.
          if @getDirection() == backward or @selection.toString().length == 0
            range.setStart newFindRange.startContainer, newFindRange.startOffset
            @selection.removeAllRanges()
            @selection.addRange range

    extend @movements,
      "n": -> executeFind false
      "N": -> executeFind true

  establishInitialSelection: ->
    nodes = document.createTreeWalker document.body, NodeFilter.SHOW_TEXT
    while node = nodes.nextNode()
      # Try not to pick really small nodes.  They're likely to be part of a banner.
      if node.nodeType == 3 and 50 <= node.data.trim().length
        element = node.parentElement
        if DomUtils.getVisibleClientRect(element) and not DomUtils.isEditable element
          range = document.createRange()
          text = node.data
          trimmed = text.replace /^\s+/, ""
          offset = text.length - trimmed.length
          range.setStart node, offset
          range.setEnd node, offset + 1
          @selection.removeAllRanges()
          @selection.addRange range
          @scrollIntoView()
          return true
    false

class VisualLineMode extends VisualMode
  constructor: (options = {}) ->
    options.name ||= "visual/line"
    super options
    unless @selection?.type == "None"
      initialDirection = @getDirection()
      for direction in [ initialDirection, @opposite[initialDirection] ]
        @runMovement direction, "lineboundary"
        @reverseSelection()

  handleMovementKeyChar: (keyChar) ->
    super keyChar
    @runMovement @getDirection(), "lineboundary"

class EditMode extends Movement
  constructor: (options = {}) ->
    @element = document.activeElement
    @alterMethod = "move"
    return unless @element and DomUtils.isEditable @element

    defaults =
      name: "edit"
      badge: "E"
      exitOnEscape: true
      exitOnBlur: @element
    super extend defaults, options

    extend @commands,
      "i": -> @enterInsertMode()
      "a": -> @enterInsertMode()
      "A": -> @runMovement "forward lineboundary"; @enterInsertMode()
      "o": -> @openLine forward
      "O": -> @openLine backward
      "p": -> @pasteClipboard forward
      "P": -> @pasteClipboard backward
      "v": -> @launchSubMode VisualMode

      "Y": -> @enterVisualModeForMovement singleMovementOnly: "Y"
      "x": -> @enterVisualModeForMovement singleMovementOnly: "h", deleteFromDocument: true
      "y": -> @enterVisualModeForMovement yYanksLine: true
      "d": -> @enterVisualModeForMovement deleteFromDocument: true, dYanksLine: true
      "c": -> @enterVisualModeForMovement deleteFromDocument: true, onYank: => @enterInsertMode()

      "D": -> @enterVisualModeForMovement singleMovementOnly: "$", deleteFromDocument: true
      "C": -> @enterVisualModeForMovement singleMovementOnly: "$", deleteFromDocument: true, onYank: => @enterInsertMode()

      # Disabled as potentially confusing.
      # # If the input is empty, then enter insert mode immediately
      # unless @element.isContentEditable
      #   if @element.value.trim() == ""
      #     @enterInsertMode()
      #     HUD.showForDuration "Input empty, entered insert mode directly.", 3500

  enterVisualModeForMovement: (options = {}) ->
    @launchSubMode VisualMode, extend options,
      badge: "M"
      initialCountPrefix: @getCountPrefix()
      oneMovementOnly: true

  enterInsertMode: () ->
    @launchSubMode InsertMode,
      exitOnEscape: true
      targetElement: @options.targetElement

  launchSubMode: (mode, options = {}) ->
    @lastSubMode =
      mode: mode
      instance: Mode.cloneMode mode, extend options, editModeParent: @

  pasteClipboard: (direction) ->
    @paste (text) =>
      DomUtils.simulateTextEntry @element, text if text

  openLine: (direction) ->
    @runMovement direction, "lineboundary"
    @enterInsertMode()
    DomUtils.simulateTextEntry @element, "\n"
    @runMovement "backward character" if direction == backward

  # Backup the clipboard, then call a function (which may affect the selection text, and hence the
  # clipboard too), then restore the clipboard.
  protectClipboard: do ->
    locked = false
    clipboard = ""

    (func) ->
      if locked
        func()
      else
        locked = true
        @paste (text) =>
          clipboard = text
          func()
          @copy clipboard
          locked = false

  exit: (event, target) ->
    super event, target

    lastSubMode =
      if @lastSubMode?.instance.modeIsActive
        @lastSubMode.instance.exit event, target
        @lastSubMode

    if event?.type == "keydown" and KeyboardUtils.isEscape event
      if target? and DomUtils.isDOMDescendant @element, target
        @element.blur()

    if event?.type == "blur"
      new SuspendedEditMode @options, lastSubMode

# In edit mode, the input blurs if the user changes tabs or clicks outside of the element.  In the former
# case, the user expects to remain in edit mode when they return.  In the latter case, they may just be
# copying some text with the mouse/Ctrl-C, and again they expect to remain in edit mode.  SuspendedEditMode
# monitors various events and tries to either exit completely or re-enter edit mode, as appropriate.
class SuspendedEditMode extends Mode
  constructor: (editModeOptions, lastSubMode = null) ->
    super
      name: "suspended-edit"
      singleton: editModeOptions.singleton

    @push
      _name: "#{@id}/monitor"
      focus: (event) =>
        @alwaysContinueBubbling =>
          if event?.target == editModeOptions.targetElement
            console.log "#{@id}: reactivating edit mode" if @debug
            editMode = Mode.cloneMode EditMode, editModeOptions
            if lastSubMode
              editMode.launchSubMode lastSubMode.mode, lastSubMode.instance.options
      keypress: (event) =>
        @alwaysContinueBubbling =>
          @exit() unless event.metaKey or event.ctrlKey or event.altKey

root = exports ? window
root.VisualMode = VisualMode
root.VisualLineMode = VisualLineMode
root.EditMode = EditMode