기본 콘텐츠로 건너뛰기

contentEditable 사용시 execCommand 에서 Selection 문제 해결법

contentEditable로 WYSWYG 에디터를 만들일이 있어서 하다보니
생각보다 까다로와서 기록해둔다.

먼저 javascript 구현체
http://jsbin.com/erukis/6/edit


<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
<script src="http://twitter.github.com/bootstrap/assets/js/bootstrap.js"></script>
<meta name="description" content="mobile" />
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title></title>
</head>
<body>
  <div class="edit" contentEditable="true">
    여기를 찍어서 수정가능
  </div>
  <button href="#myModal" role="button" class="btn" data-toggle="modal">set Color</button>
  <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h4 id="myModalLabel">set Color</h4>
  </div>
  <div class="modal-body">
    #<span id="color" contentEditable="true">000000</span>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary save" data-dismiss="modal" data-result="save"> Save</button>
  </div>
</div>
</body>
</html>

HTML은 이렇고


var range, selection;
var getRange = function() {
  if (document.body.createTextRange) {
    range = document.body.createTextRange();
  } else if (window.getSelection) {
    selection = window.getSelection();
    range = selection.getRangeAt(0);
  }
  return range;
};
var setRange = function(range) {
  if (document.body.createTextRange) {
    range.select();
  } else {
    selection.removeAllRanges();
    selection.addRange(range);
  }
};
$("#myModal").on("hide", function(e) {
  // 이쪽이 click 이벤트 이후에 발생?
//   selection.removeAllRanges();
}).on("shown", function(e) {
  // 여기서 선택 영역을 백업
  range = getRange();
  return true;
});

$(".save]").click(function() {
  setRange(range);
  console.log($("#color").text());
  document.execCommand("ForeColor", false, $("#color").text());
});

javascript 는 이런 식
stackoverflow랑 microsoft, mozilla 사이트를 뒤져가면서 했는데.
IE 8 이하 일때랑 그렇지 않을때랑 영역을 잡는 방식이 다르다.

contentEditable 인 div 영역을 선택 후 modal을 띄워 해당 텍스트의 색을 execCommand 로 변경하는 예제인데
영역을 선택하고 칼라값을 입력하려면 선택영역의 포커스를 잃어버리기 때문에 execCommand 실행 시점에 적용할 수 없게 된다.
그래서 세운 작전은

  1. 선택한 영역을 백업한다.
  2. save버튼을 누를 시 백업한 선택 영역을 재적용한다.
  3. execCommand 로 색상을 적용한다.

이렇게 구현했다.

시행착오가 있었지만 일단 chrome, FF, IE 9, Safari 등에서 작동을 확인했다.

http://jsbin.com/erukis/7/edit
소스를 coffeescript로 바꾸고 Range class를 만들었다.


class Range
  setRange: =>
    if document.body.createTextRange
      @range.select()
    else
      @selection.removeAllRanges();
      @selection.addRange @range
  getRange: =>
    if document.body.createTextRange
      @range = document.body.createTextRange()
    else
      @selection = window.getSelection()
      @range = @selection && @selection.getRangeAt 0
    return

range = new Range

$("#myModal").on "shown", ->
  range.getRange()
  true

$(".save").click ->
  range.setRange()
  document.execCommand "ForeColor", false, $("#color").text()
  true

역시 커피로 보면 깔끔해서 좋다.
분기를 한건 document.body에 createTextRange 함수가 있는지 여부에 따라 IE8 이하 버전의 처리를 하도록 했는데
document.body.createTextRange()를 하면 body 전체가 선택이 되어 문제가 있다.

document.selection.createRange() 로 변경하고 다소 수정을 해보니

http://jsbin.com/erukis/11/edit


class Range
  setRange: =>
    if document.selection
      @range.select()
    else
      @selection.removeAllRanges();
      @selection.addRange @range
  getRange: =>
    if document.selection
      @range = document.selection.createRange()
    else
      @selection = window.getSelection()
      @range = @selection && @selection.getRangeAt 0
    return

range = new Range

saveStatus = false

$("#myModal").on "shown", ->
  range.getRange()
  saveStatus = false
  true

$("#myModal").on "hidden", ->
  if saveStatus
    range.setRange()
    document.execCommand "ForeColor", false, $("#color").text()
  true

$(".save").click ->
  saveStatus = true
  true


이런 형태가 되었다.
오히려 IE 8 이전 버전의 방식이 더 좋아보인다.
  1. document.selection.createRange() 로 현재 range를 잡고 (물론 multiSelect가 아닌 가정)
  2. @range.select()로 1에서 받은 객체를 기준으로 select 함수를 통해 다시 선택
인셈이다.

달라진 점이 하나 있는데 save 버튼을 누르는 순간 IE는 포커스가 문제가 있는지 execCommand가 적용되지 않아
시점을 modal이 완전히 닫히고 난 다음에 하도록 flag를 주어서 처리하였다.
(hide도 안된다 transition 이 끝난 이후인 hidden으로 해야한다)

