Skip to content

Commit

Permalink
Merge pull request #401 from Asana/paste_container_to_delta
Browse files Browse the repository at this point in the history
Provide a paste-manager api to customize final delta
  • Loading branch information
jhchen committed Jun 26, 2015
2 parents 7243bf2 + 2db704e commit 54cae74
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/modules/paste-manager.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,34 @@ dom = Quill.require('dom')
Delta = Quill.require('delta')

class PasteManager
constructor: (@quill, @options) ->
@DEFAULTS:
onConvert: null

constructor: (@quill, options) ->
@container = @quill.addContainer('ql-paste-manager')
@container.setAttribute('contenteditable', true)
dom(@quill.root).on('paste', _.bind(this._paste, this))
@options = _.defaults(options, PasteManager.DEFAULTS)
@options.onConvert ?= this._onConvert;

_onConvert: (container) =>
doc = new Document(container, @quill.options)
delta = doc.toDelta()
lengthAdded = delta.length()
if lengthAdded == 0
return delta
# Need to remove trailing newline so paste is inline, losing format is expected and observed in Word
return delta.compose(new Delta().retain(lengthAdded - 1).delete(1))

_paste: ->
oldDocLength = @quill.getLength()
range = @quill.getSelection()
return unless range?
@container.focus()
_.defer( =>
doc = new Document(@container, @quill.options)
delta = doc.toDelta()
lengthAdded = Math.max(0, delta.length() - 1)
delta = @options.onConvert(@container)
lengthAdded = delta.length()
if lengthAdded > 0
# Need to remove trailing newline so paste is inline, losing format is expected and observed in Word
delta = delta.compose(new Delta().retain(lengthAdded).delete(1))
delta.ops.unshift({ retain: range.start }) if range.start > 0
delta.delete(range.end - range.start)
@quill.updateContents(delta, 'user')
Expand Down
38 changes: 38 additions & 0 deletions test/unit/modules/paste-manager.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,42 @@ describe('PasteManager', ->
)
)
)

it('optionally allows custom delta creation', (done) ->
container = $('#editor-container').get(0)
container.innerHTML = '
<div>
<div>0123</div>
</div>'
quill = new Quill(container.firstChild, {
modules: {
'paste-manager': {
onConvert: ->
new Quill.Delta().insert('something else', {
italic: true
})
}
}
})
pasteManager = quill.getModule('paste-manager')
quill.setSelection(2, 2)
pasteManager._paste()
pasteManager.container.innerHTML = '
<b>Pasted</b>
<div style="text-align: right;">Text</div>
'
quill.on(Quill.events.TEXT_CHANGE, (delta) ->
expect(delta).toEqualDelta(
new Quill.Delta()
.retain(2)
.insert('something else', { italic: true })
)
_.defer( ->
range = quill.getSelection()
expect(range.start).toEqual(16)
expect(range.end).toEqual(16)
done()
)
)
)
)

0 comments on commit 54cae74

Please sign in to comment.