기본 콘텐츠로 건너뛰기

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문을 없애서 좀 더 깔끔한 코드가 되었다.

댓글

이 블로그의 인기 게시물

세상 간단한 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를 쓰니까 앓던 이가 빠진 느낌. 이 조합은 당분간 계속 써야겠다 싶다.

LG G Pro 2 Custom Rom +Rooting 기록

선 루팅 https://forum.xda-developers.com/lg-g3/general/guide-root-lg-firmwares-kitkat-lollipop-t3056951 1.2버전 스크립트 모드로. echo Looking for LG serial port.. echo. adb.exe wait-for-device 여기에서 정체 상태여서 강제로 adb kill-server 했더니 알아서 재부팅하심. 폰에선 "펌웨어 업데이트"화면이 나오고 Phone found at COM5! Rooting phone.. If you don't see the SuperSu installer script runs within about a minute, then the root failed. Author : blog.lvu.kr SPECIAL COMMAND : ENTER, LEAVE ## 이런 상황이 됨. #이 느린 속도로 하나씩 증가하고 있음. 한 시간 기다려도 성과없음. 뭐 몇번해봐도 안되고 결국 불안하긴 하지만 kingroot.net  로 설치 롤리팝이니까  https://drive.google.com/file/d/0B4kfGU1z_PClQ3AyM2lKOGR1S3M/view  이걸 받아서 압축 풀기. d838recovery.bat 만 있어서 당황스럽긴한데 실행하고 1번 하니까 리커버리 모드 진입까진 잘 되는 듯. adb sideload 라는게 있어서 해봄. Advance에서 adb sideload 선택하고 USB연결한 PC에서 adb sideload RR-N-v5.8.5-20171010-d838-Final.zip 하니까 착착 잘 진행됨. 이제 흉측한 U+LTE 가 없어짐. ㅇㅋ 군더더기 없고 깔끔한데 남은 건 gapps 를 설치해야함. http://opengapps.org/  를 권해줘서 갔는데 지옥 느림. ARM + 7.1 + stock 이 기본이...

Google Daydream 소감

드디어 V30 사은품인 Daydream이 왔다. 낭랑한 벨과 함께 무심한 듯 시크하게 툭 던지고 가시는 택배느님. 수령까지 두달 걸렸다. 눈을 뜨고 꿈꿔 보세요. 여기가 눈감으면 코베어 간다는 서울인가? 주황색면으로 열면 된다. 컨트롤러의 만듦새는 아주 좋다. 기존에 나와있는 사진엔 가로 머리끈만 있어서 똥머리한 언니들도 막 쓰고 플레이하고 그랬는데 실제로 보니 이중 끈이었다. 보통 돌아다니는 착샷 Daydream 설치 - 실행 - 폰 장착 - 컨트롤러 페어링 - VR진입까지 과정을 쉽게 하려고한 노력이 보였음. NFC로 데이드림뷰어에 폰을 장착하면 자동으로 인식하여 데이드림 앱이 실행되는 경험은 꽤 괜찮았음. 컨트롤러는 크기, 그립감 면에서 매우 훌륭하고 인식률, 반응속도 모두 만족스러움. 홈버튼으로 시선을 재 조정하는 발상은 좋은데 왼쪽 오른쪽이 앱마다 조금 혼란스럽고 상하방향 캘리브레이션은 안된다. 이 부분에서 좌절했다. 누워서 넷플릭스를 보는 건 다른 방법을 찾아보아야한다는 소리. 알고보니 이런 건 Youtube이나 Netflix, Skybox player 등등에서 테스트해본 결과 자체 앱에서 지원하고 있다. Netflix는 void theater라는 것이 있는데  <출처:  https://元ボクサーの一念発起.com/2018/05/10/oculus-go/ > Netflix app에서 요렇게 눈송이 같이 생긴 아이콘을 컨트롤러로 찍고 들어가면 화면만 덩그러니 나오고 스티어링휠(자동차 핸들) 모양 아이콘을 선택하고 누으면 자연스럽게 조정이 되었다. Youtube나 Skybox앱의 경우 아예 컨트롤러에서 꾹 누르고 화면 이동하는게 가능해서 편리. 게임은 이것저것 해봤는데 Rez Infinite이 최고. 아니 이건 그냥 전 VR 기기를 통틀어서 Rez Infinite이 최고가 아닐까 싶음;;; 결론,  1. 누워서 보기 잘된다. 2. ...