만일 이런 삽질이 애초에 싫다면 rangy(https://code.google.com/p/rangy/) 같은 cross-browser library를 사용한다면 좀 더 깔끔하게 할 수 있다.

html 에서 
<script src="http://rangy.googlecode.com/svn/trunk/dev/rangy-core.js"></script>
를 삽입하여 rangy 라이브러리를 가지고 오자.

class Range
  setRange: =>
    @selection.removeAllRanges()
    @selection.addRange @range
    return
  getRange: =>
    @selection = rangy.getSelection()
    @range = @selection.getRangeAt 0
    return

range = new Range

saveStatus = false

$("#myModal").on "shown", ->
  range.getRange()
  saveStatus = false
  true

$("#myModal").on "hidden", ->
  if saveStatus
    range.setRange()
    document.execCommand "ForeColor", false, $("#color").text()
  true

$(".save").click ->
  saveStatus = true
  true

if문을 없애서 좀 더 깔끔한 코드가 되었다.

댓글

이 블로그의 인기 게시물

NeoVim + LazyVim 사용기 - 자주 쓰는 단축 포함.

주로 쓰는 컴터들이 죄다 리모트로만 연결해서 iSH나 Termux 같은 모바일 터미널에서 간단하게 개발환경을 쓰고 싶었음. 사실 vi (vim 도 아님) 으로 충분하지만 avante.nvim  이라는 녀석이 Cursor 처럼 외부 LLM 모델을 쓸 수 있다고 해서 삽질을 시작함;;; macOS 에서야 대충해도 되니 약간 삽질이 필요했던 windows 기준으로 기록. NeoVim 설치 https://winstall.app/apps/Neovim.Neovim winget 이 별도로 설치 없이 쓸 수 있는 package manager 라서 간단하게 winget install --id=Neovim.Neovim  -e 로 끝나는 점이 좋았음.  LazyVim 설치 https://www.lazyvim.org/installation  보고 Powershell 로 설치. 깔끔하다! 생각보다 빠르다! nvim-treesitter 관련 오류 수정 시작할 때 마다 nvim-treesitter 에서 오류 발생. 실행 속도도 느려지고 매우 불편! 다행스럽게도 reddit 에서 해결법을 알려줌. https://www.reddit.com/r/neovim/comments/14oozmu/neovim_cant_find_c_compiler/ choco install mingw  refreshenv   관리자모드에서 mingw 를 설치하고 (winget 으로는 설치 안되는 듯?) refreshenv 하니 해결. 필요한 외부 유틸들 설치 https://www.nerdfonts.com/font-downloads  Nerdfonts 설치. ligature를 쓰고 싶어 FiraCode Nerd Font를 선택. ripgrep ,  fd  도 설치. search & replace 를 편하게 쓸 수 있다. :, esc 눌렀을 때 모달 팝업 같은 UI가 나와서 당황. https://www.youtube.com/wat...

MQTT 접속해제 - LWT(Last will and testament)

통신에서 중요하지만 구현이 까다로운 문제로 "상대방이 예상치 못한 상황으로 인하여 접속이 끊어졌을때"의 처리가 있다. 이것이 까다로운 이유는 상대방이 의도적으로 접속을 종료한 경우는 접속 종료 직전에 자신의 종료 여부를 알리고 나갈 수 있지만 프로그램 오류/네트웍 연결 강제 종료와 같은 의도치 않은 상황에선 자신의 종료를 알릴 수 있는 방법 자체가 없기 때문이다. 그래서 전통적 방식으로는 자신의 생존 여부를 계속 ping을 통해 서버가 물어보고 timeout 시간안에 pong이 안올 경우 서버에서 접속 종료를 인식하는 번거로운 방식을 취하는데 MQTT의 경우 subscribe 시점에서 자신이 접속 종료가 되었을 때 특정 topic으로 지정한 메시지를 보내도록 미리 설정할 수 있다. 이를 LWT(Last will and testament) 라고 한다. 선언을 먼저하고 브로커가 처리하게 하는 방식인 것이다. Last Will And Testament 라는 말 자체도 흥미롭다. 법률용어인데  http://www.investopedia.com/terms/l/last-will-and-testament.asp 대략 내가 죽으면 뒷산 xx평은 작은 아들에게 물려주고 어쩌고 하는 상속 문서 같은 내용이다. 즉, 내가 죽었을(연결이 끊어졌을) 때에 변호사(MQTT Broker - ex. mosquitto/mosca/rabbitMQ등)로 하여금 나의 유언(메시지)를 상속자(해당 토픽에 가입한 subscriber)에게 전달한다라는 의미가 된다. MQTT Client 가 있다면 한번 실습해보자. 여러가지가 있겠지만 다른 글에서처럼  https://www.npmjs.com/package/mqtt  을 사용하도록 한다. npm install mqtt --save 로 설치해도 되고 내 경우는 자주 사용하는 편이어서 npm install -g mqtt 로 전역설치를 했다. 호스트는 무료 제공하고 있는 test.mosquitto.o...

세상 간단한 https(+secured websocket): Caddy

nginx, apache2 같은 걸로 매번 certbot 연동을 통해 https 하는게 지겨워서 알아보니 Caddy라는게 있더라. 설치법은 강하게 크기 위해 알아서 해본다. # cat /etc/caddy/Caddyfile your.shitty.site:8123 {   proxy / localhost:9123 {     websocket     transparent   } } 이건 외부에서 8123으로 들어오는 걸 내부적으로 9123로 맞춰서 https 맞춰주는 reverse proxy. 만일 port를 생략하면 # cat /etc/caddy/Caddyfile your.shitty.site {   proxy / localhost:9123 {     websocket     transparent   } } 기본포트인 443으로 되어 https://your.shitty.site 로 접속이 된다. 요새 말썽이던 cloudflare 버리고 netlify domain이랑 caddy를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.