Autosize.coffee 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. class Autosize extends Class
  2. constructor: (@attrs={}) ->
  3. @node = null
  4. @attrs.classes ?= {}
  5. @attrs.classes.loading ?= false
  6. @attrs.oninput ?= @handleInput
  7. @attrs.onkeydown ?= @handleKeydown
  8. @attrs.afterCreate ?= @storeNode
  9. @attrs.rows ?= 1
  10. @attrs.disabled ?= false
  11. @attrs.value ?= null
  12. @attrs.title_submit ?= null
  13. @property 'loading',
  14. get: -> @attrs.classes.loading
  15. set: (loading) ->
  16. @attrs.classes.loading = loading
  17. @node.value = @attrs.value
  18. @autoHeight()
  19. Page.projector.scheduleRender()
  20. storeNode: (node) =>
  21. @node = node
  22. if @attrs.focused
  23. node.setSelectionRange(0,0)
  24. node.focus()
  25. setTimeout =>
  26. @autoHeight()
  27. setValue: (value=null) =>
  28. @attrs.value = value
  29. if @node
  30. @node.value = value
  31. @autoHeight()
  32. Page.projector.scheduleRender()
  33. autoHeight: =>
  34. height_before = @node.style.height
  35. if height_before
  36. @node.style.height = "0px"
  37. h = @node.offsetHeight
  38. scrollh = @node.scrollHeight
  39. @node.style.height = height_before
  40. if scrollh > h
  41. anime({targets: @node, height: scrollh, scrollTop: 0})
  42. else
  43. @node.style.height = height_before
  44. handleInput: (e=null) =>
  45. @attrs.value = e.target.value
  46. RateLimit 300, @autoHeight
  47. handleKeydown: (e=null) =>
  48. if e.which == 13 and e.ctrlKey and @attrs.onsubmit and @attrs.value.trim()
  49. @submit()
  50. submit: =>
  51. @attrs.onsubmit()
  52. setTimeout ( =>
  53. @autoHeight()
  54. ), 100
  55. return false
  56. render: (body=null) =>
  57. if body and @attrs.value == null
  58. @setValue(body)
  59. if @loading
  60. attrs = clone(@attrs)
  61. #attrs.value = "Submitting..."
  62. attrs.disabled = true
  63. tag_textarea = h("textarea.autosize", attrs)
  64. else
  65. tag_textarea = h("textarea.autosize", @attrs)
  66. return [
  67. tag_textarea,
  68. if @attrs.title_submit
  69. h(
  70. "a.button.button.button-submit.button-small",
  71. {href: "#Submit", onclick: @submit, classes: @attrs.classes},
  72. @attrs.title_submit
  73. )
  74. ]
  75. window.Autosize = Autosize