Skip to content

Commit

Permalink
Try to split long messages on word breaks if there are no line breaks
Browse files Browse the repository at this point in the history
  • Loading branch information
evansolomon committed Dec 10, 2014
1 parent 6fec098 commit 3ef146f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/slack.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,21 @@ class SlackBot extends Adapter

else
# Split message at last line break, if it exists
chunk = msg.substring(0, SlackBot.MAX_MESSAGE_LENGTH)
breakIndex = chunk.lastIndexOf('\n')
breakIndex = SlackBot.MAX_MESSAGE_LENGTH if breakIndex is -1
maxSizeChunk = msg.substring(0, SlackBot.MAX_MESSAGE_LENGTH)

lastLineBreak = maxSizeChunk.lastIndexOf('\n')
lastWordBreak = maxSizeChunk.match(/\W\w+$/)?.index

breakIndex = if lastLineBreak > -1
lastLineBreak
else if lastWordBreak
lastWordBreak
else
SlackBot.MAX_MESSAGE_LENGTH

submessages.push msg.substring(0, breakIndex)

# Skip char if split on line break
# Skip char if split on line or word break
breakIndex++ if breakIndex isnt SlackBot.MAX_MESSAGE_LENGTH

msg = msg.substring(breakIndex, msg.length)
Expand Down
13 changes: 13 additions & 0 deletions test/slack.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,16 @@ describe 'Send Messages', ->
sentMessage = sentMessages.pop()
sentMessage.length.should.equal Math.ceil(len / SlackBot.MAX_MESSAGE_LENGTH)

it 'Should try to split on word breaks', ->
msg = 'Foo bar baz'
slackbot.constructor.MAX_MESSAGE_LENGTH = 10
sentMessages = slackbot.send {room: 'room-name'}, msg
sentMessage = sentMessages.pop()
sentMessage.length.should.equal 2

it 'Should split into max length chunks if there are no breaks', ->
msg = 'Foobar'
slackbot.constructor.MAX_MESSAGE_LENGTH = 3
sentMessages = slackbot.send {room: 'room-name'}, msg
sentMessage = sentMessages.pop()
sentMessage.should.eql ['Foo', 'bar']

0 comments on commit 3ef146f

Please sign in to comment.