そこで、ActiveAdmin フォーム用の Markdown ヘルパーの小さなセットを作成しています。これまでのところ、斜体のものしかありません。
#form.html.erb
# ... some form code
<%= link_to "i", "#", :class => "btn", :id => "italics_button" %>
<%= f.input :body %>
# ... rest of form omitted
ID が「italics_button」のボタンと ID が post_body のテキストエリアが表示されます。これまでのところ、すべて順調です。
これで、選択したテキストを特定のタグでラップするための coffeescript ファイルができました。
#posts.js.coffee
wrapText = (elementID, openTag, closeTag) ->
textArea = $("##{elementID}") #select the text area
len = textArea.val().length #total length of the text area
start = textArea[0].selectionStart # start of the selected text
end = textArea[0].selectionEnd # end of the selected text
selectedText = textArea.val().substring(start, end) # The selected Text
replacement = openTag + selectedText + closeTag # string with the selected text wrapped in the bbcode
textArea.val(textArea.val().substring(0,start) + replacement + textArea.val().substring(end, len)) # perform the replacement
$('#italics_button').click (event) ->
event.preventDefault()
wrapText('post_body', '*', '*')
このコードは問題ないと確信しています。数か月前に、通常の非 AA フォームで同じことを行ったプロジェクトからこのコードを取り出したからです。
カスタム JavaScript を取り込むように初期化子を更新しました。
# active_admin.rb
# rest of file omitted
config.register_javascript 'posts.js.coffee'
そして最後に、Active Admin の New Post ページで、javascript ファイルがインクルードされ、コンパイルされていることを確認できます。
ただし、javascript イベントは呼び出されないようです。#italics_button をクリックすると、ページが「#」へのリンクをたどろうとして、JavaScript が実行されません。