기본 콘텐츠로 건너뛰기

coffee는 쓰고 싶고 jsx는 쓰기 싫고. 그러면 만들어야지.

이 블로그를 꾸준히 보시는 분들은 아마도 {}, [] 같은 시작과 끝만 알리고 아무것도 실행하지 않는 주제에 오롯이 한 행을 죄다 차지하는게 싫어서 coffee나 jade나 stylus를 쓰는 변태영감탱이의 글들을 읽고 계실거다.

나는 Meteor를 매우 좋아하는 사람이고 Meteor 사용자의 저변을 넓히기 위해 frontend에서 가장 뜨거운 React를 Meteor에서 쓰면 좋다라고 열심히 약을 팔고 있는데.
정작 내게 불편한 것은 jsx였다.

https://facebook.github.io/react/docs/react-without-jsx.html
이런 것이 없는 건 아닌데
이따위로 만들어놨다는 얘기는 쓰지 말란 얘기지.
그리고 어짜피 문서가 아닌데 구태여 코드안에 html을 쓸 이유가 있나?
애초에 html,css,js 로 분리한 건 의미를 가진 문서(html)를 서식화(css)해서 로직(js)을 돌아가게 함인데 이미 html도 css도 쓰지 않는 시점에서 코드안에 html을 섞어쓰는 것은 내겐 매우 불편한 일이었다.

