기본 콘텐츠로 건너뛰기

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 이 기본이...

느려터진 안드로이드 에뮬은 버리고 VM을 쓰자.

iOS개발 환경이 안드로이드보다 우월점은 여러가지가 있겠지만 개인적으로 가장 큰부분이라고 생각하는 점이 iOS Simulator 의 넘사벽 속도다. 사실 iOS 의 경우 Emulator 가 아니라 Simulator 라는 훼이크를 써서 그런건데. 하드웨어+소프트웨어를 같이 하는 회사만이 쓸 수 있는 필살기라 볼 수 있다. 반면 안드로이드의 경우 ARM 에뮬레이터를 사용하는데 이게 참 못만들었다. 플스에뮬이나 GBA에뮬 반정도만 만들어도 써줄텐데 아직 갈길이 멀다. 그래서 구시렁 거리면서 하드웨어를 연결해서 테스트를 하고 있는데 역시 USB연결하는 건 불편하고 apk 를 전송하는 과정도 그다지 빠르지 않아서 개발 생산성이 월등히 나아지지는 않는다. 루팅을 하면 wifi 를 통해 apk 를 인스톨 할 수 있다고 해서 몇 가지를 해보았으나 잘 모르겠지만 인스톨까진 잘 되었는데 디버깅 모드로 실행이 되지 않아 그만두었다. 게다가 전송속도도 USB보다 wifi가 느리고 맘에 들지 않더라. 그러던중 stackoverflow.com(늘 신세지고 있습니다) 에서 "VM으로 안드로이드를 띄워서 adb connect 하면 좋아!" 라는 글에 눈이 번쩍. 시행착오를 몇번 했지만 의외로 간단하더라. 1. VMWare건 VirtualBox건 상관없다. VM호스트를 준비하자. 2. http://www.android-x86.org/download 로 가서  Deprecated x86 2.2 generic  을 받자. Q) 왜 Deprecated 인 2.2 generic 을 받나요. Deprecated는 쓰면 안되는 거 아님? A) http://mariuz.android-dev.ro/vm.iso.7z 도 있다고 한다. http://www.android-x86.org/download 에 있는 요즘 것들은 죄다 안된다. 3. 죄다 일단 Default 설정에 yes yes 하고 설치한다. 한글 문서가 필요한 분은 ...