morphic.js icon indicating copy to clipboard operation
morphic.js copied to clipboard

Code submission - "copy" code

Open davidedc opened this issue 12 years ago • 0 comments

Coffeescript:

    # snippets of clipboard-handling code taken from
    # http://codebits.glennjones.net/editing/setclipboarddata.htm
    # Note that this works only in Chrome. Firefox and Safari need a piece of
    # text to be selected in order to even trigger the copy event. Chrome does
    # enable clipboard access instead even if nothing is selected.
    # There are a couple of solutions to this - one is to keep a hidden textfield that
    # handles all copy/paste operations.
    # Another one is to not use a clipboard, but rather an internal string as
    # local memory. So the OS clipboard wouldn't be used, but at least there would
    # be some copy/paste working. Also one would need to intercept the copy/paste
    # key combinations manually instead of from the copy/paste events.
    document.body.addEventListener "copy", ((event) =>
      if @cursor
        selectedText = @cursor.target.selection()
        if event.clipboardData
          event.preventDefault()
          setStatus = event.clipboardData.setData("text/plain", selectedText)

        #log('setData: ' + setStatus);
        if window.clipboardData
          event.returnValue = false
          setStatus = window.clipboardData.setData "Text", selectedText

        #log('setData: ' + setStatus);
    ), false

Javascript:

    // snippets of clipboard-handling code taken from
    // http://codebits.glennjones.net/editing/setclipboarddata.htm
    // Note that this works only in Chrome. Firefox and Safari need a piece of
    // text to be selected in order to even trigger the copy event. Chrome does
    // enable clipboard access instead even if nothing is selected.
    // There are a couple of solutions to this - one is to keep a hidden textfield that
    // handles all copy/paste operations.
    // Another one is to not use a clipboard, but rather an internal string as
    // local memory. So the OS clipboard wouldn't be used, but at least there would
    // be some copy/paste working. Also one would need to intercept the copy/paste
    // key combinations manually instead of from the copy/paste events.

var _this = this;

document.body.addEventListener("copy", (function(event) {
  var selectedText, setStatus;
  if (_this.cursor) {
    selectedText = _this.cursor.target.selection();
    if (event.clipboardData) {
      event.preventDefault();
      setStatus = event.clipboardData.setData("text/plain", selectedText);
    }
    if (window.clipboardData) {
      event.returnValue = false;
      return setStatus = window.clipboardData.setData("Text", selectedText);
    }
  }
}), false);

davidedc avatar Mar 05 '13 18:03 davidedc