Nic.hs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. {-# LANGUAGE QuasiQuotes #-}
  2. {-# LANGUAGE TypeFamilies #-}
  3. {-# LANGUAGE FlexibleContexts #-}
  4. {-# LANGUAGE OverloadedStrings #-}
  5. {-# LANGUAGE CPP #-}
  6. -- | Provide the user with a rich text editor.
  7. --
  8. -- According to NIC editor homepage it is not actively maintained since June
  9. -- 2012. There is another better alternative — open sourced Summernote editor
  10. -- released under MIT licence. You can use Summernote in your Yesod forms via
  11. -- separately distributed
  12. -- <http://hackage.haskell.org/package/yesod-form-richtext yesod-form-richtext>
  13. -- package.
  14. module Yesod.Form.Nic
  15. ( YesodNic (..)
  16. , nicHtmlField
  17. ) where
  18. import Yesod.Core
  19. import Yesod.Form
  20. import Text.HTML.SanitizeXSS (sanitizeBalance)
  21. import Text.Hamlet (shamlet)
  22. import Text.Julius (julius, rawJS)
  23. import Text.Blaze.Html.Renderer.String (renderHtml)
  24. import Data.Text (Text, pack)
  25. import Data.Maybe (listToMaybe)
  26. class Yesod a => YesodNic a where
  27. -- | NIC Editor Javascript file.
  28. urlNicEdit :: a -> Either (Route a) Text
  29. urlNicEdit _ = Right "http://js.nicedit.com/nicEdit-latest.js"
  30. nicHtmlField :: YesodNic site => Field (HandlerT site IO) Html
  31. nicHtmlField = Field
  32. { fieldParse = \e _ -> return . Right . fmap (preEscapedToMarkup . sanitizeBalance) . listToMaybe $ e
  33. , fieldView = \theId name attrs val _isReq -> do
  34. toWidget [shamlet|
  35. $newline never
  36. <textarea id="#{theId}" *{attrs} name="#{name}" .html>#{showVal val}
  37. |]
  38. addScript' urlNicEdit
  39. master <- getYesod
  40. toWidget $
  41. case jsLoader master of
  42. BottomOfHeadBlocking -> [julius|
  43. bkLib.onDomLoaded(function(){new nicEditor({fullPanel:true}).panelInstance("#{rawJS theId}")});
  44. |]
  45. _ -> [julius|
  46. (function(){new nicEditor({fullPanel:true}).panelInstance("#{rawJS theId}")})();
  47. |]
  48. , fieldEnctype = UrlEncoded
  49. }
  50. where
  51. showVal = either id (pack . renderHtml)
  52. addScript' :: (MonadWidget m, HandlerSite m ~ site)
  53. => (site -> Either (Route site) Text)
  54. -> m ()
  55. addScript' f = do
  56. y <- getYesod
  57. addScriptEither $ f y