Sidebar.purs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. module PureTabs.Sidebar where
  2. import Browser.Runtime as Runtime
  3. import Browser.Tabs (Tab, TabId, WindowId)
  4. import Browser.Windows (getCurrent)
  5. import Control.Alternative (pure)
  6. import Control.Bind ((>=>))
  7. import Data.Foldable (traverse_)
  8. import Data.Function (flip)
  9. import Data.Monoid ((<>))
  10. import Data.Newtype (unwrap)
  11. import Data.Show (show)
  12. import Data.Unit (unit)
  13. import Debug.Trace (traceM)
  14. import Effect (Effect)
  15. import Effect.Aff (Aff, launchAff_)
  16. import Effect.Class (liftEffect)
  17. import Effect.Console (log)
  18. import JQuery (JQuery, append, create, remove, select, setAttr, setText)
  19. import Prelude (Unit, bind, ($), discard)
  20. import PureTabs.Model (BackgroundEvent(..), SidebarEvent(..))
  21. main :: Effect Unit
  22. main = do
  23. log "started sidebar"
  24. port <- Runtime.connect
  25. launchAff_ $ runSidebar port
  26. where
  27. runSidebar :: Runtime.Port -> Aff Unit
  28. runSidebar port = do
  29. currentWindow <- getCurrent
  30. liftEffect $ initSidebar port currentWindow.id
  31. initSidebar :: Runtime.Port -> WindowId -> Effect Unit
  32. initSidebar port winId = do
  33. log $ "windowId " <> (show winId)
  34. Runtime.postMessageJson port $ SbHasWindowId winId
  35. tabsDiv <- select "#tabs"
  36. _ <- Runtime.onMessageJsonAddListener port $ onMsg tabsDiv
  37. pure unit
  38. where
  39. onMsg :: JQuery -> BackgroundEvent -> Effect Unit
  40. onMsg contentDiv event = case event of
  41. BgTabCreated tab -> do
  42. tabElem <- createTabElement tab
  43. append tabElem contentDiv
  44. pure unit
  45. BgTabDeleted tabId -> deleteTabElement tabId
  46. BgInitialTabList tabs ->
  47. traverse_ (createTabElement >=> (flip append) contentDiv) tabs
  48. _ -> log "received unsupported message type"
  49. createTabElement :: Tab -> Effect JQuery
  50. createTabElement tab' = do
  51. let
  52. tab = unwrap tab'
  53. tabDiv <- create "<div>"
  54. setText tab.title tabDiv
  55. setAttr "class" "tab" tabDiv
  56. setAttr "id" tab.id tabDiv
  57. favicon <- create "<span class=\"favicon\">"
  58. tabTitle <- create "<span class=\"tab-title\">"
  59. append favicon tabDiv
  60. append tabTitle tabDiv
  61. pure tabDiv
  62. deleteTabElement :: TabId -> Effect Unit
  63. deleteTabElement tabId = do
  64. div <- select ("#" <> show tabId)
  65. remove div