그렇다면 DOM과 같이 위계를 갖는 요소를 어떻게 표현할 것이냐는 의문이 생기는데
다행히도 좋은 모델(http://mithril.js.org/#dom-elements)이 있다.

그러고보니 여기는 기껏 jsx를 지원한다고 했는데 내가 하려고 하는 건 그 반대;; 역시 변태영감인 것이다.
<div>
  <hr>
  <ul>
    <li>
      First
    <li>
      <p style="font-weight: bold">Second</p>
    </li>
  </ul>
  <div>
    <span>110</span>
    <hr>
  </div>
  <div>
    <label for="message">Message</label>
    <input type="text" id="message">
    <button>click</button>
  </div>
  <p>HMM Taste Good!</p>
</div>
요정도를 표현할 수 있으면 좋겠다 싶어서 뽑아보았다.
React는 CSS를 별도로 작성하는 걸 좋아하지 않아보인다. style도 인라인으로 넣었다.
만일 jade(pug) 라면 마치 CSS Selector 처럼.
div
  hr
  ul
    li First
    li
      p(style='font-weight: bold') Second
  div
    span 110
  div
    label(for="message") Message
    input#message(type="text")
    button click
  p HMM Taste Good!
이렇게 만들 수 있을 것이다.
닫는 태그들을 생략하여 라인 수가 줄어들었고 보기에도 편하다.
아마도 내가 원하는 최종 결과물은 다음과 같을 것이다.
b 'div',
  b 'hr'
  b 'ul',
    b 'li', 'First'
    b 'li',
      b 'p', style: 'font-weight': 'bold', 'Second'
  b 'div',
    b 'span', 110
  b 'div',
    b 'label', 'for': 'message', 'Message'
    b 'input', id: 'message', type: 'text'
    b 'button', 'click'
  p 'HMM Taste Good!'
이렇게 하기 위해 React.createElement를 재정의할 필요가 있다.
React.createElement(https://facebook.github.io/react/docs/react-api.html#createelement)는 세개의 인자를 받는데
https://facebook.github.io/react/docs/react-api.html#createelement
React.createElement(
  type,
  [props],
  [...children]
)
type, props, children 세가지다. (props 는 사실 object 인데 왜 []안에 넣어놨는지 모르겠다;;; )
구조상 인자가 null이 들어가는게 아름답지 않고 children이 array면 []를 써야해서 싫다.
편의상 b(mithril은 m)라고 하고 syntactic sugar를 만들어보자.
b = ->
  a = Array.from arguments
  args=[]
  if a.length is 1
    args=[a[0]]
  else
    if a[1]?.$$typeof
      args=[a[0], null, a[1..]]
    else
      if typeof a[1] isnt 'object'
        args=[a[0], null, a[1]]
      else
        args=[a[0], a[1], a[2] and a[2..]]
  React.createElement.apply React, args
결과물은 대략 이렇다. React.createElement의 반환형이 .$$typeof를 가지고 있는 것으로 구분했다.
https://jsbin.com/xaqorac/edit?html,js,output
내 기준으론 만족스럽고 아름답다.

꼭 coffee를 쓰지 않고 js로 해도
b('div',
  b('hr'),
  b('ul',
    b('li', 'First'),
    b('li',
      b('p', {style: {'font-weight': 'bold'}}, 'Second')
    )
  ),
  b('div',
    b('span', 110)
  ),
  b('div',
    b('label', 'for': 'message', 'Message'),
    b('input', id: 'message', type: 'text'),
    b('button', 'click')
  ),
  p('HMM Taste Good!')
)
https://goo.gl/VFvnDU  decaffeinate (http://decaffeinate-project.org/repl/) 로 돌려서 js 변환해보았다.
충분히 아름답다.

* 추가 수정: 반복되는 요소를 표현할 때 map을 쓰는데 반환형이 array인 경우 처리를 포함해야해서 조금 수정했다. 하위 children들은 n개의 arguments로 확장할 수도 있어서 그냥 property가 없는 경우 null을 끼워넣는 식으로 구현하는게 낫겠다 싶어서 수정.
b = ->
  a = Array.from arguments
  args = a
  args.splice 1,0,null if (a[1]?.$$typeof or
    Array.isArray a[1]) or
    (typeof a[1] isnt 'object')
  React.createElement.apply React, args
좀 더 단순하고 유연한 것 같기도.

당연한 얘기지만 React-Native에서도 쓸 수 있다.
Element를 만드는 부분을 분리한다.
React = require 'react'
module.exports = ->
  a = Array.from arguments
  args = a
  args.splice 1,0,null if (a[1]?.$$typeof or
    Array.isArray a[1]) or
    (typeof a[1] isnt 'object')
  React.createElement.apply React, args
그리고 본체에서 사용한다.
React = require 'react'
{
  AppRegistry
  StyleSheet
  Text
  View
} = require 'react-native'
b = require './src/ceact'
class App extends React.Component
  render: ->
    b View, style: styles.container,
      b Text, "Open up main.js to start working on your app."
      b View,
        b Text, key:v, "#{v}number" for v in [1..5]
styles = StyleSheet.create
  container:
    flex: 1
    backgroundColor: '#fff'
    alignItems: 'center'
    justifyContent: 'center'
AppRegistry.registerComponent 'main', => App
coffee로 쓰면 style이 stylus같이 나와서 좋다.
React Native는 각각의 Component를 구성하는 방식이라 "div" 식으로 태그 이름을 쓸 필요가 없다.
사실 React 보다는 React-Native랑 더 어울린다고 본다.
React = require 'react'
{Component} = React
{
  AppRegistry
  StyleSheet
  Text
  View
} = require 'react-native'
b = require './src/ceact'
class App extends Component
  render: ->
    b View, style: styles.container,
      b Text, "Open up main.js to start working on your app."
      b View,
        b Text, key:v, "#{v}number" for v in [1..5]
styles = StyleSheet.create
  container:
    flex: 1
    backgroundColor: '#fff'
    alignItems: 'center'
    justifyContent: 'center'
AppRegistry.registerComponent 'main', => App
잘 작동한다. "" 없이 element를 쓰니 더 좋다.

댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

OS X 터미널에서 tmux 사용시 pane 크기 조절

http://superuser.com/a/660072  글 참조. OS X 에서 tmux 사용시 나눠놓은 pane 크기 조정할 때 원래는 ctrl+b, ctrl+↑←→↓ 로 사이즈를 조정하는데 기본 터미널 키 입력이 조금 문제가 있다. 키 매핑을 다시 하자 Preferences(cmd+,) > Profile >  변경하고자 하는 Theme 선택 > Keyboards 로 들어가서 \033[1;5A \033[1;5B \033[1;5C \033[1;5D 를 순서대로 ↑↓→←순으로 매핑이 되도록 하면 된다. +를 누르고 Key에 해당 화살표키와 Modifier에 ctrl 선택 한 후 <esc>, [, 1, ;, 5 까지 한키 한키 입력 후 A,B,C,D를 써준다. 잘못 입력했을 땐 당황하지 말고 Delete on character 버튼을 눌러 수정하도록 하자. 그리고 다시 tmux에서 ctrl+b, ctrl+↑←→↓로 사이즈를 조절해보자. 잘 된다.