Advertisement
Serafim

Untitled

Feb 19th, 2015
305
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   class Textarea
  2.     constructor: (dom) ->
  3.       @textarea = dom
  4.       @value    = @textarea.value
  5.  
  6.     toFrame: (text = '', before = '', after = '') =>
  7.       selection = @getSelectionPosition()
  8.       output = (
  9.         @value.substr(0, selection.start) +
  10.           '' + before + '' +
  11.           text +
  12.           '' + after + '' +
  13.           @value.substr(selection.end)
  14.       )
  15.       @value = output
  16.       @setSelection(selection.start + before.length, selection.end + before.length)
  17.       @
  18.  
  19.     getSelectedLines: =>
  20.       lines = (text) ->
  21.         raw = text.match(/\n/g)
  22.         (if raw? then raw else []).length
  23.  
  24.       selection = @getSelectionPosition()
  25.       return {
  26.         start: lines(@value.substr(0, selection.start)),
  27.         end:   lines(@value.substr(0, selection.end))
  28.       }
  29.  
  30.     getAllLines: =>
  31.       return (@value.match(/\n/g) || []).length + 1
  32.  
  33.  
  34.     setSelection: (from, to) =>
  35.       @textarea.focus()
  36.       @textarea.selectionStart = from
  37.       @textarea.selectionEnd   = to
  38.       @
  39.  
  40.  
  41.     getSelectionText: =>
  42.       cursor = @getSelectionPosition()
  43.       return @value.substr(cursor.start, cursor.end - cursor.start)
  44.  
  45.  
  46.     getSelectionPosition: =>
  47.       [start, end] = [0, 0];
  48.       if document.selection
  49.         @textarea.focus()
  50.         sel = document.selection.createRange()
  51.         sel.moveStart 'character', -@textarea.value.length
  52.         start = sel.text.length;
  53.         sel.moveEnd 'character', -@textarea.value.length
  54.       else if @textarea.selectionStart || @textarea.selectionStart is '0'
  55.         start = @textarea.selectionStart;
  56.         end = @textarea.selectionEnd;
  57.  
  58.       return {start: start, end: end}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement