Sidebar.purs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. module PureTabs.Sidebar where
  2. import Browser.Runtime as Runtime
  3. import Browser.Windows (getCurrent)
  4. import Control.Alt (void)
  5. import Control.Alternative (pure)
  6. import Control.Coroutine as CR
  7. import Control.Coroutine.Aff (emit)
  8. import Control.Coroutine.Aff as CRA
  9. import Control.Monad.Error.Class (throwError)
  10. import Data.Function (($))
  11. import Data.Maybe (Maybe(..))
  12. import Data.Unit (Unit, unit)
  13. import Effect (Effect)
  14. import Effect.Aff (Aff, error)
  15. import Effect.Class (liftEffect)
  16. import Halogen as H
  17. import Halogen.Aff as HA
  18. import Halogen.VDom.Driver (runUI)
  19. import Prelude (bind, discard)
  20. import PureTabs.Model (BackgroundEvent(..), SidebarEvent(..))
  21. import PureTabs.Sidebar.Tabs as Tabs
  22. import Web.DOM.ParentNode (QuerySelector(..))
  23. main :: Effect Unit
  24. main = do
  25. port <- Runtime.connect
  26. HA.runHalogenAff do
  27. currentWindow <- getCurrent
  28. liftEffect $ Runtime.postMessageJson port $ SbHasWindowId currentWindow.id
  29. content' <- HA.selectElement (QuerySelector "#content")
  30. io <- case content' of
  31. Nothing -> throwError (error "Could not find #content")
  32. Just content -> runUI Tabs.component unit content
  33. io.subscribe $ onSidebarMsg port
  34. CR.runProcess ((onBackgroundMsgProducer port) CR.$$ onBackgroundMsgConsumer io.query)
  35. onBackgroundMsgProducer :: Runtime.Port -> CR.Producer BackgroundEvent Aff Unit
  36. onBackgroundMsgProducer port =
  37. CRA.produce \emitter ->
  38. liftEffect $ void $ Runtime.onMessageJsonAddListener port (emit emitter)
  39. onBackgroundMsgConsumer :: (forall a. Tabs.Query a -> Aff (Maybe a)) -> CR.Consumer BackgroundEvent Aff Unit
  40. onBackgroundMsgConsumer query =
  41. CR.consumer
  42. $ case _ of
  43. BgInitialTabList tabs -> do
  44. void $ query $ H.tell $ Tabs.InitialTabList tabs
  45. pure Nothing
  46. BgTabCreated tab -> do
  47. void $ query $ H.tell $ Tabs.TabCreated tab
  48. pure Nothing
  49. BgTabDeleted tabId -> do
  50. void $ query $ H.tell $ Tabs.TabDeleted tabId
  51. pure Nothing
  52. BgTabActivated prev next -> do
  53. void $ query $ H.tell $ Tabs.TabActivated prev next
  54. pure Nothing
  55. BgTabMoved tabId prev next -> do
  56. void $ query $ H.tell $ Tabs.TabMoved tabId prev next
  57. pure Nothing
  58. BgTabUpdated tabId cinfo tab -> do
  59. void $ query $ H.tell $ Tabs.TabInfoChanged tabId cinfo
  60. pure Nothing
  61. _ -> pure Nothing
  62. onSidebarMsg :: Runtime.Port -> CR.Consumer SidebarEvent Aff Unit
  63. onSidebarMsg port =
  64. CR.consumer \msg -> do
  65. liftEffect $ Runtime.postMessageJson port msg
  66. pure Nothing