on develop help sign in
107 files changed+12215−4919
since splitsnapshots
unifiedsplit
.github/workflows/haskell.yml+47 .gitignore+7 CONTRIBUTING.md+65 FAQ.md+31 LICENSE+1−1 Quickref.md+29−77 README.md+15−9 cabal.project+10 cabal.project-nogtk+14 chrome-test-utils/LICENSE+12 chrome-test-utils/chrome-test-utils.cabal+30 chrome-test-utils/src/Test/Util/ChromeFlags.hs+17 chrome-test-utils/src/Test/Util/UnshareNetwork.hs+12 default.nix−50 dep/reflex-platform/default.nix+2 dep/reflex-platform/github.json+8 dep/reflex-platform/thunk.nix+9 reflex-dom-core/ChangeLog.md+94 reflex-dom-core/LICENSE+12 Setup.hs → reflex-dom-core/Setup.hs reflex-dom-core/reflex-dom-core.cabal+259 reflex-dom-core/src-ghc/Foreign/JavaScript/Internal/Utils.hs+17 reflex-dom-core/src-ghcjs/Foreign/JavaScript/Internal/Utils.hs+18 reflex-dom-core/src/Foreign/JavaScript/Orphans.hs+37 reflex-dom-core/src/Foreign/JavaScript/TH.hs+581 reflex-dom-core/src/Foreign/JavaScript/Utils.hs+58 reflex-dom-core/src/Reflex/Dom/Builder/Class.hs+755 reflex-dom-core/src/Reflex/Dom/Builder/Class/Events.hs+387 reflex-dom-core/src/Reflex/Dom/Builder/Class/TH.hs+12 reflex-dom-core/src/Reflex/Dom/Builder/Hydratable.hs+116 reflex-dom-core/src/Reflex/Dom/Builder/Immediate.hs+2733 reflex-dom-core/src/Reflex/Dom/Builder/InputDisabled.hs+116 reflex-dom-core/src/Reflex/Dom/Builder/Static.hs+399 src/Reflex/Dom/Class.hs → reflex-dom-core/src/Reflex/Dom/Class.hs+6−9 reflex-dom-core/src/Reflex/Dom/Core.hs+22 reflex-dom-core/src/Reflex/Dom/Location.hs+200 reflex-dom-core/src/Reflex/Dom/Main.hs+376 reflex-dom-core/src/Reflex/Dom/Modals/Class.hs+7 src/Reflex/Dom/Old.hs → reflex-dom-core/src/Reflex/Dom/Old.hs+93−58 reflex-dom-core/src/Reflex/Dom/Prerender.hs+326 src/Reflex/Dom/Storage.hs → reflex-dom-core/src/Reflex/Dom/Storage.hs reflex-dom-core/src/Reflex/Dom/Time.hs+3 reflex-dom-core/src/Reflex/Dom/WebSocket.hs+189 reflex-dom-core/src/Reflex/Dom/WebSocket/Foreign.hs+102 reflex-dom-core/src/Reflex/Dom/WebSocket/Query.hs+37 src/Reflex/Dom/Widget.hs → reflex-dom-core/src/Reflex/Dom/Widget.hs reflex-dom-core/src/Reflex/Dom/Widget/Basic.hs+345 src/Reflex/Dom/Widget/Input.hs → reflex-dom-core/src/Reflex/Dom/Widget/Input.hs+231−121 src/Reflex/Dom/Widget/Lazy.hs → reflex-dom-core/src/Reflex/Dom/Widget/Lazy.hs+22−19 src/Reflex/Dom/Widget/Resize.hs → reflex-dom-core/src/Reflex/Dom/Widget/Resize.hs+34−22 reflex-dom-core/src/Reflex/Dom/Xhr.hs+453 src/Reflex/Dom/Xhr/Exception.hs → reflex-dom-core/src/Reflex/Dom/Xhr/Exception.hs src-ghcjs/Reflex/Dom/Xhr/Foreign.hs → reflex-dom-core/src/Reflex/Dom/Xhr/Foreign.hs+62−56 reflex-dom-core/src/Reflex/Dom/Xhr/FormData.hs+47 reflex-dom-core/src/Reflex/Dom/Xhr/ResponseType.hs+21 test/BrokenHaltSpec.hs → reflex-dom-core/test/BrokenHaltSpec.hs test/HaltSpec.hs → reflex-dom-core/test/HaltSpec.hs reflex-dom-core/test/gc.hs+98 reflex-dom-core/test/hlint.hs+26 reflex-dom-core/test/hydration.hs+1828 reflex-dom-test-selenium/CHANGELOG.md+5 reflex-dom-test-selenium/LICENSE+12 reflex-dom-test-selenium/Setup.hs+2 reflex-dom-test-selenium/add-overrides.nix+20 reflex-dom-test-selenium/reflex-dom-test-selenium.cabal+41 reflex-dom-test-selenium/src/Reflex/Dom/Test/Selenium.hs+249 reflex-dom.cabal−117 reflex-dom/ChangeLog.md+42 reflex-dom/LICENSE+12 reflex-dom/Setup.hs+2 reflex-dom/benchmark.hs+190 reflex-dom/benchmarks/krausest.hs+222 reflex-dom/cbits/MainWidget.c+89 reflex-dom/cbits/include/MainWidget.h+13 reflex-dom/examples/sortableList.hs+82 reflex-dom/java/org/reflexfrp/reflexdom/MainWidget.java+195 reflex-dom/reflex-dom.cabal+213 reflex-dom/src-android/Reflex/Dom/Android/MainWidget.hsc+117 reflex-dom/src/Reflex/Dom.hs+11 reflex-dom/src/Reflex/Dom/Internal.hs+122 release.nix+63 src-ghc/Reflex/Dom/Internal/Foreign.hs−168 src-ghc/Reflex/Dom/WebSocket/Foreign.hs−83 src-ghc/Reflex/Dom/Xhr/Foreign.hs−224 src-ghcjs/Reflex/Dom/Internal/Foreign.hs−43 src-ghcjs/Reflex/Dom/WebSocket/Foreign.hs−51 src/Foreign/JavaScript/TH.hs−519 src/Reflex/Dom.hs−17 src/Reflex/Dom/Builder/Class.hs−375 src/Reflex/Dom/Builder/Class/Events.hs−164 src/Reflex/Dom/Builder/Immediate.hs−789 src/Reflex/Dom/Builder/Static.hs−194 src/Reflex/Dom/Deletable/Class.hs−17 src/Reflex/Dom/DynamicWriter.hs−241 src/Reflex/Dom/Internal.hs−124 src/Reflex/Dom/Location.hs−13 src/Reflex/Dom/PerformEvent/Base.hs−177 src/Reflex/Dom/PerformEvent/Class.hs−46 src/Reflex/Dom/PostBuild/Class.hs−128 src/Reflex/Dom/Time.hs−184 src/Reflex/Dom/WebSocket.hs−97 src/Reflex/Dom/Widget/Basic.hs−421 src/Reflex/Dom/Xhr.hs−272 src/Reflex/Dom/Xhr/ResponseType.hs−21 test/default.nix+10 test/hlint.hs−12 test/reflex-dom-reexports.hs+72
.github/workflows/haskell.ymlnew file+47
@@ -0,0 +1,47 @@
1+name: github-action
2+
3+on: [push, pull_request]
4+
5+jobs:
6+ build:
7+ strategy:
8+ matrix:
9+ ghc: ['8.4.4', '8.6.5', '8.8.4', '8.10.2']
10+ os: ['ubuntu-latest', 'macos-latest']
11+ exclude:
12+ # There are some linker warnings in 802 on darwin that
13+ # cause compilation to fail
14+ # See https://github.com/NixOS/nixpkgs/issues/25139
15+ - ghc: '8.0.2'
16+ os: 'macos-latest'
17+ runs-on: ${{ matrix.os }}
18+
19+ name: GHC ${{ matrix.ghc }} on ${{ matrix.os }}
20+ steps:
21+ - uses: actions/checkout@v2
22+ - uses: actions/setup-haskell@v1
23+ with:
24+ ghc-version: ${{ matrix.ghc }}
25+ - name: Cache
26+ uses: actions/cache@v1
27+ env:
28+ cache-name: cache-cabal
29+ with:
30+ path: ~/.cabal
31+ key: ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-${{ hashFiles('**/*.cabal') }}-${{ hashFiles('**/cabal.project') }}
32+ restore-keys: |
33+ ${{ runner.os }}-${{ matrix.ghc }}-build-${{ env.cache-name }}-
34+ ${{ runner.os }}-${{ matrix.ghc }}-build-
35+ ${{ runner.os }}-${{ matrix.ghc }}-
36+ ${{ runner.os }}
37+
38+ - name: Set up cabal project file to avoid webkit2gtk
39+ run: cp cabal.project-nogtk cabal.project
40+ - name: Install dependencies
41+ run: |
42+ cabal update
43+ cabal build --only-dependencies --enable-tests --enable-benchmarks all
44+ - name: Build
45+ run: cabal build --enable-tests --enable-benchmarks all
46+ - name: Run tests
47+ run: cabal test all
.gitignore+7
@@ -32,3 +32,10 @@ hsenv.log
3232\#*#
3333.#*
3434*_stub.h
35+.cabal-sandbox/
36+cabal.sandbox.config
37+.stack-work
38+codex.tags
39+*.dump-*
40+*.verbose-core2core
41+*.lkshf
CONTRIBUTING.mdnew file+65
@@ -0,0 +1,65 @@
1+# Contribution Guide
2+
3+Contributions and issue reports are encouraged and appreciated!
4+
5+- [Opening Issues](#opening-issues)
6+- [Submitting Changes](#submitting-changes)
7+ - [Guidelines for Commit Messages](#guidelines-for-commit-messages)
8+ - [Guidelines for Pull Requests](#guidelines-for-pull-requests)
9+ - [Code Quality](#code-quality)
10+ - [Documentation](#documentation)
11+
12+## Opening Issues
13+
14+Before opening an issue, please check whether your issue has already been reported. Assuming it has not:
15+
16+* Describe the issue you're encountering or the suggestion you're making
17+* Include any relevant steps to reproduce or code samples you can. It's always easier for us to debug if we have something that demonstrates the error.
18+* Let us know what version of this project you were using. If you're using a github checkout, provide the git hash.
19+* Describe how you're building this project (i.e., via reflex-platform, cabal install, stack, obelisk, etc.). If you're using reflex-platform or obelisk, provide the git hash of your checkout.
20+
21+## Submitting Changes
22+
23+### Guidelines for Commit Messages
24+
25+#### Summary Line
26+The summary line of your commit message should summarize the changes being made. Commit messages should be written in the imperative mood and should describe what happens when the commit is applied.
27+
28+One way to think about it is that your commit message should be able to complete the sentence:
29+"When applied, this commit will..."
30+
31+#### Body
32+For breaking changes, new features, refactors, or other major changes, the body of the commit message should describe the motivation behind the change in greater detail and may include references to the issue tracker. The body shouldn't repeat code/comments from the diff.
33+
34+### Guidelines for Pull Requests
35+
36+Wherever possible, pull requests should add a single feature or fix a single bug. Pull requests should not bundle several unrelated changes.
37+
38+### Code Quality
39+
40+#### Warnings
41+
42+Your pull request should add no new warnings to the project. It should also generally not disable any warnings.
43+
44+#### Build and Test
45+
46+Make sure the project builds and that the tests pass! This will generally also be checked by CI before merge, but trying it yourself first means you'll catch problems earlier and your contribution can be merged that much sooner!
47+
48+### Documentation
49+
50+#### In the code
51+We're always striving to improve documentation. Please include [haddock](https://haskell-haddock.readthedocs.io/en/latest/index.html) documentation for any added code, and update the documentation for any code you modify.
52+
53+#### In the Changelog
54+Add an entry to the changelog when your PR:
55+* Adds a feature
56+* Deprecates something
57+* Includes a breaking change
58+* Makes any other change that will impact users
59+
60+You may need to add changelog entries to one or both of the changelogs in this repository:
61+* [reflex-dom-core's changelog](reflex-dom-core/ChangeLog.md)
62+* [reflex-dom's changelog](reflex-dom/ChangeLog.md)
63+
64+#### In the [Readme](README.md)
65+The readme is the first place a lot of people look for information about the repository. Update any parts of the readme that are affected by your PR.
FAQ.mdnew file+31
@@ -0,0 +1,31 @@
1+# Frequently Asked Questions
2+
3+### How do I configure DOM events with flags like `preventDefault` and `stopPropagation`?
4+
5+Using `element`, a low-level DOM builder function. Its second argument, `ElementConfig`, has a `_elementConfig_eventSpec` field that can be modified using `addEventSpecFlags`. It takes a `Proxy` that specifies the `DomSpace`, an event name, and a callback which takes the event result and returns an event flag, which can enable behavior like `preventDefault` and `stopPropagation`.
6+
7+The type signature on `def` is needed because the fields of the `ElementConfig` can change the type of the `ElementConfig`. GHC can probably figure out the type of the resulting `ElementConfig`, but it doesn't know what the type of `def` was before the modifications, since it never gets used with that configuration.
8+
9+For example:
10+
11+```haskell
12+{-# LANGUAGE OverloadedStrings #-}
13+{-# LANGUAGE ScopedTypeVariables #-}
14+
15+import Control.Lens ((&), (%~), (.~))
16+import Data.Proxy
17+import Reflex.Dom
18+
19+main :: IO ()
20+main = mainWidget $ do
21+ (click, ()) <- linkPreventDefault $ text "reflex-frp"
22+ display =<< count click
23+
24+linkPreventDefault :: forall t m a. DomBuilder t m => m a -> m (Event t (), a)
25+linkPreventDefault c = do
26+ let cfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
27+ & elementConfig_initialAttributes .~ ("href" =: "https://reflex-frp.org")
28+ & elementConfig_eventSpec %~ addEventSpecFlags (Proxy :: Proxy (DomBuilderSpace m)) Click (const preventDefault)
29+ (link, a) <- element "a" cfg c
30+ return (domEvent Click link, a)
31+```
LICENSE+1−1
@@ -1,4 +1,4 @@
1−Copyright (c) 2015, Obsidian Systems LLC
1+Copyright (c) 2020, Obsidian Systems LLC
22All rights reserved.
33
44Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Quickref.md+29−77
@@ -23,41 +23,41 @@ Widgets may return any type (this is 'a' in many of the functions below). Often
2323```haskell
2424-- Simplest form. Create a widget of given type containing the given child.
2525-- Return whatever the child returns.
26−[W] el :: String -> m a -> m a
26+[W] el :: Text -> m a -> m a
2727
2828-- This version returns the 'El' as well.
29−[W] el' :: String -> m a -> m (El, a)
29+[W] el' :: Text -> m a -> m (El, a)
3030
31−-- These two additionally apply attributes to the element, such as ("class" =: "blah")
32−[W] elAttr :: String -> Map String String -> m a -> m a
33−[W] elAttr' :: String -> Map String String -> m a -> m (El, a)
31+-- These two additionally apply attributes to the element, such as ("class" =: "blah"). (=:) is 'Map.singleton'
32+[W] elAttr :: Text -> Map Text Text -> m a -> m a
33+[W] elAttr' :: Text -> Map Text Text -> m a -> m (El, a)
3434
3535-- As above, but now the attribute map is Dynamic
36−[W] elDynAttr :: String -> Dynamic (Map String String) -> m a -> m a
37−[W] elDynAttr' :: String -> Dynamic (Map String String) -> m a -> m (El, a)
36+[W] elDynAttr :: Text -> Dynamic (Map Text Text) -> m a -> m a
37+[W] elDynAttr' :: Text -> Dynamic (Map Text Text) -> m a -> m (El, a)
38+
39+-- As above, but with an optional XML namespace for the tag. Note that this does *not* set the 'xmlns' attribute. See https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
40+[W] elDynAttrNS' :: Maybe Text -> Text -> Dynamic (Map Text Text) -> m a -> m (El, a)
3841
3942-- Shortcut for elAttr when you only want to set the "class" attribute.
40−[W] elClass :: String -> String -> m a -> m a
43+[W] elClass :: Text -> Text -> m a -> m a
4144
4245-- Even shorter-cut for above when element type is "div". Create a div of given class.
43−[W] divClass :: String -> m a -> m a
44−
45−-- Create a widget of given type with arbitrary, Dymamic HTML inside.
46−[W] elDynHtml' :: String -> Dynamic String -> m El
47−[W] elDynHtmlAttr' :: String -> Map String String -> Dynamic String -> m El
46+[W] divClass :: Text -> m a -> m a
4847
49−-- Shortcut for elDynHtml' where the type is "div" and you don't need the 'El'.
50−[W] dynHtml :: Dynamic String -> m ()
48+-- Create a widget of given type with arbitrary, Dynamic HTML inside.
49+[W] elDynHtml' :: Text -> Dynamic Text -> m El
50+[W] elDynHtmlAttr' :: Text -> Map Text Text -> Dynamic Text -> m El
5151
5252-- Create a static text element
53−[W] text :: String -> m ()
53+[W] text :: Text -> m ()
5454
5555-- Create a dynamic text element
56−[W] dynText :: Dynamic String -> m ()
56+[W] dynText :: Dynamic Text -> m ()
5757[W] display :: Show a => Dynamic a -> m ()
5858
5959-- Create a "button" element with given label, return onClick Event
60−[W] button :: String -> m (Event ())
60+[W] button :: Text -> m (Event ())
6161
6262-- Empty widget
6363[W] blank :: m ()
@@ -75,32 +75,10 @@ Note the "list" functions do not imply particular HTML tags (ul, li, etc), thoug
7575
7676-- Same as dyn, but takes initial value and an update Event instead of a Dynamic.
7777[W] widgetHold :: m a -> Event (m a) -> m (Dynamic a)
78−
79−-- Turn a Dynamic key/value map into a set of dynamically-changing widgets.
80−[W] listWithKey :: Ord k =>
81− Dynamic (Map k v) -> (k -> Dynamic v -> m a ) -> m (Dynamic (Map k a))
82−
83−-- Same as above where the widget constructor doesn't care about the key.
84−[W] list :: Ord k =>
85− Dynamic (Map k v) -> ( Dynamic v -> m a ) -> m (Dynamic (Map k a))
86−
87−-- Even simpler version where there are no keys and we just use a list.
88−[W] simpleList ::
89− Dynamic [v] -> ( Dynamic v -> m a ) -> m (Dynamic [a])
90−
91−-- Like listWithKey specialized for widgets returning (Event a).
92−[W] listViewWithKey :: Ord k =>
93− Dynamic (Map k v) -> (k -> Dynamic v -> m (Event a)) -> m (Event (Map k a))
94−
95−-- Create a dynamically-changing set of widgets, one of which is selected at any time.
96−[W] selectViewListWithKey_ :: Ord k => Dynamic k ->
97− Dynamic (Map k v) -> (k -> Dynamic v -> Dynamic Bool -> m (Event a)) -> m (Event k)
98−
99−-- Same as listWithKey, but takes initial values and an updates Event instead of a Dynamic.
100−[W] listWithKey' :: Ord k =>
101− Map k v -> Event (Map k (Maybe v)) -> (k -> v -> Event v -> m a) -> m (Dynamic (Map k a))
10278```
10379
80+Also see the "Collection management functions" section in the `reflex` Quick Reference.
81+
10482### Utility widgets
10583
10684These are useful widgets that are implemented (or could be implemented) in terms of the low-level widgets above.
@@ -121,13 +99,13 @@ Some of these widget builders take a configuration record and return a record co
12199
122100-- Dropdown with Dynamic options. First argument is initial state.
123101[W] dropdown :: (Ord k, Show k, Read k) =>
124− k -> Dynamic (Map k String) -> DropdownConfig k -> m (Dropdown k)
102+ k -> Dynamic (Map k Text) -> DropdownConfig k -> m (Dropdown k)
125103
126104-- Table with static columns and dynamic rows.
127105[W] tableDynAttr :: ... -- See Reflex.Dom.Widget.Basic
128106
129107-- Tabbed view that shows only one of its child widgets at a time.
130−[W] tabDisplay :: (Show k, Ord k) => String -> String -> Map k (String, m ()) -> m ()
108+[W] tabDisplay :: (Show k, Ord k) => Text -> Text -> Map k (Text, m ()) -> m ()
131109
132110-- Widget to efficiently display long scrolling lists.
133111[W] virtualListWithSelection :: ... -- See Reflex.Dom.Widget.Lazy
@@ -135,27 +113,12 @@ Some of these widget builders take a configuration record and return a record co
135113
136114## Connecting to the real world (I/O)
137115
138−### Connecting to DOM events
139−
140116```haskell
141117-- Extract the specified Event from an 'El'. See Reflex.Dom.Widget.Basic
142118[ ] domEvent :: EventName en -> El -> Event (EventResultType en)
143119```
144120
145−### Performing arbitrary I/O in response to Events
146−
147−```haskell
148−-- Run side-effecting actions in Event when it occurs; returned Event contains
149−-- results. Side effects run in (WidgetHost m) monad, which includes [S] and [H]
150−-- and can also do I/O via liftIO
151−[W] performEvent :: Event ( WidgetHost m a) -> m (Event a)
152−
153−-- Just run side-effects; no return Event
154−[W] performEvent_ :: Event ( WidgetHost m ()) -> m ()
155−
156−-- Actions run asynchronously; actions are given a callback to send return values
157−[W] performEventAsync :: Event ((a -> IO ()) -> WidgetHost m ()) -> m (Event a)
158−```
121+Also see the "Connection to the real world" and "Time" sections in the `reflex` Quick Reference.
159122
160123### XMLHttpRequest
161124
@@ -163,29 +126,19 @@ Convenience functions for XMLHttpRequest. see Reflex.Dom.Xhr
163126
164127```haskell
165128-- Given method, URL, and config record (with default instance), construct a request.
166−[ ] xhrRequest :: String -> String -> XhrRequestConfig -> XhrRequest
129+[ ] xhrRequest :: Text -> Text -> XhrRequestConfig a -> XhrRequest a
167130
168131-- Given Event of requests, issue them and produce Event of responses.
169−[W] performRequestAsync :: Event XhrRequest -> m (Event XhrResponse)
132+[W] performRequestAsync :: Event (XhrRequest a) -> m (Event XhrResponse)
170133
171134-- Issue a collection of requests, wait for them ALL to complete, return collected results.
172−[W] performRequestsAsync :: Traversable f => Event (f XhrRequest) -> m (Event (f XhrResponse))
135+[W] performRequestsAsync :: Traversable f => Event (f (XhrRequest a)) -> m (Event (f XhrResponse))
173136
174137-- Convenience function to decode JSON-encoded responses.
175138[ ] decodeXhrResponse :: FromJSON a => XhrResponse -> Maybe a
176139
177140-- Simplified interface to "GET" URLs and return decoded results.
178−[W] getAndDecode :: FromJSON a => Event String -> m (Event (Maybe a))
179−```
180−
181−### Time
182−
183−```haskell
184−-- Create Event at given interval with given basis time.
185−[W] tickLossy :: NominalDiffTime -> UTCTime -> m (Event t TickInfo)
186−
187−-- Delay an Event's occurrences by a given amount in seconds.
188−[W] delay :: NominalDiffTime -> Event t a -> m (Event t a)
141+[W] getAndDecode :: FromJSON a => Event Text -> m (Event (Maybe a))
189142```
190143
191144## Startup
@@ -201,7 +154,6 @@ Convenience functions for XMLHttpRequest. see Reflex.Dom.Xhr
201154[I] mainWidgetWithCss ::
202155 ByteString ->
203156 Widget Spider (Gui Spider (WithWebView SpiderHost) (HostFrame Spider)) () -> IO ()
204−
205−-- One-shot Event that is triggered once all initial widgets are built
206−[W] getPostBuild :: m (Event ())
207157```
158+
159+Also see the corresponding section in the `reflex` Quick Reference.
README.md+15−9
@@ -1,17 +1,23 @@
1−## Reflex-DOM
2−### A Framework for Functional Reactive Web Apps in Haskell
1+## [Reflex-DOM](https://reflex-frp.org)
32
4−Reflex-DOM is a framework for building web applications in Haskell, based on the [Functional Reactive Programming](https://wiki.haskell.org/Functional_Reactive_Programming) library [Reflex](https://github.com/reflex-frp/reflex).
3+[![Haskell](https://img.shields.io/badge/language-Haskell-orange.svg)](https://haskell.org) [![Hackage](https://img.shields.io/hackage/v/reflex-dom.svg)](https://hackage.haskell.org/package/reflex-dom) [![Hackage CI](https://matrix.hackage.haskell.org/api/v2/packages/reflex-dom/badge)](https://matrix.hackage.haskell.org/#/package/reflex-dom) [![BSD3 License](https://img.shields.io/badge/license-BSD3-blue.svg)](https://github.com/reflex-frp/reflex-dom/blob/master/LICENSE)
54
6−Comprehensive documentation is still a work in progress, but a [demo](https://github.com/reflex-frp/reflex-platform) is available and an introductory talk is available at [Part 1](https://www.youtube.com/watch?v=mYvkcskJbc4) / [Part 2](https://www.youtube.com/watch?v=3qfc9XFVo2c) ([Slides](https://obsidian.systems/reflex-nyhug/)).
5+Web applications without callbacks or side-effects. Reflex-DOM brings the power of [Functional Reactive Programming (FRP)](https://wiki.haskell.org/Functional_Reactive_Programming) to the web. Build [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) and other [Document Object Model (DOM)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) data with a pure functional interface.
76
8−A summary of Reflex-DOM functions is available in the [quick reference](Quickref.md).
7+Reflex-DOM is a framework for building web applications in [Haskell](https://www.haskell.org/), based on the [Functional Reactive Programming](https://wiki.haskell.org/Functional_Reactive_Programming) library [Reflex](https://github.com/reflex-frp/reflex).
8+
9+**Visit https://reflex-frp.org/ for more information, tutorials, documentation and [examples](https://examples.reflex-frp.org/).**
910
1011### Additional resources
11−[Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
1212
13−[/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
13+* [Official Website](https://reflex-frp.org/)
14+* [Quick Reference](Quickref.md)
15+* [Obelisk](https://github.com/obsidiansystems/obelisk#obelisk): A framework built on Reflex and Reflex-DOM for functional reactive web and mobile applications, with batteries included.
16+* [Get started with Reflex](https://github.com/reflex-frp/reflex-platform)
17+* [/r/reflexfrp](https://www.reddit.com/r/reflexfrp)
18+* [irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
1419
15−[hackage](https://hackage.haskell.org/package/reflex)
20+### Hacking
1621
17−[irc.freenode.net #reflex-frp](http://webchat.freenode.net?channels=%23reflex-frp&uio=d4)
22+Use the `./scripts/hack-on haskell-overlays/reflex-packages/dep/reflex-dom` script in [Reflex Platform](https://github.com/reflex-frp/reflex-platform) to checkout the source code of `reflex-dom` locally in `./dep/reflex-dom` directory.
23+Then do modifications to the source in place, and use the `./try-reflex` or `./scripts/work-on` scripts to create the shell to test your changes.
cabal.projectnew file+10
@@ -0,0 +1,10 @@
1+packages:
2+ reflex-dom-core/
3+ reflex-dom/
4+ chrome-test-utils/
5+ reflex-dom-test-selenium/
6+
7+source-repository-package
8+ type: git
9+ location: https://github.com/dfordivam/hspec-webdriver-clone
10+ tag: 0d748b7bb7cd74dce0a55a1ec86b01dbb8a71cd8
cabal.project-nogtknew file+14
@@ -0,0 +1,14 @@
1+packages:
2+ reflex-dom-core/
3+ reflex-dom/
4+
5+package reflex-dom-core
6+ flags: -hydration-tests -gc-tests
7+
8+package reflex-dom
9+ flags: +use-warp -webkit2gtk
10+
11+source-repository-package
12+ type: git
13+ location: https://github.com/dfordivam/hspec-webdriver-clone
14+ tag: 0d748b7bb7cd74dce0a55a1ec86b01dbb8a71cd8
chrome-test-utils/LICENSEnew file+12
@@ -0,0 +1,12 @@
1+Copyright (c) 2020, Obsidian Systems LLC
2+All rights reserved.
3+
4+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5+
6+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7+
8+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9+
10+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11+
12+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
chrome-test-utils/chrome-test-utils.cabalnew file+30
@@ -0,0 +1,30 @@
1+Name: chrome-test-utils
2+Version: 0.5
3+Synopsis: Utilities to write headless Chromium tests
4+License: BSD3
5+License-file: LICENSE
6+Author: Obsidian Systems LLC
7+Maintainer: maintainer@obsidian.systems
8+Stability: Experimental
9+Build-type: Simple
10+Cabal-version: >=1.9.2
11+
12+library
13+ hs-source-dirs: src
14+ ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans
15+ build-depends: base
16+ , linux-namespaces
17+ , process
18+ , temporary
19+ , text
20+ , unix
21+ exposed-modules:
22+ Test.Util.UnshareNetwork
23+ Test.Util.ChromeFlags
24+ if !os(linux) || !arch(x86_64)
25+ buildable: False
26+
27+source-repository head
28+ type: git
29+ location: https://github.com/reflex-frp/reflex-dom
30+ subdir: chrome-test-utils
chrome-test-utils/src/Test/Util/ChromeFlags.hsnew file+17
@@ -0,0 +1,17 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Test.Util.ChromeFlags where
3+
4+import Data.Semigroup
5+import Data.Text
6+import System.IO.Temp
7+
8+withSandboxedChromeFlags :: Bool -> ([Text] -> IO a) -> IO a
9+withSandboxedChromeFlags headless action =
10+ withSystemTempDirectory "reflex-dom-core_test" $ \tmp ->
11+ action
12+ [ if headless then "--headless" else "--auto-open-devtools-for-tabs"
13+ , "--disable-gpu"
14+ , "--no-sandbox"
15+ , "--remote-debugging-port=9222"
16+ , "--user-data-dir=" <> pack tmp
17+ ]
chrome-test-utils/src/Test/Util/UnshareNetwork.hsnew file+12
@@ -0,0 +1,12 @@
1+module Test.Util.UnshareNetwork where
2+
3+import System.Linux.Namespaces
4+import System.Posix
5+import System.Process
6+
7+unshareNetwork :: IO ()
8+unshareNetwork = do
9+ uid <- getEffectiveUserID
10+ unshare [User, Network]
11+ writeUserMappings Nothing [UserMapping 0 uid 1]
12+ callCommand "ip link set lo up ; ip addr"
default.nixdeleted−50
@@ -1,50 +0,0 @@
1−{ mkDerivation, pkgs, dependent-map, ghcjs-dom, lens
2−, mtl, ref-tf, reflex, text, these
3−, transformers, data-default, semigroups, blaze-builder, aeson
4−, ghc, webkitgtk3-javascriptcore, exception-transformers
5−, webkitgtk24x, dependent-sum-template, bifunctors, bimap
6−, raw-strings-qq, zenc, random, monad-control, keycode, hlint
7−, unbounded-delays
8−}:
9−
10−mkDerivation {
11− pname = "reflex-dom";
12− version = "0.3";
13− src = builtins.filterSource (path: type: baseNameOf path != ".git") ./.;
14− buildDepends = [
15− aeson
16− bifunctors
17− bimap
18− blaze-builder
19− data-default
20− dependent-map
21− dependent-sum-template
22− exception-transformers
23− ghcjs-dom
24− keycode
25− lens
26− monad-control
27− mtl
28− random
29− ref-tf
30− reflex
31− semigroups
32− text
33− these
34− transformers
35− zenc
36− unbounded-delays
37− ] ++ (if ghc.isGhcjs or false then [] else [
38− raw-strings-qq
39− webkitgtk3-javascriptcore
40− ]);
41− testDepends = if ghc.isGhcjs or false then [] else [
42− hlint
43− ];
44− pkgconfigDepends = if ghc.isGhcjs or false then [] else [
45− raw-strings-qq
46− webkitgtk24x
47− webkitgtk3-javascriptcore
48− ];
49− license = null;
50−}
dep/reflex-platform/default.nixnew file+2
@@ -0,0 +1,2 @@
1+# DO NOT HAND-EDIT THIS FILE
2+import (import ./thunk.nix)
dep/reflex-platform/github.jsonnew file+8
@@ -0,0 +1,8 @@
1+{
2+ "owner": "reflex-frp",
3+ "repo": "reflex-platform",
4+ "branch": "aa-bump-some",
5+ "private": false,
6+ "rev": "fd5acecb50474f795734db9fb924cc3b2fd2b508",
7+ "sha256": "0wsdd67g42klsf9n3pxb3pndjdz36nzf8gp7pfm8j6nyyy2qribk"
8+}
dep/reflex-platform/thunk.nixnew file+9
@@ -0,0 +1,9 @@
1+# DO NOT HAND-EDIT THIS FILE
2+let fetch = { private ? false, fetchSubmodules ? false, owner, repo, rev, sha256, ... }:
3+ if !fetchSubmodules && !private then builtins.fetchTarball {
4+ url = "https://github.com/${owner}/${repo}/archive/${rev}.tar.gz"; inherit sha256;
5+ } else (import <nixpkgs> {}).fetchFromGitHub {
6+ inherit owner repo rev sha256 fetchSubmodules private;
7+ };
8+ json = builtins.fromJSON (builtins.readFile ./github.json);
9+in fetch json
reflex-dom-core/ChangeLog.mdnew file+94
@@ -0,0 +1,94 @@
1+# Revision history for reflex-dom-core
2+
3+## 0.6.2.1
4+
5+* Fix hlint complaints with newer GHC.
6+
7+## 0.6.2.0
8+
9+* ([#400](https://github.com/reflex-frp/reflex-dom/pull/400/files)) Set value of input elements in static renderer
10+
11+## 0.6.1.0
12+
13+* Bump version bounds
14+* Update for new dependent-map and dependent-sum version (after the "some" package split)
15+* Add `MonadAtomicRef` instance for `UnrunnableT`
16+* Fix ([#467](https://github.com/reflex-frp/reflex-dom/issues/467)): Prevent multiple firings of XHR response event
17+* Updates for GHC 8.10
18+* Move `HasSetValue` from Reflex.Dom.Widget.Input to Reflex.Dom.Builder.Class and add an instance for `TextAreaElementConfig`
19+* Add `now` to the `MonadHold` instance for `UnrunnableT`
20+
21+
22+## 0.6.0.0
23+
24+* ([#375](https://github.com/reflex-frp/reflex-dom/pull/375)) **(Breaking change)** Expose resized dimensions from `resizeDetector`, `resizeDetectorWithStyle`, and `resizeDetectorWithAttrs` from `Reflex.Dom.Widget.Resize`.
25+* ([#374](https://github.com/reflex-frp/reflex-dom/pull/374)) **(Breaking change)** Provide text clipboard data as value of `Paste` event.
26+* ([#348](https://github.com/reflex-frp/reflex-dom/pull/348)) **(Breaking change)** Make XHR response headers case insensitive by changing `_xhrResponse_headers :: Map Text Text` to `_xhrResponse_headers :: Map (CI Text) Text`.
27+* ([#225](https://github.com/reflex-frp/reflex-dom/pull/225)) **(Breaking change)** Add a functional dependency to `HasDomEvent`.
28+* ([#342](https://github.com/reflex-frp/reflex-dom/issues/342)) **(Breaking change)** The mouse wheel event is now a `WheelEventResult` rather than `()`. This provides information about the wheel's motion beyond the fact that it merely moved.
29+* ([#353](https://github.com/reflex-frp/reflex-dom/pull/353)) Support GHC 8.8.
30+* ([#358](https://github.com/reflex-frp/reflex-dom/pull/358)) Fix attribute support for explicitly namespaced elements.
31+* ([#363](https://github.com/reflex-frp/reflex-dom/pull/363)) Remove deprecation warnings for the following widgets in
32+ `Reflex.Dom.Widget.Basic`:
33+ * `Link`
34+ * `button`
35+ * `dtdd`
36+ * `linkClass`
37+ * `link`
38+ * `tabDisplay`
39+ * `tableDynAttr`
40+* ([#361](https://github.com/reflex-frp/reflex-dom/pull/361)) Fix bug in hydration causing the JavaScript to crash when dealing with unexpected HTML.
41+* ([#310](https://github.com/reflex-frp/reflex-dom/issues/310)) Fix the static rendering of which dropdown value is selected.
42+* ([#364](https://github.com/reflex-frp/reflex-dom/pull/364)) Export attributes used for controlling hydration at the element level:
43+ * "data-ssr" is now available as `Reflex.Dom.Builder.Immediate.hydratableAttribute`.
44+ * "data-hydration-skip" is now available as `Reflex.Dom.Builder.Immediate.skipHydrationAttribute`.
45+* ([#366](https://github.com/reflex-frp/reflex-dom/pull/366)) Bump bounds for `reflex` to include 0.7.
46+
47+## 0.5.3
48+
49+* Deprecate a number of old inflexible widget helpers in `Reflex.Dom.Widget.Basic`:
50+ * `Link`
51+ * `button`
52+ * `dtdd`
53+ * `linkClass`
54+ * `link`
55+ * `tabDisplay`
56+ * `tableDynAttr`
57+
58+ And in `Reflex.Dom.Widget.Input`:
59+ * `TextInput`
60+ * `TextAreaConfig`
61+ * `CheckboxConfig`
62+ * `FileInput`
63+* Add `< 0.7` upper bound for `reflex`.
64+
65+## 0.5.2
66+
67+* Update to use new dependent-sum/map packages and drop dependency on `*Tag` classes (e.g., `ShowTag`).
68+
69+* Update version bounds of base, containers, and stm
70+
71+* Update to use the newly split `these`/`semialign` packages. To use the pre-split `these` package, set the `split-these` flag to false.
72+
73+* Reintroduce "data-ssr": elements without this attribute are skipped during
74+ hydration.
75+
76+* Fix an issue in the hydration tests that prevented the test from finding the chromium executable
77+
78+* Relax constraints on `dyn` and `widgetHold` to match the ones in `networkView` and `networkHold` respectively
79+
80+* Fix prerender for RequesterT so that it doesn't accidentally discard a request that is made at the same moment as getPostBuild's Event fires
81+
82+## 0.5.1
83+
84+* Added support for marking elements with a "data-skip-hydration" attribute, which will cause hydration to ignore and skip over them.
85+
86+* Removed "data-ssr" attributes from statically rendered output.
87+
88+## 0.5
89+
90+* Add HydrationDomBuilderT to support hydration of statically rendered DOM nodes. See the note at the top of Reflex.Dom.Builder.Immediate.
91+
92+* As a result of the hydration changes, the Prerender class has changed, the type of `prerender` has changed and it is now a class method.
93+
94+* Add the Reflex.Dom.Xhr.FormData module to make posting formdata over xhr more convenient.
reflex-dom-core/LICENSEnew file+12
@@ -0,0 +1,12 @@
1+Copyright (c) 2020, Obsidian Systems LLC
2+All rights reserved.
3+
4+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5+
6+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7+
8+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9+
10+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11+
12+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Setup.hs → reflex-dom-core/Setup.hsrenamed

The content is the same.

reflex-dom-core/reflex-dom-core.cabalnew file+259
@@ -0,0 +1,259 @@
1+cabal-version: 1.24
2+Name: reflex-dom-core
3+Version: 0.6.2.1
4+Synopsis: Functional Reactive Web Apps with Reflex
5+Description:
6+ Web applications without callbacks or side-effects.
7+ Reflex-DOM brings the power of functional reactive programming (FRP) to the web.
8+ Build HTML and other Document Object Model (DOM) data with a pure functional interface.
9+ .
10+ Reflex-DOM is a Functional Reactive web framework based on the Reflex FRP engine: <https://reflex-frp.org/>.
11+ .
12+ The @reflex-dom@ package is a small wrapper around the @reflex-dom-core@ package. It pulls in the
13+ correct set of dependencies for each target platform (GHCJS, WebKitGTK, WASM, mobile, etc.).
14+ Libraries should depend on @reflex-dom-core@ and executables will usually depend on @reflex-dom@.
15+ All of @reflex-dom-core@'s modules are re-exported by @reflex-dom@.
16+License: BSD3
17+License-file: LICENSE
18+Author: Ryan Trinkle
19+Maintainer: ryan.trinkle@gmail.com
20+Stability: Experimental
21+Category: FRP, Web, GUI, HTML, Javascript, Reactive, Reactivity, User Interfaces, User-interface
22+Build-type: Simple
23+-- Deal with https://github.com/haskell/cabal/issues/2544 / https://github.com/haskell/cabal/issues/367
24+extra-source-files: src-ghc/Foreign/JavaScript/Internal/Utils.hs
25+ src-ghcjs/Foreign/JavaScript/Internal/Utils.hs
26+ src/Reflex/Dom/Xhr/Foreign.hs
27+ src/Reflex/Dom/WebSocket/Foreign.hs
28+ src/Reflex/Dom/Xhr/ResponseType.hs
29+ src/Reflex/Dom/Xhr/Exception.hs
30+ ChangeLog.md
31+
32+flag use-template-haskell
33+ description: Use template haskell to generate lenses
34+ default: True
35+ manual: True
36+
37+flag use-reflex-optimizer
38+ description: Use the GHC plugin Reflex.Optimizer on some of the modules in the package. This is still experimental.
39+ default: False
40+ manual: True
41+
42+flag expose-all-unfoldings
43+ description: Build the library with -fexpose-all-unfoldings which can help client code specialize better
44+ default: False
45+ manual: True
46+
47+flag profile-reflex
48+ description: Add a layer of profiling to all Reflex events in the system
49+ default: False
50+ manual: True
51+
52+flag split-these
53+ description: Use split these/semialign packages
54+ manual: False
55+ default: True
56+
57+flag hydration-tests
58+ description: Whether to run the hydration tests (currently only available on linux)
59+ default: True
60+ manual: True
61+
62+flag gc-tests
63+ description: Whether to run the gc tests (currently only available on linux)
64+ default: True
65+ manual: True
66+
67+library
68+ hs-source-dirs: src
69+ build-depends:
70+ aeson >= 0.8 && < 1.6,
71+ base >= 4.7 && < 4.15,
72+ bifunctors >= 4.2 && < 6,
73+ bimap >= 0.3 && < 0.5,
74+ blaze-builder >= 0.4.1 && < 0.5,
75+ bytestring == 0.10.*,
76+ case-insensitive < 1.3,
77+ containers >= 0.6 && < 0.7,
78+ constraints >= 0.9 && < 0.13,
79+ contravariant >= 1.4 && < 1.6,
80+ data-default >= 0.5 && < 0.8,
81+ dependent-map >= 0.3 && < 0.5,
82+ dependent-sum >= 0.6 && < 0.8,
83+ dependent-sum-template >= 0.1 && < 0.2,
84+ directory >= 1.2 && < 1.4,
85+ exception-transformers == 0.4.*,
86+ ghcjs-dom >= 0.9.1.0 && < 0.10,
87+ jsaddle >= 0.9.0.0 && < 0.10,
88+ -- keycode-0.2 has a bug on firefox
89+ keycode >= 0.2.1 && < 0.3,
90+ lens >= 4.7 && < 5,
91+ monad-control >= 1.0.1 && < 1.1,
92+ mtl >= 2.1 && < 2.3,
93+ primitive >= 0.5 && < 0.8,
94+ random >= 1.1 && < 1.2,
95+ ref-tf == 0.4.*,
96+ reflex >= 0.8 && < 0.9,
97+ semigroups >= 0.16 && < 0.20,
98+ stm >= 2.4 && < 2.6,
99+ text == 1.2.*,
100+ transformers >= 0.3 && < 0.6,
101+ network-uri >= 2.6.1 && < 2.7,
102+ zenc == 0.1.*
103+
104+ if impl(ghcjs)
105+ hs-source-dirs: src-ghcjs
106+ build-depends:
107+ ghcjs-base,
108+ hashable >= 1.2 && < 1.4
109+ else
110+ hs-source-dirs: src-ghc
111+ if !os(windows)
112+ build-depends: unix == 2.7.*
113+
114+ if flag(split-these)
115+ build-depends:
116+ semialign >= 1 && < 1.2,
117+ these >= 1 && < 1.2
118+ else
119+ build-depends:
120+ these >= 0.4 && < 0.9
121+
122+ exposed-modules:
123+ Foreign.JavaScript.TH
124+ Foreign.JavaScript.Orphans
125+ Foreign.JavaScript.Utils
126+ Reflex.Dom.Builder.Class
127+ Reflex.Dom.Builder.Class.Events
128+ Reflex.Dom.Builder.Immediate
129+ Reflex.Dom.Builder.InputDisabled
130+ Reflex.Dom.Builder.Hydratable
131+ Reflex.Dom.Builder.Static
132+ Reflex.Dom.Class
133+ Reflex.Dom.Core
134+ Reflex.Dom.Location
135+ Reflex.Dom.Main
136+ Reflex.Dom.Modals.Class
137+ Reflex.Dom.Old
138+ Reflex.Dom.Prerender
139+ Reflex.Dom.Time
140+ Reflex.Dom.WebSocket
141+ Reflex.Dom.WebSocket.Query
142+ Reflex.Dom.Widget
143+ Reflex.Dom.Widget.Basic
144+ Reflex.Dom.Widget.Input
145+ Reflex.Dom.Widget.Lazy
146+ Reflex.Dom.Widget.Resize
147+ Reflex.Dom.Xhr
148+ Reflex.Dom.Xhr.FormData
149+ other-modules:
150+ Foreign.JavaScript.Internal.Utils
151+ Reflex.Dom.WebSocket.Foreign
152+ Reflex.Dom.Xhr.Foreign
153+ Reflex.Dom.Xhr.ResponseType
154+ Reflex.Dom.Xhr.Exception
155+
156+ default-language: Haskell98
157+ ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans -fspecialise-aggressively
158+ ghc-prof-options: -fprof-auto
159+
160+ if flag(expose-all-unfoldings)
161+ ghc-options: -fexpose-all-unfoldings
162+
163+ if flag(use-reflex-optimizer)
164+ ghc-options: -fplugin=Reflex.Optimizer
165+
166+ if flag(profile-reflex)
167+ cpp-options: -DPROFILE_REFLEX
168+
169+ if flag(use-template-haskell)
170+ build-depends:
171+ dependent-sum-template >= 0.1 && < 0.2,
172+ template-haskell >= 2.12.0 && < 2.17
173+ other-extensions: TemplateHaskell
174+ cpp-options: -DUSE_TEMPLATE_HASKELL
175+ other-modules:
176+ Reflex.Dom.Builder.Class.TH
177+
178+test-suite hlint
179+ build-depends:
180+ base,
181+ hlint >= 2.0 && < 4.0
182+ hs-source-dirs: test
183+ main-is: hlint.hs
184+ type: exitcode-stdio-1.0
185+ default-language: Haskell98
186+
187+test-suite hydration
188+ build-depends: base
189+ , aeson
190+ , async
191+ , bytestring
192+ , chrome-test-utils
193+ , constraints
194+ , constraints-extras
195+ , containers
196+ , dependent-map
197+ , dependent-sum
198+ , dependent-sum-template
199+ , directory
200+ , exceptions
201+ , filepath
202+ , ghcjs-dom
203+ , hspec
204+ , hspec-core
205+ , hspec-webdriver
206+ , http-types
207+ , HUnit
208+ , jsaddle
209+ , jsaddle-warp
210+ , lens
211+ , lifted-base
212+ , network
213+ , random
214+ , ref-tf
215+ , reflex
216+ , reflex-dom-core
217+ , process
218+ , silently
219+ , temporary
220+ , text
221+ , wai
222+ , wai-websockets
223+ , warp
224+ , webdriver
225+ , websockets
226+ , which
227+ hs-source-dirs: test
228+ ghc-options: -rtsopts -with-rtsopts=-T -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans
229+ ghc-prof-options: -fprof-auto -optP-DPROFILING
230+ main-is: hydration.hs
231+ type: exitcode-stdio-1.0
232+ default-language: Haskell98
233+ if !os(linux) || !arch(x86_64) || flag(profile-reflex) || !flag(hydration-tests)
234+ buildable: False
235+
236+-- broken test on base 4.11 & ghc 8.4.3
237+-- needs to be updated for changes in GHC.Stats
238+test-suite gc
239+ build-depends: base
240+ , chrome-test-utils
241+ , jsaddle
242+ , jsaddle-warp
243+ , process
244+ , reflex
245+ , reflex-dom-core
246+ , text
247+ hs-source-dirs: test
248+ ghc-options: -rtsopts -with-rtsopts=-T -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans
249+ ghc-prof-options: -fprof-auto -optP-DPROFILING
250+ main-is: gc.hs
251+ type: exitcode-stdio-1.0
252+ default-language: Haskell98
253+ if !os(linux) || !arch(x86_64) || !flag(gc-tests)
254+ buildable: False
255+
256+source-repository head
257+ type: git
258+ location: https://github.com/reflex-frp/reflex-dom
259+ subdir: reflex-dom-core
reflex-dom-core/src-ghc/Foreign/JavaScript/Internal/Utils.hsnew file+17
@@ -0,0 +1,17 @@
1+module Foreign.JavaScript.Internal.Utils
2+ ( synchronously
3+ , freeRequestAnimationFrameCallback
4+ , js_dataView
5+ ) where
6+
7+import GHCJS.DOM.Types (Callback (..), JSM, JSVal, RequestAnimationFrameCallback (..))
8+import Language.Javascript.JSaddle.Object (freeFunction, jsg, new)
9+
10+synchronously :: JSM a -> JSM a
11+synchronously = id
12+
13+freeRequestAnimationFrameCallback :: RequestAnimationFrameCallback -> JSM ()
14+freeRequestAnimationFrameCallback (RequestAnimationFrameCallback (Callback cb)) = freeFunction cb
15+
16+js_dataView :: Int -> Int -> JSVal -> JSM JSVal
17+js_dataView off len ref = new (jsg "DataView") (ref, off, len)
reflex-dom-core/src-ghcjs/Foreign/JavaScript/Internal/Utils.hsnew file+18
@@ -0,0 +1,18 @@
1+{-# LANGUAGE ForeignFunctionInterface #-}
2+{-# LANGUAGE JavaScriptFFI #-}
3+
4+module Foreign.JavaScript.Internal.Utils
5+ ( synchronously
6+ , freeRequestAnimationFrameCallback
7+ , js_dataView
8+ ) where
9+
10+import GHCJS.Concurrent
11+import GHCJS.DOM.Types (JSM, JSVal, RequestAnimationFrameCallback (..))
12+import GHCJS.Foreign.Callback (releaseCallback)
13+
14+freeRequestAnimationFrameCallback :: RequestAnimationFrameCallback -> JSM ()
15+freeRequestAnimationFrameCallback (RequestAnimationFrameCallback cb) = releaseCallback cb
16+
17+foreign import javascript safe "new DataView($3,$1,$2)"
18+ js_dataView :: Int -> Int -> JSVal -> IO JSVal
reflex-dom-core/src/Foreign/JavaScript/Orphans.hsnew file+37
@@ -0,0 +1,37 @@
1+{-# OPTIONS_HADDOCK hide #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE UndecidableInstances #-}
5+
6+{-# OPTIONS_GHC -fno-warn-orphans #-}
7+module Foreign.JavaScript.Orphans where
8+
9+#ifndef ghcjs_HOST_OS
10+
11+import Control.Monad.Trans.Class (lift)
12+import GHCJS.DOM.Types (MonadJSM (..))
13+import Reflex.DynamicWriter.Base (DynamicWriterT)
14+import Reflex.EventWriter.Base (EventWriterT)
15+import Reflex.Host.Class (HostFrame, ReflexHost)
16+import Reflex.PerformEvent.Base (PerformEventT (..))
17+import Reflex.PostBuild.Base (PostBuildT)
18+import Reflex.Requester.Base (RequesterT)
19+import Reflex.TriggerEvent.Base
20+import Reflex.Query.Base (QueryT)
21+
22+instance MonadJSM m => MonadJSM (PostBuildT t m) where
23+ liftJSM' = lift . liftJSM'
24+instance (MonadJSM (HostFrame t), ReflexHost t) => MonadJSM (PerformEventT t m) where
25+ liftJSM' = PerformEventT . lift . liftJSM'
26+instance MonadJSM m => MonadJSM (DynamicWriterT t w m) where
27+ liftJSM' = lift . liftJSM'
28+instance MonadJSM m => MonadJSM (EventWriterT t w m) where
29+ liftJSM' = lift . liftJSM'
30+instance MonadJSM m => MonadJSM (RequesterT t request response m) where
31+ liftJSM' = lift . liftJSM'
32+instance MonadJSM m => MonadJSM (TriggerEventT t m) where
33+ liftJSM' = lift . liftJSM'
34+instance MonadJSM m => MonadJSM (QueryT t q m) where
35+ liftJSM' = lift . liftJSM'
36+
37+#endif
reflex-dom-core/src/Foreign/JavaScript/TH.hsnew file+581
@@ -0,0 +1,581 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE EmptyDataDecls #-}
4+{-# LANGUAGE ExistentialQuantification #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE FunctionalDependencies #-}
8+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9+{-# LANGUAGE RankNTypes #-}
10+{-# LANGUAGE StandaloneDeriving #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE UndecidableInstances #-}
13+#ifdef USE_TEMPLATE_HASKELL
14+{-# LANGUAGE TemplateHaskell #-}
15+#endif
16+#ifdef ghcjs_HOST_OS
17+{-# LANGUAGE ForeignFunctionInterface #-}
18+{-# LANGUAGE JavaScriptFFI #-}
19+#endif
20+module Foreign.JavaScript.TH ( module Foreign.JavaScript.TH
21+#ifdef USE_TEMPLATE_HASKELL
22+ , Safety (..)
23+#endif
24+ ) where
25+
26+import Foreign.JavaScript.Orphans ()
27+import Prelude hiding ((!!))
28+import Reflex.Class
29+import Reflex.Adjustable.Class
30+import Reflex.DynamicWriter.Base
31+import Reflex.EventWriter.Base
32+import Reflex.Host.Class
33+import Reflex.PerformEvent.Base
34+import Reflex.PerformEvent.Class
35+import Reflex.PostBuild.Base
36+import Reflex.Requester.Base
37+import Reflex.Query.Base (QueryT (..))
38+
39+#ifdef USE_TEMPLATE_HASKELL
40+import Language.Haskell.TH
41+#endif
42+
43+import GHCJS.DOM.Types (JSContextRef, Node (..), askJSM)
44+#ifdef ghcjs_HOST_OS
45+import qualified GHCJS.Buffer as JS
46+import GHCJS.DOM.Types (MonadJSM)
47+import qualified GHCJS.DOM.Types as JS
48+import qualified GHCJS.Foreign as JS
49+import qualified GHCJS.Foreign.Callback as JS
50+import qualified GHCJS.Foreign.Callback.Internal (Callback (..))
51+import qualified JavaScript.Array as JS
52+import qualified JavaScript.Array.Internal (SomeJSArray (..))
53+import qualified JavaScript.Object as JS
54+import qualified JavaScript.Object.Internal (Object (..))
55+import qualified JavaScript.TypedArray.ArrayBuffer as JSArrayBuffer
56+
57+import Data.Hashable
58+import Data.Word
59+import Foreign.C.Types
60+import Foreign.Ptr
61+import Text.Encoding.Z
62+#else
63+import Control.Lens.Operators ((^.))
64+import Data.Word (Word8)
65+import GHCJS.DOM.Types (JSVal, MonadJSM (..), liftJSM, runJSM, toJSString, toJSVal)
66+import Language.Javascript.JSaddle (Function (..), array, eval, freeFunction, function, js, js1, jss, valBool,
67+ valIsNull, valIsUndefined, valMakeNumber, valMakeString, valToBool,
68+ valToNumber, valToText, valUndefined, (!!))
69+#endif
70+
71+import Control.Concurrent
72+import Control.Monad
73+import Control.Monad.Exception
74+import Control.Monad.Fix
75+import Control.Monad.IO.Class
76+import Control.Monad.Primitive
77+import Control.Monad.Reader
78+import Control.Monad.Ref
79+import Control.Monad.State
80+import qualified Control.Monad.State.Strict as Strict
81+import Control.Monad.Trans.Control
82+import Data.ByteString (ByteString)
83+import qualified Data.ByteString as BS
84+import Data.Coerce (coerce)
85+import Data.Monoid
86+import Data.Text (Text)
87+import qualified Data.Text as T
88+
89+class Monad m => HasJSContext m where
90+ type JSContextPhantom m :: *
91+ askJSContext :: m (JSContextSingleton (JSContextPhantom m))
92+
93+type HasWebView = HasJSContext
94+-- Not sure if we should deprecate this {-# DEPRECATED HasWebView "Use HasJSContext" #-}
95+
96+instance HasJSContext m => HasJSContext (ReaderT r m) where
97+ type JSContextPhantom (ReaderT r m) = JSContextPhantom m
98+ askJSContext = lift askJSContext
99+
100+instance HasJSContext m => HasJSContext (StateT r m) where
101+ type JSContextPhantom (StateT r m) = JSContextPhantom m
102+ askJSContext = lift askJSContext
103+
104+instance HasJSContext m => HasJSContext (Strict.StateT r m) where
105+ type JSContextPhantom (Strict.StateT r m) = JSContextPhantom m
106+ askJSContext = lift askJSContext
107+
108+instance HasJSContext m => HasJSContext (PostBuildT t m) where
109+ type JSContextPhantom (PostBuildT t m) = JSContextPhantom m
110+ askJSContext = lift askJSContext
111+
112+instance (ReflexHost t, HasJSContext (HostFrame t)) => HasJSContext (PerformEventT t m) where
113+ type JSContextPhantom (PerformEventT t m) = JSContextPhantom (HostFrame t)
114+ askJSContext = PerformEventT $ lift askJSContext
115+
116+instance HasJSContext m => HasJSContext (EventWriterT t w m) where
117+ type JSContextPhantom (EventWriterT t w m) = JSContextPhantom m
118+ askJSContext = lift askJSContext
119+
120+instance HasJSContext m => HasJSContext (DynamicWriterT t w m) where
121+ type JSContextPhantom (DynamicWriterT t w m) = JSContextPhantom m
122+ askJSContext = lift askJSContext
123+
124+instance HasJSContext m => HasJSContext (RequesterT t request response m) where
125+ type JSContextPhantom (RequesterT t request response m) = JSContextPhantom m
126+ askJSContext = lift askJSContext
127+
128+instance HasJSContext m => HasJSContext (QueryT t q m) where
129+ type JSContextPhantom (QueryT t q m) = JSContextPhantom m
130+ askJSContext = QueryT askJSContext
131+
132+newtype WithJSContextSingleton x m a = WithJSContextSingleton { unWithJSContextSingleton :: ReaderT (JSContextSingleton x) m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadTrans, MonadException, MonadAsyncException)
133+
134+instance PrimMonad m => PrimMonad (WithJSContextSingleton x m) where
135+ type PrimState (WithJSContextSingleton x m) = PrimState m
136+ primitive = lift . primitive
137+
138+instance Adjustable t m => Adjustable t (WithJSContextSingleton x m) where
139+ runWithReplace a0 a' = WithJSContextSingleton $ runWithReplace (coerce a0) (coerceEvent a')
140+ traverseIntMapWithKeyWithAdjust f dm0 dm' = WithJSContextSingleton $ traverseIntMapWithKeyWithAdjust (\k v -> unWithJSContextSingleton $ f k v) (coerce dm0) (coerceEvent dm')
141+ traverseDMapWithKeyWithAdjust f dm0 dm' = WithJSContextSingleton $ traverseDMapWithKeyWithAdjust (\k v -> unWithJSContextSingleton $ f k v) (coerce dm0) (coerceEvent dm')
142+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = WithJSContextSingleton $ traverseDMapWithKeyWithAdjustWithMove (\k v -> unWithJSContextSingleton $ f k v) (coerce dm0) (coerceEvent dm')
143+
144+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (WithJSContextSingleton x m) where
145+ {-# INLINABLE newEventWithTrigger #-}
146+ newEventWithTrigger = lift . newEventWithTrigger
147+ {-# INLINABLE newFanEventWithTrigger #-}
148+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
149+
150+instance MonadSubscribeEvent t m => MonadSubscribeEvent t (WithJSContextSingleton x m) where
151+ {-# INLINABLE subscribeEvent #-}
152+ subscribeEvent = lift . subscribeEvent
153+
154+instance MonadReflexHost t m => MonadReflexHost t (WithJSContextSingleton x m) where
155+ type ReadPhase (WithJSContextSingleton x m) = ReadPhase m
156+ {-# INLINABLE fireEventsAndRead #-}
157+ fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
158+ {-# INLINABLE runHostFrame #-}
159+ runHostFrame = lift . runHostFrame
160+
161+instance MonadSample t m => MonadSample t (WithJSContextSingleton x m) where
162+ {-# INLINABLE sample #-}
163+ sample = lift . sample
164+
165+instance MonadHold t m => MonadHold t (WithJSContextSingleton x m) where
166+ {-# INLINABLE hold #-}
167+ hold v0 = lift . hold v0
168+ {-# INLINABLE holdDyn #-}
169+ holdDyn v0 = lift . holdDyn v0
170+ {-# INLINABLE holdIncremental #-}
171+ holdIncremental v0 = lift . holdIncremental v0
172+ {-# INLINABLE buildDynamic #-}
173+ buildDynamic a0 = lift . buildDynamic a0
174+ {-# INLINABLE headE #-}
175+ headE = lift . headE
176+
177+instance MonadTransControl (WithJSContextSingleton x) where
178+ type StT (WithJSContextSingleton x) a = StT (ReaderT (JSContextSingleton x)) a
179+ {-# INLINABLE liftWith #-}
180+ liftWith = defaultLiftWith WithJSContextSingleton unWithJSContextSingleton
181+ {-# INLINABLE restoreT #-}
182+ restoreT = defaultRestoreT WithJSContextSingleton
183+
184+instance PerformEvent t m => PerformEvent t (WithJSContextSingleton x m) where
185+ type Performable (WithJSContextSingleton x m) = WithJSContextSingleton x (Performable m) --TODO: Can we eliminate this wrapper?
186+ {-# INLINABLE performEvent_ #-}
187+ performEvent_ e = liftWith $ \run -> performEvent_ $ fmap run e
188+ {-# INLINABLE performEvent #-}
189+ performEvent e = liftWith $ \run -> performEvent $ fmap run e
190+
191+runWithJSContextSingleton :: WithJSContextSingleton x m a -> JSContextSingleton x -> m a
192+runWithJSContextSingleton = runReaderT . unWithJSContextSingleton
193+
194+instance (Monad m) => HasJSContext (WithJSContextSingleton x m) where
195+ type JSContextPhantom (WithJSContextSingleton x m) = x
196+ askJSContext = WithJSContextSingleton ask
197+
198+instance MonadRef m => MonadRef (WithJSContextSingleton x m) where
199+ type Ref (WithJSContextSingleton x m) = Ref m
200+ newRef = lift . newRef
201+ readRef = lift . readRef
202+ writeRef r = lift . writeRef r
203+
204+instance MonadAtomicRef m => MonadAtomicRef (WithJSContextSingleton x m) where
205+ atomicModifyRef r = lift . atomicModifyRef r
206+
207+withJSContextSingleton :: MonadJSM m => (forall x. JSContextSingleton x -> m r) -> m r
208+withJSContextSingleton f = askJSM >>= f . JSContextSingleton
209+
210+-- | Warning: `withJSContextSingletonMono` does not provide the same guarantees that `withJSContextSingleton` does.
211+withJSContextSingletonMono :: MonadJSM m => (JSContextSingleton () -> m r) -> m r
212+withJSContextSingletonMono f = askJSM >>= f . JSContextSingleton
213+
214+-- | A singleton type for a given JSContext; we use this to statically guarantee that different JSContexts don't get mixed up
215+newtype JSContextSingleton x = JSContextSingleton { unJSContextSingleton :: JSContextRef }
216+
217+#ifdef ghcjs_HOST_OS
218+type JSFFI_Internal = JS.MutableJSArray -> IO JS.JSVal
219+newtype JSFFI = JSFFI JSFFI_Internal
220+#else
221+newtype JSFFI = JSFFI String
222+#endif
223+
224+data JSFun x = JSFun { unJSFun :: JSRef x
225+#ifndef ghcjs_HOST_OS
226+ , unJSFunction :: Function
227+#endif
228+ }
229+
230+instance ToJS x (JSFun x) where
231+ withJS r f = f (unJSFun r)
232+
233+class IsJSContext x where
234+ data JSRef x
235+
236+class (Monad m, MonadJSM (JSX m), MonadFix (JSX m), MonadJS x (JSX m)) => HasJS x m | m -> x where
237+ type JSX m :: * -> *
238+ liftJS :: JSX m a -> m a
239+
240+instance HasJS x m => HasJS x (ReaderT r m) where
241+ type JSX (ReaderT r m) = JSX m
242+ liftJS = lift . liftJS
243+
244+instance HasJS x m => HasJS x (PostBuildT t m) where
245+ type JSX (PostBuildT t m) = JSX m
246+ liftJS = lift . liftJS
247+
248+instance (HasJS x (HostFrame t), ReflexHost t) => HasJS x (PerformEventT t m) where
249+ type JSX (PerformEventT t m) = JSX (HostFrame t)
250+ liftJS = PerformEventT . lift . liftJS
251+
252+instance HasJS x m => HasJS x (DynamicWriterT t w m) where
253+ type JSX (DynamicWriterT t w m) = JSX m
254+ liftJS = lift . liftJS
255+
256+instance HasJS x m => HasJS x (EventWriterT t w m) where
257+ type JSX (EventWriterT t w m) = JSX m
258+ liftJS = lift . liftJS
259+
260+instance HasJS x m => HasJS x (RequesterT t request response m) where
261+ type JSX (RequesterT t request response m) = JSX m
262+ liftJS = lift . liftJS
263+
264+instance HasJS x m => HasJS x (QueryT t q m) where
265+ type JSX (QueryT t q m) = JSX m
266+ liftJS = lift . liftJS
267+
268+-- | A Monad that is capable of executing JavaScript
269+class Monad m => MonadJS x m | m -> x where
270+ runJS :: JSFFI -> [JSRef x] -> m (JSRef x)
271+ forkJS :: m () -> m ThreadId
272+ mkJSUndefined :: m (JSRef x)
273+ isJSNull :: JSRef x -> m Bool
274+ isJSUndefined :: JSRef x -> m Bool
275+ fromJSBool :: JSRef x -> m Bool
276+ fromJSString :: JSRef x -> m String
277+ fromJSArray :: JSRef x -> m [JSRef x]
278+ fromJSUint8Array :: JSRef x -> m ByteString
279+ fromJSNumber :: JSRef x -> m Double
280+ withJSBool :: Bool -> (JSRef x -> m r) -> m r
281+ withJSString :: String -> (JSRef x -> m r) -> m r
282+ withJSNumber :: Double -> (JSRef x -> m r) -> m r
283+ withJSArray :: [JSRef x] -> (JSRef x -> m r) -> m r
284+ withJSUint8Array :: ByteString -> (JSUint8Array x -> m r) -> m r
285+ -- | Create a JSFun with zero arguments; should be equilvant to `syncCallback AlwaysRetain True` in GHCJS
286+ mkJSFun :: ([JSRef x] -> m (JSRef x)) -> m (JSFun x) --TODO: Support 'this', exceptions
287+ freeJSFun :: JSFun x -> m ()
288+ setJSProp :: String -> JSRef x -> JSRef x -> m ()
289+ getJSProp :: String -> JSRef x -> m (JSRef x)
290+ withJSNode :: Node -> (JSRef x -> m r) -> m r
291+
292+#ifdef ghcjs_HOST_OS
293+
294+data JSCtx_IO
295+type JS' = JSCtx_IO
296+
297+instance MonadIO m => HasJS JSCtx_IO (WithJSContextSingleton x m) where
298+ type JSX (WithJSContextSingleton x m) = IO
299+ liftJS = liftIO
300+
301+instance IsJSContext JSCtx_IO where
302+ newtype JSRef JSCtx_IO = JSRef_IO { unJSRef_IO :: JS.JSVal }
303+
304+instance MonadJS JSCtx_IO IO where
305+ runJS (JSFFI f) l = fmap JSRef_IO . f =<< JS.fromListIO (coerce l)
306+ forkJS = forkIO
307+ mkJSUndefined = return $ JSRef_IO JS.jsUndefined
308+ isJSNull (JSRef_IO r) = return $ JS.isNull r
309+ isJSUndefined (JSRef_IO r) = return $ JS.isUndefined r
310+ fromJSBool (JSRef_IO r) = return $ JS.fromJSBool r
311+ fromJSString (JSRef_IO r) = return $ JS.fromJSString $ JS.pFromJSVal r
312+ fromJSArray (JSRef_IO r) = fmap coerce $ JS.toListIO $ coerce r
313+ fromJSUint8Array (JSRef_IO r) = fmap (JS.toByteString 0 Nothing . JS.createFromArrayBuffer) $ JSArrayBuffer.unsafeFreeze $ JS.pFromJSVal r --TODO: Assert that this is immutable
314+ fromJSNumber (JSRef_IO r) = JS.fromJSValUnchecked r
315+ withJSBool b f = f $ JSRef_IO $ JS.toJSBool b
316+ withJSString s f = f $ JSRef_IO $ JS.pToJSVal $ JS.toJSString s
317+ withJSNumber n f = do
318+ r <- JS.toJSVal n
319+ f $ JSRef_IO r
320+ withJSArray l f = do
321+ r <- JS.fromListIO $ coerce l
322+ f $ JSRef_IO $ coerce r
323+ withJSUint8Array payload f = BS.useAsCString payload $ \cStr -> do
324+ ba <- extractByteArray cStr $ BS.length payload
325+ f $ JSUint8Array $ JSRef_IO ba
326+ mkJSFun f = do
327+ cb <- JS.syncCallback1' $ \args -> do
328+ l <- JS.toListIO $ coerce args
329+ JSRef_IO result <- f $ coerce l
330+ return result
331+ fmap (JSFun . JSRef_IO) $ funWithArguments $ coerce cb
332+ freeJSFun (JSFun (JSRef_IO r)) = JS.releaseCallback $ coerce r
333+ setJSProp s (JSRef_IO v) (JSRef_IO o) = JS.setProp (JS.toJSString s) v $ coerce o
334+ getJSProp s (JSRef_IO o) = do
335+ r <- JS.getProp (JS.toJSString s) $ coerce o
336+ return $ JSRef_IO r
337+ withJSNode n f = f $ JSRef_IO $ unNode n
338+
339+foreign import javascript unsafe "new Uint8Array($1_1.buf, $1_2, $2)" extractByteArray :: Ptr CChar -> Int -> IO JS.JSVal
340+
341+foreign import javascript unsafe "function(){ return $1(arguments); }" funWithArguments :: JS.Callback (JS.MutableJSArray -> IO a) -> IO JS.JSVal
342+
343+#else
344+
345+data JSCtx_JavaScriptCore x
346+type JS' = JSCtx_JavaScriptCore ()
347+
348+instance IsJSContext (JSCtx_JavaScriptCore x) where
349+ newtype JSRef (JSCtx_JavaScriptCore x) = JSRef_JavaScriptCore { unJSRef_JavaScriptCore :: JSVal }
350+
351+instance MonadIO m => HasJS (JSCtx_JavaScriptCore x) (WithJSContextSingleton x m) where
352+ type JSX (WithJSContextSingleton x m) = WithJSContextSingleton x IO
353+ liftJS a = do
354+ wv <- askJSContext
355+ liftIO $ runWithJSContextSingleton a wv
356+
357+newtype WithJSContext x m a = WithJSContext { unWithJSContext :: ReaderT JSContextRef m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadTrans, MonadException, MonadAsyncException)
358+
359+runWithJSContext :: WithJSContext x m a -> JSContextRef -> m a
360+runWithJSContext = runReaderT . unWithJSContext
361+
362+instance MonadIO m => MonadJSM (WithJSContextSingleton x m) where
363+ liftJSM' f = do
364+ wv <- askJSContext
365+ runJSM f $ unJSContextSingleton wv
366+
367+instance MonadIO m => MonadJSM (WithJSContext x m) where
368+ liftJSM' f =
369+ runJSM f =<< WithJSContext ask
370+
371+lowerWithJSContext :: MonadJSM m => WithJSContext x IO a -> m a
372+lowerWithJSContext a = do
373+ c <- askJSM
374+ liftIO $ runWithJSContext a c
375+
376+liftWithJSContextSingletonThroughWithJSContext :: (HasJSContext m, MonadJSM m, MonadTrans t, Monad m1)
377+ => ((t1 -> t m1 a) -> WithJSContext x IO b)
378+ -> (t1 -> WithJSContextSingleton (JSContextPhantom m) m1 a)
379+ -> m b
380+liftWithJSContextSingletonThroughWithJSContext f a = do
381+ wv <- askJSContext
382+ lowerWithJSContext $ f $ \b' -> lift $ runWithJSContextSingleton (a b') wv
383+
384+instance MonadJS (JSCtx_JavaScriptCore x) (WithJSContextSingleton x IO) where
385+ forkJS a = do
386+ wv <- askJSContext
387+ liftIO $ forkIO $ runWithJSContextSingleton a wv
388+ mkJSFun a = do
389+ wv <- askJSContext
390+ lowerWithJSContext $ mkJSFun $ \args -> lift $ runWithJSContextSingleton (a args) wv
391+ runJS expr args = lowerWithJSContext $ runJS expr args
392+ mkJSUndefined = lowerWithJSContext mkJSUndefined
393+ isJSNull = lowerWithJSContext . isJSNull
394+ isJSUndefined = lowerWithJSContext . isJSUndefined
395+ fromJSBool = lowerWithJSContext . fromJSBool
396+ fromJSString = lowerWithJSContext . fromJSString
397+ fromJSArray = lowerWithJSContext . fromJSArray
398+ fromJSUint8Array = lowerWithJSContext . fromJSUint8Array
399+ fromJSNumber = lowerWithJSContext . fromJSNumber
400+ freeJSFun = lowerWithJSContext . freeJSFun
401+ withJSBool = liftWithJSContextSingletonThroughWithJSContext . withJSBool
402+ withJSString = liftWithJSContextSingletonThroughWithJSContext . withJSString
403+ withJSNumber = liftWithJSContextSingletonThroughWithJSContext . withJSNumber
404+ withJSArray = liftWithJSContextSingletonThroughWithJSContext . withJSArray
405+ withJSUint8Array = liftWithJSContextSingletonThroughWithJSContext . withJSUint8Array
406+ withJSNode = liftWithJSContextSingletonThroughWithJSContext . withJSNode
407+ setJSProp propName valRef objRef = lowerWithJSContext $ setJSProp propName valRef objRef
408+ getJSProp propName objRef = lowerWithJSContext $ getJSProp propName objRef
409+
410+instance MonadJS (JSCtx_JavaScriptCore x) (WithJSContext x IO) where
411+ runJS (JSFFI body) args =
412+ withJSArray args $ \(JSRef_JavaScriptCore this) -> do
413+ result <- liftJSM $ eval ("(function(){ return (" <> body <> "); })") ^. js1 "apply" this
414+ return $ JSRef_JavaScriptCore result
415+ forkJS a = do
416+ c <- askJSM
417+ liftIO . forkIO $ runWithJSContext a c
418+ mkJSUndefined = return $ JSRef_JavaScriptCore valUndefined
419+ isJSNull (JSRef_JavaScriptCore r) = liftJSM $ valIsNull r
420+ isJSUndefined (JSRef_JavaScriptCore r) = liftJSM $ valIsUndefined r
421+ fromJSBool (JSRef_JavaScriptCore r) = liftJSM $ valToBool r
422+ fromJSString (JSRef_JavaScriptCore r) = liftJSM (T.unpack <$> valToText r)
423+ withJSBool b a = a $ JSRef_JavaScriptCore (valBool b)
424+ withJSString str a = a . JSRef_JavaScriptCore =<< liftJSM (valMakeString $ toJSString str)
425+ withJSNumber n a = a . JSRef_JavaScriptCore =<< liftJSM (valMakeNumber n)
426+ withJSArray elems a = a . JSRef_JavaScriptCore =<< liftJSM
427+ (toJSVal =<< array (map (\(JSRef_JavaScriptCore r) -> r) elems))
428+ withJSUint8Array payload f = withJSArrayFromList (BS.unpack payload) $ \x -> do
429+ payloadRef <- runJS (JSFFI "new Uint8Array(this[0])") [x]
430+ f $ JSUint8Array payloadRef
431+ fromJSArray (JSRef_JavaScriptCore a) = liftJSM $ do
432+ len <- round <$> (valToNumber =<< (a ^. js "length"))
433+ forM [0..len-1] $ fmap JSRef_JavaScriptCore . (a !!)
434+ fromJSUint8Array a = do
435+ vals <- fromJSArray a
436+ doubles <- mapM fromJSNumber vals
437+ return $ BS.pack $ map round doubles
438+ fromJSNumber (JSRef_JavaScriptCore val) = liftJSM $ valToNumber val
439+ mkJSFun a = liftJSM $ do
440+ ctx <- askJSM
441+ f <- function $ \_ _ args -> liftIO $ void $ runWithJSContext (a $ map JSRef_JavaScriptCore args) ctx
442+ fRef <- toJSVal f
443+ return $ JSFun (JSRef_JavaScriptCore fRef) f
444+ freeJSFun (JSFun _ f) = liftJSM $ freeFunction f
445+ setJSProp propName (JSRef_JavaScriptCore valRef) (JSRef_JavaScriptCore objRef) =
446+ liftJSM $ objRef ^. jss propName valRef
447+ getJSProp propName (JSRef_JavaScriptCore objRef) =
448+ JSRef_JavaScriptCore <$> liftJSM (objRef ^. js propName)
449+ withJSNode n f = f . JSRef_JavaScriptCore =<< liftJSM (toJSVal n)
450+
451+#endif
452+
453+class FromJS x a where
454+ fromJS :: MonadJS x m => JSRef x -> m a
455+
456+instance FromJS x () where
457+ fromJS _ = return () --TODO: Should this do some kind of checking for the js value?
458+
459+instance FromJS x Bool where
460+ fromJS = fromJSBool
461+
462+instance ToJS x Bool where
463+ withJS = withJSBool
464+
465+instance FromJS x String where
466+ fromJS = fromJSString
467+
468+instance FromJS x Text where
469+ fromJS s = T.pack <$> fromJSString s
470+
471+instance FromJS x a => FromJS x (Maybe a) where
472+ fromJS x = do
473+ n <- isJSNull x
474+ if n then return Nothing else Just <$> fromJS x
475+
476+class ToJS x a where
477+ withJS :: MonadJS x m => a -> (JSRef x -> m r) -> m r
478+
479+instance ToJS x (JSRef x) where
480+ withJS r = ($ r)
481+
482+instance FromJS x (JSRef x) where
483+ fromJS = return
484+
485+instance ToJS x String where
486+ withJS = withJSString
487+
488+instance ToJS x Text where
489+ withJS = withJSString . T.unpack
490+
491+newtype JSArray a = JSArray { unJSArray :: [a] }
492+
493+instance ToJS x a => ToJS x (JSArray a) where
494+ withJS = withJSArrayFromList . unJSArray
495+
496+instance FromJS x a => FromJS x (JSArray a) where
497+ fromJS = fmap JSArray . mapM fromJS <=< fromJSArray
498+
499+withJSArrayFromList :: (ToJS x a, MonadJS x m) => [a] -> (JSRef x -> m r) -> m r
500+withJSArrayFromList as f = go as []
501+ where go [] jsRefs = withJSArray (reverse jsRefs) f
502+ go (h:t) jsRefs = withJS h $ \hRef -> go t (hRef : jsRefs)
503+
504+newtype JSUint8Array x = JSUint8Array { unJSUint8Array :: JSRef x }
505+
506+instance ToJS x (JSUint8Array x) where
507+ withJS (JSUint8Array r) = ($ r)
508+
509+instance FromJS x (JSUint8Array x) where
510+ fromJS = return . JSUint8Array
511+
512+instance ToJS x Word8 where
513+ withJS n = withJSNumber $ fromIntegral n --TODO: Check things; throw exceptions
514+
515+instance ToJS x Int where
516+ withJS n = withJSNumber $ fromIntegral n --TODO: Check things; throw exceptions
517+
518+instance FromJS x Int where
519+ fromJS = fmap round . fromJSNumber --TODO: Check things; throw exceptions
520+
521+instance ToJS x Double where
522+ withJS = withJSNumber
523+
524+instance FromJS x Double where
525+ fromJS = fromJSNumber
526+
527+instance ToJS x Node where
528+ withJS = withJSNode
529+
530+
531+#ifdef USE_TEMPLATE_HASKELL
532+
533+importJS :: Safety -> String -> String -> Q Type -> Q [Dec]
534+importJS safety body name qt = do
535+ t <- qt
536+ let (argTypes, _) = parseType t
537+ argNames <- forM argTypes $ \_ -> do
538+ arg <- newName "arg"
539+ argRef <- newName "argRef"
540+ return (arg, argRef)
541+ (jsffiDecs, jsffiExp) <- mkJSFFI safety body
542+ let go [] = [| runJS $(return jsffiExp) $(listE $ map (varE . snd) argNames) >>= fromJS
543+ |]
544+ go ((arg, argRef) : args) = [| withJS $(varE arg) $ $(lamE [varP argRef] $ go args) |]
545+ e <- lamE (map (varP. fst) argNames) $ go argNames
546+ let n = mkName name
547+ return $ jsffiDecs ++
548+ [ SigD n t
549+ , ValD (VarP n) (NormalB e) []
550+ ]
551+
552+mkJSFFI :: Safety -> String -> Q ([Dec], Exp)
553+#ifdef ghcjs_HOST_OS
554+mkJSFFI safety body = do
555+ -- n <- newName "jsffi" --TODO: Should use newName, but that doesn't seem to work with ghcjs
556+ l <- location
557+ n <- newName $ "jsffi_" <> zEncodeString (loc_package l <> ":" <> loc_module l) <> "_" <> show (abs (hash (show safety, body)))
558+ t <- [t| JSFFI_Internal |]
559+ let wrappedBody = "(function(){ return (" <> body <> "); }).apply($1)"
560+ let decs = [ForeignD $ ImportF JavaScript safety wrappedBody n t]
561+ e <- [| JSFFI $(varE n) |]
562+ return (decs, e)
563+#else
564+mkJSFFI _ body = do
565+ e <- [| JSFFI body |]
566+ return ([], e)
567+#endif
568+
569+parseType :: Type -> ([Type], Type)
570+parseType (ForallT _ [AppT (AppT (ConT monadJs) (VarT _)) (VarT m)] funType)
571+ | monadJs == ''MonadJS = go funType
572+ where go t = case t of
573+ AppT (AppT ArrowT arg) t' ->
574+ let (args, result) = go t'
575+ in (arg : args, result)
576+ AppT (VarT m') result
577+ | m' == m -> ([], result)
578+ _ -> error $ "parseType: can't parse type " <> show t
579+parseType t = error $ "parseType: can't parse type " <> show t
580+
581+#endif
reflex-dom-core/src/Foreign/JavaScript/Utils.hsnew file+58
@@ -0,0 +1,58 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
3+module Foreign.JavaScript.Utils
4+ ( bsFromMutableArrayBuffer
5+ , bsToArrayBuffer
6+ , jsonDecode
7+ , js_jsonParse
8+ ) where
9+
10+import Control.Lens
11+import Data.Aeson
12+import Data.ByteString (ByteString)
13+import qualified Data.ByteString as BS
14+import Foreign.JavaScript.Internal.Utils (js_dataView)
15+import qualified GHCJS.Buffer as JS
16+import GHCJS.DOM.Types (ArrayBuffer (..))
17+import GHCJS.Marshal ()
18+import Language.Javascript.JSaddle (jsg, js1)
19+import qualified JavaScript.TypedArray.ArrayBuffer as JS
20+import Language.Javascript.JSaddle.Types (JSString, JSM, JSVal, MonadJSM, ghcjsPure, jsval, liftJSM)
21+#ifdef ghcjs_HOST_OS
22+import Control.Exception (SomeException)
23+import Language.Javascript.JSaddle (fromJSVal, catch)
24+import System.IO.Unsafe
25+#else
26+import qualified Data.ByteString.Lazy as LBS
27+import Data.Text.Encoding
28+import Language.Javascript.JSaddle (textFromJSString)
29+#endif
30+
31+{-# INLINABLE bsFromMutableArrayBuffer #-}
32+bsFromMutableArrayBuffer :: MonadJSM m => JS.MutableArrayBuffer -> m ByteString
33+bsFromMutableArrayBuffer ab = liftJSM $ JS.unsafeFreeze ab >>=
34+ ghcjsPure . JS.createFromArrayBuffer >>= ghcjsPure . JS.toByteString 0 Nothing
35+
36+{-# INLINABLE bsToArrayBuffer #-}
37+bsToArrayBuffer :: MonadJSM m => ByteString -> m ArrayBuffer
38+bsToArrayBuffer bs = liftJSM $ do
39+ (b, off, len) <- ghcjsPure $ JS.fromByteString bs
40+ ArrayBuffer <$> if BS.length bs == 0 --TODO: remove this logic when https://github.com/ghcjs/ghcjs-base/issues/49 is fixed
41+ then JS.create 0 >>= ghcjsPure . JS.getArrayBuffer >>= ghcjsPure . jsval
42+ else do
43+ ref <- ghcjsPure (JS.getArrayBuffer b) >>= ghcjsPure . jsval
44+ js_dataView off len ref
45+
46+jsonDecode :: FromJSON a => JSString -> Maybe a
47+#ifdef ghcjs_HOST_OS
48+jsonDecode t = do
49+ result <- unsafePerformIO $ (fromJSVal =<< js_jsonParse t) `catch` (\(_ :: SomeException) -> pure Nothing)
50+ case fromJSON result of
51+ Success a -> Just a
52+ Error _ -> Nothing
53+#else
54+jsonDecode = decode . LBS.fromStrict . encodeUtf8 . textFromJSString
55+#endif
56+
57+js_jsonParse :: JSString -> JSM JSVal
58+js_jsonParse a = jsg "JSON" ^. js1 "parse" a
reflex-dom-core/src/Reflex/Dom/Builder/Class.hsnew file+755
@@ -0,0 +1,755 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE DataKinds #-}
4+{-# LANGUAGE DefaultSignatures #-}
5+{-# LANGUAGE DeriveFunctor #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
9+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
10+#if !MIN_VERSION_base(4,9,0)
11+{-# LANGUAGE ImpredicativeTypes #-}
12+#else
13+{-# LANGUAGE Rank2Types #-} -- Implied by ImpredicativeTypes
14+#endif
15+{-# LANGUAGE LambdaCase #-}
16+{-# LANGUAGE OverloadedStrings #-}
17+{-# LANGUAGE PolyKinds #-}
18+{-# LANGUAGE RecursiveDo #-}
19+{-# LANGUAGE ScopedTypeVariables #-}
20+{-# LANGUAGE StandaloneDeriving #-}
21+#ifdef USE_TEMPLATE_HASKELL
22+{-# LANGUAGE TemplateHaskell #-}
23+#endif
24+{-# LANGUAGE TypeFamilies #-}
25+{-# LANGUAGE UndecidableInstances #-}
26+module Reflex.Dom.Builder.Class
27+ ( module Reflex.Dom.Builder.Class
28+ , module Reflex.Dom.Builder.Class.Events
29+ , module Reflex.NotReady.Class
30+ ) where
31+
32+import Reflex.Adjustable.Class
33+import Reflex.Class as Reflex
34+import Reflex.Dom.Builder.Class.Events
35+#ifdef USE_TEMPLATE_HASKELL
36+import Reflex.Dom.Builder.Class.TH
37+#endif
38+import Reflex.BehaviorWriter.Base
39+import Reflex.DynamicWriter.Base
40+import Reflex.EventWriter.Base
41+import Reflex.NotReady.Class
42+import Reflex.PerformEvent.Class
43+import Reflex.PostBuild.Base
44+import Reflex.Query.Base
45+import Reflex.Query.Class
46+import Reflex.Requester.Base
47+
48+import qualified Control.Category
49+import Control.Lens hiding (element)
50+import Control.Monad.Reader
51+import qualified Control.Monad.State as Lazy
52+import Control.Monad.State.Strict
53+import Control.Monad.Trans.Control
54+import Data.Default
55+import Data.Functor.Misc
56+import Data.Map (Map)
57+import qualified Data.Map as Map
58+import Data.Maybe
59+import Data.Proxy
60+import Data.Semigroup
61+import Data.String
62+import Data.Text (Text)
63+import Data.Type.Coercion
64+import GHCJS.DOM.Types (JSM)
65+import qualified GHCJS.DOM.Types as DOM
66+
67+class Default (EventSpec d EventResult) => DomSpace d where
68+ type EventSpec d :: (EventTag -> *) -> *
69+ type RawDocument d :: *
70+ type RawTextNode d :: *
71+ type RawCommentNode d :: *
72+ type RawElement d :: *
73+ type RawInputElement d :: *
74+ type RawTextAreaElement d :: *
75+ type RawSelectElement d :: *
76+ addEventSpecFlags :: proxy d -> EventName en -> (Maybe (er en) -> EventFlags) -> EventSpec d er -> EventSpec d er
77+
78+-- | @'DomBuilder' t m@ indicates that @m@ is a 'Monad' capable of building
79+-- dynamic DOM in the 'Reflex' timeline @t@
80+class (Monad m, Reflex t, DomSpace (DomBuilderSpace m), NotReady t m, Adjustable t m) => DomBuilder t m | m -> t where
81+ type DomBuilderSpace m :: *
82+ textNode :: TextNodeConfig t -> m (TextNode (DomBuilderSpace m) t)
83+ default textNode :: ( MonadTrans f
84+ , m ~ f m'
85+ , DomBuilderSpace m' ~ DomBuilderSpace m
86+ , DomBuilder t m'
87+ )
88+ => TextNodeConfig t -> m (TextNode (DomBuilderSpace m) t)
89+ textNode = lift . textNode
90+ {-# INLINABLE textNode #-}
91+ commentNode :: CommentNodeConfig t -> m (CommentNode (DomBuilderSpace m) t)
92+ default commentNode :: ( MonadTrans f
93+ , m ~ f m'
94+ , DomBuilderSpace m' ~ DomBuilderSpace m
95+ , DomBuilder t m'
96+ )
97+ => CommentNodeConfig t -> m (CommentNode (DomBuilderSpace m) t)
98+ commentNode = lift . commentNode
99+ {-# INLINABLE commentNode #-}
100+ element :: Text -> ElementConfig er t (DomBuilderSpace m) -> m a -> m (Element er (DomBuilderSpace m) t, a)
101+ default element :: ( MonadTransControl f
102+ , StT f a ~ a
103+ , m ~ f m'
104+ , DomBuilderSpace m' ~ DomBuilderSpace m
105+ , DomBuilder t m'
106+ )
107+ => Text -> ElementConfig er t (DomBuilderSpace m) -> m a -> m (Element er (DomBuilderSpace m) t, a)
108+ element t cfg child = liftWith $ \run -> element t cfg $ run child
109+ {-# INLINABLE element #-}
110+ inputElement :: InputElementConfig er t (DomBuilderSpace m) -> m (InputElement er (DomBuilderSpace m) t)
111+ default inputElement :: ( MonadTransControl f
112+ , m ~ f m'
113+ , DomBuilderSpace m' ~ DomBuilderSpace m
114+ , DomBuilder t m'
115+ )
116+ => InputElementConfig er t (DomBuilderSpace m) -> m (InputElement er (DomBuilderSpace m) t)
117+ inputElement = lift . inputElement
118+ {-# INLINABLE inputElement #-}
119+ textAreaElement :: TextAreaElementConfig er t (DomBuilderSpace m) -> m (TextAreaElement er (DomBuilderSpace m) t)
120+ default textAreaElement :: ( MonadTransControl f
121+ , m ~ f m'
122+ , DomBuilderSpace m' ~ DomBuilderSpace m
123+ , DomBuilder t m'
124+ )
125+ => TextAreaElementConfig er t (DomBuilderSpace m) -> m (TextAreaElement er (DomBuilderSpace m) t)
126+ textAreaElement = lift . textAreaElement
127+ {-# INLINABLE textAreaElement #-}
128+ selectElement :: SelectElementConfig er t (DomBuilderSpace m) -> m a -> m (SelectElement er (DomBuilderSpace m) t, a)
129+ default selectElement :: ( MonadTransControl f
130+ , StT f a ~ a
131+ , m ~ f m'
132+ , DomBuilderSpace m' ~ DomBuilderSpace m
133+ , DomBuilder t m'
134+ )
135+ => SelectElementConfig er t (DomBuilderSpace m) -> m a -> m (SelectElement er (DomBuilderSpace m) t, a)
136+ selectElement cfg child = do
137+ liftWith $ \run -> selectElement cfg $ run child
138+ {-# INLINABLE selectElement #-}
139+ placeRawElement :: RawElement (DomBuilderSpace m) -> m ()
140+ default placeRawElement :: ( MonadTrans f
141+ , m ~ f m'
142+ , DomBuilderSpace m' ~ DomBuilderSpace m
143+ , DomBuilder t m'
144+ )
145+ => RawElement (DomBuilderSpace m) -> m ()
146+ placeRawElement = lift . placeRawElement
147+ {-# INLINABLE placeRawElement #-}
148+ wrapRawElement :: RawElement (DomBuilderSpace m) -> RawElementConfig er t (DomBuilderSpace m) -> m (Element er (DomBuilderSpace m) t)
149+ default wrapRawElement :: ( MonadTrans f
150+ , m ~ f m'
151+ , DomBuilderSpace m' ~ DomBuilderSpace m
152+ , DomBuilder t m'
153+ )
154+ => RawElement (DomBuilderSpace m) -> RawElementConfig er t (DomBuilderSpace m) -> m (Element er (DomBuilderSpace m) t)
155+ wrapRawElement e cfg = lift $ wrapRawElement e $ cfg
156+ { _rawElementConfig_eventSpec = _rawElementConfig_eventSpec cfg
157+ }
158+ {-# INLINABLE wrapRawElement #-}
159+
160+class DomBuilder t m => MountableDomBuilder t m where
161+ type DomFragment m :: *
162+ buildDomFragment :: m a -> m (DomFragment m, a)
163+ mountDomFragment :: DomFragment m -> Event t (DomFragment m) -> m ()
164+
165+type Namespace = Text
166+
167+data TextNodeConfig t
168+ = TextNodeConfig { _textNodeConfig_initialContents :: {-# UNPACK #-} !Text
169+ , _textNodeConfig_setContents :: !(Maybe (Event t Text))
170+ }
171+
172+#ifndef USE_TEMPLATE_HASKELL
173+textNodeConfig_initialContents :: Lens' (TextNodeConfig t) Text
174+textNodeConfig_initialContents f (TextNodeConfig a b) = (\a' -> TextNodeConfig a' b) <$> f a
175+{-# INLINE textNodeConfig_initialContents #-}
176+#endif
177+
178+instance (Reflex t) => Default (TextNodeConfig t) where
179+ {-# INLINABLE def #-}
180+ def = TextNodeConfig
181+ { _textNodeConfig_initialContents = mempty
182+ , _textNodeConfig_setContents = Nothing
183+ }
184+
185+newtype TextNode d t = TextNode
186+ { _textNode_raw :: RawTextNode d
187+ }
188+
189+data CommentNodeConfig t
190+ = CommentNodeConfig { _commentNodeConfig_initialContents :: {-# UNPACK #-} !Text
191+ , _commentNodeConfig_setContents :: !(Maybe (Event t Text))
192+ }
193+
194+#ifndef USE_TEMPLATE_HASKELL
195+commentNodeConfig_initialContents :: Lens' (CommentNodeConfig t) Text
196+commentNodeConfig_initialContents f (CommentNodeConfig a b) = (\a' -> CommentNodeConfig a' b) <$> f a
197+{-# INLINE commentNodeConfig_initialContents #-}
198+#endif
199+
200+instance (Reflex t) => Default (CommentNodeConfig t) where
201+ {-# INLINABLE def #-}
202+ def = CommentNodeConfig
203+ { _commentNodeConfig_initialContents = mempty
204+ , _commentNodeConfig_setContents = Nothing
205+ }
206+
207+newtype CommentNode d t = CommentNode
208+ { _commentNode_raw :: RawCommentNode d
209+ }
210+
211+data AttributeName = AttributeName !(Maybe Namespace) !Text deriving (Show, Read, Eq, Ord)
212+
213+mapKeysToAttributeName :: Map Text v -> Map AttributeName v
214+mapKeysToAttributeName = Map.mapKeysMonotonic (AttributeName Nothing)
215+
216+-- | By default, AttributeNames are unnamespaced
217+instance IsString AttributeName where
218+ fromString = AttributeName Nothing . fromString
219+
220+data Propagation
221+ = Propagation_Continue
222+ | Propagation_Stop
223+ | Propagation_StopImmediate
224+ deriving (Show, Read, Eq, Ord)
225+
226+instance Semigroup Propagation where
227+ {-# INLINABLE (<>) #-}
228+ (<>) = max
229+
230+instance Monoid Propagation where
231+ {-# INLINABLE mempty #-}
232+ mempty = Propagation_Continue
233+ {-# INLINABLE mappend #-}
234+ mappend = (<>)
235+
236+data EventFlags = EventFlags --TODO: Monoid; ways of building each flag
237+ { _eventFlags_propagation :: Propagation
238+ , _eventFlags_preventDefault :: Bool
239+ }
240+
241+instance Semigroup EventFlags where
242+ {-# INLINABLE (<>) #-}
243+ EventFlags p pd <> EventFlags p' pd' = EventFlags (p <> p') (pd || pd')
244+
245+instance Monoid EventFlags where
246+ {-# INLINABLE mempty #-}
247+ mempty = EventFlags Propagation_Continue False
248+ {-# INLINABLE mappend #-}
249+ mappend = (<>)
250+
251+preventDefault :: EventFlags
252+preventDefault = mempty { _eventFlags_preventDefault = True }
253+
254+stopPropagation :: EventFlags
255+stopPropagation = mempty { _eventFlags_propagation = Propagation_Stop }
256+
257+data ElementConfig er t s
258+ = ElementConfig { _elementConfig_namespace :: Maybe Namespace
259+ , _elementConfig_initialAttributes :: Map AttributeName Text
260+ , _elementConfig_modifyAttributes :: Maybe (Event t (Map AttributeName (Maybe Text)))
261+ , _elementConfig_eventSpec :: EventSpec s er
262+ }
263+
264+#ifndef USE_TEMPLATE_HASKELL
265+elementConfig_namespace :: Lens' (ElementConfig er t s) (Maybe Namespace)
266+elementConfig_namespace f (ElementConfig a b c d) = (\a' -> ElementConfig a' b c d) <$> f a
267+{-# INLINE elementConfig_namespace #-}
268+elementConfig_initialAttributes :: Lens' (ElementConfig er t s) (Map AttributeName Text)
269+elementConfig_initialAttributes f (ElementConfig a b c d) = (\b' -> ElementConfig a b' c d) <$> f b
270+{-# INLINE elementConfig_initialAttributes #-}
271+elementConfig_eventSpec :: Lens
272+ (ElementConfig er1 t s1)
273+ (ElementConfig er2 t s2)
274+ (EventSpec s1 er1)
275+ (EventSpec s2 er2)
276+elementConfig_eventSpec f (ElementConfig a b c d) = (\d' -> ElementConfig a b c d') <$> f d
277+{-# INLINE elementConfig_eventSpec #-}
278+#endif
279+
280+data Element er d t
281+ = Element { _element_events :: EventSelector t (WrapArg er EventName) --TODO: EventSelector should have two arguments
282+ , _element_raw :: RawElement d
283+ }
284+
285+data InputElementConfig er t s
286+ = InputElementConfig { _inputElementConfig_initialValue :: Text
287+ , _inputElementConfig_setValue :: Maybe (Event t Text)
288+ , _inputElementConfig_initialChecked :: Bool
289+ , _inputElementConfig_setChecked :: Maybe (Event t Bool)
290+ , _inputElementConfig_elementConfig :: ElementConfig er t s
291+ }
292+
293+#ifndef USE_TEMPLATE_HASKELL
294+inputElementConfig_initialValue :: Lens' (InputElementConfig er t m) Text
295+inputElementConfig_initialValue f (InputElementConfig a b c d e) = (\a' -> InputElementConfig a' b c d e) <$> f a
296+{-# INLINE inputElementConfig_initialValue #-}
297+inputElementConfig_initialChecked :: Lens' (InputElementConfig er t m) Bool
298+inputElementConfig_initialChecked f (InputElementConfig a b c d e) = (\c' -> InputElementConfig a b c' d e) <$> f c
299+{-# INLINE inputElementConfig_initialChecked #-}
300+inputElementConfig_elementConfig :: Lens
301+ (InputElementConfig er1 t m1)
302+ (InputElementConfig er2 t m2)
303+ (ElementConfig er1 t m1)
304+ (ElementConfig er2 t m2)
305+inputElementConfig_elementConfig f (InputElementConfig a b c d e) = (\e' -> InputElementConfig a b c d e') <$> f e
306+{-# INLINE inputElementConfig_elementConfig #-}
307+#endif
308+
309+instance (Reflex t, er ~ EventResult, DomSpace s) => Default (InputElementConfig er t s) where
310+ {-# INLINABLE def #-}
311+ def = InputElementConfig
312+ { _inputElementConfig_initialValue = ""
313+ , _inputElementConfig_setValue = Nothing
314+ , _inputElementConfig_initialChecked = False
315+ , _inputElementConfig_setChecked = Nothing
316+ , _inputElementConfig_elementConfig = def
317+ }
318+
319+data InputElement er d t
320+ = InputElement { _inputElement_value :: Dynamic t Text
321+ , _inputElement_checked :: Dynamic t Bool
322+ , _inputElement_checkedChange :: Event t Bool
323+ , _inputElement_input :: Event t Text
324+ , _inputElement_hasFocus :: Dynamic t Bool
325+ , _inputElement_element :: Element er d t
326+ , _inputElement_raw :: RawInputElement d
327+ , _inputElement_files :: Dynamic t [DOM.File]
328+ }
329+
330+data TextAreaElementConfig er t m
331+ = TextAreaElementConfig { _textAreaElementConfig_initialValue :: Text
332+ , _textAreaElementConfig_setValue :: Maybe (Event t Text)
333+ , _textAreaElementConfig_elementConfig :: ElementConfig er t m
334+ }
335+
336+#ifndef USE_TEMPLATE_HASKELL
337+textAreaElementConfig_initialValue :: Lens' (TextAreaElementConfig er t m) Text
338+textAreaElementConfig_initialValue f (TextAreaElementConfig a b c) = (\a' -> TextAreaElementConfig a' b c) <$> f a
339+{-# INLINE textAreaElementConfig_initialValue #-}
340+textAreaElementConfig_elementConfig :: Lens
341+ (TextAreaElementConfig er1 t m1)
342+ (TextAreaElementConfig er2 t m2)
343+ (ElementConfig er1 t m1)
344+ (ElementConfig er2 t m2)
345+textAreaElementConfig_elementConfig f (TextAreaElementConfig a b c) = (\c' -> TextAreaElementConfig a b c') <$> f c
346+{-# INLINE textAreaElementConfig_elementConfig #-}
347+#endif
348+
349+instance (Reflex t, er ~ EventResult, DomSpace s) => Default (TextAreaElementConfig er t s) where
350+ {-# INLINABLE def #-}
351+ def = TextAreaElementConfig
352+ { _textAreaElementConfig_initialValue = ""
353+ , _textAreaElementConfig_setValue = Nothing
354+ , _textAreaElementConfig_elementConfig = def
355+ }
356+
357+data TextAreaElement er d t
358+ = TextAreaElement { _textAreaElement_value :: Dynamic t Text
359+ , _textAreaElement_input :: Event t Text
360+ , _textAreaElement_hasFocus :: Dynamic t Bool
361+ , _textAreaElement_element :: Element er d t
362+ , _textAreaElement_raw :: RawTextAreaElement d
363+ }
364+
365+extractRawElementConfig :: ElementConfig er t m -> RawElementConfig er t m
366+extractRawElementConfig cfg = RawElementConfig
367+ { _rawElementConfig_modifyAttributes = _elementConfig_modifyAttributes cfg
368+ , _rawElementConfig_eventSpec = _elementConfig_eventSpec cfg
369+ }
370+
371+data RawElementConfig er t s = RawElementConfig
372+ { _rawElementConfig_modifyAttributes :: Maybe (Event t (Map AttributeName (Maybe Text)))
373+ , _rawElementConfig_eventSpec :: EventSpec s er
374+ }
375+
376+#ifndef USE_TEMPLATE_HASKELL
377+rawElementConfig_eventSpec :: Lens
378+ (RawElementConfig er1 t s1)
379+ (RawElementConfig er2 t s2)
380+ (EventSpec s1 er1)
381+ (EventSpec s2 er2)
382+rawElementConfig_eventSpec f (RawElementConfig a b) = (\b' -> RawElementConfig a b') <$> f b
383+{-# INLINE rawElementConfig_eventSpec #-}
384+#endif
385+
386+instance (Reflex t, er ~ EventResult, DomSpace s) => Default (RawElementConfig er t s) where
387+ def = RawElementConfig
388+ { _rawElementConfig_modifyAttributes = Nothing
389+ , _rawElementConfig_eventSpec = def
390+ }
391+
392+data SelectElementConfig er t m = SelectElementConfig
393+ { _selectElementConfig_initialValue :: Text
394+ , _selectElementConfig_setValue :: Maybe (Event t Text)
395+ , _selectElementConfig_elementConfig :: ElementConfig er t m
396+ }
397+
398+#ifndef USE_TEMPLATE_HASKELL
399+selectElementConfig_initialValue :: Lens' (SelectElementConfig er t m) Text
400+selectElementConfig_initialValue f (SelectElementConfig a b c) = (\a' -> SelectElementConfig a' b c) <$> f a
401+{-# INLINE selectElementConfig_initialValue #-}
402+selectElementConfig_elementConfig :: Lens
403+ (SelectElementConfig er1 t m1)
404+ (SelectElementConfig er2 t m2)
405+ (ElementConfig er1 t m1)
406+ (ElementConfig er2 t m2)
407+selectElementConfig_elementConfig f (SelectElementConfig a b c) = (\c' -> SelectElementConfig a b c') <$> f c
408+{-# INLINE selectElementConfig_elementConfig #-}
409+#endif
410+
411+instance (Reflex t, er ~ EventResult, DomSpace s) => Default (SelectElementConfig er t s) where
412+ def = SelectElementConfig
413+ { _selectElementConfig_initialValue = ""
414+ , _selectElementConfig_setValue = Nothing
415+ , _selectElementConfig_elementConfig = def
416+ }
417+
418+data SelectElement er d t = SelectElement
419+ { _selectElement_element :: Element er d t
420+ , _selectElement_value :: Dynamic t Text
421+ , _selectElement_change :: Event t Text -- ^ Fires when the value is changed by the user, but not when it is set by setValue
422+ , _selectElement_hasFocus :: Dynamic t Bool
423+ , _selectElement_raw :: RawSelectElement d
424+ }
425+
426+#ifdef USE_TEMPLATE_HASKELL
427+concat <$> mapM (uncurry makeLensesWithoutField)
428+ [ (["_textNodeConfig_setContents"], ''TextNodeConfig)
429+ , (["_commentNodeConfig_setContents"], ''CommentNodeConfig)
430+ , ([ "_inputElementConfig_setValue"
431+ , "_inputElementConfig_setChecked" ], ''InputElementConfig)
432+ , (["_rawElementConfig_modifyAttributes"], ''RawElementConfig)
433+ , (["_elementConfig_modifyAttributes"], ''ElementConfig)
434+ , (["_textAreaElementConfig_setValue"], ''TextAreaElementConfig)
435+ , (["_selectElementConfig_setValue"], ''SelectElementConfig)
436+ ]
437+#endif
438+
439+-- | This lens is technically illegal. The implementation of 'TextNodeConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'TextNodeConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
440+textNodeConfig_setContents :: Reflex t => Lens' (TextNodeConfig t) (Event t Text)
441+textNodeConfig_setContents =
442+ let getter = fromMaybe never . _textNodeConfig_setContents
443+ setter t e = t { _textNodeConfig_setContents = Just e }
444+ in lens getter setter
445+
446+-- | This lens is technically illegal. The implementation of 'CommentNodeConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'CommentNodeConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
447+commentNodeConfig_setContents :: Reflex t => Lens (CommentNodeConfig t) (CommentNodeConfig t) (Event t Text) (Event t Text)
448+commentNodeConfig_setContents =
449+ let getter = fromMaybe never . _commentNodeConfig_setContents
450+ setter t e = t { _commentNodeConfig_setContents = Just e }
451+ in lens getter setter
452+
453+-- | This lens is technically illegal. The implementation of 'InputElementConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'InputElementConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
454+inputElementConfig_setValue :: Reflex t => Lens' (InputElementConfig er t m) (Event t Text)
455+inputElementConfig_setValue =
456+ let getter = fromMaybe never . _inputElementConfig_setValue
457+ setter t e = t { _inputElementConfig_setValue = Just e }
458+ in lens getter setter
459+
460+-- | This lens is technically illegal. The implementation of 'InputElementConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'InputElementConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
461+inputElementConfig_setChecked :: Reflex t => Lens' (InputElementConfig er t m) (Event t Bool)
462+inputElementConfig_setChecked =
463+ let getter = fromMaybe never . _inputElementConfig_setChecked
464+ setter t e = t { _inputElementConfig_setChecked = Just e }
465+ in lens getter setter
466+
467+-- | This lens is technically illegal. The implementation of 'RawElementConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'RawElementConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
468+rawElementConfig_modifyAttributes :: Reflex t => Lens' (RawElementConfig er t m) (Event t (Map AttributeName (Maybe Text)))
469+rawElementConfig_modifyAttributes =
470+ let getter = fromMaybe never . _rawElementConfig_modifyAttributes
471+ setter t e = t { _rawElementConfig_modifyAttributes = Just e }
472+ in lens getter setter
473+
474+-- | This lens is technically illegal. The implementation of 'RawElementConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'RawElementConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
475+elementConfig_modifyAttributes :: Reflex t => Lens' (ElementConfig er t m) (Event t (Map AttributeName (Maybe Text)))
476+elementConfig_modifyAttributes =
477+ let getter = fromMaybe never . _elementConfig_modifyAttributes
478+ setter t e = t { _elementConfig_modifyAttributes = Just e }
479+ in lens getter setter
480+
481+-- | This lens is technically illegal. The implementation of 'TextAreaElementConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'TextAreaElementConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
482+textAreaElementConfig_setValue :: Reflex t => Lens' (TextAreaElementConfig er t m) (Event t Text)
483+textAreaElementConfig_setValue =
484+ let getter = fromMaybe never . _textAreaElementConfig_setValue
485+ setter t e = t { _textAreaElementConfig_setValue = Just e }
486+ in lens getter setter
487+
488+-- | This lens is technically illegal. The implementation of 'SelectElementConfig' uses a 'Maybe' under the hood for efficiency reasons. However, always interacting with 'SelectElementConfig' via lenses will always behave correctly, and if you pattern match on it, you should always treat 'Nothing' as 'never'.
489+selectElementConfig_setValue :: Reflex t => Lens' (SelectElementConfig er t m) (Event t Text)
490+selectElementConfig_setValue =
491+ let getter = fromMaybe never . _selectElementConfig_setValue
492+ setter t e = t { _selectElementConfig_setValue = Just e }
493+ in lens getter setter
494+
495+class InitialAttributes a where
496+ initialAttributes :: Lens' a (Map AttributeName Text)
497+
498+instance InitialAttributes (ElementConfig er t m) where
499+ {-# INLINABLE initialAttributes #-}
500+ initialAttributes = elementConfig_initialAttributes
501+
502+instance InitialAttributes (InputElementConfig er t m) where
503+ {-# INLINABLE initialAttributes #-}
504+ initialAttributes = inputElementConfig_elementConfig . elementConfig_initialAttributes
505+
506+instance InitialAttributes (TextAreaElementConfig er t m) where
507+ {-# INLINABLE initialAttributes #-}
508+ initialAttributes = textAreaElementConfig_elementConfig . elementConfig_initialAttributes
509+
510+instance InitialAttributes (SelectElementConfig er t m) where
511+ {-# INLINABLE initialAttributes #-}
512+ initialAttributes = selectElementConfig_elementConfig . elementConfig_initialAttributes
513+
514+class ModifyAttributes t a | a -> t where
515+ modifyAttributes :: Reflex t => Lens' a (Event t (Map AttributeName (Maybe Text)))
516+
517+instance ModifyAttributes t (ElementConfig er t m) where
518+ {-# INLINABLE modifyAttributes #-}
519+ modifyAttributes = elementConfig_modifyAttributes
520+
521+instance ModifyAttributes t (InputElementConfig er t m) where
522+ {-# INLINABLE modifyAttributes #-}
523+ modifyAttributes = inputElementConfig_elementConfig . elementConfig_modifyAttributes
524+
525+instance ModifyAttributes t (TextAreaElementConfig er t m) where
526+ {-# INLINABLE modifyAttributes #-}
527+ modifyAttributes = textAreaElementConfig_elementConfig . elementConfig_modifyAttributes
528+
529+instance ModifyAttributes t (SelectElementConfig er t m) where
530+ {-# INLINABLE modifyAttributes #-}
531+ modifyAttributes = selectElementConfig_elementConfig . elementConfig_modifyAttributes
532+
533+instance ModifyAttributes t (RawElementConfig er t m) where
534+ {-# INLINABLE modifyAttributes #-}
535+ modifyAttributes = rawElementConfig_modifyAttributes
536+
537+class HasNamespace a where
538+ namespace :: Lens' a (Maybe Namespace)
539+
540+instance HasNamespace (ElementConfig er t m) where
541+ {-# INLINABLE namespace #-}
542+ namespace = elementConfig_namespace
543+
544+instance (Reflex t, er ~ EventResult, DomSpace s) => Default (ElementConfig er t s) where
545+ {-# INLINABLE def #-}
546+ def = ElementConfig
547+ { _elementConfig_namespace = Nothing
548+ , _elementConfig_initialAttributes = mempty
549+ , _elementConfig_modifyAttributes = Nothing
550+ , _elementConfig_eventSpec = def
551+ }
552+
553+instance (DomBuilder t m, PerformEvent t m, MonadFix m, MonadHold t m) => DomBuilder t (PostBuildT t m) where
554+ type DomBuilderSpace (PostBuildT t m) = DomBuilderSpace m
555+ wrapRawElement e = lift . wrapRawElement e
556+
557+instance (MountableDomBuilder t m, PerformEvent t m, MonadFix m, MonadHold t m) => MountableDomBuilder t (PostBuildT t m) where
558+ type DomFragment (PostBuildT t m) = DomFragment m
559+ buildDomFragment = liftThrough buildDomFragment
560+ mountDomFragment f0 f' = lift $ mountDomFragment f0 f'
561+
562+instance (DomBuilder t m, Monoid w, MonadHold t m, MonadFix m) => DomBuilder t (DynamicWriterT t w m) where
563+ type DomBuilderSpace (DynamicWriterT t w m) = DomBuilderSpace m
564+ textNode = liftTextNode
565+ commentNode = liftCommentNode
566+ element elementTag cfg (DynamicWriterT child) = DynamicWriterT $ do
567+ s <- get
568+ (el, (a, newS)) <- lift $ element elementTag cfg $ runStateT child s
569+ put newS
570+ return (el, a)
571+ inputElement = lift . inputElement
572+ textAreaElement = lift . textAreaElement
573+ selectElement cfg (DynamicWriterT child) = DynamicWriterT $ do
574+ s <- get
575+ (el, (a, newS)) <- lift $ selectElement cfg $ runStateT child s
576+ put newS
577+ return (el, a)
578+ placeRawElement = lift . placeRawElement
579+ wrapRawElement e = lift . wrapRawElement e
580+
581+instance (DomBuilder t m, MonadHold t m, MonadFix m) => DomBuilder t (RequesterT t request response m) where
582+ type DomBuilderSpace (RequesterT t request response m) = DomBuilderSpace m
583+ textNode = liftTextNode
584+ commentNode = liftCommentNode
585+ element elementTag cfg (RequesterT child) = RequesterT $ do
586+ r <- ask
587+ old <- get
588+ (el, (a, new)) <- lift $ lift $ element elementTag cfg $ runReaderT (runStateT child old) r
589+ put new
590+ return (el, a)
591+ inputElement = lift . inputElement
592+ textAreaElement = lift . textAreaElement
593+ selectElement cfg (RequesterT child) = RequesterT $ do
594+ r <- ask
595+ old <- get
596+ (el, (a, new)) <- lift $ lift $ selectElement cfg $ runReaderT (runStateT child old) r
597+ put new
598+ return (el, a)
599+ placeRawElement = lift . placeRawElement
600+ wrapRawElement e = lift . wrapRawElement e
601+
602+instance (DomBuilder t m, MonadHold t m, MonadFix m, Semigroup w) => DomBuilder t (EventWriterT t w m) where
603+ type DomBuilderSpace (EventWriterT t w m) = DomBuilderSpace m
604+ textNode = liftTextNode
605+ commentNode = liftCommentNode
606+ element elementTag cfg (EventWriterT child) = EventWriterT $ do
607+ old <- get
608+ (el, (a, new)) <- lift $ element elementTag cfg $ runStateT child old
609+ put new
610+ return (el, a)
611+ inputElement = lift . inputElement
612+ textAreaElement = lift . textAreaElement
613+ selectElement cfg (EventWriterT child) = EventWriterT $ do
614+ old <- get
615+ (el, (a, new)) <- lift $ selectElement cfg $ runStateT child old
616+ put new
617+ return (el, a)
618+ placeRawElement = lift . placeRawElement
619+ wrapRawElement e = lift . wrapRawElement e
620+
621+instance (DomBuilder t m, MonadFix m, MonadHold t m, Group q, Query q, Additive q, Eq q) => DomBuilder t (QueryT t q m) where
622+ type DomBuilderSpace (QueryT t q m) = DomBuilderSpace m
623+ textNode = liftTextNode
624+ commentNode = liftCommentNode
625+ element elementTag cfg (QueryT child) = QueryT $ do
626+ s <- get
627+ (e, (a, newS)) <- lift $ element elementTag cfg $ runStateT child s
628+ put newS
629+ return (e, a)
630+ inputElement = lift . inputElement
631+ textAreaElement = lift . textAreaElement
632+ selectElement cfg (QueryT child) = QueryT $ do
633+ s <- get
634+ (e, (a, newS)) <- lift $ selectElement cfg $ runStateT child s
635+ put newS
636+ return (e, a)
637+ placeRawElement = lift . placeRawElement
638+ wrapRawElement e = lift . wrapRawElement e
639+
640+-- * Convenience functions
641+
642+class HasDomEvent t target eventName | target -> t where
643+ type DomEventType target eventName :: *
644+ domEvent :: EventName eventName -> target -> Event t (DomEventType target eventName)
645+
646+instance Reflex t => HasDomEvent t (Element EventResult d t) en where
647+ type DomEventType (Element EventResult d t) en = EventResultType en
648+ {-# INLINABLE domEvent #-}
649+ domEvent en e = coerceEvent $ Reflex.select (_element_events e) (WrapArg en)
650+
651+instance Reflex t => HasDomEvent t (InputElement EventResult d t) en where
652+ type DomEventType (InputElement EventResult d t) en = EventResultType en
653+ {-# INLINABLE domEvent #-}
654+ domEvent en = domEvent en . _inputElement_element
655+
656+instance Reflex t => HasDomEvent t (TextAreaElement EventResult d t) en where
657+ type DomEventType (TextAreaElement EventResult d t) en = EventResultType en
658+ {-# INLINABLE domEvent #-}
659+ domEvent en = domEvent en . _textAreaElement_element
660+
661+instance DomBuilder t m => DomBuilder t (ReaderT r m) where
662+ type DomBuilderSpace (ReaderT r m) = DomBuilderSpace m
663+
664+type LiftDomBuilder t f m =
665+ ( Reflex t
666+ , MonadTransControlStateless f
667+ , Monad m
668+ , DomBuilder t m
669+ , DomBuilderSpace (f m) ~ DomBuilderSpace m
670+ )
671+
672+class MonadTransControl t => MonadTransControlStateless t where
673+ stTCoercion :: proxy t -> Coercion (StT t a) a
674+ default stTCoercion :: (a ~ StT t a) => proxy t -> Coercion (StT t a) a
675+ stTCoercion _ = Control.Category.id
676+
677+toStT :: MonadTransControlStateless t => proxy t -> a -> StT t a
678+toStT = coerceWith . sym . stTCoercion
679+
680+fromStT :: MonadTransControlStateless t => proxy t -> StT t a -> a
681+fromStT = coerceWith . stTCoercion
682+
683+instance MonadTransControlStateless (ReaderT r)
684+
685+type RunStateless t = forall n b. Monad n => t n b -> n b
686+
687+liftWithStateless :: forall m t a. (Monad m, MonadTransControlStateless t) => (RunStateless t -> m a) -> t m a
688+liftWithStateless a = liftWith $ \run -> a $ fmap (fromStT (Proxy :: Proxy t)) . run
689+
690+liftTextNode :: (MonadTrans f, DomBuilder t m) => TextNodeConfig t -> f m (TextNode (DomBuilderSpace m) t)
691+liftTextNode = lift . textNode
692+
693+liftCommentNode :: (MonadTrans f, DomBuilder t m) => CommentNodeConfig t -> f m (CommentNode (DomBuilderSpace m) t)
694+liftCommentNode = lift . commentNode
695+
696+liftElement :: LiftDomBuilder t f m => Text -> ElementConfig er t (DomBuilderSpace m) -> f m a -> f m (Element er (DomBuilderSpace m) t, a)
697+liftElement elementTag cfg child = liftWithStateless $ \run -> element elementTag cfg $ run child
698+
699+class (Reflex t, Monad m) => DomRenderHook t m | m -> t where
700+ withRenderHook :: (forall x. JSM x -> JSM x) -> m a -> m a
701+ requestDomAction :: Event t (JSM a) -> m (Event t a)
702+ requestDomAction_ :: Event t (JSM a) -> m ()
703+
704+instance DomRenderHook t m => DomRenderHook t (ReaderT e m) where
705+ withRenderHook hook (ReaderT a) = ReaderT $ \e -> withRenderHook hook $ a e
706+ requestDomAction = lift . requestDomAction
707+ requestDomAction_ = lift . requestDomAction_
708+
709+instance DomRenderHook t m => DomRenderHook t (StateT e m) where
710+ withRenderHook hook (StateT a) = StateT $ \s -> withRenderHook hook $ a s
711+ requestDomAction = lift . requestDomAction
712+ requestDomAction_ = lift . requestDomAction_
713+
714+instance DomRenderHook t m => DomRenderHook t (Lazy.StateT e m) where
715+ withRenderHook hook (Lazy.StateT a) = Lazy.StateT $ \s -> withRenderHook hook $ a s
716+ requestDomAction = lift . requestDomAction
717+ requestDomAction_ = lift . requestDomAction_
718+
719+deriving instance DomRenderHook t m => DomRenderHook t (BehaviorWriterT t w m)
720+deriving instance DomRenderHook t m => DomRenderHook t (EventWriterT t w m)
721+deriving instance DomRenderHook t m => DomRenderHook t (DynamicWriterT t w m)
722+deriving instance DomRenderHook t m => DomRenderHook t (RequesterT t req rsp m)
723+deriving instance DomRenderHook t m => DomRenderHook t (PostBuildT t m)
724+deriving instance DomRenderHook t m => DomRenderHook t (QueryT t q m)
725+
726+{-# DEPRECATED liftElementConfig "Use 'id' instead; this function is no longer necessary" #-}
727+liftElementConfig :: ElementConfig er t s -> ElementConfig er t s
728+liftElementConfig = id
729+
730+class Monad m => HasDocument m where
731+ askDocument :: m (RawDocument (DomBuilderSpace m))
732+ default askDocument
733+ :: ( m ~ f m'
734+ , RawDocument (DomBuilderSpace m) ~ RawDocument (DomBuilderSpace m')
735+ , MonadTrans f
736+ , Monad m'
737+ , HasDocument m'
738+ )
739+ => m (RawDocument (DomBuilderSpace m))
740+ askDocument = lift askDocument
741+
742+instance HasDocument m => HasDocument (ReaderT r m)
743+instance HasDocument m => HasDocument (EventWriterT t w m)
744+instance HasDocument m => HasDocument (DynamicWriterT t w m)
745+instance HasDocument m => HasDocument (PostBuildT t m)
746+instance HasDocument m => HasDocument (RequesterT t request response m)
747+instance HasDocument m => HasDocument (QueryT t q m)
748+
749+class HasSetValue a where
750+ type SetValue a :: *
751+ setValue :: Lens' a (SetValue a)
752+
753+instance Reflex t => HasSetValue (TextAreaElementConfig er t m) where
754+ type SetValue (TextAreaElementConfig er t m) = Event t Text
755+ setValue = textAreaElementConfig_setValue
reflex-dom-core/src/Reflex/Dom/Builder/Class/Events.hsnew file+387
@@ -0,0 +1,387 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE GADTs #-}
4+{-# LANGUAGE PolyKinds #-}
5+#ifdef USE_TEMPLATE_HASKELL
6+{-# LANGUAGE TemplateHaskell #-}
7+#endif
8+{-# LANGUAGE TypeFamilies #-}
9+module Reflex.Dom.Builder.Class.Events where
10+
11+#ifdef USE_TEMPLATE_HASKELL
12+import Data.GADT.Compare.TH
13+#else
14+import Data.GADT.Compare
15+ (GOrdering(..), (:~:)(..), GEq(..), GCompare(..))
16+#endif
17+import Data.Text (Text)
18+
19+data EventTag
20+ = AbortTag
21+ | BlurTag
22+ | ChangeTag
23+ | ClickTag
24+ | ContextmenuTag
25+ | DblclickTag
26+ | DragTag
27+ | DragendTag
28+ | DragenterTag
29+ | DragleaveTag
30+ | DragoverTag
31+ | DragstartTag
32+ | DropTag
33+ | ErrorTag
34+ | FocusTag
35+ | InputTag
36+ | InvalidTag
37+ | KeydownTag
38+ | KeypressTag
39+ | KeyupTag
40+ | LoadTag
41+ | MousedownTag
42+ | MouseenterTag
43+ | MouseleaveTag
44+ | MousemoveTag
45+ | MouseoutTag
46+ | MouseoverTag
47+ | MouseupTag
48+ | MousewheelTag
49+ | ScrollTag
50+ | SelectTag
51+ | SubmitTag
52+ | WheelTag
53+ | BeforecutTag
54+ | CutTag
55+ | BeforecopyTag
56+ | CopyTag
57+ | BeforepasteTag
58+ | PasteTag
59+ | ResetTag
60+ | SearchTag
61+ | SelectstartTag
62+ | TouchstartTag
63+ | TouchmoveTag
64+ | TouchendTag
65+ | TouchcancelTag
66+
67+data EventName :: EventTag -> * where
68+ Abort :: EventName 'AbortTag
69+ Blur :: EventName 'BlurTag
70+ Change :: EventName 'ChangeTag
71+ Click :: EventName 'ClickTag
72+ Contextmenu :: EventName 'ContextmenuTag
73+ Dblclick :: EventName 'DblclickTag
74+ Drag :: EventName 'DragTag
75+ Dragend :: EventName 'DragendTag
76+ Dragenter :: EventName 'DragenterTag
77+ Dragleave :: EventName 'DragleaveTag
78+ Dragover :: EventName 'DragoverTag
79+ Dragstart :: EventName 'DragstartTag
80+ Drop :: EventName 'DropTag
81+ Error :: EventName 'ErrorTag
82+ Focus :: EventName 'FocusTag
83+ Input :: EventName 'InputTag
84+ Invalid :: EventName 'InvalidTag
85+ Keydown :: EventName 'KeydownTag
86+ Keypress :: EventName 'KeypressTag
87+ Keyup :: EventName 'KeyupTag
88+ Load :: EventName 'LoadTag
89+ Mousedown :: EventName 'MousedownTag
90+ Mouseenter :: EventName 'MouseenterTag
91+ Mouseleave :: EventName 'MouseleaveTag
92+ Mousemove :: EventName 'MousemoveTag
93+ Mouseout :: EventName 'MouseoutTag
94+ Mouseover :: EventName 'MouseoverTag
95+ Mouseup :: EventName 'MouseupTag
96+ Mousewheel :: EventName 'MousewheelTag
97+ Scroll :: EventName 'ScrollTag
98+ Select :: EventName 'SelectTag
99+ Submit :: EventName 'SubmitTag
100+ Wheel :: EventName 'WheelTag
101+ Beforecut :: EventName 'BeforecutTag
102+ Cut :: EventName 'CutTag
103+ Beforecopy :: EventName 'BeforecopyTag
104+ Copy :: EventName 'CopyTag
105+ Beforepaste :: EventName 'BeforepasteTag
106+ Paste :: EventName 'PasteTag
107+ Reset :: EventName 'ResetTag
108+ Search :: EventName 'SearchTag
109+ Selectstart :: EventName 'SelectstartTag
110+ Touchstart :: EventName 'TouchstartTag
111+ Touchmove :: EventName 'TouchmoveTag
112+ Touchend :: EventName 'TouchendTag
113+ Touchcancel :: EventName 'TouchcancelTag
114+
115+newtype EventResult en = EventResult { unEventResult :: EventResultType en }
116+
117+type family EventResultType (en :: EventTag) :: * where
118+ EventResultType 'ClickTag = ()
119+ EventResultType 'DblclickTag = (Int, Int)
120+ EventResultType 'KeypressTag = Word
121+ EventResultType 'KeydownTag = Word
122+ EventResultType 'KeyupTag = Word
123+ EventResultType 'ScrollTag = Double
124+ EventResultType 'MousemoveTag = (Int, Int)
125+ EventResultType 'MousedownTag = (Int, Int)
126+ EventResultType 'MouseupTag = (Int, Int)
127+ EventResultType 'MouseenterTag = ()
128+ EventResultType 'MouseleaveTag = ()
129+ EventResultType 'FocusTag = ()
130+ EventResultType 'BlurTag = ()
131+ EventResultType 'ChangeTag = ()
132+ EventResultType 'DragTag = ()
133+ EventResultType 'DragendTag = ()
134+ EventResultType 'DragenterTag = ()
135+ EventResultType 'DragleaveTag = ()
136+ EventResultType 'DragoverTag = ()
137+ EventResultType 'DragstartTag = ()
138+ EventResultType 'DropTag = ()
139+ EventResultType 'AbortTag = ()
140+ EventResultType 'ContextmenuTag = ()
141+ EventResultType 'ErrorTag = ()
142+ EventResultType 'InputTag = ()
143+ EventResultType 'InvalidTag = ()
144+ EventResultType 'LoadTag = ()
145+ EventResultType 'MouseoutTag = ()
146+ EventResultType 'MouseoverTag = ()
147+ EventResultType 'MousewheelTag = ()
148+ EventResultType 'SelectTag = ()
149+ EventResultType 'SubmitTag = ()
150+ EventResultType 'BeforecutTag = ()
151+ EventResultType 'CutTag = ()
152+ EventResultType 'BeforecopyTag = ()
153+ EventResultType 'CopyTag = ()
154+ EventResultType 'BeforepasteTag = ()
155+ EventResultType 'PasteTag = Maybe Text
156+ EventResultType 'ResetTag = ()
157+ EventResultType 'SearchTag = ()
158+ EventResultType 'SelectstartTag = ()
159+ EventResultType 'TouchstartTag = TouchEventResult
160+ EventResultType 'TouchmoveTag = TouchEventResult
161+ EventResultType 'TouchendTag = TouchEventResult
162+ EventResultType 'TouchcancelTag = TouchEventResult
163+ EventResultType 'WheelTag = WheelEventResult
164+
165+data DeltaMode = DeltaPixel | DeltaLine | DeltaPage
166+ deriving (Show, Read, Eq, Ord, Bounded, Enum)
167+
168+data WheelEventResult = WheelEventResult
169+ { _wheelEventResult_deltaX :: Double
170+ , _wheelEventResult_deltaY :: Double
171+ , _wheelEventResult_deltaZ :: Double
172+ , _wheelEventResult_deltaMode :: DeltaMode
173+ } deriving (Show, Read, Eq, Ord)
174+
175+data TouchEventResult = TouchEventResult
176+ { _touchEventResult_altKey :: Bool
177+ , _touchEventResult_changedTouches :: [TouchResult]
178+ , _touchEventResult_ctrlKey :: Bool
179+ , _touchEventResult_metaKey :: Bool
180+ , _touchEventResult_shiftKey :: Bool
181+ , _touchEventResult_targetTouches :: [TouchResult]
182+ , _touchEventResult_touches :: [TouchResult]
183+ }
184+ deriving (Show, Read, Eq, Ord)
185+
186+data TouchResult = TouchResult
187+ { _touchResult_identifier :: Word
188+ , _touchResult_screenX :: Int
189+ , _touchResult_screenY :: Int
190+ , _touchResult_clientX :: Int
191+ , _touchResult_clientY :: Int
192+ , _touchResult_pageX :: Int
193+ , _touchResult_pageY :: Int
194+ }
195+ deriving (Show, Read, Eq, Ord)
196+
197+#ifdef USE_TEMPLATE_HASKELL
198+deriveGEq ''EventName
199+deriveGCompare ''EventName
200+#else
201+instance GEq EventName
202+ where geq Abort Abort = return Refl
203+ geq Blur Blur = return Refl
204+ geq Change Change = return Refl
205+ geq Click Click = return Refl
206+ geq Contextmenu Contextmenu = return Refl
207+ geq Dblclick Dblclick = return Refl
208+ geq Drag Drag = return Refl
209+ geq Dragend Dragend = return Refl
210+ geq Dragenter Dragenter = return Refl
211+ geq Dragleave Dragleave = return Refl
212+ geq Dragover Dragover = return Refl
213+ geq Dragstart Dragstart = return Refl
214+ geq Drop Drop = return Refl
215+ geq Error Error = return Refl
216+ geq Focus Focus = return Refl
217+ geq Input Input = return Refl
218+ geq Invalid Invalid = return Refl
219+ geq Keydown Keydown = return Refl
220+ geq Keypress Keypress = return Refl
221+ geq Keyup Keyup = return Refl
222+ geq Load Load = return Refl
223+ geq Mousedown Mousedown = return Refl
224+ geq Mouseenter Mouseenter = return Refl
225+ geq Mouseleave Mouseleave = return Refl
226+ geq Mousemove Mousemove = return Refl
227+ geq Mouseout Mouseout = return Refl
228+ geq Mouseover Mouseover = return Refl
229+ geq Mouseup Mouseup = return Refl
230+ geq Mousewheel Mousewheel = return Refl
231+ geq Scroll Scroll = return Refl
232+ geq Select Select = return Refl
233+ geq Submit Submit = return Refl
234+ geq Wheel Wheel = return Refl
235+ geq Beforecut Beforecut = return Refl
236+ geq Cut Cut = return Refl
237+ geq Beforecopy Beforecopy = return Refl
238+ geq Copy Copy = return Refl
239+ geq Beforepaste Beforepaste = return Refl
240+ geq Paste Paste = return Refl
241+ geq Reset Reset = return Refl
242+ geq Search Search = return Refl
243+ geq Selectstart Selectstart = return Refl
244+ geq Touchstart Touchstart = return Refl
245+ geq Touchmove Touchmove = return Refl
246+ geq Touchend Touchend = return Refl
247+ geq Touchcancel Touchcancel = return Refl
248+ geq _ _ = Nothing
249+
250+instance GCompare EventName
251+ where gcompare Abort Abort = GEQ
252+ gcompare Abort _ = GLT
253+ gcompare _ Abort = GGT
254+ gcompare Blur Blur = GEQ
255+ gcompare Blur _ = GLT
256+ gcompare _ Blur = GGT
257+ gcompare Change Change = GEQ
258+ gcompare Change _ = GLT
259+ gcompare _ Change = GGT
260+ gcompare Click Click = GEQ
261+ gcompare Click _ = GLT
262+ gcompare _ Click = GGT
263+ gcompare Contextmenu Contextmenu = GEQ
264+ gcompare Contextmenu _ = GLT
265+ gcompare _ Contextmenu = GGT
266+ gcompare Dblclick Dblclick = GEQ
267+ gcompare Dblclick _ = GLT
268+ gcompare _ Dblclick = GGT
269+ gcompare Drag Drag = GEQ
270+ gcompare Drag _ = GLT
271+ gcompare _ Drag = GGT
272+ gcompare Dragend Dragend = GEQ
273+ gcompare Dragend _ = GLT
274+ gcompare _ Dragend = GGT
275+ gcompare Dragenter Dragenter = GEQ
276+ gcompare Dragenter _ = GLT
277+ gcompare _ Dragenter = GGT
278+ gcompare Dragleave Dragleave = GEQ
279+ gcompare Dragleave _ = GLT
280+ gcompare _ Dragleave = GGT
281+ gcompare Dragover Dragover = GEQ
282+ gcompare Dragover _ = GLT
283+ gcompare _ Dragover = GGT
284+ gcompare Dragstart Dragstart = GEQ
285+ gcompare Dragstart _ = GLT
286+ gcompare _ Dragstart = GGT
287+ gcompare Drop Drop = GEQ
288+ gcompare Drop _ = GLT
289+ gcompare _ Drop = GGT
290+ gcompare Error Error = GEQ
291+ gcompare Error _ = GLT
292+ gcompare _ Error = GGT
293+ gcompare Focus Focus = GEQ
294+ gcompare Focus _ = GLT
295+ gcompare _ Focus = GGT
296+ gcompare Input Input = GEQ
297+ gcompare Input _ = GLT
298+ gcompare _ Input = GGT
299+ gcompare Invalid Invalid = GEQ
300+ gcompare Invalid _ = GLT
301+ gcompare _ Invalid = GGT
302+ gcompare Keydown Keydown = GEQ
303+ gcompare Keydown _ = GLT
304+ gcompare _ Keydown = GGT
305+ gcompare Keypress Keypress = GEQ
306+ gcompare Keypress _ = GLT
307+ gcompare _ Keypress = GGT
308+ gcompare Keyup Keyup = GEQ
309+ gcompare Keyup _ = GLT
310+ gcompare _ Keyup = GGT
311+ gcompare Load Load = GEQ
312+ gcompare Load _ = GLT
313+ gcompare _ Load = GGT
314+ gcompare Mousedown Mousedown = GEQ
315+ gcompare Mousedown _ = GLT
316+ gcompare _ Mousedown = GGT
317+ gcompare Mouseenter Mouseenter = GEQ
318+ gcompare Mouseenter _ = GLT
319+ gcompare _ Mouseenter = GGT
320+ gcompare Mouseleave Mouseleave = GEQ
321+ gcompare Mouseleave _ = GLT
322+ gcompare _ Mouseleave = GGT
323+ gcompare Mousemove Mousemove = GEQ
324+ gcompare Mousemove _ = GLT
325+ gcompare _ Mousemove = GGT
326+ gcompare Mouseout Mouseout = GEQ
327+ gcompare Mouseout _ = GLT
328+ gcompare _ Mouseout = GGT
329+ gcompare Mouseover Mouseover = GEQ
330+ gcompare Mouseover _ = GLT
331+ gcompare _ Mouseover = GGT
332+ gcompare Mouseup Mouseup = GEQ
333+ gcompare Mouseup _ = GLT
334+ gcompare _ Mouseup = GGT
335+ gcompare Mousewheel Mousewheel = GEQ
336+ gcompare Mousewheel _ = GLT
337+ gcompare _ Mousewheel = GGT
338+ gcompare Scroll Scroll = GEQ
339+ gcompare Scroll _ = GLT
340+ gcompare _ Scroll = GGT
341+ gcompare Select Select = GEQ
342+ gcompare Select _ = GLT
343+ gcompare _ Select = GGT
344+ gcompare Submit Submit = GEQ
345+ gcompare Submit _ = GLT
346+ gcompare _ Submit = GGT
347+ gcompare Wheel Wheel = GEQ
348+ gcompare Wheel _ = GLT
349+ gcompare _ Wheel = GGT
350+ gcompare Beforecut Beforecut = GEQ
351+ gcompare Beforecut _ = GLT
352+ gcompare _ Beforecut = GGT
353+ gcompare Cut Cut = GEQ
354+ gcompare Cut _ = GLT
355+ gcompare _ Cut = GGT
356+ gcompare Beforecopy Beforecopy = GEQ
357+ gcompare Beforecopy _ = GLT
358+ gcompare _ Beforecopy = GGT
359+ gcompare Copy Copy = GEQ
360+ gcompare Copy _ = GLT
361+ gcompare _ Copy = GGT
362+ gcompare Beforepaste Beforepaste = GEQ
363+ gcompare Beforepaste _ = GLT
364+ gcompare _ Beforepaste = GGT
365+ gcompare Paste Paste = GEQ
366+ gcompare Paste _ = GLT
367+ gcompare _ Paste = GGT
368+ gcompare Reset Reset = GEQ
369+ gcompare Reset _ = GLT
370+ gcompare _ Reset = GGT
371+ gcompare Search Search = GEQ
372+ gcompare Search _ = GLT
373+ gcompare _ Search = GGT
374+ gcompare Selectstart Selectstart = GEQ
375+ gcompare Selectstart _ = GLT
376+ gcompare _ Selectstart = GGT
377+ gcompare Touchstart Touchstart = GEQ
378+ gcompare Touchstart _ = GLT
379+ gcompare _ Touchstart = GGT
380+ gcompare Touchmove Touchmove = GEQ
381+ gcompare Touchmove _ = GLT
382+ gcompare _ Touchmove = GGT
383+ gcompare Touchend Touchend = GEQ
384+ gcompare Touchend _ = GLT
385+ gcompare _ Touchend = GGT
386+ gcompare Touchcancel Touchcancel = GEQ
387+#endif
reflex-dom-core/src/Reflex/Dom/Builder/Class/TH.hsnew file+12
@@ -0,0 +1,12 @@
1+module Reflex.Dom.Builder.Class.TH where
2+
3+import Control.Lens
4+import Language.Haskell.TH.Lib (DecsQ)
5+import Language.Haskell.TH.Syntax (Name, nameBase)
6+
7+namer :: [String] -> Name -> [Name] -> Name -> [DefName]
8+namer s n ks t | nameBase t `elem` s = []
9+ | otherwise = underscoreNoPrefixNamer n ks t
10+
11+makeLensesWithoutField :: [String] -> Name -> DecsQ
12+makeLensesWithoutField s = makeLensesWith (lensRules & lensField .~ namer s)
reflex-dom-core/src/Reflex/Dom/Builder/Hydratable.hsnew file+116
@@ -0,0 +1,116 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE OverloadedStrings #-}
6+{-# LANGUAGE StandaloneDeriving #-}
7+{-# LANGUAGE TypeFamilies #-}
8+{-# LANGUAGE UndecidableInstances #-}
9+module Reflex.Dom.Builder.Hydratable where
10+
11+import Control.Monad.Fix
12+import Control.Monad.Primitive
13+import Control.Monad.Ref
14+import Control.Monad.Trans
15+import Control.Monad.Trans.Control
16+import Data.Coerce
17+import qualified Data.Map as Map
18+import Foreign.JavaScript.TH
19+#ifndef ghcjs_HOST_OS
20+import GHCJS.DOM.Types (MonadJSM (..))
21+#endif
22+import Reflex
23+import Reflex.Dom.Builder.Class
24+import Reflex.Dom.Builder.Immediate (HasDocument (..), hydratableAttribute)
25+import Reflex.Host.Class
26+
27+-- | A DomBuilder transformer that adds an attribute to all elements such that the
28+-- hydration builder knows which bits of DOM were added by us, and which were
29+-- added by external scripts.
30+newtype HydratableT m a = HydratableT { runHydratableT :: m a } deriving (Functor, Applicative, Monad, MonadAtomicRef, MonadFix, MonadIO)
31+
32+#ifndef ghcjs_HOST_OS
33+instance MonadJSM m => MonadJSM (HydratableT m) where
34+ liftJSM' = HydratableT . liftJSM'
35+#endif
36+
37+deriving instance MonadSample t m => MonadSample t (HydratableT m)
38+deriving instance MonadHold t m => MonadHold t (HydratableT m)
39+
40+instance MonadTrans HydratableT where
41+ lift = HydratableT
42+
43+instance MonadTransControl HydratableT where
44+ type StT HydratableT a = a
45+ liftWith f = HydratableT $ f runHydratableT
46+ restoreT = HydratableT
47+
48+instance MonadRef m => MonadRef (HydratableT m) where
49+ type Ref (HydratableT m) = Ref m
50+ newRef = lift . newRef
51+ readRef = lift . readRef
52+ writeRef ref = lift . writeRef ref
53+
54+instance PerformEvent t m => PerformEvent t (HydratableT m) where
55+ type Performable (HydratableT m) = Performable m
56+ performEvent_ = lift . performEvent_
57+ performEvent = lift . performEvent
58+
59+instance PrimMonad m => PrimMonad (HydratableT m) where
60+ type PrimState (HydratableT m) = PrimState m
61+ primitive = lift . primitive
62+
63+makeHydratable :: Reflex t => ElementConfig er t m -> ElementConfig er t m
64+makeHydratable cfg = cfg
65+ { _elementConfig_initialAttributes = Map.insert hydratableAttribute "" $ _elementConfig_initialAttributes cfg
66+ , _elementConfig_modifyAttributes = fmap (Map.delete hydratableAttribute) <$> _elementConfig_modifyAttributes cfg
67+ }
68+
69+instance PostBuild t m => PostBuild t (HydratableT m) where
70+ getPostBuild = lift getPostBuild
71+
72+deriving instance TriggerEvent t m => TriggerEvent t (HydratableT m)
73+
74+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (HydratableT m) where
75+ newEventWithTrigger = lift . newEventWithTrigger
76+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
77+
78+instance Adjustable t m => Adjustable t (HydratableT m) where
79+ runWithReplace a0 a' = HydratableT $ runWithReplace (coerce a0) (coerceEvent a')
80+ traverseDMapWithKeyWithAdjust f dm0 dm' = HydratableT $ traverseDMapWithKeyWithAdjust (\k v -> runHydratableT $ f k v) (coerce dm0) (coerceEvent dm')
81+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = HydratableT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> runHydratableT $ f k v) (coerce dm0) (coerceEvent dm')
82+ traverseIntMapWithKeyWithAdjust f m0 m' = HydratableT $ traverseIntMapWithKeyWithAdjust (\k v -> runHydratableT $ f k v) (coerce m0) (coerceEvent m')
83+
84+instance NotReady t m => NotReady t (HydratableT m) where
85+ notReadyUntil = lift . notReadyUntil
86+ notReady = lift notReady
87+
88+instance DomBuilder t m => DomBuilder t (HydratableT m) where
89+ type DomBuilderSpace (HydratableT m) = DomBuilderSpace m
90+ element t cfg = lift . element t (makeHydratable cfg) . runHydratableT
91+ inputElement cfg = lift $ inputElement $ cfg
92+ { _inputElementConfig_elementConfig = makeHydratable $ _inputElementConfig_elementConfig cfg
93+ }
94+ textAreaElement cfg = lift $ textAreaElement $ cfg
95+ { _textAreaElementConfig_elementConfig = makeHydratable $ _textAreaElementConfig_elementConfig cfg
96+ }
97+ selectElement cfg child = do
98+ let cfg' = cfg
99+ { _selectElementConfig_elementConfig = makeHydratable $ _selectElementConfig_elementConfig cfg
100+ }
101+ lift $ selectElement cfg' $ runHydratableT child
102+
103+instance HasDocument m => HasDocument (HydratableT m)
104+
105+instance HasJSContext m => HasJSContext (HydratableT m) where
106+ type JSContextPhantom (HydratableT m) = JSContextPhantom m
107+ askJSContext = lift askJSContext
108+
109+instance HasJS js m => HasJS js (HydratableT m) where
110+ type JSX (HydratableT m) = JSX m
111+ liftJS = lift . liftJS
112+
113+instance DomRenderHook t m => DomRenderHook t (HydratableT m) where
114+ withRenderHook f = HydratableT . withRenderHook f . runHydratableT
115+ requestDomAction = HydratableT . requestDomAction
116+ requestDomAction_ = HydratableT . requestDomAction_
reflex-dom-core/src/Reflex/Dom/Builder/Immediate.hsnew file+2733
@@ -0,0 +1,2733 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE DataKinds #-}
5+{-# LANGUAGE DeriveTraversable #-}
6+{-# LANGUAGE EmptyDataDecls #-}
7+{-# LANGUAGE FlexibleContexts #-}
8+{-# LANGUAGE FlexibleInstances #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE LambdaCase #-}
12+{-# LANGUAGE MultiParamTypeClasses #-}
13+{-# LANGUAGE OverloadedStrings #-}
14+{-# LANGUAGE PatternGuards #-}
15+{-# LANGUAGE PolyKinds #-}
16+{-# LANGUAGE RankNTypes #-}
17+{-# LANGUAGE RecursiveDo #-}
18+{-# LANGUAGE ScopedTypeVariables #-}
19+#ifdef USE_TEMPLATE_HASKELL
20+{-# LANGUAGE TemplateHaskell #-}
21+#endif
22+{-# LANGUAGE TupleSections #-}
23+{-# LANGUAGE TypeFamilies #-}
24+{-# LANGUAGE TypeOperators #-}
25+{-# LANGUAGE UndecidableInstances #-}
26+#ifdef ghcjs_HOST_OS
27+{-# LANGUAGE ForeignFunctionInterface #-}
28+{-# LANGUAGE JavaScriptFFI #-}
29+#endif
30+-- | This is a builder to be used on the client side. It can be run in two modes:
31+--
32+-- 1. in "hydration mode", reusing DOM nodes already in the page (as produced
33+-- by 'Reflex.Dom.Builder.Static.renderStatic')
34+-- 2. in "immediate mode", creating and appending DOM nodes as required
35+--
36+-- In "hydration mode", the preexisting DOM __must contain__ what the builder
37+-- will expect at switchover time (the time at which parity with the static
38+-- renderer is reached, and the time after which the page is "live").
39+--
40+-- For example, displaying the current time as text should be done inside
41+-- 'Reflex.Dom.Prerender.prerender' to ensure that we don't attempt to hydrate the incorrect text.
42+-- The server will prerender a text node with time A, and the client will expect
43+-- a text node with time B. Barring a miracle, time A and time B will not match,
44+-- and hydration will fail.
45+module Reflex.Dom.Builder.Immediate
46+ ( HydrationDomBuilderT (..)
47+ , HydrationDomBuilderEnv (..)
48+ , HydrationMode (..)
49+ , HydrationRunnerT (..)
50+ , runHydrationRunnerT
51+ , runHydrationRunnerTWithFailure
52+ , ImmediateDomBuilderT
53+ , runHydrationDomBuilderT
54+ , getHydrationMode
55+ , addHydrationStep
56+ , addHydrationStepWithSetup
57+ , setPreviousNode
58+ , insertAfterPreviousNode
59+ , hydrateComment
60+ , askParent
61+ , askEvents
62+ , append
63+ , textNodeInternal
64+ , removeSubsequentNodes
65+ , deleteBetweenExclusive
66+ , extractBetweenExclusive
67+ , deleteUpTo
68+ , extractUpTo
69+ , SupportsHydrationDomBuilder
70+ , collectUpTo
71+ , collectUpToGivenParent
72+ , EventTriggerRef (..)
73+ , EventFilterTriggerRef (..)
74+ , wrap
75+ , elementInternal
76+ , HydrationDomSpace
77+ , GhcjsDomSpace
78+ , GhcjsDomHandler (..)
79+ , GhcjsDomHandler1 (..)
80+ , GhcjsDomEvent (..)
81+ , GhcjsEventFilter (..)
82+ , Pair1 (..)
83+ , Maybe1 (..)
84+ , GhcjsEventSpec (..)
85+ , HasDocument (..)
86+ , ghcjsEventSpec_filters
87+ , ghcjsEventSpec_handler
88+ , GhcjsEventHandler (..)
89+ , drawChildUpdate
90+ , ChildReadyState (..)
91+ , mkHasFocus
92+ , insertBefore
93+ , EventType
94+ , defaultDomEventHandler
95+ , defaultDomWindowEventHandler
96+ , withIsEvent
97+ , showEventName
98+ , elementOnEventName
99+ , windowOnEventName
100+ , wrapDomEvent
101+ , subscribeDomEvent
102+ , wrapDomEventMaybe
103+ , wrapDomEventsMaybe
104+ , getKeyEvent
105+ , getMouseEventCoords
106+ , getTouchEvent
107+ , WindowConfig (..)
108+ , Window (..)
109+ , wrapWindow
110+ -- * Attributes for controlling hydration
111+ , hydratableAttribute
112+ , skipHydrationAttribute
113+ -- * Internal
114+ , traverseDMapWithKeyWithAdjust'
115+ , hoistTraverseWithKeyWithAdjust
116+ , traverseIntMapWithKeyWithAdjust'
117+ , hoistTraverseIntMapWithKeyWithAdjust
118+ ) where
119+
120+import Control.Concurrent
121+import Control.Exception (bracketOnError)
122+import Control.Lens (Identity(..), imapM_, iforM_, (^.), makeLenses)
123+import Control.Monad.Exception
124+import Control.Monad.Primitive
125+import Control.Monad.Reader
126+import Control.Monad.Ref
127+import Control.Monad.State.Strict (StateT, mapStateT, get, modify', gets, runStateT)
128+import Data.Bitraversable
129+import Data.Default
130+import Data.Dependent.Map (DMap)
131+import Data.Dependent.Sum
132+import Data.FastMutableIntMap (PatchIntMap (..))
133+import Data.Foldable (for_, traverse_)
134+import Data.Functor.Compose
135+import Data.Functor.Constant
136+import Data.Functor.Misc
137+import Data.Functor.Product
138+import Data.GADT.Compare (GCompare)
139+import Data.IORef
140+import Data.IntMap.Strict (IntMap)
141+import Data.Maybe
142+import Data.Monoid ((<>))
143+import Data.Some (Some(..))
144+import Data.GADT.Compare (GCompare)
145+import Data.String (IsString)
146+import Data.Text (Text)
147+import Foreign.JavaScript.Internal.Utils
148+import Foreign.JavaScript.TH
149+import GHCJS.DOM.ClipboardEvent as ClipboardEvent
150+import GHCJS.DOM.Document (Document, createDocumentFragment, createElement, createElementNS, createTextNode, createComment)
151+import GHCJS.DOM.Element (getScrollTop, removeAttribute, removeAttributeNS, setAttribute, setAttributeNS, hasAttribute)
152+import GHCJS.DOM.EventM (EventM, event, on)
153+import GHCJS.DOM.KeyboardEvent as KeyboardEvent
154+import GHCJS.DOM.MouseEvent
155+import GHCJS.DOM.Node (appendChild_, getOwnerDocumentUnchecked, getParentNodeUnchecked, setNodeValue, toNode)
156+import GHCJS.DOM.Types (liftJSM, askJSM, runJSM, JSM, MonadJSM, FocusEvent, IsElement, IsEvent, IsNode, KeyboardEvent, Node, TouchEvent, WheelEvent, uncheckedCastTo, ClipboardEvent)
157+import GHCJS.DOM.UIEvent
158+import Language.Javascript.JSaddle (call, eval)
159+import Reflex.Adjustable.Class
160+import Reflex.Class as Reflex
161+import Reflex.Dom.Builder.Class
162+import Reflex.Dynamic
163+import Reflex.Host.Class
164+import Reflex.Patch.DMapWithMove (PatchDMapWithMove(..))
165+import Reflex.Patch.MapWithMove (PatchMapWithMove(..))
166+import Reflex.PerformEvent.Base (PerformEventT)
167+import Reflex.PerformEvent.Class
168+import Reflex.PostBuild.Base (PostBuildT)
169+import Reflex.PostBuild.Class
170+#ifdef PROFILE_REFLEX
171+import Reflex.Profiled
172+#endif
173+import Reflex.Requester.Base
174+import Reflex.Requester.Class
175+import Reflex.Spider (Spider, SpiderHost, Global)
176+import Reflex.TriggerEvent.Base hiding (askEvents)
177+import Reflex.TriggerEvent.Class
178+
179+import qualified Data.Dependent.Map as DMap
180+import qualified Data.FastMutableIntMap as FastMutableIntMap
181+import qualified Data.IntMap.Strict as IntMap
182+import qualified Data.Map as Map
183+import qualified Data.Text as T
184+import qualified GHCJS.DOM as DOM
185+import qualified GHCJS.DOM.DataTransfer as DataTransfer
186+import qualified GHCJS.DOM.DocumentAndElementEventHandlers as Events
187+import qualified GHCJS.DOM.DocumentOrShadowRoot as Document
188+import qualified GHCJS.DOM.Element as Element
189+import qualified GHCJS.DOM.Event as Event
190+import qualified GHCJS.DOM.EventM as DOM
191+import qualified GHCJS.DOM.FileList as FileList
192+import qualified GHCJS.DOM.GlobalEventHandlers as Events
193+import qualified GHCJS.DOM.HTMLInputElement as Input
194+import qualified GHCJS.DOM.HTMLSelectElement as Select
195+import qualified GHCJS.DOM.HTMLTextAreaElement as TextArea
196+import qualified GHCJS.DOM.Node as Node
197+import qualified GHCJS.DOM.Text as DOM
198+import qualified GHCJS.DOM.Touch as Touch
199+import qualified GHCJS.DOM.TouchEvent as TouchEvent
200+import qualified GHCJS.DOM.TouchList as TouchList
201+import qualified GHCJS.DOM.Types as DOM
202+import qualified GHCJS.DOM.Window as Window
203+import qualified GHCJS.DOM.WheelEvent as WheelEvent
204+import qualified Reflex.Patch.DMap as PatchDMap
205+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
206+import qualified Reflex.Patch.MapWithMove as PatchMapWithMove
207+import qualified Reflex.TriggerEvent.Base as TriggerEventT (askEvents)
208+
209+#ifndef USE_TEMPLATE_HASKELL
210+import Data.Functor.Contravariant (phantom)
211+import Control.Lens (Lens', Getter)
212+#endif
213+
214+#ifndef ghcjs_HOST_OS
215+import GHCJS.DOM.Types (MonadJSM (..))
216+
217+instance MonadJSM m => MonadJSM (HydrationRunnerT t m) where
218+ {-# INLINABLE liftJSM' #-}
219+ liftJSM' = lift . liftJSM'
220+
221+instance MonadJSM m => MonadJSM (HydrationDomBuilderT s t m) where
222+ {-# INLINABLE liftJSM' #-}
223+ liftJSM' = lift . liftJSM'
224+
225+instance MonadJSM m => MonadJSM (DomRenderHookT t m) where
226+ {-# INLINABLE liftJSM' #-}
227+ liftJSM' = lift . liftJSM'
228+#endif
229+
230+data HydrationDomBuilderEnv t m = HydrationDomBuilderEnv
231+ { _hydrationDomBuilderEnv_document :: {-# UNPACK #-} !Document
232+ -- ^ Reference to the document
233+ , _hydrationDomBuilderEnv_parent :: !(Either Node (IORef Node))
234+ -- ^ This is in an IORef because in the time up to hydration we can't actually know what the
235+ -- parent is - we populate this reference during the DOM traversal at hydration time
236+ , _hydrationDomBuilderEnv_unreadyChildren :: {-# UNPACK #-} !(IORef Word)
237+ -- ^ Number of children who still aren't fully rendered
238+ , _hydrationDomBuilderEnv_commitAction :: !(JSM ())
239+ -- ^ Action to take when all children are ready --TODO: we should probably get rid of this once we invoke it
240+ , _hydrationDomBuilderEnv_hydrationMode :: {-# UNPACK #-} !(IORef HydrationMode)
241+ -- ^ In hydration mode? Should be switched to `HydrationMode_Immediate` after hydration is finished
242+ , _hydrationDomBuilderEnv_switchover :: !(Event t ())
243+ , _hydrationDomBuilderEnv_delayed :: {-# UNPACK #-} !(IORef (HydrationRunnerT t m ()))
244+ }
245+
246+-- | A monad for DomBuilder which just gets the results of children and pushes
247+-- work into an action that is delayed until after postBuild (to match the
248+-- static builder). The action runs in 'HydrationRunnerT', which performs the
249+-- DOM takeover and sets up the events, after which point this monad will
250+-- continue in the vein of 'ImmediateDomBuilderT'.
251+newtype HydrationDomBuilderT s t m a = HydrationDomBuilderT { unHydrationDomBuilderT :: ReaderT (HydrationDomBuilderEnv t m) (DomRenderHookT t m) a }
252+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
253+#if MIN_VERSION_base(4,9,1)
254+ , MonadAsyncException
255+#endif
256+ )
257+
258+instance PrimMonad m => PrimMonad (HydrationDomBuilderT s t m) where
259+ type PrimState (HydrationDomBuilderT s t m) = PrimState m
260+ primitive = lift . primitive
261+
262+instance MonadTrans (HydrationDomBuilderT s t) where
263+ lift = HydrationDomBuilderT . lift . lift
264+
265+instance (Reflex t, MonadFix m) => DomRenderHook t (HydrationDomBuilderT s t m) where
266+ withRenderHook hook = HydrationDomBuilderT . mapReaderT (withRenderHook hook) . unHydrationDomBuilderT
267+ requestDomAction = HydrationDomBuilderT . lift . requestDomAction
268+ requestDomAction_ = HydrationDomBuilderT . lift . requestDomAction_
269+
270+-- | The monad which performs the delayed actions to reuse prerendered nodes and set up events.
271+-- State contains reference to the previous node sibling, if any, and the reader contains reference to the parent node.
272+newtype HydrationRunnerT t m a = HydrationRunnerT { unHydrationRunnerT :: StateT HydrationState (ReaderT Node (DomRenderHookT t m)) a }
273+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
274+#if MIN_VERSION_base(4,9,1)
275+ , MonadAsyncException
276+#endif
277+ )
278+
279+data HydrationState = HydrationState
280+ { _hydrationState_previousNode :: !(Maybe Node)
281+ , _hydrationState_failed :: !Bool
282+ }
283+
284+{-# INLINABLE localRunner #-}
285+localRunner :: (MonadJSM m, Monad m) => HydrationRunnerT t m a -> Maybe Node -> Node -> HydrationRunnerT t m a
286+localRunner (HydrationRunnerT m) s parent = do
287+ s0 <- HydrationRunnerT get
288+ (a, s') <- HydrationRunnerT $ lift $ local (\_ -> parent) $ runStateT m (s0 { _hydrationState_previousNode = s })
289+ traverse_ removeSubsequentNodes $ _hydrationState_previousNode s'
290+ HydrationRunnerT $ modify' $ \hs -> hs { _hydrationState_failed = _hydrationState_failed s' }
291+ pure a
292+
293+{-# INLINABLE runHydrationRunnerT #-}
294+runHydrationRunnerT
295+ :: (MonadRef m, Ref m ~ IORef, Monad m, PerformEvent t m, MonadFix m, MonadReflexCreateTrigger t m, MonadJSM m, MonadJSM (Performable m))
296+ => HydrationRunnerT t m a -> Maybe Node -> Node -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a
297+runHydrationRunnerT m = runHydrationRunnerTWithFailure m (pure ())
298+
299+{-# INLINABLE runHydrationRunnerTWithFailure #-}
300+runHydrationRunnerTWithFailure
301+ :: (MonadRef m, Ref m ~ IORef, Monad m, PerformEvent t m, MonadFix m, MonadReflexCreateTrigger t m, MonadJSM m, MonadJSM (Performable m))
302+ => HydrationRunnerT t m a -> IO () -> Maybe Node -> Node -> Chan [DSum (EventTriggerRef t) TriggerInvocation] -> m a
303+runHydrationRunnerTWithFailure (HydrationRunnerT m) onFailure s parent events = flip runDomRenderHookT events $ flip runReaderT parent $ do
304+ (a, s') <- runStateT m (HydrationState s False)
305+ traverse_ removeSubsequentNodes $ _hydrationState_previousNode s'
306+ when (_hydrationState_failed s') $ liftIO $ putStrLn "reflex-dom warning: hydration failed: the DOM was not as expected at switchover time. This may be due to invalid HTML which the browser has altered upon parsing, some external JS altering the DOM, or the page being served from an outdated cache."
307+ when (_hydrationState_failed s') $ liftIO onFailure
308+ pure a
309+
310+
311+
312+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (HydrationRunnerT t m) where
313+ {-# INLINABLE newEventWithTrigger #-}
314+ newEventWithTrigger = lift . newEventWithTrigger
315+ {-# INLINABLE newFanEventWithTrigger #-}
316+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
317+
318+instance MonadTrans (HydrationRunnerT t) where
319+ {-# INLINABLE lift #-}
320+ lift = HydrationRunnerT . lift . lift . lift
321+
322+instance MonadSample t m => MonadSample t (HydrationRunnerT t m) where
323+ {-# INLINABLE sample #-}
324+ sample = lift . sample
325+
326+instance (Reflex t, MonadFix m) => DomRenderHook t (HydrationRunnerT t m) where
327+ withRenderHook hook = HydrationRunnerT . mapStateT (mapReaderT (withRenderHook hook)) . unHydrationRunnerT
328+ requestDomAction = HydrationRunnerT . lift . lift . requestDomAction
329+ requestDomAction_ = HydrationRunnerT . lift . lift . requestDomAction_
330+
331+-- | Add a hydration step which depends on some computation that should only be
332+-- done *before* the switchover to immediate mode - this is most likely some
333+-- form of 'hold' which we want to remove after hydration is done
334+{-# INLINABLE addHydrationStepWithSetup #-}
335+addHydrationStepWithSetup :: MonadIO m => m a -> (a -> HydrationRunnerT t m ()) -> HydrationDomBuilderT s t m ()
336+addHydrationStepWithSetup setup f = getHydrationMode >>= \case
337+ HydrationMode_Immediate -> pure ()
338+ HydrationMode_Hydrating -> do
339+ s <- lift setup
340+ addHydrationStep (f s)
341+
342+-- | Add a hydration step
343+{-# INLINABLE addHydrationStep #-}
344+addHydrationStep :: MonadIO m => HydrationRunnerT t m () -> HydrationDomBuilderT s t m ()
345+addHydrationStep m = do
346+ delayedRef <- HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_delayed
347+ liftIO $ modifyIORef' delayedRef (>> m)
348+
349+-- | Shared behavior for HydrationDomBuilderT and HydrationRunnerT
350+newtype DomRenderHookT t m a = DomRenderHookT { unDomRenderHookT :: RequesterT t JSM Identity (TriggerEventT t m) a }
351+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException
352+#if MIN_VERSION_base(4,9,1)
353+ , MonadAsyncException
354+#endif
355+ )
356+
357+{-# INLINABLE runDomRenderHookT #-}
358+runDomRenderHookT
359+ :: (MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadJSM m, MonadJSM (Performable m), MonadRef m, Ref m ~ IORef)
360+ => DomRenderHookT t m a
361+ -> Chan [DSum (EventTriggerRef t) TriggerInvocation]
362+ -> m a
363+runDomRenderHookT (DomRenderHookT a) events = do
364+ flip runTriggerEventT events $ do
365+ rec (result, req) <- runRequesterT a rsp
366+ rsp <- performEventAsync $ ffor req $ \rm f -> liftJSM $ runInAnimationFrame f $
367+ traverseRequesterData (fmap Identity) rm
368+ return result
369+ where
370+ runInAnimationFrame f x = void . DOM.inAnimationFrame' $ \_ -> do
371+ v <- synchronously x
372+ void . liftIO $ f v
373+
374+instance MonadTrans (DomRenderHookT t) where
375+ {-# INLINABLE lift #-}
376+ lift = DomRenderHookT . lift . lift
377+
378+instance (Reflex t, MonadFix m) => DomRenderHook t (DomRenderHookT t m) where
379+ withRenderHook hook (DomRenderHookT a) = do
380+ DomRenderHookT $ withRequesting $ \rsp -> do
381+ (x, req) <- lift $ runRequesterT a $ runIdentity <$> rsp
382+ return (ffor req $ \rm -> hook $ traverseRequesterData (fmap Identity) rm, x)
383+ requestDomAction = DomRenderHookT . requestingIdentity
384+ requestDomAction_ = DomRenderHookT . requesting_
385+
386+{-# INLINABLE runHydrationDomBuilderT #-}
387+runHydrationDomBuilderT
388+ :: ( MonadFix m
389+ , PerformEvent t m
390+ , MonadReflexCreateTrigger t m
391+ , MonadJSM m
392+ , MonadJSM (Performable m)
393+ , MonadRef m
394+ , Ref m ~ IORef
395+ )
396+ => HydrationDomBuilderT s t m a
397+ -> HydrationDomBuilderEnv t m
398+ -> Chan [DSum (EventTriggerRef t) TriggerInvocation]
399+ -> m a
400+runHydrationDomBuilderT (HydrationDomBuilderT a) env = runDomRenderHookT (runReaderT a env)
401+
402+instance (RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, Monad m) => HasDocument (HydrationDomBuilderT s t m) where
403+ {-# INLINABLE askDocument #-}
404+ askDocument = HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_document
405+
406+{-# INLINABLE askParent #-}
407+askParent :: Monad m => HydrationRunnerT t m DOM.Node
408+askParent = HydrationRunnerT ask
409+
410+{-# INLINABLE getParent #-}
411+getParent :: MonadIO m => HydrationDomBuilderT s t m DOM.Node
412+getParent = either pure (liftIO . readIORef) =<< HydrationDomBuilderT (asks _hydrationDomBuilderEnv_parent)
413+
414+{-# INLINABLE askEvents #-}
415+askEvents :: Monad m => HydrationDomBuilderT s t m (Chan [DSum (EventTriggerRef t) TriggerInvocation])
416+askEvents = HydrationDomBuilderT . lift . DomRenderHookT . lift $ TriggerEventT.askEvents
417+
418+{-# INLINABLE localEnv #-}
419+localEnv :: Monad m => (HydrationDomBuilderEnv t m -> HydrationDomBuilderEnv t m) -> HydrationDomBuilderT s t m a -> HydrationDomBuilderT s t m a
420+localEnv f = HydrationDomBuilderT . local (f $!) . unHydrationDomBuilderT
421+
422+{-# INLINABLE append #-}
423+append :: MonadJSM m => DOM.Node -> HydrationDomBuilderT s t m ()
424+append n = do
425+ p <- getParent
426+ liftJSM $ appendChild_ p n
427+ return ()
428+
429+{-# SPECIALIZE append
430+ :: DOM.Node
431+ -> HydrationDomBuilderT s Spider HydrationM ()
432+ #-}
433+
434+data HydrationMode
435+ = HydrationMode_Hydrating
436+ -- ^ The time from initial load to parity with static builder
437+ | HydrationMode_Immediate
438+ -- ^ After hydration
439+ deriving (Eq, Ord, Show)
440+
441+{-# INLINABLE getPreviousNode #-}
442+getPreviousNode :: Monad m => HydrationRunnerT t m (Maybe DOM.Node)
443+getPreviousNode = HydrationRunnerT $ gets _hydrationState_previousNode
444+
445+{-# INLINABLE setPreviousNode #-}
446+setPreviousNode :: Monad m => Maybe DOM.Node -> HydrationRunnerT t m ()
447+setPreviousNode n = HydrationRunnerT $ modify' (\hs -> hs { _hydrationState_previousNode = n })
448+
449+{-# INLINABLE askUnreadyChildren #-}
450+askUnreadyChildren :: Monad m => HydrationDomBuilderT s t m (IORef Word)
451+askUnreadyChildren = HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_unreadyChildren
452+
453+{-# INLINABLE askCommitAction #-}
454+askCommitAction :: Monad m => HydrationDomBuilderT s t m (JSM ())
455+askCommitAction = HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_commitAction
456+
457+{-# INLINABLE getHydrationMode #-}
458+getHydrationMode :: MonadIO m => HydrationDomBuilderT s t m HydrationMode
459+getHydrationMode = liftIO . readIORef =<< HydrationDomBuilderT (asks _hydrationDomBuilderEnv_hydrationMode)
460+
461+-- | Remove all nodes after given node
462+removeSubsequentNodes :: (MonadJSM m, IsNode n) => n -> m ()
463+removeSubsequentNodes n = liftJSM $ do
464+ f <- eval ("(function(n) { while (n.nextSibling) { (n.parentNode).removeChild(n.nextSibling); }; })" :: Text)
465+ void $ call f f [n]
466+
467+-- | s and e must both be children of the same node and s must precede e;
468+-- all nodes between s and e will be removed, but s and e will not be removed
469+deleteBetweenExclusive :: (MonadJSM m, IsNode start, IsNode end) => start -> end -> m ()
470+deleteBetweenExclusive s e = liftJSM $ do
471+ df <- createDocumentFragment =<< getOwnerDocumentUnchecked s
472+ extractBetweenExclusive df s e -- In many places in ImmediateDomBuilderT, we assume that things always have a parent; by adding them to this DocumentFragment, we maintain that invariant
473+
474+-- | s and e must both be children of the same node and s must precede e; all
475+-- nodes between s and e will be moved into the given DocumentFragment, but s
476+-- and e will not be moved
477+extractBetweenExclusive :: (MonadJSM m, IsNode start, IsNode end) => DOM.DocumentFragment -> start -> end -> m ()
478+extractBetweenExclusive df s e = liftJSM $ do
479+ f <- eval ("(function(df,s,e) { var x; for(;;) { x = s['nextSibling']; if(e===x) { break; }; df['appendChild'](x); } })" :: Text)
480+ void $ call f f (df, s, e)
481+
482+-- | s and e must both be children of the same node and s must precede e;
483+-- s and all nodes between s and e will be removed, but e will not be removed
484+{-# INLINABLE deleteUpTo #-}
485+deleteUpTo :: (MonadJSM m, IsNode start, IsNode end) => start -> end -> m ()
486+deleteUpTo s e = do
487+ df <- createDocumentFragment =<< getOwnerDocumentUnchecked s
488+ extractUpTo df s e -- In many places in ImmediateDomBuilderT, we assume that things always have a parent; by adding them to this DocumentFragment, we maintain that invariant
489+
490+extractUpTo :: (MonadJSM m, IsNode start, IsNode end) => DOM.DocumentFragment -> start -> end -> m ()
491+#ifdef ghcjs_HOST_OS
492+--NOTE: Although wrapping this javascript in a function seems unnecessary, GHCJS's optimizer will break it if it is entered without that wrapping (as of 2017-09-04)
493+foreign import javascript unsafe
494+ "(function() { var x = $2; while(x !== $3) { var y = x['nextSibling']; $1['appendChild'](x); x = y; } })()"
495+ extractUpTo_ :: DOM.DocumentFragment -> DOM.Node -> DOM.Node -> IO ()
496+extractUpTo df s e = liftJSM $ extractUpTo_ df (toNode s) (toNode e)
497+#else
498+extractUpTo df s e = liftJSM $ do
499+ f <- eval ("(function(df,s,e){ var x = s; var y; for(;;) { y = x['nextSibling']; df['appendChild'](x); if(e===y) { break; } x = y; } })" :: Text)
500+ void $ call f f (df, s, e)
501+#endif
502+
503+type SupportsHydrationDomBuilder t m = (Reflex t, MonadJSM m, MonadHold t m, MonadFix m, MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref JSM, Adjustable t m, PrimMonad m, PerformEvent t m, MonadJSM (Performable m))
504+
505+{-# INLINABLE collectUpTo #-}
506+collectUpTo :: (MonadJSM m, IsNode start, IsNode end) => start -> end -> m DOM.DocumentFragment
507+collectUpTo s e = do
508+ currentParent <- getParentNodeUnchecked e -- May be different than it was at initial construction, e.g., because the parent may have dumped us in from a DocumentFragment
509+ collectUpToGivenParent currentParent s e
510+
511+{-# INLINABLE collectUpToGivenParent #-}
512+collectUpToGivenParent :: (MonadJSM m, IsNode parent, IsNode start, IsNode end) => parent -> start -> end -> m DOM.DocumentFragment
513+collectUpToGivenParent currentParent s e = do
514+ doc <- getOwnerDocumentUnchecked currentParent
515+ df <- createDocumentFragment doc
516+ extractUpTo df s e
517+ return df
518+
519+newtype EventFilterTriggerRef t er (en :: EventTag) = EventFilterTriggerRef (IORef (Maybe (EventTrigger t (er en))))
520+
521+-- | This 'wrap' is only partial: it doesn't create the 'EventSelector' itself
522+{-# INLINE wrap #-}
523+wrap
524+ :: forall s m er t. (Reflex t, MonadJSM m, MonadReflexCreateTrigger t m, DomRenderHook t m, EventSpec s ~ GhcjsEventSpec)
525+ => Chan [DSum (EventTriggerRef t) TriggerInvocation]
526+ -> DOM.Element
527+ -> RawElementConfig er t s
528+ -> m (DMap EventName (EventFilterTriggerRef t er))
529+wrap events e cfg = do
530+ forM_ (_rawElementConfig_modifyAttributes cfg) $ \modifyAttrs -> requestDomAction_ $ ffor modifyAttrs $ imapM_ $ \(AttributeName mAttrNamespace n) mv -> case mAttrNamespace of
531+ Nothing -> maybe (removeAttribute e n) (setAttribute e n) mv
532+ Just ns -> maybe (removeAttributeNS e (Just ns) n) (setAttributeNS e (Just ns) n) mv
533+ eventTriggerRefs :: DMap EventName (EventFilterTriggerRef t er) <- liftJSM $ fmap DMap.fromList $ forM (DMap.toList $ _ghcjsEventSpec_filters $ _rawElementConfig_eventSpec cfg) $ \(en :=> GhcjsEventFilter f) -> do
534+ triggerRef <- liftIO $ newIORef Nothing
535+ _ <- elementOnEventName en e $ do --TODO: Something safer than this cast
536+ evt <- DOM.event
537+ (flags, k) <- liftJSM $ f $ GhcjsDomEvent evt
538+ when (_eventFlags_preventDefault flags) $ withIsEvent en DOM.preventDefault
539+ case _eventFlags_propagation flags of
540+ Propagation_Continue -> return ()
541+ Propagation_Stop -> withIsEvent en DOM.stopPropagation
542+ Propagation_StopImmediate -> withIsEvent en DOM.stopImmediatePropagation
543+ mv <- liftJSM k --TODO: Only do this when the event is subscribed
544+ liftIO $ forM_ mv $ \v -> writeChan events [EventTriggerRef triggerRef :=> TriggerInvocation v (return ())]
545+ return $ en :=> EventFilterTriggerRef triggerRef
546+ return eventTriggerRefs
547+
548+{-# SPECIALIZE wrap
549+ :: Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation]
550+ -> DOM.Element
551+ -> RawElementConfig er DomTimeline HydrationDomSpace
552+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (DMap EventName (EventFilterTriggerRef DomTimeline er))
553+ #-}
554+
555+{-# SPECIALIZE wrap
556+ :: Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation]
557+ -> DOM.Element
558+ -> RawElementConfig er DomTimeline GhcjsDomSpace
559+ -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (DMap EventName (EventFilterTriggerRef DomTimeline er))
560+ #-}
561+
562+{-# INLINE triggerBody #-}
563+triggerBody
564+ :: forall s er t x. EventSpec s ~ GhcjsEventSpec
565+ => DOM.JSContextRef
566+ -> RawElementConfig er t s
567+ -> Chan [DSum (EventTriggerRef t) TriggerInvocation]
568+ -> DMap EventName (EventFilterTriggerRef t er)
569+ -> DOM.Element
570+ -> WrapArg er EventName x
571+ -> EventTrigger t x
572+ -> IO (IO ())
573+triggerBody ctx cfg events eventTriggerRefs e (WrapArg en) t = case DMap.lookup en eventTriggerRefs of
574+ Just (EventFilterTriggerRef r) -> do
575+ writeIORef r $ Just t
576+ return $ do
577+ writeIORef r Nothing
578+ Nothing -> (`runJSM` ctx) <$> (`runJSM` ctx) (elementOnEventName en e $ do
579+ evt <- DOM.event
580+ mv <- lift $ unGhcjsEventHandler handler (en, GhcjsDomEvent evt)
581+ case mv of
582+ Nothing -> return ()
583+ Just v -> liftIO $ do
584+ --TODO: I don't think this is quite right: if a new trigger is created between when this is enqueued and when it fires, this may not work quite right
585+ ref <- newIORef $ Just t
586+ writeChan events [EventTriggerRef ref :=> TriggerInvocation v (return ())])
587+ where
588+ -- Note: this needs to be done strictly and outside of the newFanEventWithTrigger, so that the newFanEventWithTrigger doesn't
589+ -- retain the entire cfg, which can cause a cyclic dependency that the GC won't be able to clean up
590+ handler :: GhcjsEventHandler er
591+ !handler = _ghcjsEventSpec_handler $ _rawElementConfig_eventSpec cfg
592+
593+{-# SPECIALIZE triggerBody
594+ :: DOM.JSContextRef
595+ -> RawElementConfig er DomTimeline HydrationDomSpace
596+ -> Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation]
597+ -> DMap EventName (EventFilterTriggerRef DomTimeline er)
598+ -> DOM.Element
599+ -> WrapArg er EventName x
600+ -> EventTrigger DomTimeline x
601+ -> IO (IO ())
602+ #-}
603+
604+{-# SPECIALIZE triggerBody
605+ :: DOM.JSContextRef
606+ -> RawElementConfig er DomTimeline GhcjsDomSpace
607+ -> Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation]
608+ -> DMap EventName (EventFilterTriggerRef DomTimeline er)
609+ -> DOM.Element
610+ -> WrapArg er EventName x
611+ -> EventTrigger DomTimeline x
612+ -> IO (IO ())
613+ #-}
614+
615+newtype GhcjsDomHandler a b = GhcjsDomHandler { unGhcjsDomHandler :: a -> JSM b }
616+
617+newtype GhcjsDomHandler1 a b = GhcjsDomHandler1 { unGhcjsDomHandler1 :: forall (x :: EventTag). a x -> JSM (b x) }
618+
619+newtype GhcjsDomEvent en = GhcjsDomEvent { unGhcjsDomEvent :: EventType en }
620+
621+data GhcjsDomSpace
622+
623+instance DomSpace GhcjsDomSpace where
624+ type EventSpec GhcjsDomSpace = GhcjsEventSpec
625+ type RawDocument GhcjsDomSpace = DOM.Document
626+ type RawTextNode GhcjsDomSpace = DOM.Text
627+ type RawCommentNode GhcjsDomSpace = DOM.Comment
628+ type RawElement GhcjsDomSpace = DOM.Element
629+ type RawInputElement GhcjsDomSpace = DOM.HTMLInputElement
630+ type RawTextAreaElement GhcjsDomSpace = DOM.HTMLTextAreaElement
631+ type RawSelectElement GhcjsDomSpace = DOM.HTMLSelectElement
632+ addEventSpecFlags _ en f es = es
633+ { _ghcjsEventSpec_filters =
634+ let f' = Just . GhcjsEventFilter . \case
635+ Nothing -> \evt -> do
636+ mEventResult <- unGhcjsEventHandler (_ghcjsEventSpec_handler es) (en, evt)
637+ return (f mEventResult, return mEventResult)
638+ Just (GhcjsEventFilter oldFilter) -> \evt -> do
639+ (oldFlags, oldContinuation) <- oldFilter evt
640+ mEventResult <- oldContinuation
641+ let newFlags = oldFlags <> f mEventResult
642+ return (newFlags, return mEventResult)
643+ in DMap.alter f' en $ _ghcjsEventSpec_filters es
644+ }
645+
646+newtype GhcjsEventFilter er en = GhcjsEventFilter (GhcjsDomEvent en -> JSM (EventFlags, JSM (Maybe (er en))))
647+
648+data Pair1 (f :: k -> *) (g :: k -> *) (a :: k) = Pair1 (f a) (g a)
649+
650+data Maybe1 f a = Nothing1 | Just1 (f a)
651+
652+data GhcjsEventSpec er = GhcjsEventSpec
653+ { _ghcjsEventSpec_filters :: DMap EventName (GhcjsEventFilter er)
654+ , _ghcjsEventSpec_handler :: GhcjsEventHandler er
655+ }
656+
657+newtype GhcjsEventHandler er = GhcjsEventHandler { unGhcjsEventHandler :: forall en. (EventName en, GhcjsDomEvent en) -> JSM (Maybe (er en)) }
658+
659+#ifndef USE_TEMPLATE_HASKELL
660+ghcjsEventSpec_filters :: forall er . Lens' (GhcjsEventSpec er) (DMap EventName (GhcjsEventFilter er))
661+ghcjsEventSpec_filters f (GhcjsEventSpec a b) = (\a' -> GhcjsEventSpec a' b) <$> f a
662+{-# INLINE ghcjsEventSpec_filters #-}
663+ghcjsEventSpec_handler :: forall er en . Getter (GhcjsEventSpec er) ((EventName en, GhcjsDomEvent en) -> JSM (Maybe (er en)))
664+ghcjsEventSpec_handler f (GhcjsEventSpec _ (GhcjsEventHandler b)) = phantom (f b)
665+{-# INLINE ghcjsEventSpec_handler #-}
666+#endif
667+
668+instance er ~ EventResult => Default (GhcjsEventSpec er) where
669+ def = GhcjsEventSpec
670+ { _ghcjsEventSpec_filters = mempty
671+ , _ghcjsEventSpec_handler = GhcjsEventHandler $ \(en, GhcjsDomEvent evt) -> do
672+ t :: DOM.EventTarget <- withIsEvent en $ Event.getTargetUnchecked evt --TODO: Rework this; defaultDomEventHandler shouldn't need to take this as an argument
673+ let e = uncheckedCastTo DOM.Element t
674+ runReaderT (defaultDomEventHandler e en) evt
675+ }
676+
677+{-# INLINE makeElement #-}
678+makeElement :: MonadJSM m => Document -> Text -> ElementConfig er t s -> m DOM.Element
679+makeElement doc elementTag cfg = do
680+ e <- uncheckedCastTo DOM.Element <$> case cfg ^. namespace of
681+ Nothing -> createElement doc elementTag
682+ Just ens -> createElementNS doc (Just ens) elementTag
683+ iforM_ (cfg ^. initialAttributes) $ \(AttributeName mAttrNamespace n) v -> case mAttrNamespace of
684+ Nothing -> setAttribute e n v
685+ Just ans -> setAttributeNS e (Just ans) n v
686+ pure e
687+
688+{-# INLINE elementImmediate #-}
689+elementImmediate
690+ :: ( RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, EventSpec s ~ GhcjsEventSpec
691+ , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m )
692+ => Text
693+ -> ElementConfig er t s
694+ -> HydrationDomBuilderT s t m a
695+ -> HydrationDomBuilderT s t m (Element er GhcjsDomSpace t, a)
696+elementImmediate elementTag cfg child = do
697+ doc <- askDocument
698+ ctx <- askJSM
699+ events <- askEvents
700+ parent <- getParent
701+ e <- makeElement doc elementTag cfg
702+ appendChild_ parent e
703+ -- Run the child builder with updated parent and previous sibling references
704+ result <- localEnv (\env -> env { _hydrationDomBuilderEnv_parent = Left $ toNode e }) child
705+ let rawCfg = extractRawElementConfig cfg
706+ eventTriggerRefs <- wrap events e rawCfg
707+ es <- newFanEventWithTrigger $ triggerBody ctx rawCfg events eventTriggerRefs e
708+ return (Element es e, result)
709+
710+{-# SPECIALIZE elementImmediate
711+ :: Text
712+ -> ElementConfig er DomTimeline HydrationDomSpace
713+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM a
714+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (Element er GhcjsDomSpace DomTimeline, a)
715+ #-}
716+
717+{-# SPECIALIZE elementImmediate
718+ :: Text
719+ -> ElementConfig er DomTimeline GhcjsDomSpace
720+ -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM a
721+ -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (Element er GhcjsDomSpace DomTimeline, a)
722+ #-}
723+
724+-- For specialisation
725+
726+-- | The Reflex timeline for interacting with the DOM
727+type DomTimeline =
728+#ifdef PROFILE_REFLEX
729+ ProfiledTimeline
730+#endif
731+ Spider
732+
733+-- | The ReflexHost the DOM lives in
734+type DomHost =
735+#ifdef PROFILE_REFLEX
736+ ProfiledM
737+#endif
738+ (SpiderHost Global)
739+
740+type DomCoreWidget x = PostBuildT DomTimeline (WithJSContextSingleton x (PerformEventT DomTimeline DomHost))
741+type HydrationM = DomCoreWidget ()
742+
743+{-# INLINE elementInternal #-}
744+elementInternal
745+ :: (MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m)
746+ => Text
747+ -> ElementConfig er t HydrationDomSpace
748+ -> HydrationDomBuilderT HydrationDomSpace t m a
749+ -> HydrationDomBuilderT HydrationDomSpace t m (Element er HydrationDomSpace t, a)
750+elementInternal elementTag cfg child = getHydrationMode >>= \case
751+ HydrationMode_Immediate -> do
752+ (Element es _, result) <- elementImmediate elementTag cfg child
753+ return (Element es (), result)
754+ HydrationMode_Hydrating -> fst <$> hydrateElement elementTag cfg child
755+
756+{-# SPECIALIZE elementInternal
757+ :: Text
758+ -> ElementConfig er DomTimeline HydrationDomSpace
759+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM a
760+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (Element er HydrationDomSpace DomTimeline, a)
761+ #-}
762+
763+-- | An attribute which causes hydration to skip over an element completely.
764+skipHydrationAttribute :: IsString s => s
765+skipHydrationAttribute = "data-hydration-skip"
766+
767+-- | An attribute which signals that an element should be hydrated.
768+hydratableAttribute :: IsString s => s
769+hydratableAttribute = "data-ssr"
770+
771+{-# INLINE hydrateElement #-}
772+hydrateElement
773+ :: forall er t m a. (MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m)
774+ => Text
775+ -> ElementConfig er t HydrationDomSpace
776+ -> HydrationDomBuilderT HydrationDomSpace t m a
777+ -> HydrationDomBuilderT HydrationDomSpace t m ((Element er HydrationDomSpace t, a), IORef DOM.Element)
778+hydrateElement elementTag cfg child = do
779+ ctx <- askJSM
780+ events <- askEvents
781+ -- Schedule everything for after postBuild, except for getting the result itself
782+ parentRef <- liftIO $ newIORef $ error "Parent not yet initialized"
783+ e' <- liftIO $ newIORef $ error "hydrateElement: Element not yet initialized"
784+ env <- HydrationDomBuilderT ask
785+ childDelayedRef <- liftIO $ newIORef $ pure ()
786+ let env' = env
787+ { _hydrationDomBuilderEnv_parent = Right parentRef
788+ , _hydrationDomBuilderEnv_delayed = childDelayedRef
789+ }
790+ result <- HydrationDomBuilderT $ lift $ runReaderT (unHydrationDomBuilderT child) env'
791+ wrapResult <- liftIO newEmptyMVar
792+ let -- Determine if we should skip an element. We currently skip elements for
793+ -- two reasons:
794+ -- 1) it was not produced by a static builder which supports hydration
795+ -- 2) it is explicitly marked to be skipped
796+ shouldSkip :: DOM.Element -> HydrationRunnerT t m Bool
797+ shouldSkip e = do
798+ skip <- hasAttribute e (skipHydrationAttribute :: DOM.JSString)
799+ hydratable <- hasAttribute e (hydratableAttribute :: DOM.JSString)
800+ pure $ skip || not hydratable
801+ childDom <- liftIO $ readIORef childDelayedRef
802+ let rawCfg = extractRawElementConfig cfg
803+ doc <- askDocument
804+ addHydrationStep $ do
805+ parent <- askParent
806+ lastHydrationNode <- getPreviousNode
807+ let go mLastNode = maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case
808+ Nothing -> do -- ran out of nodes, create the element
809+ HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True }
810+ e <- makeElement doc elementTag cfg
811+ insertAfterPreviousNode e
812+ pure e
813+ Just node -> DOM.castTo DOM.Element node >>= \case
814+ Nothing -> go (Just node) -- this node is not an element, skip
815+ Just e -> shouldSkip e >>= \case
816+ True -> go (Just node) -- this element should be skipped by hydration
817+ False -> do
818+ t <- Element.getTagName e
819+ -- TODO: check attributes?
820+ if T.toCaseFold elementTag == T.toCaseFold t
821+ then pure e
822+ -- we came to some other statically rendered element, so something has gone wrong
823+ else do
824+ HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True }
825+ n <- makeElement doc elementTag cfg
826+ insertAfterPreviousNode n
827+ pure n
828+ e <- go lastHydrationNode
829+ setPreviousNode $ Just $ toNode e
830+ -- Update the parent node used by the children
831+ liftIO $ writeIORef parentRef $ toNode e
832+ liftIO $ writeIORef e' e
833+ -- Setup events, store the result so we can wait on it later
834+ refs <- wrap events e rawCfg
835+ liftIO $ putMVar wrapResult (e, refs)
836+ localRunner childDom Nothing $ toNode e
837+ -- We need the EventSelector to switch to the real event handler after activation
838+ es <- newFanEventWithTrigger $ \(WrapArg en) t -> do
839+ cleanup <- newEmptyMVar
840+ threadId <- forkIO $ do
841+ -- Wait on the data we need from the delayed action
842+ (e, eventTriggerRefs) <- readMVar wrapResult
843+ bracketOnError
844+ -- Run the setup, acquiring the cleanup action
845+ (triggerBody ctx rawCfg events eventTriggerRefs e (WrapArg en) t)
846+ -- Run the cleanup, if we have it - but only when an exception is
847+ -- raised (we might get killed between acquiring the cleanup action
848+ -- from 'triggerBody' and putting it in the MVar)
849+ id
850+ -- Try to put this action into the cleanup MVar
851+ (putMVar cleanup)
852+ pure $ do
853+ tryReadMVar cleanup >>= \case
854+ Nothing -> killThread threadId
855+ Just c -> c
856+ return ((Element es (), result), e')
857+
858+{-# SPECIALIZE hydrateElement
859+ :: Text
860+ -> ElementConfig er DomTimeline HydrationDomSpace
861+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM a
862+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM ((Element er HydrationDomSpace DomTimeline, a), IORef DOM.Element)
863+ #-}
864+
865+{-# INLINE inputElementImmediate #-}
866+inputElementImmediate
867+ :: ( RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, EventSpec s ~ GhcjsEventSpec
868+ , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m
869+ , MonadRef m, Ref m ~ IORef )
870+ => InputElementConfig er t s -> HydrationDomBuilderT s t m (InputElement er GhcjsDomSpace t)
871+inputElementImmediate cfg = do
872+ (e@(Element eventSelector domElement), ()) <- elementImmediate "input" (_inputElementConfig_elementConfig cfg) $ return ()
873+ let domInputElement = uncheckedCastTo DOM.HTMLInputElement domElement
874+ Input.setValue domInputElement $ cfg ^. inputElementConfig_initialValue
875+ v0 <- Input.getValue domInputElement
876+ let getMyValue = Input.getValue domInputElement
877+ valueChangedByUI <- requestDomAction $ liftJSM getMyValue <$ Reflex.select eventSelector (WrapArg Input)
878+ valueChangedBySetValue <- case _inputElementConfig_setValue cfg of
879+ Nothing -> return never
880+ Just eSetValue -> requestDomAction $ ffor eSetValue $ \v' -> do
881+ Input.setValue domInputElement v'
882+ getMyValue -- We get the value after setting it in case the browser has mucked with it somehow
883+ v <- holdDyn v0 $ leftmost
884+ [ valueChangedBySetValue
885+ , valueChangedByUI
886+ ]
887+ Input.setChecked domInputElement $ _inputElementConfig_initialChecked cfg
888+ checkedChangedByUI <- wrapDomEvent domInputElement (`on` Events.click) $ do
889+ Input.getChecked domInputElement
890+ checkedChangedBySetChecked <- case _inputElementConfig_setChecked cfg of
891+ Nothing -> return never
892+ Just eNewchecked -> requestDomAction $ ffor eNewchecked $ \newChecked -> do
893+ oldChecked <- Input.getChecked domInputElement
894+ Input.setChecked domInputElement newChecked
895+ return $ if newChecked /= oldChecked
896+ then Just newChecked
897+ else Nothing
898+ c <- holdDyn (_inputElementConfig_initialChecked cfg) $ leftmost
899+ [ fmapMaybe id checkedChangedBySetChecked
900+ , checkedChangedByUI
901+ ]
902+ hasFocus <- mkHasFocus e
903+ files <- holdDyn mempty <=< wrapDomEvent domInputElement (`on` Events.change) $ do
904+ mfiles <- Input.getFiles domInputElement
905+ let getMyFiles xs = fmap catMaybes . mapM (FileList.item xs) . flip take [0..] . fromIntegral =<< FileList.getLength xs
906+ maybe (return []) getMyFiles mfiles
907+ checked <- holdUniqDyn c
908+ return $ InputElement
909+ { _inputElement_value = v
910+ , _inputElement_checked = checked
911+ , _inputElement_checkedChange = checkedChangedByUI
912+ , _inputElement_input = valueChangedByUI
913+ , _inputElement_hasFocus = hasFocus
914+ , _inputElement_element = e
915+ , _inputElement_raw = domInputElement
916+ , _inputElement_files = files
917+ }
918+
919+{-# INLINE inputElementInternal #-}
920+inputElementInternal
921+ :: ( MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m
922+ , MonadRef m, Ref m ~ IORef )
923+ => InputElementConfig er t HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace t m (InputElement er HydrationDomSpace t)
924+inputElementInternal cfg = getHydrationMode >>= \case
925+ HydrationMode_Immediate -> ffor (inputElementImmediate cfg) $ \result -> result
926+ { _inputElement_element = Element (_element_events $ _inputElement_element result) ()
927+ , _inputElement_raw = ()
928+ }
929+ HydrationMode_Hydrating -> do
930+ ((e, _), domElementRef) <- hydrateElement "input" (cfg ^. inputElementConfig_elementConfig) $ return ()
931+ (valueChangedByUI, triggerChangeByUI) <- newTriggerEvent
932+ (valueChangedBySetValue, triggerChangeBySetValue) <- newTriggerEvent
933+ (focusChange, triggerFocusChange) <- newTriggerEvent
934+ (checkedChangedByUI, triggerCheckedChangedByUI) <- newTriggerEvent
935+ (checkedChangedBySetChecked, triggerCheckedChangedBySetChecked) <- newTriggerEvent
936+ (fileChange, triggerFileChange) <- newTriggerEvent
937+ doc <- askDocument
938+ -- Expected initial value from config
939+ let v0 = _inputElementConfig_initialValue cfg
940+ c0 = _inputElementConfig_initialChecked cfg
941+ valuesAtSwitchover = do
942+ v <- maybe (pure $ pure v0) (hold v0) (_inputElementConfig_setValue cfg)
943+ c <- maybe (pure $ pure c0) (hold c0) (_inputElementConfig_setChecked cfg)
944+ pure (v, c)
945+ addHydrationStepWithSetup valuesAtSwitchover $ \(switchoverValue', switchoverChecked') -> do
946+ switchoverValue <- sample switchoverValue'
947+ switchoverChecked <- sample switchoverChecked'
948+ domElement <- liftIO $ readIORef domElementRef
949+ let domInputElement = uncheckedCastTo DOM.HTMLInputElement domElement
950+ getValue = Input.getValue domInputElement
951+ -- When the value has been updated by setValue before switchover, we must
952+ -- send an update here to remain in sync. This is because the later
953+ -- requestDomAction based on the setValue event will not capture events
954+ -- happening before postBuild, because this code runs after switchover.
955+ when (v0 /= switchoverValue) $ liftIO $ triggerChangeBySetValue switchoverValue
956+ -- The user could have altered the value before switchover. This must be
957+ -- triggered after the setValue one in order for the events to be in the
958+ -- correct order.
959+ liftJSM getValue >>= \realValue -> when (realValue /= switchoverValue) $ liftIO $ triggerChangeByUI realValue
960+ -- Watch for user interaction and trigger event accordingly
961+ requestDomAction_ $ (liftJSM getValue >>= liftIO . triggerChangeByUI) <$ Reflex.select (_element_events e) (WrapArg Input)
962+ for_ (_inputElementConfig_setValue cfg) $ \eSetValue ->
963+ requestDomAction_ $ ffor eSetValue $ \v' -> do
964+ Input.setValue domInputElement v'
965+ v <- getValue -- We get the value after setting it in case the browser has mucked with it somehow
966+ liftIO $ triggerChangeBySetValue v
967+ let focusChange' = leftmost
968+ [ False <$ Reflex.select (_element_events e) (WrapArg Blur)
969+ , True <$ Reflex.select (_element_events e) (WrapArg Focus)
970+ ]
971+ liftIO . triggerFocusChange =<< Node.isSameNode (toNode domElement) . fmap toNode =<< Document.getActiveElement doc
972+ requestDomAction_ $ liftIO . triggerFocusChange <$> focusChange'
973+ -- When the checked state has been updated by setChecked before
974+ -- switchover, we must send an update here to remain in sync. This is
975+ -- because the later requestDomAction based on the setChecked event will not
976+ -- capture events happening before postBuild, because this code runs after
977+ -- switchover.
978+ when (c0 /= switchoverChecked) $ liftIO $ triggerCheckedChangedBySetChecked switchoverChecked
979+ -- The user could have clicked the checkbox before switchover, we only
980+ -- detect cases where they flipped the state. This must be triggered after
981+ -- the setValue one in order for the events to be in the correct order.
982+ liftJSM (Input.getChecked domInputElement) >>= \realChecked -> when (realChecked /= switchoverChecked) $
983+ liftIO $ triggerCheckedChangedByUI realChecked
984+ _ <- liftJSM $ domInputElement `on` Events.click $ do
985+ liftIO . triggerCheckedChangedByUI =<< Input.getChecked domInputElement
986+ for_ (_inputElementConfig_setChecked cfg) $ \eNewchecked ->
987+ requestDomAction $ ffor eNewchecked $ \newChecked -> do
988+ oldChecked <- Input.getChecked domInputElement
989+ Input.setChecked domInputElement newChecked
990+ when (newChecked /= oldChecked) $ liftIO $ triggerCheckedChangedBySetChecked newChecked
991+ _ <- liftJSM $ domInputElement `on` Events.change $ do
992+ mfiles <- Input.getFiles domInputElement
993+ let getMyFiles xs = fmap catMaybes . mapM (FileList.item xs) . flip take [0..] . fromIntegral =<< FileList.getLength xs
994+ liftIO . triggerFileChange =<< maybe (return []) getMyFiles mfiles
995+ return ()
996+ checked' <- holdDyn c0 $ leftmost
997+ [ checkedChangedBySetChecked
998+ , checkedChangedByUI
999+ ]
1000+ checked <- holdUniqDyn checked'
1001+ let initialFocus = False -- Assume it isn't focused, but we update the actual focus state at switchover
1002+ hasFocus <- holdUniqDyn =<< holdDyn initialFocus focusChange
1003+ v <- holdDyn v0 $ leftmost
1004+ [ valueChangedBySetValue
1005+ , valueChangedByUI
1006+ ]
1007+ files <- holdDyn mempty fileChange
1008+ return $ InputElement
1009+ { _inputElement_value = v
1010+ , _inputElement_checked = checked
1011+ , _inputElement_checkedChange = checkedChangedByUI
1012+ , _inputElement_input = valueChangedByUI
1013+ , _inputElement_hasFocus = hasFocus
1014+ , _inputElement_element = e
1015+ , _inputElement_raw = ()
1016+ , _inputElement_files = files
1017+ }
1018+
1019+{-# INLINE textAreaElementImmediate #-}
1020+textAreaElementImmediate
1021+ :: ( RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, EventSpec s ~ GhcjsEventSpec
1022+ , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m
1023+ , MonadRef m, Ref m ~ IORef )
1024+ => TextAreaElementConfig er t s -> HydrationDomBuilderT s t m (TextAreaElement er GhcjsDomSpace t)
1025+textAreaElementImmediate cfg = do
1026+ (e@(Element eventSelector domElement), _) <- elementImmediate "textarea" (cfg ^. textAreaElementConfig_elementConfig) $ return ()
1027+ let domTextAreaElement = uncheckedCastTo DOM.HTMLTextAreaElement domElement
1028+ TextArea.setValue domTextAreaElement $ cfg ^. textAreaElementConfig_initialValue
1029+ v0 <- TextArea.getValue domTextAreaElement
1030+ let getMyValue = TextArea.getValue domTextAreaElement
1031+ valueChangedByUI <- requestDomAction $ liftJSM getMyValue <$ Reflex.select eventSelector (WrapArg Input)
1032+ valueChangedBySetValue <- case _textAreaElementConfig_setValue cfg of
1033+ Nothing -> return never
1034+ Just eSetValue -> requestDomAction $ ffor eSetValue $ \v' -> do
1035+ TextArea.setValue domTextAreaElement v'
1036+ getMyValue -- We get the value after setting it in case the browser has mucked with it somehow
1037+ v <- holdDyn v0 $ leftmost
1038+ [ valueChangedBySetValue
1039+ , valueChangedByUI
1040+ ]
1041+ hasFocus <- mkHasFocus e
1042+ return $ TextAreaElement
1043+ { _textAreaElement_value = v
1044+ , _textAreaElement_input = valueChangedByUI
1045+ , _textAreaElement_hasFocus = hasFocus
1046+ , _textAreaElement_element = e
1047+ , _textAreaElement_raw = domTextAreaElement
1048+ }
1049+
1050+{-# INLINE textAreaElementInternal #-}
1051+textAreaElementInternal
1052+ :: ( MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m
1053+ , MonadRef m, Ref m ~ IORef )
1054+ => TextAreaElementConfig er t HydrationDomSpace -> HydrationDomBuilderT HydrationDomSpace t m (TextAreaElement er HydrationDomSpace t)
1055+textAreaElementInternal cfg = getHydrationMode >>= \case
1056+ HydrationMode_Immediate -> ffor (textAreaElementImmediate cfg) $ \result -> result
1057+ { _textAreaElement_element = Element (_element_events $ _textAreaElement_element result) ()
1058+ , _textAreaElement_raw = ()
1059+ }
1060+ HydrationMode_Hydrating -> do
1061+ ((e, _), domElementRef) <- hydrateElement "textarea" (cfg ^. textAreaElementConfig_elementConfig) $ return ()
1062+ (valueChangedByUI, triggerChangeByUI) <- newTriggerEvent
1063+ (valueChangedBySetValue, triggerChangeBySetValue) <- newTriggerEvent
1064+ (focusChange, triggerFocusChange) <- newTriggerEvent
1065+ doc <- askDocument
1066+ -- Expected initial value from config
1067+ let v0 = _textAreaElementConfig_initialValue cfg
1068+ valueAtSwitchover = maybe (pure $ pure v0) (hold v0) (_textAreaElementConfig_setValue cfg)
1069+ addHydrationStepWithSetup valueAtSwitchover $ \switchoverValue' -> do
1070+ switchoverValue <- sample switchoverValue'
1071+ domElement <- liftIO $ readIORef domElementRef
1072+ let domTextAreaElement = uncheckedCastTo DOM.HTMLTextAreaElement domElement
1073+ getValue = TextArea.getValue domTextAreaElement
1074+ -- When the value has been updated by setValue before switchover, we must
1075+ -- send an update here to remain in sync. This is because the later
1076+ -- requestDomAction based on the setValue event will not capture events
1077+ -- happening before postBuild, because this code runs after switchover.
1078+ when (v0 /= switchoverValue) $ liftIO $ triggerChangeBySetValue switchoverValue
1079+ -- The user could have altered the value before switchover. This must be
1080+ -- triggered after the setValue one in order for the events to be in the
1081+ -- correct order.
1082+ liftJSM getValue >>= \realValue -> when (realValue /= switchoverValue) $ liftIO $ triggerChangeByUI realValue
1083+ -- Watch for user interaction and trigger event accordingly
1084+ requestDomAction_ $ (liftJSM getValue >>= liftIO . triggerChangeByUI) <$ Reflex.select (_element_events e) (WrapArg Input)
1085+ for_ (_textAreaElementConfig_setValue cfg) $ \eSetValue ->
1086+ requestDomAction_ $ ffor eSetValue $ \v' -> do
1087+ TextArea.setValue domTextAreaElement v'
1088+ v <- getValue -- We get the value after setting it in case the browser has mucked with it somehow
1089+ liftIO $ triggerChangeBySetValue v
1090+ let focusChange' = leftmost
1091+ [ False <$ Reflex.select (_element_events e) (WrapArg Blur)
1092+ , True <$ Reflex.select (_element_events e) (WrapArg Focus)
1093+ ]
1094+ liftIO . triggerFocusChange =<< Node.isSameNode (toNode domElement) . fmap toNode =<< Document.getActiveElement doc
1095+ requestDomAction_ $ liftIO . triggerFocusChange <$> focusChange'
1096+ let initialFocus = False -- Assume it isn't focused, but we update the actual focus state at switchover
1097+ hasFocus <- holdUniqDyn =<< holdDyn initialFocus focusChange
1098+ v <- holdDyn v0 $ leftmost
1099+ [ valueChangedBySetValue
1100+ , valueChangedByUI
1101+ ]
1102+ return $ TextAreaElement
1103+ { _textAreaElement_value = v
1104+ , _textAreaElement_input = valueChangedByUI
1105+ , _textAreaElement_hasFocus = hasFocus
1106+ , _textAreaElement_element = e
1107+ , _textAreaElement_raw = ()
1108+ }
1109+
1110+{-# INLINE selectElementImmediate #-}
1111+selectElementImmediate
1112+ :: ( EventSpec s ~ GhcjsEventSpec, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document
1113+ , MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m )
1114+ => SelectElementConfig er t s
1115+ -> HydrationDomBuilderT s t m a
1116+ -> HydrationDomBuilderT s t m (SelectElement er GhcjsDomSpace t, a)
1117+selectElementImmediate cfg child = do
1118+ (e@(Element eventSelector domElement), result) <- elementImmediate "select" (cfg ^. selectElementConfig_elementConfig) child
1119+ let domSelectElement = uncheckedCastTo DOM.HTMLSelectElement domElement
1120+ Select.setValue domSelectElement $ cfg ^. selectElementConfig_initialValue
1121+ v0 <- Select.getValue domSelectElement
1122+ let getMyValue = Select.getValue domSelectElement
1123+ valueChangedByUI <- requestDomAction $ liftJSM getMyValue <$ Reflex.select eventSelector (WrapArg Change)
1124+ valueChangedBySetValue <- case _selectElementConfig_setValue cfg of
1125+ Nothing -> return never
1126+ Just eSetValue -> requestDomAction $ ffor eSetValue $ \v' -> do
1127+ Select.setValue domSelectElement v'
1128+ getMyValue -- We get the value after setting it in case the browser has mucked with it somehow
1129+ v <- holdDyn v0 $ leftmost
1130+ [ valueChangedBySetValue
1131+ , valueChangedByUI
1132+ ]
1133+ hasFocus <- mkHasFocus e
1134+ let wrapped = SelectElement
1135+ { _selectElement_value = v
1136+ , _selectElement_change = valueChangedByUI
1137+ , _selectElement_hasFocus = hasFocus
1138+ , _selectElement_element = e
1139+ , _selectElement_raw = domSelectElement
1140+ }
1141+ return (wrapped, result)
1142+
1143+{-# INLINE selectElementInternal #-}
1144+selectElementInternal
1145+ :: ( MonadJSM m, Reflex t, MonadReflexCreateTrigger t m, MonadFix m, MonadHold t m
1146+ , MonadRef m, Ref m ~ IORef )
1147+ => SelectElementConfig er t HydrationDomSpace
1148+ -> HydrationDomBuilderT HydrationDomSpace t m a
1149+ -> HydrationDomBuilderT HydrationDomSpace t m (SelectElement er HydrationDomSpace t, a)
1150+selectElementInternal cfg child = getHydrationMode >>= \case
1151+ HydrationMode_Immediate -> ffor (selectElementImmediate cfg child) $ \(e, result) -> (e
1152+ { _selectElement_element = Element (_element_events $ _selectElement_element e) ()
1153+ , _selectElement_raw = ()
1154+ }, result)
1155+ HydrationMode_Hydrating -> do
1156+ ((e, result), domElementRef) <- hydrateElement "select" (cfg ^. selectElementConfig_elementConfig) child
1157+ (valueChangedByUI, triggerChangeByUI) <- newTriggerEvent
1158+ (valueChangedBySetValue, triggerChangeBySetValue) <- newTriggerEvent
1159+ (focusChange, triggerFocusChange) <- newTriggerEvent
1160+ doc <- askDocument
1161+ -- Expected initial value from config
1162+ let v0 = _selectElementConfig_initialValue cfg
1163+ addHydrationStep $ do
1164+ domElement <- liftIO $ readIORef domElementRef
1165+ let domSelectElement = uncheckedCastTo DOM.HTMLSelectElement domElement
1166+ getValue = Select.getValue domSelectElement
1167+ -- The browser might have messed with the value, or the user could have
1168+ -- altered it before activation, so we set it if it isn't what we expect
1169+ liftJSM getValue >>= \v0' -> do
1170+ when (v0' /= v0) $ liftIO $ triggerChangeByUI v0'
1171+ -- Watch for user interaction and trigger event accordingly
1172+ requestDomAction_ $ (liftJSM getValue >>= liftIO . triggerChangeByUI) <$ Reflex.select (_element_events e) (WrapArg Change)
1173+ for_ (_selectElementConfig_setValue cfg) $ \eSetValue ->
1174+ requestDomAction_ $ ffor eSetValue $ \v' -> do
1175+ Select.setValue domSelectElement v'
1176+ v <- getValue -- We get the value after setting it in case the browser has mucked with it somehow
1177+ liftIO $ triggerChangeBySetValue v
1178+ let focusChange' = leftmost
1179+ [ False <$ Reflex.select (_element_events e) (WrapArg Blur)
1180+ , True <$ Reflex.select (_element_events e) (WrapArg Focus)
1181+ ]
1182+ liftIO . triggerFocusChange =<< Node.isSameNode (toNode domElement) . fmap toNode =<< Document.getActiveElement doc
1183+ requestDomAction_ $ liftIO . triggerFocusChange <$> focusChange'
1184+ let initialFocus = False -- Assume it isn't focused, but we update the actual focus state at switchover
1185+ hasFocus <- holdUniqDyn =<< holdDyn initialFocus focusChange
1186+ v <- holdDyn v0 $ leftmost
1187+ [ valueChangedBySetValue
1188+ , valueChangedByUI
1189+ ]
1190+ return $ (,result) $ SelectElement
1191+ { _selectElement_value = v
1192+ , _selectElement_change = valueChangedByUI
1193+ , _selectElement_hasFocus = hasFocus
1194+ , _selectElement_element = e
1195+ , _selectElement_raw = ()
1196+ }
1197+
1198+{-# INLINE textNodeImmediate #-}
1199+textNodeImmediate
1200+ :: (RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, MonadJSM m, Reflex t, MonadFix m)
1201+ => TextNodeConfig t -> HydrationDomBuilderT s t m DOM.Text
1202+textNodeImmediate (TextNodeConfig !t mSetContents) = do
1203+ p <- getParent
1204+ doc <- askDocument
1205+ n <- createTextNode doc t
1206+ appendChild_ p n
1207+ mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents
1208+ pure n
1209+
1210+{-# SPECIALIZE textNodeImmediate
1211+ :: TextNodeConfig DomTimeline
1212+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM DOM.Text
1213+ #-}
1214+
1215+{-# SPECIALIZE textNodeImmediate
1216+ :: TextNodeConfig DomTimeline
1217+ -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM DOM.Text
1218+ #-}
1219+
1220+{-# INLINE textNodeInternal #-}
1221+textNodeInternal
1222+ :: (Adjustable t m, MonadHold t m, MonadJSM m, MonadFix m, Reflex t)
1223+ => TextNodeConfig t -> HydrationDomBuilderT HydrationDomSpace t m (TextNode HydrationDomSpace t)
1224+textNodeInternal tc@(TextNodeConfig !t mSetContents) = do
1225+ doc <- askDocument
1226+ getHydrationMode >>= \case
1227+ HydrationMode_Immediate -> void $ textNodeImmediate tc
1228+ HydrationMode_Hydrating -> addHydrationStepWithSetup (maybe (pure $ pure t) (hold t) mSetContents) $ \currentText -> do
1229+ n <- hydrateTextNode doc =<< sample currentText
1230+ mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents
1231+ pure $ TextNode ()
1232+
1233+{-# SPECIALIZE textNodeInternal
1234+ :: TextNodeConfig DomTimeline
1235+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (TextNode HydrationDomSpace DomTimeline)
1236+ #-}
1237+
1238+-- | The static builder mashes adjacent text nodes into one node: we check the
1239+-- text content of each node we come to, comparing it to the content we
1240+-- expect. We also have a special case for empty text nodes - we always create
1241+-- the and add them after the previous node reference.
1242+{-# INLINE hydrateTextNode #-}
1243+hydrateTextNode :: MonadJSM m => Document -> Text -> HydrationRunnerT t m DOM.Text
1244+hydrateTextNode doc t@"" = do
1245+ tn <- createTextNode doc t
1246+ insertAfterPreviousNode tn
1247+ pure tn
1248+hydrateTextNode doc t = do
1249+ n <- join $ go <$> askParent <*> getPreviousNode
1250+ setPreviousNode $ Just $ toNode n
1251+ return n
1252+ where
1253+ go parent mLastNode = maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case
1254+ Nothing -> do
1255+ HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True }
1256+ n <- createTextNode doc t
1257+ insertAfterPreviousNode n
1258+ pure n
1259+ Just node -> DOM.castTo DOM.Text node >>= \case
1260+ Nothing -> go parent $ Just node
1261+ Just originalNode -> do
1262+ originalText <- Node.getTextContentUnchecked originalNode
1263+ case T.stripPrefix t originalText of
1264+ Just "" -> return originalNode
1265+ Just _ -> do
1266+ -- If we have the right prefix, we split the text node into a node containing the
1267+ -- required text and a subsequent sibling node containing the rest of the text.
1268+ DOM.splitText_ originalNode $ fromIntegral $ T.length t
1269+ return originalNode
1270+ Nothing -> do
1271+ HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True }
1272+ n <- createTextNode doc t
1273+ insertAfterPreviousNode n
1274+ pure n
1275+
1276+{-# INLINE commentNodeImmediate #-}
1277+commentNodeImmediate
1278+ :: (RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document, MonadJSM m, Reflex t, MonadFix m)
1279+ => CommentNodeConfig t -> HydrationDomBuilderT s t m DOM.Comment
1280+commentNodeImmediate (CommentNodeConfig !t mSetContents) = do
1281+ p <- getParent
1282+ doc <- askDocument
1283+ n <- createComment doc t
1284+ appendChild_ p n
1285+ mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents
1286+ pure n
1287+
1288+{-# INLINE commentNodeInternal #-}
1289+commentNodeInternal
1290+ :: (Ref m ~ IORef, MonadRef m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadJSM (Performable m), MonadJSM m, MonadFix m, Reflex t, Adjustable t m, MonadHold t m, MonadSample t m)
1291+ => CommentNodeConfig t -> HydrationDomBuilderT HydrationDomSpace t m (CommentNode HydrationDomSpace t)
1292+commentNodeInternal tc@(CommentNodeConfig t0 mSetContents) = do
1293+ doc <- askDocument
1294+ getHydrationMode >>= \case
1295+ HydrationMode_Immediate -> void $ commentNodeInternal tc
1296+ HydrationMode_Hydrating -> addHydrationStepWithSetup (maybe (pure $ pure t0) (hold t0) mSetContents) $ \bt -> do
1297+ t <- sample bt
1298+ void $ hydrateComment doc t mSetContents
1299+ pure $ CommentNode ()
1300+
1301+{-# INLINE hydrateComment #-}
1302+hydrateComment :: (MonadJSM m, Reflex t, MonadFix m) => Document -> Text -> Maybe (Event t Text) -> HydrationRunnerT t m DOM.Comment
1303+hydrateComment doc t mSetContents = do
1304+ parent <- askParent
1305+ let go mLastNode = maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case
1306+ Nothing -> do
1307+ c <- createComment doc t
1308+ insertAfterPreviousNode c
1309+ pure c
1310+ Just node -> DOM.castTo DOM.Comment node >>= \case
1311+ Nothing -> go (Just node)
1312+ Just c -> do
1313+ t' <- Node.getTextContentUnchecked c
1314+ if t == t'
1315+ then pure c
1316+ else do
1317+ c' <- createComment doc t
1318+ insertAfterPreviousNode c'
1319+ pure c'
1320+ n <- go =<< getPreviousNode
1321+ setPreviousNode $ Just $ toNode n
1322+ mapM_ (requestDomAction_ . fmap (setNodeValue n . Just)) mSetContents
1323+ pure n
1324+
1325+-- | We leave markers in the static builder as comments, and rip these comments
1326+-- out at hydration time, replacing them with empty text nodes.
1327+{-# INLINABLE skipToAndReplaceComment #-}
1328+skipToAndReplaceComment
1329+ :: (MonadJSM m, Reflex t, MonadFix m, Adjustable t m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document)
1330+ => Text
1331+ -> IORef (Maybe Text)
1332+ -> HydrationDomBuilderT s t m (HydrationRunnerT t m (), IORef DOM.Text, IORef (Maybe Text))
1333+skipToAndReplaceComment prefix key0Ref = getHydrationMode >>= \case
1334+ HydrationMode_Immediate -> do
1335+ -- If we're in immediate mode, we don't try to replace an existing comment,
1336+ -- and just return a dummy key
1337+ t <- textNodeImmediate $ TextNodeConfig ("" :: Text) Nothing
1338+ append $ toNode t
1339+ textNodeRef <- liftIO $ newIORef t
1340+ keyRef <- liftIO $ newIORef Nothing
1341+ pure (pure (), textNodeRef, keyRef)
1342+ HydrationMode_Hydrating -> do
1343+ doc <- askDocument
1344+ textNodeRef <- liftIO $ newIORef $ error "textNodeRef not yet initialized"
1345+ keyRef <- liftIO $ newIORef $ error "keyRef not yet initialized"
1346+ let
1347+ go Nothing _ = do
1348+ tn <- createTextNode doc ("" :: Text)
1349+ insertAfterPreviousNode tn
1350+ HydrationRunnerT $ modify' $ \s -> s { _hydrationState_failed = True }
1351+ pure (tn, Nothing)
1352+ go (Just key0) mLastNode = do
1353+ parent <- askParent
1354+ maybe (Node.getFirstChild parent) Node.getNextSibling mLastNode >>= \case
1355+ Nothing -> go Nothing Nothing
1356+ Just node -> DOM.castTo DOM.Comment node >>= \case
1357+ Just comment -> do
1358+ commentText <- fromMaybe (error "Cannot get text content of comment node") <$> Node.getTextContent comment
1359+ case T.stripPrefix (prefix <> key0) commentText of -- 'key0' may be @""@ in which case we're just finding the actual key; TODO: Don't be clever.
1360+ Just key -> do
1361+ -- Replace the comment with an (invisible) text node
1362+ tn <- createTextNode doc ("" :: Text)
1363+ Node.replaceChild_ parent tn comment
1364+ pure (tn, Just key)
1365+ Nothing -> do
1366+ go (Just key0) (Just node)
1367+ Nothing -> do
1368+ go (Just key0) (Just node)
1369+ switchComment = do
1370+ key0 <- liftIO $ readIORef key0Ref
1371+ (tn, key) <- go key0 =<< getPreviousNode
1372+ setPreviousNode $ Just $ toNode tn
1373+ liftIO $ do
1374+ writeIORef textNodeRef tn
1375+ writeIORef keyRef key
1376+ pure (switchComment, textNodeRef, keyRef)
1377+
1378+{-# INLINABLE skipToReplaceStart #-}
1379+skipToReplaceStart :: (MonadJSM m, Reflex t, MonadFix m, Adjustable t m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => HydrationDomBuilderT s t m (HydrationRunnerT t m (), IORef DOM.Text, IORef (Maybe Text))
1380+skipToReplaceStart = skipToAndReplaceComment "replace-start" =<< liftIO (newIORef $ Just "") -- TODO: Don't rely on clever usage @""@ to make this work.
1381+
1382+{-# INLINABLE skipToReplaceEnd #-}
1383+skipToReplaceEnd :: (MonadJSM m, Reflex t, MonadFix m, Adjustable t m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => IORef (Maybe Text) -> HydrationDomBuilderT s t m (HydrationRunnerT t m (), IORef DOM.Text)
1384+skipToReplaceEnd key = fmap (\(m,e,_) -> (m,e)) $ skipToAndReplaceComment "replace-end" key
1385+
1386+instance SupportsHydrationDomBuilder t m => NotReady t (HydrationDomBuilderT s t m) where
1387+ notReadyUntil e = do
1388+ eOnce <- headE e
1389+ unreadyChildren <- askUnreadyChildren
1390+ commitAction <- askCommitAction
1391+ liftIO $ modifyIORef' unreadyChildren succ
1392+ let ready = do
1393+ old <- liftIO $ readIORef unreadyChildren
1394+ let new = pred old
1395+ liftIO $ writeIORef unreadyChildren $! new
1396+ when (new == 0) commitAction
1397+ requestDomAction_ $ ready <$ eOnce
1398+ notReady = do
1399+ unreadyChildren <- askUnreadyChildren
1400+ liftIO $ modifyIORef' unreadyChildren succ
1401+
1402+data HydrationDomSpace
1403+
1404+instance DomSpace HydrationDomSpace where
1405+ type EventSpec HydrationDomSpace = GhcjsEventSpec
1406+ type RawDocument HydrationDomSpace = DOM.Document
1407+ type RawTextNode HydrationDomSpace = ()
1408+ type RawCommentNode HydrationDomSpace = ()
1409+ type RawElement HydrationDomSpace = ()
1410+ type RawInputElement HydrationDomSpace = ()
1411+ type RawTextAreaElement HydrationDomSpace = ()
1412+ type RawSelectElement HydrationDomSpace = ()
1413+ addEventSpecFlags _ en f es = es
1414+ { _ghcjsEventSpec_filters =
1415+ let f' = Just . GhcjsEventFilter . \case
1416+ Nothing -> \evt -> do
1417+ mEventResult <- unGhcjsEventHandler (_ghcjsEventSpec_handler es) (en, evt)
1418+ return (f mEventResult, return mEventResult)
1419+ Just (GhcjsEventFilter oldFilter) -> \evt -> do
1420+ (oldFlags, oldContinuation) <- oldFilter evt
1421+ mEventResult <- oldContinuation
1422+ let newFlags = oldFlags <> f mEventResult
1423+ return (newFlags, return mEventResult)
1424+ in DMap.alter f' en $ _ghcjsEventSpec_filters es
1425+ }
1426+
1427+instance SupportsHydrationDomBuilder t m => DomBuilder t (HydrationDomBuilderT HydrationDomSpace t m) where
1428+ type DomBuilderSpace (HydrationDomBuilderT HydrationDomSpace t m) = HydrationDomSpace
1429+ {-# INLINABLE element #-}
1430+ element = elementInternal
1431+ {-# INLINABLE textNode #-}
1432+ textNode = textNodeInternal
1433+ {-# INLINABLE commentNode #-}
1434+ commentNode = commentNodeInternal
1435+ {-# INLINABLE inputElement #-}
1436+ inputElement = inputElementInternal
1437+ {-# INLINABLE textAreaElement #-}
1438+ textAreaElement = textAreaElementInternal
1439+ {-# INLINABLE selectElement #-}
1440+ selectElement = selectElementInternal
1441+ placeRawElement () = pure ()
1442+ wrapRawElement () _cfg = pure $ Element (EventSelector $ const never) ()
1443+
1444+instance SupportsHydrationDomBuilder t m => DomBuilder t (HydrationDomBuilderT GhcjsDomSpace t m) where
1445+ type DomBuilderSpace (HydrationDomBuilderT GhcjsDomSpace t m) = GhcjsDomSpace
1446+ {-# INLINABLE element #-}
1447+ element = elementImmediate
1448+ {-# INLINABLE textNode #-}
1449+ textNode = fmap TextNode . textNodeImmediate
1450+ {-# INLINABLE commentNode #-}
1451+ commentNode = fmap CommentNode . commentNodeImmediate
1452+ {-# INLINABLE inputElement #-}
1453+ inputElement = inputElementImmediate
1454+ {-# INLINABLE textAreaElement #-}
1455+ textAreaElement = textAreaElementImmediate
1456+ {-# INLINABLE selectElement #-}
1457+ selectElement = selectElementImmediate
1458+ placeRawElement = append . toNode
1459+ wrapRawElement e rawCfg = do
1460+ events <- askEvents
1461+ ctx <- askJSM
1462+ eventTriggerRefs <- wrap events e rawCfg
1463+ es <- newFanEventWithTrigger $ triggerBody ctx rawCfg events eventTriggerRefs e
1464+ pure $ Element es e
1465+
1466+data FragmentState
1467+ = FragmentState_Unmounted
1468+ | FragmentState_Mounted (DOM.Text, DOM.Text)
1469+
1470+data ImmediateDomFragment = ImmediateDomFragment
1471+ { _immediateDomFragment_document :: DOM.DocumentFragment
1472+ , _immediateDomFragment_state :: IORef FragmentState
1473+ }
1474+
1475+extractFragment :: MonadJSM m => ImmediateDomFragment -> m ()
1476+extractFragment fragment = do
1477+ state <- liftIO $ readIORef $ _immediateDomFragment_state fragment
1478+ case state of
1479+ FragmentState_Unmounted -> return ()
1480+ FragmentState_Mounted (before, after) -> do
1481+ extractBetweenExclusive (_immediateDomFragment_document fragment) before after
1482+ liftIO $ writeIORef (_immediateDomFragment_state fragment) FragmentState_Unmounted
1483+
1484+instance SupportsHydrationDomBuilder t m => MountableDomBuilder t (HydrationDomBuilderT GhcjsDomSpace t m) where
1485+ type DomFragment (HydrationDomBuilderT GhcjsDomSpace t m) = ImmediateDomFragment
1486+ buildDomFragment w = do
1487+ df <- createDocumentFragment =<< askDocument
1488+ result <- flip localEnv w $ \env -> env
1489+ { _hydrationDomBuilderEnv_parent = Left $ toNode df
1490+ }
1491+ state <- liftIO $ newIORef FragmentState_Unmounted
1492+ return (ImmediateDomFragment df state, result)
1493+ mountDomFragment fragment setFragment = do
1494+ parent <- getParent
1495+ extractFragment fragment
1496+ before <- textNodeImmediate $ TextNodeConfig ("" :: Text) Nothing
1497+ appendChild_ parent $ _immediateDomFragment_document fragment
1498+ after <- textNodeImmediate $ TextNodeConfig ("" :: Text) Nothing
1499+ xs <- foldDyn (\new (previous, _) -> (new, Just previous)) (fragment, Nothing) setFragment
1500+ requestDomAction_ $ ffor (updated xs) $ \(childFragment, Just previousFragment) -> do
1501+ extractFragment previousFragment
1502+ extractFragment childFragment
1503+ insertBefore (_immediateDomFragment_document childFragment) after
1504+ liftIO $ writeIORef (_immediateDomFragment_state childFragment) $ FragmentState_Mounted (before, after)
1505+ liftIO $ writeIORef (_immediateDomFragment_state fragment) $ FragmentState_Mounted (before, after)
1506+
1507+instance (Reflex t, Monad m, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (DomRenderHookT t m) where
1508+ runWithReplace a0 a' = DomRenderHookT $ runWithReplace (unDomRenderHookT a0) (fmapCheap unDomRenderHookT a')
1509+ traverseIntMapWithKeyWithAdjust f m = DomRenderHookT . traverseIntMapWithKeyWithAdjust (\k -> unDomRenderHookT . f k) m
1510+ traverseDMapWithKeyWithAdjust f m = DomRenderHookT . traverseDMapWithKeyWithAdjust (\k -> unDomRenderHookT . f k) m
1511+ traverseDMapWithKeyWithAdjustWithMove f m = DomRenderHookT . traverseDMapWithKeyWithAdjustWithMove (\k -> unDomRenderHookT . f k) m
1512+
1513+instance (Adjustable t m, MonadJSM m, MonadHold t m, MonadFix m, PrimMonad m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document) => Adjustable t (HydrationDomBuilderT s t m) where
1514+ {-# INLINABLE runWithReplace #-}
1515+ runWithReplace a0 a' = do
1516+ initialEnv <- HydrationDomBuilderT ask
1517+ let hydrating = _hydrationDomBuilderEnv_hydrationMode initialEnv
1518+ (hydrateStart, before, beforeKey) <- skipToReplaceStart
1519+ let parentUnreadyChildren = _hydrationDomBuilderEnv_unreadyChildren initialEnv
1520+ haveEverBeenReady <- liftIO $ newIORef False
1521+ currentCohort <- liftIO $ newIORef (-1 :: Int) -- Equal to the cohort currently in the DOM
1522+ let myCommitAction = do
1523+ liftIO (readIORef haveEverBeenReady) >>= \case
1524+ True -> return ()
1525+ False -> do
1526+ liftIO $ writeIORef haveEverBeenReady True
1527+ old <- liftIO $ readIORef parentUnreadyChildren
1528+ let new = pred old
1529+ liftIO $ writeIORef parentUnreadyChildren $! new
1530+ when (new == 0) $ _hydrationDomBuilderEnv_commitAction initialEnv
1531+ -- We draw 'after' in this roundabout way to avoid using MonadFix
1532+ doc <- askDocument
1533+ parent <- getParent
1534+ (hydrateEnd, after) <- skipToReplaceEnd beforeKey
1535+ let drawInitialChild = do
1536+ h <- liftIO $ readIORef hydrating
1537+ p' <- case h of
1538+ HydrationMode_Hydrating -> pure parent
1539+ HydrationMode_Immediate -> toNode <$> createDocumentFragment doc
1540+ unreadyChildren <- liftIO $ newIORef 0
1541+ let a0' = case h of
1542+ HydrationMode_Hydrating -> a0
1543+ HydrationMode_Immediate -> do
1544+ a <- a0
1545+ insertBefore p' =<< liftIO (readIORef after)
1546+ pure a
1547+ delayed <- case h of
1548+ HydrationMode_Hydrating -> liftIO $ newIORef $ pure ()
1549+ HydrationMode_Immediate -> pure $ _hydrationDomBuilderEnv_delayed initialEnv
1550+ result <- runReaderT (unHydrationDomBuilderT a0') initialEnv
1551+ { _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
1552+ , _hydrationDomBuilderEnv_commitAction = myCommitAction
1553+ , _hydrationDomBuilderEnv_parent = Left p'
1554+ , _hydrationDomBuilderEnv_delayed = delayed
1555+ }
1556+ dom <- case h of
1557+ HydrationMode_Hydrating -> liftIO $ readIORef delayed
1558+ HydrationMode_Immediate -> pure $ pure ()
1559+ liftIO $ readIORef unreadyChildren >>= \case
1560+ 0 -> writeIORef haveEverBeenReady True
1561+ _ -> modifyIORef' parentUnreadyChildren succ
1562+ return (dom, result)
1563+ a'' <- numberOccurrences a'
1564+ ((hydrate0, result0), child') <- HydrationDomBuilderT $ lift $ runWithReplace drawInitialChild $ ffor a'' $ \(cohortId, child) -> do
1565+ h <- liftIO $ readIORef hydrating
1566+ p' <- case h of
1567+ HydrationMode_Hydrating -> pure parent
1568+ HydrationMode_Immediate -> toNode <$> createDocumentFragment doc
1569+ unreadyChildren <- liftIO $ newIORef 0
1570+ let commitAction = do
1571+ c <- liftIO $ readIORef currentCohort
1572+ when (c <= cohortId) $ do -- If a newer cohort has already been committed, just ignore this
1573+ !before' <- liftIO $ readIORef before
1574+ !after' <- liftIO $ readIORef after
1575+ deleteBetweenExclusive before' after'
1576+ insertBefore p' after'
1577+ liftIO $ writeIORef currentCohort cohortId
1578+ myCommitAction
1579+ delayed <- case h of
1580+ HydrationMode_Hydrating -> liftIO $ newIORef $ pure ()
1581+ HydrationMode_Immediate -> pure $ _hydrationDomBuilderEnv_delayed initialEnv
1582+ result <- runReaderT (unHydrationDomBuilderT child) $ initialEnv
1583+ { _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
1584+ , _hydrationDomBuilderEnv_commitAction = case h of
1585+ HydrationMode_Hydrating -> myCommitAction
1586+ HydrationMode_Immediate -> commitAction
1587+ , _hydrationDomBuilderEnv_parent = Left p'
1588+ , _hydrationDomBuilderEnv_delayed = delayed
1589+ }
1590+ dom <- case h of
1591+ HydrationMode_Hydrating -> liftIO $ readIORef delayed
1592+ HydrationMode_Immediate -> pure $ pure ()
1593+ uc <- liftIO $ readIORef unreadyChildren
1594+ let commitActionToRunNow = if uc == 0
1595+ then Just $ commitAction
1596+ else Nothing -- A child will run it when unreadyChildren is decremented to 0
1597+ actions = case h of
1598+ HydrationMode_Hydrating -> Left dom
1599+ HydrationMode_Immediate -> Right commitActionToRunNow
1600+ return (actions, result)
1601+ let (hydrate', commitAction) = fanEither $ fmap fst child'
1602+ addHydrationStepWithSetup (hold hydrate0 hydrate') $ \contents -> do
1603+ hydrateStart
1604+ join $ sample contents
1605+ hydrateEnd
1606+ requestDomAction_ $ fmapMaybe id commitAction
1607+ return (result0, snd <$> child')
1608+
1609+ {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}
1610+ traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjust'
1611+ {-# INLINABLE traverseDMapWithKeyWithAdjust #-}
1612+ traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjust'
1613+ {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-}
1614+ traverseDMapWithKeyWithAdjustWithMove = do
1615+ let updateChildUnreadiness (p :: PatchDMapWithMove k (Compose (TraverseChild t m (Some k)) v')) old = do
1616+ let new :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Compose (TraverseChild t m (Some k)) v') a -> IO (PatchDMapWithMove.NodeInfo k (Constant (IORef (ChildReadyState (Some k)))) a)
1617+ new k = PatchDMapWithMove.nodeInfoMapFromM $ \case
1618+ PatchDMapWithMove.From_Insert (Compose (TraverseChild (Left _hydration) _)) -> return PatchDMapWithMove.From_Delete
1619+ PatchDMapWithMove.From_Insert (Compose (TraverseChild (Right immediate) _)) -> do
1620+ readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case
1621+ ChildReadyState_Ready -> return PatchDMapWithMove.From_Delete
1622+ ChildReadyState_Unready _ -> do
1623+ writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just $ Some k
1624+ return $ PatchDMapWithMove.From_Insert $ Constant (_traverseChildImmediate_childReadyState immediate)
1625+ PatchDMapWithMove.From_Delete -> return PatchDMapWithMove.From_Delete
1626+ PatchDMapWithMove.From_Move fromKey -> return $ PatchDMapWithMove.From_Move fromKey
1627+ deleteOrMove :: forall a. k a -> Product (Constant (IORef (ChildReadyState (Some k)))) (ComposeMaybe k) a -> IO (Constant () a)
1628+ deleteOrMove _ (Pair (Constant sRef) (ComposeMaybe mToKey)) = do
1629+ writeIORef sRef $ ChildReadyState_Unready $ Some <$> mToKey -- This will be Nothing if deleting, and Just if moving, so it works out in both cases
1630+ return $ Constant ()
1631+ p' <- fmap unsafePatchDMapWithMove $ DMap.traverseWithKey new $ unPatchDMapWithMove p
1632+ _ <- DMap.traverseWithKey deleteOrMove $ PatchDMapWithMove.getDeletionsAndMoves p old
1633+ return $ applyAlways p' old
1634+ hoistTraverseWithKeyWithAdjust traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove updateChildUnreadiness $ \placeholders lastPlaceholder (p_ :: PatchDMapWithMove k (Compose (TraverseChild t m (Some k)) v')) -> do
1635+ let p = unPatchDMapWithMove p_
1636+ phsBefore <- liftIO $ readIORef placeholders
1637+ let collectIfMoved :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Compose (TraverseChild t m (Some k)) v') a -> JSM (Constant (Maybe DOM.DocumentFragment) a)
1638+ collectIfMoved k e = do
1639+ let mThisPlaceholder = Map.lookup (Some k) phsBefore -- Will be Nothing if this element wasn't present before
1640+ nextPlaceholder = maybe lastPlaceholder snd $ Map.lookupGT (Some k) phsBefore
1641+ case isJust $ getComposeMaybe $ PatchDMapWithMove._nodeInfo_to e of
1642+ False -> do
1643+ mapM_ (`deleteUpTo` nextPlaceholder) mThisPlaceholder
1644+ return $ Constant Nothing
1645+ True -> do
1646+ Constant <$> mapM (`collectUpTo` nextPlaceholder) mThisPlaceholder
1647+ collected <- DMap.traverseWithKey collectIfMoved p
1648+ let !phsAfter = fromMaybe phsBefore $ apply filtered phsBefore
1649+ weakened :: PatchMapWithMove (Some k) (Either (TraverseChildHydration t m) (TraverseChildImmediate (Some k)))
1650+ weakened = weakenPatchDMapWithMoveWith (_traverseChild_mode . getCompose) p_
1651+ filtered :: PatchMapWithMove (Some k) DOM.Text
1652+ filtered = PatchMapWithMove $ flip Map.mapMaybe (unPatchMapWithMove weakened) $ \(PatchMapWithMove.NodeInfo from to) -> flip PatchMapWithMove.NodeInfo to <$> case from of
1653+ PatchMapWithMove.From_Insert (Left _hydration) -> Nothing
1654+ PatchMapWithMove.From_Insert (Right immediate) -> Just $ PatchMapWithMove.From_Insert $ _traverseChildImmediate_placeholder immediate
1655+ PatchMapWithMove.From_Delete -> Just $ PatchMapWithMove.From_Delete
1656+ PatchMapWithMove.From_Move k -> Just $ PatchMapWithMove.From_Move k
1657+ let placeFragment :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Compose (TraverseChild t m (Some k)) v') a -> JSM (Constant () a)
1658+ placeFragment k e = do
1659+ let nextPlaceholder = maybe lastPlaceholder snd $ Map.lookupGT (Some k) phsAfter
1660+ case PatchDMapWithMove._nodeInfo_from e of
1661+ PatchDMapWithMove.From_Insert (Compose (TraverseChild x _)) -> case x of
1662+ Left _ -> pure ()
1663+ Right immediate -> _traverseChildImmediate_fragment immediate `insertBefore` nextPlaceholder
1664+ PatchDMapWithMove.From_Delete -> do
1665+ return ()
1666+ PatchDMapWithMove.From_Move fromKey -> do
1667+ Just (Constant mdf) <- return $ DMap.lookup fromKey collected
1668+ mapM_ (`insertBefore` nextPlaceholder) mdf
1669+ return $ Constant ()
1670+ mapM_ (\(k :=> v) -> void $ placeFragment k v) $ DMap.toDescList p -- We need to go in reverse order here, to make sure the placeholders are in the right spot at the right time
1671+ liftIO $ writeIORef placeholders $! phsAfter
1672+
1673+{-# INLINABLE traverseDMapWithKeyWithAdjust' #-}
1674+traverseDMapWithKeyWithAdjust'
1675+ :: forall s t m (k :: * -> *) v v'. (Adjustable t m, MonadHold t m, MonadFix m, MonadJSM m, PrimMonad m, GCompare k, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document)
1676+ => (forall a. k a -> v a -> HydrationDomBuilderT s t m (v' a))
1677+ -> DMap k v
1678+ -> Event t (PatchDMap k v)
1679+ -> HydrationDomBuilderT s t m (DMap k v', Event t (PatchDMap k v'))
1680+traverseDMapWithKeyWithAdjust' = do
1681+ let updateChildUnreadiness (p :: PatchDMap k (Compose (TraverseChild t m (Some k)) v')) old = do
1682+ let new :: forall a. k a -> ComposeMaybe (Compose (TraverseChild t m (Some k)) v') a -> IO (ComposeMaybe (Constant (IORef (ChildReadyState (Some k)))) a)
1683+ new k (ComposeMaybe m) = ComposeMaybe <$> case m of
1684+ Nothing -> return Nothing
1685+ Just (Compose (TraverseChild (Left _hydration) _)) -> pure Nothing
1686+ Just (Compose (TraverseChild (Right immediate) _)) -> do
1687+ readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case
1688+ ChildReadyState_Ready -> return Nothing -- Delete this child, since it's ready
1689+ ChildReadyState_Unready _ -> do
1690+ writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just $ Some k
1691+ return $ Just $ Constant (_traverseChildImmediate_childReadyState immediate)
1692+ delete _ (Constant sRef) = do
1693+ writeIORef sRef $ ChildReadyState_Unready Nothing
1694+ return $ Constant ()
1695+ p' <- fmap PatchDMap $ DMap.traverseWithKey new $ unPatchDMap p
1696+ _ <- DMap.traverseWithKey delete $ PatchDMap.getDeletions p old
1697+ return $ applyAlways p' old
1698+ hoistTraverseWithKeyWithAdjust traverseDMapWithKeyWithAdjust mapPatchDMap updateChildUnreadiness $ \placeholders lastPlaceholder (PatchDMap patch) -> do
1699+ phs <- liftIO $ readIORef placeholders
1700+ forM_ (DMap.toList patch) $ \(k :=> ComposeMaybe mv) -> do
1701+ let nextPlaceholder = maybe lastPlaceholder snd $ Map.lookupGT (Some k) phs
1702+ -- Delete old node
1703+ forM_ (Map.lookup (Some k) phs) $ \thisPlaceholder -> do
1704+ thisPlaceholder `deleteUpTo` nextPlaceholder
1705+ -- Insert new node
1706+ forM_ mv $ \(Compose (TraverseChild e _)) -> case e of
1707+ Left _hydration -> pure ()
1708+ Right immediate -> do
1709+ _traverseChildImmediate_fragment immediate `insertBefore` nextPlaceholder
1710+ let weakened :: PatchMap (Some k) (Either (TraverseChildHydration t m) (TraverseChildImmediate (Some k)))
1711+ weakened = weakenPatchDMapWith (_traverseChild_mode . getCompose) $ PatchDMap patch
1712+ filtered :: PatchMap (Some k) DOM.Text
1713+ filtered = PatchMap $ flip Map.mapMaybe (unPatchMap weakened) $ \case
1714+ Nothing -> Just Nothing -- deletion
1715+ Just (Left _) -> Nothing
1716+ Just (Right immediate) -> Just $ Just $ _traverseChildImmediate_placeholder immediate
1717+ liftIO $ writeIORef placeholders $! fromMaybe phs $ apply filtered phs
1718+
1719+{-# INLINABLE traverseIntMapWithKeyWithAdjust' #-}
1720+traverseIntMapWithKeyWithAdjust'
1721+ :: forall s t m v v'. (Adjustable t m, MonadJSM m, MonadFix m, PrimMonad m, MonadHold t m, RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document)
1722+ => (IntMap.Key -> v -> HydrationDomBuilderT s t m v')
1723+ -> IntMap v
1724+ -> Event t (PatchIntMap v)
1725+ -> HydrationDomBuilderT s t m (IntMap v', Event t (PatchIntMap v'))
1726+traverseIntMapWithKeyWithAdjust' = do
1727+ let updateChildUnreadiness (p@(PatchIntMap pInner) :: PatchIntMap (TraverseChild t m Int v')) old = do
1728+ let new :: IntMap.Key -> Maybe (TraverseChild t m Int v') -> IO (Maybe (IORef (ChildReadyState Int)))
1729+ new k m = case m of
1730+ Nothing -> return Nothing
1731+ Just (TraverseChild (Left _hydration) _) -> pure Nothing
1732+ Just (TraverseChild (Right immediate) _) -> do
1733+ let sRef = _traverseChildImmediate_childReadyState immediate
1734+ readIORef sRef >>= \case
1735+ ChildReadyState_Ready -> return Nothing -- Delete this child, since it's ready
1736+ ChildReadyState_Unready _ -> do
1737+ writeIORef sRef $ ChildReadyState_Unready $ Just k
1738+ return $ Just sRef
1739+ delete _ sRef = do
1740+ writeIORef sRef $ ChildReadyState_Unready Nothing
1741+ return ()
1742+ p' <- PatchIntMap <$> IntMap.traverseWithKey new pInner
1743+ _ <- IntMap.traverseWithKey delete $ FastMutableIntMap.getDeletions p old
1744+ return $ applyAlways p' old
1745+ hoistTraverseIntMapWithKeyWithAdjust traverseIntMapWithKeyWithAdjust updateChildUnreadiness $ \placeholders lastPlaceholder (PatchIntMap p) -> do
1746+ phs <- liftIO $ readIORef placeholders
1747+ forM_ (IntMap.toList p) $ \(k, mv) -> do
1748+ let nextPlaceholder = maybe lastPlaceholder snd $ IntMap.lookupGT k phs
1749+ -- Delete old node
1750+ forM_ (IntMap.lookup k phs) $ \thisPlaceholder -> thisPlaceholder `deleteUpTo` nextPlaceholder
1751+ -- Insert new node
1752+ forM_ mv $ \(TraverseChild e _) -> case e of
1753+ Left _hydration -> pure ()
1754+ Right immediate -> do
1755+ _traverseChildImmediate_fragment immediate `insertBefore` nextPlaceholder
1756+ let filtered :: PatchIntMap DOM.Text
1757+ filtered = PatchIntMap $ flip IntMap.mapMaybe p $ \case
1758+ Nothing -> Just Nothing -- deletion
1759+ Just tc
1760+ | Right immediate <- _traverseChild_mode tc -> Just $ Just $ _traverseChildImmediate_placeholder immediate
1761+ | otherwise -> Nothing
1762+ liftIO $ writeIORef placeholders $! fromMaybe phs $ apply filtered phs
1763+
1764+{-# SPECIALIZE traverseIntMapWithKeyWithAdjust'
1765+ :: (IntMap.Key -> v -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM v')
1766+ -> IntMap v
1767+ -> Event DomTimeline (PatchIntMap v)
1768+ -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v'))
1769+ #-}
1770+
1771+{-# SPECIALIZE traverseIntMapWithKeyWithAdjust'
1772+ :: (IntMap.Key -> v -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM v')
1773+ -> IntMap v
1774+ -> Event DomTimeline (PatchIntMap v)
1775+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v'))
1776+ #-}
1777+
1778+data ChildReadyState a
1779+ = ChildReadyState_Ready
1780+ | ChildReadyState_Unready !(Maybe a)
1781+ deriving (Show, Read, Eq, Ord)
1782+
1783+insertAfterPreviousNode :: (Monad m, MonadJSM m) => DOM.IsNode node => node -> HydrationRunnerT t m ()
1784+insertAfterPreviousNode node = do
1785+ parent <- askParent
1786+ nextNode <- maybe (Node.getFirstChild parent) Node.getNextSibling =<< getPreviousNode
1787+ Node.insertBefore_ parent node nextNode
1788+ setPreviousNode $ Just $ toNode node
1789+
1790+{-# INLINABLE hoistTraverseWithKeyWithAdjust #-}
1791+hoistTraverseWithKeyWithAdjust
1792+ ::
1793+ ( Adjustable t m
1794+ , MonadHold t m
1795+ , GCompare k
1796+ , MonadIO m
1797+ , MonadJSM m
1798+ , PrimMonad m
1799+ , MonadFix m
1800+ , Patch (p k v)
1801+ , Patch (p k (Constant Int))
1802+ , PatchTarget (p k (Constant Int)) ~ DMap k (Constant Int)
1803+ , Patch (p k (Compose (TraverseChild t m (Some k)) v'))
1804+ , PatchTarget (p k (Compose (TraverseChild t m (Some k)) v')) ~ DMap k (Compose (TraverseChild t m (Some k)) v')
1805+ , Monoid (p k (Compose (TraverseChild t m (Some k)) v'))
1806+ , RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document
1807+ )
1808+ => (forall vv vv'.
1809+ (forall a. k a -> vv a -> DomRenderHookT t m (vv' a))
1810+ -> DMap k vv
1811+ -> Event t (p k vv)
1812+ -> DomRenderHookT t m (DMap k vv', Event t (p k vv')))
1813+ -- ^ The base monad's traversal
1814+ -> (forall vv vv'. (forall a. vv a -> vv' a) -> p k vv -> p k vv')
1815+ -- ^ A way of mapping over the patch type
1816+ -> (p k (Compose (TraverseChild t m (Some k)) v') -> DMap k (Constant (IORef (ChildReadyState (Some k)))) -> IO (DMap k (Constant (IORef (ChildReadyState (Some k))))))
1817+ -- ^ Given a patch for the children DOM elements, produce a patch for the childrens' unreadiness state
1818+ -> (IORef (Map.Map (Some k) DOM.Text) -> DOM.Text -> p k (Compose (TraverseChild t m (Some k)) v') -> JSM ())
1819+ -- ^ Apply a patch to the DOM
1820+ -> (forall a. k a -> v a -> HydrationDomBuilderT s t m (v' a))
1821+ -> DMap k v
1822+ -> Event t (p k v)
1823+ -> HydrationDomBuilderT s t m (DMap k v', Event t (p k v'))
1824+hoistTraverseWithKeyWithAdjust base mapPatch updateChildUnreadiness applyDomUpdate_ f dm0 dm' = do
1825+ doc <- askDocument
1826+ initialEnv <- HydrationDomBuilderT ask
1827+ let parentUnreadyChildren = _hydrationDomBuilderEnv_unreadyChildren initialEnv
1828+ pendingChange :: IORef (DMap k (Constant (IORef (ChildReadyState (Some k)))), p k (Compose (TraverseChild t m (Some k)) v')) <- liftIO $ newIORef mempty
1829+ haveEverBeenReady <- liftIO $ newIORef False
1830+ placeholders <- liftIO $ newIORef Map.empty
1831+ lastPlaceholder <- createTextNode doc ("" :: Text)
1832+ let applyDomUpdate p = do
1833+ applyDomUpdate_ placeholders lastPlaceholder p
1834+ markSelfReady
1835+ liftIO $ writeIORef pendingChange $! mempty
1836+ markSelfReady = do
1837+ liftIO (readIORef haveEverBeenReady) >>= \case
1838+ True -> return ()
1839+ False -> do
1840+ liftIO $ writeIORef haveEverBeenReady True
1841+ old <- liftIO $ readIORef parentUnreadyChildren
1842+ let new = pred old
1843+ liftIO $ writeIORef parentUnreadyChildren $! new
1844+ when (new == 0) $ _hydrationDomBuilderEnv_commitAction initialEnv
1845+ markChildReady :: IORef (ChildReadyState (Some k)) -> JSM ()
1846+ markChildReady childReadyState = do
1847+ liftIO (readIORef childReadyState) >>= \case
1848+ ChildReadyState_Ready -> return ()
1849+ ChildReadyState_Unready countedAt -> do
1850+ liftIO $ writeIORef childReadyState ChildReadyState_Ready
1851+ case countedAt of
1852+ Nothing -> return ()
1853+ Just (Some k) -> do -- This child has been counted as unready, so we need to remove it from the unready set
1854+ (oldUnready, p) <- liftIO $ readIORef pendingChange
1855+ when (not $ DMap.null oldUnready) $ do -- This shouldn't actually ever be null
1856+ let newUnready = DMap.delete k oldUnready
1857+ liftIO $ writeIORef pendingChange (newUnready, p)
1858+ when (DMap.null newUnready) $ do
1859+ applyDomUpdate p
1860+ (children0 :: DMap k (Compose (TraverseChild t m (Some k)) v'), children' :: Event t (p k (Compose (TraverseChild t m (Some k)) v')))
1861+ <- HydrationDomBuilderT $ lift $ base (\k v -> drawChildUpdate initialEnv markChildReady $ f k v) dm0 dm'
1862+ let processChild k (Compose (TraverseChild e _)) = case e of
1863+ Left _ -> pure $ ComposeMaybe Nothing
1864+ Right immediate -> ComposeMaybe <$> do
1865+ readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case
1866+ ChildReadyState_Ready -> return Nothing
1867+ ChildReadyState_Unready _ -> do
1868+ writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just $ Some k
1869+ return $ Just $ Constant (_traverseChildImmediate_childReadyState immediate)
1870+ initialUnready <- liftIO $ DMap.mapMaybeWithKey (\_ -> getComposeMaybe) <$> DMap.traverseWithKey processChild children0
1871+ liftIO $ if DMap.null initialUnready
1872+ then writeIORef haveEverBeenReady True
1873+ else do
1874+ modifyIORef' parentUnreadyChildren succ
1875+ writeIORef pendingChange (initialUnready, mempty) -- The patch is always empty because it got applied implicitly when we ran the children the first time
1876+ getHydrationMode >>= \case
1877+ HydrationMode_Hydrating -> addHydrationStepWithSetup (holdIncremental children0 children') $ \children -> do
1878+ dm :: DMap k (Compose (TraverseChild t m (Some k)) v') <- sample $ currentIncremental children
1879+ phs <- sequenceA $ weakenDMapWith (either _traverseChildHydration_delayed (pure . _traverseChildImmediate_placeholder) . _traverseChild_mode . getCompose) dm
1880+ liftIO $ writeIORef placeholders $! phs
1881+ insertAfterPreviousNode lastPlaceholder
1882+ HydrationMode_Immediate -> do
1883+ let activate i = do
1884+ append $ toNode $ _traverseChildImmediate_fragment i
1885+ pure $ _traverseChildImmediate_placeholder i
1886+ phs <- sequenceA $ weakenDMapWith (either (error "impossible") activate . _traverseChild_mode . getCompose) children0
1887+ liftIO $ writeIORef placeholders $! phs
1888+ append $ toNode lastPlaceholder
1889+ requestDomAction_ $ ffor children' $ \p -> do
1890+ (oldUnready, oldP) <- liftIO $ readIORef pendingChange
1891+ newUnready <- liftIO $ updateChildUnreadiness p oldUnready
1892+ let !newP = p <> oldP
1893+ liftIO $ writeIORef pendingChange (newUnready, newP)
1894+ when (DMap.null newUnready) $ do
1895+ applyDomUpdate newP
1896+ let result0 = DMap.map (_traverseChild_result . getCompose) children0
1897+ result' = ffor children' $ mapPatch $ _traverseChild_result . getCompose
1898+ return (result0, result')
1899+
1900+{-# INLINE hoistTraverseIntMapWithKeyWithAdjust #-}
1901+hoistTraverseIntMapWithKeyWithAdjust ::
1902+ ( Adjustable t m
1903+ , MonadHold t m
1904+ , MonadJSM m
1905+ , MonadFix m
1906+ , PrimMonad m
1907+ , Monoid (p (TraverseChild t m Int v'))
1908+ , Functor p
1909+ , PatchTarget (p (HydrationRunnerT t m ())) ~ IntMap (HydrationRunnerT t m ())
1910+ , PatchTarget (p (TraverseChild t m Int v')) ~ IntMap (TraverseChild t m Int v')
1911+ , Patch (p (HydrationRunnerT t m ()))
1912+ , Patch (p (TraverseChild t m Int v'))
1913+ , RawDocument (DomBuilderSpace (HydrationDomBuilderT s t m)) ~ Document
1914+ )
1915+ => ((IntMap.Key -> v -> DomRenderHookT t m (TraverseChild t m Int v'))
1916+ -> IntMap v
1917+ -> Event t (p v)
1918+ -> DomRenderHookT t m (IntMap (TraverseChild t m Int v'), Event t (p (TraverseChild t m Int v'))))
1919+ -- ^ The base monad's traversal
1920+ -> (p (TraverseChild t m Int v')
1921+ -> IntMap (IORef (ChildReadyState Int))
1922+ -> IO (IntMap (IORef (ChildReadyState Int))))
1923+ -- ^ Given a patch for the children DOM elements, produce a patch for the childrens' unreadiness state
1924+ -> (IORef (IntMap DOM.Text)
1925+ -> DOM.Text
1926+ -> p (TraverseChild t m Int v')
1927+ -> JSM ())
1928+ -- ^ Apply a patch to the DOM
1929+ -> (IntMap.Key -> v -> HydrationDomBuilderT s t m v')
1930+ -> IntMap v
1931+ -> Event t (p v)
1932+ -> HydrationDomBuilderT s t m (IntMap v', Event t (p v'))
1933+hoistTraverseIntMapWithKeyWithAdjust base updateChildUnreadiness applyDomUpdate_ f dm0 dm' = do
1934+ doc <- askDocument
1935+ initialEnv <- HydrationDomBuilderT ask
1936+ let parentUnreadyChildren = _hydrationDomBuilderEnv_unreadyChildren initialEnv
1937+ pendingChange :: IORef (IntMap (IORef (ChildReadyState Int)), p (TraverseChild t m Int v')) <- liftIO $ newIORef mempty
1938+ haveEverBeenReady <- liftIO $ newIORef False
1939+ placeholders <- liftIO $ newIORef IntMap.empty
1940+ lastPlaceholder <- createTextNode doc ("" :: Text)
1941+ let applyDomUpdate p = do
1942+ applyDomUpdate_ placeholders lastPlaceholder p
1943+ markSelfReady
1944+ liftIO $ writeIORef pendingChange $! mempty
1945+ markSelfReady = do
1946+ liftIO (readIORef haveEverBeenReady) >>= \case
1947+ True -> return ()
1948+ False -> do
1949+ liftIO $ writeIORef haveEverBeenReady True
1950+ old <- liftIO $ readIORef parentUnreadyChildren
1951+ let new = pred old
1952+ liftIO $ writeIORef parentUnreadyChildren $! new
1953+ when (new == 0) $ _hydrationDomBuilderEnv_commitAction initialEnv
1954+ markChildReady :: IORef (ChildReadyState Int) -> JSM ()
1955+ markChildReady childReadyState = do
1956+ liftIO (readIORef childReadyState) >>= \case
1957+ ChildReadyState_Ready -> return ()
1958+ ChildReadyState_Unready countedAt -> do
1959+ liftIO $ writeIORef childReadyState ChildReadyState_Ready
1960+ case countedAt of
1961+ Nothing -> return ()
1962+ Just k -> do -- This child has been counted as unready, so we need to remove it from the unready set
1963+ (oldUnready, p) <- liftIO $ readIORef pendingChange
1964+ when (not $ IntMap.null oldUnready) $ do -- This shouldn't actually ever be null
1965+ let newUnready = IntMap.delete k oldUnready
1966+ liftIO $ writeIORef pendingChange (newUnready, p)
1967+ when (IntMap.null newUnready) $ do
1968+ applyDomUpdate p
1969+ (children0 :: IntMap (TraverseChild t m Int v'), children' :: Event t (p (TraverseChild t m Int v')))
1970+ <- HydrationDomBuilderT $ lift $ base (\k v -> drawChildUpdateInt initialEnv markChildReady $ f k v) dm0 dm'
1971+ let processChild k (TraverseChild e _) = case e of
1972+ Left _ -> pure Nothing
1973+ Right immediate -> do
1974+ readIORef (_traverseChildImmediate_childReadyState immediate) >>= \case
1975+ ChildReadyState_Ready -> return Nothing
1976+ ChildReadyState_Unready _ -> do
1977+ writeIORef (_traverseChildImmediate_childReadyState immediate) $ ChildReadyState_Unready $ Just k
1978+ return $ Just (_traverseChildImmediate_childReadyState immediate)
1979+ initialUnready <- liftIO $ IntMap.mapMaybe id <$> IntMap.traverseWithKey processChild children0
1980+ liftIO $ if IntMap.null initialUnready
1981+ then writeIORef haveEverBeenReady True
1982+ else do
1983+ modifyIORef' parentUnreadyChildren succ
1984+ writeIORef pendingChange (initialUnready, mempty) -- The patch is always empty because it got applied implicitly when we ran the children the first time
1985+ getHydrationMode >>= \case
1986+ HydrationMode_Hydrating -> addHydrationStepWithSetup (holdIncremental children0 children') $ \children -> do
1987+ dm :: IntMap (TraverseChild t m Int v') <- sample $ currentIncremental children
1988+ phs <- traverse (either _traverseChildHydration_delayed (pure . _traverseChildImmediate_placeholder) . _traverseChild_mode) dm
1989+ liftIO $ writeIORef placeholders $! phs
1990+ insertAfterPreviousNode lastPlaceholder
1991+ HydrationMode_Immediate -> do
1992+ let activate i = do
1993+ append $ toNode $ _traverseChildImmediate_fragment i
1994+ pure $ _traverseChildImmediate_placeholder i
1995+ phs <- traverse (either (error "impossible") activate . _traverseChild_mode) children0
1996+ liftIO $ writeIORef placeholders $! phs
1997+ append $ toNode lastPlaceholder
1998+ requestDomAction_ $ ffor children' $ \p -> do
1999+ (oldUnready, oldP) <- liftIO $ readIORef pendingChange
2000+ newUnready <- liftIO $ updateChildUnreadiness p oldUnready
2001+ let !newP = p <> oldP
2002+ liftIO $ writeIORef pendingChange (newUnready, newP)
2003+ when (IntMap.null newUnready) $ do
2004+ applyDomUpdate newP
2005+ let result0 = IntMap.map _traverseChild_result children0
2006+ result' = ffor children' $ fmap $ _traverseChild_result
2007+ return (result0, result')
2008+
2009+{-# SPECIALIZE hoistTraverseIntMapWithKeyWithAdjust
2010+ :: ((IntMap.Key -> v -> DomRenderHookT DomTimeline HydrationM (TraverseChild DomTimeline HydrationM Int v'))
2011+ -> IntMap v
2012+ -> Event DomTimeline (PatchIntMap v)
2013+ -> DomRenderHookT DomTimeline HydrationM (IntMap (TraverseChild DomTimeline HydrationM Int v'), Event DomTimeline (PatchIntMap (TraverseChild DomTimeline HydrationM Int v'))))
2014+ -> (PatchIntMap (TraverseChild DomTimeline HydrationM Int v')
2015+ -> IntMap (IORef (ChildReadyState Int))
2016+ -> IO (IntMap (IORef (ChildReadyState Int))))
2017+ -> (IORef (IntMap DOM.Text)
2018+ -> DOM.Text
2019+ -> PatchIntMap (TraverseChild DomTimeline HydrationM Int v')
2020+ -> JSM ())
2021+ -> (IntMap.Key -> v -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM v')
2022+ -> IntMap v
2023+ -> Event DomTimeline (PatchIntMap v)
2024+ -> HydrationDomBuilderT HydrationDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v'))
2025+ #-}
2026+
2027+{-# SPECIALIZE hoistTraverseIntMapWithKeyWithAdjust
2028+ :: ((IntMap.Key -> v -> DomRenderHookT DomTimeline HydrationM (TraverseChild DomTimeline HydrationM Int v'))
2029+ -> IntMap v
2030+ -> Event DomTimeline (PatchIntMap v)
2031+ -> DomRenderHookT DomTimeline HydrationM (IntMap (TraverseChild DomTimeline HydrationM Int v'), Event DomTimeline (PatchIntMap (TraverseChild DomTimeline HydrationM Int v'))))
2032+ -> (PatchIntMap (TraverseChild DomTimeline HydrationM Int v')
2033+ -> IntMap (IORef (ChildReadyState Int))
2034+ -> IO (IntMap (IORef (ChildReadyState Int))))
2035+ -> (IORef (IntMap DOM.Text)
2036+ -> DOM.Text
2037+ -> PatchIntMap (TraverseChild DomTimeline HydrationM Int v')
2038+ -> JSM ())
2039+ -> (IntMap.Key -> v -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM v')
2040+ -> IntMap v
2041+ -> Event DomTimeline (PatchIntMap v)
2042+ -> HydrationDomBuilderT GhcjsDomSpace DomTimeline HydrationM (IntMap v', Event DomTimeline (PatchIntMap v'))
2043+ #-}
2044+
2045+data TraverseChildImmediate k = TraverseChildImmediate
2046+ { _traverseChildImmediate_fragment :: {-# UNPACK #-} !DOM.DocumentFragment
2047+ -- ^ Child is appended to this fragment
2048+ , _traverseChildImmediate_placeholder :: {-# UNPACK #-} !DOM.Text
2049+ -- ^ Placeholder reference
2050+ , _traverseChildImmediate_childReadyState :: {-# UNPACK #-} !(IORef (ChildReadyState k))
2051+ }
2052+
2053+newtype TraverseChildHydration t m = TraverseChildHydration
2054+ { _traverseChildHydration_delayed :: HydrationRunnerT t m DOM.Text
2055+ -- ^ Action to run at switchover, returns the placeholder
2056+ }
2057+
2058+data TraverseChild t m k a = TraverseChild
2059+ { _traverseChild_mode :: !(Either (TraverseChildHydration t m) (TraverseChildImmediate k))
2060+ , _traverseChild_result :: !a
2061+ } deriving Functor
2062+
2063+{-# INLINABLE drawChildUpdate #-}
2064+drawChildUpdate :: (MonadJSM m, Reflex t)
2065+ => HydrationDomBuilderEnv t m
2066+ -> (IORef (ChildReadyState k) -> JSM ()) -- This will NOT be called if the child is ready at initialization time; instead, the ChildReadyState return value will be ChildReadyState_Ready
2067+ -> HydrationDomBuilderT s t m (f a)
2068+ -> DomRenderHookT t m (Compose (TraverseChild t m k) f a)
2069+drawChildUpdate initialEnv markReady child = do
2070+ let doc = _hydrationDomBuilderEnv_document initialEnv
2071+ unreadyChildren <- liftIO $ newIORef 0
2072+ liftIO (readIORef $ _hydrationDomBuilderEnv_hydrationMode initialEnv) >>= \case
2073+ HydrationMode_Hydrating -> do
2074+ childDelayedRef <- liftIO $ newIORef $ pure ()
2075+ result <- runReaderT (unHydrationDomBuilderT child) initialEnv
2076+ { _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
2077+ , _hydrationDomBuilderEnv_delayed = childDelayedRef
2078+ }
2079+ childDelayed <- liftIO $ readIORef childDelayedRef
2080+ return $ Compose $ TraverseChild
2081+ { _traverseChild_result = result
2082+ , _traverseChild_mode = Left TraverseChildHydration
2083+ { _traverseChildHydration_delayed = do
2084+ placeholder <- createTextNode doc ("" :: Text)
2085+ insertAfterPreviousNode placeholder
2086+ childDelayed
2087+ pure placeholder
2088+ }
2089+ }
2090+ HydrationMode_Immediate -> do
2091+ childReadyState <- liftIO $ newIORef $ ChildReadyState_Unready Nothing
2092+ df <- createDocumentFragment doc
2093+ placeholder <- createTextNode doc ("" :: Text)
2094+ Node.appendChild_ df placeholder
2095+ result <- runReaderT (unHydrationDomBuilderT child) initialEnv
2096+ { _hydrationDomBuilderEnv_parent = Left $ toNode df
2097+ , _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
2098+ , _hydrationDomBuilderEnv_commitAction = markReady childReadyState
2099+ }
2100+ u <- liftIO $ readIORef unreadyChildren
2101+ when (u == 0) $ liftIO $ writeIORef childReadyState ChildReadyState_Ready
2102+ return $ Compose $ TraverseChild
2103+ { _traverseChild_result = result
2104+ , _traverseChild_mode = Right TraverseChildImmediate
2105+ { _traverseChildImmediate_fragment = df
2106+ , _traverseChildImmediate_placeholder = placeholder
2107+ , _traverseChildImmediate_childReadyState = childReadyState
2108+ }
2109+ }
2110+
2111+{-# SPECIALIZE drawChildUpdate
2112+ :: HydrationDomBuilderEnv DomTimeline HydrationM
2113+ -> (IORef (ChildReadyState Int) -> JSM ())
2114+ -> HydrationDomBuilderT s DomTimeline HydrationM (Identity a)
2115+ -> DomRenderHookT DomTimeline HydrationM (Compose (TraverseChild DomTimeline HydrationM Int) Identity a)
2116+ #-}
2117+
2118+{-# SPECIALIZE drawChildUpdate
2119+ :: HydrationDomBuilderEnv DomTimeline HydrationM
2120+ -> (IORef (ChildReadyState (Some k)) -> JSM ())
2121+ -> HydrationDomBuilderT s DomTimeline HydrationM (f a)
2122+ -> DomRenderHookT DomTimeline HydrationM (Compose (TraverseChild DomTimeline HydrationM (Some k)) f a)
2123+ #-}
2124+
2125+{-# INLINABLE drawChildUpdateInt #-}
2126+drawChildUpdateInt :: (MonadIO m, MonadJSM m, Reflex t)
2127+ => HydrationDomBuilderEnv t m
2128+ -> (IORef (ChildReadyState k) -> JSM ())
2129+ -> HydrationDomBuilderT s t m v
2130+ -> DomRenderHookT t m (TraverseChild t m k v)
2131+drawChildUpdateInt env mark m = fmap runIdentity . getCompose <$> drawChildUpdate env mark (Identity <$> m)
2132+
2133+{-# SPECIALIZE drawChildUpdateInt
2134+ :: HydrationDomBuilderEnv DomTimeline HydrationM
2135+ -> (IORef (ChildReadyState k) -> JSM ())
2136+ -> HydrationDomBuilderT s DomTimeline HydrationM v
2137+ -> DomRenderHookT DomTimeline HydrationM (TraverseChild DomTimeline HydrationM k v)
2138+ #-}
2139+
2140+{-# INLINE mkHasFocus #-}
2141+mkHasFocus
2142+ :: (HasDocument m, MonadJSM m, IsNode (RawElement d), MonadHold t m, Reflex t, DOM.IsDocumentOrShadowRoot (RawDocument (DomBuilderSpace m)))
2143+ => Element er d t -> m (Dynamic t Bool)
2144+mkHasFocus e = do
2145+ doc <- askDocument
2146+ initialFocus <- Node.isSameNode (toNode $ _element_raw e) . fmap toNode =<< Document.getActiveElement doc
2147+ holdDyn initialFocus $ leftmost
2148+ [ False <$ Reflex.select (_element_events e) (WrapArg Blur)
2149+ , True <$ Reflex.select (_element_events e) (WrapArg Focus)
2150+ ]
2151+
2152+insertBefore :: (MonadJSM m, IsNode new, IsNode existing) => new -> existing -> m ()
2153+insertBefore new existing = do
2154+ p <- getParentNodeUnchecked existing
2155+ Node.insertBefore_ p new (Just existing) -- If there's no parent, that means we've been removed from the DOM; this should not happen if the we're removing ourselves from the performEvent properly
2156+
2157+type ImmediateDomBuilderT = HydrationDomBuilderT GhcjsDomSpace
2158+
2159+instance PerformEvent t m => PerformEvent t (HydrationDomBuilderT s t m) where
2160+ type Performable (HydrationDomBuilderT s t m) = Performable m
2161+ {-# INLINABLE performEvent_ #-}
2162+ performEvent_ e = lift $ performEvent_ e
2163+ {-# INLINABLE performEvent #-}
2164+ performEvent e = lift $ performEvent e
2165+
2166+instance PostBuild t m => PostBuild t (HydrationDomBuilderT s t m) where
2167+ {-# INLINABLE getPostBuild #-}
2168+ getPostBuild = lift getPostBuild
2169+
2170+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (HydrationDomBuilderT s t m) where
2171+ {-# INLINABLE newEventWithTrigger #-}
2172+ newEventWithTrigger = lift . newEventWithTrigger
2173+ {-# INLINABLE newFanEventWithTrigger #-}
2174+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
2175+
2176+instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (HydrationDomBuilderT s t m) where
2177+ {-# INLINABLE newTriggerEvent #-}
2178+ newTriggerEvent = HydrationDomBuilderT . lift $ newTriggerEvent
2179+ {-# INLINABLE newTriggerEventWithOnComplete #-}
2180+ newTriggerEventWithOnComplete = HydrationDomBuilderT . lift $ newTriggerEventWithOnComplete
2181+ {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
2182+ newEventWithLazyTriggerWithOnComplete f = HydrationDomBuilderT . lift $ newEventWithLazyTriggerWithOnComplete f
2183+
2184+instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (DomRenderHookT t m) where
2185+ {-# INLINABLE newTriggerEvent #-}
2186+ newTriggerEvent = DomRenderHookT . lift $ newTriggerEvent
2187+ {-# INLINABLE newTriggerEventWithOnComplete #-}
2188+ newTriggerEventWithOnComplete = DomRenderHookT . lift $ newTriggerEventWithOnComplete
2189+ {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
2190+ newEventWithLazyTriggerWithOnComplete f = DomRenderHookT . lift $ newEventWithLazyTriggerWithOnComplete f
2191+
2192+instance HasJSContext m => HasJSContext (HydrationDomBuilderT s t m) where
2193+ type JSContextPhantom (HydrationDomBuilderT s t m) = JSContextPhantom m
2194+ askJSContext = lift askJSContext
2195+
2196+instance MonadRef m => MonadRef (HydrationDomBuilderT s t m) where
2197+ type Ref (HydrationDomBuilderT s t m) = Ref m
2198+ {-# INLINABLE newRef #-}
2199+ newRef = lift . newRef
2200+ {-# INLINABLE readRef #-}
2201+ readRef = lift . readRef
2202+ {-# INLINABLE writeRef #-}
2203+ writeRef r = lift . writeRef r
2204+
2205+instance MonadAtomicRef m => MonadAtomicRef (HydrationDomBuilderT s t m) where
2206+ {-# INLINABLE atomicModifyRef #-}
2207+ atomicModifyRef r = lift . atomicModifyRef r
2208+
2209+instance (HasJS x m, ReflexHost t) => HasJS x (HydrationDomBuilderT s t m) where
2210+ type JSX (HydrationDomBuilderT s t m) = JSX m
2211+ liftJS = lift . liftJS
2212+
2213+type family EventType en where
2214+ EventType 'AbortTag = UIEvent
2215+ EventType 'BlurTag = FocusEvent
2216+ EventType 'ChangeTag = DOM.Event
2217+ EventType 'ClickTag = MouseEvent
2218+ EventType 'ContextmenuTag = MouseEvent
2219+ EventType 'DblclickTag = MouseEvent
2220+ EventType 'DragTag = MouseEvent
2221+ EventType 'DragendTag = MouseEvent
2222+ EventType 'DragenterTag = MouseEvent
2223+ EventType 'DragleaveTag = MouseEvent
2224+ EventType 'DragoverTag = MouseEvent
2225+ EventType 'DragstartTag = MouseEvent
2226+ EventType 'DropTag = MouseEvent
2227+ EventType 'ErrorTag = UIEvent
2228+ EventType 'FocusTag = FocusEvent
2229+ EventType 'InputTag = DOM.Event
2230+ EventType 'InvalidTag = DOM.Event
2231+ EventType 'KeydownTag = KeyboardEvent
2232+ EventType 'KeypressTag = KeyboardEvent
2233+ EventType 'KeyupTag = KeyboardEvent
2234+ EventType 'LoadTag = UIEvent
2235+ EventType 'MousedownTag = MouseEvent
2236+ EventType 'MouseenterTag = MouseEvent
2237+ EventType 'MouseleaveTag = MouseEvent
2238+ EventType 'MousemoveTag = MouseEvent
2239+ EventType 'MouseoutTag = MouseEvent
2240+ EventType 'MouseoverTag = MouseEvent
2241+ EventType 'MouseupTag = MouseEvent
2242+ EventType 'MousewheelTag = MouseEvent
2243+ EventType 'ScrollTag = UIEvent
2244+ EventType 'SelectTag = UIEvent
2245+ EventType 'SubmitTag = DOM.Event
2246+ EventType 'WheelTag = WheelEvent
2247+ EventType 'BeforecutTag = ClipboardEvent
2248+ EventType 'CutTag = ClipboardEvent
2249+ EventType 'BeforecopyTag = ClipboardEvent
2250+ EventType 'CopyTag = ClipboardEvent
2251+ EventType 'BeforepasteTag = ClipboardEvent
2252+ EventType 'PasteTag = ClipboardEvent
2253+ EventType 'ResetTag = DOM.Event
2254+ EventType 'SearchTag = DOM.Event
2255+ EventType 'SelectstartTag = DOM.Event
2256+ EventType 'TouchstartTag = TouchEvent
2257+ EventType 'TouchmoveTag = TouchEvent
2258+ EventType 'TouchendTag = TouchEvent
2259+ EventType 'TouchcancelTag = TouchEvent
2260+
2261+{-# INLINABLE defaultDomEventHandler #-}
2262+defaultDomEventHandler :: IsElement e => e -> EventName en -> EventM e (EventType en) (Maybe (EventResult en))
2263+defaultDomEventHandler e evt = fmap (Just . EventResult) $ case evt of
2264+ Click -> return ()
2265+ Dblclick -> getMouseEventCoords
2266+ Keypress -> getKeyEvent
2267+ Scroll -> fromIntegral <$> getScrollTop e
2268+ Keydown -> getKeyEvent
2269+ Keyup -> getKeyEvent
2270+ Mousemove -> getMouseEventCoords
2271+ Mouseup -> getMouseEventCoords
2272+ Mousedown -> getMouseEventCoords
2273+ Mouseenter -> return ()
2274+ Mouseleave -> return ()
2275+ Focus -> return ()
2276+ Blur -> return ()
2277+ Change -> return ()
2278+ Drag -> return ()
2279+ Dragend -> return ()
2280+ Dragenter -> return ()
2281+ Dragleave -> return ()
2282+ Dragover -> return ()
2283+ Dragstart -> return ()
2284+ Drop -> return ()
2285+ Abort -> return ()
2286+ Contextmenu -> return ()
2287+ Error -> return ()
2288+ Input -> return ()
2289+ Invalid -> return ()
2290+ Load -> return ()
2291+ Mouseout -> return ()
2292+ Mouseover -> return ()
2293+ Select -> return ()
2294+ Submit -> return ()
2295+ Beforecut -> return ()
2296+ Cut -> return ()
2297+ Beforecopy -> return ()
2298+ Copy -> return ()
2299+ Beforepaste -> return ()
2300+ Paste -> getPasteData
2301+ Reset -> return ()
2302+ Search -> return ()
2303+ Selectstart -> return ()
2304+ Touchstart -> getTouchEvent
2305+ Touchmove -> getTouchEvent
2306+ Touchend -> getTouchEvent
2307+ Touchcancel -> getTouchEvent
2308+ Mousewheel -> return ()
2309+ Wheel -> getWheelEvent
2310+
2311+{-# INLINABLE defaultDomWindowEventHandler #-}
2312+defaultDomWindowEventHandler :: DOM.Window -> EventName en -> EventM DOM.Window (EventType en) (Maybe (EventResult en))
2313+defaultDomWindowEventHandler w evt = fmap (Just . EventResult) $ case evt of
2314+ Click -> return ()
2315+ Dblclick -> getMouseEventCoords
2316+ Keypress -> getKeyEvent
2317+ Scroll -> Window.getScrollY w
2318+ Keydown -> getKeyEvent
2319+ Keyup -> getKeyEvent
2320+ Mousemove -> getMouseEventCoords
2321+ Mouseup -> getMouseEventCoords
2322+ Mousedown -> getMouseEventCoords
2323+ Mouseenter -> return ()
2324+ Mouseleave -> return ()
2325+ Focus -> return ()
2326+ Blur -> return ()
2327+ Change -> return ()
2328+ Drag -> return ()
2329+ Dragend -> return ()
2330+ Dragenter -> return ()
2331+ Dragleave -> return ()
2332+ Dragover -> return ()
2333+ Dragstart -> return ()
2334+ Drop -> return ()
2335+ Abort -> return ()
2336+ Contextmenu -> return ()
2337+ Error -> return ()
2338+ Input -> return ()
2339+ Invalid -> return ()
2340+ Load -> return ()
2341+ Mouseout -> return ()
2342+ Mouseover -> return ()
2343+ Select -> return ()
2344+ Submit -> return ()
2345+ Beforecut -> return ()
2346+ Cut -> return ()
2347+ Beforecopy -> return ()
2348+ Copy -> return ()
2349+ Beforepaste -> return ()
2350+ Paste -> getPasteData
2351+ Reset -> return ()
2352+ Search -> return ()
2353+ Selectstart -> return ()
2354+ Touchstart -> getTouchEvent
2355+ Touchmove -> getTouchEvent
2356+ Touchend -> getTouchEvent
2357+ Touchcancel -> getTouchEvent
2358+ Mousewheel -> return ()
2359+ Wheel -> getWheelEvent
2360+
2361+{-# INLINABLE withIsEvent #-}
2362+withIsEvent :: EventName en -> (IsEvent (EventType en) => r) -> r
2363+withIsEvent en r = case en of
2364+ Click -> r
2365+ Dblclick -> r
2366+ Keypress -> r
2367+ Scroll -> r
2368+ Keydown -> r
2369+ Keyup -> r
2370+ Mousemove -> r
2371+ Mouseup -> r
2372+ Mousedown -> r
2373+ Mouseenter -> r
2374+ Mouseleave -> r
2375+ Focus -> r
2376+ Blur -> r
2377+ Change -> r
2378+ Drag -> r
2379+ Dragend -> r
2380+ Dragenter -> r
2381+ Dragleave -> r
2382+ Dragover -> r
2383+ Dragstart -> r
2384+ Drop -> r
2385+ Abort -> r
2386+ Contextmenu -> r
2387+ Error -> r
2388+ Input -> r
2389+ Invalid -> r
2390+ Load -> r
2391+ Mouseout -> r
2392+ Mouseover -> r
2393+ Select -> r
2394+ Submit -> r
2395+ Beforecut -> r
2396+ Cut -> r
2397+ Beforecopy -> r
2398+ Copy -> r
2399+ Beforepaste -> r
2400+ Paste -> r
2401+ Reset -> r
2402+ Search -> r
2403+ Selectstart -> r
2404+ Touchstart -> r
2405+ Touchmove -> r
2406+ Touchend -> r
2407+ Touchcancel -> r
2408+ Mousewheel -> r
2409+ Wheel -> r
2410+
2411+showEventName :: EventName en -> String
2412+showEventName en = case en of
2413+ Abort -> "Abort"
2414+ Blur -> "Blur"
2415+ Change -> "Change"
2416+ Click -> "Click"
2417+ Contextmenu -> "Contextmenu"
2418+ Dblclick -> "Dblclick"
2419+ Drag -> "Drag"
2420+ Dragend -> "Dragend"
2421+ Dragenter -> "Dragenter"
2422+ Dragleave -> "Dragleave"
2423+ Dragover -> "Dragover"
2424+ Dragstart -> "Dragstart"
2425+ Drop -> "Drop"
2426+ Error -> "Error"
2427+ Focus -> "Focus"
2428+ Input -> "Input"
2429+ Invalid -> "Invalid"
2430+ Keydown -> "Keydown"
2431+ Keypress -> "Keypress"
2432+ Keyup -> "Keyup"
2433+ Load -> "Load"
2434+ Mousedown -> "Mousedown"
2435+ Mouseenter -> "Mouseenter"
2436+ Mouseleave -> "Mouseleave"
2437+ Mousemove -> "Mousemove"
2438+ Mouseout -> "Mouseout"
2439+ Mouseover -> "Mouseover"
2440+ Mouseup -> "Mouseup"
2441+ Mousewheel -> "Mousewheel"
2442+ Scroll -> "Scroll"
2443+ Select -> "Select"
2444+ Submit -> "Submit"
2445+ Wheel -> "Wheel"
2446+ Beforecut -> "Beforecut"
2447+ Cut -> "Cut"
2448+ Beforecopy -> "Beforecopy"
2449+ Copy -> "Copy"
2450+ Beforepaste -> "Beforepaste"
2451+ Paste -> "Paste"
2452+ Reset -> "Reset"
2453+ Search -> "Search"
2454+ Selectstart -> "Selectstart"
2455+ Touchstart -> "Touchstart"
2456+ Touchmove -> "Touchmove"
2457+ Touchend -> "Touchend"
2458+ Touchcancel -> "Touchcancel"
2459+
2460+--TODO: Get rid of this hack
2461+-- ElementEventTarget is here to allow us to treat SVG and HTML elements as the same thing; without it, we'll break any existing SVG code.
2462+newtype ElementEventTarget = ElementEventTarget DOM.Element deriving (DOM.IsGObject, DOM.ToJSVal, DOM.IsSlotable, DOM.IsParentNode, DOM.IsNonDocumentTypeChildNode, DOM.IsChildNode, DOM.IsAnimatable, IsNode, IsElement)
2463+instance DOM.FromJSVal ElementEventTarget where
2464+ fromJSVal = fmap (fmap ElementEventTarget) . DOM.fromJSVal
2465+instance DOM.IsEventTarget ElementEventTarget
2466+instance DOM.IsGlobalEventHandlers ElementEventTarget
2467+instance DOM.IsDocumentAndElementEventHandlers ElementEventTarget
2468+
2469+{-# INLINABLE elementOnEventName #-}
2470+elementOnEventName :: IsElement e => EventName en -> e -> EventM e (EventType en) () -> JSM (JSM ())
2471+elementOnEventName en e_ = let e = ElementEventTarget (DOM.toElement e_) in case en of
2472+ Abort -> on e Events.abort
2473+ Blur -> on e Events.blur
2474+ Change -> on e Events.change
2475+ Click -> on e Events.click
2476+ Contextmenu -> on e Events.contextMenu
2477+ Dblclick -> on e Events.dblClick
2478+ Drag -> on e Events.drag
2479+ Dragend -> on e Events.dragEnd
2480+ Dragenter -> on e Events.dragEnter
2481+ Dragleave -> on e Events.dragLeave
2482+ Dragover -> on e Events.dragOver
2483+ Dragstart -> on e Events.dragStart
2484+ Drop -> on e Events.drop
2485+ Error -> on e Events.error
2486+ Focus -> on e Events.focus
2487+ Input -> on e Events.input
2488+ Invalid -> on e Events.invalid
2489+ Keydown -> on e Events.keyDown
2490+ Keypress -> on e Events.keyPress
2491+ Keyup -> on e Events.keyUp
2492+ Load -> on e Events.load
2493+ Mousedown -> on e Events.mouseDown
2494+ Mouseenter -> on e Events.mouseEnter
2495+ Mouseleave -> on e Events.mouseLeave
2496+ Mousemove -> on e Events.mouseMove
2497+ Mouseout -> on e Events.mouseOut
2498+ Mouseover -> on e Events.mouseOver
2499+ Mouseup -> on e Events.mouseUp
2500+ Mousewheel -> on e Events.mouseWheel
2501+ Scroll -> on e Events.scroll
2502+ Select -> on e Events.select
2503+ Submit -> on e Events.submit
2504+ Wheel -> on e Events.wheel
2505+ Beforecut -> on e Events.beforeCut
2506+ Cut -> on e Events.cut
2507+ Beforecopy -> on e Events.beforeCopy
2508+ Copy -> on e Events.copy
2509+ Beforepaste -> on e Events.beforePaste
2510+ Paste -> on e Events.paste
2511+ Reset -> on e Events.reset
2512+ Search -> on e Events.search
2513+ Selectstart -> on e Element.selectStart
2514+ Touchstart -> on e Events.touchStart
2515+ Touchmove -> on e Events.touchMove
2516+ Touchend -> on e Events.touchEnd
2517+ Touchcancel -> on e Events.touchCancel
2518+
2519+{-# INLINABLE windowOnEventName #-}
2520+windowOnEventName :: EventName en -> DOM.Window -> EventM DOM.Window (EventType en) () -> JSM (JSM ())
2521+windowOnEventName en e = case en of
2522+ Abort -> on e Events.abort
2523+ Blur -> on e Events.blur
2524+ Change -> on e Events.change
2525+ Click -> on e Events.click
2526+ Contextmenu -> on e Events.contextMenu
2527+ Dblclick -> on e Events.dblClick
2528+ Drag -> on e Events.drag
2529+ Dragend -> on e Events.dragEnd
2530+ Dragenter -> on e Events.dragEnter
2531+ Dragleave -> on e Events.dragLeave
2532+ Dragover -> on e Events.dragOver
2533+ Dragstart -> on e Events.dragStart
2534+ Drop -> on e Events.drop
2535+ Error -> on e Events.error
2536+ Focus -> on e Events.focus
2537+ Input -> on e Events.input
2538+ Invalid -> on e Events.invalid
2539+ Keydown -> on e Events.keyDown
2540+ Keypress -> on e Events.keyPress
2541+ Keyup -> on e Events.keyUp
2542+ Load -> on e Events.load
2543+ Mousedown -> on e Events.mouseDown
2544+ Mouseenter -> on e Events.mouseEnter
2545+ Mouseleave -> on e Events.mouseLeave
2546+ Mousemove -> on e Events.mouseMove
2547+ Mouseout -> on e Events.mouseOut
2548+ Mouseover -> on e Events.mouseOver
2549+ Mouseup -> on e Events.mouseUp
2550+ Mousewheel -> on e Events.mouseWheel
2551+ Scroll -> on e Events.scroll
2552+ Select -> on e Events.select
2553+ Submit -> on e Events.submit
2554+ Wheel -> on e Events.wheel
2555+ Beforecut -> const $ return $ return () --TODO
2556+ Cut -> const $ return $ return () --TODO
2557+ Beforecopy -> const $ return $ return () --TODO
2558+ Copy -> const $ return $ return () --TODO
2559+ Beforepaste -> const $ return $ return () --TODO
2560+ Paste -> const $ return $ return () --TODO
2561+ Reset -> on e Events.reset
2562+ Search -> on e Events.search
2563+ Selectstart -> const $ return $ return () --TODO
2564+ Touchstart -> on e Events.touchStart
2565+ Touchmove -> on e Events.touchMove
2566+ Touchend -> on e Events.touchEnd
2567+ Touchcancel -> on e Events.touchCancel
2568+
2569+{-# INLINABLE wrapDomEvent #-}
2570+wrapDomEvent :: (TriggerEvent t m, MonadJSM m) => e -> (e -> EventM e event () -> JSM (JSM ())) -> EventM e event a -> m (Event t a)
2571+wrapDomEvent el elementOnevent getValue = wrapDomEventMaybe el elementOnevent $ fmap Just getValue
2572+
2573+{-# INLINABLE subscribeDomEvent #-}
2574+subscribeDomEvent :: (EventM e event () -> JSM (JSM ()))
2575+ -> EventM e event (Maybe a)
2576+ -> Chan [DSum (EventTriggerRef t) TriggerInvocation]
2577+ -> EventTrigger t a
2578+ -> JSM (JSM ())
2579+subscribeDomEvent elementOnevent getValue eventChan et = elementOnevent $ do
2580+ mv <- getValue
2581+ forM_ mv $ \v -> liftIO $ do
2582+ --TODO: I don't think this is quite right: if a new trigger is created between when this is enqueued and when it fires, this may not work quite right
2583+ etr <- newIORef $ Just et
2584+ writeChan eventChan [EventTriggerRef etr :=> TriggerInvocation v (return ())]
2585+
2586+{-# INLINABLE wrapDomEventMaybe #-}
2587+wrapDomEventMaybe :: (TriggerEvent t m, MonadJSM m)
2588+ => e
2589+ -> (e -> EventM e event () -> JSM (JSM ()))
2590+ -> EventM e event (Maybe a)
2591+ -> m (Event t a)
2592+wrapDomEventMaybe el elementOnevent getValue = do
2593+ ctx <- askJSM
2594+ newEventWithLazyTriggerWithOnComplete $ \trigger -> (`runJSM` ctx) <$> (`runJSM` ctx) (elementOnevent el $ do
2595+ mv <- getValue
2596+ forM_ mv $ \v -> liftIO $ trigger v $ return ())
2597+
2598+{-# INLINABLE wrapDomEventsMaybe #-}
2599+wrapDomEventsMaybe :: (MonadJSM m, MonadReflexCreateTrigger t m)
2600+ => e
2601+ -> (forall en. IsEvent (EventType en) => EventName en -> EventM e (EventType en) (Maybe (f en)))
2602+ -> (forall en. EventName en -> e -> EventM e (EventType en) () -> JSM (JSM ()))
2603+ -> ImmediateDomBuilderT t m (EventSelector t (WrapArg f EventName))
2604+wrapDomEventsMaybe target handlers onEventName = do
2605+ ctx <- askJSM
2606+ eventChan <- askEvents
2607+ e <- lift $ newFanEventWithTrigger $ \(WrapArg en) -> withIsEvent en
2608+ (((`runJSM` ctx) <$>) . (`runJSM` ctx) . subscribeDomEvent (onEventName en target) (handlers en) eventChan)
2609+ return $! e
2610+
2611+{-# INLINABLE getKeyEvent #-}
2612+getKeyEvent :: EventM e KeyboardEvent Word
2613+getKeyEvent = do
2614+ e <- event
2615+ which <- KeyboardEvent.getWhich e
2616+ if which /= 0 then return which else do
2617+ charCode <- getCharCode e
2618+ if charCode /= 0 then return charCode else
2619+ getKeyCode e
2620+
2621+{-# INLINABLE getMouseEventCoords #-}
2622+getMouseEventCoords :: EventM e MouseEvent (Int, Int)
2623+getMouseEventCoords = do
2624+ e <- event
2625+ bisequence (getClientX e, getClientY e)
2626+
2627+{-# INLINABLE getPasteData #-}
2628+getPasteData :: EventM e ClipboardEvent (Maybe Text)
2629+getPasteData = do
2630+ e <- event
2631+ mdt <- ClipboardEvent.getClipboardData e
2632+ case mdt of
2633+ Nothing -> return Nothing
2634+ Just dt -> Just <$> DataTransfer.getData dt ("text" :: Text)
2635+
2636+{-# INLINABLE getTouchEvent #-}
2637+getTouchEvent :: EventM e TouchEvent TouchEventResult
2638+getTouchEvent = do
2639+ let touchResults ts = do
2640+ n <- TouchList.getLength ts
2641+ forM (takeWhile (< n) [0..]) $ \ix -> do
2642+ t <- TouchList.item ts ix
2643+ identifier <- Touch.getIdentifier t
2644+ screenX <- Touch.getScreenX t
2645+ screenY <- Touch.getScreenY t
2646+ clientX <- Touch.getClientX t
2647+ clientY <- Touch.getClientY t
2648+ pageX <- Touch.getPageX t
2649+ pageY <- Touch.getPageY t
2650+ return TouchResult
2651+ { _touchResult_identifier = identifier
2652+ , _touchResult_screenX = screenX
2653+ , _touchResult_screenY = screenY
2654+ , _touchResult_clientX = clientX
2655+ , _touchResult_clientY = clientY
2656+ , _touchResult_pageX = pageX
2657+ , _touchResult_pageY = pageY
2658+ }
2659+ e <- event
2660+ altKey <- TouchEvent.getAltKey e
2661+ ctrlKey <- TouchEvent.getCtrlKey e
2662+ shiftKey <- TouchEvent.getShiftKey e
2663+ metaKey <- TouchEvent.getMetaKey e
2664+ changedTouches <- touchResults =<< TouchEvent.getChangedTouches e
2665+ targetTouches <- touchResults =<< TouchEvent.getTargetTouches e
2666+ touches <- touchResults =<< TouchEvent.getTouches e
2667+ return $ TouchEventResult
2668+ { _touchEventResult_altKey = altKey
2669+ , _touchEventResult_changedTouches = changedTouches
2670+ , _touchEventResult_ctrlKey = ctrlKey
2671+ , _touchEventResult_metaKey = metaKey
2672+ , _touchEventResult_shiftKey = shiftKey
2673+ , _touchEventResult_targetTouches = targetTouches
2674+ , _touchEventResult_touches = touches
2675+ }
2676+
2677+{-# INLINABLE getWheelEvent #-}
2678+getWheelEvent :: EventM e WheelEvent WheelEventResult
2679+getWheelEvent = do
2680+ e <- event
2681+ dx :: Double <- WheelEvent.getDeltaX e
2682+ dy :: Double <- WheelEvent.getDeltaY e
2683+ dz :: Double <- WheelEvent.getDeltaZ e
2684+ deltaMode :: Word <- WheelEvent.getDeltaMode e
2685+ return $ WheelEventResult
2686+ { _wheelEventResult_deltaX = dx
2687+ , _wheelEventResult_deltaY = dy
2688+ , _wheelEventResult_deltaZ = dz
2689+ , _wheelEventResult_deltaMode = case deltaMode of
2690+ 0 -> DeltaPixel
2691+ 1 -> DeltaLine
2692+ 2 -> DeltaPage
2693+ -- See https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode
2694+ _ -> error "getWheelEvent: impossible encoding"
2695+ }
2696+
2697+instance MonadSample t m => MonadSample t (HydrationDomBuilderT s t m) where
2698+ {-# INLINABLE sample #-}
2699+ sample = lift . sample
2700+
2701+instance MonadHold t m => MonadHold t (HydrationDomBuilderT s t m) where
2702+ {-# INLINABLE hold #-}
2703+ hold v0 v' = lift $ hold v0 v'
2704+ {-# INLINABLE holdDyn #-}
2705+ holdDyn v0 v' = lift $ holdDyn v0 v'
2706+ {-# INLINABLE holdIncremental #-}
2707+ holdIncremental v0 v' = lift $ holdIncremental v0 v'
2708+ {-# INLINABLE buildDynamic #-}
2709+ buildDynamic a0 = lift . buildDynamic a0
2710+ {-# INLINABLE headE #-}
2711+ headE = lift . headE
2712+
2713+data WindowConfig t = WindowConfig -- No config options yet
2714+
2715+instance Default (WindowConfig t) where
2716+ def = WindowConfig
2717+
2718+data Window t = Window
2719+ { _window_events :: EventSelector t (WrapArg EventResult EventName)
2720+ , _window_raw :: DOM.Window
2721+ }
2722+
2723+wrapWindow :: (MonadJSM m, MonadReflexCreateTrigger t m) => DOM.Window -> WindowConfig t -> HydrationDomBuilderT GhcjsDomSpace t m (Window t)
2724+wrapWindow wv _ = do
2725+ events <- wrapDomEventsMaybe wv (defaultDomWindowEventHandler wv) windowOnEventName
2726+ return $ Window
2727+ { _window_events = events
2728+ , _window_raw = wv
2729+ }
2730+
2731+#ifdef USE_TEMPLATE_HASKELL
2732+makeLenses ''GhcjsEventSpec
2733+#endif
reflex-dom-core/src/Reflex/Dom/Builder/InputDisabled.hsnew file+116
@@ -0,0 +1,116 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4+{-# LANGUAGE MultiParamTypeClasses #-}
5+{-# LANGUAGE OverloadedStrings #-}
6+{-# LANGUAGE StandaloneDeriving #-}
7+{-# LANGUAGE TypeFamilies #-}
8+{-# LANGUAGE UndecidableInstances #-}
9+module Reflex.Dom.Builder.InputDisabled where
10+
11+import Control.Monad.Fix
12+import Control.Monad.Primitive
13+import Control.Monad.Ref
14+import Control.Monad.Trans
15+import Control.Monad.Trans.Control
16+import Data.Coerce
17+import qualified Data.Map as Map
18+import Foreign.JavaScript.TH
19+#ifndef ghcjs_HOST_OS
20+import GHCJS.DOM.Types (MonadJSM (..))
21+#endif
22+import Reflex
23+import Reflex.Dom.Builder.Class
24+import Reflex.Dom.Builder.Immediate (HasDocument (..))
25+import Reflex.Host.Class
26+
27+-- | A DomBuilder transformer that disables all 'inputElement's,
28+-- 'textAreaElement's, and 'selectElement's by adding the "disabled" HTML
29+-- attribute. Note that 'element's that happen to have "input", "textarea", or
30+-- "select" as their tag will NOT be disabled.
31+newtype InputDisabledT m a = InputDisabledT { runInputDisabledT :: m a } deriving (Functor, Applicative, Monad, MonadAtomicRef, MonadFix, MonadIO)
32+
33+#ifndef ghcjs_HOST_OS
34+instance MonadJSM m => MonadJSM (InputDisabledT m) where
35+ liftJSM' = InputDisabledT . liftJSM'
36+#endif
37+
38+deriving instance MonadSample t m => MonadSample t (InputDisabledT m)
39+deriving instance MonadHold t m => MonadHold t (InputDisabledT m)
40+
41+instance MonadTrans InputDisabledT where
42+ lift = InputDisabledT
43+
44+instance MonadTransControl InputDisabledT where
45+ type StT InputDisabledT a = a
46+ liftWith f = InputDisabledT $ f runInputDisabledT
47+ restoreT = InputDisabledT
48+
49+instance MonadRef m => MonadRef (InputDisabledT m) where
50+ type Ref (InputDisabledT m) = Ref m
51+ newRef = lift . newRef
52+ readRef = lift . readRef
53+ writeRef ref = lift . writeRef ref
54+
55+instance PerformEvent t m => PerformEvent t (InputDisabledT m) where
56+ type Performable (InputDisabledT m) = Performable m
57+ performEvent_ = lift . performEvent_
58+ performEvent = lift . performEvent
59+
60+instance PrimMonad m => PrimMonad (InputDisabledT m) where
61+ type PrimState (InputDisabledT m) = PrimState m
62+ primitive = lift . primitive
63+
64+disableElementConfig :: Reflex t => ElementConfig er t m -> ElementConfig er t m
65+disableElementConfig cfg = cfg
66+ { _elementConfig_initialAttributes = Map.insert "disabled" "disabled" $ _elementConfig_initialAttributes cfg
67+ , _elementConfig_modifyAttributes = fmap (Map.delete "disabled") <$> _elementConfig_modifyAttributes cfg
68+ }
69+
70+instance PostBuild t m => PostBuild t (InputDisabledT m) where
71+ getPostBuild = lift getPostBuild
72+
73+deriving instance TriggerEvent t m => TriggerEvent t (InputDisabledT m)
74+
75+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (InputDisabledT m) where
76+ newEventWithTrigger = lift . newEventWithTrigger
77+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
78+
79+instance Adjustable t m => Adjustable t (InputDisabledT m) where
80+ runWithReplace a0 a' = InputDisabledT $ runWithReplace (coerce a0) (coerceEvent a')
81+ traverseDMapWithKeyWithAdjust f dm0 dm' = InputDisabledT $ traverseDMapWithKeyWithAdjust (\k v -> runInputDisabledT $ f k v) (coerce dm0) (coerceEvent dm')
82+ traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = InputDisabledT $ traverseDMapWithKeyWithAdjustWithMove (\k v -> runInputDisabledT $ f k v) (coerce dm0) (coerceEvent dm')
83+ traverseIntMapWithKeyWithAdjust f m0 m' = InputDisabledT $ traverseIntMapWithKeyWithAdjust (\k v -> runInputDisabledT $ f k v) (coerce m0) (coerceEvent m')
84+
85+instance NotReady t m => NotReady t (InputDisabledT m) where
86+ notReadyUntil = lift . notReadyUntil
87+ notReady = lift notReady
88+
89+instance DomBuilder t m => DomBuilder t (InputDisabledT m) where
90+ type DomBuilderSpace (InputDisabledT m) = DomBuilderSpace m
91+ inputElement cfg = lift $ inputElement $ cfg
92+ { _inputElementConfig_elementConfig = disableElementConfig $ _inputElementConfig_elementConfig cfg
93+ }
94+ textAreaElement cfg = lift $ textAreaElement $ cfg
95+ { _textAreaElementConfig_elementConfig = disableElementConfig $ _textAreaElementConfig_elementConfig cfg
96+ }
97+ selectElement cfg child = do
98+ let cfg' = cfg
99+ { _selectElementConfig_elementConfig = disableElementConfig $ _selectElementConfig_elementConfig cfg
100+ }
101+ lift $ selectElement cfg' $ runInputDisabledT child
102+
103+instance HasDocument m => HasDocument (InputDisabledT m)
104+
105+instance HasJSContext m => HasJSContext (InputDisabledT m) where
106+ type JSContextPhantom (InputDisabledT m) = JSContextPhantom m
107+ askJSContext = lift askJSContext
108+
109+instance HasJS js m => HasJS js (InputDisabledT m) where
110+ type JSX (InputDisabledT m) = JSX m
111+ liftJS = lift . liftJS
112+
113+instance DomRenderHook t m => DomRenderHook t (InputDisabledT m) where
114+ withRenderHook f = InputDisabledT . withRenderHook f . runInputDisabledT
115+ requestDomAction = InputDisabledT . requestDomAction
116+ requestDomAction_ = InputDisabledT . requestDomAction_
reflex-dom-core/src/Reflex/Dom/Builder/Static.hsnew file+399
@@ -0,0 +1,399 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE DeriveGeneric #-}
4+{-# LANGUAGE EmptyDataDecls #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8+{-# LANGUAGE MultiParamTypeClasses #-}
9+{-# LANGUAGE OverloadedStrings #-}
10+{-# LANGUAGE PolyKinds #-}
11+{-# LANGUAGE RankNTypes #-}
12+{-# LANGUAGE ScopedTypeVariables #-}
13+{-# LANGUAGE TypeFamilies #-}
14+{-# LANGUAGE TypeOperators #-}
15+{-# LANGUAGE UndecidableInstances #-}
16+module Reflex.Dom.Builder.Static where
17+
18+import Data.IORef (IORef)
19+import Blaze.ByteString.Builder.Html.Utf8
20+import Control.Lens hiding (element)
21+import Control.Monad.Exception
22+import Control.Monad.Identity
23+import Control.Monad.Primitive
24+import Control.Monad.Ref
25+import Control.Monad.State.Strict
26+import Control.Monad.Trans.Reader
27+import Data.ByteString (ByteString)
28+import Data.ByteString.Builder (Builder, byteString, toLazyByteString)
29+import qualified Data.ByteString.Lazy as LBS
30+import Data.Default
31+import Data.Dependent.Map (DMap)
32+import qualified Data.Dependent.Map as DMap
33+import Data.Dependent.Sum (DSum (..))
34+import Data.Functor.Compose
35+import Data.Functor.Constant
36+import Data.IntMap (IntMap)
37+import qualified Data.IntMap as IntMap
38+import qualified Data.Map as Map
39+import Data.Map.Misc (applyMap)
40+import Data.Maybe (fromMaybe)
41+import Data.Monoid ((<>))
42+import qualified Data.Set as Set
43+import Data.Text (Text)
44+import qualified Data.Text as T
45+import Data.Text.Encoding
46+import Data.Tuple
47+import GHC.Generics
48+import Reflex.Adjustable.Class
49+import Reflex.Class
50+import Reflex.Dom.Main (DomHost, DomTimeline, runDomHost)
51+import Reflex.Dom.Builder.Class
52+import Reflex.Dynamic
53+import Reflex.Host.Class
54+import Reflex.PerformEvent.Base
55+import Reflex.PerformEvent.Class
56+import Reflex.PostBuild.Base
57+import Reflex.PostBuild.Class
58+import Reflex.TriggerEvent.Class
59+
60+data StaticDomBuilderEnv t = StaticDomBuilderEnv
61+ { _staticDomBuilderEnv_shouldEscape :: Bool
62+ , _staticDomBuilderEnv_selectValue :: Maybe (Behavior t Text)
63+ -- ^ When the parent element is a "select" whose value has been set, this value tells us the current value.
64+ -- We use this to add a "selected" attribute to the appropriate "option" child element.
65+ -- This is not yet a perfect simulation of what the browser does, but it is much closer than doing nothing.
66+ -- TODO: Handle edge cases, e.g. setting to a value for which there is no option, then adding that option dynamically afterwards.
67+ , _staticDomBuilderEnv_nextRunWithReplaceKey :: IORef Int
68+ }
69+
70+newtype StaticDomBuilderT t m a = StaticDomBuilderT
71+ { unStaticDomBuilderT :: ReaderT (StaticDomBuilderEnv t) (StateT [Behavior t Builder] m) a -- Accumulated Html will be in reversed order
72+ }
73+ deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
74+
75+instance PrimMonad m => PrimMonad (StaticDomBuilderT x m) where
76+ type PrimState (StaticDomBuilderT x m) = PrimState m
77+ primitive = lift . primitive
78+
79+instance MonadTrans (StaticDomBuilderT t) where
80+ lift = StaticDomBuilderT . lift . lift
81+
82+runStaticDomBuilderT :: (Monad m, Reflex t) => StaticDomBuilderT t m a -> StaticDomBuilderEnv t -> m (a, Behavior t Builder)
83+runStaticDomBuilderT (StaticDomBuilderT a) e = do
84+ (result, a') <- runStateT (runReaderT a e) []
85+ return (result, mconcat $ reverse a')
86+
87+instance PostBuild t m => PostBuild t (StaticDomBuilderT t m) where
88+ {-# INLINABLE getPostBuild #-}
89+ getPostBuild = lift getPostBuild
90+
91+instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StaticDomBuilderT t m) where
92+ {-# INLINABLE newEventWithTrigger #-}
93+ newEventWithTrigger = lift . newEventWithTrigger
94+ {-# INLINABLE newFanEventWithTrigger #-}
95+ newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
96+
97+instance PerformEvent t m => PerformEvent t (StaticDomBuilderT t m) where
98+ type Performable (StaticDomBuilderT t m) = Performable m
99+ {-# INLINABLE performEvent_ #-}
100+ performEvent_ e = lift $ performEvent_ e
101+ {-# INLINABLE performEvent #-}
102+ performEvent e = lift $ performEvent e
103+
104+instance MonadSample t m => MonadSample t (StaticDomBuilderT t m) where
105+ {-# INLINABLE sample #-}
106+ sample = lift . sample
107+
108+instance MonadHold t m => MonadHold t (StaticDomBuilderT t m) where
109+ {-# INLINABLE hold #-}
110+ hold v0 v' = lift $ hold v0 v'
111+ {-# INLINABLE holdDyn #-}
112+ holdDyn v0 v' = lift $ holdDyn v0 v'
113+ {-# INLINABLE holdIncremental #-}
114+ holdIncremental v0 v' = lift $ holdIncremental v0 v'
115+ {-# INLINABLE buildDynamic #-}
116+ buildDynamic a0 = lift . buildDynamic a0
117+ {-# INLINABLE headE #-}
118+ headE = lift . headE
119+
120+instance (Monad m, Ref m ~ Ref IO, Reflex t) => TriggerEvent t (StaticDomBuilderT t m) where
121+ {-# INLINABLE newTriggerEvent #-}
122+ newTriggerEvent = return (never, const $ return ())
123+ {-# INLINABLE newTriggerEventWithOnComplete #-}
124+ newTriggerEventWithOnComplete = return (never, \_ _ -> return ())
125+ {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
126+ newEventWithLazyTriggerWithOnComplete _ = return never
127+
128+instance MonadRef m => MonadRef (StaticDomBuilderT t m) where
129+ type Ref (StaticDomBuilderT t m) = Ref m
130+ newRef = lift . newRef
131+ readRef = lift . readRef
132+ writeRef r = lift . writeRef r
133+
134+instance MonadAtomicRef m => MonadAtomicRef (StaticDomBuilderT t m) where
135+ atomicModifyRef r = lift . atomicModifyRef r
136+
137+type SupportsStaticDomBuilder t m = (Reflex t, MonadIO m, MonadHold t m, MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO, Adjustable t m)
138+
139+data StaticDomSpace
140+
141+-- | Static documents never produce any events, so this type has no inhabitants
142+data StaticDomEvent (a :: k)
143+
144+-- | Static documents don't process events, so all handlers are equivalent
145+data StaticDomHandler (a :: k) (b :: k) = StaticDomHandler
146+
147+data StaticEventSpec (er :: EventTag -> *) = StaticEventSpec deriving (Generic)
148+
149+instance Default (StaticEventSpec er)
150+
151+instance DomSpace StaticDomSpace where
152+ type EventSpec StaticDomSpace = StaticEventSpec
153+ type RawDocument StaticDomSpace = ()
154+ type RawTextNode StaticDomSpace = ()
155+ type RawCommentNode StaticDomSpace = ()
156+ type RawElement StaticDomSpace = ()
157+ type RawInputElement StaticDomSpace = ()
158+ type RawTextAreaElement StaticDomSpace = ()
159+ type RawSelectElement StaticDomSpace = ()
160+ addEventSpecFlags _ _ _ _ = StaticEventSpec
161+
162+instance (SupportsStaticDomBuilder t m, Monad m) => HasDocument (StaticDomBuilderT t m) where
163+ askDocument = pure ()
164+
165+instance (Reflex t, Adjustable t m, MonadHold t m, SupportsStaticDomBuilder t m) => Adjustable t (StaticDomBuilderT t m) where
166+ runWithReplace a0 a' = do
167+ e <- StaticDomBuilderT ask
168+ key <- replaceStart e
169+ (result0, result') <- lift $ runWithReplace (runStaticDomBuilderT a0 e) (flip runStaticDomBuilderT e <$> a')
170+ o <- hold (snd result0) $ fmapCheap snd result'
171+ StaticDomBuilderT $ modify $ (:) $ join o
172+ replaceEnd key
173+ return (fst result0, fmapCheap fst result')
174+ traverseIntMapWithKeyWithAdjust = hoistIntMapWithKeyWithAdjust traverseIntMapWithKeyWithAdjust
175+ traverseDMapWithKeyWithAdjust = hoistDMapWithKeyWithAdjust traverseDMapWithKeyWithAdjust mapPatchDMap
176+ traverseDMapWithKeyWithAdjustWithMove = hoistDMapWithKeyWithAdjust traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove
177+
178+replaceStart :: (DomBuilder t m, MonadIO m) => StaticDomBuilderEnv t -> m Text
179+replaceStart env = do
180+ str <- show <$> liftIO (atomicModifyRef (_staticDomBuilderEnv_nextRunWithReplaceKey env) $ \k -> (succ k, k))
181+ let key = "-" <> T.pack str
182+ _ <- commentNode $ def { _commentNodeConfig_initialContents = "replace-start" <> key }
183+ pure key
184+
185+replaceEnd :: DomBuilder t m => Text -> m ()
186+replaceEnd key = void $ commentNode $ def { _commentNodeConfig_initialContents = "replace-end" <> key }
187+
188+hoistIntMapWithKeyWithAdjust :: forall t m p a b.
189+ ( Adjustable t m
190+ , MonadHold t m
191+ , Patch (p a)
192+ , Functor p
193+ , Patch (p (Behavior t Builder))
194+ , PatchTarget (p (Behavior t Builder)) ~ IntMap (Behavior t Builder)
195+ , Ref m ~ IORef, MonadIO m, MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadRef m -- TODO remove
196+ )
197+ => (forall x. (IntMap.Key -> a -> m x)
198+ -> IntMap a
199+ -> Event t (p a)
200+ -> m (IntMap x, Event t (p x))
201+ ) -- ^ The base monad's traversal
202+ -> (IntMap.Key -> a -> StaticDomBuilderT t m b)
203+ -> IntMap a
204+ -> Event t (p a)
205+ -> StaticDomBuilderT t m (IntMap b, Event t (p b))
206+hoistIntMapWithKeyWithAdjust base f im0 im' = do
207+ e <- StaticDomBuilderT ask
208+ (children0, children') <- lift $ base (\k v -> runStaticDomBuilderT (f k v) e) im0 im'
209+ let result0 = IntMap.map fst children0
210+ result' = (fmap . fmap) fst children'
211+ outputs0 :: IntMap (Behavior t Builder)
212+ outputs0 = IntMap.map snd children0
213+ outputs' :: Event t (p (Behavior t Builder))
214+ outputs' = (fmap . fmap) snd children'
215+ outputs <- holdIncremental outputs0 outputs'
216+ StaticDomBuilderT $ modify $ (:) $ pull $ do
217+ os <- sample $ currentIncremental outputs
218+ fmap mconcat $ forM (IntMap.toList os) $ \(_, o) -> do
219+ sample o
220+ return (result0, result')
221+
222+hoistDMapWithKeyWithAdjust :: forall (k :: * -> *) v v' t m p.
223+ ( Adjustable t m
224+ , MonadHold t m
225+ , PatchTarget (p k (Constant (Behavior t Builder))) ~ DMap k (Constant (Behavior t Builder))
226+ , Patch (p k (Constant (Behavior t Builder)))
227+ , Ref m ~ IORef, MonadIO m, MonadFix m, PerformEvent t m, MonadReflexCreateTrigger t m, MonadRef m -- TODO remove
228+ )
229+ => (forall vv vv'.
230+ (forall a. k a -> vv a -> m (vv' a))
231+ -> DMap k vv
232+ -> Event t (p k vv)
233+ -> m (DMap k vv', Event t (p k vv'))
234+ ) -- ^ The base monad's traversal
235+ -> (forall vv vv'. (forall a. vv a -> vv' a) -> p k vv -> p k vv') -- ^ A way of mapping over the patch type
236+ -> (forall a. k a -> v a -> StaticDomBuilderT t m (v' a))
237+ -> DMap k v
238+ -> Event t (p k v)
239+ -> StaticDomBuilderT t m (DMap k v', Event t (p k v'))
240+hoistDMapWithKeyWithAdjust base mapPatch f dm0 dm' = do
241+ e <- StaticDomBuilderT ask
242+ (children0, children') <- lift $ base (\k v -> fmap (Compose . swap) (runStaticDomBuilderT (f k v) e)) dm0 dm'
243+ let result0 = DMap.map (snd . getCompose) children0
244+ result' = ffor children' $ mapPatch $ snd . getCompose
245+ outputs0 :: DMap k (Constant (Behavior t Builder))
246+ outputs0 = DMap.map (Constant . fst . getCompose) children0
247+ outputs' :: Event t (p k (Constant (Behavior t Builder)))
248+ outputs' = ffor children' $ mapPatch $ Constant . fst . getCompose
249+ outputs <- holdIncremental outputs0 outputs'
250+ StaticDomBuilderT $ modify $ (:) $ pull $ do
251+ os <- sample $ currentIncremental outputs
252+ fmap mconcat $ forM (DMap.toList os) $ \(_ :=> Constant o) -> do
253+ sample o
254+ return (result0, result')
255+
256+instance SupportsStaticDomBuilder t m => NotReady t (StaticDomBuilderT t m) where
257+ notReadyUntil _ = pure ()
258+ notReady = pure ()
259+
260+-- TODO: the uses of illegal lenses in this instance causes it to be somewhat less efficient than it can be. replacing them with explicit cases to get the underlying Maybe Event and working with those is ideal.
261+instance SupportsStaticDomBuilder t m => DomBuilder t (StaticDomBuilderT t m) where
262+ type DomBuilderSpace (StaticDomBuilderT t m) = StaticDomSpace
263+ {-# INLINABLE textNode #-}
264+ textNode (TextNodeConfig initialContents mSetContents) = StaticDomBuilderT $ do
265+ --TODO: Do not escape quotation marks; see https://stackoverflow.com/questions/25612166/what-characters-must-be-escaped-in-html-5
266+ shouldEscape <- asks _staticDomBuilderEnv_shouldEscape
267+ let escape = if shouldEscape then fromHtmlEscapedText else byteString . encodeUtf8
268+ modify . (:) =<< case mSetContents of
269+ Nothing -> return (pure (escape initialContents))
270+ Just setContents -> hold (escape initialContents) $ fmapCheap escape setContents --Only because it doesn't get optimized when profiling is on
271+ return $ TextNode ()
272+ {-# INLINABLE commentNode #-}
273+ commentNode (CommentNodeConfig initialContents mSetContents) = StaticDomBuilderT $ do
274+ --TODO: Do not escape quotation marks; see https://stackoverflow.com/questions/25612166/what-characters-must-be-escaped-in-html-5
275+ shouldEscape <- asks _staticDomBuilderEnv_shouldEscape
276+ let escape = if shouldEscape then fromHtmlEscapedText else byteString . encodeUtf8
277+ (modify . (:)) . (\c -> "<!--" <> c <> "-->") =<< case mSetContents of
278+ Nothing -> return (pure (escape initialContents))
279+ Just setContents -> hold (escape initialContents) $ fmapCheap escape setContents --Only because it doesn't get optimized when profiling is on
280+ return $ CommentNode ()
281+ {-# INLINABLE element #-}
282+ element elementTag cfg child = do
283+ -- https://www.w3.org/TR/html-markup/syntax.html#syntax-elements
284+ let voidElements = Set.fromList ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]
285+ let noEscapeElements = Set.fromList ["style", "script"]
286+ let toAttr (AttributeName _mns k) v = byteString (encodeUtf8 k) <> byteString "=\"" <> fromHtmlEscapedText v <> byteString "\""
287+ es <- newFanEventWithTrigger $ \_ _ -> return (return ())
288+ StaticDomBuilderT $ do
289+ let shouldEscape = elementTag `Set.notMember` noEscapeElements
290+ nextRunWithReplaceKey <- asks _staticDomBuilderEnv_nextRunWithReplaceKey
291+ (result, innerHtml) <- lift $ lift $ runStaticDomBuilderT child $ StaticDomBuilderEnv shouldEscape Nothing nextRunWithReplaceKey
292+ attrs0 <- foldDyn applyMap (cfg ^. initialAttributes) (cfg ^. modifyAttributes)
293+ selectValue <- asks _staticDomBuilderEnv_selectValue
294+ let addSelectedAttr attrs sel = case Map.lookup "value" attrs of
295+ Just v | v == sel -> attrs <> Map.singleton "selected" ""
296+ _ -> Map.delete "selected" attrs
297+ let attrs1 = case (elementTag, selectValue) of
298+ ("option", Just sv) -> pull $ addSelectedAttr <$> sample (current attrs0) <*> sample sv
299+ _ -> current attrs0
300+ let attrs2 = ffor attrs1 $ mconcat . fmap (\(k, v) -> " " <> toAttr k v) . Map.toList
301+ let tagBS = encodeUtf8 elementTag
302+ if Set.member elementTag voidElements
303+ then modify $ (:) $ mconcat [constant ("<" <> byteString tagBS), attrs2, constant (byteString " />")]
304+ else do
305+ let open = mconcat [constant ("<" <> byteString tagBS), attrs2, constant (byteString ">")]
306+ let close = constant $ byteString $ "</" <> tagBS <> ">"
307+ modify $ (:) $ mconcat [open, innerHtml, close]
308+ let e = Element
309+ { _element_events = es
310+ , _element_raw = ()
311+ }
312+ return (e, result)
313+ {-# INLINABLE inputElement #-}
314+ inputElement cfg = do
315+ -- Tweak the config to update the "value" and "checked" attributes appropriately.
316+ -- TODO: warn upon overwriting values.
317+ let setInitialValue = Map.insert "value" (_inputElementConfig_initialValue cfg)
318+ setUpdatedValue updatedAttrs = case _inputElementConfig_setValue cfg of
319+ Nothing -> updatedAttrs
320+ Just e -> (Map.singleton "value" . Just <$> e) <> updatedAttrs
321+ setInitialChecked = case _inputElementConfig_initialChecked cfg of
322+ True -> Map.insert "checked" "checked"
323+ False -> id
324+ setUpdatedChecked updatedAttrs = case _inputElementConfig_setChecked cfg of
325+ Nothing -> updatedAttrs
326+ Just e -> (Map.singleton "checked" (Just "checked") <$ e) <> updatedAttrs
327+ adjustedConfig = _inputElementConfig_elementConfig cfg
328+ & elementConfig_initialAttributes %~ setInitialValue . setInitialChecked
329+ & elementConfig_modifyAttributes %~ setUpdatedValue . setUpdatedChecked
330+ (e, _result) <- element "input" adjustedConfig $ return ()
331+ v <- case _inputElementConfig_setValue cfg of
332+ Nothing -> pure $ constDyn (cfg ^. inputElementConfig_initialValue)
333+ Just ev -> holdDyn (cfg ^. inputElementConfig_initialValue) ev
334+ c <- case _inputElementConfig_setChecked cfg of
335+ Nothing -> pure $ constDyn $ _inputElementConfig_initialChecked cfg
336+ Just ev -> holdDyn (_inputElementConfig_initialChecked cfg) ev
337+ let hasFocus = constDyn False -- TODO should this be coming from initialAtttributes
338+ return $ InputElement
339+ { _inputElement_value = v
340+ , _inputElement_checked = c
341+ , _inputElement_checkedChange = never
342+ , _inputElement_input = never
343+ , _inputElement_hasFocus = hasFocus
344+ , _inputElement_element = e
345+ , _inputElement_raw = ()
346+ , _inputElement_files = constDyn mempty
347+ }
348+ {-# INLINABLE textAreaElement #-}
349+ textAreaElement cfg = do
350+ (e, _domElement) <- element "textarea" (_textAreaElementConfig_elementConfig cfg) $ do
351+ -- Set the initial value
352+ void $ textNode $ def
353+ & textNodeConfig_initialContents .~ _textAreaElementConfig_initialValue cfg
354+ & textNodeConfig_setContents .~ fromMaybe never (_textAreaElementConfig_setValue cfg)
355+ v <- case _textAreaElementConfig_setValue cfg of
356+ Nothing -> pure $ constDyn (cfg ^. textAreaElementConfig_initialValue)
357+ Just ev -> holdDyn (cfg ^. textAreaElementConfig_initialValue) ev
358+ let hasFocus = constDyn False -- TODO should this be coming from initialAtttributes
359+ return $ TextAreaElement
360+ { _textAreaElement_value = v
361+ , _textAreaElement_input = never
362+ , _textAreaElement_hasFocus = hasFocus
363+ , _textAreaElement_element = e
364+ , _textAreaElement_raw = ()
365+ }
366+ selectElement cfg child = do
367+ v <- holdDyn (cfg ^. selectElementConfig_initialValue) (cfg ^. selectElementConfig_setValue)
368+ (e, result) <- element "select" (_selectElementConfig_elementConfig cfg) $ do
369+ (a, innerHtml) <- StaticDomBuilderT $ do
370+ nextRunWithReplaceKey <- asks _staticDomBuilderEnv_nextRunWithReplaceKey
371+ lift $ lift $ runStaticDomBuilderT child $ StaticDomBuilderEnv False (Just $ current v) nextRunWithReplaceKey
372+ StaticDomBuilderT $ lift $ modify $ (:) innerHtml
373+ return a
374+ let wrapped = SelectElement
375+ { _selectElement_value = v
376+ , _selectElement_change = never
377+ , _selectElement_hasFocus = constDyn False --TODO: How do we make sure this is correct?
378+ , _selectElement_element = e
379+ , _selectElement_raw = ()
380+ }
381+ return (wrapped, result)
382+ placeRawElement () = return ()
383+ wrapRawElement () _ = return $ Element (EventSelector $ const never) ()
384+
385+--TODO: Make this more abstract --TODO: Put the WithWebView underneath PerformEventT - I think this would perform better
386+type StaticWidget x = PostBuildT DomTimeline (StaticDomBuilderT DomTimeline (PerformEventT DomTimeline DomHost))
387+
388+{-# INLINE renderStatic #-}
389+renderStatic :: StaticWidget x a -> IO (a, ByteString)
390+renderStatic w = do
391+ runDomHost $ do
392+ (postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
393+ nextRunWithReplaceKey <- newRef 0
394+ let env0 = StaticDomBuilderEnv True Nothing nextRunWithReplaceKey
395+ ((res, bs), FireCommand fire) <- hostPerformEventT $ runStaticDomBuilderT (runPostBuildT w postBuild) env0
396+ mPostBuildTrigger <- readRef postBuildTriggerRef
397+ forM_ mPostBuildTrigger $ \postBuildTrigger -> fire [postBuildTrigger :=> Identity ()] $ return ()
398+ bs' <- sample bs
399+ return (res, LBS.toStrict $ toLazyByteString bs')
src/Reflex/Dom/Class.hs → reflex-dom-core/src/Reflex/Dom/Class.hsrenamed+6−9
@@ -4,20 +4,17 @@ module Reflex.Dom.Class ( module Reflex.Dom.Class
44 , module Web.KeyCode
55 ) where
66
7−import Data.Map (Map)
8−import qualified Data.Map as Map
7+import Control.Lens
98import Reflex.Class
109import Web.KeyCode
1110
1211import Foreign.JavaScript.TH
13−import Reflex.Dom.PerformEvent.Class
14−import Reflex.Dom.PostBuild.Class
12+import Reflex.PerformEvent.Class
13+import Reflex.PostBuild.Class
1514
16−import Prelude hiding (concat, mapM, mapM_, sequence)
17−
18−-- | Alias for Data.Map.singleton
19−(=:) :: k -> a -> Map k a
20−(=:) = Map.singleton
15+-- | Previously an alias for 'Data.Map.singleton', but now generalised to 'At'
16+(=:) :: (At m, Monoid m) => Index m -> IxValue m -> m
17+k =: a = at k ?~ a $ mempty
2118infixr 7 =: -- Ought to bind tighter than <>, which is infixr 6
2219
2320{-# DEPRECATED keycodeEnter "Instead of `x == keycodeEnter`, use `keyCodeLookup x == Enter`" #-}
reflex-dom-core/src/Reflex/Dom/Core.hsnew file+22
@@ -0,0 +1,22 @@
1+-- Disable haddocks on this module due to a bug on haddocks when selectively
2+-- reexporting on ghc > 8.2.
3+-- https://github.com/haskell/haddock/issues/979
4+{-# OPTIONS_HADDOCK hide, prune, ignore-exports #-}
5+module Reflex.Dom.Core (module X) where
6+
7+import Reflex as X hiding (askEvents)
8+import Reflex.Dom.Builder.Class as X
9+import Reflex.Dom.Builder.Hydratable as X
10+import Reflex.Dom.Builder.Immediate as X
11+import Reflex.Dom.Builder.InputDisabled as X
12+import Reflex.Dom.Builder.Static as X
13+import Reflex.Dom.Class as X
14+import Reflex.Dom.Location as X
15+import Reflex.Dom.Main as X
16+import Reflex.Dom.Modals.Class as X
17+import Reflex.Dom.Old as X
18+import Reflex.Dom.Prerender as X
19+import Reflex.Dom.WebSocket as X
20+import Reflex.Dom.Widget as X
21+import Reflex.Dom.Xhr as X
22+import Reflex.Dom.Xhr.FormData as X
reflex-dom-core/src/Reflex/Dom/Location.hsnew file+200
@@ -0,0 +1,200 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE MultiParamTypeClasses #-}
4+{-# LANGUAGE OverloadedStrings #-}
5+{-# LANGUAGE RankNTypes #-}
6+module Reflex.Dom.Location
7+ ( browserHistoryWith
8+ , getLocationAfterHost
9+ , getLocationFragment
10+ , getLocationHost
11+ , getLocationPath
12+ , getLocationProtocol
13+ , getLocationUrl
14+ , manageHistory
15+ , manageHistory'
16+ , HistoryCommand (..)
17+ , HistoryStateUpdate (..)
18+ , HistoryItem (..)
19+ , getLocationUri
20+ ) where
21+
22+import Reflex
23+import Reflex.Dom.Builder.Immediate (wrapDomEvent)
24+
25+import Control.Lens ((^.))
26+import Control.Monad ((>=>))
27+import Control.Monad.Fix (MonadFix)
28+import Data.Align (align)
29+import Data.Monoid
30+import Data.Text (Text)
31+import Data.These (These(..))
32+import qualified GHCJS.DOM as DOM
33+import qualified GHCJS.DOM.EventM as DOM
34+import qualified GHCJS.DOM.Location as Location
35+import qualified GHCJS.DOM.History as History
36+import qualified GHCJS.DOM.PopStateEvent as PopStateEvent
37+import GHCJS.DOM.Types (Location, History, SerializedScriptValue (..), liftJSM)
38+import qualified GHCJS.DOM.Types as DOM
39+import qualified GHCJS.DOM.Window as Window
40+import qualified GHCJS.DOM.WindowEventHandlers as DOM
41+import Language.Javascript.JSaddle (FromJSString, MonadJSM, ToJSString, fromJSValUnchecked, js1, ToJSVal (..), FromJSVal (..))
42+import Network.URI
43+
44+withLocation :: (MonadJSM m) => (Location -> m a) -> m a
45+withLocation f = DOM.currentWindowUnchecked >>= Window.getLocation >>= f
46+
47+-- | Returns the full URI-decoded URL of the current window location.
48+getLocationUrl :: (MonadJSM m) => m Text
49+getLocationUrl = withLocation (Location.getHref >=> decodeURIText)
50+
51+-- | Returns the host of the current window location
52+getLocationHost :: (MonadJSM m) => m Text
53+getLocationHost = withLocation Location.getHost
54+
55+-- | Returns the protocol/scheme (e.g. @http:@ or @https:@) of the current window location
56+getLocationProtocol :: (MonadJSM m) => m Text
57+getLocationProtocol = withLocation Location.getProtocol
58+
59+-- | Returns the URI-decoded location after the host and port; i.e. returns the path, query, and fragment of the location.
60+getLocationAfterHost :: (MonadJSM m) => m Text
61+getLocationAfterHost = withLocation $ \loc -> do
62+ pathname <- Location.getPathname loc
63+ search <- Location.getSearch loc
64+ hash <- Location.getHash loc
65+ decodeURI (mconcat [pathname, search, hash] :: Text)
66+
67+-- | Returns the URI-decoded path of the current window location.
68+getLocationPath :: (MonadJSM m) => m Text
69+getLocationPath = withLocation (Location.getPathname >=> decodeURIText)
70+
71+-- | Returns the URI-decoded fragment/hash of the current window location.
72+getLocationFragment :: (MonadJSM m) => m Text
73+getLocationFragment = withLocation (Location.getHash >=> decodeURIText)
74+
75+
76+-- | Decodes a URI with JavaScript's @decodeURI@ function.
77+--
78+-- FIXME: @decodeURI@ will throw when URI is malformed
79+decodeURI :: (MonadJSM m, ToJSString a, FromJSString b) => a -> m b
80+decodeURI input = do
81+ window <- DOM.currentWindowUnchecked
82+ window' <- DOM.liftJSM $ toJSVal window
83+ DOM.liftJSM $ window' ^. js1 ("decodeURI"::Text) input >>= fromJSValUnchecked
84+
85+decodeURIText :: (MonadJSM m) => Text -> m Text
86+decodeURIText = decodeURI
87+
88+-- | Builds a Dynamic carrying the current window location.
89+browserHistoryWith :: (MonadJSM m, TriggerEvent t m, MonadHold t m)
90+ => (forall jsm. MonadJSM jsm => Location -> jsm a)
91+ -- ^ A function to encode the window location in a more useful form (e.g. @getLocationAfterHost@).
92+ -> m (Dynamic t a)
93+browserHistoryWith f = do
94+ window <- DOM.currentWindowUnchecked
95+ location <- Window.getLocation window
96+ loc0 <- f location
97+ locEv <- wrapDomEvent window (`DOM.on` DOM.popState) $ f location
98+ holdDyn loc0 locEv
99+
100+--TODO: Pending https://github.com/haskell/network-uri/issues/39, ensure that
101+--we're handling escaping of URIs correctly
102+data HistoryItem = HistoryItem
103+ { _historyItem_state :: SerializedScriptValue
104+ , _historyItem_uri :: URI
105+ -- ^ NOTE: All URIs in this module are assumed to be already percent-escaped
106+ }
107+
108+data HistoryStateUpdate = HistoryStateUpdate
109+ { _historyStateUpdate_state :: SerializedScriptValue
110+ , _historyStateUpdate_title :: Text
111+ , _historyStateUpdate_uri :: Maybe URI
112+ -- ^ If Just, update the URI; otherwise leave it unchanged
113+ -- NOTE: All URIs in this module are assumed to be already percent-escaped
114+ }
115+
116+data HistoryCommand
117+ = HistoryCommand_PushState HistoryStateUpdate
118+ | HistoryCommand_ReplaceState HistoryStateUpdate
119+
120+runHistoryCommand :: MonadJSM m => History -> HistoryCommand -> m ()
121+runHistoryCommand history = \case
122+ HistoryCommand_PushState su -> History.pushState history
123+ (_historyStateUpdate_state su)
124+ (_historyStateUpdate_title su)
125+ (show <$> _historyStateUpdate_uri su)
126+ HistoryCommand_ReplaceState su -> History.replaceState history
127+ (_historyStateUpdate_state su)
128+ (_historyStateUpdate_title su)
129+ (show <$> _historyStateUpdate_uri su)
130+
131+getLocationUriAuth :: MonadJSM m => Location -> m URIAuth
132+getLocationUriAuth location = URIAuth "" -- Username and password don't seem to be available in most browsers
133+ <$> Location.getHostname location
134+ <*> (appendColonIfNotEmpty <$> Location.getPort location)
135+ where appendColonIfNotEmpty = \case
136+ "" -> ""
137+ x -> ":" <> x
138+
139+getLocationUri :: MonadJSM m => Location -> m URI
140+getLocationUri location = URI
141+ <$> Location.getProtocol location
142+ <*> (Just <$> getLocationUriAuth location)
143+ <*> Location.getPathname location
144+ <*> Location.getSearch location
145+ <*> Location.getHash location
146+
147+manageHistory :: (MonadJSM m, TriggerEvent t m, MonadHold t m, PerformEvent t m, MonadJSM (Performable m)) => Event t HistoryCommand -> m (Dynamic t HistoryItem)
148+manageHistory runCmd = do
149+ window <- DOM.currentWindowUnchecked
150+ location <- Window.getLocation window
151+ history <- Window.getHistory window
152+ let getCurrentHistoryItem = HistoryItem
153+ <$> History.getState history
154+ <*> getLocationUri location
155+ item0 <- liftJSM getCurrentHistoryItem
156+ itemSetInternal <- performEvent $ ffor runCmd $ \cmd -> liftJSM $ do
157+ runHistoryCommand history cmd
158+ getCurrentHistoryItem
159+ itemSetExternal <- wrapDomEvent window (`DOM.on` DOM.popState) $ do
160+ e <- DOM.event
161+ HistoryItem
162+ <$> (SerializedScriptValue <$> PopStateEvent.getState e)
163+ <*> getLocationUri location
164+ holdDyn item0 $ leftmost [itemSetInternal, itemSetExternal]
165+--TODO: Handle title setting better
166+
167+manageHistory'
168+ :: (MonadFix m, MonadJSM m, TriggerEvent t m, MonadHold t m, PerformEvent t m, MonadJSM (Performable m))
169+ => Event t ()
170+ -- ^ Don't do anything until this event has fired
171+ -> Event t HistoryCommand
172+ -> m (Dynamic t HistoryItem)
173+manageHistory' switchover runCmd = do
174+ window <- DOM.currentWindowUnchecked
175+ location <- Window.getLocation window
176+ history <- Window.getHistory window
177+ let getCurrentHistoryItem = HistoryItem
178+ <$> History.getState history
179+ <*> getLocationUri location
180+ item0 <- liftJSM getCurrentHistoryItem
181+ itemSetExternal' <- wrapDomEvent window (`DOM.on` DOM.popState) $ do
182+ e <- DOM.event
183+ HistoryItem
184+ <$> (SerializedScriptValue <$> PopStateEvent.getState e)
185+ <*> getLocationUri location
186+ let f :: (Bool, Maybe a) -> These a () -> (Maybe (Bool, Maybe a), Maybe a)
187+ f (switched, acc) = \case
188+ This change
189+ | switched -> (Nothing, Just change)
190+ | otherwise -> (Just (switched, Just change), Nothing)
191+ That () -> (Just (True, Nothing), acc)
192+ These change () -> (Just (True, Nothing), Just change)
193+ -- Accumulate the events before switchover
194+ (_, cmd') <- mapAccumMaybeB f (False, Nothing) $ align (leftmost [Left <$> runCmd, Right <$> itemSetExternal']) switchover
195+ let (itemSetInternal', itemSetExternal) = fanEither cmd'
196+ itemSetInternal <- performEvent $ ffor itemSetInternal' $ \cmd -> liftJSM $ do
197+ runHistoryCommand history cmd
198+ getCurrentHistoryItem
199+ holdDyn item0 $ leftmost [itemSetInternal, itemSetExternal]
200+--TODO: Handle title setting better
reflex-dom-core/src/Reflex/Dom/Main.hsnew file+376
@@ -0,0 +1,376 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE NoMonomorphismRestriction #-}
8+{-# LANGUAGE RankNTypes #-}
9+{-# LANGUAGE RecursiveDo #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE TypeFamilies #-}
12+{-# LANGUAGE TypeOperators #-}
13+{-# LANGUAGE UndecidableInstances #-}
14+{-# OPTIONS_GHC -fspecialise-aggressively #-}
15+module Reflex.Dom.Main where
16+
17+import Prelude hiding (concat, mapM, mapM_, sequence, sequence_)
18+
19+import Reflex.Adjustable.Class
20+import Reflex.Class
21+import Reflex.Dom.Builder.Immediate
22+import Reflex.Dom.Class
23+import Reflex.Host.Class
24+import Reflex.PerformEvent.Base
25+import Reflex.PostBuild.Base
26+import Reflex.Spider (Global, Spider, SpiderHost, runSpiderHost)
27+import Reflex.TriggerEvent.Base
28+import Reflex.TriggerEvent.Class
29+#ifdef PROFILE_REFLEX
30+import Reflex.Profiled
31+#endif
32+
33+import Control.Concurrent
34+import Control.Lens
35+import Control.Monad
36+import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
37+import Control.Monad.Ref
38+import Data.ByteString (ByteString)
39+import Data.Dependent.Sum (DSum (..))
40+import Data.Foldable (for_)
41+import Data.IORef
42+import Data.Maybe
43+import Data.Monoid ((<>))
44+import Data.Text (Text)
45+import qualified Data.Text as T
46+import Data.Text.Encoding
47+import GHCJS.DOM
48+import GHCJS.DOM.Document
49+import GHCJS.DOM.Element
50+import GHCJS.DOM.Node
51+import GHCJS.DOM.NonElementParentNode
52+import GHCJS.DOM.Types (JSM)
53+import qualified GHCJS.DOM.Types as DOM
54+
55+#ifdef PROFILE_REFLEX
56+import Reflex.Profiled
57+#endif
58+
59+{-# INLINE mainHydrationWidgetWithHead #-}
60+mainHydrationWidgetWithHead :: (forall x. HydrationWidget x ()) -> (forall x. HydrationWidget x ()) -> JSM ()
61+mainHydrationWidgetWithHead = mainHydrationWidgetWithHead'
62+
63+{-# INLINABLE mainHydrationWidgetWithHead' #-}
64+-- | Warning: `mainHydrationWidgetWithHead'` is provided only as performance tweak. It is expected to disappear in future releases.
65+mainHydrationWidgetWithHead' :: HydrationWidget () () -> HydrationWidget () () -> JSM ()
66+mainHydrationWidgetWithHead' = mainHydrationWidgetWithSwitchoverAction' (pure ())
67+
68+{-# INLINE mainHydrationWidgetWithSwitchoverAction #-}
69+mainHydrationWidgetWithSwitchoverAction :: JSM () -> (forall x. HydrationWidget x ()) -> (forall x. HydrationWidget x ()) -> JSM ()
70+mainHydrationWidgetWithSwitchoverAction = mainHydrationWidgetWithSwitchoverAction'
71+
72+{-# INLINABLE mainHydrationWidgetWithSwitchoverAction' #-}
73+-- | Warning: `mainHydrationWidgetWithSwitchoverAction'` is provided only as performance tweak. It is expected to disappear in future releases.
74+mainHydrationWidgetWithSwitchoverAction' :: JSM () -> HydrationWidget () () -> HydrationWidget () () -> JSM ()
75+mainHydrationWidgetWithSwitchoverAction' = mainHydrationWidgetWithSwitchoverActionWithFailure' (pure ())
76+
77+
78+{-# INLINABLE mainHydrationWidgetWithSwitchoverActionWithFailure' #-}
79+-- | Warning: `mainHydrationWidgetWithSwitchoverActionWithFaiilure'` is provided only as performance tweak. It is expected to disappear in future releases.
80+mainHydrationWidgetWithSwitchoverActionWithFailure' :: IO () -> JSM () -> HydrationWidget () () -> HydrationWidget () () -> JSM ()
81+mainHydrationWidgetWithSwitchoverActionWithFailure' onFailure switchoverAction head' body = do
82+ runHydrationWidgetWithHeadAndBodyWithFailure onFailure switchoverAction $ \appendHead appendBody -> do
83+ appendHead head'
84+ appendBody body
85+
86+{-# INLINABLE attachHydrationWidget #-}
87+attachHydrationWidget
88+ :: JSM ()
89+ -> JSContextSingleton ()
90+ -> ( Event DomTimeline ()
91+ -> IORef HydrationMode
92+ -> Maybe (IORef [(Node, HydrationRunnerT DomTimeline (DomCoreWidget ()) ())])
93+ -> EventChannel
94+ -> PerformEventT DomTimeline DomHost (a, IORef (Maybe (EventTrigger DomTimeline ())))
95+ )
96+ -> IO (a, FireCommand DomTimeline DomHost)
97+attachHydrationWidget = attachHydrationWidgetWithFailure (pure ())
98+
99+{-# INLINABLE attachHydrationWidgetWithFailure #-}
100+attachHydrationWidgetWithFailure
101+ :: IO ()
102+ -> JSM ()
103+ -> JSContextSingleton ()
104+ -> ( Event DomTimeline ()
105+ -> IORef HydrationMode
106+ -> Maybe (IORef [(Node, HydrationRunnerT DomTimeline (DomCoreWidget ()) ())])
107+ -> EventChannel
108+ -> PerformEventT DomTimeline DomHost (a, IORef (Maybe (EventTrigger DomTimeline ())))
109+ )
110+ -> IO (a, FireCommand DomTimeline DomHost)
111+attachHydrationWidgetWithFailure onFailure switchoverAction jsSing w = do
112+ hydrationMode <- liftIO $ newIORef HydrationMode_Hydrating
113+ rootNodesRef <- liftIO $ newIORef []
114+ events <- newChan
115+ runDomHost $ flip runTriggerEventT events $ mdo
116+ (syncEvent, fireSync) <- newTriggerEvent
117+ ((result, postBuildTriggerRef), fc@(FireCommand fire)) <- lift $ hostPerformEventT $ do
118+ a <- w syncEvent hydrationMode (Just rootNodesRef) events
119+ _ <- runWithReplace (return ()) $ delayedAction <$ syncEvent
120+ pure a
121+ mPostBuildTrigger <- readRef postBuildTriggerRef
122+ lift $ forM_ mPostBuildTrigger $ \postBuildTrigger -> fire [postBuildTrigger :=> Identity ()] $ return ()
123+ liftIO $ fireSync ()
124+ rootNodes <- liftIO $ readIORef rootNodesRef
125+ let delayedAction = do
126+ for_ (reverse rootNodes) $ \(rootNode, runner) -> do
127+ let hydrate = runHydrationRunnerTWithFailure runner onFailure Nothing rootNode events
128+ void $ runWithJSContextSingleton (runPostBuildT hydrate never) jsSing
129+ liftIO $ writeIORef hydrationMode HydrationMode_Immediate
130+ runWithJSContextSingleton (DOM.liftJSM switchoverAction) jsSing
131+ pure (result, fc)
132+
133+type HydrationWidget x a = HydrationDomBuilderT HydrationDomSpace DomTimeline (DomCoreWidget x) a
134+
135+-- | A widget that isn't attached to any particular part of the DOM hierarchy
136+type FloatingWidget x = TriggerEventT DomTimeline (DomCoreWidget x)
137+
138+type DomCoreWidget x = PostBuildT DomTimeline (WithJSContextSingleton x (PerformEventT DomTimeline DomHost))
139+
140+{-# INLINABLE runHydrationWidgetWithHeadAndBody #-}
141+runHydrationWidgetWithHeadAndBody
142+ :: JSM ()
143+ -> ( (forall c. HydrationWidget () c -> FloatingWidget () c) -- "Append to head" --TODO: test invoking this more than once
144+ -> (forall c. HydrationWidget () c -> FloatingWidget () c) -- "Append to body" --TODO: test invoking this more than once
145+ -> FloatingWidget () ()
146+ )
147+ -> JSM ()
148+runHydrationWidgetWithHeadAndBody = runHydrationWidgetWithHeadAndBodyWithFailure (pure ())
149+
150+{-# INLINABLE runHydrationWidgetWithHeadAndBodyWithFailure #-}
151+runHydrationWidgetWithHeadAndBodyWithFailure
152+ :: IO ()
153+ -> JSM ()
154+ -> ( (forall c. HydrationWidget () c -> FloatingWidget () c) -- "Append to head" --TODO: test invoking this more than once
155+ -> (forall c. HydrationWidget () c -> FloatingWidget () c) -- "Append to body" --TODO: test invoking this more than once
156+ -> FloatingWidget () ()
157+ )
158+ -> JSM ()
159+runHydrationWidgetWithHeadAndBodyWithFailure onFailure switchoverAction app = withJSContextSingletonMono $ \jsSing -> do
160+ globalDoc <- currentDocumentUnchecked
161+ headElement <- getHeadUnchecked globalDoc
162+ bodyElement <- getBodyUnchecked globalDoc
163+ (events, fc) <- liftIO . attachHydrationWidgetWithFailure onFailure switchoverAction jsSing $ \switchover hydrationMode hydrationResult events -> do
164+ (postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
165+ let hydrateDom :: DOM.Node -> HydrationWidget () c -> FloatingWidget () c
166+ hydrateDom n w = do
167+ delayed <- liftIO $ newIORef $ pure ()
168+ unreadyChildren <- liftIO $ newIORef 0
169+ lift $ do
170+ let builderEnv = HydrationDomBuilderEnv
171+ { _hydrationDomBuilderEnv_document = globalDoc
172+ , _hydrationDomBuilderEnv_parent = Left $ toNode n
173+ , _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
174+ , _hydrationDomBuilderEnv_commitAction = pure ()
175+ , _hydrationDomBuilderEnv_hydrationMode = hydrationMode
176+ , _hydrationDomBuilderEnv_switchover = switchover
177+ , _hydrationDomBuilderEnv_delayed = delayed
178+ }
179+ a <- runHydrationDomBuilderT w builderEnv events
180+ forM_ hydrationResult $ \hr -> do
181+ res <- liftIO $ readIORef delayed
182+ liftIO $ modifyIORef' hr ((n, res) :)
183+ pure a
184+ runWithJSContextSingleton (runPostBuildT (runTriggerEventT (app (hydrateDom $ toNode headElement) (hydrateDom $ toNode bodyElement)) events) postBuild) jsSing
185+ return (events, postBuildTriggerRef)
186+ liftIO $ processAsyncEvents events fc
187+
188+{-# INLINE mainWidget #-}
189+mainWidget :: (forall x. Widget x ()) -> JSM ()
190+mainWidget = mainWidget'
191+
192+{-# INLINABLE mainWidget' #-}
193+-- | Warning: `mainWidget'` is provided only as performance tweak. It is expected to disappear in future releases.
194+mainWidget' :: Widget () () -> JSM ()
195+mainWidget' w = withJSContextSingletonMono $ \jsSing -> do
196+ doc <- currentDocumentUnchecked
197+ body <- getBodyUnchecked doc
198+ attachWidget body jsSing w
199+
200+--TODO: The x's should be unified here
201+{-# INLINABLE mainWidgetWithHead #-}
202+mainWidgetWithHead :: (forall x. Widget x ()) -> (forall x. Widget x ()) -> JSM ()
203+mainWidgetWithHead h b = withJSContextSingletonMono $ \jsSing -> do
204+ doc <- currentDocumentUnchecked
205+ headElement <- getHeadUnchecked doc
206+ attachWidget headElement jsSing h
207+ body <- getBodyUnchecked doc
208+ attachWidget body jsSing b
209+
210+{-# INLINABLE mainWidgetWithCss #-}
211+mainWidgetWithCss :: ByteString -> (forall x. Widget x ()) -> JSM ()
212+mainWidgetWithCss css w = withJSContextSingleton $ \jsSing -> do
213+ doc <- currentDocumentUnchecked
214+ headElement <- getHeadUnchecked doc
215+ setInnerHTML headElement $ "<style>" <> T.unpack (decodeUtf8 css) <> "</style>" --TODO: Fix this
216+ body <- getBodyUnchecked doc
217+ attachWidget body jsSing w
218+
219+-- | The Reflex timeline for interacting with the DOM
220+type DomTimeline =
221+#ifdef PROFILE_REFLEX
222+ ProfiledTimeline
223+#endif
224+ Spider
225+
226+-- | The ReflexHost the DOM lives in
227+type DomHost =
228+#ifdef PROFILE_REFLEX
229+ ProfiledM
230+#endif
231+ (SpiderHost Global)
232+
233+runDomHost :: DomHost a -> IO a
234+runDomHost = runSpiderHost
235+#ifdef PROFILE_REFLEX
236+ . runProfiledM
237+#endif
238+
239+type Widget x = ImmediateDomBuilderT DomTimeline (DomCoreWidget x)
240+
241+{-# INLINABLE attachWidget #-}
242+attachWidget :: DOM.IsElement e => e -> JSContextSingleton x -> Widget x a -> JSM a
243+attachWidget rootElement wv w = fst <$> attachWidget' rootElement wv w
244+
245+{-# INLINABLE runImmediateWidgetWithHeadAndBody #-}
246+runImmediateWidgetWithHeadAndBody
247+ :: ( (forall c. Widget () c -> FloatingWidget () c) -- "Append to head"
248+ -> (forall c. Widget () c -> FloatingWidget () c) -- "Append to body"
249+ -> FloatingWidget () ()
250+ )
251+ -> JSM ()
252+runImmediateWidgetWithHeadAndBody app = withJSContextSingletonMono $ \jsSing -> do
253+ globalDoc <- currentDocumentUnchecked
254+ headElement <- getHeadUnchecked globalDoc
255+ bodyElement <- getBodyUnchecked globalDoc
256+ headFragment <- createDocumentFragment globalDoc
257+ bodyFragment <- createDocumentFragment globalDoc
258+ (events, fc) <- liftIO . attachImmediateWidget $ \hydrationMode events -> do
259+ (postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
260+ let go :: forall c. DOM.DocumentFragment -> Widget () c -> FloatingWidget () c
261+ go df w = do
262+ unreadyChildren <- liftIO $ newIORef 0
263+ delayed <- liftIO $ newIORef $ pure ()
264+ let builderEnv = HydrationDomBuilderEnv
265+ { _hydrationDomBuilderEnv_document = globalDoc
266+ , _hydrationDomBuilderEnv_parent = Left $ toNode df
267+ , _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
268+ , _hydrationDomBuilderEnv_commitAction = pure () --TODO: possibly `replaceElementContents n f`
269+ , _hydrationDomBuilderEnv_hydrationMode = hydrationMode
270+ , _hydrationDomBuilderEnv_switchover = never
271+ , _hydrationDomBuilderEnv_delayed = delayed
272+ }
273+ lift $ runHydrationDomBuilderT w builderEnv events
274+ runWithJSContextSingleton (runPostBuildT (runTriggerEventT (app (go headFragment) (go bodyFragment)) events) postBuild) jsSing
275+ return (events, postBuildTriggerRef)
276+ replaceElementContents headElement headFragment
277+ replaceElementContents bodyElement bodyFragment
278+ liftIO $ processAsyncEvents events fc
279+
280+-- | Warning: `mainWidgetWithHead'` is provided only as performance tweak. It is expected to disappear in future releases.
281+mainWidgetWithHead' :: (a -> Widget () b, b -> Widget () a) -> JSM ()
282+mainWidgetWithHead' (h, b) = runImmediateWidgetWithHeadAndBody $ \appendHead appendBody -> do
283+ rec hOut <- appendHead $ h bOut
284+ bOut <- appendBody $ b hOut
285+ pure ()
286+
287+replaceElementContents :: DOM.IsElement e => e -> DOM.DocumentFragment -> JSM ()
288+replaceElementContents e df = do
289+ setInnerHTML e ("" :: String)
290+ _ <- appendChild e df
291+ return ()
292+
293+{-# INLINABLE attachWidget' #-}
294+attachWidget' :: DOM.IsElement e => e -> JSContextSingleton x -> Widget x a -> JSM (a, FireCommand DomTimeline DomHost)
295+attachWidget' rootElement jsSing w = do
296+ doc <- getOwnerDocumentUnchecked rootElement
297+ df <- createDocumentFragment doc
298+ ((a, events), fc) <- liftIO . attachImmediateWidget $ \hydrationMode events -> do
299+ (postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
300+ unreadyChildren <- liftIO $ newIORef 0
301+ delayed <- liftIO $ newIORef $ pure ()
302+ let builderEnv = HydrationDomBuilderEnv
303+ { _hydrationDomBuilderEnv_document = toDocument doc
304+ , _hydrationDomBuilderEnv_parent = Left $ toNode df
305+ , _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
306+ , _hydrationDomBuilderEnv_commitAction = return () --TODO
307+ , _hydrationDomBuilderEnv_switchover = never
308+ , _hydrationDomBuilderEnv_delayed = delayed
309+ , _hydrationDomBuilderEnv_hydrationMode = hydrationMode
310+ }
311+ a <- runWithJSContextSingleton (runPostBuildT (runHydrationDomBuilderT w builderEnv events) postBuild) jsSing
312+ return ((a, events), postBuildTriggerRef)
313+ replaceElementContents rootElement df
314+ liftIO $ processAsyncEvents events fc
315+ return (a, fc)
316+
317+type EventChannel = Chan [DSum (EventTriggerRef DomTimeline) TriggerInvocation]
318+
319+{-# INLINABLE attachImmediateWidget #-}
320+attachImmediateWidget
321+ :: ( IORef HydrationMode
322+ -> EventChannel
323+ -> PerformEventT DomTimeline DomHost (a, IORef (Maybe (EventTrigger DomTimeline ())))
324+ )
325+ -> IO (a, FireCommand DomTimeline DomHost)
326+attachImmediateWidget w = do
327+ hydrationMode <- liftIO $ newIORef HydrationMode_Immediate
328+ events <- newChan
329+ runDomHost $ do
330+ ((result, postBuildTriggerRef), fc@(FireCommand fire)) <- hostPerformEventT $ w hydrationMode events
331+ mPostBuildTrigger <- readRef postBuildTriggerRef
332+ forM_ mPostBuildTrigger $ \postBuildTrigger -> fire [postBuildTrigger :=> Identity ()] $ return ()
333+ return (result, fc)
334+
335+processAsyncEvents :: EventChannel -> FireCommand DomTimeline DomHost -> IO ()
336+processAsyncEvents events (FireCommand fire) = void $ forkIO $ forever $ do
337+ ers <- readChan events
338+ _ <- runDomHost $ do
339+ mes <- liftIO $ forM ers $ \(EventTriggerRef er :=> TriggerInvocation a _) -> do
340+ me <- readIORef er
341+ return $ fmap (\e -> e :=> Identity a) me
342+ _ <- fire (catMaybes mes) $ return ()
343+ liftIO $ forM_ ers $ \(_ :=> TriggerInvocation _ cb) -> cb
344+ return ()
345+
346+-- | Run a reflex-dom application inside of an existing DOM element with the given ID
347+mainWidgetInElementById :: Text -> (forall x. Widget x ()) -> JSM ()
348+mainWidgetInElementById eid w = withJSContextSingleton $ \jsSing -> do
349+ doc <- currentDocumentUnchecked
350+ root <- getElementByIdUnchecked doc eid
351+ attachWidget root jsSing w
352+
353+newtype AppInput t = AppInput
354+ { _appInput_window :: Window t
355+ }
356+
357+newtype AppOutput t = AppOutput --TODO: Add quit event
358+ { _appOutput_windowConfig :: WindowConfig t
359+ }
360+
361+runApp' :: (t ~ DomTimeline) => (forall x. AppInput t -> Widget x (AppOutput t)) -> JSM ()
362+runApp' app = withJSContextSingleton $ \jsSing -> do
363+ doc <- currentDocumentUnchecked
364+ body <- getBodyUnchecked doc
365+ win <- getDefaultViewUnchecked doc
366+ rec o <- attachWidget body jsSing $ do
367+ w <- wrapWindow win $ _appOutput_windowConfig o
368+ app $ AppInput
369+ { _appInput_window = w
370+ }
371+ return ()
372+
373+{-# DEPRECATED attachWidget'' "Use 'attachImmediateWidget . const' instead" #-}
374+{-# INLINABLE attachWidget'' #-}
375+attachWidget'' :: (EventChannel -> PerformEventT DomTimeline DomHost (a, IORef (Maybe (EventTrigger DomTimeline ())))) -> IO (a, FireCommand DomTimeline DomHost)
376+attachWidget'' = attachImmediateWidget . const
reflex-dom-core/src/Reflex/Dom/Modals/Class.hsnew file+7
@@ -0,0 +1,7 @@
1+{-# LANGUAGE MultiParamTypeClasses #-}
2+module Reflex.Dom.Modals.Class where
3+
4+import Reflex
5+
6+class ModalOpener t m where
7+ requestingModal :: Event t (m (Event t a)) -> m (Event t (Maybe a))
src/Reflex/Dom/Old.hs → reflex-dom-core/src/Reflex/Dom/Old.hsrenamed+93−58
@@ -1,16 +1,22 @@
1+{-# LANGUAGE CPP #-}
12{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE ExplicitForAll #-}
33{-# LANGUAGE FlexibleContexts #-}
44{-# LANGUAGE FlexibleInstances #-}
55{-# LANGUAGE MultiParamTypeClasses #-}
66{-# LANGUAGE Rank2Types #-}
77{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TemplateHaskell #-}
98{-# LANGUAGE TypeFamilies #-}
109{-# LANGUAGE UndecidableInstances #-}
10+{-# LANGUAGE LambdaCase #-}
11+#ifdef USE_TEMPLATE_HASKELL
12+{-# LANGUAGE TemplateHaskell #-}
13+#endif
1114module Reflex.Dom.Old
1215 ( MonadWidget
1316 , El
17+ , ElConfig (..)
18+ , elConfig_namespace
19+ , elConfig_attributes
1420 , _el_clicked
1521 , _el_element
1622 , _el_events
@@ -18,63 +24,85 @@ module Reflex.Dom.Old
1824 , AttributeMap
1925 , Attributes (..)
2026 , buildElement
27+ , buildElementNS
2128 , buildEmptyElement
2229 , buildEmptyElementNS
23− , deleteBetweenExclusive
30+ , elDynHtml'
31+ , elDynHtmlAttr'
32+ , elStopPropagationNS
2433 , elWith
2534 , elWith'
2635 , emptyElWith
2736 , emptyElWith'
28− , getQuitWidget
2937 , namedNodeMapGetNames
3038 , nodeClear
3139 , onEventName
3240 , schedulePostBuild
3341 , text'
3442 , unsafePlaceElement
43+ , WidgetHost
3544 , wrapElement
3645 ) where
3746
3847import Control.Arrow (first)
39−import Control.Lens (makeLenses, (&), (.~), (^.))
48+#ifdef USE_TEMPLATE_HASKELL
49+import Control.Lens (makeLenses, (%~), (&), (.~), (^.))
50+#else
51+import Control.Lens (Lens, Lens', (%~), (&), (.~), (^.))
52+#endif
4053import Control.Monad
41−import Control.Monad.Exception
4254import Control.Monad.Fix
4355import Control.Monad.IO.Class
4456import Control.Monad.Reader
4557import Control.Monad.Ref
4658import Data.Default
59+import Data.Dependent.Map as DMap
4760import Data.Functor.Misc
4861import Data.Map (Map)
4962import qualified Data.Map as Map
50−import Data.Maybe
5163import Data.Set (Set)
5264import qualified Data.Set as Set
53−import Data.Text
65+import Data.Text (Text)
5466import Foreign.JavaScript.TH
67+import qualified GHCJS.DOM.Element as Element
5568import GHCJS.DOM.EventM (EventM)
5669import GHCJS.DOM.NamedNodeMap as NNM
57−import GHCJS.DOM.Node (getFirstChild, getNodeName, getParentNode, getPreviousSibling, removeChild, toNode)
58−import GHCJS.DOM.Types (IsElement, IsNode)
70+import GHCJS.DOM.Node (getFirstChild, getNodeName, removeChild)
71+import GHCJS.DOM.Types
72+ (liftJSM, JSM, IsHTMLElement, IsNode)
5973import qualified GHCJS.DOM.Types as DOM
60−import Reflex
74+import Reflex.Class
6175import Reflex.Dom.Builder.Class
6276import Reflex.Dom.Builder.Immediate
63−import Reflex.Dom.Internal.Foreign
64−import Reflex.Dom.PerformEvent.Class
65−import Reflex.Dom.PostBuild.Class
6677import Reflex.Dom.Widget.Basic
6778import Reflex.Host.Class
79+import Reflex.PerformEvent.Class
80+import Reflex.PostBuild.Class
81+import Reflex.TriggerEvent.Class
6882
6983data ElConfig attrs = ElConfig
7084 { _elConfig_namespace :: Maybe Text
7185 , _elConfig_attributes :: attrs
7286 }
7387
74−makeLenses ''ElConfig
88+instance attrs ~ Map Text Text => Default (ElConfig attrs) where
89+ def = ElConfig
90+ { _elConfig_namespace = Nothing
91+ , _elConfig_attributes = mempty
92+ }
7593
76−--TODO: HasDocument is still not accounted for
77−type MonadWidget t m =
94+#ifdef USE_TEMPLATE_HASKELL
95+makeLenses ''ElConfig
96+#else
97+elConfig_namespace :: Lens' (ElConfig attrs1) (Maybe Text)
98+elConfig_namespace f (ElConfig a b) = (\a' -> ElConfig a' b) <$> f a
99+{-# INLINE elConfig_namespace #-}
100+elConfig_attributes :: Lens (ElConfig attrs1) (ElConfig attrs2) attrs1 attrs2
101+elConfig_attributes f (ElConfig a b) = (\b' -> ElConfig a b') <$> f b
102+{-# INLINE elConfig_attributes #-}
103+#endif
104+
105+type MonadWidgetConstraints t m =
78106 ( DomBuilder t m
79107 , DomBuilderSpace m ~ GhcjsDomSpace
80108 , MonadFix m
@@ -85,17 +113,23 @@ type MonadWidget t m =
85113 , PerformEvent t m
86114 , MonadIO m
87115 , MonadIO (Performable m)
116+#ifndef ghcjs_HOST_OS
117+ , DOM.MonadJSM m
118+ , DOM.MonadJSM (Performable m)
119+#endif
88120 , TriggerEvent t m
89− , HasWebView m
90− , HasWebView (Performable m)
91− , MonadAsyncException m
92− , MonadAsyncException (Performable m)
121+ , HasJSContext m
122+ , HasJSContext (Performable m)
123+ , HasDocument m
93124 , MonadRef m
94125 , Ref m ~ Ref IO
95126 , MonadRef (Performable m)
96127 , Ref (Performable m) ~ Ref IO
97128 )
98129
130+class MonadWidgetConstraints t m => MonadWidget t m
131+instance MonadWidgetConstraints t m => MonadWidget t m
132+
99133type WidgetHost m = Performable m
100134
101135type El = Element EventResult GhcjsDomSpace
@@ -125,9 +159,9 @@ instance Attributes m (Map Text Text) t where
125159 let cfg = def & elementConfig_namespace .~ ns
126160 buildElementCommon elementTag child =<< addStaticAttributes attrs cfg
127161
128−addStaticAttributes :: Applicative m => Map Text Text -> ElementConfig er t m -> m (ElementConfig er t m)
162+addStaticAttributes :: Applicative m => Map Text Text -> ElementConfig er t (DomBuilderSpace m) -> m (ElementConfig er t (DomBuilderSpace m))
129163addStaticAttributes attrs cfg = do
130− let initialAttrs = Map.fromList $ first ((,) Nothing) <$> Map.toList attrs
164+ let initialAttrs = Map.fromList $ first (AttributeName Nothing) <$> Map.toList attrs
131165 pure $ cfg & elementConfig_initialAttributes .~ initialAttrs
132166
133167instance PostBuild t m => Attributes m (Dynamic t (Map Text Text)) t where
@@ -135,29 +169,16 @@ instance PostBuild t m => Attributes m (Dynamic t (Map Text Text)) t where
135169 let cfg = def & elementConfig_namespace .~ ns
136170 buildElementCommon elementTag child =<< addDynamicAttributes attrs cfg
137171
138−addDynamicAttributes :: PostBuild t m => Dynamic t (Map Text Text) -> ElementConfig er t m -> m (ElementConfig er t m)
172+addDynamicAttributes :: PostBuild t m => Dynamic t (Map Text Text) -> ElementConfig er t (DomBuilderSpace m) -> m (ElementConfig er t (DomBuilderSpace m))
139173addDynamicAttributes attrs cfg = do
140174 modifyAttrs <- dynamicAttributesToModifyAttributes attrs
141− return $ cfg & elementConfig_modifyAttributes .~ modifyAttrs
175+ return $ cfg & elementConfig_modifyAttributes .~ fmap mapKeysToAttributeName modifyAttrs
142176
143−buildElementCommon :: MonadWidget t m => Text -> m a -> ElementConfig er t m -> m (Element er (DomBuilderSpace m) t, a)
177+buildElementCommon :: MonadWidget t m => Text -> m a -> ElementConfig er t (DomBuilderSpace m) -> m (Element er (DomBuilderSpace m) t, a)
144178buildElementCommon elementTag child cfg = element elementTag cfg child
145179
146−-- | s and e must both be children of the same node and s must precede e
147−deleteBetweenExclusive :: (IsNode start, IsNode end) => start -> end -> IO ()
148−deleteBetweenExclusive s e = do
149− mCurrentParent <- getParentNode e -- May be different than it was at initial construction, e.g., because the parent may have dumped us in from a DocumentFragment
150− case mCurrentParent of
151− Nothing -> return () --TODO: Is this the right behavior?
152− Just currentParent -> do
153− let go = do
154− Just x <- getPreviousSibling e -- This can't be Nothing because we should hit 's' first
155− when (toNode s /= toNode x) $ do
156− _ <- removeChild currentParent $ Just x
157− go
158− go
159−
160−onEventName :: IsElement e => EventName en -> e -> EventM e (EventType en) () -> IO (IO ())
180+
181+onEventName :: IsHTMLElement e => EventName en -> e -> EventM e (EventType en) () -> JSM (JSM ())
161182onEventName = elementOnEventName
162183
163184schedulePostBuild :: (PostBuild t m, PerformEvent t m) => WidgetHost m () -> m ()
@@ -200,45 +221,59 @@ _el_events :: Element er d t -> EventSelector t (WrapArg er EventName)
200221_el_events = _element_events
201222
202223{-# DEPRECATED _el_keypress "Use 'domEvent Keypress' instead" #-}
203−_el_keypress :: Reflex t => El t -> Event t Int
224+_el_keypress :: Reflex t => El t -> Event t Word
204225_el_keypress = domEvent Keypress
205226
206227{-# DEPRECATED _el_scrolled "Use 'domEvent Scroll' instead" #-}
207−_el_scrolled :: Reflex t => El t -> Event t Int
228+_el_scrolled :: Reflex t => El t -> Event t Double
208229_el_scrolled = domEvent Scroll
209230
210231wrapElement :: forall t m. MonadWidget t m => (forall en. DOM.HTMLElement -> EventName en -> EventM DOM.Element (EventType en) (Maybe (EventResult en))) -> DOM.HTMLElement -> m (El t)
211232wrapElement eh e = do
212− let h :: (EventName en, GhcjsDomEvent en) -> IO (Maybe (EventResult en))
233+ let h :: (EventName en, GhcjsDomEvent en) -> JSM (Maybe (EventResult en))
213234 h (en, GhcjsDomEvent evt) = runReaderT (eh e en) evt
214− wrapRawElement e $ (def :: RawElementConfig EventResult t m)
235+ wrapRawElement (DOM.toElement e) $ (def :: RawElementConfig EventResult t (DomBuilderSpace m))
215236 { _rawElementConfig_eventSpec = def
216− { _ghcjsEventSpec_handler = h
237+ { _ghcjsEventSpec_handler = GhcjsEventHandler h
217238 }
218239 }
219240
220241unsafePlaceElement :: MonadWidget t m => DOM.HTMLElement -> m (Element EventResult (DomBuilderSpace m) t)
221242unsafePlaceElement e = do
222− placeRawElement e
223− wrapRawElement e def
243+ placeRawElement $ DOM.toElement e
244+ wrapRawElement (DOM.toElement e) def
224245
225−namedNodeMapGetNames :: DOM.NamedNodeMap -> IO (Set String)
246+namedNodeMapGetNames :: DOM.NamedNodeMap -> JSM (Set Text)
226247namedNodeMapGetNames self = do
227248 l <- NNM.getLength self
228− let locations = if l == 0 then [] else [0..l-1] -- Can't use 0..l-1 if l is 0 because l is unsigned and will wrap around
229− liftM (Set.fromList . catMaybes) $ forM locations $ \i -> do
230− Just n <- NNM.item self i
231− getNodeName n
249+ Set.fromList <$> forM (take (fromIntegral l) [0..]) (
250+ NNM.itemUnchecked self >=> getNodeName)
232251
233−nodeClear :: IsNode self => self -> IO ()
252+nodeClear :: IsNode self => self -> JSM ()
234253nodeClear n = do
235254 mfc <- getFirstChild n
236255 case mfc of
237256 Nothing -> return ()
238257 Just fc -> do
239− _ <- removeChild n $ Just fc
258+ _ <- removeChild n fc
240259 nodeClear n
241260
242−getQuitWidget :: MonadWidget t m => m (WidgetHost m ())
243−getQuitWidget = return $ do WebViewSingleton wv <- askWebView
244− liftIO $ quitWebView wv
261+elStopPropagationNS :: forall t m en a. (MonadWidget t m) => Maybe Text -> Text -> EventName en -> m a -> m a
262+elStopPropagationNS ns elementTag en child = do
263+ let f = GhcjsEventFilter $ \_ -> do
264+ return (stopPropagation, return Nothing)
265+ cfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
266+ & namespace .~ ns
267+ & elementConfig_eventSpec . ghcjsEventSpec_filters %~ DMap.insert en f
268+ snd <$> element elementTag cfg child
269+
270+elDynHtmlAttr' :: (DOM.MonadJSM m, MonadWidget t m) => Text -> Map Text Text -> Dynamic t Text -> m (Element EventResult GhcjsDomSpace t)
271+elDynHtmlAttr' elementTag attrs html = do
272+ let cfg = def & initialAttributes .~ Map.mapKeys (AttributeName Nothing) attrs
273+ (e, _) <- element elementTag cfg $ return ()
274+ postBuild <- getPostBuild
275+ performEvent_ $ liftJSM . Element.setInnerHTML (_element_raw e) <$> leftmost [updated html, tag (current html) postBuild]
276+ return e
277+
278+elDynHtml' :: MonadWidget t m => Text -> Dynamic t Text -> m (Element EventResult GhcjsDomSpace t)
279+elDynHtml' elementTag = elDynHtmlAttr' elementTag mempty
reflex-dom-core/src/Reflex/Dom/Prerender.hsnew file+326
@@ -0,0 +1,326 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE EmptyCase #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE FlexibleInstances #-}
6+{-# LANGUAGE FunctionalDependencies #-}
7+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8+{-# LANGUAGE LambdaCase #-}
9+{-# LANGUAGE OverloadedStrings #-}
10+{-# LANGUAGE Rank2Types #-}
11+{-# LANGUAGE RecursiveDo #-}
12+{-# LANGUAGE ScopedTypeVariables #-}
13+{-# LANGUAGE TypeFamilies #-}
14+{-# LANGUAGE UndecidableInstances #-}
15+{-# LANGUAGE UndecidableSuperClasses #-}
16+
17+-- | Render the first widget on the server, and the second on the client.
18+module Reflex.Dom.Prerender
19+ ( Prerender (..)
20+ , prerender_
21+ , PrerenderClientConstraint
22+ , PrerenderBaseConstraints
23+ ) where
24+
25+import Control.Monad.Primitive (PrimMonad(..))
26+import Control.Monad.Reader
27+import Control.Monad.Ref (MonadRef(..), MonadAtomicRef(..))
28+import Data.IORef (IORef, newIORef)
29+import Data.Semigroup (Semigroup)
30+import Data.Text (Text)
31+import Data.Void
32+import Foreign.JavaScript.TH
33+import GHCJS.DOM.Types (MonadJSM)
34+import Reflex hiding (askEvents)
35+import Reflex.Dom.Builder.Class
36+import Reflex.Dom.Builder.Hydratable
37+import Reflex.Dom.Builder.Immediate
38+import Reflex.Dom.Builder.InputDisabled
39+import Reflex.Dom.Builder.Static
40+import Reflex.Host.Class
41+import Data.IntMap.Strict (IntMap)
42+import qualified Data.IntMap.Strict as IntMap
43+
44+import qualified GHCJS.DOM.Document as Document
45+import qualified GHCJS.DOM.Node as Node
46+import qualified GHCJS.DOM.Types as DOM
47+
48+type PrerenderClientConstraint js t m =
49+ ( DomBuilder t m
50+ , DomBuilderSpace m ~ GhcjsDomSpace
51+ , DomRenderHook t m
52+ , HasDocument m
53+ , TriggerEvent t m
54+ , PrerenderBaseConstraints js t m
55+ )
56+
57+type PrerenderBaseConstraints js t m =
58+ ( HasJSContext (Performable m)
59+ , HasJSContext m
60+ , MonadFix m
61+ , MonadHold t m
62+ , MonadJSM (Performable m)
63+ , MonadJSM m
64+ , MonadRef (Performable m)
65+ , MonadRef m
66+ , MonadReflexCreateTrigger t m
67+ , MonadSample t (Performable m)
68+ , PerformEvent t m
69+ , PostBuild t m
70+ , PrimMonad m
71+ , Ref (Performable m) ~ IORef
72+ , Ref m ~ IORef
73+ , HasJS js m
74+ , HasJS js (Performable m)
75+ )
76+
77+-- | Render the first widget on the server, and the second on the client. The
78+-- hydration builder will run *both* widgets.
79+prerender_
80+ :: (Functor m, Reflex t, Prerender js t m)
81+ => m () -> Client m () -> m ()
82+prerender_ server client = void $ prerender server client
83+
84+class (PrerenderClientConstraint js t (Client m), Client (Client m) ~ Client m, Prerender js t (Client m)) => Prerender js t m | m -> t js where
85+ -- | Monad in which the client widget is built
86+ type Client m :: * -> *
87+ -- | Render the first widget on the server, and the second on the client. The
88+ -- hydration builder will run *both* widgets, updating the result dynamic at
89+ -- switchover time.
90+ prerender :: m a -> Client m a -> m (Dynamic t a)
91+
92+instance (ReflexHost t, Adjustable t m, PrerenderBaseConstraints js t m) => Prerender js t (HydrationDomBuilderT GhcjsDomSpace t m) where
93+ type Client (HydrationDomBuilderT GhcjsDomSpace t m) = HydrationDomBuilderT GhcjsDomSpace t m
94+ prerender _ client = pure <$> client
95+
96+instance (Adjustable t m, PrerenderBaseConstraints js t m, ReflexHost t) => Prerender js t (HydrationDomBuilderT HydrationDomSpace t m) where
97+ -- | PostBuildT is needed here because we delay running the client builder
98+ -- until after switchover, at which point the postBuild of @m@ has already fired
99+ type Client (HydrationDomBuilderT HydrationDomSpace t m) = PostBuildT t (HydrationDomBuilderT GhcjsDomSpace t m)
100+ -- | Runs the server widget up until switchover, then replaces it with the
101+ -- client widget.
102+ prerender server client = do
103+ env <- HydrationDomBuilderT ask
104+ events <- askEvents
105+ doc <- askDocument
106+ serverDf <- Document.createDocumentFragment doc -- server dom should not be mounted in the window's doc in hydration
107+ df <- Document.createDocumentFragment doc
108+ unreadyChildren <- HydrationDomBuilderT $ asks _hydrationDomBuilderEnv_unreadyChildren
109+ immediateMode <- liftIO $ newIORef HydrationMode_Immediate
110+ delayed <- liftIO $ newIORef $ pure ()
111+ let clientEnv = env
112+ { _hydrationDomBuilderEnv_parent = Left $ DOM.toNode df
113+ , _hydrationDomBuilderEnv_hydrationMode = immediateMode
114+ }
115+ serverEnv = HydrationDomBuilderEnv
116+ { _hydrationDomBuilderEnv_document = doc
117+ , _hydrationDomBuilderEnv_parent = Left $ DOM.toNode serverDf
118+ , _hydrationDomBuilderEnv_unreadyChildren = unreadyChildren
119+ , _hydrationDomBuilderEnv_commitAction = pure ()
120+ , _hydrationDomBuilderEnv_delayed = delayed
121+ , _hydrationDomBuilderEnv_hydrationMode = immediateMode
122+ , _hydrationDomBuilderEnv_switchover = never
123+ }
124+ a0 <- lift $ runHydrationDomBuilderT server serverEnv events
125+ (a', trigger) <- newTriggerEvent
126+ getHydrationMode >>= \case
127+ HydrationMode_Immediate -> do
128+ liftIO . trigger <=< lift $ runHydrationDomBuilderT (runPostBuildT client $ void a') clientEnv events
129+ append $ DOM.toNode df
130+ HydrationMode_Hydrating -> addHydrationStep $ do
131+ liftIO . trigger <=< lift $ runHydrationDomBuilderT (runPostBuildT client $ void a') clientEnv events
132+ insertBefore df =<< deleteToPrerenderEnd doc
133+ holdDyn a0 a'
134+
135+newtype UnrunnableT js t m a = UnrunnableT (ReaderT Void m a)
136+ deriving (Functor, Applicative, Monad, MonadTrans)
137+
138+unrunnable :: UnrunnableT js t m a
139+unrunnable = UnrunnableT $ ReaderT $ \case {}
140+
141+instance (Reflex t, Monad m) => DomBuilder t (UnrunnableT js t m) where
142+ type DomBuilderSpace (UnrunnableT js t m) = GhcjsDomSpace
143+ textNode _ = unrunnable
144+ commentNode _ = unrunnable
145+ element _ _ _ = unrunnable
146+ inputElement _ = unrunnable
147+ textAreaElement _ = unrunnable
148+ selectElement _ _ = unrunnable
149+ placeRawElement _ = unrunnable
150+ wrapRawElement _ _ = unrunnable
151+instance (Reflex t, Monad m) => NotReady t (UnrunnableT js t m) where
152+ notReadyUntil _ = unrunnable
153+ notReady = unrunnable
154+instance (Reflex t, Monad m) => Adjustable t (UnrunnableT js t m) where
155+ runWithReplace _ _ = unrunnable
156+ traverseIntMapWithKeyWithAdjust _ _ _ = unrunnable
157+ traverseDMapWithKeyWithAdjust _ _ _ = unrunnable
158+ traverseDMapWithKeyWithAdjustWithMove _ _ _ = unrunnable
159+instance (Reflex t, Monad m) => PerformEvent t (UnrunnableT js t m) where
160+ type Performable (UnrunnableT js t m) = UnrunnableT js t m
161+ performEvent _ = unrunnable
162+ performEvent_ _ = unrunnable
163+instance Monad m => MonadRef (UnrunnableT js t m) where
164+ type Ref (UnrunnableT js t m) = Ref IO
165+ newRef _ = unrunnable
166+ readRef _ = unrunnable
167+ writeRef _ _ = unrunnable
168+instance Monad m => MonadAtomicRef (UnrunnableT js t m) where
169+ atomicModifyRef _ _ = unrunnable
170+instance Monad m => HasDocument (UnrunnableT js t m) where
171+ askDocument = unrunnable
172+instance Monad m => HasJSContext (UnrunnableT js t m) where
173+ type JSContextPhantom (UnrunnableT js t m) = ()
174+ askJSContext = unrunnable
175+instance Monad m => HasJS JS' (UnrunnableT js t m) where
176+ type JSX (UnrunnableT js t m) = UnrunnableT js t m
177+ liftJS _ = unrunnable
178+instance Monad m => MonadJS JS' (UnrunnableT js t m) where
179+ runJS _ _ = unrunnable
180+ forkJS _ = unrunnable
181+ mkJSUndefined = unrunnable
182+ isJSNull _ = unrunnable
183+ isJSUndefined _ = unrunnable
184+ fromJSBool _ = unrunnable
185+ fromJSString _ = unrunnable
186+ fromJSArray _ = unrunnable
187+ fromJSUint8Array _ = unrunnable
188+ fromJSNumber _ = unrunnable
189+ withJSBool _ _ = unrunnable
190+ withJSString _ _ = unrunnable
191+ withJSNumber _ _ = unrunnable
192+ withJSArray _ _ = unrunnable
193+ withJSUint8Array _ _ = unrunnable
194+ mkJSFun _ = unrunnable
195+ freeJSFun _ = unrunnable
196+ setJSProp _ _ _ = unrunnable
197+ getJSProp _ _ = unrunnable
198+ withJSNode _ _ = unrunnable
199+instance Monad m => TriggerEvent t (UnrunnableT js t m) where
200+ newTriggerEvent = unrunnable
201+ newTriggerEventWithOnComplete = unrunnable
202+ newEventWithLazyTriggerWithOnComplete _ = unrunnable
203+instance Monad m => MonadReflexCreateTrigger t (UnrunnableT js t m) where
204+ newEventWithTrigger _ = unrunnable
205+ newFanEventWithTrigger _ = unrunnable
206+instance Monad m => MonadFix (UnrunnableT js t m) where
207+ mfix _ = unrunnable
208+instance (Monad m, MonadHold t m) => MonadHold t (UnrunnableT js t m) where
209+ hold _ _ = unrunnable
210+ holdDyn _ _ = unrunnable
211+ holdIncremental _ _ = unrunnable
212+ buildDynamic _ _ = unrunnable
213+ headE _ = unrunnable
214+ now = unrunnable
215+instance Monad m => MonadSample t (UnrunnableT js t m) where
216+ sample _ = unrunnable
217+instance Monad m => MonadIO (UnrunnableT js t m) where
218+ liftIO _ = unrunnable
219+#ifndef ghcjs_HOST_OS
220+instance Monad m => MonadJSM (UnrunnableT js t m) where
221+ liftJSM' _ = unrunnable
222+#endif
223+instance (Reflex t, Monad m) => PostBuild t (UnrunnableT js t m) where
224+ getPostBuild = unrunnable
225+instance Monad m => PrimMonad (UnrunnableT js t m) where
226+ type PrimState (UnrunnableT js t m) = PrimState IO
227+ primitive _ = unrunnable
228+instance (Reflex t, Monad m) => DomRenderHook t (UnrunnableT js t m) where
229+ withRenderHook _ _ = unrunnable
230+ requestDomAction _ = unrunnable
231+ requestDomAction_ _ = unrunnable
232+instance (Reflex t, Monad m, MonadHold t m) => Prerender JS' t (UnrunnableT js t m) where
233+ type Client (UnrunnableT js t m) = UnrunnableT js t m
234+ prerender _ _ = unrunnable
235+
236+instance (SupportsStaticDomBuilder t m) => Prerender JS' t (StaticDomBuilderT t m) where
237+ type Client (StaticDomBuilderT t m) = UnrunnableT JS' t m
238+ prerender server _ = do
239+ _ <- commentNode $ CommentNodeConfig startMarker Nothing
240+ a <- server
241+ _ <- commentNode $ CommentNodeConfig endMarker Nothing
242+ pure $ pure a
243+
244+instance (Prerender js t m, Monad m) => Prerender js t (ReaderT r m) where
245+ type Client (ReaderT r m) = ReaderT r (Client m)
246+ prerender server client = do
247+ r <- ask
248+ lift $ prerender (runReaderT server r) (runReaderT client r)
249+
250+instance (Prerender js t m, Monad m, Reflex t, MonadFix m, Monoid w) => Prerender js t (DynamicWriterT t w m) where
251+ type Client (DynamicWriterT t w m) = DynamicWriterT t w (Client m)
252+ prerender server client = do
253+ x <- lift $ prerender (runDynamicWriterT server) (runDynamicWriterT client)
254+ let (a, w') = splitDynPure x
255+ w = join w'
256+ tellDyn w
257+ pure a
258+
259+instance (Prerender js t m, Monad m, Reflex t, Semigroup w) => Prerender js t (EventWriterT t w m) where
260+ type Client (EventWriterT t w m) = EventWriterT t w (Client m)
261+ prerender server client = do
262+ x <- lift $ prerender (runEventWriterT server) (runEventWriterT client)
263+ let (a, w') = splitDynPure x
264+ w = switch $ current w'
265+ tellEvent w
266+ pure a
267+
268+instance (Prerender js t m, MonadFix m, Reflex t) => Prerender js t (RequesterT t request response m) where
269+ type Client (RequesterT t request response m) = RequesterT t request response (Client m)
270+ prerender server client = mdo
271+ let fannedResponses = fanInt responses
272+ withFannedResponses :: forall m' a. Monad m' => RequesterT t request response m' a -> Int -> m' (a, Event t (IntMap (RequesterData request)))
273+ withFannedResponses w selector = do
274+ (x, e) <- runRequesterT w (selectInt fannedResponses selector)
275+ pure (x, fmapCheap (IntMap.singleton selector) e)
276+ (result, requestsDyn) <- fmap splitDynPure $ lift $ prerender (withFannedResponses server 0) (withFannedResponses client 1)
277+ responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requestsDyn
278+ return result
279+
280+instance (Prerender js t m, Monad m, Reflex t, MonadFix m, Group q, Additive q, Query q, Eq q) => Prerender js t (QueryT t q m) where
281+ type Client (QueryT t q m) = QueryT t q (Client m)
282+ prerender server client = mdo
283+ result <- queryDyn query
284+ x <- lift $ prerender (runQueryT server result) (runQueryT client result)
285+ let (a, inc) = splitDynPure x
286+ query = incrementalToDynamic =<< inc -- Can we avoid the incrementalToDynamic?
287+ pure a
288+
289+instance (Prerender js t m, Monad m) => Prerender js t (InputDisabledT m) where
290+ type Client (InputDisabledT m) = InputDisabledT (Client m)
291+ prerender (InputDisabledT server) (InputDisabledT client) = InputDisabledT $ prerender server client
292+
293+instance (Prerender js t m, Monad m) => Prerender js t (HydratableT m) where
294+ type Client (HydratableT m) = HydratableT (Client m)
295+ prerender (HydratableT server) (HydratableT client) = HydratableT $ prerender server client
296+
297+instance (Prerender js t m, Monad m, ReflexHost t) => Prerender js t (PostBuildT t m) where
298+ type Client (PostBuildT t m) = PostBuildT t (Client m)
299+ prerender server client = PostBuildT $ do
300+ pb <- ask
301+ lift $ prerender (runPostBuildT server pb) (runPostBuildT client pb)
302+
303+startMarker, endMarker :: Text
304+startMarker = "prerender/start"
305+endMarker = "prerender/end"
306+
307+deleteToPrerenderEnd :: (MonadIO m, MonadJSM m, Reflex t, MonadFix m) => DOM.Document -> HydrationRunnerT t m DOM.Comment
308+deleteToPrerenderEnd doc = do
309+ startNode <- hydrateComment doc startMarker Nothing
310+ let go (n :: Int) lastNode = Node.getNextSibling lastNode >>= \case
311+ Nothing -> do
312+ c <- Document.createComment doc endMarker
313+ insertAfterPreviousNode c
314+ pure c
315+ Just node -> DOM.castTo DOM.Comment node >>= \case
316+ Nothing -> go n node
317+ Just c -> Node.getTextContentUnchecked c >>= \case
318+ t | t == startMarker -> go (succ n) node
319+ | t == endMarker -> case n of
320+ 0 -> pure c
321+ _ -> go (pred n) node
322+ | otherwise -> go n node
323+ endNode <- go 0 $ DOM.toNode startNode
324+ deleteBetweenExclusive startNode endNode
325+ setPreviousNode $ Just $ DOM.toNode endNode
326+ pure endNode
src/Reflex/Dom/Storage.hs → reflex-dom-core/src/Reflex/Dom/Storage.hsrenamed

The content is the same.

reflex-dom-core/src/Reflex/Dom/Time.hsnew file+3
@@ -0,0 +1,3 @@
1+module Reflex.Dom.Time {-# DEPRECATED "Use Reflex.Time instead" #-} (module Reflex.Time) where
2+
3+import Reflex.Time
reflex-dom-core/src/Reflex/Dom/WebSocket.hsnew file+189
@@ -0,0 +1,189 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE AllowAmbiguousTypes #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE DeriveDataTypeable #-}
5+{-# LANGUAGE EmptyDataDecls #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE ForeignFunctionInterface #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE JavaScriptFFI #-}
12+{-# LANGUAGE LambdaCase #-}
13+{-# LANGUAGE MultiParamTypeClasses #-}
14+{-# LANGUAGE NoMonomorphismRestriction #-}
15+{-# LANGUAGE PolyKinds #-}
16+{-# LANGUAGE RankNTypes #-}
17+{-# LANGUAGE RecursiveDo #-}
18+{-# LANGUAGE ScopedTypeVariables #-}
19+{-# LANGUAGE StandaloneDeriving #-}
20+#ifdef USE_TEMPLATE_HASKELL
21+{-# LANGUAGE TemplateHaskell #-}
22+#endif
23+{-# LANGUAGE TypeFamilies #-}
24+{-# LANGUAGE UndecidableInstances #-}
25+
26+module Reflex.Dom.WebSocket
27+ ( module Reflex.Dom.WebSocket
28+ , jsonDecode
29+ ) where
30+
31+import Prelude hiding (all, concat, concatMap, div, mapM, mapM_, sequence, span)
32+
33+import Reflex.Class
34+import Reflex.Dom.Class
35+import Reflex.Dom.WebSocket.Foreign
36+import Reflex.PerformEvent.Class
37+import Reflex.PostBuild.Class
38+import Reflex.TriggerEvent.Class
39+
40+import Control.Concurrent
41+import Control.Concurrent.STM
42+import Control.Exception
43+import Control.Lens
44+import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
45+import Control.Monad.IO.Class
46+import Control.Monad.State
47+import Data.Aeson
48+import Data.ByteString (ByteString)
49+import Data.ByteString.Lazy (toStrict)
50+import Data.Default
51+import Data.IORef
52+import Data.JSString.Text
53+import Data.Maybe (isJust)
54+import Data.Text
55+import Data.Text.Encoding
56+import Foreign.JavaScript.Utils (jsonDecode)
57+import GHCJS.DOM.Types (runJSM, askJSM, MonadJSM, liftJSM, JSM)
58+import GHCJS.DOM.WebSocket (getReadyState)
59+import GHCJS.Marshal
60+import qualified Language.Javascript.JSaddle.Monad as JS (catch)
61+
62+data WebSocketConfig t a
63+ = WebSocketConfig { _webSocketConfig_send :: Event t [a]
64+ , _webSocketConfig_close :: Event t (Word, Text)
65+ , _webSocketConfig_reconnect :: Bool
66+ , _webSocketConfig_protocols :: [Text]
67+ }
68+
69+instance Reflex t => Default (WebSocketConfig t a) where
70+ def = WebSocketConfig never never True []
71+
72+type WebSocket t = RawWebSocket t ByteString
73+
74+data RawWebSocket t a
75+ = RawWebSocket { _webSocket_recv :: Event t a
76+ , _webSocket_open :: Event t ()
77+ , _webSocket_error :: Event t () -- eror event does not carry any data and is always
78+ -- followed by termination of the connection
79+ -- for details see the close event
80+ , _webSocket_close :: Event t ( Bool -- wasClean
81+ , Word -- code
82+ , Text -- reason
83+ )
84+ }
85+
86+webSocket :: (MonadJSM m, MonadJSM (Performable m), HasJSContext m, PerformEvent t m, TriggerEvent t m, PostBuild t m, IsWebSocketMessage a) => Text -> WebSocketConfig t a -> m (WebSocket t)
87+webSocket url config = webSocket' url config onBSMessage
88+
89+webSocket' :: (MonadJSM m, MonadJSM (Performable m), HasJSContext m, PerformEvent t m, TriggerEvent t m, PostBuild t m, IsWebSocketMessage a) => Text -> WebSocketConfig t a -> (Either ByteString JSVal -> JSM b) -> m (RawWebSocket t b)
90+webSocket' url config onRawMessage = do
91+ wv <- fmap unJSContextSingleton askJSContext
92+ (eRecv, onMessage) <- newTriggerEvent
93+ currentSocketRef <- liftIO $ newIORef Nothing
94+ (eOpen, triggerEOpen) <- newTriggerEventWithOnComplete
95+ (eError, triggerEError) <- newTriggerEvent
96+ (eClose, triggerEClose) <- newTriggerEvent
97+ payloadQueue <- liftIO newTQueueIO
98+ isOpen <- liftIO newEmptyTMVarIO
99+ let onOpen = triggerEOpen () $ liftIO $ void $ atomically $ tryPutTMVar isOpen ()
100+ onError = triggerEError ()
101+ onClose args = do
102+ liftIO $ triggerEClose args
103+ _ <- liftIO $ atomically $ tryTakeTMVar isOpen
104+ liftIO $ writeIORef currentSocketRef Nothing
105+ when (_webSocketConfig_reconnect config) $ forkJSM $ do
106+ liftIO $ threadDelay 1000000
107+ start
108+ start = do
109+ ws <- newWebSocket wv url (_webSocketConfig_protocols config) (onRawMessage >=> liftIO . onMessage) (liftIO onOpen) (liftIO onError) onClose
110+ liftIO $ writeIORef currentSocketRef $ Just ws
111+ return ()
112+ performEvent_ . (liftJSM start <$) =<< getPostBuild
113+ performEvent_ $ ffor (_webSocketConfig_send config) $ \payloads -> forM_ payloads $ \payload ->
114+ liftIO $ atomically $ writeTQueue payloadQueue payload
115+ performEvent_ $ ffor (_webSocketConfig_close config) $ \(code,reason) -> liftJSM $ do
116+ mws <- liftIO $ readIORef currentSocketRef
117+ case mws of
118+ Nothing -> return ()
119+ Just ws -> closeWebSocket ws (fromIntegral code) reason
120+
121+ ctx <- askJSM
122+ _ <- liftIO $ forkIO $ forever $ do
123+ payload <- atomically $ do
124+ pl <- readTQueue payloadQueue
125+ open <- tryReadTMVar isOpen
126+ if isJust open then return pl else retry
127+
128+ mws <- liftIO $ readIORef currentSocketRef
129+ success <- case mws of
130+ Nothing -> return False
131+ Just ws -> flip runJSM ctx $ do
132+ rs <- getReadyState $ unWebSocket ws
133+ if rs == 1
134+ then (webSocketSend ws payload >> return True) `JS.catch` (\(_ :: SomeException) -> return False)
135+ else return False
136+ unless success $ atomically $ unGetTQueue payloadQueue payload
137+ return $ RawWebSocket eRecv eOpen eError eClose
138+
139+textWebSocket :: (IsWebSocketMessage a, MonadJSM m, MonadJSM (Performable m), HasJSContext m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, Reflex t) => Text -> WebSocketConfig t a -> m (RawWebSocket t Text)
140+textWebSocket url cfg = webSocket' url cfg (either (return . decodeUtf8) fromJSValUnchecked)
141+
142+jsonWebSocket :: (ToJSON a, FromJSON b, MonadJSM m, MonadJSM (Performable m), HasJSContext m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, Reflex t) => Text -> WebSocketConfig t a -> m (RawWebSocket t (Maybe b))
143+jsonWebSocket url cfg = do
144+ ws <- textWebSocket url $ cfg { _webSocketConfig_send = fmap (decodeUtf8 . toStrict . encode) <$> _webSocketConfig_send cfg }
145+ return ws { _webSocket_recv = jsonDecode . textToJSString <$> _webSocket_recv ws }
146+
147+forkJSM :: JSM () -> JSM ()
148+forkJSM a = do
149+ jsm <- askJSM
150+ void $ liftIO $ forkIO $ runJSM a jsm
151+
152+#ifdef USE_TEMPLATE_HASKELL
153+makeLensesWith (lensRules & simpleLenses .~ True) ''WebSocketConfig
154+makeLensesWith (lensRules & simpleLenses .~ True) ''RawWebSocket
155+#else
156+
157+webSocketConfig_send :: Lens' (WebSocketConfig t a) (Event t [a])
158+webSocketConfig_send f (WebSocketConfig x1 x2 x3 x4) = (\y -> WebSocketConfig y x2 x3 x4) <$> f x1
159+{-# INLINE webSocketConfig_send #-}
160+
161+webSocketConfig_close :: Lens' (WebSocketConfig t a) (Event t (Word, Text))
162+webSocketConfig_close f (WebSocketConfig x1 x2 x3 x4) = (\y -> WebSocketConfig x1 y x3 x4) <$> f x2
163+{-# INLINE webSocketConfig_close #-}
164+
165+webSocketConfig_reconnect :: Lens' (WebSocketConfig t a) Bool
166+webSocketConfig_reconnect f (WebSocketConfig x1 x2 x3 x4) = (\y -> WebSocketConfig x1 x2 y x4) <$> f x3
167+{-# INLINE webSocketConfig_reconnect #-}
168+
169+webSocketConfig_protocols :: Lens' (WebSocketConfig t a) [Text]
170+webSocketConfig_protocols f (WebSocketConfig x1 x2 x3 x4) = (\y -> WebSocketConfig x1 x2 x3 y) <$> f x4
171+{-# INLINE webSocketConfig_protocols #-}
172+
173+webSocket_recv :: Lens' (RawWebSocket t a) (Event t a)
174+webSocket_recv f (RawWebSocket x1 x2 x3 x4) = (\y -> RawWebSocket y x2 x3 x4) <$> f x1
175+{-# INLINE webSocket_recv #-}
176+
177+webSocket_open :: Lens' (RawWebSocket t a) (Event t ())
178+webSocket_open f (RawWebSocket x1 x2 x3 x4) = (\y -> RawWebSocket x1 y x3 x4) <$> f x2
179+{-# INLINE webSocket_open #-}
180+
181+webSocket_error :: Lens' (RawWebSocket t a) (Event t ())
182+webSocket_error f (RawWebSocket x1 x2 x3 x4) = (\y -> RawWebSocket x1 x2 y x4) <$> f x3
183+{-# INLINE webSocket_error #-}
184+
185+webSocket_close :: Lens' (RawWebSocket t a) (Event t (Bool, Word, Text))
186+webSocket_close f (RawWebSocket x1 x2 x3 x4) = (\y -> RawWebSocket x1 x2 x3 y) <$> f x4
187+{-# INLINE webSocket_close #-}
188+
189+#endif
reflex-dom-core/src/Reflex/Dom/WebSocket/Foreign.hsnew file+102
@@ -0,0 +1,102 @@
1+{-# LANGUAGE CPP #-}
2+#ifdef ghcjs_HOST_OS
3+{-# LANGUAGE ForeignFunctionInterface #-}
4+{-# LANGUAGE JavaScriptFFI #-}
5+#endif
6+{-# LANGUAGE LambdaCase #-}
7+
8+module Reflex.Dom.WebSocket.Foreign
9+ ( module Reflex.Dom.WebSocket.Foreign
10+ , JSVal
11+ ) where
12+
13+import Prelude hiding (all, concat, concatMap, div, mapM, mapM_, sequence, span)
14+
15+import Data.Bifoldable
16+import Data.ByteString (ByteString)
17+import qualified Data.ByteString.Lazy as LBS
18+import Data.Text (Text)
19+import Data.Text.Encoding
20+import Foreign.JavaScript.Utils (bsFromMutableArrayBuffer, bsToArrayBuffer)
21+import GHCJS.DOM.CloseEvent
22+import GHCJS.DOM.MessageEvent
23+import GHCJS.DOM.Types (JSM, JSVal, liftJSM, fromJSValUnchecked, WebSocket(..))
24+import qualified GHCJS.DOM.WebSocket as DOM
25+import GHCJS.Foreign (JSType(..), jsTypeOf)
26+import Language.Javascript.JSaddle (fun, eval, toJSVal, call)
27+import Language.Javascript.JSaddle.Helper (mutableArrayBufferFromJSVal)
28+import Language.Javascript.JSaddle.Types (ghcjsPure)
29+
30+newtype JSWebSocket = JSWebSocket { unWebSocket :: WebSocket }
31+
32+class IsWebSocketMessage a where
33+ webSocketSend :: JSWebSocket -> a -> JSM ()
34+
35+instance (IsWebSocketMessage a, IsWebSocketMessage b) => IsWebSocketMessage (Either a b) where
36+ webSocketSend jws = bitraverse_ (webSocketSend jws) (webSocketSend jws)
37+
38+-- Use binary websocket communication for ByteString
39+-- Note: Binary websockets may not work correctly in IE 11 and below
40+instance IsWebSocketMessage ByteString where
41+ webSocketSend (JSWebSocket ws) bs = do
42+ ab <- bsToArrayBuffer bs
43+ DOM.send ws ab
44+
45+instance IsWebSocketMessage LBS.ByteString where
46+ webSocketSend ws = webSocketSend ws . LBS.toStrict
47+
48+-- Use plaintext websocket communication for Text, and String
49+instance IsWebSocketMessage Text where
50+ webSocketSend (JSWebSocket ws) = DOM.sendString ws
51+
52+closeWebSocket :: JSWebSocket -> Word -> Text -> JSM ()
53+closeWebSocket (JSWebSocket ws) code reason = DOM.close ws (Just code) (Just reason)
54+
55+newWebSocket
56+ :: a
57+ -> Text -- url
58+ -> [Text] -- protocols
59+ -> (Either ByteString JSVal -> JSM ()) -- onmessage
60+ -> JSM () -- onopen
61+ -> JSM () -- onerror
62+ -> ((Bool, Word, Text) -> JSM ()) -- onclose
63+ -> JSM JSWebSocket
64+newWebSocket _ url protocols onMessage onOpen onError onClose = do
65+ let onOpenWrapped = fun $ \_ _ _ -> onOpen
66+ onErrorWrapped = fun $ \_ _ _ -> onError
67+ onCloseWrapped = fun $ \_ _ (e:_) -> do
68+ let e' = CloseEvent e
69+ wasClean <- getWasClean e'
70+ code <- getCode e'
71+ reason <- getReason e'
72+ liftJSM $ onClose (wasClean, code, reason)
73+ onMessageWrapped = fun $ \_ _ (e:_) -> do
74+ let e' = MessageEvent e
75+ d <- getData e'
76+ liftJSM $ ghcjsPure (jsTypeOf d) >>= \case
77+ String -> onMessage $ Right d
78+ _ -> do
79+ ab <- mutableArrayBufferFromJSVal d
80+ bsFromMutableArrayBuffer ab >>= onMessage . Left
81+ newWS <- eval $ unlines
82+ [ "(function(url, protos, open, error, close, message) {"
83+ , " var ws = new window['WebSocket'](url, protos);"
84+ , " ws['binaryType'] = 'arraybuffer';"
85+ , " ws['addEventListener']('open', open);"
86+ , " ws['addEventListener']('error', error);"
87+ , " ws['addEventListener']('close', close);"
88+ , " ws['addEventListener']('message', message);"
89+ , " return ws;"
90+ , "})"
91+ ]
92+ url' <- toJSVal url
93+ protocols' <- toJSVal protocols
94+ onOpen' <- toJSVal onOpenWrapped
95+ onError' <- toJSVal onErrorWrapped
96+ onClose' <- toJSVal onCloseWrapped
97+ onMessage' <- toJSVal onMessageWrapped
98+ ws <- call newWS newWS [url', protocols', onOpen', onError', onClose', onMessage']
99+ return $ JSWebSocket $ WebSocket ws
100+
101+onBSMessage :: Either ByteString JSVal -> JSM ByteString
102+onBSMessage = either return $ fmap encodeUtf8 . fromJSValUnchecked
reflex-dom-core/src/Reflex/Dom/WebSocket/Query.hsnew file+37
@@ -0,0 +1,37 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE RecursiveDo #-}
3+module Reflex.Dom.WebSocket.Query (cropQueryT, runWebSocketQuery) where
4+
5+import Data.Default
6+import Control.Monad.Fix
7+import Data.Text (Text)
8+import Data.Aeson
9+import Reflex
10+import Reflex.Dom.WebSocket
11+import Foreign.JavaScript.TH
12+import Data.Maybe
13+import Language.Javascript.JSaddle.Types (MonadJSM)
14+
15+runWebSocketQuery :: (MonadJSM m, MonadJSM (Performable m), HasJSContext m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, Reflex t, ToJSON q, MonadFix m, Query q, FromJSON (QueryResult q), Additive q, Group q, Eq q)
16+ => QueryT t q m a
17+ -> Text -- ^ WebSocket url
18+ -> m a
19+runWebSocketQuery app url = do
20+ postBuild <- getPostBuild
21+ rec ws <- jsonWebSocket url $ def { _webSocketConfig_send = pure <$> updatedRequest }
22+ (a, request) <- cropQueryT app $ fromMaybe mempty <$> _webSocket_recv ws
23+ let updatedRequest = leftmost [updated request, tag (current request) postBuild]
24+ return a
25+
26+cropQueryT :: (Reflex t, MonadHold t m, MonadFix m, Query q, Additive q, Group q, Eq q)
27+ => QueryT t q m a
28+ -> Event t (QueryResult q)
29+ -> m (a, Dynamic t q)
30+cropQueryT app result = do
31+ rec (a, requestPatch) <- runQueryT app croppedResult
32+ requestUniq <- holdUniqDyn $ incrementalToDynamic requestPatch
33+ croppedResult <- cropDyn requestUniq result
34+ return (a, requestUniq)
35+
36+cropDyn :: (Query q, MonadHold t m, Reflex t, MonadFix m) => Dynamic t q -> Event t (QueryResult q) -> m (Dynamic t (QueryResult q))
37+cropDyn q = foldDyn (\(q', qr) v -> crop q' (qr `mappend` v)) mempty . attach (current q)
src/Reflex/Dom/Widget.hs → reflex-dom-core/src/Reflex/Dom/Widget.hsrenamed

The content is the same.

reflex-dom-core/src/Reflex/Dom/Widget/Basic.hsnew file+345
@@ -0,0 +1,345 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE DataKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE OverloadedStrings #-}
8+{-# LANGUAGE RankNTypes #-}
9+{-# LANGUAGE RecursiveDo #-}
10+{-# LANGUAGE ScopedTypeVariables #-}
11+{-# LANGUAGE TypeFamilies #-}
12+module Reflex.Dom.Widget.Basic
13+ (
14+ -- * Displaying Values
15+ text
16+ , dynText
17+ , comment
18+ , dynComment
19+ , display
20+ , button
21+ , dyn
22+ , dyn_
23+ , widgetHold
24+ , widgetHold_
25+
26+ -- * Creating DOM Elements
27+ , el
28+ , elAttr
29+ , elClass
30+ , elDynAttr
31+ , elDynClass
32+ , elDynAttrNS
33+
34+ -- ** With Element Results
35+ , el'
36+ , elAttr'
37+ , elClass'
38+ , elDynAttr'
39+ , elDynClass'
40+ , elDynAttrNS'
41+ , dynamicAttributesToModifyAttributes
42+ , dynamicAttributesToModifyAttributesWithInitial
43+
44+ -- * Specific DOM Elements
45+ , Link (..)
46+ , linkClass
47+ , link
48+ , divClass
49+ , dtdd
50+ , blank
51+
52+ -- * Tables and Lists
53+ , tableDynAttr
54+ , tabDisplay
55+
56+ , HasAttributes (..)
57+ , module Data.Map.Misc
58+ , module Reflex.Collection
59+ , module Reflex.Workflow
60+ , partitionMapBySetLT
61+ ) where
62+
63+import Reflex.Adjustable.Class
64+import Reflex.Class
65+import Reflex.Collection
66+import Reflex.Dom.Builder.Class
67+import Reflex.Dom.Class
68+import Reflex.Dynamic
69+import Reflex.Network
70+import Reflex.PostBuild.Class
71+import Reflex.Workflow
72+
73+import Control.Arrow
74+import Control.Lens hiding (children, element)
75+import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
76+import Data.Align
77+import Data.Default
78+import Data.Either
79+import Data.Foldable
80+import Data.Functor (void)
81+import Data.Map (Map)
82+import qualified Data.Map as Map
83+import Data.Map.Misc
84+import Data.Maybe
85+import Data.Set (Set)
86+import qualified Data.Set as Set
87+import Data.Text (Text)
88+import qualified Data.Text as T
89+import Data.These
90+import Data.Traversable
91+import Prelude hiding (mapM, mapM_, sequence, sequence_)
92+
93+-- | Breaks the given Map into pieces based on the given Set. Each piece will contain only keys that are less than the key of the piece, and greater than or equal to the key of the piece with the next-smaller key. There will be one additional piece containing all keys from the original Map that are larger or equal to the largest key in the Set.
94+-- Either k () is used instead of Maybe k so that the resulting map of pieces is sorted so that the additional piece has the largest key.
95+-- No empty pieces will be included in the output.
96+
97+--TODO: This can probably be done more efficiently by dividing and conquering, re-using the structure of the Set instead of going through the Set linearally
98+{-# DEPRECATED partitionMapBySetLT "This will be removed in future releases." #-}
99+partitionMapBySetLT :: forall k v. Ord k => Set k -> Map k v -> Map (Either k ()) (Map k v)
100+partitionMapBySetLT s m0 = Map.fromDistinctAscList $ go (Set.toAscList s) m0
101+ where go :: [k] -> Map k v -> [(Either k (), Map k v)]
102+ go [] m = if Map.null m
103+ then []
104+ else [(Right (), m)]
105+ go (h:t) m = let (lt, eq, gt) = Map.splitLookup h m
106+ geq = maybe id (Map.insert h) eq gt
107+ in if Map.null lt
108+ then go t geq
109+ else (Left h, lt) : go t geq
110+
111+{-# INLINABLE text #-}
112+text :: DomBuilder t m => Text -> m ()
113+text t = void $ textNode $ def & textNodeConfig_initialContents .~ t
114+
115+{-# INLINABLE dynText #-}
116+dynText :: forall t m. (PostBuild t m, DomBuilder t m) => Dynamic t Text -> m ()
117+dynText t = do
118+ postBuild <- getPostBuild
119+ void $ textNode $ (def :: TextNodeConfig t) & textNodeConfig_setContents .~ leftmost
120+ [ updated t
121+ , tag (current t) postBuild
122+ ]
123+ notReadyUntil postBuild
124+
125+comment :: DomBuilder t m => Text -> m ()
126+comment t = void $ commentNode $ def & commentNodeConfig_initialContents .~ t
127+
128+{-# INLINABLE dynComment #-}
129+dynComment :: forall t m. (PostBuild t m, DomBuilder t m) => Dynamic t Text -> m ()
130+dynComment t = do
131+ postBuild <- getPostBuild
132+ void $ commentNode $ (def :: CommentNodeConfig t) & commentNodeConfig_setContents .~ leftmost
133+ [ updated t
134+ , tag (current t) postBuild
135+ ]
136+ notReadyUntil postBuild
137+
138+display :: (PostBuild t m, DomBuilder t m, Show a) => Dynamic t a -> m ()
139+display = dynText . fmap (T.pack . show)
140+
141+button :: DomBuilder t m => Text -> m (Event t ())
142+button t = do
143+ (e, _) <- element "button" def $ text t
144+ return $ domEvent Click e
145+
146+--TODO: Should this be renamed to 'widgetView' for consistency with 'widgetHold'?
147+-- | Given a Dynamic of widget-creating actions, create a widget that is recreated whenever the Dynamic updates.
148+-- The returned Event occurs whenever the child widget is updated, which is
149+-- at post-build in addition to the times at which the input Dynamic is
150+-- updated, and its value is the result of running the widget.
151+-- Note: Often, the type @a@ is an 'Event', in which case the return value is an Event-of-Events that would typically be flattened (via 'switchHold').
152+dyn :: (Adjustable t m, NotReady t m, PostBuild t m) => Dynamic t (m a) -> m (Event t a)
153+dyn = networkView
154+
155+-- | Like 'dyn' but discards result.
156+dyn_ :: (Adjustable t m, NotReady t m, PostBuild t m) => Dynamic t (m a) -> m ()
157+dyn_ = void . dyn
158+
159+-- | Given an initial widget and an Event of widget-creating actions, create a widget that is recreated whenever the Event fires.
160+-- The returned Dynamic of widget results occurs when the Event does.
161+-- Note: Often, the type 'a' is an Event, in which case the return value is a Dynamic-of-Events that would typically be flattened (via 'switchDyn').
162+widgetHold :: (Adjustable t m, MonadHold t m) => m a -> Event t (m a) -> m (Dynamic t a)
163+widgetHold = networkHold
164+
165+-- | Like 'widgetHold' but discards result.
166+widgetHold_ :: (Adjustable t m, MonadHold t m) => m a -> Event t (m a) -> m ()
167+widgetHold_ z = void . widgetHold z
168+
169+-- | Create a DOM element
170+--
171+-- >>> el "div" (text "Hello World")
172+-- <div>Hello World</div>
173+{-# INLINABLE el #-}
174+el :: forall t m a. DomBuilder t m => Text -> m a -> m a
175+el elementTag child = snd <$> el' elementTag child
176+
177+-- | Create a DOM element with attributes
178+--
179+-- >>> elAttr "a" ("href" =: "https://reflex-frp.org") (text "Reflex-FRP!")
180+-- <a href="https://reflex-frp.org">Reflex-FRP!</a>
181+{-# INLINABLE elAttr #-}
182+elAttr :: forall t m a. DomBuilder t m => Text -> Map Text Text -> m a -> m a
183+elAttr elementTag attrs child = snd <$> elAttr' elementTag attrs child
184+
185+-- | Create a DOM element with classes
186+--
187+-- >>> elClass "div" "row" (return ())
188+-- <div class="row"></div>
189+{-# INLINABLE elClass #-}
190+elClass :: forall t m a. DomBuilder t m => Text -> Text -> m a -> m a
191+elClass elementTag c child = snd <$> elClass' elementTag c child
192+
193+-- | Create a DOM element with Dynamic Attributes
194+--
195+-- >>> elClass "div" (constDyn ("class" =: "row")) (return ())
196+-- <div class="row"></div>
197+{-# INLINABLE elDynAttr #-}
198+elDynAttr :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t (Map Text Text) -> m a -> m a
199+elDynAttr elementTag attrs child = snd <$> elDynAttr' elementTag attrs child
200+
201+-- | Create a DOM element with a Dynamic Class
202+--
203+-- >>> elDynClass "div" (constDyn "row") (return ())
204+-- <div class="row"></div>
205+{-# INLINABLE elDynClass #-}
206+elDynClass :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t Text -> m a -> m a
207+elDynClass elementTag c child = snd <$> elDynClass' elementTag c child
208+
209+-- | Create a DOM element and return the element
210+--
211+-- @
212+-- do (e, _) <- el' "div" (text "Click")
213+-- return $ domEvent Click e
214+-- @
215+{-# INLINABLE el' #-}
216+el' :: forall t m a. DomBuilder t m => Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
217+el' elementTag = element elementTag def
218+
219+-- | Create a DOM element with attributes and return the element
220+{-# INLINABLE elAttr' #-}
221+elAttr' :: forall t m a. DomBuilder t m => Text -> Map Text Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
222+elAttr' elementTag attrs = element elementTag $ def
223+ & initialAttributes .~ Map.mapKeys (AttributeName Nothing) attrs
224+
225+-- | Create a DOM element with a class and return the element
226+{-# INLINABLE elClass' #-}
227+elClass' :: forall t m a. DomBuilder t m => Text -> Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
228+elClass' elementTag c = elAttr' elementTag ("class" =: c)
229+
230+-- | Create a DOM element with Dynamic Attributes and return the element
231+{-# INLINABLE elDynAttr' #-}
232+elDynAttr' :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t (Map Text Text) -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
233+elDynAttr' = elDynAttrNS' Nothing
234+
235+-- | Create a DOM element with a Dynamic class and return the element
236+{-# INLINABLE elDynClass' #-}
237+elDynClass' :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
238+elDynClass' elementTag c = elDynAttr' elementTag (fmap ("class" =:) c)
239+
240+{-# INLINABLE elDynAttrNS' #-}
241+elDynAttrNS' :: forall t m a. (DomBuilder t m, PostBuild t m) => Maybe Text -> Text -> Dynamic t (Map Text Text) -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
242+elDynAttrNS' mns elementTag attrs child = do
243+ modifyAttrs <- dynamicAttributesToModifyAttributes attrs
244+ let cfg = def
245+ & elementConfig_namespace .~ mns
246+ & modifyAttributes .~ fmapCheap mapKeysToAttributeName modifyAttrs
247+ result <- element elementTag cfg child
248+ postBuild <- getPostBuild
249+ notReadyUntil postBuild
250+ return result
251+
252+{-# INLINABLE elDynAttrNS #-}
253+elDynAttrNS :: forall t m a. (DomBuilder t m, PostBuild t m) => Maybe Text -> Text -> Dynamic t (Map Text Text) -> m a -> m a
254+elDynAttrNS mns elementTag attrs child = fmap snd $ elDynAttrNS' mns elementTag attrs child
255+
256+dynamicAttributesToModifyAttributes :: (Ord k, PostBuild t m) => Dynamic t (Map k Text) -> m (Event t (Map k (Maybe Text)))
257+dynamicAttributesToModifyAttributes = dynamicAttributesToModifyAttributesWithInitial mempty
258+
259+dynamicAttributesToModifyAttributesWithInitial :: (Ord k, PostBuild t m) => Map k Text -> Dynamic t (Map k Text) -> m (Event t (Map k (Maybe Text)))
260+dynamicAttributesToModifyAttributesWithInitial attrs0 d = do
261+ postBuild <- getPostBuild
262+ let modificationsNeeded = flip push (align postBuild $ updated d) $ \x -> do
263+ p <- case x of
264+ This () -> do
265+ new <- sample $ current d
266+ return $ diffMap attrs0 new
267+ These () new -> return $ diffMap attrs0 new
268+ That new -> do
269+ old <- sample $ current d
270+ return $ diffMap old new
271+ return $ if Map.null p then Nothing else Just p
272+ return modificationsNeeded
273+
274+newtype Link t
275+ = Link { _link_clicked :: Event t ()
276+ }
277+
278+linkClass :: DomBuilder t m => Text -> Text -> m (Link t)
279+linkClass s c = do
280+ (l,_) <- elAttr' "a" ("class" =: c) $ text s
281+ return $ Link $ domEvent Click l
282+
283+link :: DomBuilder t m => Text -> m (Link t)
284+link s = linkClass s ""
285+
286+divClass :: forall t m a. DomBuilder t m => Text -> m a -> m a
287+divClass = elClass "div"
288+
289+dtdd :: forall t m a. DomBuilder t m => Text -> m a -> m a
290+dtdd h w = do
291+ el "dt" $ text h
292+ el "dd" w
293+
294+blank :: forall m. Monad m => m ()
295+blank = return ()
296+
297+-- TODO: Move to an example project.
298+-- | A widget to display a table with static columns and dynamic rows.
299+tableDynAttr :: forall t m r k v. (Ord k, DomBuilder t m, MonadHold t m, PostBuild t m, MonadFix m)
300+ => Text -- ^ Class applied to <table> element
301+ -> [(Text, k -> Dynamic t r -> m v)] -- ^ Columns of (header, row key -> row value -> child widget)
302+ -> Dynamic t (Map k r) -- ^ Map from row key to row value
303+ -> (k -> m (Dynamic t (Map Text Text))) -- ^ Function to compute <tr> element attributes from row key
304+ -> m (Dynamic t (Map k (Element EventResult (DomBuilderSpace m) t, [v]))) -- ^ Map from row key to (El, list of widget return values)
305+tableDynAttr klass cols dRows rowAttrs = elAttr "div" (Map.singleton "style" "zoom: 1; overflow: auto; background: white;") $
306+ elAttr "table" (Map.singleton "class" klass) $ do
307+ el "thead" $ el "tr" $
308+ mapM_ (\(h, _) -> el "th" $ text h) cols
309+ el "tbody" $
310+ listWithKey dRows (\k r -> do
311+ dAttrs <- rowAttrs k
312+ elDynAttr' "tr" dAttrs $ mapM (\x -> el "td" $ snd x k r) cols)
313+
314+-- TODO: Move to an example project.
315+-- | A widget to construct a tabbed view that shows only one of its child widgets at a time.
316+-- Creates a header bar containing a <ul> with one <li> per child; clicking a <li> displays
317+-- the corresponding child and hides all others.
318+tabDisplay :: forall t m k. (MonadFix m, DomBuilder t m, MonadHold t m, PostBuild t m, Ord k)
319+ => Text -- ^ Class applied to <ul> element
320+ -> Text -- ^ Class applied to currently active <li> element
321+ -> Map k (Text, m ()) -- ^ Map from (arbitrary) key to (tab label, child widget)
322+ -> m ()
323+tabDisplay ulClass activeClass tabItems = do
324+ let t0 = listToMaybe $ Map.keys tabItems
325+ rec currentTab :: Demux t (Maybe k) <- elAttr "ul" ("class" =: ulClass) $ do
326+ tabClicksList :: [Event t k] <- Map.elems <$> imapM (\k (s,_) -> headerBarLink s k $ demuxed currentTab (Just k)) tabItems
327+ let eTabClicks :: Event t k = leftmost tabClicksList
328+ fmap demux $ holdDyn t0 $ fmap Just eTabClicks
329+ el "div" $ do
330+ iforM_ tabItems $ \k (_, w) -> do
331+ let isSelected = demuxed currentTab $ Just k
332+ attrs = ffor isSelected $ \s -> if s then Map.empty else Map.singleton "style" "display:none;"
333+ elDynAttr "div" attrs w
334+ return ()
335+ where
336+ headerBarLink :: Text -> k -> Dynamic t Bool -> m (Event t k)
337+ headerBarLink x k isSelected = do
338+ let attrs = fmap (\b -> if b then Map.singleton "class" activeClass else Map.empty) isSelected
339+ elDynAttr "li" attrs $ do
340+ a <- link x
341+ return $ fmap (const k) (_link_clicked a)
342+
343+class HasAttributes a where
344+ type Attrs a :: *
345+ attributes :: Lens' a (Attrs a)
src/Reflex/Dom/Widget/Input.hs → reflex-dom-core/src/Reflex/Dom/Widget/Input.hsrenamed+231−121
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
12{-# LANGUAGE ConstraintKinds #-}
23{-# LANGUAGE DataKinds #-}
34{-# LANGUAGE FlexibleContexts #-}
@@ -8,7 +9,9 @@
89{-# LANGUAGE PolyKinds #-}
910{-# LANGUAGE RecursiveDo #-}
1011{-# LANGUAGE ScopedTypeVariables #-}
12+#ifdef USE_TEMPLATE_HASKELL
1113{-# LANGUAGE TemplateHaskell #-}
14+#endif
1215{-# LANGUAGE TypeFamilies #-}
1316{-# LANGUAGE UndecidableInstances #-}
1417module Reflex.Dom.Widget.Input (module Reflex.Dom.Widget.Input, def, (&), (.~)) where
@@ -30,37 +33,45 @@ import Data.Maybe
3033import Data.Semigroup
3134import Data.Text (Text)
3235import qualified Data.Text as T
33−import GHCJS.DOM.Element (castToElement)
34−import qualified GHCJS.DOM.Element as Element
36+import qualified GHCJS.DOM.GlobalEventHandlers as Events
3537import GHCJS.DOM.EventM (on)
3638import qualified GHCJS.DOM.FileList as FileList
37−import GHCJS.DOM.HTMLInputElement (HTMLInputElement, castToHTMLInputElement)
38−import GHCJS.DOM.HTMLSelectElement (castToHTMLSelectElement)
39−import qualified GHCJS.DOM.HTMLSelectElement as HTMLSelectElement
40−import GHCJS.DOM.HTMLTextAreaElement (HTMLTextAreaElement, castToHTMLTextAreaElement)
41−import GHCJS.DOM.Types (File)
42−import Reflex
39+import GHCJS.DOM.HTMLInputElement (HTMLInputElement)
40+import GHCJS.DOM.HTMLTextAreaElement (HTMLTextAreaElement)
41+import GHCJS.DOM.Types (MonadJSM, File, uncheckedCastTo)
42+import qualified GHCJS.DOM.Types as DOM (HTMLElement(..), EventTarget(..))
43+import Reflex.Class
44+import Reflex.Collection
4345import Reflex.Dom.Builder.Class
4446import Reflex.Dom.Builder.Immediate
4547import Reflex.Dom.Class
46−import Reflex.Dom.PerformEvent.Class
47−import Reflex.Dom.PostBuild.Class
4848import Reflex.Dom.Widget.Basic
49+import Reflex.Dynamic
50+import Reflex.PostBuild.Class
51+import Reflex.TriggerEvent.Class
4952import qualified Text.Read as T
5053
5154import qualified GHCJS.DOM.Event as Event
5255import qualified GHCJS.DOM.HTMLInputElement as Input
5356
57+{-# DEPRECATED TextInput, _textInput_element, TextInputConfig, textInput "Use 'inputElement' directly" #-}
5458data TextInput t
5559 = TextInput { _textInput_value :: Dynamic t Text
5660 , _textInput_input :: Event t Text
57− , _textInput_keypress :: Event t Int
58− , _textInput_keydown :: Event t Int
59− , _textInput_keyup :: Event t Int
61+ , _textInput_keypress :: Event t Word
62+ , _textInput_keydown :: Event t Word
63+ , _textInput_keyup :: Event t Word
6064 , _textInput_hasFocus :: Dynamic t Bool
61− , _textInput_element :: HTMLInputElement
65+ , _textInput_builderElement :: InputElement EventResult GhcjsDomSpace t
6266 }
6367
68+_textInput_element :: TextInput t -> HTMLInputElement
69+_textInput_element = _inputElement_raw . _textInput_builderElement
70+
71+instance Reflex t => HasDomEvent t (TextInput t) en where
72+ type DomEventType (TextInput t) en = DomEventType (InputElement EventResult GhcjsDomSpace t) en
73+ domEvent en = domEvent en . _textInput_builderElement
74+
6475data TextInputConfig t
6576 = TextInputConfig { _textInputConfig_inputType :: Text
6677 , _textInputConfig_initialValue :: Text
@@ -84,7 +95,7 @@ textInput (TextInputConfig inputType initial eSetValue dAttrs) = do
8495 i <- inputElement $ def
8596 & inputElementConfig_initialValue .~ initial
8697 & inputElementConfig_setValue .~ eSetValue
87− & inputElementConfig_elementConfig . elementConfig_modifyAttributes .~ modifyAttrs
98+ & inputElementConfig_elementConfig . elementConfig_modifyAttributes .~ fmap mapKeysToAttributeName modifyAttrs
8899 return $ TextInput
89100 { _textInput_value = _inputElement_value i
90101 , _textInput_input = _inputElement_input i
@@ -92,12 +103,25 @@ textInput (TextInputConfig inputType initial eSetValue dAttrs) = do
92103 , _textInput_keydown = domEvent Keydown i
93104 , _textInput_keyup = domEvent Keyup i
94105 , _textInput_hasFocus = _inputElement_hasFocus i
95− , _textInput_element = castToHTMLInputElement $ _element_raw $ _inputElement_element i
106+ , _textInput_builderElement = i
96107 }
97108
98−{-# INLINABLE textInputGetEnter #-}
109+{-# INLINE textInputGetEnter #-}
110+{-# DEPRECATED textInputGetEnter "Use 'keypress Enter' instead" #-}
99111textInputGetEnter :: Reflex t => TextInput t -> Event t ()
100−textInputGetEnter i = fmapMaybe (\n -> if keyCodeLookup n == Enter then Just () else Nothing) $ _textInput_keypress i
112+textInputGetEnter = keypress Enter
113+
114+{-# INLINABLE keypress #-}
115+keypress :: (Reflex t, HasDomEvent t e 'KeypressTag, DomEventType e 'KeypressTag ~ Word) => Key -> e -> Event t ()
116+keypress key = fmapMaybe (\n -> guard $ keyCodeLookup (fromIntegral n) == key) . domEvent Keypress
117+
118+{-# INLINABLE keydown #-}
119+keydown :: (Reflex t, HasDomEvent t e 'KeydownTag, DomEventType e 'KeydownTag ~ Word) => Key -> e -> Event t ()
120+keydown key = fmapMaybe (\n -> guard $ keyCodeLookup (fromIntegral n) == key) . domEvent Keydown
121+
122+{-# INLINABLE keyup #-}
123+keyup :: (Reflex t, HasDomEvent t e 'KeyupTag, DomEventType e 'KeyupTag ~ Word) => Key -> e -> Event t ()
124+keyup key = fmapMaybe (\n -> guard $ keyCodeLookup (fromIntegral n) == key) . domEvent Keyup
101125
102126data RangeInputConfig t
103127 = RangeInputConfig { _rangeInputConfig_initialValue :: Float
@@ -129,15 +153,16 @@ rangeInput (RangeInputConfig initial eSetValue dAttrs) = do
129153 i <- inputElement $ def
130154 & inputElementConfig_initialValue .~ (T.pack . show $ initial)
131155 & inputElementConfig_setValue .~ (T.pack . show <$> eSetValue)
132− & inputElementConfig_elementConfig . elementConfig_modifyAttributes .~ modifyAttrs
156+ & inputElementConfig_elementConfig . elementConfig_modifyAttributes .~ fmap mapKeysToAttributeName modifyAttrs
133157 return $ RangeInput
134158 { _rangeInput_value = read . T.unpack <$> _inputElement_value i
135159 , _rangeInput_input = read . T.unpack <$> _inputElement_input i
136160 , _rangeInput_mouseup = domEvent Mouseup i
137161 , _rangeInput_hasFocus = _inputElement_hasFocus i
138− , _rangeInput_element = castToHTMLInputElement $ _element_raw $ _inputElement_element i
162+ , _rangeInput_element = _inputElement_raw i
139163 }
140164
165+{-# DEPRECATED TextAreaConfig, TextArea, textArea "Use 'textAreaElement' directly" #-}
141166data TextAreaConfig t
142167 = TextAreaConfig { _textAreaConfig_initialValue :: Text
143168 , _textAreaConfig_setValue :: Event t Text
@@ -155,7 +180,7 @@ data TextArea t
155180 = TextArea { _textArea_value :: Dynamic t Text
156181 , _textArea_input :: Event t Text
157182 , _textArea_hasFocus :: Dynamic t Bool
158− , _textArea_keypress :: Event t Int
183+ , _textArea_keypress :: Event t Word
159184 , _textArea_element :: HTMLTextAreaElement
160185 }
161186
@@ -166,15 +191,16 @@ textArea (TextAreaConfig initial eSet attrs) = do
166191 i <- textAreaElement $ def
167192 & textAreaElementConfig_initialValue .~ initial
168193 & textAreaElementConfig_setValue .~ eSet
169− & textAreaElementConfig_elementConfig . elementConfig_modifyAttributes .~ modifyAttrs
194+ & textAreaElementConfig_elementConfig . elementConfig_modifyAttributes .~ fmap mapKeysToAttributeName modifyAttrs
170195 return $ TextArea
171196 { _textArea_value = _textAreaElement_value i
172197 , _textArea_input = _textAreaElement_input i
173198 , _textArea_keypress = domEvent Keypress i
174199 , _textArea_hasFocus = _textAreaElement_hasFocus i
175− , _textArea_element = castToHTMLTextAreaElement $ _element_raw $ _textAreaElement_element i
200+ , _textArea_element = _textAreaElement_raw i
176201 }
177202
203+{-# DEPRECATED CheckboxConfig, Checkbox, checkbox, checkboxView, CheckboxViewEventResultType, regularToCheckboxViewEventType, CheckboxViewEventResult "Use 'inputElement' directly" #-}
178204data CheckboxConfig t
179205 = CheckboxConfig { _checkboxConfig_setValue :: Event t Bool
180206 , _checkboxConfig_attributes :: Dynamic t (Map Text Text)
@@ -202,8 +228,8 @@ checkbox checked config = do
202228 i <- inputElement $ def
203229 & inputElementConfig_initialChecked .~ checked
204230 & inputElementConfig_setChecked .~ _checkboxConfig_setValue config
205− & inputElementConfig_elementConfig . elementConfig_initialAttributes .~ Map.mapKeys ((,) Nothing) permanentAttrs
206− & inputElementConfig_elementConfig . elementConfig_modifyAttributes .~ modifyAttrs
231+ & inputElementConfig_elementConfig . elementConfig_initialAttributes .~ Map.mapKeys (AttributeName Nothing) permanentAttrs
232+ & inputElementConfig_elementConfig . elementConfig_modifyAttributes .~ fmap mapKeysToAttributeName modifyAttrs
207233 return $ Checkbox
208234 { _checkbox_value = _inputElement_checked i
209235 , _checkbox_change = _inputElement_checkedChange i
@@ -248,17 +274,15 @@ regularToCheckboxViewEventType en r = case en of
248274 Select -> r
249275 Submit -> r
250276 Wheel -> r
251− {-
252277 Beforecut -> r
253278 Cut -> r
254279 Beforecopy -> r
255280 Copy -> r
256281 Beforepaste -> r
257282 Paste -> r
258−-}
259283 Reset -> r
260284 Search -> r
261−-- Selectstart -> r
285+ Selectstart -> r
262286 Touchstart -> r
263287 Touchmove -> r
264288 Touchend -> r
@@ -266,7 +290,7 @@ regularToCheckboxViewEventType en r = case en of
266290
267291newtype CheckboxViewEventResult en = CheckboxViewEventResult { unCheckboxViewEventResult :: CheckboxViewEventResultType en }
268292
269−--TODO
293+-- | Create a view only checkbox
270294{-# INLINABLE checkboxView #-}
271295checkboxView :: forall t m. (DomBuilder t m, DomBuilderSpace m ~ GhcjsDomSpace, PostBuild t m, MonadHold t m) => Dynamic t (Map Text Text) -> Dynamic t Bool -> m (Event t Bool)
272296checkboxView dAttrs dValue = do
@@ -275,36 +299,38 @@ checkboxView dAttrs dValue = do
275299 postBuild <- getPostBuild
276300 let filters :: DMap EventName (GhcjsEventFilter CheckboxViewEventResult)
277301 filters = DMap.singleton Click $ GhcjsEventFilter $ \(GhcjsDomEvent evt) -> do
278− Just t <- Event.getTarget evt
279− b <- Input.getChecked $ Input.castToHTMLInputElement t
302+ t <- Event.getTargetUnchecked evt
303+ b <- Input.getChecked $ uncheckedCastTo Input.HTMLInputElement t
280304 return $ (,) preventDefault $ return $ Just $ CheckboxViewEventResult b
281− elementConfig :: ElementConfig CheckboxViewEventResult t m
282− elementConfig = (def :: ElementConfig EventResult t m)
283− { _elementConfig_modifyAttributes = modifyAttrs
284− , _elementConfig_initialAttributes = Map.mapKeys ((,) Nothing) permanentAttrs
305+ elementConfig :: ElementConfig CheckboxViewEventResult t (DomBuilderSpace m)
306+ elementConfig = (def :: ElementConfig EventResult t (DomBuilderSpace m))
307+ { _elementConfig_modifyAttributes = Just $ fmap mapKeysToAttributeName modifyAttrs
308+ , _elementConfig_initialAttributes = Map.mapKeys (AttributeName Nothing) permanentAttrs
285309 , _elementConfig_eventSpec = GhcjsEventSpec
286310 { _ghcjsEventSpec_filters = filters
287− , _ghcjsEventSpec_handler = \(en, GhcjsDomEvent evt) -> case en of
311+ , _ghcjsEventSpec_handler = GhcjsEventHandler $ \(en, GhcjsDomEvent evt) -> case en of
288312 Click -> error "impossible"
289313 _ -> do
290− Just e <- withIsEvent en $ Event.getTarget evt
291− mr <- runReaderT (defaultDomEventHandler (castToElement e) en) evt
314+ e :: DOM.EventTarget <- withIsEvent en $ Event.getTargetUnchecked evt
315+ let myElement = uncheckedCastTo DOM.HTMLElement e
316+ mr <- runReaderT (defaultDomEventHandler myElement en) evt
292317 return $ ffor mr $ \(EventResult r) -> CheckboxViewEventResult $ regularToCheckboxViewEventType en r
293318 }
294319 }
295− inputElementConfig :: InputElementConfig CheckboxViewEventResult t m
296− inputElementConfig = (def :: InputElementConfig EventResult t m)
320+ inputElementConfig :: InputElementConfig CheckboxViewEventResult t (DomBuilderSpace m)
321+ inputElementConfig = (def :: InputElementConfig EventResult t (DomBuilderSpace m))
297322 & inputElementConfig_setChecked .~ leftmost [updated dValue, tag (current dValue) postBuild]
298323 & inputElementConfig_elementConfig .~ elementConfig
299324 i <- inputElement inputElementConfig
300325 return $ unCheckboxViewEventResult <$> select (_element_events $ _inputElement_element i) (WrapArg Click)
301326
327+{-# DEPRECATED FileInput, FileInputConfig, fileInput "Use 'inputElement' directly" #-}
302328data FileInput d t
303329 = FileInput { _fileInput_value :: Dynamic t [File]
304330 , _fileInput_element :: RawInputElement d
305331 }
306332
307−data FileInputConfig t
333+newtype FileInputConfig t
308334 = FileInputConfig { _fileInputConfig_attributes :: Dynamic t (Map Text Text)
309335 }
310336
@@ -312,7 +338,7 @@ instance Reflex t => Default (FileInputConfig t) where
312338 def = FileInputConfig { _fileInputConfig_attributes = constDyn mempty
313339 }
314340
315−fileInput :: forall t m. (MonadIO m, MonadFix m, MonadHold t m, TriggerEvent t m, DomBuilder t m, PostBuild t m, DomBuilderSpace m ~ GhcjsDomSpace)
341+fileInput :: forall t m. (MonadIO m, MonadJSM m, MonadFix m, MonadHold t m, TriggerEvent t m, DomBuilder t m, PostBuild t m, DomBuilderSpace m ~ GhcjsDomSpace)
316342 => FileInputConfig t -> m (FileInput (DomBuilderSpace m) t)
317343fileInput config = do
318344 let insertType = Map.insert "type" "file"
@@ -320,20 +346,14 @@ fileInput config = do
320346 modifyAttrs <- dynamicAttributesToModifyAttributes dAttrs
321347 let filters = DMap.singleton Change . GhcjsEventFilter $ \_ -> do
322348 return . (,) mempty $ return . Just $ EventResult ()
323− elCfg = (def :: ElementConfig EventResult t m)
324− & modifyAttributes .~ modifyAttrs
349+ elCfg = (def :: ElementConfig EventResult t (DomBuilderSpace m))
350+ & modifyAttributes .~ fmap mapKeysToAttributeName modifyAttrs
325351 & elementConfig_eventSpec . ghcjsEventSpec_filters .~ filters
326− cfg = (def :: InputElementConfig EventResult t m) & inputElementConfig_elementConfig .~ elCfg
327− eRaw <- inputElement cfg
328− let e = _inputElement_raw eRaw
329− eChange <- wrapDomEvent e (`on` Element.change) $ do
330− Just files <- Input.getFiles e
331− len <- FileList.getLength files
332− mapM (fmap (fromMaybe (error "fileInput: fileList.item returned null")) . FileList.item files) [0 .. len-1]
333− dValue <- holdDyn [] eChange
352+ cfg = (def :: InputElementConfig EventResult t (DomBuilderSpace m)) & inputElementConfig_elementConfig .~ elCfg
353+ input <- inputElement cfg
334354 return $ FileInput
335− { _fileInput_value = dValue
336− , _fileInput_element = e
355+ { _fileInput_value = _inputElement_files input
356+ , _fileInput_element = _inputElement_raw input
337357 }
338358
339359data Dropdown t k
@@ -392,17 +412,15 @@ regularToDropdownViewEventType en r = case en of
392412 Select -> r
393413 Submit -> r
394414 Wheel -> r
395− {-
396415 Beforecut -> r
397416 Cut -> r
398417 Beforecopy -> r
399418 Copy -> r
400419 Beforepaste -> r
401420 Paste -> r
402−-}
403421 Reset -> r
404422 Search -> r
405−-- Selectstart -> r
423+ Selectstart -> r
406424 Touchstart -> r
407425 Touchmove -> r
408426 Touchend -> r
@@ -411,7 +429,7 @@ regularToDropdownViewEventType en r = case en of
411429--TODO: We should allow the user to specify an ordering instead of relying on the ordering of the Map
412430-- | Create a dropdown box
413431-- The first argument gives the initial value of the dropdown; if it is not present in the map of options provided, it will be added with an empty string as its text
414−dropdown :: forall k t m. (DomBuilder t m, MonadFix m, MonadHold t m, PerformEvent t m, MonadIO (Performable m), MonadIO m, TriggerEvent t m, PostBuild t m, DomBuilderSpace m ~ GhcjsDomSpace, Ord k) => k -> Dynamic t (Map k Text) -> DropdownConfig t k -> m (Dropdown t k)
432+dropdown :: forall k t m. (DomBuilder t m, MonadFix m, MonadHold t m, PostBuild t m, Ord k) => k -> Dynamic t (Map k Text) -> DropdownConfig t k -> m (Dropdown t k)
415433dropdown k0 options (DropdownConfig setK attrs) = do
416434 optionsWithAddedKeys <- fmap (zipDynWith Map.union options) $ foldDyn Map.union (k0 =: "") $ fmap (=: "") setK
417435 defaultKey <- holdDyn k0 setK
@@ -419,31 +437,19 @@ dropdown k0 options (DropdownConfig setK attrs) = do
419437 let xs = fmap (\(ix, (k, v)) -> ((ix, k), ((ix, k), v))) $ zip [0::Int ..] $ Map.toList os
420438 in (Map.fromList $ map snd xs, Bimap.fromList $ map fst xs)
421439 modifyAttrs <- dynamicAttributesToModifyAttributes attrs
422− let cfg = (def :: ElementConfig EventResult t m)
423− { _elementConfig_modifyAttributes = modifyAttrs
424− , _elementConfig_eventSpec = GhcjsEventSpec
425− { _ghcjsEventSpec_filters = DMap.singleton Change $ GhcjsEventFilter $ \(GhcjsDomEvent evt) -> do
426− Just t <- Event.getTarget evt
427− Just v <- HTMLSelectElement.getValue $ HTMLSelectElement.castToHTMLSelectElement t
428− return $ (,) mempty $ return $ Just $ DropdownViewEventResult v
429− , _ghcjsEventSpec_handler = \(en, GhcjsDomEvent evt) -> case en of
430− Click -> error "impossible"
431− _ -> do
432− Just e <- withIsEvent en $ Event.getTarget evt
433− mr <- runReaderT (defaultDomEventHandler (castToElement e) en) evt
434− return $ ffor mr $ \(EventResult r) -> DropdownViewEventResult $ regularToDropdownViewEventType en r
435− }
436− }
437− (eRaw, _) <- element "select" cfg $ listWithKey indexedOptions $ \(ix, k) v -> do
440+ postBuild <- getPostBuild
441+ let setSelection = attachPromptlyDynWithMaybe (flip Bimap.lookupR) ixKeys $
442+ leftmost [setK, k0 <$ postBuild]
443+ let cfg = def
444+ & selectElementConfig_elementConfig . elementConfig_modifyAttributes .~ fmap mapKeysToAttributeName modifyAttrs
445+ & selectElementConfig_setValue .~ fmap (T.pack . show) setSelection
446+ (eRaw, _) <- selectElement cfg $ listWithKey indexedOptions $ \(ix, k) v -> do
438447 let optionAttrs = fmap (\dk -> "value" =: T.pack (show ix) <> if dk == k then "selected" =: "selected" else mempty) defaultKey
439448 elDynAttr "option" optionAttrs $ dynText v
440− let e = castToHTMLSelectElement $ _element_raw eRaw
441− performEvent_ $ HTMLSelectElement.setValue e . Just . show <$> attachPromptlyDynWithMaybe (flip Bimap.lookupR) ixKeys setK
442− let lookupSelected ks value = do
443− v <- value
444− key <- T.readMaybe v
449+ let lookupSelected ks v = do
450+ key <- T.readMaybe $ T.unpack v
445451 Bimap.lookup key ks
446− eChange <- attachPromptlyDynWith lookupSelected ixKeys <$> wrapDomEvent e (`on` Element.change) (HTMLSelectElement.getValue e)
452+ let eChange = attachPromptlyDynWith lookupSelected ixKeys $ _selectElement_change eRaw
447453 let readKey keys mk = fromMaybe k0 $ do
448454 k <- mk
449455 guard $ Bimap.memberR k keys
@@ -451,6 +457,7 @@ dropdown k0 options (DropdownConfig setK attrs) = do
451457 dValue <- fmap (zipDynWith readKey ixKeys) $ holdDyn (Just k0) $ leftmost [eChange, fmap Just setK]
452458 return $ Dropdown dValue (attachPromptlyDynWith readKey ixKeys eChange)
453459
460+#ifdef USE_TEMPLATE_HASKELL
454461concat <$> mapM makeLenses
455462 [ ''TextAreaConfig
456463 , ''TextArea
@@ -465,6 +472,138 @@ concat <$> mapM makeLenses
465472 , ''CheckboxConfig
466473 , ''Checkbox
467474 ]
475+#else
476+textAreaConfig_attributes :: Lens' (TextAreaConfig t) (Dynamic t (Map Text Text))
477+textAreaConfig_attributes f (TextAreaConfig x1 x2 x3) = (\y -> TextAreaConfig x1 x2 y) <$> f x3
478+{-# INLINE textAreaConfig_attributes #-}
479+textAreaConfig_initialValue :: Lens' (TextAreaConfig t) Text
480+textAreaConfig_initialValue f (TextAreaConfig x1 x2 x3) = (\y -> TextAreaConfig y x2 x3) <$> f x1
481+{-# INLINE textAreaConfig_initialValue #-}
482+textAreaConfig_setValue :: Lens' (TextAreaConfig t) (Event t Text)
483+textAreaConfig_setValue f (TextAreaConfig x1 x2 x3) = (\y -> TextAreaConfig x1 y x3) <$> f x2
484+{-# INLINE textAreaConfig_setValue #-}
485+textArea_element :: Lens' (TextArea t) HTMLTextAreaElement
486+textArea_element f (TextArea x1 x2 x3 x4 x5) = (\y -> TextArea x1 x2 x3 x4 y) <$> f x5
487+{-# INLINE textArea_element #-}
488+textArea_hasFocus :: Lens' (TextArea t) (Dynamic t Bool)
489+textArea_hasFocus f (TextArea x1 x2 x3 x4 x5) = (\y -> TextArea x1 x2 y x4 x5) <$> f x3
490+{-# INLINE textArea_hasFocus #-}
491+textArea_input :: Lens' (TextArea t) (Event t Text)
492+textArea_input f (TextArea x1 x2 x3 x4 x5) = (\y -> TextArea x1 y x3 x4 x5) <$> f x2
493+{-# INLINE textArea_input #-}
494+textArea_keypress :: Lens' (TextArea t) (Event t Word)
495+textArea_keypress f (TextArea x1 x2 x3 x4 x5) = (\y -> TextArea x1 x2 x3 y x5) <$> f x4
496+{-# INLINE textArea_keypress #-}
497+textArea_value :: Lens' (TextArea t) (Dynamic t Text)
498+textArea_value f (TextArea x1 x2 x3 x4 x5) = (\y -> TextArea y x2 x3 x4 x5) <$> f x1
499+{-# INLINE textArea_value #-}
500+textInputConfig_attributes :: Lens' (TextInputConfig t) (Dynamic t (Map Text Text))
501+textInputConfig_attributes f (TextInputConfig x1 x2 x3 x4) = (\y -> TextInputConfig x1 x2 x3 y) <$> f x4
502+{-# INLINE textInputConfig_attributes #-}
503+textInputConfig_initialValue :: Lens' (TextInputConfig t) Text
504+textInputConfig_initialValue f (TextInputConfig x1 x2 x3 x4) = (\y -> TextInputConfig x1 y x3 x4) <$> f x2
505+{-# INLINE textInputConfig_initialValue #-}
506+textInputConfig_inputType :: Lens' (TextInputConfig t) Text
507+textInputConfig_inputType f (TextInputConfig x1 x2 x3 x4) = (\y -> TextInputConfig y x2 x3 x4) <$> f x1
508+{-# INLINE textInputConfig_inputType #-}
509+textInputConfig_setValue :: Lens' (TextInputConfig t) (Event t Text)
510+textInputConfig_setValue f (TextInputConfig x1 x2 x3 x4) = (\y -> TextInputConfig x1 x2 y x4) <$> f x3
511+{-# INLINE textInputConfig_setValue #-}
512+textInput_builderElement :: Lens' (TextInput t) (InputElement EventResult GhcjsDomSpace t)
513+textInput_builderElement f (TextInput x1 x2 x3 x4 x5 x6 x7) = (\y -> TextInput x1 x2 x3 x4 x5 x6 y) <$> f x7
514+{-# INLINE textInput_builderElement #-}
515+textInput_hasFocus :: Lens' (TextInput t) (Dynamic t Bool)
516+textInput_hasFocus f (TextInput x1 x2 x3 x4 x5 x6 x7) = (\y -> TextInput x1 x2 x3 x4 x5 y x7) <$> f x6
517+{-# INLINE textInput_hasFocus #-}
518+textInput_input :: Lens' (TextInput t) (Event t Text)
519+textInput_input f (TextInput x1 x2 x3 x4 x5 x6 x7) = (\y -> TextInput x1 y x3 x4 x5 x6 x7) <$> f x2
520+{-# INLINE textInput_input #-}
521+textInput_keydown :: Lens' (TextInput t) (Event t Word)
522+textInput_keydown f (TextInput x1 x2 x3 x4 x5 x6 x7) = (\y -> TextInput x1 x2 x3 y x5 x6 x7) <$> f x4
523+{-# INLINE textInput_keydown #-}
524+textInput_keypress :: Lens' (TextInput t) (Event t Word)
525+textInput_keypress f (TextInput x1 x2 x3 x4 x5 x6 x7) = (\y -> TextInput x1 x2 y x4 x5 x6 x7) <$> f x3
526+{-# INLINE textInput_keypress #-}
527+textInput_keyup :: Lens' (TextInput t) (Event t Word)
528+textInput_keyup f (TextInput x1 x2 x3 x4 x5 x6 x7) = (\y -> TextInput x1 x2 x3 x4 y x6 x7) <$> f x5
529+{-# INLINE textInput_keyup #-}
530+textInput_value :: Lens' (TextInput t) (Dynamic t Text)
531+textInput_value f (TextInput x1 x2 x3 x4 x5 x6 x7) = (\y -> TextInput y x2 x3 x4 x5 x6 x7) <$> f x1
532+{-# INLINE textInput_value #-}
533+rangeInputConfig_attributes :: Lens' (RangeInputConfig t) (Dynamic t (Map Text Text))
534+rangeInputConfig_attributes f (RangeInputConfig x1 x2 x3) = (\y -> RangeInputConfig x1 x2 y) <$> f x3
535+{-# INLINE rangeInputConfig_attributes #-}
536+rangeInputConfig_initialValue :: Lens' (RangeInputConfig t) Float
537+rangeInputConfig_initialValue f (RangeInputConfig x1 x2 x3) = (\y -> RangeInputConfig y x2 x3) <$> f x1
538+{-# INLINE rangeInputConfig_initialValue #-}
539+rangeInputConfig_setValue :: Lens' (RangeInputConfig t) (Event t Float)
540+rangeInputConfig_setValue f (RangeInputConfig x1 x2 x3) = (\y -> RangeInputConfig x1 y x3) <$> f x2
541+{-# INLINE rangeInputConfig_setValue #-}
542+rangeInput_element :: Lens' (RangeInput t) HTMLInputElement
543+rangeInput_element f (RangeInput x1 x2 x3 x4 x5) = (\y -> RangeInput x1 x2 x3 x4 y) <$> f x5
544+{-# INLINE rangeInput_element #-}
545+rangeInput_hasFocus :: Lens' (RangeInput t) (Dynamic t Bool)
546+rangeInput_hasFocus f (RangeInput x1 x2 x3 x4 x5) = (\y -> RangeInput x1 x2 x3 y x5) <$> f x4
547+{-# INLINE rangeInput_hasFocus #-}
548+rangeInput_input :: Lens' (RangeInput t) (Event t Float)
549+rangeInput_input f (RangeInput x1 x2 x3 x4 x5) = (\y -> RangeInput x1 y x3 x4 x5) <$> f x2
550+{-# INLINE rangeInput_input #-}
551+rangeInput_mouseup :: Lens' (RangeInput t) (Event t (Int, Int))
552+rangeInput_mouseup f (RangeInput x1 x2 x3 x4 x5) = (\y -> RangeInput x1 x2 y x4 x5) <$> f x3
553+{-# INLINE rangeInput_mouseup #-}
554+rangeInput_value :: Lens' (RangeInput t) (Dynamic t Float)
555+rangeInput_value f (RangeInput x1 x2 x3 x4 x5) = (\y -> RangeInput y x2 x3 x4 x5) <$> f x1
556+{-# INLINE rangeInput_value #-}
557+fileInputConfig_attributes :: Iso
558+ (FileInputConfig t1)
559+ (FileInputConfig t2)
560+ (Dynamic t1 (Map Text Text))
561+ (Dynamic t2 (Map Text Text))
562+fileInputConfig_attributes = iso (\(FileInputConfig x) -> x) FileInputConfig
563+{-# INLINE fileInputConfig_attributes #-}
564+fileInput_element :: Lens
565+ (FileInput d1 t)
566+ (FileInput d2 t)
567+ (RawInputElement d1)
568+ (RawInputElement d2)
569+fileInput_element f (FileInput x1 x2) = (\y -> FileInput x1 y) <$> f x2
570+{-# INLINE fileInput_element #-}
571+fileInput_value :: Lens
572+ (FileInput d t1)
573+ (FileInput d t2)
574+ (Dynamic t1 [File])
575+ (Dynamic t2 [File])
576+fileInput_value f (FileInput x1 x2) = (\y -> FileInput y x2) <$> f x1
577+{-# INLINE fileInput_value #-}
578+dropdownConfig_attributes :: Lens' (DropdownConfig t k) (Dynamic t (Map Text Text))
579+dropdownConfig_attributes f (DropdownConfig x1 x2) = (\y -> DropdownConfig x1 y) <$> f x2
580+{-# INLINE dropdownConfig_attributes #-}
581+dropdownConfig_setValue :: Lens
582+ (DropdownConfig t k1)
583+ (DropdownConfig t k2)
584+ (Event t k1)
585+ (Event t k2)
586+dropdownConfig_setValue f (DropdownConfig x1 x2) = (\y -> DropdownConfig y x2) <$> f x1
587+{-# INLINE dropdownConfig_setValue #-}
588+dropdown_change :: Lens' (Dropdown t k) (Event t k)
589+dropdown_change f (Dropdown x1 x2) = (\y -> Dropdown x1 y) <$> f x2
590+{-# INLINE dropdown_change #-}
591+dropdown_value :: Lens' (Dropdown t k) (Dynamic t k)
592+dropdown_value f (Dropdown x1 x2) = (\y -> Dropdown y x2) <$> f x1
593+{-# INLINE dropdown_value #-}
594+checkboxConfig_attributes :: Lens' (CheckboxConfig t) (Dynamic t (Map Text Text))
595+checkboxConfig_attributes f (CheckboxConfig x1 x2) = (\y -> CheckboxConfig x1 y) <$> f x2
596+{-# INLINE checkboxConfig_attributes #-}
597+checkboxConfig_setValue :: Lens' (CheckboxConfig t) (Event t Bool)
598+checkboxConfig_setValue f (CheckboxConfig x1 x2) = (\y -> CheckboxConfig y x2) <$> f x1
599+{-# INLINE checkboxConfig_setValue #-}
600+checkbox_change :: Lens' (Checkbox t) (Event t Bool)
601+checkbox_change f (Checkbox x1 x2) = (\y -> Checkbox x1 y) <$> f x2
602+{-# INLINE checkbox_change #-}
603+checkbox_value :: Lens' (Checkbox t) (Dynamic t Bool)
604+checkbox_value f (Checkbox x1 x2) = (\y -> Checkbox y x2) <$> f x1
605+{-# INLINE checkbox_value #-}
606+#endif
468607
469608instance HasAttributes (TextAreaConfig t) where
470609 type Attrs (TextAreaConfig t) = Dynamic t (Map Text Text)
@@ -490,9 +629,6 @@ instance HasAttributes (FileInputConfig t) where
490629 type Attrs (FileInputConfig t) = Dynamic t (Map Text Text)
491630 attributes = fileInputConfig_attributes
492631
493−class HasSetValue a where
494− type SetValue a :: *
495− setValue :: Lens' a (SetValue a)
496632
497633instance HasSetValue (TextAreaConfig t) where
498634 type SetValue (TextAreaConfig t) = Event t Text
@@ -518,6 +654,14 @@ class HasValue a where
518654 type Value a :: *
519655 value :: a -> Value a
520656
657+instance HasValue (InputElement er d t) where
658+ type Value (InputElement er d t) = Dynamic t Text
659+ value = _inputElement_value
660+
661+instance HasValue (TextAreaElement er d t) where
662+ type Value (TextAreaElement er d t) = Dynamic t Text
663+ value = _textAreaElement_value
664+
521665instance HasValue (TextArea t) where
522666 type Value (TextArea t) = Dynamic t Text
523667 value = _textArea_value
@@ -526,6 +670,10 @@ instance HasValue (TextInput t) where
526670 type Value (TextInput t) = Dynamic t Text
527671 value = _textInput_value
528672
673+instance HasValue (RangeInput t) where
674+ type Value (RangeInput t) = Dynamic t Float
675+ value = _rangeInput_value
676+
529677instance HasValue (FileInput d t) where
530678 type Value (FileInput d t) = Dynamic t [File]
531679 value = _fileInput_value
@@ -537,41 +685,3 @@ instance HasValue (Dropdown t k) where
537685instance HasValue (Checkbox t) where
538686 type Value (Checkbox t) = Dynamic t Bool
539687 value = _checkbox_value
540−
541−{-
542−type family Controller sm t a where
543− Controller Edit t a = (a, Event t a) -- Initial value and setter
544− Controller View t a = Dynamic t a -- Value (always)
545−
546−type family Output sm t a where
547− Output Edit t a = Dynamic t a -- Value (always)
548− Output View t a = Event t a -- Requested changes
549−
550−data CheckboxConfig sm t
551− = CheckboxConfig { _checkbox_input :: Controller sm t Bool
552− , _checkbox_attributes :: Attributes
553− }
554−
555−instance Reflex t => Default (CheckboxConfig Edit t) where
556− def = CheckboxConfig (False, never) mempty
557−
558−data Checkbox sm t
559− = Checkbox { _checkbox_output :: Output sm t Bool
560− }
561−
562−data StateMode = Edit | View
563−
564−--TODO: There must be a more generic way to get this witness and allow us to case on the type-level StateMode
565−data StateModeWitness (sm :: StateMode) where
566− EditWitness :: StateModeWitness Edit
567− ViewWitness :: StateModeWitness View
568−
569−class HasStateModeWitness (sm :: StateMode) where
570− stateModeWitness :: StateModeWitness sm
571−
572−instance HasStateModeWitness Edit where
573− stateModeWitness = EditWitness
574−
575−instance HasStateModeWitness View where
576− stateModeWitness = ViewWitness
577−-}
src/Reflex/Dom/Widget/Lazy.hs → reflex-dom-core/src/Reflex/Dom/Widget/Lazy.hsrenamed+22−19
@@ -6,16 +6,17 @@
66{-# LANGUAGE TypeFamilies #-}
77module Reflex.Dom.Widget.Lazy where
88
9−import Reflex
9+import Reflex.Class
10+import Reflex.Collection
1011import Reflex.Dom.Builder.Class
1112import Reflex.Dom.Builder.Immediate
1213import Reflex.Dom.Class
13−import Reflex.Dom.PerformEvent.Class
14−import Reflex.Dom.PostBuild.Class
1514import Reflex.Dom.Widget.Basic
15+import Reflex.Dynamic
16+import Reflex.PerformEvent.Class
17+import Reflex.PostBuild.Class
1618
1719import Control.Monad.Fix
18−import Control.Monad.IO.Class
1920import Data.Fixed
2021import Data.Map (Map)
2122import qualified Data.Map as Map
@@ -23,9 +24,10 @@ import Data.Monoid
2324import Data.Text (Text)
2425import qualified Data.Text as T
2526import GHCJS.DOM.Element
27+import GHCJS.DOM.Types (MonadJSM)
2628
2729-- |A list view for long lists. Creates a scrollable element and only renders child row elements near the current scroll position.
28−virtualListWithSelection :: forall t m k v. (DomBuilder t m, PostBuild t m, MonadHold t m, PerformEvent t m, MonadIO (Performable m), DomBuilderSpace m ~ GhcjsDomSpace, MonadFix m, Ord k)
30+virtualListWithSelection :: forall t m k v. (DomBuilder t m, PostBuild t m, MonadHold t m, PerformEvent t m, MonadJSM (Performable m), DomBuilderSpace m ~ GhcjsDomSpace, MonadFix m, Ord k)
2931 => Dynamic t Int -- ^ The height of the visible region in pixels
3032 -> Int -- ^ The height of each row in pixels
3133 -> Dynamic t Int -- ^ The total number of items
@@ -51,18 +53,18 @@ virtualListWithSelection heightPx rowPx maxIndex i0 setI listTag listAttrs rowTa
5153 return lis
5254 selected <- holdDyn (indexToKey i0) sel
5355 pb <- getPostBuild
54− scrollPosition <- holdDyn 0 $ leftmost [ domEvent Scroll container
56+ scrollPosition <- holdDyn 0 $ leftmost [ round <$> domEvent Scroll container
5557 , fmap (const (i0 * rowPx)) pb
5658 ]
5759 let window = zipDynWith (findWindow rowPx) heightPx scrollPosition
5860 itemsInWindow = zipDynWith (\(_,(idx,num)) is -> Map.fromList $ map (\i -> let ix = indexToKey i in (ix, Map.lookup ix is)) [idx .. idx + num]) window items
5961 postBuild <- getPostBuild
60− performEvent_ $ ffor (leftmost [setI, i0 <$ postBuild]) $ \i -> do
61− liftIO $ setScrollTop (_element_raw container) (i * rowPx)
62+ performEvent_ $ ffor (leftmost [setI, i0 <$ postBuild]) $ \i ->
63+ setScrollTop (_element_raw container) (i * rowPx)
6264 let indexAndLength = fmap snd window
6365 return (indexAndLength, sel)
6466 where
65− toStyleAttr m = "style" =: Map.foldWithKey (\k v s -> k <> ":" <> v <> ";" <> s) "" m
67+ toStyleAttr m = "style" =: Map.foldrWithKey (\k v s -> k <> ":" <> v <> ";" <> s) "" m
6668 toViewport h = toStyleAttr $ "overflow" =: "auto" <> "position" =: "absolute" <>
6769 "left" =: "0" <> "right" =: "0" <> "height" =: (T.pack (show h) <> "px")
6870 toContainer h = toStyleAttr $ "position" =: "relative" <> "height" =: (T.pack (show h) <> "px")
@@ -79,7 +81,7 @@ virtualListWithSelection heightPx rowPx maxIndex i0 setI listTag listAttrs rowTa
7981 preItems = min startingIndex numItems
8082 in (topPx - preItems * sizeIncrement, (startingIndex - preItems, preItems + numItems * 2))
8183
82−virtualList :: forall t m k v a. (DomBuilder t m, PostBuild t m, MonadHold t m, PerformEvent t m, MonadIO (Performable m), DomBuilderSpace m ~ GhcjsDomSpace, MonadFix m, Ord k)
84+virtualList :: forall t m k v a. (DomBuilder t m, PostBuild t m, MonadHold t m, PerformEvent t m, MonadJSM (Performable m), DomBuilderSpace m ~ GhcjsDomSpace, MonadFix m, Ord k)
8385 => Dynamic t Int -- ^ A 'Dynamic' of the visible region's height in pixels
8486 -> Int -- ^ The fixed height of each row in pixels
8587 -> Dynamic t Int -- ^ A 'Dynamic' of the total number of items
@@ -91,21 +93,22 @@ virtualList :: forall t m k v a. (DomBuilder t m, PostBuild t m, MonadHold t m,
9193 -> (k -> v -> Event t v -> m a) -- ^ The row child element builder.
9294 -> m (Dynamic t (Int, Int), Dynamic t (Map k a)) -- ^ A tuple containing: a 'Dynamic' of the index (based on the current scroll position) and number of items currently being rendered, and the 'Dynamic' list result
9395virtualList heightPx rowPx maxIndex i0 setI keyToIndex items0 itemsUpdate itemBuilder = do
94− let virtualH = fmap (mkVirtualHeight . (*) rowPx) maxIndex
96+ let virtualH = mkVirtualHeight <$> maxIndex
9597 containerStyle = fmap mkContainer heightPx
9698 viewportStyle = fmap mkViewport heightPx
9799 pb <- getPostBuild
98100 rec (viewport, result) <- elDynAttr "div" containerStyle $ elDynAttr' "div" viewportStyle $ elDynAttr "div" virtualH $
99101 listWithKeyShallowDiff items0 itemsUpdate $ \k v e -> elAttr "div" (mkRow k) $ itemBuilder k v e
100− scrollPosition <- holdDyn 0 $ leftmost [ domEvent Scroll viewport
102+ scrollPosition <- holdDyn 0 $ leftmost [ round <$> domEvent Scroll viewport
101103 , fmap (const (i0 * rowPx)) pb
102104 ]
103105 let window = zipDynWith (findWindow rowPx) heightPx scrollPosition
104− performEvent_ $ ffor (leftmost [setI, i0 <$ pb]) $ \i -> do
105− liftIO $ setScrollTop (_element_raw viewport) (i * rowPx)
106− return (uniqDyn window, result)
106+ performEvent_ $ ffor (leftmost [setI, i0 <$ pb]) $ \i ->
107+ setScrollTop (_element_raw viewport) (i * rowPx)
108+ uniqWindow <- holdUniqDyn window
109+ return (uniqWindow, result)
107110 where
108− toStyleAttr m = "style" =: Map.foldWithKey (\k v s -> k <> ":" <> v <> ";" <> s) "" m
111+ toStyleAttr m = "style" =: Map.foldrWithKey (\k v s -> k <> ":" <> v <> ";" <> s) "" m
109112 mkViewport h = toStyleAttr $ "overflow" =: "auto" <> "position" =: "absolute" <>
110113 "left" =: "0" <> "right" =: "0" <> "height" =: (T.pack (show h) <> "px")
111114 mkContainer h = toStyleAttr $ "position" =: "relative" <> "height" =: (T.pack (show h) <> "px")
@@ -114,7 +117,7 @@ virtualList heightPx rowPx maxIndex i0 setI keyToIndex items0 itemsUpdate itemBu
114117 "overflow" =: "hidden" <>
115118 "position" =: "relative"
116119 mkRow k = toStyleAttr $ "height" =: (T.pack (show rowPx) <> "px") <>
117− "top" =: ((<>"px") $ T.pack $ show $ keyToIndex k * rowPx) <>
120+ "top" =: (<> "px") (T.pack $ show $ keyToIndex k * rowPx) <>
118121 "position" =: "absolute" <>
119122 "width" =: "100%"
120123 findWindow sizeIncrement windowSize startingPosition =
@@ -123,7 +126,7 @@ virtualList heightPx rowPx maxIndex i0 setI keyToIndex items0 itemsUpdate itemBu
123126 in (startingIndex, numItems)
124127
125128virtualListBuffered
126− :: (DomBuilder t m, PostBuild t m, MonadHold t m, PerformEvent t m, MonadIO (Performable m), DomBuilderSpace m ~ GhcjsDomSpace, MonadFix m, Ord k)
129+ :: (DomBuilder t m, PostBuild t m, MonadHold t m, PerformEvent t m, MonadJSM (Performable m), DomBuilderSpace m ~ GhcjsDomSpace, MonadFix m, Ord k)
127130 => Int
128131 -> Dynamic t Int
129132 -> Int
@@ -139,7 +142,7 @@ virtualListBuffered buffer heightPx rowPx maxIndex i0 setI keyToIndex items0 ite
139142 (win, m) <- virtualList heightPx rowPx maxIndex i0 setI keyToIndex items0 itemsUpdate itemBuilder
140143 pb <- getPostBuild
141144 let extendWin o l = (max 0 (o - l * (buffer-1) `div` 2), l * buffer)
142− rec let winHitEdge = fmapMaybe id $ attachWith (\(oldOffset, oldLimit) (winOffset, winLimit) ->
145+ rec let winHitEdge = attachWithMaybe (\(oldOffset, oldLimit) (winOffset, winLimit) ->
143146 if winOffset > oldOffset && winOffset + winLimit < oldOffset + oldLimit
144147 then Nothing
145148 else Just (extendWin winOffset winLimit)) (current winBuffered) (updated win)
src/Reflex/Dom/Widget/Resize.hs → reflex-dom-core/src/Reflex/Dom/Widget/Resize.hsrenamed+34−22
@@ -2,16 +2,19 @@
22{-# LANGUAGE MultiParamTypeClasses #-}
33{-# LANGUAGE OverloadedStrings #-}
44{-# LANGUAGE RecursiveDo #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
56{-# LANGUAGE TypeFamilies #-}
67module Reflex.Dom.Widget.Resize where
78
8−import Reflex
9+import Reflex.Class
10+import Reflex.Time
911import Reflex.Dom.Builder.Class
1012import Reflex.Dom.Builder.Immediate
1113import Reflex.Dom.Class
12−import Reflex.Dom.PerformEvent.Class
13−import Reflex.Dom.PostBuild.Class
1414import Reflex.Dom.Widget.Basic
15+import Reflex.PerformEvent.Class
16+import Reflex.PostBuild.Class
17+import Reflex.TriggerEvent.Class
1518
1619import Control.Monad
1720import Control.Monad.Fix
@@ -21,24 +24,32 @@ import qualified Data.Map as Map
2124import Data.Monoid
2225import Data.Text (Text)
2326import qualified Data.Text as T
24−import GHCJS.DOM.Element hiding (reset)
27+import GHCJS.DOM.Element
2528import GHCJS.DOM.EventM (on)
29+import qualified GHCJS.DOM.GlobalEventHandlers as Events (scroll)
30+import GHCJS.DOM.Types (MonadJSM, liftJSM, uncheckedCastTo, HTMLElement(..))
31+import GHCJS.DOM.HTMLElement (getOffsetWidth, getOffsetHeight)
32+import qualified GHCJS.DOM.Types as DOM
2633
2734-- | A widget that wraps the given widget in a div and fires an event when resized.
28−-- Adapted from github.com/marcj/css-element-queries
29−resizeDetector :: (DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadIO (Performable m), MonadFix m) => m a -> m (Event t (), a)
35+-- Adapted from @github.com\/marcj\/css-element-queries@
36+--
37+-- This function can cause strange scrollbars to appear in some circumstances.
38+-- These can be hidden with pseudo selectors, for example, in webkit browsers:
39+-- .wrapper *::-webkit-scrollbar { width: 0px; background: transparent; }
40+resizeDetector :: (MonadJSM m, DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadJSM (Performable m), MonadFix m) => m a -> m (Event t (Maybe Double, Maybe Double), a)
3041resizeDetector = resizeDetectorWithStyle ""
3142
32−resizeDetectorWithStyle :: (DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadIO (Performable m), MonadFix m)
43+resizeDetectorWithStyle :: (MonadJSM m, DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadJSM (Performable m), MonadFix m)
3344 => Text -- ^ A css style string. Warning: It should not contain the "position" style attribute.
3445 -> m a -- ^ The embedded widget
35− -> m (Event t (), a) -- ^ An 'Event' that fires on resize, and the result of the embedded widget
46+ -> m (Event t (Maybe Double, Maybe Double), a) -- ^ An 'Event' that fires on resize, and the result of the embedded widget
3647resizeDetectorWithStyle styleString = resizeDetectorWithAttrs ("style" =: styleString)
3748
38−resizeDetectorWithAttrs :: (DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadIO (Performable m), MonadFix m)
49+resizeDetectorWithAttrs :: (MonadJSM m, DomBuilder t m, PostBuild t m, TriggerEvent t m, PerformEvent t m, MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace, MonadJSM (Performable m), MonadFix m)
3950 => Map Text Text -- ^ A map of attributes. Warning: It should not modify the "position" style attribute.
4051 -> m a -- ^ The embedded widget
41− -> m (Event t (), a) -- ^ An 'Event' that fires on resize, and the result of the embedded widget
52+ -> m (Event t (Maybe Double, Maybe Double), a) -- ^ An 'Event' that fires on resize, and the result of the embedded widget
4253resizeDetectorWithAttrs attrs w = do
4354 let childStyle = "position: absolute; left: 0; top: 0;"
4455 containerAttrs = "style" =: "position: absolute; left: 0; top: 0; right: 0; bottom: 0; overflow: scroll; z-index: -1; visibility: hidden;"
@@ -48,8 +59,9 @@ resizeDetectorWithAttrs attrs w = do
4859 (expand, (expandChild, _)) <- elAttr' "div" containerAttrs $ elAttr' "div" ("style" =: childStyle) $ return ()
4960 (shrink, _) <- elAttr' "div" containerAttrs $ elAttr "div" ("style" =: (childStyle <> "width: 200%; height: 200%;")) $ return ()
5061 return (expand, expandChild, shrink, w')
51− let reset = do
52− let e = _element_raw expand
62+ let p = uncheckedCastTo HTMLElement $ _element_raw parent
63+ reset = do
64+ let e = uncheckedCastTo HTMLElement $ _element_raw expand
5365 s = _element_raw shrink
5466 eow <- getOffsetWidth e
5567 eoh <- getOffsetHeight e
@@ -64,19 +76,19 @@ resizeDetectorWithAttrs attrs w = do
6476 setScrollLeft s ssw
6577 ssh <- getScrollHeight s
6678 setScrollTop s ssh
67− lastWidth <- getOffsetWidth (_element_raw parent)
68− lastHeight <- getOffsetHeight (_element_raw parent)
79+ lastWidth <- getOffsetWidth p
80+ lastHeight <- getOffsetHeight p
6981 return (Just lastWidth, Just lastHeight)
7082 resetIfChanged ds = do
71− pow <- getOffsetWidth (_element_raw parent)
72− poh <- getOffsetHeight (_element_raw parent)
83+ pow <- getOffsetWidth p
84+ poh <- getOffsetHeight p
7385 if ds == (Just pow, Just poh)
7486 then return Nothing
7587 else fmap Just reset
76− pb <- getPostBuild
77− expandScroll <- wrapDomEvent (_element_raw expand) (`on` scroll) $ return ()
78− shrinkScroll <- wrapDomEvent (_element_raw shrink) (`on` scroll) $ return ()
79− size0 <- performEvent $ fmap (const $ liftIO reset) pb
80− rec resize <- performEventAsync $ fmap (\d cb -> liftIO $ cb =<< resetIfChanged d) $ tag (current dimensions) $ leftmost [expandScroll, shrinkScroll]
88+ pb <- delay 0 =<< getPostBuild
89+ expandScroll <- wrapDomEvent (DOM.uncheckedCastTo DOM.HTMLElement $ _element_raw expand) (`on` Events.scroll) $ return ()
90+ shrinkScroll <- wrapDomEvent (DOM.uncheckedCastTo DOM.HTMLElement $ _element_raw shrink) (`on` Events.scroll) $ return ()
91+ size0 <- performEvent $ fmap (const $ liftJSM reset) pb
92+ rec resize <- performEventAsync $ fmap (\d cb -> (liftIO . cb) =<< liftJSM (resetIfChanged d)) $ tag (current dimensions) $ leftmost [expandScroll, shrinkScroll]
8193 dimensions <- holdDyn (Nothing, Nothing) $ leftmost [ size0, fmapMaybe id resize ]
82− return (fmapMaybe void resize, w')
94+ return (updated dimensions, w')
reflex-dom-core/src/Reflex/Dom/Xhr.hsnew file+453
@@ -0,0 +1,453 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE DeriveFunctor #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE MultiParamTypeClasses #-}
7+{-# LANGUAGE OverloadedStrings #-}
8+#ifdef USE_TEMPLATE_HASKELL
9+{-# LANGUAGE TemplateHaskell #-}
10+#endif
11+
12+-- | A module for performing asynchronous HTTP calls from JavaScript
13+-- using the
14+-- <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest XMLHttpRequest>
15+-- API (essentially AJAX). Despite the name, there is nothing whatsoever specific to XML.
16+--
17+-- The API has two components:
18+--
19+-- * convenient functions for common usecases like GET and POST
20+-- requests to APIs using JSON.
21+--
22+-- * a flexible set of functions for creating and executing arbitrary
23+-- requests and handling responses.
24+--
25+module Reflex.Dom.Xhr
26+ ( -- * Common Patterns
27+
28+ -- | Functions that conveniently expose common uses like GET and
29+ -- POST to JSON APIs.
30+ getAndDecode
31+ , getMay
32+ , postJson
33+
34+ , decodeXhrResponse
35+ , decodeText
36+
37+ -- * General Request API
38+
39+ -- | This is the most general flow for sending XHR requests:
40+ --
41+ -- 1. Create an 'Event' stream of 'XhrRequest' records (ie
42+ -- @Event t (XhrRequest a)@). The records configure the request,
43+ -- and the 'Event' controls when the request or requests are
44+ -- actually sent.
45+ --
46+ -- 2. Plug the @Event t (XhrRequest a)@ into one of the functions
47+ -- for performing requests like 'performRequestAsync'.
48+ --
49+ -- 3. Consume the resulting stream of 'XhrResponse' events,
50+ -- parsing the body of the response however appropriate. A really
51+ -- common pattern is turning the 'Event' into a 'Dynamic' with
52+ -- 'holdDyn' or a related function.
53+ --
54+ -- Here is an example of calling a search API whenever the user
55+ -- types in a text input field and printing the result on the page:
56+ --
57+ -- @
58+ -- url query = "http:\/\/example.com\/search?query=" \<> query
59+ --
60+ -- search queries = do
61+ -- responses \<- performRequestAsync $ toRequest \<$> queries
62+ -- return $ view xhrResponse_responseText \<$> responses
63+ -- where toRequest query = XhrRequest \"GET" (url query) def
64+ --
65+ -- main = mainWidget $ do
66+ -- input \<- textInput def
67+ -- let queries = updated $ input ^. textInput_value
68+ -- results \<- search queries
69+ -- asText \<- holdDyn "No results." $ pack . show \<$> results
70+ -- dynText asText
71+ -- @
72+
73+ -- ** XHR Requests
74+ , XhrRequest (..)
75+ , XhrRequestConfig (..)
76+
77+ , xhrRequest
78+ , xhrRequestConfig_headers
79+ , xhrRequestConfig_password
80+ , xhrRequestConfig_responseType
81+ , xhrRequestConfig_sendData
82+ , xhrRequestConfig_user
83+ , xhrRequestConfig_withCredentials
84+ , xhrRequestConfig_responseHeaders
85+ , xhrRequest_config
86+ , xhrRequest_method
87+ , xhrRequest_url
88+
89+ -- ** Performing Requests
90+ , performMkRequestAsync
91+ , performMkRequestsAsync
92+ , performRequestAsync
93+ , performRequestAsyncWithError
94+ , performRequestsAsync
95+ , performRequestsAsyncWithError
96+
97+ -- ** XHR Responses
98+ , XhrResponse (..)
99+ , XhrResponseBody (..)
100+ , XhrResponseHeaders (..)
101+ , XhrResponseType (..)
102+
103+ , xhrResponse_response
104+ , xhrResponse_responseText
105+ , xhrResponse_status
106+ , xhrResponse_statusText
107+ , xhrResponse_headers
108+
109+ -- *** Deprecated
110+ , xhrResponse_body
111+ , _xhrResponse_body
112+
113+ -- ** Error Handling
114+ , XhrException (..)
115+ , IsXhrPayload (..)
116+
117+ -- * JavaScript XMLHttpRequest Objects
118+
119+ -- | 'XMLHttpRequest' is the type of JavaScript's underlying runtime
120+ -- objects that represent XHR requests.
121+ --
122+ -- Chances are you shouldn't need these in day-to-day code.
123+ , XMLHttpRequest
124+
125+ -- ** Constructors
126+ , newXMLHttpRequest
127+ , newXMLHttpRequestWithError
128+
129+ -- ** Fields
130+ , xmlHttpRequestGetReadyState
131+ , xmlHttpRequestGetResponseText
132+ , xmlHttpRequestGetStatus
133+ , xmlHttpRequestGetStatusText
134+ , xmlHttpRequestNew
135+ , xmlHttpRequestOnreadystatechange
136+ , xmlHttpRequestOpen
137+ , xmlHttpRequestSetRequestHeader
138+ , xmlHttpRequestSetResponseType
139+ )
140+where
141+
142+import Reflex.Class
143+import Reflex.Dom.Class
144+import Reflex.PerformEvent.Class
145+import Reflex.TriggerEvent.Class
146+import Reflex.Dom.Xhr.Exception
147+import Reflex.Dom.Xhr.Foreign
148+import Reflex.Dom.Xhr.ResponseType
149+
150+import Control.Concurrent
151+import Control.Exception (handle)
152+import Control.Lens
153+import Control.Monad hiding (forM)
154+import Control.Monad.IO.Class
155+import Data.Aeson
156+#if MIN_VERSION_aeson(1,0,0)
157+import Data.Aeson.Text
158+#else
159+import Data.Aeson.Encode
160+#endif
161+import qualified Data.ByteString.Lazy as BL
162+import Data.CaseInsensitive (CI)
163+import qualified Data.CaseInsensitive as CI
164+import Data.Default
165+import qualified Data.List as L
166+import Data.Map (Map)
167+import qualified Data.Map as Map
168+import Data.Maybe
169+import qualified Data.Set as Set
170+import Data.Text (Text)
171+import qualified Data.Text as T
172+import Data.Text.Encoding
173+import qualified Data.Text.Lazy as LT
174+import qualified Data.Text.Lazy.Builder as B
175+import Data.Traversable
176+import Data.Typeable
177+
178+import Language.Javascript.JSaddle.Monad (JSM, askJSM, runJSM, MonadJSM, liftJSM)
179+
180+data XhrRequest a
181+ = XhrRequest { _xhrRequest_method :: Text
182+ , _xhrRequest_url :: Text
183+ , _xhrRequest_config :: XhrRequestConfig a
184+ }
185+ deriving (Show, Read, Eq, Ord, Typeable, Functor)
186+
187+data XhrRequestConfig a
188+ = XhrRequestConfig { _xhrRequestConfig_headers :: Map Text Text
189+ , _xhrRequestConfig_user :: Maybe Text
190+ , _xhrRequestConfig_password :: Maybe Text
191+ , _xhrRequestConfig_responseType :: Maybe XhrResponseType
192+ , _xhrRequestConfig_sendData :: a
193+ , _xhrRequestConfig_withCredentials :: Bool
194+ , _xhrRequestConfig_responseHeaders :: XhrResponseHeaders
195+ }
196+ deriving (Show, Read, Eq, Ord, Typeable, Functor)
197+
198+data XhrResponse
199+ = XhrResponse { _xhrResponse_status :: Word
200+ , _xhrResponse_statusText :: Text
201+ , _xhrResponse_response :: Maybe XhrResponseBody
202+ , _xhrResponse_responseText :: Maybe Text
203+ , _xhrResponse_headers :: Map (CI Text) Text
204+ }
205+ deriving (Typeable)
206+
207+data XhrResponseHeaders =
208+ OnlyHeaders (Set.Set (CI Text)) -- ^ Parse a subset of headers from the XHR Response
209+ | AllHeaders -- ^ Parse all headers from the XHR Response
210+ deriving (Show, Read, Eq, Ord, Typeable)
211+
212+instance Default XhrResponseHeaders where
213+ def = OnlyHeaders mempty
214+
215+{-# DEPRECATED _xhrResponse_body "Use _xhrResponse_response or _xhrResponse_responseText instead." #-}
216+_xhrResponse_body :: XhrResponse -> Maybe Text
217+_xhrResponse_body = _xhrResponse_responseText
218+
219+{-# DEPRECATED xhrResponse_body "Use xhrResponse_response or xhrResponse_responseText instead." #-}
220+xhrResponse_body :: Lens' XhrResponse (Maybe Text)
221+xhrResponse_body = lens _xhrResponse_responseText (\r t -> r { _xhrResponse_responseText = t })
222+
223+instance a ~ () => Default (XhrRequestConfig a) where
224+ def = XhrRequestConfig { _xhrRequestConfig_headers = Map.empty
225+ , _xhrRequestConfig_user = Nothing
226+ , _xhrRequestConfig_password = Nothing
227+ , _xhrRequestConfig_responseType = Nothing
228+ , _xhrRequestConfig_sendData = ()
229+ , _xhrRequestConfig_withCredentials = False
230+ , _xhrRequestConfig_responseHeaders = def
231+ }
232+
233+-- | Construct a request object from method, URL, and config record.
234+xhrRequest :: Text -> Text -> XhrRequestConfig a -> XhrRequest a
235+xhrRequest = XhrRequest
236+
237+-- | Make a new asyncronous XHR request. This does not block (it forks),
238+-- and returns an XHR object immediately (which you can use to abort
239+-- the XHR connection), and will pass an exception ('XhrException') to the
240+-- continuation if the connection cannot be made (or is aborted).
241+newXMLHttpRequestWithError
242+ :: (HasJSContext m, MonadJSM m, IsXhrPayload a)
243+ => XhrRequest a
244+ -- ^ The request to make.
245+ -> (Either XhrException XhrResponse -> JSM ())
246+ -- ^ A continuation to be called once a response comes back, or in
247+ -- case of error.
248+ -> m XMLHttpRequest
249+ -- ^ The XHR request, which could for example be aborted.
250+newXMLHttpRequestWithError req cb = do
251+ xhr <- xmlHttpRequestNew
252+ ctx <- askJSM
253+ void $ liftIO $ forkIO $ handle ((`runJSM` ctx) . cb . Left) $ void . (`runJSM` ctx) $ do
254+ let c = _xhrRequest_config req
255+ rt = _xhrRequestConfig_responseType c
256+ creds = _xhrRequestConfig_withCredentials c
257+ xmlHttpRequestOpen
258+ xhr
259+ (_xhrRequest_method req)
260+ (_xhrRequest_url req)
261+ True
262+ (fromMaybe "" $ _xhrRequestConfig_user c)
263+ (fromMaybe "" $ _xhrRequestConfig_password c)
264+ iforM_ (_xhrRequestConfig_headers c) $ xmlHttpRequestSetRequestHeader xhr
265+ maybe (return ()) (xmlHttpRequestSetResponseType xhr . fromResponseType) rt
266+ xmlHttpRequestSetWithCredentials xhr creds
267+ _ <- xmlHttpRequestOnreadystatechange xhr $ do
268+ readyState <- xmlHttpRequestGetReadyState xhr
269+ status <- xmlHttpRequestGetStatus xhr
270+ statusText <- xmlHttpRequestGetStatusText xhr
271+ when (readyState == 4) $ do
272+ t <- if rt == Just XhrResponseType_Text || isNothing rt
273+ then xmlHttpRequestGetResponseText xhr
274+ else return Nothing
275+ r <- xmlHttpRequestGetResponse xhr
276+ h <- case _xhrRequestConfig_responseHeaders c of
277+ AllHeaders -> parseAllHeadersString <$>
278+ xmlHttpRequestGetAllResponseHeaders xhr
279+ OnlyHeaders xs -> traverse (xmlHttpRequestGetResponseHeader xhr)
280+ (Map.fromSet CI.original xs)
281+ _ <- liftJSM $ cb $ Right
282+ XhrResponse { _xhrResponse_status = status
283+ , _xhrResponse_statusText = statusText
284+ , _xhrResponse_response = r
285+ , _xhrResponse_responseText = t
286+ , _xhrResponse_headers = h
287+ }
288+ return ()
289+ _ <- xmlHttpRequestSend xhr (_xhrRequestConfig_sendData c)
290+ return ()
291+ return xhr
292+
293+parseAllHeadersString :: Text -> Map (CI Text) Text
294+parseAllHeadersString s = Map.fromList $ fmap (stripBoth . T.span (/=':')) $
295+ L.dropWhileEnd T.null $ T.splitOn (T.pack "\r\n") s
296+ where stripBoth (txt1, txt2) = (CI.mk $ T.strip txt1, T.strip $ T.drop 1 txt2)
297+
298+newXMLHttpRequest :: (HasJSContext m, MonadJSM m, IsXhrPayload a) => XhrRequest a -> (XhrResponse -> JSM ()) -> m XMLHttpRequest
299+newXMLHttpRequest req cb = newXMLHttpRequestWithError req $ mapM_ cb
300+
301+-- | Given Event of requests, issue them when the Event fires.
302+-- Returns Event of corresponding responses.
303+--
304+-- The request is processed asynchronously, therefore handling does
305+-- not block or cause a delay while creating the connection.
306+performRequestAsyncWithError
307+ :: (MonadJSM (Performable m), HasJSContext (Performable m), PerformEvent t m, TriggerEvent t m, IsXhrPayload a)
308+ => Event t (XhrRequest a)
309+ -> m (Event t (Either XhrException XhrResponse))
310+performRequestAsyncWithError = performRequestAsync' newXMLHttpRequestWithError . fmap return
311+
312+-- | Given Event of request, issue them when the Event fires. Returns Event of corresponding response.
313+performRequestAsync :: (MonadJSM (Performable m), HasJSContext (Performable m), PerformEvent t m, TriggerEvent t m, IsXhrPayload a) => Event t (XhrRequest a) -> m (Event t XhrResponse)
314+performRequestAsync = performRequestAsync' newXMLHttpRequest . fmap return
315+
316+-- | Given Event with an action that creates a request, build and issue the request when the Event fires. Returns Event of corresponding response.
317+performMkRequestAsync :: (MonadJSM (Performable m), HasJSContext (Performable m), PerformEvent t m, TriggerEvent t m, IsXhrPayload a) => Event t (Performable m (XhrRequest a)) -> m (Event t XhrResponse)
318+performMkRequestAsync = performRequestAsync' newXMLHttpRequest
319+
320+performRequestAsync' :: (MonadJSM (Performable m), PerformEvent t m, TriggerEvent t m) => (XhrRequest p -> (a -> JSM ()) -> Performable m XMLHttpRequest) -> Event t (Performable m (XhrRequest p)) -> m (Event t a)
321+performRequestAsync' newXhr req = performEventAsync $ ffor req $ \hr cb -> do
322+ r <- hr
323+ _ <- newXhr r $ liftIO . cb
324+ return ()
325+
326+-- | Issues a collection of requests when the supplied Event fires.
327+-- When ALL requests from a given firing complete, the results are
328+-- collected and returned via the return Event.
329+--
330+-- The requests are processed asynchronously, therefore handling does
331+-- not block or cause a delay while creating the connection.
332+--
333+-- Order of request execution and completion is not guaranteed, but
334+-- order of creation and the collection result is preserved.
335+performRequestsAsyncWithError
336+ :: (MonadJSM (Performable m), HasJSContext (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f, IsXhrPayload a)
337+ => Event t (f (XhrRequest a)) -> m (Event t (f (Either XhrException XhrResponse)))
338+performRequestsAsyncWithError = performRequestsAsync' newXMLHttpRequestWithError . fmap return
339+
340+-- | Issues a collection of requests when the supplied Event fires. When ALL requests from a given firing complete, the results are collected and returned via the return Event.
341+performRequestsAsync :: (MonadJSM (Performable m), HasJSContext (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f, IsXhrPayload a) => Event t (f (XhrRequest a)) -> m (Event t (f XhrResponse))
342+performRequestsAsync = performRequestsAsync' newXMLHttpRequest . fmap return
343+
344+-- | Builds and issues a collection of requests when the supplied Event fires. When ALL requests from a given firing complete, the results are collected and returned via the return Event.
345+performMkRequestsAsync :: (MonadJSM (Performable m), HasJSContext (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f, IsXhrPayload a) => Event t (Performable m (f (XhrRequest a))) -> m (Event t (f XhrResponse))
346+performMkRequestsAsync = performRequestsAsync' newXMLHttpRequest
347+
348+performRequestsAsync' :: (MonadJSM (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f) => (XhrRequest b -> (a -> JSM ()) -> Performable m XMLHttpRequest) -> Event t (Performable m (f (XhrRequest b))) -> m (Event t (f a))
349+performRequestsAsync' newXhr req = performEventAsync $ ffor req $ \hrs cb -> do
350+ rs <- hrs
351+ resps <- forM rs $ \r -> do
352+ resp <- liftIO newEmptyMVar
353+ _ <- newXhr r $ liftIO . putMVar resp
354+ return resp
355+ _ <- liftIO $ forkIO $ cb =<< forM resps takeMVar
356+ return ()
357+
358+-- | Simplified interface to "GET" URLs and return decoded results.
359+getAndDecode :: (MonadIO m, MonadJSM (Performable m), PerformEvent t m, HasJSContext (Performable m), TriggerEvent t m, FromJSON a) => Event t Text -> m (Event t (Maybe a))
360+getAndDecode url = do
361+ r <- performRequestAsync $ fmap (\x -> XhrRequest "GET" x def) url
362+ return $ fmap decodeXhrResponse r
363+
364+-- | Create a "POST" request from an URL and thing with a JSON representation
365+postJson :: (ToJSON a) => Text -> a -> XhrRequest Text
366+postJson url a =
367+ XhrRequest "POST" url $ def { _xhrRequestConfig_headers = headerUrlEnc
368+ , _xhrRequestConfig_sendData = body
369+ }
370+ where headerUrlEnc = "Content-type" =: "application/json"
371+ body = LT.toStrict $ B.toLazyText $ encodeToTextBuilder $ toJSON a
372+
373+getMay :: (Monad m, Reflex t) => (Event t a -> m (Event t b)) -> Event t (Maybe a) -> m (Event t (Maybe b))
374+getMay f e = do
375+ e' <- f (fmapMaybe id e)
376+ return $ leftmost [fmap Just e', fmapMaybe (maybe (Just Nothing) (const Nothing)) e]
377+
378+decodeText :: FromJSON a => Text -> Maybe a
379+decodeText = decode . BL.fromStrict . encodeUtf8
380+
381+-- | Convenience function to decode JSON-encoded responses.
382+decodeXhrResponse :: FromJSON a => XhrResponse -> Maybe a
383+decodeXhrResponse = decodeText <=< _xhrResponse_responseText
384+
385+#ifdef USE_TEMPLATE_HASKELL
386+concat <$> mapM makeLenses
387+ [ ''XhrRequest
388+ , ''XhrRequestConfig
389+ , ''XhrResponse
390+ ]
391+#else
392+
393+xhrRequest_method :: Lens' (XhrRequest a) Text
394+xhrRequest_method f (XhrRequest x1 x2 x3) = (\y -> XhrRequest y x2 x3) <$> f x1
395+{-# INLINE xhrRequest_method #-}
396+
397+xhrRequest_url :: Lens' (XhrRequest a) Text
398+xhrRequest_url f (XhrRequest x1 x2 x3) = (\y -> XhrRequest x1 y x3) <$> f x2
399+{-# INLINE xhrRequest_url #-}
400+
401+xhrRequest_config :: Lens' (XhrRequest a) (XhrRequestConfig a)
402+xhrRequest_config f (XhrRequest x1 x2 x3) = (\y -> XhrRequest x1 x2 y) <$> f x3
403+{-# INLINE xhrRequest_config #-}
404+
405+xhrRequestConfig_headers :: Lens' (XhrRequestConfig a) (Map Text Text)
406+xhrRequestConfig_headers f (XhrRequestConfig x1 x2 x3 x4 x5 x6 x7) = (\y -> XhrRequestConfig y x2 x3 x4 x5 x6 x7) <$> f x1
407+{-# INLINE xhrRequestConfig_headers #-}
408+
409+xhrRequestConfig_user :: Lens' (XhrRequestConfig a) (Maybe Text)
410+xhrRequestConfig_user f (XhrRequestConfig x1 x2 x3 x4 x5 x6 x7) = (\y -> XhrRequestConfig x1 y x3 x4 x5 x6 x7) <$> f x2
411+{-# INLINE xhrRequestConfig_user #-}
412+
413+xhrRequestConfig_password :: Lens' (XhrRequestConfig a) (Maybe Text)
414+xhrRequestConfig_password f (XhrRequestConfig x1 x2 x3 x4 x5 x6 x7) = (\y -> XhrRequestConfig x1 x2 y x4 x5 x6 x7) <$> f x3
415+{-# INLINE xhrRequestConfig_password #-}
416+
417+xhrRequestConfig_responseType :: Lens' (XhrRequestConfig a) (Maybe XhrResponseType)
418+xhrRequestConfig_responseType f (XhrRequestConfig x1 x2 x3 x4 x5 x6 x7) = (\y -> XhrRequestConfig x1 x2 x3 y x5 x6 x7) <$> f x4
419+{-# INLINE xhrRequestConfig_responseType #-}
420+
421+xhrRequestConfig_sendData :: Lens (XhrRequestConfig a) (XhrRequestConfig b) a b
422+xhrRequestConfig_sendData f (XhrRequestConfig x1 x2 x3 x4 x5 x6 x7) = (\y -> XhrRequestConfig x1 x2 x3 x4 y x6 x7) <$> f x5
423+{-# INLINE xhrRequestConfig_sendData #-}
424+
425+xhrRequestConfig_withCredentials :: Lens' (XhrRequestConfig a) Bool
426+xhrRequestConfig_withCredentials f (XhrRequestConfig x1 x2 x3 x4 x5 x6 x7) = (\y -> XhrRequestConfig x1 x2 x3 x4 x5 y x7) <$> f x6
427+{-# INLINE xhrRequestConfig_withCredentials #-}
428+
429+xhrRequestConfig_responseHeaders :: Lens' (XhrRequestConfig a) XhrResponseHeaders
430+xhrRequestConfig_responseHeaders f (XhrRequestConfig x1 x2 x3 x4 x5 x6 x7) = (\y -> XhrRequestConfig x1 x2 x3 x4 x5 x6 y) <$> f x7
431+{-# INLINE xhrRequestConfig_responseHeaders #-}
432+
433+xhrResponse_status :: Lens' XhrResponse Word
434+xhrResponse_status f (XhrResponse x1 x2 x3 x4 x5) = (\y -> XhrResponse y x2 x3 x4 x5) <$> f x1
435+{-# INLINE xhrResponse_status #-}
436+
437+xhrResponse_statusText :: Lens' XhrResponse Text
438+xhrResponse_statusText f (XhrResponse x1 x2 x3 x4 x5) = (\y -> XhrResponse x1 y x3 x4 x5) <$> f x2
439+{-# INLINE xhrResponse_statusText #-}
440+
441+xhrResponse_response :: Lens' XhrResponse (Maybe XhrResponseBody)
442+xhrResponse_response f (XhrResponse x1 x2 x3 x4 x5) = (\y -> XhrResponse x1 x2 y x4 x5) <$> f x3
443+{-# INLINE xhrResponse_response #-}
444+
445+xhrResponse_responseText :: Lens' XhrResponse (Maybe Text)
446+xhrResponse_responseText f (XhrResponse x1 x2 x3 x4 x5) = (\y -> XhrResponse x1 x2 x3 y x5) <$> f x4
447+{-# INLINE xhrResponse_responseText #-}
448+
449+xhrResponse_headers :: Lens' XhrResponse (Map (CI Text) Text)
450+xhrResponse_headers f (XhrResponse x1 x2 x3 x4 x5) = (\y -> XhrResponse x1 x2 x3 x4 y) <$> f x5
451+{-# INLINE xhrResponse_headers #-}
452+
453+#endif
src/Reflex/Dom/Xhr/Exception.hs → reflex-dom-core/src/Reflex/Dom/Xhr/Exception.hsrenamed

The content is the same.

src-ghcjs/Reflex/Dom/Xhr/Foreign.hs → reflex-dom-core/src/Reflex/Dom/Xhr/Foreign.hsrenamed+62−56
@@ -1,7 +1,6 @@
11{-# LANGUAGE FlexibleInstances #-}
22{-# LANGUAGE JavaScriptFFI #-}
33{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE TypeSynonymInstances #-}
54
65module Reflex.Dom.Xhr.Foreign (
76 XMLHttpRequest
@@ -9,31 +8,30 @@ module Reflex.Dom.Xhr.Foreign (
98 , module Reflex.Dom.Xhr.Foreign
109) where
1110
12−import Control.Exception (catch, throwIO)
11+import Control.Exception (throwIO)
12+import Control.Monad.IO.Class (MonadIO(..))
1313import Data.Maybe (fromMaybe)
1414import Data.Text (Text)
15−import GHCJS.DOM
15+import Data.ByteString (ByteString)
16+import Foreign.JavaScript.Utils (bsFromMutableArrayBuffer, bsToArrayBuffer)
1617import GHCJS.DOM.Enums
17−import GHCJS.DOM.EventM (EventM, on)
18+import GHCJS.DOM.EventM (EventM, on, onSync)
1819import GHCJS.DOM.EventTarget (dispatchEvent)
19−import GHCJS.DOM.Types hiding (Text)
20+import GHCJS.DOM.Types (MonadJSM, ToJSString, FormData, Document, Blob (..), ArrayBuffer (..), JSVal, JSM, IsEvent, XMLHttpRequestProgressEvent, ProgressEvent, Event, XMLHttpRequestUpload, FromJSString, ArrayBufferView (..), liftJSM, castTo)
2021import GHCJS.DOM.XMLHttpRequest
21−import GHCJS.Types
22+import Language.Javascript.JSaddle.Helper (mutableArrayBufferFromJSVal)
23+import qualified Language.Javascript.JSaddle.Monad as JS (catch)
2224import Prelude hiding (error)
23−import Reflex.Dom.Internal.Foreign
2425import Reflex.Dom.Xhr.Exception
2526import Reflex.Dom.Xhr.ResponseType
2627
27−prepareWebView :: WebView -> IO ()
28−prepareWebView _ = return ()
29−
30−xmlHttpRequestNew :: a -> IO XMLHttpRequest
31−xmlHttpRequestNew _ = newXMLHttpRequest
28+xmlHttpRequestNew :: MonadJSM m => m XMLHttpRequest
29+xmlHttpRequestNew = newXMLHttpRequest
3230
3331xmlHttpRequestOpen ::
34− (ToJSString method, ToJSString url, ToJSString user, ToJSString password) =>
35− XMLHttpRequest -> method -> url -> Bool -> user -> password -> IO ()
36−xmlHttpRequestOpen = open
32+ (ToJSString method, ToJSString url, ToJSString user, ToJSString password, MonadJSM m) =>
33+ XMLHttpRequest -> method -> url -> Bool -> user -> password -> m ()
34+xmlHttpRequestOpen request method url async user password = open request method url async (Just user) (Just password)
3735
3836convertException :: XHRError -> XhrException
3937convertException e = case e of
@@ -41,7 +39,7 @@ convertException e = case e of
4139 XHRAborted -> XhrException_Aborted
4240
4341class IsXhrPayload a where
44− sendXhrPayload :: XMLHttpRequest -> a -> IO ()
42+ sendXhrPayload :: MonadJSM m => XMLHttpRequest -> a -> m ()
4543
4644instance IsXhrPayload () where
4745 sendXhrPayload xhr _ = send xhr
@@ -49,6 +47,9 @@ instance IsXhrPayload () where
4947instance IsXhrPayload String where
5048 sendXhrPayload = sendString
5149
50+instance IsXhrPayload Text where
51+ sendXhrPayload = sendString
52+
5253instance IsXhrPayload FormData where
5354 sendXhrPayload = sendFormData
5455
@@ -58,82 +59,88 @@ instance IsXhrPayload Document where
5859instance IsXhrPayload Blob where
5960 sendXhrPayload = sendBlob
6061
62+instance IsXhrPayload ArrayBuffer where
63+ sendXhrPayload xhr ab = sendArrayBuffer xhr (ArrayBufferView $ unArrayBuffer ab)
64+
65+instance IsXhrPayload ByteString where
66+ sendXhrPayload xhr bs = sendXhrPayload xhr =<< liftJSM (bsToArrayBuffer bs)
67+
6168newtype XhrPayload = XhrPayload { unXhrPayload :: JSVal }
6269
6370-- This used to be a non blocking call, but now it uses an interruptible ffi
64−xmlHttpRequestSend :: IsXhrPayload payload => XMLHttpRequest -> payload -> IO ()
65−xmlHttpRequestSend self p = sendXhrPayload self p `catch` (throwIO . convertException)
71+xmlHttpRequestSend :: IsXhrPayload payload => XMLHttpRequest -> payload -> JSM ()
72+xmlHttpRequestSend self p = sendXhrPayload self p `JS.catch` (liftIO . throwIO . convertException)
6673
6774
68−xmlHttpRequestSetRequestHeader :: (ToJSString header, ToJSString value)
69− => XMLHttpRequest -> header -> value -> IO ()
75+xmlHttpRequestSetRequestHeader :: (ToJSString header, ToJSString value, MonadJSM m)
76+ => XMLHttpRequest -> header -> value -> m ()
7077xmlHttpRequestSetRequestHeader = setRequestHeader
7178
72−xmlHttpRequestAbort :: XMLHttpRequest -> IO ()
79+xmlHttpRequestAbort :: MonadJSM m => XMLHttpRequest -> m ()
7380xmlHttpRequestAbort = abort
7481
75−xmlHttpRequestGetAllResponseHeaders :: XMLHttpRequest -> IO Text
76−xmlHttpRequestGetAllResponseHeaders self = fromMaybe "" <$> getAllResponseHeaders self
82+xmlHttpRequestGetAllResponseHeaders :: MonadJSM m => XMLHttpRequest -> m Text
83+xmlHttpRequestGetAllResponseHeaders = getAllResponseHeaders
7784
78−xmlHttpRequestGetResponseHeader :: (ToJSString header)
79− => XMLHttpRequest -> header -> IO Text
85+xmlHttpRequestGetResponseHeader :: (ToJSString header, MonadJSM m)
86+ => XMLHttpRequest -> header -> m Text
8087xmlHttpRequestGetResponseHeader self header = fromMaybe "" <$> getResponseHeader self header
8188
82−xmlHttpRequestOverrideMimeType :: ToJSString override => XMLHttpRequest -> override -> IO ()
89+xmlHttpRequestOverrideMimeType :: (ToJSString override, MonadJSM m) => XMLHttpRequest -> override -> m ()
8390xmlHttpRequestOverrideMimeType = overrideMimeType
8491
85−xmlHttpRequestDispatchEvent :: IsEvent evt => XMLHttpRequest -> Maybe evt -> IO Bool
92+xmlHttpRequestDispatchEvent :: (IsEvent evt, MonadJSM m) => XMLHttpRequest -> evt -> m Bool
8693xmlHttpRequestDispatchEvent = dispatchEvent
8794
88−xmlHttpRequestOnabort :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
95+xmlHttpRequestOnabort :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ())
8996xmlHttpRequestOnabort = (`on` abortEvent)
9097
91−xmlHttpRequestOnerror :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
98+xmlHttpRequestOnerror :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ())
9299xmlHttpRequestOnerror = (`on` error)
93100
94−xmlHttpRequestOnload :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
101+xmlHttpRequestOnload :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ())
95102xmlHttpRequestOnload = (`on` load)
96103
97−xmlHttpRequestOnloadend :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> IO (IO ())
104+xmlHttpRequestOnloadend :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> JSM (JSM ())
98105xmlHttpRequestOnloadend = (`on` loadEnd)
99106
100−xmlHttpRequestOnloadstart :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> IO (IO ())
107+xmlHttpRequestOnloadstart :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> JSM (JSM ())
101108xmlHttpRequestOnloadstart = (`on` loadStart)
102109
103−xmlHttpRequestOnprogress :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> IO (IO ())
110+xmlHttpRequestOnprogress :: XMLHttpRequest -> EventM XMLHttpRequest XMLHttpRequestProgressEvent () -> JSM (JSM ())
104111xmlHttpRequestOnprogress = (`on` progress)
105112
106−xmlHttpRequestOntimeout :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> IO (IO ())
113+xmlHttpRequestOntimeout :: XMLHttpRequest -> EventM XMLHttpRequest ProgressEvent () -> JSM (JSM ())
107114xmlHttpRequestOntimeout = (`on` timeout)
108115
109−xmlHttpRequestOnreadystatechange :: XMLHttpRequest -> EventM XMLHttpRequest Event () -> IO (IO ())
110−xmlHttpRequestOnreadystatechange = (`on` readyStateChange)
116+xmlHttpRequestOnreadystatechange :: XMLHttpRequest -> EventM XMLHttpRequest Event () -> JSM (JSM ())
117+xmlHttpRequestOnreadystatechange = (`onSync` readyStateChange)
111118
112−xmlHttpRequestSetTimeout :: XMLHttpRequest -> Word -> IO ()
119+xmlHttpRequestSetTimeout :: MonadJSM m => XMLHttpRequest -> Word -> m ()
113120xmlHttpRequestSetTimeout = setTimeout
114121
115−xmlHttpRequestGetTimeout :: XMLHttpRequest -> IO Word
122+xmlHttpRequestGetTimeout :: MonadJSM m => XMLHttpRequest -> m Word
116123xmlHttpRequestGetTimeout = getTimeout
117124
118−xmlHttpRequestGetReadyState :: XMLHttpRequest -> IO Word
125+xmlHttpRequestGetReadyState :: MonadJSM m => XMLHttpRequest -> m Word
119126xmlHttpRequestGetReadyState = getReadyState
120127
121−xmlHttpRequestSetWithCredentials :: XMLHttpRequest -> Bool -> IO ()
128+xmlHttpRequestSetWithCredentials :: MonadJSM m => XMLHttpRequest -> Bool -> m ()
122129xmlHttpRequestSetWithCredentials = setWithCredentials
123130
124−xmlHttpRequestGetWithCredentials :: XMLHttpRequest -> IO Bool
131+xmlHttpRequestGetWithCredentials :: MonadJSM m => XMLHttpRequest -> m Bool
125132xmlHttpRequestGetWithCredentials = getWithCredentials
126133
127−xmlHttpRequestGetUpload :: XMLHttpRequest -> IO (Maybe XMLHttpRequestUpload)
128−xmlHttpRequestGetUpload = getUpload
134+xmlHttpRequestGetUpload :: MonadJSM m => XMLHttpRequest -> m (Maybe XMLHttpRequestUpload)
135+xmlHttpRequestGetUpload = fmap Just . getUpload
129136
130−xmlHttpRequestGetResponseText :: FromJSString result => XMLHttpRequest -> IO (Maybe result)
137+xmlHttpRequestGetResponseText :: (FromJSString result, MonadJSM m) => XMLHttpRequest -> m (Maybe result)
131138xmlHttpRequestGetResponseText = getResponseText
132139
133−xmlHttpRequestGetResponseXML :: XMLHttpRequest -> IO (Maybe Document)
140+xmlHttpRequestGetResponseXML :: MonadJSM m => XMLHttpRequest -> m (Maybe Document)
134141xmlHttpRequestGetResponseXML = getResponseXML
135142
136−xmlHttpRequestSetResponseType :: XMLHttpRequest -> XMLHttpRequestResponseType -> IO ()
143+xmlHttpRequestSetResponseType :: MonadJSM m => XMLHttpRequest -> XMLHttpRequestResponseType -> m ()
137144xmlHttpRequestSetResponseType = setResponseType
138145
139146fromResponseType :: XhrResponseType -> XMLHttpRequestResponseType
@@ -149,28 +156,27 @@ toResponseType XMLHttpRequestResponseTypeBlob = Just XhrResponseType_Blob
149156toResponseType XMLHttpRequestResponseTypeText = Just XhrResponseType_Text
150157toResponseType _ = Nothing
151158
152−xmlHttpRequestGetResponseType :: XMLHttpRequest -> IO (Maybe XhrResponseType)
159+xmlHttpRequestGetResponseType :: MonadJSM m => XMLHttpRequest -> m (Maybe XhrResponseType)
153160xmlHttpRequestGetResponseType = fmap toResponseType . getResponseType
154161
155−xmlHttpRequestGetStatus :: XMLHttpRequest -> IO Word
162+xmlHttpRequestGetStatus :: MonadJSM m => XMLHttpRequest -> m Word
156163xmlHttpRequestGetStatus = getStatus
157164
158−xmlHttpRequestGetStatusText :: FromJSString result => XMLHttpRequest -> IO result
165+xmlHttpRequestGetStatusText :: MonadJSM m => FromJSString result => XMLHttpRequest -> m result
159166xmlHttpRequestGetStatusText = getStatusText
160167
161−xmlHttpRequestGetResponseURL :: FromJSString result => XMLHttpRequest -> IO result
168+xmlHttpRequestGetResponseURL :: (FromJSString result, MonadJSM m) => XMLHttpRequest -> m result
162169xmlHttpRequestGetResponseURL = getResponseURL
163170
164−xmlHttpRequestGetResponse :: XMLHttpRequest -> IO (Maybe XhrResponseBody)
171+xmlHttpRequestGetResponse :: MonadJSM m => XMLHttpRequest -> m (Maybe XhrResponseBody)
165172xmlHttpRequestGetResponse xhr = do
166173 mr <- getResponse xhr
167174 rt <- xmlHttpRequestGetResponseType xhr
168175 case rt of
169− Just XhrResponseType_Blob -> return $ XhrResponseBody_Blob . castToBlob <$> mr
176+ Just XhrResponseType_Blob -> fmap XhrResponseBody_Blob <$> castTo Blob mr
170177 Just XhrResponseType_Text -> Just . XhrResponseBody_Text <$> xmlHttpRequestGetStatusText xhr
171178 Just XhrResponseType_Default -> Just . XhrResponseBody_Text <$> xmlHttpRequestGetStatusText xhr
172− Just XhrResponseType_ArrayBuffer -> case fmap unGObject mr of
173− Nothing -> return Nothing
174− Just ptr -> Just . XhrResponseBody_ArrayBuffer <$> bsFromArrayBuffer ptr ptr
179+ Just XhrResponseType_ArrayBuffer -> do
180+ ab <- liftJSM $ mutableArrayBufferFromJSVal mr
181+ Just . XhrResponseBody_ArrayBuffer <$> bsFromMutableArrayBuffer ab
175182 _ -> return Nothing
176−
reflex-dom-core/src/Reflex/Dom/Xhr/FormData.hsnew file+47
@@ -0,0 +1,47 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Reflex.Dom.Xhr.FormData
4+ ( postForms
5+ , FormValue (..)
6+ , fileToFormValue
7+ )
8+ where
9+
10+import Control.Lens
11+import Data.Default
12+import Data.Map (Map)
13+import Data.Text (Text)
14+import Data.Traversable
15+import qualified GHCJS.DOM.FormData as FD
16+import Foreign.JavaScript.TH
17+import GHCJS.DOM.File (getName)
18+import GHCJS.DOM.Types (File, IsBlob)
19+import Language.Javascript.JSaddle.Monad (MonadJSM, liftJSM)
20+import Reflex
21+import Reflex.Dom.Xhr
22+
23+-- | A FormData value may be a blob/file or a string. The file can optionally be provided with filename.
24+data FormValue blob = FormValue_Text Text
25+ | FormValue_File blob (Maybe Text) -- maybe filename
26+
27+-- | Performs a POST request with the provided FormData payload
28+postForms
29+ :: ( IsBlob blob, HasJSContext (Performable m), MonadJSM (Performable m)
30+ , PerformEvent t m, TriggerEvent t m
31+ , Traversable f)
32+ => Text -- ^ The target url
33+ -> Event t (f (Map Text (FormValue blob))) -- ^ Maps of text keys and values that will be sent as "FormData"
34+ -> m (Event t (f XhrResponse))
35+postForms url payload = do
36+ performMkRequestsAsync $ ffor payload $ \fs -> for fs $ \u -> liftJSM $ do
37+ fd <- FD.newFormData Nothing
38+ iforM_ u $ \k v -> case v of
39+ FormValue_Text t -> FD.append fd k t
40+ FormValue_File b fn -> FD.appendBlob fd k b fn
41+ return $ xhrRequest "POST" url $ def & xhrRequestConfig_sendData .~ fd
42+
43+-- | Converts a File (e.g., the output of a 'FileInput') into a 'FormValue'. The filename will be included if it is available.
44+fileToFormValue :: MonadJSM m => File -> m (FormValue File)
45+fileToFormValue f = do
46+ fn <- getName f
47+ return $ FormValue_File f $ Just fn
reflex-dom-core/src/Reflex/Dom/Xhr/ResponseType.hsnew file+21
@@ -0,0 +1,21 @@
1+{-# LANGUAGE DeriveDataTypeable #-}
2+
3+module Reflex.Dom.Xhr.ResponseType where
4+
5+import Data.ByteString (ByteString)
6+import Data.Text (Text)
7+import Data.Typeable
8+import GHCJS.DOM.Blob (Blob)
9+
10+data XhrResponseType
11+ = XhrResponseType_Default
12+ | XhrResponseType_ArrayBuffer
13+ | XhrResponseType_Blob
14+ | XhrResponseType_Text
15+ deriving (Show, Read, Eq, Ord, Typeable)
16+
17+data XhrResponseBody
18+ = XhrResponseBody_Default Text
19+ | XhrResponseBody_Text Text
20+ | XhrResponseBody_Blob Blob
21+ | XhrResponseBody_ArrayBuffer ByteString
test/BrokenHaltSpec.hs → reflex-dom-core/test/BrokenHaltSpec.hsrenamed

The content is the same.

test/HaltSpec.hs → reflex-dom-core/test/HaltSpec.hsrenamed

The content is the same.

reflex-dom-core/test/gc.hsnew file+98
@@ -0,0 +1,98 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE RecursiveDo #-}
5+{-# LANGUAGE ScopedTypeVariables #-}
6+import Control.Concurrent
7+import Control.Exception
8+import Control.Monad
9+import Control.Monad.IO.Class
10+import Data.Int
11+import Data.Text as T
12+import Language.Javascript.JSaddle.Warp
13+import Reflex.Dom.Core
14+import Reflex.Time
15+import System.Exit
16+import System.Mem
17+import System.Process
18+
19+import Test.Util.ChromeFlags
20+import Test.Util.UnshareNetwork
21+
22+#if MIN_VERSION_base(4,11,0)
23+import GHC.Stats (getRTSStatsEnabled, getRTSStats, RTSStats(..), gcdetails_live_bytes, gc)
24+currentBytesUsed :: RTSStats -> Int64
25+currentBytesUsed = fromIntegral . gcdetails_live_bytes . gc
26+#else
27+import GHC.Stats (getGCStats, GCStats(..))
28+getRTSStats = getGCStats
29+#endif
30+
31+-- In initial testing, the minimum live bytes count was 233128 and maximum was
32+-- 363712. Going over the maximum means the test has actually failed - we
33+-- probably have a memory leak; going under the minimum doesn't indicate a
34+-- memory leak, but may mean the test needs to be updated.
35+minBytesAllowed, resetThreshold, maxBytesAllowed :: Int64
36+(minBytesAllowed, resetThreshold, maxBytesAllowed) = (200000, 400000, 600000)
37+
38+-- Some times the memory usage might flair up and then then return to normal
39+-- this probably indicates an issue, but if you are trying to fix a slow consistent
40+-- leak it can confuse the results by making the tests fail when the slow leak is
41+-- fixed.
42+-- Set this limit to say how many failures (currentBytesUsed > maxBytesAllowed)
43+-- want to ignore. If the memory usage goes back under resetThreshold
44+-- the failure count is reset to 0.
45+failureLimit :: Int
46+failureLimit = 0
47+
48+main :: IO ()
49+main = do
50+ handle (\(_ :: IOError) -> return ()) $ unshareNetwork -- If we run into an exception with sandboxing, just don't bother
51+ withSandboxedChromeFlags True $ \chromeFlags -> do
52+ mainThread <- myThreadId
53+ browserProcess <- spawnCommand $ mconcat
54+ [ "echo 'Starting Chromium' ; chromium "
55+ , unpack $ T.unwords chromeFlags
56+ , " http://localhost:3911 ; echo 'Chromium exited'"
57+ ]
58+ let finishTest result = do
59+ interruptProcessGroupOf browserProcess
60+ throwTo mainThread result
61+ putStrLn "About to start the server"
62+ run 3911 $ do
63+ -- enableLogging True
64+ liftIO $ putStrLn "Running..."
65+ mainWidget $ do
66+ let w = do
67+ rec let modifyAttrs = flip pushAlways (updated d) $ \_ -> sample $ current d
68+ (e, _) <- element "button" (def & modifyAttributes .~ modifyAttrs) blank
69+ d <- holdDyn mempty $ mempty <$ domEvent Click e
70+ return ()
71+ postBuild <- getPostBuild
72+ let f (!failures, !n) = liftIO $ if n < 3000
73+ then do performMajorGC
74+ threadDelay 5000 -- Wait a bit to allow requestAnimationFrame to call its callback sometimes; this value was experimentally determined
75+ gcStats <- getRTSStats
76+ print $ currentBytesUsed gcStats
77+ when (currentBytesUsed gcStats < minBytesAllowed) $ do
78+ putStrLn "FAILED: currentBytesUsed < minBytesAllowed"
79+ finishTest $ ExitFailure 2
80+ let overMax = currentBytesUsed gcStats > maxBytesAllowed
81+ underReset = currentBytesUsed gcStats < resetThreshold
82+ when (overMax && failures >= failureLimit) $ do
83+ putStrLn "FAILED: currentBytesUsed > maxBytesAllowed"
84+ finishTest $ ExitFailure 1
85+ return $ Just (
86+ if overMax
87+ then succ failures
88+ else (if underReset then 0 else failures), succ n)
89+ else do putStrLn "SUCCEEDED"
90+ finishTest ExitSuccess
91+ return Nothing
92+ rec redraw <- performEvent <=< delay 0 $ f <$> leftmost
93+ [ (0 :: Int, 0 :: Int) <$ postBuild
94+ , fmapMaybe id redraw
95+ ]
96+ _ <- widgetHold w $ w <$ redraw
97+ return ()
98+ liftIO $ forever $ threadDelay 1000000000
reflex-dom-core/test/hlint.hsnew file+26
@@ -0,0 +1,26 @@
1+import Language.Haskell.HLint (hlint)
2+import System.Exit (exitFailure, exitSuccess)
3+
4+main :: IO ()
5+main = do
6+ ideas <- hlint
7+ [ "."
8+ , "--ignore=Redundant do"
9+ , "--ignore=Use camelCase"
10+ , "--ignore=Redundant $"
11+ , "--ignore=Use &&"
12+ , "--ignore=Use &&&"
13+ , "--ignore=Use const"
14+ , "--ignore=Use >=>"
15+ , "--ignore=Use ."
16+ , "--ignore=Use unless"
17+ , "--ignore=Use if"
18+ , "--ignore=Use fewer imports"
19+ , "--ignore=Use list comprehension"
20+ , "--ignore=Unnecessary hiding" -- Interferes with cross-version compatibility
21+ , "--ignore=Use <$>"
22+ , "--ignore=Reduce duplication" --TODO: Re-enable this test
23+ , "--ignore=Use list comprehension"
24+ , "--cpp-define=USE_TEMPLATE_HASKELL"
25+ ]
26+ if null ideas then exitSuccess else exitFailure
reflex-dom-core/test/hydration.hsnew file+1828
@@ -0,0 +1,1828 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE GADTs #-}
6+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7+{-# LANGUAGE LambdaCase #-}
8+{-# LANGUAGE MultiParamTypeClasses #-}
9+{-# LANGUAGE OverloadedStrings #-}
10+{-# LANGUAGE PolyKinds #-}
11+{-# LANGUAGE RankNTypes #-}
12+{-# LANGUAGE RecursiveDo #-}
13+{-# LANGUAGE ScopedTypeVariables #-}
14+{-# LANGUAGE StandaloneDeriving #-}
15+{-# LANGUAGE TemplateHaskell #-}
16+{-# LANGUAGE TupleSections #-}
17+{-# LANGUAGE TypeApplications #-}
18+{-# LANGUAGE TypeFamilies #-}
19+{-# LANGUAGE UndecidableInstances #-}
20+
21+{-# OPTIONS_GHC -fno-warn-orphans #-}
22+
23+-- Notice to those working on this test suite:
24+-- It doesn't appear to be possible to use --match to run a particular test, in
25+-- this situation the test may hang before reaching our code. This seems to
26+-- happen when the test is not the first test in the block. As a workaround, you
27+-- can just comment out the other tests. Also, using `xit` will cause the same
28+-- issue. `xit` tests must be the last tests in the session, or the session will
29+-- hang in the following test.
30+
31+import Prelude hiding (fail)
32+import Control.Concurrent
33+import qualified Control.Concurrent.Async as Async
34+import Control.Lens.Operators
35+import Control.Monad hiding (fail)
36+import Control.Monad.Catch
37+import Control.Monad.Fail
38+import Control.Monad.Fix
39+import Control.Monad.IO.Class
40+import Control.Monad.Ref
41+import Data.Constraint.Extras
42+import Data.Constraint.Extras.TH
43+import Data.Dependent.Map (DMap)
44+import Data.Dependent.Sum (DSum(..), (==>))
45+import Data.Functor.Identity
46+import Data.Functor.Misc
47+import Data.GADT.Compare.TH
48+import Data.GADT.Show.TH
49+import Data.IORef (IORef)
50+import Data.List (sort)
51+import Data.Maybe
52+import Data.Proxy
53+import Data.Text (Text)
54+import Language.Javascript.JSaddle (syncPoint, liftJSM)
55+import Language.Javascript.JSaddle.Warp
56+import Network.HTTP.Types (status200)
57+import Network.Socket
58+import Network.Wai
59+import Network.WebSockets
60+import Reflex.Dom.Core
61+import Reflex.Dom.Widget.Input (dropdown)
62+import Reflex.Patch.DMapWithMove
63+import System.Directory
64+import System.Environment
65+import System.IO (stderr)
66+import System.IO.Silently
67+import System.IO.Temp
68+import System.Process
69+import System.Which (staticWhich)
70+import qualified Test.HUnit as HUnit
71+import qualified Test.Hspec as H
72+import qualified Test.Hspec.Core.Spec as H
73+import Test.Hspec (xit)
74+import Test.Hspec.WebDriver hiding (runWD, click, uploadFile, WD)
75+import qualified Test.Hspec.WebDriver as WD
76+import Test.WebDriver (WD(..))
77+
78+import qualified Data.ByteString.Lazy as LBS
79+import qualified Data.Dependent.Map as DMap
80+import qualified Data.IntMap as IntMap
81+import qualified Data.Text as T
82+import qualified Data.Text.Encoding as TE
83+import qualified GHCJS.DOM.File as File
84+import qualified Network.Wai.Handler.Warp as Warp
85+import qualified System.FilePath as FilePath
86+import qualified Test.WebDriver as WD
87+import qualified Test.WebDriver.Capabilities as WD
88+
89+import Test.Util.ChromeFlags
90+import Test.Util.UnshareNetwork
91+
92+-- ORPHAN: https://github.com/kallisti-dev/hs-webdriver/pull/167
93+deriving instance MonadMask WD
94+
95+chromium :: FilePath
96+chromium = $(staticWhich "chromium")
97+
98+seleniumPort, jsaddlePort :: PortNumber
99+seleniumPort = 8000
100+jsaddlePort = 8001
101+
102+-- TODO Remove orphan
103+instance MonadRef WD where
104+ type Ref WD = Ref IO
105+ newRef = WD . newRef
106+ readRef = WD . readRef
107+ writeRef r = WD . writeRef r
108+
109+assertEqual :: (MonadIO m, Eq a, Show a) => String -> a -> a -> m ()
110+assertEqual msg a b = liftIO $ HUnit.assertEqual msg a b
111+
112+assertFailure :: MonadIO m => String -> m ()
113+assertFailure = liftIO . HUnit.assertFailure
114+
115+assertBool :: (MonadIO m) => String -> Bool -> m ()
116+assertBool msg bool = liftIO $ HUnit.assertBool msg bool
117+
118+chromeConfig :: Text -> [Text] -> WD.WDConfig
119+chromeConfig fp flags = WD.useBrowser (WD.chrome { WD.chromeBinary = Just $ T.unpack fp, WD.chromeOptions = T.unpack <$> flags }) WD.defaultConfig
120+
121+keyMap :: DMap DKey Identity
122+keyMap = DMap.fromList
123+ [ Key_Int ==> 0
124+ , Key_Char ==> 'A'
125+ ]
126+
127+data DKey a where
128+ Key_Int :: DKey Int
129+ Key_Char :: DKey Char
130+ Key_Bool :: DKey Bool
131+
132+
133+textKey :: DKey a -> Text
134+textKey = \case
135+ Key_Int -> "Key_Int"
136+ Key_Char -> "Key_Char"
137+ Key_Bool -> "Key_Bool"
138+
139+deriveArgDict ''DKey
140+deriveGEq ''DKey
141+deriveGCompare ''DKey
142+deriveGShow ''DKey
143+
144+deriving instance MonadFail WD
145+
146+main :: IO ()
147+main = do
148+ unshareNetwork
149+ isHeadless <- (== Nothing) <$> lookupEnv "NO_HEADLESS"
150+ withSandboxedChromeFlags isHeadless $ \chromeFlags -> do
151+ withSeleniumServer $ \selenium -> do
152+ let browserPath = T.strip $ T.pack chromium
153+ when (T.null browserPath) $ fail "No browser found"
154+ withDebugging <- isNothing <$> lookupEnv "NO_DEBUG"
155+ let wdConfig = WD.defaultConfig { WD.wdPort = fromIntegral $ _selenium_portNumber selenium }
156+ chromeCaps' = WD.getCaps $ chromeConfig browserPath chromeFlags
157+ hspec (tests withDebugging wdConfig [(chromeCaps', "chrome")] selenium) `finally` _selenium_stopServer selenium
158+
159+tests :: Bool -> WD.WDConfig -> [(Capabilities, String)] -> Selenium -> Spec
160+tests withDebugging wdConfig caps _selenium = do
161+ let putStrLnDebug :: MonadIO m => Text -> m ()
162+ putStrLnDebug m = when withDebugging $ liftIO $ putStrLn $ T.unpack m
163+ session' t = sessionWith wdConfig t . using caps
164+ runWD m = runWDOptions (WdOptions False) $ do
165+ putStrLnDebug "before"
166+ r <- m
167+ putStrLnDebug "after"
168+ return r
169+ testWidgetStatic :: WD b -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ()) -> WD b
170+ testWidgetStatic = testWidgetStaticDebug withDebugging
171+ testWidget :: WD () -> WD b -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ()) -> WD b
172+ testWidget = testWidgetDebug True withDebugging
173+ testWidget' :: WD a -> (a -> WD b) -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ()) -> WD b
174+ testWidget' = testWidgetDebug' True withDebugging
175+ session' "text" $ do
176+ it "works" $ runWD $ do
177+ testWidgetStatic (checkBodyText "hello world") $ do
178+ text "hello world"
179+ it "works with postBuild" $ runWD $ do
180+ testWidgetStatic (checkBodyText "pb") $ do
181+ pb <- getPostBuild
182+ void $ textNode $ TextNodeConfig "" $ Just $ "pb" <$ pb
183+ it "works for adjacent text nodes" $ runWD $ do
184+ testWidgetStatic (checkBodyText "hello world") $ do
185+ text "hello "
186+ text "world"
187+ it "works for empty adjacent text nodes" $ runWD $ do
188+ testWidgetStatic (checkBodyText "hello world") $ do
189+ pb <- getPostBuild
190+ text ""
191+ text ""
192+ _ <- textNode $ TextNodeConfig "" $ Just $ "hello " <$ pb
193+ _ <- textNode $ TextNodeConfig "abc" $ Just $ "" <$ pb
194+ _ <- textNode $ TextNodeConfig "" $ Just $ "world" <$ pb
195+ text ""
196+ it "works when empty text nodes are the only children of an element" $ runWD $ do
197+ testWidgetStatic (checkBodyText "hello world") $ do
198+ el "div" $ do
199+ text ""
200+ text ""
201+ text "hello world"
202+ it "works when an empty text node is the first child before text" $ runWD $ do
203+ testWidgetStatic (checkTextInTag "div" "hello world") $ do
204+ el "div" $ do
205+ text ""
206+ text "hello world"
207+ it "works when an empty text node is the first child before element" $ runWD $ do
208+ testWidgetStatic (checkTextInTag "div" "hello world") $ do
209+ el "div" $ do
210+ text ""
211+ el "span" $ text "hello world"
212+ it "works when an empty text node is the last child" $ runWD $ do
213+ testWidgetStatic (checkTextInTag "div" "hello world") $ do
214+ el "div" $ do
215+ el "span" $ text "hello world"
216+ text ""
217+-- TODO I think these two tests are broken
218+-- it "updates after postBuild" $ runWD $ do
219+-- testWidget (checkBodyText "initial") (checkBodyText "after") $ do
220+-- after <- delay 0 =<< getPostBuild
221+-- void $ textNode $ TextNodeConfig "initial" $ Just $ "after" <$ after
222+-- it "updates immediately after postBuild" $ runWD $ do
223+-- testWidget (checkBodyText "pb") (checkBodyText "after") $ do
224+-- pb <- getPostBuild
225+-- after <- delay 0 pb
226+-- void $ textNode $ TextNodeConfig "initial" $ Just $ leftmost ["pb" <$ pb, "after" <$ after]
227+ it "updates in immediate mode" $ runWD $ do
228+ let checkUpdated = do
229+ checkBodyText "initial"
230+ WD.click =<< findElemWithRetry (WD.ByTag "button")
231+ checkBodyText "after"
232+ testWidget (pure ()) checkUpdated $ prerender_ (pure ()) $ do
233+ click <- button ""
234+ void $ textNode $ TextNodeConfig "initial" $ Just $ "after" <$ click
235+
236+ session' "element" $ do
237+ it "works with domEvent Click" $ runWD $ do
238+ clickedRef <- liftIO $ newRef False
239+ testWidget' (findElemWithRetry $ WD.ByTag "div") WD.click $ do
240+ (e, _) <- el' "div" $ text "hello world"
241+ performEvent_ $ liftIO (writeRef clickedRef True) <$ domEvent Click e
242+ readRef clickedRef `shouldBeWithRetryM` True
243+ it "works with eventFlags stopPropagation" $ runWD $ do
244+ firstClickedRef <- newRef False
245+ secondClickedRef <- newRef False
246+ let clickBoth = do
247+ findElemWithRetry (WD.ById "first") >>= WD.click
248+ findElemWithRetry (WD.ById "second") >>= WD.click
249+ testWidget (pure ()) clickBoth $ do
250+ (firstDivEl, _) <- el' "div" $ prerender_ (pure ()) $ do
251+ void $ elAttr "span" ("id" =: "first") $ text "hello world"
252+ performEvent_ $ liftIO (writeRef firstClickedRef True) <$ domEvent Click firstDivEl
253+ (secondDivEl, _) <- el' "div" $ prerender_ (pure ()) $ do
254+ let conf :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace
255+ conf = (def :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace)
256+ & initialAttributes .~ "id" =: "second"
257+ & elementConfig_eventSpec .~ addEventSpecFlags (Proxy :: Proxy GhcjsDomSpace) Click (\_ -> stopPropagation) def
258+ void $ element "span" conf $ text "hello world"
259+ performEvent_ $ liftIO (writeRef secondClickedRef True) <$ domEvent Click secondDivEl
260+ firstClicked <- readRef firstClickedRef
261+ secondClicked <- readRef secondClickedRef
262+ assertEqual "Click propagated when it should have stopped" (True, False) (firstClicked, secondClicked)
263+ it "works with eventFlags preventDefault" $ runWD $ do
264+ let click = do
265+ e <- findElemWithRetry $ WD.ByTag "input"
266+ s0 <- WD.isSelected e
267+ WD.click e
268+ s1 <- WD.isSelected e
269+ pure (s0, s1)
270+ clicked <- testWidget (pure ()) click $ prerender_ (pure ()) $ do
271+ let conf :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace
272+ conf = (def :: ElementConfig EventResult (SpiderTimeline Global) GhcjsDomSpace)
273+ & elementConfig_eventSpec .~ addEventSpecFlags (Proxy :: Proxy GhcjsDomSpace) Click (\_ -> preventDefault) def
274+ & initialAttributes .~ "type" =: "checkbox"
275+ void $ element "input" conf $ text "hello world"
276+ assertEqual "Click not prevented" (False, False) clicked
277+ it "can add/update/remove attributes" $ runWD $ do
278+ let checkInitialAttrs = do
279+ e <- findElemWithRetry $ WD.ByTag "div"
280+ assertAttr e "const" (Just "const")
281+ assertAttr e "delete" (Just "delete")
282+ assertAttr e "init" (Just "init")
283+ assertAttr e "click" Nothing
284+ pure e
285+ checkModifyAttrs e = do
286+ WD.click e
287+ withRetry $ do
288+ assertAttr e "const" (Just "const")
289+ assertAttr e "delete" Nothing
290+ assertAttr e "init" (Just "click")
291+ assertAttr e "click" (Just "click")
292+ testWidget' checkInitialAttrs checkModifyAttrs $ mdo
293+ let conf = def
294+ & initialAttributes .~ "const" =: "const" <> "delete" =: "delete" <> "init" =: "init"
295+ & modifyAttributes .~ (("delete" =: Nothing <> "init" =: Just "click" <> "click" =: Just "click") <$ click)
296+ (e, ()) <- element "div" conf $ text "hello world"
297+ let click = domEvent Click e
298+ return ()
299+
300+ session' "inputElement" $ do
301+ describe "static renderer" $ do
302+ it "sets value attribute" $ runWD $ do
303+ let checkStatic = do
304+ e <- findElemWithRetry $ WD.ByTag "input"
305+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
306+ pure e
307+ checkHydrated e = do
308+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
309+ testWidget' checkStatic checkHydrated $ void $ inputElement $ def
310+ & inputElementConfig_initialValue .~ "test"
311+ it "updates value attribute at postBuild" $ runWD $ do
312+ let checkStatic = do
313+ e <- findElemWithRetry $ WD.ByTag "input"
314+ WD.attr e "value" `shouldBeWithRetryM` Just "test-updated"
315+ pure e
316+ checkHydrated e = do
317+ WD.attr e "value" `shouldBeWithRetryM` Just "test-updated"
318+ testWidget' checkStatic checkHydrated $ do
319+ pb <- getPostBuild
320+ _ <- inputElement $ def
321+ & inputElementConfig_initialValue .~ "test"
322+ & inputElementConfig_setValue .~ ("test-updated" <$ pb)
323+ pure ()
324+ it "sets checked attr appropriately" $ runWD $ do
325+ setCheckedChan <- liftIO newChan
326+ let checkStatic = do
327+ e <- findElemWithRetry $ WD.ByTag "input"
328+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
329+ pure e
330+ checkValue e = do
331+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
332+ WD.moveToCenter e
333+ WD.click e -- Click to uncheck
334+ WD.attr e "checked" `shouldBeWithRetryM` Nothing
335+ liftIO $ writeChan setCheckedChan True -- Programatically check the checkbox
336+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
337+ testWidget' checkStatic checkValue $ do
338+ setChecked <- triggerEventWithChan setCheckedChan
339+ _ <- inputElement $ def
340+ & initialAttributes .~ "type" =: "checkbox"
341+ & inputElementConfig_initialChecked .~ True
342+ & inputElementConfig_setChecked .~ setChecked
343+ pure ()
344+ it "sets checked attr appropriately at postbuild" $ runWD $ do
345+ let checkStatic = do
346+ e <- findElemWithRetry $ WD.ByTag "input"
347+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
348+ pure e
349+ checkValue e = do
350+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
351+ testWidget' checkStatic checkValue $ do
352+ pb <- getPostBuild
353+ _ <- inputElement $ def
354+ & initialAttributes .~ "type" =: "checkbox"
355+ & inputElementConfig_initialChecked .~ False
356+ & inputElementConfig_setChecked .~ (True <$ pb)
357+ pure ()
358+ describe "hydration" $ do
359+ it "doesn't wipe user input when switching over" $ runWD $ do
360+ inputRef <- newRef ("hello " :: Text)
361+ testWidget'
362+ (do
363+ e <- findElemWithRetry $ WD.ByTag "input"
364+ WD.sendKeys "world" e
365+ pure e)
366+ (\e -> do
367+ WD.attr e "value" `shouldBeWithRetryM` Just "hello world"
368+ WD.click =<< findElemWithRetry (WD.ByTag "button")
369+ readRef inputRef `shouldBeWithRetryM` "hello world"
370+ ) $ do
371+ e <- inputElement $ def & inputElementConfig_initialValue .~ "hello "
372+ click <- button "save"
373+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
374+ it "captures user input after switchover" $ runWD $ do
375+ inputRef <- newRef ("" :: Text)
376+ let checkValue = do
377+ WD.sendKeys "hello world" =<< findElemWithRetry (WD.ByTag "input")
378+ WD.click =<< findElemWithRetry (WD.ByTag "button")
379+ readRef inputRef `shouldBeWithRetryM` "hello world"
380+ testWidget (pure ()) checkValue $ do
381+ e <- inputElement def
382+ click <- button "save"
383+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
384+ it "sets focus appropriately" $ runWD $ do
385+ focusRef <- newRef False
386+ let checkValue = do
387+ readRef focusRef `shouldBeWithRetryM` False
388+ e <- findElemWithRetry $ WD.ByTag "input"
389+ WD.click e
390+ readRef focusRef `shouldBeWithRetryM` True
391+ testWidget (pure ()) checkValue $ do
392+ e <- inputElement def
393+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_inputElement_hasFocus e)
394+ it "sets focus when focus occurs before hydration" $ runWD $ do
395+ focusRef <- newRef False
396+ let setup = do
397+ e <- findElemWithRetry $ WD.ByTag "input"
398+ WD.click e
399+ ((== e) <$> WD.activeElem) `shouldBeWithRetryM` True
400+ readRef focusRef `shouldBeWithRetryM` False
401+ check = readRef focusRef `shouldBeWithRetryM` True
402+ testWidget setup check $ do
403+ e <- inputElement def
404+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_inputElement_hasFocus e)
405+ it "sets value appropriately" $ runWD $ do
406+ valueByUIRef <- newRef ("" :: Text)
407+ valueRef <- newRef ("" :: Text)
408+ setValueChan :: Chan Text <- liftIO newChan
409+ let checkValue = do
410+ readRef valueByUIRef `shouldBeWithRetryM` ""
411+ readRef valueRef `shouldBeWithRetryM` ""
412+ e <- findElemWithRetry $ WD.ByTag "input"
413+ WD.sendKeys "hello" e
414+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
415+ readRef valueRef `shouldBeWithRetryM` "hello"
416+ liftIO $ writeChan setValueChan "world"
417+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
418+ readRef valueRef `shouldBeWithRetryM` "world"
419+ testWidget (pure ()) checkValue $ do
420+ update <- triggerEventWithChan setValueChan
421+ e <- inputElement $ def & inputElementConfig_setValue .~ update
422+ performEvent_ $ liftIO . writeRef valueByUIRef <$> _inputElement_input e
423+ performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
424+ it "sets checked appropriately" $ runWD $ do
425+ checkedByUIRef <- newRef False
426+ checkedRef <- newRef False
427+ setCheckedChan <- liftIO newChan
428+ let checkStatic = do
429+ e <- findElemWithRetry $ WD.ByTag "input"
430+ WD.attr e "checked" `shouldBeWithRetryM` Nothing
431+ pure e
432+ checkValue e = do
433+ readRef checkedByUIRef `shouldBeWithRetryM` False
434+ readRef checkedRef `shouldBeWithRetryM` False
435+ WD.attr e "checked" `shouldBeWithRetryM` Nothing
436+ WD.moveToCenter e
437+ WD.click e
438+ readRef checkedByUIRef `shouldBeWithRetryM` True
439+ readRef checkedRef `shouldBeWithRetryM` True
440+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
441+ liftIO $ writeChan setCheckedChan False
442+ readRef checkedByUIRef `shouldBeWithRetryM` True
443+ readRef checkedRef `shouldBeWithRetryM` False
444+ WD.attr e "checked" `shouldBeWithRetryM` Nothing
445+ testWidget' checkStatic checkValue $ do
446+ setChecked <- triggerEventWithChan setCheckedChan
447+ e <- inputElement $ def
448+ & initialAttributes .~ "type" =: "checkbox"
449+ & inputElementConfig_setChecked .~ setChecked
450+ performEvent_ $ liftIO . writeRef checkedByUIRef <$> _inputElement_checkedChange e
451+ performEvent_ $ liftIO . writeRef checkedRef <$> updated (_inputElement_checked e)
452+ it "respects user updates to checked which happen before hydration" $ runWD $ do
453+ checkedByUIRef <- newRef False
454+ checkedRef <- newRef False
455+ let checkStatic = do
456+ e <- findElemWithRetry $ WD.ByTag "input"
457+ WD.attr e "checked" `shouldBeWithRetryM` Nothing
458+ WD.moveToCenter e
459+ WD.click e
460+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
461+ pure e
462+ checkValue e = do
463+ WD.attr e "checked" `shouldBeWithRetryM` Just "true"
464+ readRef checkedByUIRef `shouldBeWithRetryM` True
465+ readRef checkedRef `shouldBeWithRetryM` True
466+ testWidget' checkStatic checkValue $ do
467+ e <- inputElement $ def
468+ & initialAttributes .~ "type" =: "checkbox"
469+ performEvent_ $ liftIO . writeRef checkedByUIRef <$> _inputElement_checkedChange e
470+ performEvent_ $ liftIO . writeRef checkedRef <$> updated (_inputElement_checked e)
471+ it "captures file uploads" $ runWD $ do
472+ filesRef :: IORef [Text] <- newRef []
473+ let uploadFile = do
474+ e <- findElemWithRetry $ WD.ByTag "input"
475+ path <- liftIO $ writeSystemTempFile "testFile" "file contents"
476+ WD.sendKeys (T.pack path) e
477+ WD.click =<< findElemWithRetry (WD.ByTag "button")
478+ liftIO $ removeFile path
479+ readRef filesRef `shouldBeWithRetryM` [T.pack $ FilePath.takeFileName path]
480+ testWidget (pure ()) uploadFile $ do
481+ e <- inputElement $ def & initialAttributes .~ "type" =: "file"
482+ click <- button "save"
483+ prerender_ (pure ()) $ performEvent_ $ ffor (tag (current (_inputElement_files e)) click) $ \fs -> do
484+ names <- liftJSM $ traverse File.getName fs
485+ liftIO $ writeRef filesRef names
486+ it "fires _input event if the user altered the value before hydration" $ runWD $ do
487+ input <- newRef ("" :: Text)
488+ update <- newRef ("" :: Text)
489+ let checkStatic = do
490+ e <- findElemWithRetry $ WD.ByTag "input"
491+ WD.attr e "value" `shouldBeWithRetryM` Just ""
492+ WD.sendKeys "test" e
493+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
494+ pure e
495+ checkHydrated e = do
496+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
497+ readRef input `shouldBeWithRetryM` "test"
498+ readRef update `shouldBeWithRetryM` "test"
499+ testWidget' checkStatic checkHydrated $ do
500+ e <- inputElement def
501+ performEvent_ $ liftIO . writeRef input <$> _inputElement_input e
502+ performEvent_ $ liftIO . writeRef update <$> updated (_inputElement_value e)
503+ it "does not fire _input event when the value is updated at postBuild" $ runWD $ do
504+ input <- newRef (Nothing :: Maybe Text)
505+ let checkStatic = do
506+ e <- findElemWithRetry $ WD.ByTag "input"
507+ WD.attr e "value" `shouldBeWithRetryM` Just "pb"
508+ pure e
509+ checkHydrated e = do
510+ WD.attr e "value" `shouldBeWithRetryM` Just "pb"
511+ readRef input `shouldBeWithRetryM` Nothing
512+ testWidget' checkStatic checkHydrated $ do
513+ pb <- getPostBuild
514+ e <- inputElement $ def & inputElementConfig_setValue .~ ("pb" <$ pb)
515+ performEvent_ $ liftIO . writeRef input . Just <$> _inputElement_input e
516+ it "SSR produces correct DOM based on inputElement values when setValue happens at postBuild" $ runWD $ do
517+ let checkBoth = do
518+ input <- findElemWithRetry $ WD.ByTag "input"
519+ WD.attr input "value" `shouldBeWithRetryM` Just "pb"
520+ p <- findElemWithRetry (WD.ByTag "p")
521+ shouldContainText "pb" p
522+ testWidget checkBoth checkBoth $ do
523+ pb <- getPostBuild
524+ e <- inputElement $ def & inputElementConfig_setValue .~ ("pb" <$ pb)
525+ el "p" $ dynText $ _inputElement_value e
526+ it "does not fail when both setValue AND user updated value happen before switchover" $ runWD $ do
527+ let checkStatic = do
528+ input <- findElemWithRetry $ WD.ByTag "input"
529+ h2_value <- findElemWithRetry (WD.ByTag "h2")
530+ h3_input <- findElemWithRetry (WD.ByTag "h3")
531+ WD.attr input "value" `shouldBeWithRetryM` Just "pb"
532+ shouldContainText "pb" h2_value
533+ shouldContainText "" h3_input
534+ WD.sendKeys "abc" input
535+ WD.attr input "value" `shouldBeWithRetryM` Just "pbabc"
536+ shouldContainText "pb" h2_value
537+ shouldContainText "" h3_input
538+ pure (input, h2_value, h3_input)
539+ checkHydrated (input, h2_value, h3_input) = do
540+ WD.attr input "value" `shouldBeWithRetryM` Just "pbabc"
541+ shouldContainText "pbabc" h3_input
542+ shouldContainText "pbabc pb" h2_value
543+ pure ()
544+ testWidget' checkStatic checkHydrated $ do
545+ pb <- getPostBuild
546+ e <- inputElement $ def & inputElementConfig_setValue .~ ("pb" <$ pb)
547+ el "h1" $ dynText $ _inputElement_value e
548+ el "h2" $ dynText . fmap T.unwords <=< foldDyn (:) [] $ updated $ _inputElement_value e
549+ el "h3" $ dynText . fmap T.unwords <=< foldDyn (:) [] $ _inputElement_input e
550+ it "value is correct when both setValue AND user updated value happen before switchover" $ runWD $ do
551+ let checkStatic = do
552+ input <- findElemWithRetry $ WD.ByTag "input"
553+ p <- findElemWithRetry (WD.ByTag "p")
554+ WD.attr input "value" `shouldBeWithRetryM` Just "pb"
555+ shouldContainText "pb" p
556+ WD.sendKeys "abc" input
557+ WD.attr input "value" `shouldBeWithRetryM` Just "pbabc"
558+ shouldContainText "pb" p -- It won't be updated yet
559+ pure (input, p)
560+ checkHydrated (input, p) = do
561+ WD.attr input "value" `shouldBeWithRetryM` Just "pbabc"
562+ shouldContainText "pbabc" p
563+ pure ()
564+ testWidget' checkStatic checkHydrated $ do
565+ pb <- getPostBuild
566+ e <- inputElement $ def & inputElementConfig_setValue .~ ("pb" <$ pb)
567+ el "p" $ dynText $ _inputElement_value e
568+ it "input event and (updated value) fire correctly when both setValue AND user updated value happen before switchover" $ runWD $ do
569+ valRef <- newRef ([] :: [Text])
570+ inputRef <- newRef ([] :: [Text])
571+ let consRef ref a = liftIO $ atomicModifyRef ref $ \as -> (a:as, ())
572+ checkStatic = do
573+ input <- findElemWithRetry $ WD.ByTag "input"
574+ p <- findElemWithRetry (WD.ByTag "p")
575+ WD.attr input "value" `shouldBeWithRetryM` Just "pb"
576+ shouldContainText "pb" p
577+ WD.sendKeys "abc" input
578+ WD.attr input "value" `shouldBeWithRetryM` Just "pbabc"
579+ shouldContainText "pb" p -- It won't be updated yet
580+ readRef inputRef `shouldBeWithRetryM` [] -- Should never fire input ref during SSR
581+ readRef valRef `shouldBeWithRetryM` ["pb"]
582+ pure (input, p)
583+ checkHydrated (input, p) = do
584+ readRef inputRef `shouldBeWithRetryM` ["pbabc"]
585+ readRef valRef `shouldBeWithRetryM` ["pbabc", "pb"]
586+ WD.attr input "value" `shouldBeWithRetryM` Just "pbabc"
587+ shouldContainText "pbabc" p
588+ pure ()
589+ testWidget' checkStatic checkHydrated $ do
590+ liftIO $ writeRef valRef []
591+ pb <- getPostBuild
592+ e <- inputElement $ def & inputElementConfig_setValue .~ ("pb" <$ pb)
593+ el "p" $ dynText $ _inputElement_value e
594+ performEvent_ $ consRef valRef <$> updated (_inputElement_value e)
595+ performEvent_ $ consRef inputRef <$> _inputElement_input e
596+ describe "hydration/immediate" $ do
597+ it "captures user input after switchover" $ runWD $ do
598+ inputRef :: IORef Text <- newRef ""
599+ let checkValue = do
600+ WD.sendKeys "hello world" =<< findElemWithRetry (WD.ByTag "input")
601+ WD.click =<< findElemWithRetry (WD.ByTag "button")
602+ readRef inputRef `shouldBeWithRetryM` "hello world"
603+ testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
604+ e <- inputElement def
605+ click <- button "save"
606+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
607+ it "sets focus appropriately" $ runWD $ do
608+ focusRef <- newRef False
609+ let checkValue = do
610+ readRef focusRef `shouldBeWithRetryM` False
611+ e <- findElemWithRetry $ WD.ByTag "input"
612+ WD.click e
613+ readRef focusRef `shouldBeWithRetryM` True
614+ testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
615+ e <- inputElement def
616+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_inputElement_hasFocus e)
617+ it "sets value appropriately" $ runWD $ do
618+ valueByUIRef :: IORef Text <- newRef ""
619+ valueRef :: IORef Text <- newRef ""
620+ setValueChan :: Chan Text <- liftIO newChan
621+ let checkValue = do
622+ readRef valueByUIRef `shouldBeWithRetryM` ""
623+ readRef valueRef `shouldBeWithRetryM` ""
624+ e <- findElemWithRetry $ WD.ByTag "input"
625+ WD.sendKeys "hello" e
626+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
627+ readRef valueRef `shouldBeWithRetryM` "hello"
628+ liftIO $ writeChan setValueChan "world"
629+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
630+ readRef valueRef `shouldBeWithRetryM` "world"
631+ testWidget (pure ()) checkValue $ do
632+ update <- triggerEventWithChan setValueChan
633+ prerender_ (pure ()) $ do
634+ e <- inputElement $ def & inputElementConfig_setValue .~ update
635+ performEvent_ $ liftIO . writeRef valueByUIRef <$> _inputElement_input e
636+ performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
637+ it "sets checked appropriately" $ runWD $ do
638+ checkedByUIRef <- newRef False
639+ checkedRef <- newRef False
640+ setCheckedChan <- liftIO newChan
641+ let checkValue = do
642+ readRef checkedByUIRef `shouldBeWithRetryM` False
643+ readRef checkedRef `shouldBeWithRetryM` False
644+ e <- findElemWithRetry $ WD.ByTag "input"
645+ WD.moveToCenter e
646+ WD.click e
647+ readRef checkedByUIRef `shouldBeWithRetryM` True
648+ readRef checkedRef `shouldBeWithRetryM` True
649+ liftIO $ writeChan setCheckedChan False
650+ readRef checkedByUIRef `shouldBeWithRetryM` True
651+ readRef checkedRef `shouldBeWithRetryM` False
652+ testWidget (pure ()) checkValue $ do
653+ setChecked <- triggerEventWithChan setCheckedChan
654+ prerender_ (pure ()) $ do
655+ e <- inputElement $ def
656+ & initialAttributes .~ "type" =: "checkbox"
657+ & inputElementConfig_setChecked .~ setChecked
658+ performEvent_ $ liftIO . writeRef checkedByUIRef <$> _inputElement_checkedChange e
659+ performEvent_ $ liftIO . writeRef checkedRef <$> updated (_inputElement_checked e)
660+ it "captures file uploads" $ runWD $ do
661+ filesRef :: IORef [Text] <- newRef []
662+ let uploadFile = do
663+ e <- findElemWithRetry $ WD.ByTag "input"
664+ path <- liftIO $ writeSystemTempFile "testFile" "file contents"
665+ WD.sendKeys (T.pack path) e
666+ WD.click =<< findElemWithRetry (WD.ByTag "button")
667+ liftIO $ removeFile path
668+ readRef filesRef `shouldBeWithRetryM` [T.pack $ FilePath.takeFileName path]
669+ testWidget (pure ()) uploadFile $ prerender_ (pure ()) $ do
670+ e <- inputElement $ def & initialAttributes .~ "type" =: "file"
671+ click <- button "save"
672+ performEvent_ $ ffor (tag (current (_inputElement_files e)) click) $ \fs -> do
673+ names <- liftJSM $ traverse File.getName fs
674+ liftIO $ writeRef filesRef names
675+
676+ session' "textAreaElement" $ do
677+ describe "static renderer" $ do
678+ it "sets value attribute" $ runWD $ do
679+ let checkStatic = do
680+ e <- findElemWithRetry $ WD.ByTag "textarea"
681+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
682+ pure e
683+ checkHydrated e = do
684+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
685+ testWidget' checkStatic checkHydrated $ void $ textAreaElement $ def
686+ & textAreaElementConfig_initialValue .~ "test"
687+ it "updates value attribute at postBuild" $ runWD $ do
688+ let checkStatic = do
689+ e <- findElemWithRetry $ WD.ByTag "textarea"
690+ WD.attr e "value" `shouldBeWithRetryM` Just "test-updated"
691+ pure e
692+ checkHydrated e = do
693+ WD.attr e "value" `shouldBeWithRetryM` Just "test-updated"
694+ testWidget' checkStatic checkHydrated $ do
695+ pb <- getPostBuild
696+ _ <- textAreaElement $ def
697+ & textAreaElementConfig_initialValue .~ "test"
698+ & textAreaElementConfig_setValue .~ ("test-updated" <$ pb)
699+ pure ()
700+ describe "hydration" $ do
701+ it "doesn't wipe user input when switching over" $ runWD $ do
702+ inputRef <- newRef ("" :: Text)
703+ testWidget'
704+ (do
705+ e <- findElemWithRetry $ WD.ByTag "textarea"
706+ WD.sendKeys "hello world" e
707+ pure e)
708+ (\e -> do
709+ WD.attr e "value" `shouldBeWithRetryM` Just "hello world"
710+ WD.click <=< findElemWithRetry $ WD.ByTag "button"
711+ readRef inputRef `shouldBeWithRetryM` "hello world"
712+ ) $ do
713+ e <- textAreaElement def
714+ click <- button "save"
715+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
716+ it "captures user input after switchover" $ runWD $ do
717+ inputRef <- newRef ("" :: Text)
718+ let checkValue = do
719+ WD.sendKeys "hello world" =<< findElemWithRetry (WD.ByTag "textarea")
720+ WD.click =<< findElemWithRetry (WD.ByTag "button")
721+ readRef inputRef `shouldBeWithRetryM` "hello world"
722+ testWidget (pure ()) checkValue $ do
723+ e <- textAreaElement def
724+ click <- button "save"
725+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
726+ it "sets focus appropriately" $ runWD $ do
727+ focusRef <- newRef False
728+ let checkValue = do
729+ readRef focusRef `shouldBeWithRetryM` False
730+ e <- findElemWithRetry $ WD.ByTag "textarea"
731+ WD.click e
732+ readRef focusRef `shouldBeWithRetryM` True
733+ testWidget (pure ()) checkValue $ do
734+ e <- textAreaElement def
735+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_textAreaElement_hasFocus e)
736+ it "sets focus when focus occurs before hydration" $ runWD $ do
737+ focusRef <- newRef False
738+ let setup = do
739+ e <- findElemWithRetry $ WD.ByTag "textarea"
740+ WD.click e
741+ ((== e) <$> WD.activeElem) `shouldBeWithRetryM` True
742+ readRef focusRef `shouldBeWithRetryM` False
743+ check = readRef focusRef `shouldBeWithRetryM` True
744+ testWidget setup check $ do
745+ e <- textAreaElement def
746+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_textAreaElement_hasFocus e)
747+ it "sets value appropriately" $ runWD $ do
748+ valueByUIRef <- newRef ("" :: Text)
749+ valueRef <- newRef ("" :: Text)
750+ setValueChan :: Chan Text <- liftIO newChan
751+ let checkValue = do
752+ readRef valueByUIRef `shouldBeWithRetryM` ""
753+ readRef valueRef `shouldBeWithRetryM` ""
754+ e <- findElemWithRetry $ WD.ByTag "textarea"
755+ WD.sendKeys "hello" e
756+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
757+ readRef valueRef `shouldBeWithRetryM` "hello"
758+ liftIO $ writeChan setValueChan "world"
759+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
760+ readRef valueRef `shouldBeWithRetryM` "world"
761+ testWidget (pure ()) checkValue $ do
762+ setValue' <- triggerEventWithChan setValueChan
763+ e <- textAreaElement $ def { _textAreaElementConfig_setValue = Just setValue' }
764+ performEvent_ $ liftIO . writeRef valueByUIRef <$> _textAreaElement_input e
765+ performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
766+ it "fires _input event if the user altered the value before hydration" $ runWD $ do
767+ textarea <- newRef ("" :: Text)
768+ update <- newRef ("" :: Text)
769+ let checkStatic = do
770+ e <- findElemWithRetry $ WD.ByTag "textarea"
771+ WD.attr e "value" `shouldBeWithRetryM` Just ""
772+ WD.sendKeys "test" e
773+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
774+ pure e
775+ checkHydrated e = do
776+ WD.attr e "value" `shouldBeWithRetryM` Just "test"
777+ readRef textarea `shouldBeWithRetryM` "test"
778+ readRef update `shouldBeWithRetryM` "test"
779+ testWidget' checkStatic checkHydrated $ do
780+ e <- textAreaElement def
781+ performEvent_ $ liftIO . writeRef textarea <$> _textAreaElement_input e
782+ performEvent_ $ liftIO . writeRef update <$> updated (_textAreaElement_value e)
783+ it "does not fire _input event when the value is updated at postBuild" $ runWD $ do
784+ textarea <- newRef (Nothing :: Maybe Text)
785+ let checkStatic = do
786+ e <- findElemWithRetry $ WD.ByTag "textarea"
787+ WD.attr e "value" `shouldBeWithRetryM` Just "pb"
788+ pure e
789+ checkHydrated e = do
790+ WD.attr e "value" `shouldBeWithRetryM` Just "pb"
791+ readRef textarea `shouldBeWithRetryM` Nothing
792+ testWidget' checkStatic checkHydrated $ do
793+ pb <- getPostBuild
794+ e <- textAreaElement $ def & textAreaElementConfig_setValue .~ ("pb" <$ pb)
795+ performEvent_ $ liftIO . writeRef textarea . Just <$> _textAreaElement_input e
796+ it "SSR produces correct DOM based on textAreaElement values when setValue happens at postBuild" $ runWD $ do
797+ let checkBoth = do
798+ textarea <- findElemWithRetry $ WD.ByTag "textarea"
799+ WD.attr textarea "value" `shouldBeWithRetryM` Just "pb"
800+ p <- findElemWithRetry (WD.ByTag "p")
801+ shouldContainText "pb" p
802+ testWidget checkBoth checkBoth $ do
803+ pb <- getPostBuild
804+ e <- textAreaElement $ def & textAreaElementConfig_setValue .~ ("pb" <$ pb)
805+ el "p" $ dynText $ _textAreaElement_value e
806+ it "does not fail when both setValue AND user updated value happen before switchover" $ runWD $ do
807+ let checkStatic = do
808+ textarea <- findElemWithRetry $ WD.ByTag "textarea"
809+ h2_value <- findElemWithRetry (WD.ByTag "h2")
810+ h3_input <- findElemWithRetry (WD.ByTag "h3")
811+ WD.attr textarea "value" `shouldBeWithRetryM` Just "pb"
812+ shouldContainText "pb" h2_value
813+ shouldContainText "" h3_input
814+ WD.sendKeys "abc" textarea
815+ WD.attr textarea "value" `shouldBeWithRetryM` Just "pbabc"
816+ shouldContainText "pb" h2_value
817+ shouldContainText "" h3_input
818+ pure (textarea, h2_value, h3_input)
819+ checkHydrated (textarea, h2_value, h3_input) = do
820+ WD.attr textarea "value" `shouldBeWithRetryM` Just "pbabc"
821+ shouldContainText "pbabc" h3_input
822+ shouldContainText "pbabc pb" h2_value
823+ pure ()
824+ testWidget' checkStatic checkHydrated $ do
825+ pb <- getPostBuild
826+ e <- textAreaElement $ def & textAreaElementConfig_setValue .~ ("pb" <$ pb)
827+ el "h1" $ dynText $ _textAreaElement_value e
828+ el "h2" $ dynText . fmap T.unwords <=< foldDyn (:) [] $ updated $ _textAreaElement_value e
829+ el "h3" $ dynText . fmap T.unwords <=< foldDyn (:) [] $ _textAreaElement_input e
830+ it "value is correct when both setValue AND user updated value happen before switchover" $ runWD $ do
831+ let checkStatic = do
832+ textarea <- findElemWithRetry $ WD.ByTag "textarea"
833+ p <- findElemWithRetry (WD.ByTag "p")
834+ WD.attr textarea "value" `shouldBeWithRetryM` Just "pb"
835+ shouldContainText "pb" p
836+ WD.sendKeys "abc" textarea
837+ WD.attr textarea "value" `shouldBeWithRetryM` Just "pbabc"
838+ shouldContainText "pb" p -- It won't be updated yet
839+ pure (textarea, p)
840+ checkHydrated (textarea, p) = do
841+ WD.attr textarea "value" `shouldBeWithRetryM` Just "pbabc"
842+ shouldContainText "pbabc" p
843+ pure ()
844+ testWidget' checkStatic checkHydrated $ do
845+ pb <- getPostBuild
846+ e <- textAreaElement $ def & textAreaElementConfig_setValue .~ ("pb" <$ pb)
847+ el "p" $ dynText $ _textAreaElement_value e
848+
849+ describe "hydration/immediate" $ do
850+ it "captures user input after switchover" $ runWD $ do
851+ inputRef :: IORef Text <- newRef ""
852+ let checkValue = do
853+ WD.sendKeys "hello world" <=< findElemWithRetry $ WD.ByTag "textarea"
854+ WD.click <=< findElemWithRetry $ WD.ByTag "button"
855+ readRef inputRef `shouldBeWithRetryM` "hello world"
856+ testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
857+ e <- textAreaElement def
858+ click <- button "save"
859+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (value e)) click
860+ it "sets focus appropriately" $ runWD $ do
861+ focusRef <- newRef False
862+ let checkValue = do
863+ readRef focusRef `shouldBeWithRetryM` False
864+ e <- findElemWithRetry $ WD.ByTag "textarea"
865+ WD.click e
866+ readRef focusRef `shouldBeWithRetryM` True
867+ testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
868+ e <- textAreaElement def
869+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_textAreaElement_hasFocus e)
870+ it "sets value appropriately" $ runWD $ do
871+ valueByUIRef :: IORef Text <- newRef ""
872+ valueRef :: IORef Text <- newRef ""
873+ setValueChan :: Chan Text <- liftIO newChan
874+ let checkValue = do
875+ readRef valueByUIRef `shouldBeWithRetryM` ""
876+ readRef valueRef `shouldBeWithRetryM` ""
877+ e <- findElemWithRetry $ WD.ByTag "textarea"
878+ WD.sendKeys "hello" e
879+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
880+ readRef valueRef `shouldBeWithRetryM` "hello"
881+ liftIO $ writeChan setValueChan "world"
882+ readRef valueByUIRef `shouldBeWithRetryM` "hello"
883+ readRef valueRef `shouldBeWithRetryM` "world"
884+ testWidget (pure ()) checkValue $ do
885+ setValue' <- triggerEventWithChan setValueChan
886+ prerender_ (pure ()) $ do
887+ e <- textAreaElement $ def { _textAreaElementConfig_setValue = Just setValue' }
888+ performEvent_ $ liftIO . writeRef valueByUIRef <$> _textAreaElement_input e
889+ performEvent_ $ liftIO . writeRef valueRef <$> updated (value e)
890+
891+ session' "selectElement" $ do
892+ let options :: DomBuilder t m => m ()
893+ options = do
894+ elAttr "option" ("value" =: "one" <> "id" =: "one") $ text "one"
895+ elAttr "option" ("value" =: "two" <> "id" =: "two") $ text "two"
896+ elAttr "option" ("value" =: "three" <> "id" =: "three") $ text "three"
897+ describe "hydration" $ do
898+ it "sets initial value correctly" $ runWD $ do
899+ inputRef <- newRef ("" :: Text)
900+ let setup = do
901+ e <- findElemWithRetry $ WD.ByTag "select"
902+ assertAttr e "value" (Just "three")
903+ WD.click =<< findElemWithRetry (WD.ById "two")
904+ pure e
905+ check e = do
906+ assertAttr e "value" (Just "two")
907+ readRef inputRef `shouldBeWithRetryM` "three"
908+ WD.click =<< findElemWithRetry (WD.ByTag "button")
909+ assertAttr e "value" (Just "two")
910+ readRef inputRef `shouldBeWithRetryM` "two"
911+ testWidget' setup check $ do
912+ (e, ()) <- selectElement (def { _selectElementConfig_initialValue = "three" }) options
913+ click <- button "save"
914+ liftIO . writeRef inputRef <=< sample $ current $ _selectElement_value e
915+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (_selectElement_value e)) click
916+ it "captures user input after switchover" $ runWD $ do
917+ inputRef <- newRef ("" :: Text)
918+ let checkValue = do
919+ e <- findElemWithRetry $ WD.ByTag "select"
920+ assertAttr e "value" (Just "one")
921+ WD.click =<< findElemWithRetry (WD.ById "two")
922+ assertAttr e "value" (Just "two")
923+ WD.click =<< findElemWithRetry (WD.ByTag "button")
924+ readRef inputRef `shouldBeWithRetryM` "two"
925+ testWidget (pure ()) checkValue $ do
926+ (e, ()) <- selectElement def options
927+ click <- button "save"
928+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (_selectElement_value e)) click
929+ it "sets focus appropriately" $ runWD $ do
930+ focusRef <- newRef False
931+ let checkValue = do
932+ readRef focusRef `shouldBeWithRetryM` False
933+ e <- findElemWithRetry $ WD.ByTag "select"
934+ WD.click e
935+ readRef focusRef `shouldBeWithRetryM` True
936+ testWidget (pure ()) checkValue $ do
937+ (e, ()) <- selectElement def options
938+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_selectElement_hasFocus e)
939+ it "sets focus when focus occurs before hydration" $ runWD $ do
940+ focusRef <- newRef False
941+ let setup = do
942+ e <- findElemWithRetry $ WD.ByTag "select"
943+ WD.click e
944+ ((== e) <$> WD.activeElem) `shouldBeWithRetryM` True
945+ readRef focusRef `shouldBeWithRetryM` False
946+ check = readRef focusRef `shouldBeWithRetryM` True
947+ testWidget setup check $ do
948+ (e, ()) <- selectElement def options
949+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_selectElement_hasFocus e)
950+ it "sets value appropriately" $ runWD $ do
951+ valueByUIRef <- newRef ("" :: Text)
952+ valueRef <- newRef ("" :: Text)
953+ setValueChan :: Chan Text <- liftIO newChan
954+ let checkValue = do
955+ e <- findElemWithRetry $ WD.ByTag "select"
956+ assertAttr e "value" (Just "one")
957+ readRef valueByUIRef `shouldBeWithRetryM` "one"
958+ readRef valueRef `shouldBeWithRetryM` "one"
959+ WD.click <=< findElemWithRetry $ WD.ById "two"
960+ readRef valueByUIRef `shouldBeWithRetryM` "two"
961+ readRef valueRef `shouldBeWithRetryM` "two"
962+ liftIO $ writeChan setValueChan "three"
963+ readRef valueByUIRef `shouldBeWithRetryM` "two"
964+ readRef valueRef `shouldBeWithRetryM` "three"
965+ testWidget (pure ()) checkValue $ do
966+ setValue' <- triggerEventWithChan setValueChan
967+ (e, ()) <- selectElement def { _selectElementConfig_setValue = Just setValue' } options
968+ performEvent_ $ liftIO . writeRef valueByUIRef <$> _selectElement_change e
969+ performEvent_ $ liftIO . writeRef valueRef <$> updated (_selectElement_value e)
970+
971+ describe "hydration/immediate" $ do
972+ it "captures user input after switchover" $ runWD $ do
973+ inputRef :: IORef Text <- newRef ""
974+ let checkValue = do
975+ WD.click <=< findElemWithRetry $ WD.ById "two"
976+ WD.click <=< findElemWithRetry $ WD.ByTag "button"
977+ readRef inputRef `shouldBeWithRetryM` "two"
978+ testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
979+ (e, ()) <- selectElement def options
980+ click <- button "save"
981+ performEvent_ $ liftIO . writeRef inputRef <$> tag (current (_selectElement_value e)) click
982+ it "sets focus appropriately" $ runWD $ do
983+ focusRef <- newRef False
984+ let checkValue = do
985+ readRef focusRef `shouldBeWithRetryM` False
986+ e <- findElemWithRetry $ WD.ByTag "select"
987+ WD.click e
988+ readRef focusRef `shouldBeWithRetryM` True
989+ testWidget (pure ()) checkValue $ prerender_ (pure ()) $ do
990+ (e, ()) <- selectElement def options
991+ performEvent_ $ liftIO . writeRef focusRef <$> updated (_selectElement_hasFocus e)
992+ it "has correct initial value" $ runWD $ do
993+ valueRef :: IORef Text <- newRef ""
994+ let checkValue = readRef valueRef `shouldBeWithRetryM` "one"
995+ testWidget (pure ()) checkValue $ do
996+ prerender_ (pure ()) $ do
997+ (e, ()) <- selectElement def { _selectElementConfig_initialValue = "one" } options
998+ liftIO . writeRef valueRef <=< sample $ current $ _selectElement_value e
999+ it "sets value appropriately" $ runWD $ do
1000+ valueByUIRef :: IORef Text <- newRef ""
1001+ valueRef :: IORef Text <- newRef ""
1002+ setValueChan :: Chan Text <- liftIO newChan
1003+ let checkValue = do
1004+ WD.click =<< findElemWithRetry (WD.ById "two")
1005+ readRef valueByUIRef `shouldBeWithRetryM` "two"
1006+ readRef valueRef `shouldBeWithRetryM` "two"
1007+ liftIO $ writeChan setValueChan "three"
1008+ readRef valueByUIRef `shouldBeWithRetryM` "two"
1009+ readRef valueRef `shouldBeWithRetryM` "three"
1010+ testWidget (pure ()) checkValue $ do
1011+ setValue' <- triggerEventWithChan setValueChan
1012+ prerender_ (pure ()) $ do
1013+ (e, ()) <- selectElement def { _selectElementConfig_setValue = Just setValue' } options
1014+ performEvent_ $ liftIO . writeRef valueByUIRef <$> _selectElement_change e
1015+ performEvent_ $ liftIO . writeRef valueRef <$> updated (_selectElement_value e)
1016+
1017+ session' "prerender" $ do
1018+ it "works in simple case" $ runWD $ do
1019+ testWidget (checkBodyText "One") (checkBodyText "Two") $ do
1020+ prerender_ (text "One") (text "Two")
1021+ it "removes element correctly" $ runWD $ do
1022+ testWidget' (findElemWithRetry $ WD.ByTag "span") elementShouldBeRemoved $ do
1023+ prerender_ (el "span" $ text "One") (text "Two")
1024+ it "can be nested in server widget" $ runWD $ do
1025+ testWidget (checkBodyText "One") (checkBodyText "Three") $ do
1026+ prerender_ (prerender_ (text "One") (text "Two")) (text "Three")
1027+ it "can be nested in client widget" $ runWD $ do
1028+ testWidget (checkBodyText "One") (checkBodyText "Three") $ do
1029+ prerender_ (text "One") (prerender_ (text "Two") (text "Three"))
1030+ it "works with prerender_ siblings" $ runWD $ do
1031+ testWidget
1032+ (checkTextInId "a1" "One" >> checkTextInId "b1" "Three" >> checkTextInId "c1" "Five")
1033+ (checkTextInId "a2" "Two" >> checkTextInId "b2" "Four" >> checkTextInId "c2" "Six") $ do
1034+ prerender_ (divId "a1" $ text "One") (divId "a2" $ text "Two")
1035+ prerender_ (divId "b1" $ text "Three") (divId "b2" $ text "Four")
1036+ prerender_ (divId "c1" $ text "Five") (divId "c2" $ text "Six")
1037+ it "works inside other element" $ runWD $ do
1038+ testWidget (checkTextInTag "div" "One") (checkTextInTag "div" "Two") $ do
1039+ el "div" $ prerender_ (text "One") (text "Two")
1040+-- TODO re-enable this
1041+-- it "places fences and removes them" $ runWD $ do
1042+-- testWidget'
1043+-- (do
1044+-- scripts <- WD.findElems $ WD.ByTag "script"
1045+-- filterM (\s -> maybe False (\t -> "prerender" `T.isPrefixOf` t) <$> WD.attr s "type") scripts
1046+-- )
1047+-- (traverse_ elementShouldBeRemoved)
1048+-- (el "span" $ prerender_ (text "One") (text "Two"))
1049+ it "postBuild works on server side" $ runWD $ do
1050+ lock :: MVar () <- liftIO newEmptyMVar
1051+ testWidget (liftIO $ takeMVar lock) (pure ()) $ do
1052+ prerender_ (do
1053+ pb <- getPostBuild
1054+ performEvent_ $ liftIO (putMVar lock ()) <$ pb) blank
1055+ it "postBuild works on client side" $ runWD $ do
1056+ lock :: MVar () <- liftIO newEmptyMVar
1057+ testWidget (pure ()) (liftIO $ takeMVar lock) $ do
1058+ prerender_ blank $ do
1059+ pb <- getPostBuild
1060+ performEvent_ $ liftIO (putMVar lock ()) <$ pb
1061+ it "result Dynamic is updated *after* switchover" $ runWD $ do
1062+ let preSwitchover = checkBodyText "PostBuild"
1063+ check = checkBodyText "Client"
1064+ testWidget preSwitchover check $ void $ do
1065+ d <- prerender (pure "Initial") (pure "Client")
1066+ pb <- getPostBuild
1067+ initial <- sample $ current d
1068+ textNode $ TextNodeConfig initial $ Just $ leftmost [updated d, "PostBuild" <$ pb]
1069+ -- This essentially checks that the client IO runs *after* switchover/postBuild,
1070+ -- thus can't create conflicting DOM
1071+ it "can't exploit IO to break hydration" $ runWD $ do
1072+ let preSwitchover = checkBodyText "Initial"
1073+ testWidgetStatic preSwitchover $ void $ do
1074+ ref <- liftIO $ newRef "Initial"
1075+ prerender_ (pure ()) (liftIO $ writeRef ref "Client")
1076+ text <=< liftIO $ readRef ref
1077+ -- As above, so below
1078+ it "can't exploit triggerEvent to break hydration" $ runWD $ do
1079+ let preSwitchover = checkBodyText "Initial"
1080+ check = checkBodyText "Client"
1081+ testWidget preSwitchover check $ void $ do
1082+ (e, trigger) <- newTriggerEvent
1083+ prerender_ (pure ()) (liftIO $ trigger "Client")
1084+ textNode $ TextNodeConfig "Initial" $ Just e
1085+
1086+ session' "namespaces" $ do
1087+ it "dyn can be nested in namespaced widget" $ runWD $ do
1088+ testWidget (pure ()) (checkTextInTag "svg" "one") $ do
1089+ let svgRootCfg = def
1090+ & (elementConfig_namespace ?~ "http://www.w3.org/2000/svg")
1091+ & (elementConfig_initialAttributes .~ ("width" =: "100%" <> "height" =: "100%" <> "viewBox" =: "0 0 1536 2048"))
1092+ void $ element "svg" svgRootCfg $ do
1093+ dyn_ $ text "one" <$ pure ()
1094+
1095+ session' "runWithReplace" $ do
1096+ it "works" $ runWD $ do
1097+ replaceChan :: Chan Text <- liftIO newChan
1098+ let setup = findElemWithRetry $ WD.ByTag "div"
1099+ check ssr = do
1100+ -- Check that the original element still exists and has the correct text
1101+ shouldContainText "two" ssr
1102+ liftIO $ writeChan replaceChan "three"
1103+ elementShouldBeRemoved ssr
1104+ shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
1105+ testWidget' setup check $ do
1106+ replace <- triggerEventWithChan replaceChan
1107+ pb <- getPostBuild
1108+ void $ runWithReplace (el "div" $ text "one") $ leftmost
1109+ [ el "div" (text "two") <$ pb
1110+ , el "span" . text <$> replace
1111+ ]
1112+ it "can be nested in initial widget" $ runWD $ do
1113+ replaceChan :: Chan Text <- liftIO newChan
1114+ let setup = findElemWithRetry $ WD.ByTag "div"
1115+ check ssr = do
1116+ -- Check that the original element still exists and has the correct text
1117+ shouldContainText "two" ssr
1118+ liftIO $ writeChan replaceChan "three"
1119+ elementShouldBeRemoved ssr
1120+ shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
1121+ testWidget' setup check $ void $ flip runWithReplace never $ do
1122+ replace <- triggerEventWithChan replaceChan
1123+ pb <- getPostBuild
1124+ void $ runWithReplace (el "div" $ text "one") $ leftmost
1125+ [ el "div" (text "two") <$ pb
1126+ , el "span" . text <$> replace
1127+ ]
1128+ it "can be nested in postBuild widget" $ runWD $ do
1129+ replaceChan :: Chan Text <- liftIO newChan
1130+ let setup = findElemWithRetry $ WD.ByTag "div"
1131+ check ssr = do
1132+ -- Check that the original element still exists and has the correct text
1133+ shouldContainText "two" ssr
1134+ liftIO $ writeChan replaceChan "three"
1135+ elementShouldBeRemoved ssr
1136+ shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
1137+ testWidget' setup check $ void $ do
1138+ pb <- getPostBuild
1139+ runWithReplace (pure ()) $ ffor pb $ \() -> do
1140+ replace <- triggerEventWithChan replaceChan
1141+ pb' <- getPostBuild
1142+ void $ runWithReplace (el "div" $ text "one") $ leftmost
1143+ [ el "div" (text "two") <$ pb'
1144+ , el "span" . text <$> replace
1145+ ]
1146+ it "postBuild works in replaced widget" $ runWD $ do
1147+ replaceChan <- liftIO newChan
1148+ pbLock <- liftIO newEmptyMVar
1149+ let check = liftIO $ do
1150+ writeChan replaceChan ()
1151+ takeMVar pbLock
1152+ testWidget (pure ()) check $ void $ do
1153+ replace <- triggerEventWithChan replaceChan
1154+ runWithReplace (pure ()) $ ffor replace $ \() -> do
1155+ pb <- getPostBuild
1156+ performEvent_ $ liftIO (putMVar pbLock ()) <$ pb
1157+ it "can be nested in event widget" $ runWD $ do
1158+ replaceChan1 :: Chan Text <- liftIO newChan
1159+ replaceChan2 :: Chan Text <- liftIO newChan
1160+ lock :: MVar () <- liftIO newEmptyMVar
1161+ let check = do
1162+ shouldContainText "" =<< findElemWithRetry (WD.ByTag "body")
1163+ liftIO $ do
1164+ writeChan replaceChan1 "one"
1165+ takeMVar lock
1166+ one <- findElemWithRetry $ WD.ByTag "div"
1167+ shouldContainText "pb" one
1168+ liftIO $ writeChan replaceChan2 "two"
1169+ elementShouldBeRemoved one
1170+ shouldContainText "two" =<< findElemWithRetry (WD.ByTag "span")
1171+ testWidget (pure ()) check $ void $ do
1172+ replace1 <- triggerEventWithChan replaceChan1
1173+ runWithReplace (pure ()) $ ffor replace1 $ \r1 -> do
1174+ replace2 <- triggerEventWithChan replaceChan2
1175+ pb <- getPostBuild
1176+ performEvent_ $ liftIO (putMVar lock ()) <$ pb
1177+ void $ runWithReplace (el "div" $ text r1) $ leftmost
1178+ [ el "span" . text <$> replace2
1179+ , el "div" (text "pb") <$ pb
1180+ ]
1181+ it "prerender works in replaced widget" $ runWD $ do
1182+ replaceChan <- liftIO newChan
1183+ lock :: MVar () <- liftIO newEmptyMVar
1184+ pbLock :: MVar () <- liftIO newEmptyMVar
1185+ let check = do
1186+ liftIO $ do
1187+ writeChan replaceChan ()
1188+ takeMVar lock
1189+ takeMVar pbLock
1190+ testWidget (pure ()) check $ void $ do
1191+ replace <- triggerEventWithChan replaceChan
1192+ runWithReplace (pure ()) $ ffor replace $ \() -> do
1193+ prerender_ (pure ()) $ do
1194+ liftIO $ putMVar lock ()
1195+ pb <- getPostBuild
1196+ performEvent_ $ liftIO (putMVar pbLock ()) <$ pb
1197+ it "prerender returns in immediate mode" $ runWD $ do
1198+ replaceChan <- liftIO newChan
1199+ pbLock <- liftIO newEmptyMVar
1200+ let check = liftIO $ do
1201+ writeChan replaceChan ()
1202+ takeMVar pbLock
1203+ testWidget (pure ()) check $ void $ do
1204+ replace <- triggerEventWithChan replaceChan
1205+ runWithReplace (pure ()) $ ffor replace $ \() -> do
1206+ prerender_ (pure ()) (pure ())
1207+ liftIO $ putMVar pbLock ()
1208+ it "works in immediate mode (RHS of prerender)" $ runWD $ do
1209+ replaceChan :: Chan Text <- liftIO newChan
1210+ let check = do
1211+ checkBodyText "one"
1212+ one <- findElemWithRetry $ WD.ByTag "div"
1213+ shouldContainText "one" one
1214+ liftIO $ writeChan replaceChan "pb"
1215+ elementShouldBeRemoved one
1216+ shouldContainText "pb" =<< findElemWithRetry (WD.ByTag "span")
1217+ testWidget (pure ()) check $ void $ do
1218+ replace <- triggerEventWithChan replaceChan
1219+ prerender_ blank $ do
1220+ void $ runWithReplace (el "div" $ text "one") $ el "span" . text <$> replace
1221+ it "works with postBuild in immediate mode (RHS of prerender)" $ runWD $ do
1222+ replaceChan :: Chan Text <- liftIO newChan
1223+ let check = do
1224+ checkBodyText "two"
1225+ two <- findElemWithRetry $ WD.ByTag "div"
1226+ shouldContainText "two" two
1227+ liftIO $ writeChan replaceChan "three"
1228+ elementShouldBeRemoved two
1229+ shouldContainText "three" =<< findElemWithRetry (WD.ByTag "span")
1230+ testWidget (pure ()) check $ void $ do
1231+ replace <- triggerEventWithChan replaceChan
1232+ prerender_ blank $ do
1233+ pb <- getPostBuild
1234+ void $ runWithReplace (el "div" $ text "one") $ leftmost
1235+ [ el "div" (text "two") <$ pb
1236+ , el "span" . text <$> replace
1237+ ]
1238+
1239+ let checkInnerHtml t x = findElemWithRetry (WD.ByTag t) >>= (`attr` "innerHTML") >>= (`shouldBe` Just x)
1240+ it "removes bracketing comments" $ runWD $ do
1241+ replaceChan :: Chan () <- liftIO newChan
1242+ let
1243+ preSwitchover = checkInnerHtml "div" "before|<!--replace-start-0-->inner1<!--replace-end-0-->|after"
1244+ check () = do
1245+ liftIO $ writeChan replaceChan () -- trigger creation of p tag
1246+ _ <- findElemWithRetry $ WD.ByTag "p" -- wait till p tag is created
1247+ checkInnerHtml "div" "before|<p>inner2</p>|after"
1248+ testWidget' preSwitchover check $ do
1249+ replace <- triggerEventWithChan replaceChan
1250+ el "div" $ do
1251+ text "before|"
1252+ _ <- runWithReplace (text "inner1") $ el "p" (text "inner2") <$ replace
1253+ text "|after"
1254+ it "ignores extra ending bracketing comment" $ runWD $ do
1255+ replaceChan :: Chan () <- liftIO newChan
1256+ let
1257+ preSwitchover = checkInnerHtml "div" "before|<!--replace-start-0-->inner1<!--replace-end-0--><!--replace-end-0-->|after"
1258+ check () = do
1259+ liftIO $ writeChan replaceChan () -- trigger creation of p tag
1260+ _ <- findElemWithRetry $ WD.ByTag "p" -- wait till p tag is created
1261+ checkInnerHtml "div" "before|inner2|after"
1262+ testWidget' preSwitchover check $ do
1263+ replace <- triggerEventWithChan replaceChan
1264+ el "div" $ do
1265+ text "before|"
1266+ _ <- runWithReplace (text "inner1" *> comment "replace-end-0") $ text "inner2" <$ replace
1267+ text "|after"
1268+ void $ runWithReplace blank $ el "p" blank <$ replace -- Signal tag for end of test
1269+ -- TODO This test actually causes a hydration failure, but it wasn't
1270+ -- previously detected, so I've marked it pending
1271+ xit "ignores missing ending bracketing comments" $ runWD $ do
1272+ replaceChan :: Chan () <- liftIO newChan
1273+ let
1274+ preSwitchover = do
1275+ checkInnerHtml "div" "before|<!--replace-start-0-->inner1<!--replace-end-0-->|after"
1276+ divEl <- findElemWithRetry (WD.ByTag "div")
1277+ let wrongHtml = "<!--replace-start-0-->inner1"
1278+ actualHtml :: String <- WD.executeJS
1279+ [WD.JSArg divEl, WD.JSArg wrongHtml]
1280+ "arguments[0].innerHTML = arguments[1]; return arguments[0].innerHTML"
1281+ actualHtml `shouldBe` wrongHtml
1282+ check () = do
1283+ liftIO $ writeChan replaceChan () -- trigger creation of p tag
1284+ _ <- findElemWithRetry $ WD.ByTag "p" -- wait till p tag is created
1285+ checkInnerHtml "div" "before|<p>inner2</p>|after"
1286+ testWidget' preSwitchover check $ do
1287+ replace <- triggerEventWithChan replaceChan
1288+ el "div" $ do
1289+ text "before|"
1290+ _ <- runWithReplace (text "inner1") $ el "p" (text "inner2") <$ replace
1291+ text "|after"
1292+
1293+ session' "traverseDMapWithKeyWithAdjust" $ do
1294+ let widget :: DomBuilder t m => DKey a -> Identity a -> m (Identity a)
1295+ widget k (Identity v) = elAttr "li" ("id" =: textKey k) $ do
1296+ elClass "span" "key" $ text $ textKey k
1297+ elClass "span" "value" $ text $ T.pack $ has @Show k $ show v
1298+ pure (Identity v)
1299+ checkItem :: WD.Element -> Text -> Text -> WD ()
1300+ checkItem li k v = do
1301+ putStrLnDebug "checkItem"
1302+ shouldContainTextNoRetry k =<< WD.findElemFrom li (WD.ByClass "key")
1303+ shouldContainTextNoRetry v =<< WD.findElemFrom li (WD.ByClass "value")
1304+ checkInitialItems dm xs = do
1305+ putStrLnDebug "checkInitialItems"
1306+ liftIO $ assertEqual "Wrong amount of items in DOM" (DMap.size dm) (length xs)
1307+ forM_ (zip xs (DMap.toList dm)) $ \(e, k :=> Identity v) -> checkItem e (textKey k) (T.pack $ has @Show k $ show v)
1308+ getAndCheckInitialItems dm = withRetry $ do
1309+ putStrLnDebug "getAndCheckInitialItems"
1310+ xs <- WD.findElems (WD.ByTag "li")
1311+ checkInitialItems dm xs
1312+ pure xs
1313+ checkRemoval chan k = do
1314+ putStrLnDebug "checkRemoval"
1315+ e <- findElemWithRetry (WD.ById $ textKey k)
1316+ liftIO $ writeChan chan $ PatchDMap $ DMap.singleton k (ComposeMaybe Nothing)
1317+ elementShouldBeRemoved e
1318+ checkReplace chan k v = do
1319+ putStrLnDebug "checkReplace"
1320+ e <- findElemWithRetry (WD.ById $ textKey k)
1321+ liftIO $ writeChan chan $ PatchDMap $ DMap.singleton k (ComposeMaybe $ Just $ Identity v)
1322+ elementShouldBeRemoved e
1323+ e' <- findElemWithRetry $ WD.ById $ textKey k
1324+ checkItem e' (textKey k) (T.pack $ show v)
1325+ checkInsert chan k v = do
1326+ putStrLnDebug "checkInsert"
1327+ liftIO $ writeChan chan $ PatchDMap $ DMap.singleton k (ComposeMaybe $ Just $ Identity v)
1328+ e <- findElemWithRetry (WD.ById $ textKey k)
1329+ checkItem e (textKey k) (T.pack $ show v)
1330+ postBuildPatch = PatchDMap $ DMap.fromList [Key_Char :=> ComposeMaybe Nothing, Key_Bool :=> ComposeMaybe (Just $ Identity True)]
1331+ it "doesn't replace elements at switchover, can delete/update/insert" $ runWD $ do
1332+ chan <- liftIO newChan
1333+ let preSwitchover :: WD [WD.Element]
1334+ preSwitchover = getAndCheckInitialItems keyMap
1335+ check :: [WD.Element] -> WD ()
1336+ check xs = do
1337+ checkInitialItems keyMap xs
1338+ checkRemoval chan Key_Int
1339+ checkReplace chan Key_Char 'B'
1340+ checkInsert chan Key_Bool True
1341+ testWidget' preSwitchover check $ do
1342+ (dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap =<< triggerEventWithChan chan
1343+ liftIO $ dmap `H.shouldBe` keyMap
1344+ it "handles postBuild correctly" $ runWD $ do
1345+ chan <- liftIO newChan
1346+ let preSwitchover = getAndCheckInitialItems $ applyAlways postBuildPatch keyMap
1347+ check xs = do
1348+ withRetry $ checkInitialItems (applyAlways postBuildPatch keyMap) xs
1349+ checkRemoval chan Key_Int
1350+ checkInsert chan Key_Char 'B'
1351+ checkReplace chan Key_Bool True
1352+ testWidget' preSwitchover check $ void $ do
1353+ pb <- getPostBuild
1354+ replace <- triggerEventWithChan chan
1355+ (dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap $ leftmost [postBuildPatch <$ pb, replace]
1356+ liftIO $ dmap `H.shouldBe` keyMap
1357+ it "can delete/update/insert when built in prerender" $ runWD $ do
1358+ chan <- liftIO newChan
1359+ let check = do
1360+ _ <- getAndCheckInitialItems keyMap
1361+ checkRemoval chan Key_Int
1362+ checkReplace chan Key_Char 'B'
1363+ checkInsert chan Key_Bool True
1364+ testWidget (pure ()) check $ do
1365+ replace <- triggerEventWithChan chan
1366+ prerender_ (pure ()) $ do
1367+ (dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap replace
1368+ liftIO $ dmap `H.shouldBe` keyMap
1369+ it "can delete/update/insert when built in immediate mode" $ runWD $ do
1370+ chan <- liftIO newChan
1371+ let check = do
1372+ _ <- getAndCheckInitialItems keyMap
1373+ checkRemoval chan Key_Int
1374+ checkReplace chan Key_Char 'B'
1375+ checkInsert chan Key_Bool True
1376+ testWidget (pure ()) check $ void $ do
1377+ pb <- getPostBuild
1378+ runWithReplace (pure ()) $ ffor pb $ \() -> void $ do
1379+ (dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap =<< triggerEventWithChan chan
1380+ liftIO $ dmap `H.shouldBe` keyMap
1381+ -- Should be fixed by prerender changes!
1382+ it "handles postBuild correctly in prerender" $ runWD $ do
1383+ chan <- liftIO newChan
1384+ let check = do
1385+ _ <- getAndCheckInitialItems $ applyAlways postBuildPatch keyMap
1386+ checkRemoval chan Key_Int
1387+ checkInsert chan Key_Char 'B'
1388+ checkReplace chan Key_Bool True
1389+ testWidget (pure ()) check $ do
1390+ replace <- triggerEventWithChan chan
1391+ prerender_ (pure ()) $ void $ do
1392+ pb <- getPostBuild
1393+ (dmap, _evt) <- traverseDMapWithKeyWithAdjust widget keyMap $ leftmost [postBuildPatch <$ pb, replace]
1394+ liftIO $ dmap `H.shouldBe` keyMap
1395+
1396+ session' "traverseIntMapWithKeyWithAdjust" $ do
1397+ let textKeyInt k = "key" <> T.pack (show k)
1398+ intMap = IntMap.fromList
1399+ [ (1, "one")
1400+ , (2, "two")
1401+ , (3, "three")
1402+ ]
1403+ let widget :: DomBuilder t m => IntMap.Key -> Text -> m Text
1404+ widget k v = elAttr "li" ("id" =: textKeyInt k) $ do
1405+ elClass "span" "key" $ text $ textKeyInt k
1406+ elClass "span" "value" $ text v
1407+ pure v
1408+ checkItem :: WD.Element -> Text -> Text -> WD ()
1409+ checkItem li k v = do
1410+ putStrLnDebug "checkItem"
1411+ shouldContainTextNoRetry k =<< WD.findElemFrom li (WD.ByClass "key")
1412+ shouldContainTextNoRetry v =<< WD.findElemFrom li (WD.ByClass "value")
1413+ checkInitialItems dm xs = do
1414+ putStrLnDebug "checkInitialItems"
1415+ liftIO $ assertEqual "Wrong amount of items in DOM" (IntMap.size dm) (length xs)
1416+ forM_ (zip xs (IntMap.toList dm)) $ \(e, (k, v)) -> checkItem e (textKeyInt k) v
1417+ getAndCheckInitialItems dm = withRetry $ do
1418+ putStrLnDebug "getAndCheckInitialItems"
1419+ xs <- WD.findElems (WD.ByTag "li")
1420+ checkInitialItems dm xs
1421+ pure xs
1422+ checkRemoval chan k = do
1423+ putStrLnDebug "checkRemoval"
1424+ e <- findElemWithRetry (WD.ById $ textKeyInt k)
1425+ liftIO $ writeChan chan $ PatchIntMap $ IntMap.singleton k Nothing
1426+ elementShouldBeRemoved e
1427+ checkReplace chan k v = do
1428+ putStrLnDebug "checkReplace"
1429+ e <- findElemWithRetry (WD.ById $ textKeyInt k)
1430+ liftIO $ writeChan chan $ PatchIntMap $ IntMap.singleton k $ Just v
1431+ elementShouldBeRemoved e
1432+ e' <- findElemWithRetry (WD.ById $ textKeyInt k)
1433+ withRetry $ checkItem e' (textKeyInt k) v
1434+ checkInsert chan k v = do
1435+ putStrLnDebug "checkInsert"
1436+ liftIO $ writeChan chan $ PatchIntMap $ IntMap.singleton k $ Just v
1437+ e <- findElemWithRetry (WD.ById $ textKeyInt k)
1438+ checkItem e (textKeyInt k) v
1439+ postBuildPatch = PatchIntMap $ IntMap.fromList [(2, Nothing), (3, Just "trois"), (4, Just "four")]
1440+ xit "doesn't replace elements at switchover, can delete/update/insert" $ runWD $ do
1441+ chan <- liftIO newChan
1442+ let preSwitchover = getAndCheckInitialItems intMap
1443+ check xs = do
1444+ checkInitialItems intMap xs
1445+ checkRemoval chan 1
1446+ checkReplace chan 2 "deux"
1447+ checkInsert chan 4 "four"
1448+ testWidget' preSwitchover check $ void $ do
1449+ (im, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap =<< triggerEventWithChan chan
1450+ liftIO $ im `H.shouldBe` intMap
1451+ xit "handles postBuild correctly" $ runWD $ do
1452+ chan <- liftIO newChan
1453+ let preSwitchover = getAndCheckInitialItems $ applyAlways postBuildPatch intMap
1454+ check xs = do
1455+ withRetry $ checkInitialItems (applyAlways postBuildPatch intMap) xs
1456+ checkRemoval chan 1
1457+ checkInsert chan 2 "deux"
1458+ checkReplace chan 3 "trois"
1459+ testWidget' preSwitchover check $ void $ do
1460+ pb <- getPostBuild
1461+ replace <- triggerEventWithChan chan
1462+ (dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap $ leftmost [postBuildPatch <$ pb, replace]
1463+ liftIO $ dmap `H.shouldBe` intMap
1464+ xit "can delete/update/insert when built in prerender" $ runWD $ do
1465+ chan <- liftIO newChan
1466+ let check = do
1467+ _ <- getAndCheckInitialItems intMap
1468+ checkRemoval chan 1
1469+ checkReplace chan 2 "deux"
1470+ checkInsert chan 4 "quatre"
1471+ testWidget (pure ()) check $ do
1472+ replace <- triggerEventWithChan chan
1473+ prerender_ (pure ()) $ do
1474+ (dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap replace
1475+ liftIO $ dmap `H.shouldBe` intMap
1476+ xit "can delete/update/insert when built in immediate mode" $ runWD $ do
1477+ chan <- liftIO newChan
1478+ let check = do
1479+ _ <- getAndCheckInitialItems intMap
1480+ checkRemoval chan 1
1481+ checkReplace chan 2 "deux"
1482+ checkInsert chan 4 "quatre"
1483+ testWidget (pure ()) check $ void $ do
1484+ pb <- getPostBuild
1485+ runWithReplace (pure ()) $ ffor pb $ \() -> void $ do
1486+ (dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap =<< triggerEventWithChan chan
1487+ liftIO $ dmap `H.shouldBe` intMap
1488+ -- Should be fixed by prerender changes!
1489+ xit "handles postBuild correctly in prerender" $ runWD $ do
1490+ chan <- liftIO newChan
1491+ let check = do
1492+ _ <- getAndCheckInitialItems $ applyAlways postBuildPatch intMap
1493+ checkRemoval chan 1
1494+ checkInsert chan 2 "deux"
1495+ checkReplace chan 3 "trois"
1496+ testWidget (pure ()) check $ do
1497+ replace <- triggerEventWithChan chan
1498+ prerender_ (pure ()) $ void $ do
1499+ pb <- getPostBuild
1500+ (dmap, _evt) <- traverseIntMapWithKeyWithAdjust widget intMap $ leftmost [postBuildPatch <$ pb, replace]
1501+ liftIO $ dmap `H.shouldBe` intMap
1502+
1503+ session' "traverseDMapWithKeyWithAdjustWithMove" $ do
1504+ let widget :: DomBuilder t m => Key2 a -> Identity a -> m (Identity a)
1505+ widget k (Identity v) = elAttr "li" ("id" =: textKey2 k) $ do
1506+ elClass "span" "key" $ text $ textKey2 k
1507+ elClass "span" "value" $ text $ T.pack $ has @Show k $ show v
1508+ pure (Identity v)
1509+ textKey2 :: Key2 a -> Text
1510+ textKey2 = \case
1511+ Key2_Int i -> "i" <> T.pack (show i)
1512+ Key2_Char c -> "c" <> T.pack [c]
1513+ checkItem :: WD.Element -> Text -> Text -> WD ()
1514+ checkItem li k v = do
1515+ shouldContainTextNoRetry k =<< WD.findElemFrom li (WD.ByClass "key")
1516+ shouldContainTextNoRetry v =<< WD.findElemFrom li (WD.ByClass "value")
1517+ checkInitialItems dm xs = do
1518+ liftIO $ assertEqual "Wrong amount of items in DOM" (DMap.size dm) (length xs)
1519+ forM_ (zip xs (DMap.toList dm)) $ \(e, k :=> Identity v) -> checkItem e (textKey2 k) (T.pack $ has @Show k $ show v)
1520+ getAndCheckInitialItems dm = withRetry $ do
1521+ xs <- WD.findElems (WD.ByTag "li")
1522+ checkInitialItems dm xs
1523+ pure xs
1524+ moveSpec
1525+ :: (DMap Key2 Identity -> (WD.Element -> Chan (PatchDMapWithMove Key2 Identity) -> WD ()) -> WD ())
1526+ -> H.SpecM (WdTestSession ()) ()
1527+ moveSpec testMove = do
1528+ it "can insert an item" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 3 ==> 3]) $ \body chan -> do
1529+ shouldContainText (T.strip $ T.unlines ["i11","i33"]) body
1530+ liftIO $ writeChan chan (insertDMapKey (Key2_Int 2) 2)
1531+ shouldContainText (T.strip $ T.unlines ["i11","i22","i33"]) body
1532+ it "can delete an item" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 2 ==> 2, Key2_Int 3 ==> 3]) $ \body chan -> do
1533+ shouldContainText (T.strip $ T.unlines ["i11","i22","i33"]) body
1534+ liftIO $ writeChan chan (deleteDMapKey (Key2_Int 2))
1535+ shouldContainText (T.strip $ T.unlines ["i11","i33"]) body
1536+ it "can swap items" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 2 ==> 2, Key2_Int 3 ==> 3, Key2_Int 4 ==> 4]) $ \body chan -> do
1537+ shouldContainText (T.strip $ T.unlines ["i11","i22","i33","i44"]) body
1538+ liftIO $ writeChan chan (swapDMapKey (Key2_Int 2) (Key2_Int 3))
1539+ shouldContainText (T.strip $ T.unlines ["i11","i33","i22","i44"]) body
1540+-- TODO re-enable this
1541+-- it "can move items" $ runWD $ testMove (DMap.fromList [Key2_Int 1 ==> 1, Key2_Int 2 ==> 2, Key2_Int 3 ==> 3, Key2_Int 4 ==> 4]) $ \body chan -> do
1542+-- shouldContainText (T.strip $ T.unlines ["i11","i22","i33", "i44"]) body
1543+-- liftIO $ writeChan chan (moveDMapKey (Key2_Int 2) (Key2_Int 3))
1544+-- shouldContainText (T.strip $ T.unlines ["i11","i22","i44"]) body
1545+-- liftIO $ writeChan chan (moveDMapKey (Key2_Int 2) (Key2_Int 3)) -- attempt a move to nonexistent key should delete
1546+-- shouldContainText (T.strip $ T.unlines ["i11","i44"]) body
1547+-- liftIO $ writeChan chan (moveDMapKey (Key2_Int 2) (Key2_Int 3)) -- this causes a JSException in immediate builder too
1548+-- shouldContainText (T.strip $ T.unlines ["i11","i44"]) body
1549+-- liftIO $ writeChan chan (insertDMapKey (Key2_Int 2) 2) -- this step will fail if the above caused an exception, thus works as a proxy for detecting the exception given we can't catch it
1550+-- shouldContainText (T.strip $ T.unlines ["i11","i22","i44"]) body
1551+
1552+ describe "hydration" $ moveSpec $ \initMap test -> do
1553+ chan <- liftIO newChan
1554+ let preSwitchover = getAndCheckInitialItems initMap
1555+ check xs = do
1556+ checkInitialItems initMap xs
1557+ body <- getBody
1558+ test body chan
1559+ testWidget' preSwitchover check $ void $ do
1560+ (dmap, _evt) <- traverseDMapWithKeyWithAdjustWithMove widget initMap =<< triggerEventWithChan chan
1561+ liftIO $ assertEqual "DMap" initMap dmap
1562+
1563+ describe "hydration/immediate" $ moveSpec $ \initMap test -> do
1564+ chan <- liftIO newChan
1565+ replace <- liftIO newChan
1566+ lock :: MVar () <- liftIO newEmptyMVar
1567+ let check = do
1568+ liftIO $ do
1569+ writeChan replace ()
1570+ takeMVar lock
1571+ xs <- getAndCheckInitialItems initMap
1572+ checkInitialItems initMap xs
1573+ body <- getBody
1574+ test body chan
1575+ testWidget (pure ()) check $ void $ do
1576+ e <- triggerEventWithChan replace
1577+ runWithReplace (pure ()) $ ffor e $ \() -> void $ do
1578+ pb <- getPostBuild
1579+ performEvent_ $ liftIO (putMVar lock ()) <$ pb
1580+ (dmap, _evt) <- traverseDMapWithKeyWithAdjustWithMove widget initMap =<< triggerEventWithChan chan
1581+ liftIO $ assertEqual "DMap" initMap dmap
1582+
1583+ session' "hydrating invalid HTML" $ do
1584+ xit "can hydrate list in paragraph" $ runWD $ do
1585+ let preSwitchover = do
1586+ checkBodyText "before\ninner\nafter"
1587+ -- Two <p> tags should be present
1588+ (p1, p2) <- WD.findElems (WD.ByTag "p") >>= \case
1589+ [p1, p2] -> pure (p1, p2)
1590+ _ -> error "Unexpected number of `p` tags (expected 2)"
1591+ ol <- findElemWithRetry (WD.ByTag "ol")
1592+ shouldContainText "before" p1
1593+ shouldContainText "inner" ol
1594+ shouldContainText "" p2
1595+ pure (p1, ol, p2)
1596+ check (p1, ol, p2) = do
1597+ checkBodyText "before\ninner\nafter"
1598+ shouldContainText "before\ninner\nafter" p1
1599+ elementShouldBeRemoved ol
1600+ elementShouldBeRemoved p2
1601+ -- Don't fail fatally when hydration encounters the invalid DOM
1602+ testWidgetDebug' False withDebugging preSwitchover check $ do
1603+ -- This is deliberately invalid HTML, the browser will interpret it as
1604+ -- <p>before</p><ol>inner</ol>after<p></p>
1605+ el "p" $ do
1606+ text "before"
1607+ el "ol" $ text "inner"
1608+ text "after"
1609+
1610+ -- TODO: This test presupposes the exact set of labels that "dropdown" places in the "value" fields to distinguish options.
1611+ -- This dependence on internal implementation details is undesirable in a test case, but seems fairly tricky to avoid.
1612+ -- It seems expedient for the time being to expect this test case to be updated, should those implementation details ever change.
1613+ session' "dropdown" $ do
1614+ let doTest expectedOpts (initialValue :: Text) = do
1615+ let doCheck = do
1616+ es <- findElemsWithRetry $ WD.ByTag "option"
1617+ opts <- mapM fetchElement es
1618+ assertEqual "missing/extra/incorrect option element(s)" expectedOpts (sort opts)
1619+ testWidget doCheck doCheck $ do
1620+ void $ dropdown initialValue (constDyn (("aa" :: Text) =: "aaa" <> "bb" =: "bbb")) def
1621+ fetchElement e = do
1622+ val <- WD.attr e "value"
1623+ sel <- WD.attr e "selected"
1624+ return (fromMaybe "" val, isJust sel)
1625+ -- The "aa" test case is important, but a good test implementation probably needs to avoid selenium, because HTML parsers will insert a "selected" attribute on the first "option" tag if no selected attributes are present; thus as written, this erroneously succeeds on the old implementation (but properly implemented, should fail)
1626+ -- Thus, it would appear that we do actually need a HTML5 or maybe XML parser for this test suite.
1627+ xit "statically renders initial values (on aa)" $ runWD $ do
1628+ doTest [("0",True),("1",False)] "aa"
1629+ -- These tests are currently marked "pending" (by using "xit" instead of "it") because this test has a high chance of non-deterministically failing, which is a problem elsewhere in this test suite as well
1630+ xit "statically renders initial values (on bb)" $ runWD $ do
1631+ doTest [("0",False),("1",True)] "bb"
1632+
1633+data Selenium = Selenium
1634+ { _selenium_portNumber :: PortNumber
1635+ , _selenium_stopServer :: IO ()
1636+ }
1637+
1638+startSeleniumServer :: PortNumber -> IO (IO ())
1639+startSeleniumServer port = do
1640+ (_,_,_,ph) <- createProcess $ (proc "selenium-server" ["-port", show port])
1641+ { std_in = NoStream
1642+ , std_out = NoStream
1643+ , std_err = NoStream
1644+ }
1645+ return $ terminateProcess ph
1646+
1647+withSeleniumServer :: (Selenium -> IO ()) -> IO ()
1648+withSeleniumServer f = do
1649+ stopServer <- startSeleniumServer seleniumPort
1650+ threadDelay $ 1000 * 1000 * 2 -- TODO poll or wait on a a signal to block on
1651+ f $ Selenium
1652+ { _selenium_portNumber = seleniumPort
1653+ , _selenium_stopServer = stopServer
1654+ }
1655+
1656+triggerEventWithChan :: (Reflex t, TriggerEvent t m, Prerender js t m) => Chan a -> m (Event t a)
1657+triggerEventWithChan chan = do
1658+ (e, trigger) <- newTriggerEvent
1659+ -- In prerender because we only want to do this on the client
1660+ prerender_ (pure ()) $ void $ liftIO $ forkIO $ forever $ trigger =<< readChan chan
1661+ pure e
1662+
1663+shouldBeWithRetryM :: (Eq a, Show a) => WD a -> a -> WD ()
1664+shouldBeWithRetryM m expected = withRetry $ do
1665+ got <- m
1666+ got `shouldBe` expected
1667+
1668+assertAttr :: WD.Element -> Text -> Maybe Text -> WD ()
1669+assertAttr e k v = liftIO . assertEqual "Incorrect attribute value" v =<< WD.attr e k
1670+
1671+elementShouldBeRemoved :: WD.Element -> WD ()
1672+elementShouldBeRemoved e = withRetry $ do
1673+ try (WD.getText e) >>= \case
1674+ Left (WD.FailedCommand WD.StaleElementReference _) -> return ()
1675+ Left err -> throwM err
1676+ Right !_ -> liftIO $ assertFailure "Expected element to be removed, but it still exists"
1677+
1678+shouldContainText :: Text -> WD.Element -> WD ()
1679+shouldContainText t = withRetry . shouldContainTextNoRetry t
1680+
1681+shouldContainTextNoRetry :: Text -> WD.Element -> WD ()
1682+shouldContainTextNoRetry t = flip shouldBe t <=< WD.getText
1683+
1684+checkBodyText :: Text -> WD ()
1685+checkBodyText = checkTextInTag "body"
1686+
1687+checkTextInTag :: Text -> Text -> WD ()
1688+checkTextInTag t expected = do
1689+ e <- findElemWithRetry (WD.ByTag t)
1690+ shouldContainText expected e
1691+
1692+checkTextInId :: Text -> Text -> WD ()
1693+checkTextInId i expected = do
1694+ e <- findElemWithRetry (WD.ById i)
1695+ shouldContainText expected e
1696+
1697+findElemWithRetry :: Selector -> WD WD.Element
1698+findElemWithRetry = withRetry . WD.findElem
1699+
1700+findElemsWithRetry :: Selector -> WD [WD.Element]
1701+findElemsWithRetry = withRetry . WD.findElems
1702+
1703+getBody :: WD WD.Element
1704+getBody = WD.findElem $ WD.ByTag "body"
1705+
1706+withRetry :: forall a. WD a -> WD a
1707+withRetry a = wait 300
1708+ where wait :: Int -> WD a
1709+ wait 0 = a
1710+ wait n = try a >>= \case
1711+ Left (e :: SomeException) -> do
1712+ liftIO $ putStrLn ("(retrying due to " <> show e <> ")") *> threadDelay 100000
1713+ wait $ n - 1
1714+ Right v -> return v
1715+
1716+divId :: DomBuilder t m => Text -> m a -> m a
1717+divId i = elAttr "div" ("id" =: i)
1718+
1719+type TestWidget js t m = (DomBuilder t m, MonadHold t m, PostBuild t m, Prerender js t m, PerformEvent t m, TriggerEvent t m, MonadFix m, MonadIO (Performable m), MonadIO m)
1720+
1721+testWidgetStaticDebug
1722+ :: Bool
1723+ -> WD b
1724+ -- ^ Webdriver commands to run before JS runs and after hydration switchover
1725+ -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
1726+ -- ^ Widget we are testing
1727+ -> WD b
1728+testWidgetStaticDebug withDebugging w = testWidgetDebug True withDebugging (void w) w
1729+
1730+-- | TODO: do something about JSExceptions not causing tests to fail
1731+testWidgetDebug
1732+ :: Bool
1733+ -> Bool
1734+ -> WD ()
1735+ -- ^ Webdriver commands to run before the JS runs (i.e. on the statically rendered page)
1736+ -> WD b
1737+ -- ^ Webdriver commands to run after hydration switchover
1738+ -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
1739+ -- ^ Widget we are testing
1740+ -> WD b
1741+testWidgetDebug hardFailure withDebugging beforeJS afterSwitchover =
1742+ testWidgetDebug' hardFailure withDebugging beforeJS (const afterSwitchover)
1743+
1744+data HydrationFailedException = HydrationFailedException deriving Show
1745+instance Exception HydrationFailedException
1746+
1747+-- | TODO: do something about JSExceptions not causing tests to fail
1748+testWidgetDebug'
1749+ :: Bool
1750+ -> Bool
1751+ -> WD a
1752+ -- ^ Webdriver commands to run before the JS runs (i.e. on the statically rendered page)
1753+ -> (a -> WD b)
1754+ -- ^ Webdriver commands to run after hydration switchover
1755+ -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
1756+ -- ^ Widget we are testing (contents of body)
1757+ -> WD b
1758+testWidgetDebug' hardFailure withDebugging beforeJS afterSwitchover bodyWidget = do
1759+ let putStrLnDebug :: MonadIO m => Text -> m ()
1760+ putStrLnDebug m = when withDebugging $ liftIO $ putStrLn $ T.unpack m
1761+ staticApp = do
1762+ el "head" $ pure ()
1763+ el "body" $ do
1764+ bodyWidget
1765+ el "script" $ text $ TE.decodeUtf8 $ LBS.toStrict $ jsaddleJs False
1766+ putStrLnDebug "rendering static"
1767+ ((), html) <- liftIO $ renderStatic $ runHydratableT staticApp
1768+ putStrLnDebug "rendered static"
1769+ waitBeforeJS <- liftIO newEmptyMVar -- Empty until JS should be run
1770+ onFailure <- if hardFailure then (`throwTo` HydrationFailedException) <$> liftIO myThreadId else pure $ pure ()
1771+ waitUntilSwitchover <- liftIO newEmptyMVar -- Empty until switchover
1772+ let entryPoint = do
1773+ putStrLnDebug "taking waitBeforeJS"
1774+ liftIO $ takeMVar waitBeforeJS
1775+ let switchOverAction = do
1776+ putStrLnDebug "switchover syncPoint"
1777+ syncPoint
1778+ putStrLnDebug "putting waitUntilSwitchover"
1779+ liftIO $ putMVar waitUntilSwitchover ()
1780+ putStrLnDebug "put waitUntilSwitchover"
1781+ putStrLnDebug "running mainHydrationWidgetWithSwitchoverAction"
1782+ mainHydrationWidgetWithSwitchoverActionWithFailure' onFailure switchOverAction blank bodyWidget
1783+ putStrLnDebug "syncPoint after mainHydrationWidgetWithSwitchoverAction"
1784+ syncPoint
1785+ application <- liftIO $ jsaddleOr defaultConnectionOptions entryPoint $ \_ sendResponse -> do
1786+ putStrLnDebug "sending response"
1787+ r <- sendResponse $ responseLBS status200 [] $ "<!doctype html>\n" <> LBS.fromStrict html
1788+ putStrLnDebug "sent response"
1789+ return r
1790+ waitJSaddle <- liftIO newEmptyMVar
1791+ let settings = foldr ($) Warp.defaultSettings
1792+ [ Warp.setPort $ fromIntegral $ toInteger jsaddlePort
1793+ , Warp.setBeforeMainLoop $ do
1794+ putStrLnDebug "putting waitJSaddle"
1795+ putMVar waitJSaddle ()
1796+ putStrLnDebug "put waitJSaddle"
1797+ ]
1798+ -- hSilence to get rid of ConnectionClosed logs
1799+ silenceIfDebug = if withDebugging then id else hSilence [stderr]
1800+ jsaddleWarp = silenceIfDebug $ Warp.runSettings settings application
1801+ withAsync' jsaddleWarp $ do
1802+ putStrLnDebug "taking waitJSaddle"
1803+ liftIO $ takeMVar waitJSaddle
1804+ putStrLnDebug "opening page"
1805+ WD.openPage $ "http://localhost:" <> show jsaddlePort
1806+ putStrLnDebug "running beforeJS"
1807+ a <- beforeJS
1808+ putStrLnDebug "putting waitBeforeJS"
1809+ liftIO $ putMVar waitBeforeJS ()
1810+ putStrLnDebug "taking waitUntilSwitchover"
1811+ liftIO $ takeMVar waitUntilSwitchover
1812+ putStrLnDebug "running afterSwitchover"
1813+ afterSwitchover a
1814+
1815+withAsync' :: (MonadIO m, MonadMask m) => IO a -> m b -> m b
1816+withAsync' f g = bracket
1817+ (liftIO $ Async.async f)
1818+ (liftIO . Async.uninterruptibleCancel)
1819+ (const g)
1820+
1821+data Key2 a where
1822+ Key2_Int :: Int -> Key2 Int
1823+ Key2_Char :: Char -> Key2 Char
1824+
1825+deriveGEq ''Key2
1826+deriveGCompare ''Key2
1827+deriveGShow ''Key2
1828+deriveArgDict ''Key2
reflex-dom-test-selenium/CHANGELOG.mdnew file+5
@@ -0,0 +1,5 @@
1+# Revision history for reflex-dom-core-selenium
2+
3+## 0.1.0.0 -- YYYY-mm-dd
4+
5+* First version. Released on an unsuspecting world.
reflex-dom-test-selenium/LICENSEnew file+12
@@ -0,0 +1,12 @@
1+Copyright (c) 2020, Obsidian Systems LLC
2+All rights reserved.
3+
4+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5+
6+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7+
8+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9+
10+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11+
12+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
reflex-dom-test-selenium/Setup.hsnew file+2
@@ -0,0 +1,2 @@
1+import Distribution.Simple
2+main = defaultMain
reflex-dom-test-selenium/add-overrides.nixnew file+20
@@ -0,0 +1,20 @@
1+{ nixpkgs }: testPackage:
2+ nixpkgs.haskell.lib.overrideCabal testPackage
3+ (drv: {
4+
5+ # The headless browser run as part of the tests will exit without this
6+ preBuild = ''
7+ export HOME="$PWD"
8+ '';
9+
10+ testSystemDepends = with nixpkgs; (drv.testSystemDepends or []) ++ [
11+ selenium-server-standalone which
12+ chromium
13+ nixpkgs.iproute
14+ ];
15+
16+ # The headless browser run as part of gc tests would hang/crash without this
17+ preCheck = ''
18+ export FONTCONFIG_PATH=${nixpkgs.fontconfig.out}/etc/fonts
19+ '';
20+ })
reflex-dom-test-selenium/reflex-dom-test-selenium.cabalnew file+41
@@ -0,0 +1,41 @@
1+cabal-version: 1.24
2+Name: reflex-dom-test-selenium
3+Version: 0.0.0.1
4+Synopsis: Testing framework for selenium tests
5+Description:
6+License: BSD3
7+License-file: LICENSE
8+Author: Ryan Trinkle
9+Maintainer: ryan.trinkle@gmail.com
10+Stability: Experimental
11+Category: FRP, Web, GUI, HTML, Javascript, Reactive, Reactivity, User Interfaces, User-interface
12+Build-type: Simple
13+
14+library
15+ hs-source-dirs: src
16+ build-depends:
17+ async,
18+ base >= 4.7 && < 4.15,
19+ bytestring == 0.10.*,
20+ chrome-test-utils,
21+ exceptions,
22+ hspec-core,
23+ hspec-webdriver >= 1.2.1,
24+ http-types,
25+ jsaddle >= 0.9.0.0 && < 0.10,
26+ jsaddle-warp,
27+ network,
28+ process,
29+ reflex-dom-core,
30+ silently,
31+ text == 1.2.*,
32+ wai,
33+ warp,
34+ webdriver,
35+ websockets
36+
37+ exposed-modules:
38+ Reflex.Dom.Test.Selenium
39+
40+ default-language: Haskell98
41+ ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans -fspecialise-aggressively
reflex-dom-test-selenium/src/Reflex/Dom/Test/Selenium.hsnew file+249
@@ -0,0 +1,249 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE FlexibleContexts #-}
3+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4+{-# LANGUAGE OverloadedStrings #-}
5+{-# LANGUAGE RankNTypes #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+{-# LANGUAGE StandaloneDeriving #-}
8+{-# LANGUAGE TemplateHaskell #-}
9+
10+{-# OPTIONS_GHC -fno-warn-orphans #-}
11+
12+-- | Utilities for testing reflex-dom widgets with Selenium.
13+--
14+-- Any uses of the 'testWidget' functions will start a jsaddle warp server and
15+-- serve the given widget in an otherwise empty page. Webdriver commands can run
16+-- on the statically rendered page, and on the hydrated page.
17+module Reflex.Dom.Test.Selenium
18+ ( TestWidget
19+ , TestWidgetConfig (..)
20+ , testWidget, testWidget', testWidgetStatic, testWidgetHydrated
21+ , withSeleniumSpec
22+ , embedSpec
23+ , SeleniumSetupConfig (..)
24+ ) where
25+
26+import Control.Concurrent (threadDelay, newEmptyMVar, takeMVar, putMVar)
27+import Control.Exception (throwIO)
28+import Control.Monad (when)
29+import Control.Monad.Catch (MonadMask, handle)
30+import Control.Monad.Fix (MonadFix)
31+import Control.Monad.IO.Class (MonadIO, liftIO)
32+import Data.Text (Text)
33+import Language.Javascript.JSaddle
34+import Language.Javascript.JSaddle.Warp
35+import Network.HTTP.Types (status200)
36+import Network.Socket (PortNumber)
37+import Network.Wai (responseLBS)
38+import Network.WebSockets (defaultConnectionOptions)
39+import Reflex.Dom.Core
40+import System.IO (stderr)
41+import System.IO.Silently (hSilence)
42+import System.Process (std_in, std_out, std_err, createProcess, proc, StdStream (..), terminateProcess)
43+import Test.Hspec.WebDriver (Spec, SpecWith, WdTestSession, sessionWith, using)
44+import Test.Util.ChromeFlags
45+import Test.Util.UnshareNetwork
46+import Test.WebDriver (WD)
47+
48+import qualified Control.Concurrent.Async as Async
49+import qualified Data.ByteString.Lazy as LBS
50+import qualified Data.Text as T
51+import qualified Data.Text.Encoding as TE
52+import qualified Network.Wai.Handler.Warp as Warp
53+import qualified Test.Hspec.Core.Spec as Hspec
54+import qualified Test.WebDriver as WD
55+import qualified Test.WebDriver.Capabilities as WD
56+
57+deriving instance MonadMask WD
58+
59+data SeleniumSetupConfig = SeleniumSetupConfig
60+ { _seleniumSetupConfig_chromiumPath :: FilePath
61+ -- ^ Path to the chromium executable
62+ , _seleniumSetupConfig_headless :: Bool
63+ -- ^ True means that the browser is invoked in headless mode, False means that
64+ -- the user can see the interaction happening on the browser (useful for debugging).
65+ , _seleniumSetupConfig_seleniumPort :: PortNumber
66+ -- ^ The port number used by selenium
67+ }
68+
69+-- | Setup a selenium server and use it to run some hspec tests.
70+--
71+-- withSeleniumSpec config $ \runSession -> hspec $ do
72+-- describe "tests using webdriver session" $ runSession $ do
73+-- webdriver tests here
74+withSeleniumSpec :: SeleniumSetupConfig -> ((forall multi. SpecWith (WdTestSession multi) -> Spec) -> IO a) -> IO a
75+withSeleniumSpec config runSpec = do
76+ liftIO $ handle (\(_ :: IOError) -> return ()) $ unshareNetork -- If we run into an exception with sandboxing, just don't bother
77+ withSandboxedChromeFlags (_seleniumSetupConfig_headless config) $ \chromeFlags -> do
78+ withSeleniumServer (_seleniumSetupConfig_seleniumPort config) $ do
79+ let browserPath = T.strip $ T.pack $ _seleniumSetupConfig_chromiumPath config
80+ when (T.null browserPath) $ fail "No browser found"
81+ let wdConfig = WD.defaultConfig { WD.wdPort = fromIntegral $ _seleniumSetupConfig_seleniumPort config }
82+ chromeCaps' = WD.getCaps $ chromeConfig browserPath chromeFlags
83+ runSpec $ sessionWith wdConfig "" . using [(chromeCaps', "chrome")]
84+
85+startSeleniumServer :: PortNumber -> IO (IO ())
86+startSeleniumServer port = do
87+ (_,_,_,ph) <- createProcess $ (proc "selenium-server" ["-port", show port])
88+ { std_in = NoStream
89+ , std_out = NoStream
90+ , std_err = NoStream
91+ }
92+ return $ terminateProcess ph
93+
94+withSeleniumServer :: PortNumber -> IO a -> IO a
95+withSeleniumServer port f = bracket (startSeleniumServer port) id $ \_ -> do
96+ threadDelay $ 1000 * 1000 * 2 -- TODO poll or wait on a a signal to block on
97+ f
98+
99+chromeConfig :: Text -> [Text] -> WD.WDConfig
100+chromeConfig fp flags =
101+ WD.useBrowser
102+ (WD.chrome { WD.chromeBinary = Just $ T.unpack fp, WD.chromeOptions = T.unpack <$> flags })
103+ WD.defaultConfig
104+
105+--------------------------------------------------------------------------------
106+-- Function to test widgets
107+--------------------------------------------------------------------------------
108+
109+-- | The environment in which your widgets can be tested
110+type TestWidget js t m =
111+ (DomBuilder t m, MonadHold t m, PostBuild t m
112+ , Prerender js t m, PerformEvent t m, TriggerEvent t m
113+ , MonadFix m, MonadIO (Performable m), MonadIO m)
114+
115+-- | Configuration of individual tests
116+data TestWidgetConfig = TestWidgetConfig
117+ { _testWidgetConfig_debug :: Bool
118+ -- ^ If this flag is set to True, during the test we will emit debug messages
119+ , _testWidgetConfig_headWidget :: (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
120+ -- ^ We can add widgets here that will be included in the head of the page
121+ -- (useful for example to include external js libraries in the tests)
122+ , _testWidgetConfig_jsaddlePort :: PortNumber
123+ -- ^ Port used by the jsaddle server
124+ }
125+
126+-- | Test a widget by running some webdriver commands before and after
127+-- hydration.
128+testWidget
129+ :: TestWidgetConfig
130+ -> WD a
131+ -- ^ Webdriver commands to run before the JS runs (i.e. on the statically rendered page)
132+ -> WD b
133+ -- ^ Webdriver commands to run after hydration switchover
134+ -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
135+ -- ^ Widget we are testing (contents of body)
136+ -> WD b
137+testWidget cfg before after widget = testWidget' cfg before (const after) widget
138+
139+-- | Test a widget by running some webdriver commands before hydration (on the
140+-- statically rendered page).
141+testWidgetStatic
142+ :: TestWidgetConfig
143+ -> WD a
144+ -- ^ Webdriver commands to run before the JS runs (i.e. on the statically rendered page)
145+ -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
146+ -- ^ Widget we are testing (contents of body)
147+ -> WD a
148+testWidgetStatic cfg before widget = testWidget' cfg before pure widget
149+
150+-- | Test a widget by running some webdriver commands after hydration.
151+testWidgetHydrated
152+ :: TestWidgetConfig
153+ -> WD b
154+ -- ^ Webdriver commands to run after hydration switchover
155+ -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
156+ -- ^ Widget we are testing (contents of body)
157+ -> WD b
158+testWidgetHydrated cfg after widget = testWidget' cfg (pure ()) (const after) widget
159+
160+-- | Test a widget by running some webdriver commands before and after
161+-- hydration. Like 'testWidget', but you can use the result of the webdriver
162+-- commands from before hydration in the post hydration test.
163+testWidget'
164+ :: TestWidgetConfig
165+ -> WD a
166+ -- ^ Webdriver commands to run before the JS runs (i.e. on the statically rendered page)
167+ -> (a -> WD b)
168+ -- ^ Webdriver commands to run after hydration switchover
169+ -> (forall m js. TestWidget js (SpiderTimeline Global) m => m ())
170+ -- ^ Widget we are testing (contents of body)
171+ -> WD b
172+testWidget' (TestWidgetConfig withDebugging headWidget jsaddlePort) beforeJS afterSwitchover bodyWidget = do
173+ let putStrLnDebug :: MonadIO m => Text -> m ()
174+ putStrLnDebug m = when withDebugging $ liftIO $ putStrLn $ T.unpack m
175+ staticApp = do
176+ el "head" $ headWidget
177+ el "body" $ do
178+ bodyWidget
179+ el "script" $ text $ TE.decodeUtf8 $ LBS.toStrict $ jsaddleJs False
180+ putStrLnDebug "rendering static"
181+ ((), html) <- liftIO $ renderStatic $ runHydratableT staticApp
182+ putStrLnDebug "rendered static"
183+ waitBeforeJS <- liftIO newEmptyMVar -- Empty until JS should be run
184+ waitUntilSwitchover <- liftIO newEmptyMVar -- Empty until switchover
185+ let entryPoint = do
186+ putStrLnDebug "taking waitBeforeJS"
187+ liftIO $ takeMVar waitBeforeJS
188+ let switchOverAction = do
189+ putStrLnDebug "switchover syncPoint"
190+ syncPoint
191+ putStrLnDebug "putting waitUntilSwitchover"
192+ liftIO $ putMVar waitUntilSwitchover ()
193+ putStrLnDebug "put waitUntilSwitchover"
194+ putStrLnDebug "running mainHydrationWidgetWithSwitchoverAction"
195+ mainHydrationWidgetWithSwitchoverAction switchOverAction blank bodyWidget
196+ putStrLnDebug "syncPoint after mainHydrationWidgetWithSwitchoverAction"
197+ syncPoint
198+ application <- liftIO $ jsaddleOr defaultConnectionOptions entryPoint $ \_ sendResponse -> do
199+ putStrLnDebug "sending response"
200+ r <- sendResponse $ responseLBS status200 [] $ "<!doctype html>\n" <> LBS.fromStrict html
201+ putStrLnDebug "sent response"
202+ return r
203+ waitJSaddle <- liftIO newEmptyMVar
204+ let settings = foldr ($) Warp.defaultSettings
205+ [ Warp.setPort $ fromIntegral $ toInteger jsaddlePort
206+ , Warp.setBeforeMainLoop $ do
207+ putStrLnDebug "putting waitJSaddle"
208+ putMVar waitJSaddle ()
209+ putStrLnDebug "put waitJSaddle"
210+ ]
211+ -- hSilence to get rid of ConnectionClosed logs
212+ silenceIfNotDebugging = if withDebugging then id else hSilence [stderr]
213+ jsaddleWarp = silenceIfNotDebugging $ Warp.runSettings settings application
214+ withAsync' jsaddleWarp $ do
215+ putStrLnDebug "taking waitJSaddle"
216+ liftIO $ takeMVar waitJSaddle
217+ putStrLnDebug "opening page"
218+ WD.openPage $ "http://localhost:" <> show jsaddlePort
219+ putStrLnDebug "running beforeJS"
220+ a <- beforeJS
221+ putStrLnDebug "putting waitBeforeJS"
222+ liftIO $ putMVar waitBeforeJS ()
223+ putStrLnDebug "taking waitUntilSwitchover"
224+ liftIO $ takeMVar waitUntilSwitchover
225+ putStrLnDebug "running afterSwitchover"
226+ afterSwitchover a
227+
228+--------------------------------------------------------------------------------
229+-- Utilities
230+--------------------------------------------------------------------------------
231+
232+-- | Embed a different spec type by evaluating it directly.
233+embedSpec :: (Hspec.Example a, MonadIO m) => Hspec.Arg a -> a -> m ()
234+embedSpec arg spec = liftIO $ do
235+ Hspec.Result _info status <- Hspec.evaluateExample
236+ spec
237+ Hspec.defaultParams
238+ (\actionWith -> actionWith arg)
239+ (\_ -> pure ())
240+ case status of
241+ Hspec.Success -> pure ()
242+ Hspec.Pending _ _ -> pure () -- should not happen
243+ failure -> throwIO failure
244+
245+withAsync' :: (MonadIO m, MonadMask m) => IO a -> m b -> m b
246+withAsync' f g = bracket
247+ (liftIO $ Async.async f)
248+ (liftIO . Async.uninterruptibleCancel)
249+ (const g)
reflex-dom.cabaldeleted−117
@@ -1,117 +0,0 @@
1−Name: reflex-dom
2−Version: 0.3
3−Synopsis: Functional Reactive Web Apps with Reflex
4−Description: Reflex-DOM is a Functional Reactive web framework based on the Reflex FRP engine
5−License: BSD3
6−License-file: LICENSE
7−Author: Ryan Trinkle
8−Maintainer: ryan.trinkle@gmail.com
9−Stability: Experimental
10−Category: FRP, Web, GUI, HTML, Javascript, Reactive, Reactivity, User Interfaces, User-interface
11−Build-type: Simple
12−Cabal-version: >=1.9.2
13−-- Deal with https://github.com/haskell/cabal/issues/2544 / https://github.com/haskell/cabal/issues/367
14−extra-source-files: src-ghc/Reflex/Dom/Internal/Foreign.hs
15− src-ghc/Reflex/Dom/Xhr/Foreign.hs
16− src-ghc/Reflex/Dom/WebSocket/Foreign.hs
17− src-ghcjs/Reflex/Dom/Internal/Foreign.hs
18− src-ghcjs/Reflex/Dom/Xhr/Foreign.hs
19− src-ghcjs/Reflex/Dom/WebSocket/Foreign.hs
20− src/Reflex/Dom/Xhr/ResponseType.hs
21− src/Reflex/Dom/Xhr/Exception.hs
22−
23−library
24− hs-source-dirs: src
25− build-depends:
26− base >= 4.7 && < 4.10,
27− template-haskell,
28− stm == 2.4.*,
29− reflex == 0.4.*,
30− dependent-sum == 0.3.*,
31− dependent-map == 0.2.*,
32− semigroups >= 0.16 && < 0.19,
33− mtl >= 2.1 && < 2.3,
34− containers == 0.5.*,
35− these >= 0.4 && < 0.8,
36− ref-tf == 0.4.*,
37− random == 1.1.*,
38− ghcjs-dom >= 0.2.1 && < 0.3,
39− transformers >= 0.3 && < 0.6,
40− lens >= 4.7 && < 5,
41− text == 1.2.*,
42− blaze-builder,
43− bytestring == 0.10.*,
44− data-default >= 0.5 && < 0.8,
45− aeson >= 0.8 && < 0.12,
46− time >= 1.4 && < 1.7,
47− exception-transformers == 0.4.*,
48− directory == 1.2.*,
49− dependent-sum-template >= 0.0.0.4 && < 0.1,
50− zenc == 0.1.*,
51− bifunctors >= 4.2 && < 6,
52− bimap >= 0.3 && < 0.4,
53− monad-control >= 1.0.1 && < 1.1,
54− keycode == 0.2.*,
55− unbounded-delays >= 0.1.0.9 && < 0.2
56−
57− if impl(ghcjs)
58− hs-source-dirs: src-ghcjs
59− build-depends:
60− ghcjs-base,
61− hashable == 1.2.*
62− else
63− hs-source-dirs: src-ghc
64− build-depends:
65− glib == 0.13.*,
66− gtk3 >= 0.13.0 && < 0.15,
67− webkitgtk3 == 0.14.*,
68− webkitgtk3-javascriptcore == 0.13.*,
69− raw-strings-qq
70− pkgconfig-depends:
71− webkitgtk-3.0 >= 1.8
72− if !os(windows)
73− build-depends: unix == 2.7.*
74−
75− exposed-modules:
76− Foreign.JavaScript.TH
77− Reflex.Dom
78− Reflex.Dom.Builder.Class
79− Reflex.Dom.Builder.Class.Events
80− Reflex.Dom.Builder.Immediate
81− Reflex.Dom.Builder.Static
82− Reflex.Dom.Class
83− Reflex.Dom.Deletable.Class
84− Reflex.Dom.DynamicWriter
85− Reflex.Dom.Internal
86− Reflex.Dom.Internal.Foreign
87− Reflex.Dom.Location
88− Reflex.Dom.PerformEvent.Base
89− Reflex.Dom.PerformEvent.Class
90− Reflex.Dom.PostBuild.Class
91− Reflex.Dom.Old
92− Reflex.Dom.Time
93− Reflex.Dom.WebSocket
94− Reflex.Dom.Widget
95− Reflex.Dom.Widget.Basic
96− Reflex.Dom.Widget.Input
97− Reflex.Dom.Widget.Lazy
98− Reflex.Dom.Widget.Resize
99− Reflex.Dom.Xhr
100− other-modules:
101− Reflex.Dom.WebSocket.Foreign
102− Reflex.Dom.Xhr.Foreign
103− Reflex.Dom.Xhr.ResponseType
104− Reflex.Dom.Xhr.Exception
105−
106− other-extensions: TemplateHaskell
107− ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans
108−
109−test-suite hlint
110− build-depends: base, hlint == 1.9.*
111− hs-source-dirs: test
112− main-is: hlint.hs
113− type: exitcode-stdio-1.0
114−
115−source-repository head
116− type: git
117− location: https://github.com/reflex-frp/reflex-dom
reflex-dom/ChangeLog.mdnew file+42
@@ -0,0 +1,42 @@
1+# Revision history for reflex-dom
2+
3+## 0.6.1.0-r1
4+
5+* Loosen reflex-dom-core version bounds
6+
7+## 0.6.1.0
8+
9+* Update for new dependent-map and dependent-sum (after the "some" package split)
10+
11+## 0.6.0.0
12+
13+* ([#379](https://github.com/reflex-frp/reflex-dom/pull/379)) Re-export all modules from `reflex-dom-core`. The newly re-exported modules are:
14+ * `Foreign.JavaScript.Utils`
15+ * `Reflex.Dom.Builder.Hydratable`
16+ * `Reflex.Dom.Modals.Class`
17+ * `Reflex.Dom.Prerender`
18+ * `Reflex.Dom.Time`
19+ * `Reflex.Dom.WebSocket.Query`
20+ * `Reflex.Dom.Xhr.FormData`
21+* ([#366](https://github.com/reflex-frp/reflex-dom/pull/366)) Bump bounds for `reflex` to include 0.7.
22+
23+## 0.5.3
24+
25+* On Android, enable prompting the user for geolocation
26+ permissions on demand by default. See
27+ https://developer.android.com/reference/android/webkit/WebChromeClient.html#onGeolocationPermissionsShowPrompt(java.lang.String,%20android.webkit.GeolocationPermissions.Callback)
28+ for details.
29+
30+ * Add `< 0.7` upper bound for reflex
31+
32+## 0.5.2
33+
34+* The default jsaddle backend on macOS when built from nix
35+ is now jsaddle-wkwebview, matching the behaviour of cabal
36+ builds.
37+
38+## 0.5
39+
40+* Re-export new hydration widget "mainWidget" functions.
41+
42+* The use-warp flag now properly takes precedence on macOS.
reflex-dom/LICENSEnew file+12
@@ -0,0 +1,12 @@
1+Copyright (c) 2020, Obsidian Systems LLC
2+All rights reserved.
3+
4+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5+
6+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7+
8+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9+
10+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11+
12+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
reflex-dom/Setup.hsnew file+2
@@ -0,0 +1,2 @@
1+import Distribution.Simple
2+main = defaultMain
reflex-dom/benchmark.hsnew file+190
@@ -0,0 +1,190 @@
1+{-# LANGUAGE RecursiveDo #-}
2+{-# LANGUAGE GADTs #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE ScopedTypeVariables #-}
5+{-# LANGUAGE RecordWildCards #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE Rank2Types #-}
8+{-# OPTIONS_GHC -ddump-simpl -ddump-rules -ddump-spec -ddump-to-file -dsuppress-coercions -dsuppress-idinfo #-}
9+module Main (main) where
10+
11+import Control.Monad.State
12+import Data.Monoid
13+import Data.Text (Text)
14+import qualified Data.Text as T
15+import Reflex.Dom
16+import System.Random
17+import qualified Data.Map as Map
18+import Data.Dependent.Map (DMap (..))
19+import qualified Data.Dependent.Map as DMap
20+import Data.Dependent.Sum (DSum (..))
21+import Data.Functor.Misc
22+import Data.Functor.Identity
23+import Data.Functor.Compose
24+import Data.IORef
25+import GHCJS.DOM.Types (JSM)
26+import qualified Data.Some as Some
27+import Data.Functor.Constant
28+import Data.IntMap.Strict (IntMap)
29+import qualified Data.IntMap.Strict as IntMap
30+import Data.FastMutableIntMap
31+
32+import qualified GHCJS.DOM.Element as DOM
33+import qualified GHCJS.DOM.Types as DOM
34+
35+--{-
36+main :: IO ()
37+main = mainWidget' $ do
38+ create1000 <- button "Create 1,000 rows"
39+ let row k _ = el "li" $ text $ T.pack $ show k
40+ el "ul" $ traverseIntMapWithKeyWithAdjust row IntMap.empty $ PatchIntMap (IntMap.fromDistinctAscList [(x, Just ()) | x <- [1 :: Int .. 1000]]) <$ create1000
41+ return ()
42+--}
43+
44+
45+{-
46+main :: IO ()
47+main = do
48+ mainWidget' $ do
49+ create1000 <- button "Create 1,000 rows"
50+ partialUpdate <- button "Update every 10th row"
51+ elClass "table" "table table-hover table-striped test-data" $ el "tbody" $ do
52+ --runWithReplace blank $ forM_ [1..1000] row <$ create1000
53+ rec let u = leftmost
54+ [ PatchIntMap (IntMap.fromDistinctAscList [(x, Just ()) | x <- [1..1000]]) <$ create1000
55+ , PatchIntMap (IntMap.fromDistinctAscList [(x, Just ()) | x <- [1, 11..1000]]) <$ partialUpdate
56+ , PatchIntMap <$> deletes
57+ ]
58+ (_, deletes) <- runEventWriterT $ traverseIntMapWithKeyWithAdjust (\k _ -> row k) mempty u
59+ return ()
60+
61+row :: MonadWidget t m => Int -> EventWriterT t (IntMap (Maybe ())) m ()
62+row rowNum = el "tr" $ do
63+ elClass "td" "col-md-1" $ text $ T.pack $ show rowNum
64+ (sel, _) <- elClass' "td" "col-md-4" $ el "a" $ text "asdf"
65+ (del, _) <- elClass' "td" "col-md-1" deleteButton
66+ tellEvent $ IntMap.singleton rowNum Nothing <$ domEvent Click del
67+ elClass "td" "col-md-6" blank
68+
69+deleteButton :: MonadWidget t m => m ()
70+deleteButton = el "a" $ elAttr "span" ("aria-hidden" =: "true" <> "class" =: "glyphicon glyphicon-remove") $ text "X"
71+
72+--}
73+
74+--
75+{-
76+type RNG = StdGen
77+type Entropy = Int
78+type RowPosition = Int
79+type RowNumber = Int
80+data Row = Row { pos :: RowPosition, num :: RowNumber , txt :: Text } deriving (Eq, Show)
81+type Table = Map RowPosition Row
82+data Model = Model { rng :: RNG, table :: Table, nextNum :: RowNumber, selected :: Maybe Row } deriving Show
83+
84+{- Widgets -}
85+
86+titleW :: MonadWidget t m => m ()
87+titleW = text "Reflex-Dom"
88+
89+headW :: MonadWidget t m => m ()
90+headW = do
91+ el "title" titleW
92+ elAttr "link" ("href" =: "/css/currentStyle.css" <> "rel" =: "stylesheet") blank
93+
94+bodyW :: MonadWidget t m => Entropy -> m ()
95+bodyW seed = divClass "main" $ divClass "container" $ mdo
96+ let initial = Model { rng = mkStdGen seed, table = empty, nextNum = 1, selected = Nothing }
97+ dynModel <- foldDyn ($) initial $ mergeWith (.) $ rowEvents : buttonEvents
98+
99+ buttonEvents :: [Event t (Model -> Model)] <- divClass "jumbotron" $ divClass "row" $ do
100+ divClass "col-md-6" $ el "h1" titleW
101+ divClass "col-md-6" $ divClass "row" $ sequence [
102+ buttonW "run" "Create 1,000 rows" $ createRows 1000,
103+ buttonW "runlots" "Create 10,000 rows" $ createRows 10000,
104+ buttonW "add" "Append 1,000 rows" $ appendRows 1000,
105+ buttonW "update" "Update every 10th row" $ updateRows (\p -> mod p 10 == 0) (<> " !!!"),
106+ buttonW "clear" "Clear" $ clearRows,
107+ buttonW "swaprows" "Swap Rows" $ swapRows (4, 9)
108+ ]
109+
110+ rowEvents' <- tableW dynModel
111+ let rowEvents = foldl (.) id <$> rowEvents'
112+
113+ blank
114+
115+buttonW :: MonadWidget t m => Text -> Text -> a -> m (Event t a)
116+buttonW id txt val = divClass "col-sm-6 smallpad" $ buttonW' ("class" =: "btn btn-primary btn-block" <> "id" =: id)
117+ where
118+ buttonW' attrs = do
119+ (b, _) <- elAttr' "button" attrs $ text txt
120+ pure $ val <$ domEvent Click b
121+
122+tableW :: MonadWidget t m => Dynamic t Model -> m (Event t (Map RowPosition (Model -> Model)))
123+tableW dynM =
124+ elClass "table" "table table-hover table-striped test-data"
125+ $ el "tbody"
126+ $ listViewWithKey (table <$> dynM) (\_ dynRow -> rowW (selectedIs <$> dynM <*> dynRow) dynRow)
127+ where
128+ selectedIs m r = selected m == Just r
129+
130+rowW :: MonadWidget t m => Dynamic t Bool -> Dynamic t Row -> m (Event t (Model -> Model))
131+rowW dynSelected dynRow = elDynClass "tr" trClass $
132+ do
133+ elClass "td" "col-md-1". dynText $ pack . show . num <$> dynRow
134+ (sel, _) <- elClass' "td" "col-md-4". el "a" . dynText $ txt <$> dynRow
135+ (del, _) <- elClass' "td" "col-md-1" deleteW
136+ elClass "td" "col-md-6" blank
137+ pure $ mergeWith (.) $ zipWith tagClick [selectRow, deleteRow] [sel, del]
138+ where
139+ trClass = (\b -> if b then "danger" else "") <$> dynSelected
140+ tagClick f el = (tag . current) (f <$> dynRow) (domEvent Click el)
141+
142+
143+{- Domain logic -}
144+
145+clearRows :: Model -> Model
146+clearRows (Model {..}) = Model { table = empty, .. }
147+
148+updateRows :: (RowPosition -> Bool) -> (Text -> Text) -> Model -> Model
149+updateRows p f (Model {..}) = Model { table = (update <$> targets) <> table, .. }
150+ where
151+ targets = filterWithKey (const . p) table
152+ update = \(Row{..}) -> Row { txt = f txt, ..}
153+
154+swapRows :: (RowPosition, RowPosition) -> Model -> Model
155+swapRows (a,b) (Model {..}) = Model { table = (a =: val b) <> (b =: val a) <> table, .. }
156+ where val = (table !)
157+
158+selectRow, deleteRow :: Row -> Model -> Model
159+selectRow r m = m { selected = Just r }
160+deleteRow r (Model {..}) = Model { table = shifted table, .. }
161+ where
162+ shifted = fromList . zipWith update [0..] . elems . delete (pos r)
163+ update p (Row{..}) = (p, Row { pos = p, .. })
164+
165+createRows, appendRows :: Int -> Model -> Model
166+createRows = newRows False
167+appendRows = newRows True
168+
169+newRows :: Bool -> Int -> Model -> Model
170+newRows keepOld count (Model {..}) = Model { rng = rng', table = table', nextNum = nextNum', .. }
171+ where
172+ nextPos = if keepOld then length table else 0
173+ rowsST = sequence (rowST <$ [0..count-1])
174+ (rows, (nextPos', nextNum', rng')) = runState rowsST (nextPos, nextNum, rng)
175+ combine = if keepOld then (<>) else \_ new -> new
176+ table' = fromList . zip [0..] $ combine (elems table) rows
177+
178+rowST :: State (RowPosition, RowNumber, RNG) Row
179+rowST = state (\(p,n,g) -> let (e, g') = next g in (Row {pos = p, num = n, txt = randomName e}, (p+1,n+1,g')))
180+
181+randomName :: Entropy -> Text
182+randomName e = intercalate " " $ (!!% e) <$> [adjectives, colours, nouns]
183+ where xs !!% n = xs !! mod n (length xs)
184+
185+adjectives,colours,nouns :: [Text]
186+adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"]
187+colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"]
188+nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"]
189+
190+-}
reflex-dom/benchmarks/krausest.hsnew file+222
@@ -0,0 +1,222 @@
1+{-# LANGUAGE RecursiveDo #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+{-# LANGUAGE ScopedTypeVariables #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# OPTIONS_GHC -fmax-simplifier-iterations=5 -ddump-simpl -ddump-to-file -dsuppress-coercions -dsuppress-idinfo #-}
6+import Control.Monad.State
7+import Data.Monoid
8+import Data.IntMap (IntMap, assocs, elems, empty, fromList, size, singleton)
9+import Data.Text (Text)
10+import qualified Data.Text as T
11+import Data.Vector (Vector)
12+import qualified Data.Vector as Vector
13+import Reflex.Dom
14+import Data.FastMutableIntMap
15+import System.Random
16+
17+type RNG = StdGen
18+type Entropy = Int
19+type RowNumber = Int
20+type RowIndex = Int
21+data Row = Row { num :: RowNumber, txt :: Text, selected :: Bool } deriving (Eq, Show)
22+type Table = IntMap Row
23+data Model = Model { rng :: RNG, nextNum :: RowNumber, selection :: Maybe Row } deriving Show
24+type TableDiff = PatchIntMap Row
25+
26+main :: IO ()
27+main = do
28+ seed <- randomIO
29+ mainWidgetWithHead' (\_ -> headW, \_ -> bodyW seed)
30+
31+titleW :: DomBuilder t m => m ()
32+titleW = text "Reflex-dom keyed"
33+
34+headW :: DomBuilder t m => m ()
35+headW = do
36+ el "title" titleW
37+ elAttr "link" ("href" =: "/css/currentStyle.css" <> "rel" =: "stylesheet") blank
38+
39+bodyW :: forall t m. (MonadFix m, MonadHold t m, DomBuilder t m) => Entropy -> m ()
40+bodyW seed = divClass "main" $ divClass "container" $ mdo
41+ buttonEvents <- divClass "jumbotron" $ divClass "row" $ do
42+ divClass "col-md-6" $ el "h1" titleW
43+ divClass "col-md-6" $ divClass "row" $ sequence
44+ [ buttonW "run" "Create 1,000 rows" $ resetRows 1000
45+ , buttonW "runlots" "Create 10,000 rows" $ resetRows 10000
46+ , buttonW "add" "Append 1,000 rows" $ appendRows 1000
47+ , buttonW "update" "Update every 10th row" $ updateRows (\i -> mod i 10 == 0) (<> " !!!")
48+ , buttonW "clear" "Clear" $ clearRows
49+ , buttonW "swaprows" "Swap Rows" $ swapRows (1, 998)
50+ ]
51+
52+ let initial = Model { rng = mkStdGen seed, nextNum = 1, selection = Nothing }
53+ let events = leftmost $ fmap (foldl1 sequenceSteps) rowEvents : buttonEvents
54+
55+ rowEvents <- tableW dynMT
56+
57+ dynMT <- mapAccum_ step (initial, empty) events
58+
59+ elAttr "span" ("class" =: "preloadicon glyphicon glyphicon-remove" <> "aria-hidden" =: "true") blank
60+
61+ blank
62+
63+type Step = (Model, Table) -> (Model, TableDiff)
64+
65+sequenceSteps :: Step -> Step -> Step
66+sequenceSteps a b (m, t) =
67+ let (ma, tda) = a (m, t)
68+ ta = applyAlways tda t
69+ (mb, tdb) = b (ma, ta)
70+ in (mb, tdb <> tda)
71+
72+step :: (Model, Table) -> Step -> ((Model, Table), TableDiff)
73+step (m, t) f = ((m', t'), dt)
74+ where
75+ (m', dt) = f (m, t)
76+ t' = applyAlways dt t
77+
78+buttonW :: DomBuilder t m => Text -> Text -> a -> m (Event t a)
79+buttonW id txt val = divClass "col-sm-6 smallpad" $ buttonW' ("class" =: "btn btn-primary btn-block" <> "id" =: id)
80+ where
81+ buttonW' attrs = do
82+ (b, _) <- elAttr' "button" attrs $ text txt
83+ pure $ val <$ domEvent Click b
84+
85+tableW :: (MonadHold t m, DomBuilder t m) => Event t TableDiff -> m (Event t (IntMap Step))
86+tableW diff = do
87+ elClass "table" "table table-hover table-striped test-data" $ do
88+ el "tbody" $ do
89+ (v0, v') <- traverseIntMapWithKeyWithAdjust (\_ -> rowW) empty diff
90+ rowEvents <- holdIncremental v0 v'
91+ return $ mergeIntIncremental rowEvents
92+
93+rowW :: DomBuilder t m => Row -> m (Event t Step)
94+rowW row = elClass "tr" (if selected row then "danger" else "") $
95+ do
96+ elClass "td" "col-md-1" $ do
97+ text $ T.pack $ show $ num row
98+ (sel, _) <- elClass' "td" "col-md-4". el "a" . text $ txt row
99+ (del, _) <- elClass' "td" "col-md-1" deleteW
100+ elClass "td" "col-md-6" blank
101+ pure . leftmost $ zipWith tagClick [selectRow, deleteRow] [sel, del]
102+ where
103+ tagClick f el = f row <$ (domEvent Click el)
104+
105+deleteW :: DomBuilder t m => m ()
106+deleteW = el "a" $ elAttr "span" ("aria-hidden" =: "true" <> "class" =: "glyphicon glyphicon-remove") blank
107+
108+
109+{- Domain logic -}
110+clearRows :: (Model, Table) -> (Model, TableDiff)
111+clearRows (m, t) = (m { selection = Nothing }, PatchIntMap $ Nothing <$ t)
112+
113+updateRows :: (RowIndex -> Bool) -> (Text -> Text) -> (Model, Table) -> (Model, TableDiff)
114+updateRows p f (m, t) = (m, PatchIntMap $ Just . update <$> targets)
115+ where
116+ targets = fromList . filterByIndex p . assocs $ t
117+ update = \r -> r { txt = f $ txt r }
118+
119+filterByIndex :: (Int -> Bool) -> [a] -> [a]
120+filterByIndex p = map snd . filter (\(i, _) -> p i) . zip [0..]
121+
122+swapRows :: (RowIndex, RowIndex) -> (Model, Table) -> (Model, TableDiff)
123+swapRows (a, b) (m, t) = (m, PatchIntMap $ if max a b < length t then swap else empty)
124+ where
125+ swap = point a b <> point b a
126+ point x y = singleton (fst (val x)) $ Just $ snd $ val y
127+ val = (assocs t !!)
128+
129+selectRow :: Row -> (Model, Table) -> (Model, TableDiff)
130+selectRow r (m, t) = (m { selection = Just r}, PatchIntMap $ dr <> ds)
131+ where
132+ dr = sel True r
133+ ds = maybe empty (sel False) $ selection m
134+ sel b r' = singleton (num r') $ Just r' { selected = b }
135+
136+deleteRow :: Row -> (Model, Table) -> (Model, TableDiff)
137+deleteRow r (m, t) = (m { selection = mfilter (/= r) (selection m) }, PatchIntMap $ singleton (num r) Nothing)
138+
139+resetRows :: Int -> (Model, Table) -> (Model, TableDiff)
140+resetRows n (m, t) = (m'', dt <> dt')
141+ where
142+ (m', dt ) = addRows n (m, t)
143+ (m'', dt') = clearRows (m', t)
144+
145+appendRows :: Int -> (Model, Table) -> (Model, TableDiff)
146+appendRows n (m, t) = addRows n (m, t)
147+
148+addRows :: Int -> (Model, Table) -> (Model, TableDiff)
149+addRows count (m, t) = (m { rng = rng', nextNum = nextNum' }, PatchIntMap diff)
150+ where
151+ rowsST = sequence (rowST <$ [0..count-1])
152+ (rows, (nextNum', rng')) = runState rowsST (nextNum m, rng m)
153+ diff = fromList . fmap (\r -> (num r, Just r)) $ rows
154+
155+rowST :: State (RowNumber, RNG) Row
156+rowST = state (\(n, g) -> let (e, g') = next g in (Row {num = n, txt = randomName e, selected = False}, (n+1, g')))
157+
158+randomName :: Entropy -> Text
159+randomName e = T.intercalate " " $ (`modIndex` e) <$> [adjectives, colours, nouns]
160+
161+-- | Index into a Vector, modulo its length
162+--
163+-- WARNING: The vector must have length >= 1, and the index must be >= 0.
164+modIndex :: Vector a -> Int -> a
165+modIndex v n = Vector.unsafeIndex v $ n `mod` Vector.length v
166+
167+adjectives, colours, nouns :: Vector Text
168+adjectives = Vector.fromList
169+ [ "pretty"
170+ , "large"
171+ , "big"
172+ , "small"
173+ , "tall"
174+ , "short"
175+ , "long"
176+ , "handsome"
177+ , "plain"
178+ , "quaint"
179+ , "clean"
180+ , "elegant"
181+ , "easy"
182+ , "angry"
183+ , "crazy"
184+ , "helpful"
185+ , "mushy"
186+ , "odd"
187+ , "unsightly"
188+ , "adorable"
189+ , "important"
190+ , "inexpensive"
191+ , "cheap"
192+ , "expensive"
193+ , "fancy"
194+ ]
195+colours = Vector.fromList
196+ [ "red"
197+ , "yellow"
198+ , "blue"
199+ , "green"
200+ , "pink"
201+ , "brown"
202+ , "purple"
203+ , "brown"
204+ , "white"
205+ , "black"
206+ , "orange"
207+ ]
208+nouns = Vector.fromList
209+ [ "table"
210+ , "chair"
211+ , "house"
212+ , "bbq"
213+ , "desk"
214+ , "car"
215+ , "pony"
216+ , "cookie"
217+ , "sandwich"
218+ , "burger"
219+ , "pizza"
220+ , "mouse"
221+ , "keyboard"
222+ ]
reflex-dom/cbits/MainWidget.cnew file+89
@@ -0,0 +1,89 @@
1+#include <jni.h>
2+#include <assert.h>
3+#include <stdlib.h>
4+#include <android/log.h>
5+#include <HaskellActivity.h>
6+#include "MainWidget.h"
7+
8+jobject Reflex_Dom_Android_MainWidget_start(jobject activity, const char *url, const JSaddleCallbacks *jsaddleCallbacks) {
9+ assert(activity);
10+ assert(url);
11+
12+ JNIEnv *env;
13+ jint attachResult = (*HaskellActivity_jvm)->AttachCurrentThread(HaskellActivity_jvm, &env, NULL);
14+ assert(attachResult == JNI_OK);
15+
16+ jclass cls = (*env)->FindClass(env, "org/reflexfrp/reflexdom/MainWidget");
17+ assert(cls);
18+ jmethodID startMainWidget = (*env)->GetStaticMethodID(env, cls, "startMainWidget", "(Lsystems/obsidian/HaskellActivity;Ljava/lang/String;JLjava/lang/String;)Ljava/lang/Object;");
19+ assert(startMainWidget);
20+
21+ jstring jurl = (*env)->NewStringUTF(env, url);
22+ assert(jurl);
23+ jstring initialJS = (*env)->NewStringUTF(env, jsaddleCallbacks->jsaddleJsData);
24+ jobject result = (*env)->CallStaticObjectMethod(env, cls, startMainWidget, activity, jurl, (jlong)jsaddleCallbacks, initialJS);
25+ (*env)->DeleteLocalRef(env, initialJS);
26+ if((*env)->ExceptionOccurred(env)) {
27+ __android_log_write(ANDROID_LOG_DEBUG, "MainWidget", "startMainWidget exception");
28+ (*env)->ExceptionDescribe(env);
29+ }
30+ return (*env)->NewGlobalRef(env, result);
31+}
32+
33+void Reflex_Dom_Android_MainWidget_runJS(jobject jsExecutor, const char* js, size_t js_len) {
34+ JNIEnv *env;
35+ jint attachResult = (*HaskellActivity_jvm)->AttachCurrentThread(HaskellActivity_jvm, &env, NULL);
36+ assert (attachResult == JNI_OK);
37+
38+ (*env)->PushLocalFrame(env, 5);
39+
40+ //TODO: Don't search for this method every time
41+ jclass cls = (*env)->GetObjectClass(env, jsExecutor);
42+ assert(cls);
43+ jmethodID evaluateJavascript = (*env)->GetMethodID(env, cls, "evaluateJavascript", "([B)V");
44+ assert(evaluateJavascript);
45+ jbyteArray js_str = (*env)->NewByteArray(env, js_len);
46+ (*env)->SetByteArrayRegion(env, js_str, 0, js_len, (const jbyte*)js);
47+ (*env)->CallVoidMethod(env, jsExecutor, evaluateJavascript, js_str, 0);
48+ if((*env)->ExceptionOccurred(env)) {
49+ __android_log_write(ANDROID_LOG_DEBUG, "MainWidget", "runJS exception");
50+ (*env)->ExceptionDescribe(env);
51+ }
52+
53+ (*env)->PopLocalFrame(env, 0);
54+}
55+
56+JNIEXPORT void JNICALL Java_org_reflexfrp_reflexdom_MainWidget_00024JSaddleCallbacks_startProcessing (JNIEnv *env, jobject thisObj, jlong callbacksLong) {
57+ const JSaddleCallbacks *callbacks = (const JSaddleCallbacks *)callbacksLong;
58+ (*(callbacks->jsaddleStart))();
59+ return;
60+}
61+
62+JNIEXPORT void JNICALL Java_org_reflexfrp_reflexdom_MainWidget_00024JSaddleCallbacks_processMessage (JNIEnv *env, jobject thisObj, jlong callbacksLong, jbyteArray msg) {
63+ const JSaddleCallbacks *callbacks = (const JSaddleCallbacks *)callbacksLong;
64+
65+ jbyte *msg_str = (*env)->GetByteArrayElements(env, msg, NULL);
66+ jsize msg_str_len = (*env)->GetArrayLength(env, msg);
67+ (*(callbacks->jsaddleResult))(msg_str, msg_str_len);
68+ (*env)->ReleaseByteArrayElements(env, msg, msg_str, JNI_ABORT);
69+ return;
70+}
71+
72+JNIEXPORT jbyteArray JNICALL Java_org_reflexfrp_reflexdom_MainWidget_00024JSaddleCallbacks_processSyncMessage (JNIEnv *env, jobject thisObj, jlong callbacksLong, jbyteArray msg) {
73+ const JSaddleCallbacks *callbacks = (const JSaddleCallbacks *)callbacksLong;
74+
75+ char const *next_str;
76+ size_t next_str_len;
77+
78+ jbyte *msg_str = (*env)->GetByteArrayElements(env, msg, NULL);
79+ jsize msg_str_len = (*env)->GetArrayLength(env, msg);
80+ (*(callbacks->jsaddleSyncResult))(msg_str, msg_str_len, &next_str, &next_str_len);
81+ (*env)->ReleaseByteArrayElements(env, msg, msg_str, JNI_ABORT);
82+
83+ jbyteArray next_jstr = (*env)->NewByteArray(env, next_str_len);
84+ (*env)->SetByteArrayRegion(env, next_jstr, 0, next_str_len, next_str);
85+
86+ free(next_str);
87+
88+ return next_jstr;
89+}
reflex-dom/cbits/include/MainWidget.hnew file+13
@@ -0,0 +1,13 @@
1+#ifndef MAINWIDGET_H_INCLUDED
2+#define MAINWIDGET_H_INCLUDED
3+
4+#include <stddef.h>
5+
6+typedef struct JSaddleCallbacks {
7+ void (* jsaddleStart) ();
8+ void (* jsaddleResult) (const char *, size_t);
9+ void (* jsaddleSyncResult) (const char *, size_t, const char**, size_t*);
10+ char * jsaddleJsData;
11+} JSaddleCallbacks;
12+
13+#endif
reflex-dom/examples/sortableList.hsnew file+82
@@ -0,0 +1,82 @@
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE GADTs #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE RankNTypes #-}
5+{-# LANGUAGE RecursiveDo #-}
6+{-# LANGUAGE ScopedTypeVariables #-}
7+import Control.Lens
8+import Control.Monad.Identity
9+import Control.Monad.IO.Class
10+import Data.Dependent.Map (DMap)
11+import Data.Functor.Constant
12+import Data.Functor.Misc
13+import Data.List
14+import Data.Map (Map)
15+import qualified Data.Map as Map
16+import Data.Monoid
17+import Data.Ord
18+import qualified Data.Text as T
19+import Data.Time.Clock
20+import Reflex.Dom
21+import System.Random
22+
23+main :: IO ()
24+main = mainWidget $ do
25+ let f _ (a, b, c) = el "tr" $ do
26+ mapM_ (el "td" . text . T.pack . show) [a, b, c]
27+ _ <- el "td" $ inputElement def
28+ return ()
29+ let numKeys = 1000 :: Int
30+ keys = take numKeys [0 :: Int ..]
31+ values :: [(Int, Int, Int)]
32+ values = zip3 (randoms (mkStdGen 0)) (randoms (mkStdGen 1)) (randoms (mkStdGen 2))
33+ testMap = Map.fromList $ zip keys values
34+ resortButtons = el "div" $ leftmost <$> sequence
35+ [ (comparing (view _1) <$) <$> button "A ASC"
36+ , (flip (comparing (view _1)) <$) <$> button "A DESC"
37+ , (comparing (view _2) <$) <$> button "B ASC"
38+ , (flip (comparing (view _2)) <$) <$> button "B DESC"
39+ , (comparing (view _3) <$) <$> button "C ASC"
40+ , (flip (comparing (view _3)) <$) <$> button "C DESC"
41+ ]
42+ el "h1" $ text "Improved list sorting"
43+ el "p" $ text $ "This app shows a table of " <> T.pack (show numKeys) <> " rows, and allows you to re-sort by columns a, b, and c, which are full of pseudorandom numbers. Each row also includes an element with internal state (a textbox) to demonstrate that the state is preserved, only when using the new way."
44+ el "h3" $ text "Re-sort the list the OLD way (by redrawing everything)"
45+ resortSlow <- resortButtons
46+ displayRedrawTime resortSlow
47+ el "h3" $ text "Re-sort the list the NEW way (by reordering existing elements)"
48+ resort <- resortButtons
49+ displayRedrawTime resort
50+ el "hr" blank
51+ el "table" $ do
52+ el "tr" $ do
53+ el "th" $ text "A"
54+ el "th" $ text "B"
55+ el "th" $ text "C"
56+ el "th" $ text "Stateful Element (textbox)"
57+ simpleSortableList f testMap resort resortSlow
58+ return ()
59+
60+displayRedrawTime :: (DomBuilder t m, MonadHold t m, PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => Event t a -> m ()
61+displayRedrawTime e = do
62+ et1 <- performEvent $ liftIO getCurrentTime <$ e
63+ et1' <- delay 0 et1
64+ diff <- performEvent $ ffor et1' $ \t1 -> do
65+ t2 <- liftIO getCurrentTime
66+ return $ t2 `diffUTCTime` t1
67+ text "Time: "
68+ dynText =<< holdDyn "not yet run" (T.pack . show <$> diff)
69+
70+simpleSortableList :: forall t m k v. (MonadHold t m, MonadFix m, Adjustable t m, Ord k) => (k -> v -> m ()) -> Map k v -> Event t (v -> v -> Ordering) -> Event t (v -> v -> Ordering) -> m ()
71+simpleSortableList f m0 resortFunc resortSlowFunc = do
72+ rec let resortPatchFast = attachWith (flip patchThatSortsMapWith) (currentIncremental m) resortFunc
73+ redrawPatch :: Map k v -> (v -> v -> Ordering) -> PatchMapWithMove k v
74+ redrawPatch d cmp = unsafePatchMapWithMove $ fmap (MapEdit_Insert False) $ Map.fromList $ zip (Map.keys d) (sortBy cmp $ Map.elems d)
75+ resortPatchSlow = attachWith redrawPatch (currentIncremental m) resortSlowFunc
76+ resortPatch = leftmost
77+ [ resortPatchFast
78+ , resortPatchSlow
79+ ]
80+ m <- holdIncremental m0 resortPatch
81+ _ <- mapMapWithAdjustWithMove f m0 resortPatch
82+ return ()
reflex-dom/java/org/reflexfrp/reflexdom/MainWidget.javanew file+195
@@ -0,0 +1,195 @@
1+package org.reflexfrp.reflexdom;
2+
3+import android.annotation.TargetApi;
4+import android.net.Uri;
5+import android.os.Build;
6+import android.os.Handler;
7+import android.util.Log;
8+import android.view.ViewGroup.LayoutParams;
9+import android.view.Window;
10+import android.webkit.CookieManager;
11+import android.webkit.GeolocationPermissions;
12+import android.webkit.JavascriptInterface;
13+import android.webkit.MimeTypeMap;
14+import android.webkit.PermissionRequest;
15+import android.webkit.WebChromeClient;
16+import android.webkit.WebResourceRequest;
17+import android.webkit.WebResourceResponse;
18+import android.webkit.WebSettings;
19+import android.webkit.WebView;
20+import android.webkit.WebViewClient;
21+import android.graphics.Bitmap;
22+import java.io.IOException;
23+import java.io.InputStream;
24+import android.content.Intent;
25+import android.content.ActivityNotFoundException;
26+import java.util.concurrent.atomic.AtomicBoolean;
27+
28+import java.nio.charset.StandardCharsets;
29+
30+import systems.obsidian.HaskellActivity;
31+
32+public class MainWidget {
33+ private static Object startMainWidget(final HaskellActivity a, String url, long jsaddleCallbacks, final String initialJS) {
34+ CookieManager.setAcceptFileSchemeCookies(true); //TODO: Can we do this just for our own WebView?
35+
36+ // Remove title and notification bars
37+ a.requestWindowFeature(Window.FEATURE_NO_TITLE);
38+
39+ final WebView wv = new WebView(a);
40+ wv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
41+ a.setContentView(wv);
42+ final WebSettings ws = wv.getSettings();
43+ ws.setJavaScriptEnabled(true);
44+ ws.setAllowFileAccessFromFileURLs(true);
45+ ws.setAllowUniversalAccessFromFileURLs(true);
46+ ws.setDomStorageEnabled(true);
47+ wv.setWebContentsDebuggingEnabled(true);
48+ // allow video to play without user interaction
49+ wv.getSettings().setMediaPlaybackRequiresUserGesture(false);
50+ final AtomicBoolean jsaddleLoaded = new AtomicBoolean(false);
51+
52+ wv.setWebViewClient(new WebViewClient() {
53+ @Override
54+ public void onPageFinished(WebView _view, String _url) {
55+ Log.i("reflex", "onPageFinished");
56+ boolean alreadyLoaded = jsaddleLoaded.getAndSet(true);
57+ if(!alreadyLoaded) {
58+ Log.i("reflex", "loading jsaddle");
59+ wv.evaluateJavascript(initialJS, null);
60+ }
61+ }
62+
63+ // Re-route / to /android_asset
64+ @Override
65+ public WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request) {
66+ Uri uri = request.getUrl();
67+ if(!uri.getScheme().equals("file"))
68+ return null;
69+
70+ String path = uri.getPath();
71+ path = getAssetPath(path);
72+
73+ String mimeType = getMimeType(uri.toString());
74+ String encoding = "";
75+
76+ try {
77+ InputStream data = a.getApplicationContext().getAssets().open(path);
78+ return new WebResourceResponse(mimeType, encoding, data);
79+ }
80+ catch (IOException e) {
81+ Log.i("reflex", "Opening resource failed, Webview will handle the request ..");
82+ e.printStackTrace();
83+ }
84+
85+ return null;
86+ }
87+
88+ @Override
89+ public boolean shouldOverrideUrlLoading(WebView view, String url) {
90+ if( url != null && !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("file://")) {
91+ try {
92+ view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
93+ }
94+ catch(ActivityNotFoundException e) {
95+ Log.e("reflex", "Starting activity for intent '" + url + "' failed!");
96+ }
97+ return true;
98+ } else {
99+ return false;
100+ }
101+ }
102+ });
103+
104+ wv.setWebChromeClient(new WebChromeClient() {
105+ // Need to accept permissions to use the camera and audio
106+ @Override
107+ public void onPermissionRequest(final PermissionRequest request) {
108+ if(request.getOrigin().toString().startsWith("file://")) {
109+ a.requestWebViewPermissions(request);
110+ }
111+ else {
112+ a.runOnUiThread(new Runnable() {
113+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
114+ @Override
115+ public void run() {
116+ request.deny();
117+ }
118+ });
119+ }
120+ }
121+
122+ @Override
123+ public Bitmap getDefaultVideoPoster() {
124+ return Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888);
125+ }
126+
127+ @Override
128+ public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
129+ callback.invoke(origin, true, false);
130+ }
131+ });
132+
133+ wv.addJavascriptInterface(new JSaddleCallbacks(jsaddleCallbacks), "jsaddle");
134+
135+ wv.loadUrl(url);
136+
137+ final Handler hnd = new Handler();
138+ return new Object() {
139+ public final void evaluateJavascript(final byte[] js) {
140+ final String jsStr = new String(js, StandardCharsets.UTF_8);
141+ hnd.post(new Runnable() {
142+ @Override
143+ public void run() {
144+ wv.evaluateJavascript(jsStr, null);
145+ }
146+ });
147+ }
148+ };
149+ }
150+
151+ private static String getMimeType(String url) {
152+ String type = "";
153+ String extension = MimeTypeMap.getFileExtensionFromUrl(url);
154+ if (extension != null) {
155+ type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
156+ }
157+ return type;
158+ }
159+
160+ /** Get the path of an asset. Strips leading / and leading /android_asset/ */
161+ private static String getAssetPath(String path) {
162+ path = path.startsWith("/android_asset") ? path.substring("/android_asset".length()) : path;
163+ path = path.startsWith("/") ? path.substring(1) : path;
164+ return path;
165+ }
166+
167+ private static class JSaddleCallbacks {
168+ private final long callbacks;
169+ private native void startProcessing(long callbacks);
170+ private native void processMessage(long callbacks, byte[] msg);
171+ private native byte[] processSyncMessage(long callbacks, byte[] msg);
172+
173+ public JSaddleCallbacks(long _callbacks) {
174+ callbacks = _callbacks;
175+ }
176+
177+ @JavascriptInterface
178+ public boolean postReady() {
179+ startProcessing(callbacks);
180+ return true;
181+ }
182+
183+ @JavascriptInterface
184+ public boolean postMessage(final String msg) {
185+ processMessage(callbacks, msg.getBytes(StandardCharsets.UTF_8));
186+ return true;
187+ }
188+
189+ @JavascriptInterface
190+ public String syncMessage(final String msg) {
191+ return new String(processSyncMessage(callbacks, msg.getBytes(StandardCharsets.UTF_8)),
192+ StandardCharsets.UTF_8);
193+ }
194+ }
195+}
reflex-dom/reflex-dom.cabalnew file+213
@@ -0,0 +1,213 @@
1+cabal-version: 1.24
2+Name: reflex-dom
3+Version: 0.6.1.0
4+Synopsis: Functional Reactive Web Apps with Reflex
5+Description:
6+ Web applications without callbacks or side-effects.
7+ Reflex-DOM brings the power of functional reactive programming (FRP) to the web.
8+ Build HTML and other Document Object Model (DOM) data with a pure functional interface.
9+ .
10+ Reflex-DOM is a Functional Reactive web framework based on the Reflex FRP engine: <https://reflex-frp.org/>.
11+ .
12+ The @reflex-dom@ package is a small wrapper around the @reflex-dom-core@ package. It pulls in the
13+ correct set of dependencies for each target platform (GHCJS, WebKitGTK, WASM, mobile, etc.).
14+ Libraries should depend on @reflex-dom-core@ and executables will usually depend on @reflex-dom@.
15+ All of @reflex-dom-core@'s modules are re-exported by @reflex-dom@.
16+ .
17+ For Hackage documentation, please see: <https://hackage.haskell.org/package/reflex-dom-core>.
18+License: BSD3
19+License-file: LICENSE
20+Author: Ryan Trinkle
21+Maintainer: ryan.trinkle@gmail.com
22+Stability: Experimental
23+Category: FRP, Web, GUI, HTML, Javascript, Reactive, Reactivity, User Interfaces, User-interface
24+Build-type: Simple
25+extra-source-files:
26+ java/org/reflexfrp/reflexdom/MainWidget.java
27+ ChangeLog.md
28+
29+flag use-warp
30+ description: Use jsaddle-warp server
31+ default: False
32+ manual: True
33+
34+flag webkit2gtk
35+ description: Use WebKit2 version of WebKitGTK.
36+ default: True
37+
38+flag use-reflex-optimizer
39+ description: Use the GHC plugin Reflex.Optimizer on some of the modules in the package. This is still experimental.
40+ default: False
41+ manual: True
42+
43+flag expose-all-unfoldings
44+ description: Build the library with -fexpose-all-unfoldings which can help client code specialize better
45+ default: False
46+ manual: True
47+
48+flag build-examples
49+ description: Build the executables in ./examples
50+ default: False
51+ manual: True
52+
53+flag wasm32
54+ description: Build for wasm32 architecture
55+ default: False
56+ manual: True
57+
58+library
59+ hs-source-dirs: src
60+ if os(android)
61+ hs-source-dirs: src-android
62+ other-modules: Reflex.Dom.Android.MainWidget
63+ build-depends:
64+ aeson >= 1.4 && < 1.6,
65+ android-activity == 0.1.*,
66+ data-default == 0.7.*,
67+ jsaddle >= 0.9.6 && < 0.10
68+ c-sources: cbits/MainWidget.c
69+ include-dirs: cbits/include
70+ install-includes: MainWidget.h
71+ cpp-options: -DANDROID
72+ build-tools: hsc2hs
73+ build-depends:
74+ base >= 4.7 && < 4.15,
75+ bytestring == 0.10.*,
76+ reflex >= 0.8 && < 0.9,
77+ reflex-dom-core >= 0.6.1.0 && <0.7,
78+ text == 1.2.*
79+ if !impl(ghcjs)
80+ if flag(use-warp) && (os(linux) || os(osx))
81+ build-depends:
82+ jsaddle >= 0.9.6 && < 0.10,
83+ jsaddle-warp >= 0.9.6 && < 0.10
84+ else
85+ if os(osx) || os(ios)
86+ build-depends:
87+ data-default == 0.7.*,
88+ jsaddle >= 0.9.6 && < 0.10,
89+ jsaddle-wkwebview >= 0.9.6 && < 0.10
90+ else
91+ if flag(wasm32)
92+ build-depends:
93+ jsaddle >= 0.9.6 && < 0.10,
94+ jsaddle-wasm >= 0.1 && < 0.2
95+ else
96+ if flag(webkit2gtk)
97+ build-depends:
98+ jsaddle-webkit2gtk >= 0.9.6 && < 0.10
99+ else
100+ if !os(android)
101+ build-depends:
102+ jsaddle-webkit2gtk >= 0.9.6 && < 0.10
103+
104+ exposed-modules:
105+ Reflex.Dom
106+ Reflex.Dom.Internal
107+ reexported-modules:
108+ Foreign.JavaScript.Orphans
109+ , Foreign.JavaScript.TH
110+ , Foreign.JavaScript.Utils
111+ , Reflex.Dom.Builder.Class
112+ , Reflex.Dom.Builder.Class.Events
113+ , Reflex.Dom.Builder.Hydratable
114+ , Reflex.Dom.Builder.Immediate
115+ , Reflex.Dom.Builder.InputDisabled
116+ , Reflex.Dom.Builder.Static
117+ , Reflex.Dom.Class
118+ , Reflex.Dom.Core
119+ , Reflex.Dom.Location
120+ , Reflex.Dom.Main
121+ , Reflex.Dom.Modals.Class
122+ , Reflex.Dom.Old
123+ , Reflex.Dom.Prerender
124+ , Reflex.Dom.Time
125+ , Reflex.Dom.WebSocket
126+ , Reflex.Dom.WebSocket.Query
127+ , Reflex.Dom.Widget
128+ , Reflex.Dom.Widget.Basic
129+ , Reflex.Dom.Widget.Input
130+ , Reflex.Dom.Widget.Lazy
131+ , Reflex.Dom.Widget.Resize
132+ , Reflex.Dom.Xhr
133+ , Reflex.Dom.Xhr.FormData
134+ ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans
135+ if flag(expose-all-unfoldings)
136+ ghc-options: -fexpose-all-unfoldings
137+ if flag(use-reflex-optimizer)
138+ ghc-options: -fplugin=Reflex.Optimizer
139+ default-language: Haskell2010
140+
141+executable sortableList
142+ build-depends: base
143+ , containers
144+ , dependent-map
145+ , lens
146+ , mtl
147+ , random
148+ , reflex
149+ , reflex-dom
150+ , text
151+ , time
152+ , transformers
153+ hs-source-dirs: examples
154+ main-is: sortableList.hs
155+ ghc-options: -Wall -fwarn-tabs -funbox-strict-fields -O2 -ferror-spans -fspecialise-aggressively
156+ if !flag(build-examples)
157+ buildable: False
158+ if flag(expose-all-unfoldings)
159+ ghc-options: -fexpose-all-unfoldings
160+ if flag(use-reflex-optimizer)
161+ ghc-options: -fplugin=Reflex.Optimizer
162+ default-language: Haskell2010
163+
164+executable benchmark
165+ build-depends: base
166+ , containers
167+ , dependent-map
168+ , dependent-sum
169+ , ghc-prim
170+ , ghcjs-dom
171+ , mtl
172+ , prim-uniq
173+ , random
174+ , reflex
175+ , reflex-dom
176+ , text
177+ , transformers
178+ hs-source-dirs: .
179+ main-is: benchmark.hs
180+ ghc-options: -O2 -fspecialise-aggressively
181+ if !impl(ghcjs)
182+ buildable: False
183+ default-language: Haskell2010
184+
185+executable krausest
186+ build-depends: base
187+ , containers
188+ , dependent-map
189+ , dependent-sum
190+ , ghc-prim
191+ , ghcjs-dom
192+ , mtl
193+ , prim-uniq
194+ , random
195+ , reflex
196+ , reflex-dom
197+ , text
198+ , transformers
199+ , vector
200+ hs-source-dirs: benchmarks
201+ main-is: krausest.hs
202+ ghc-options: -O2 -fspecialise-aggressively
203+ if impl(ghcjs)
204+ ghcjs-options: -dedupe
205+ cpp-options: -DGHCJS_BROWSER -DGHCJS_GC_INTERVAL=60000
206+ else
207+ buildable: False
208+ default-language: Haskell2010
209+
210+source-repository head
211+ type: git
212+ location: https://github.com/reflex-frp/reflex-dom
213+ subdir: reflex-dom
reflex-dom/src-android/Reflex/Dom/Android/MainWidget.hscnew file+117
@@ -0,0 +1,117 @@
1+{-# LANGUAGE ForeignFunctionInterface #-}
2+{-# LANGUAGE OverloadedStrings #-}
3+module Reflex.Dom.Android.MainWidget
4+ ( startMainWidget
5+ ) where
6+
7+import Android.HaskellActivity
8+import Control.Concurrent
9+import Control.Monad
10+import Data.Aeson
11+import Data.ByteString (ByteString)
12+import qualified Data.ByteString as BS
13+import qualified Data.ByteString.Lazy as LBS
14+import qualified Data.ByteString.Unsafe as BSU
15+import Data.IORef
16+import Data.Monoid
17+import Foreign.C.String
18+import Foreign.C.Types
19+import Foreign.Marshal.Utils
20+import Foreign.Marshal.Array
21+import Foreign.Ptr
22+import Foreign.Storable
23+import Language.Javascript.JSaddle (JSM)
24+import Language.Javascript.JSaddle.Run (runJavaScript)
25+import Language.Javascript.JSaddle.Run.Files (initState, runBatch, ghcjsHelpers)
26+
27+#include "MainWidget.h"
28+
29+
30+startMainWidget :: HaskellActivity -> ByteString -> JSM () -> IO ()
31+startMainWidget a url jsm = do
32+ --TODO: Find a way to eventually release this
33+ executorRef <- newIORef $ error "startMainWidget: executor not created yet"
34+ let go batch = do
35+ executor <- readIORef executorRef
36+ BSU.unsafeUseAsCStringLen (LBS.toStrict $ "runJSaddleBatch(" <> encode batch <> ");") $ \(cstr, len) -> do
37+ runJS executor cstr (fromIntegral len)
38+ (processResult, processSyncResult, start) <- runJavaScript go jsm
39+ callbacks <- new <=< jsaddleCallbacksToPtrs $ JSaddleCallbacks
40+ { _jsaddleCallbacks_jsaddleStart = void $ forkIO start
41+ , _jsaddleCallbacks_jsaddleResult = \s -> do
42+ case decode $ LBS.fromStrict s of
43+ Nothing -> error $ "jsaddle message decode failed: " <> show s
44+ Just r -> processResult r
45+ , _jsaddleCallbacks_jsaddleSyncResult = \s -> do
46+ case decode $ LBS.fromStrict s of
47+ Nothing -> error $ "jsaddle message decode failed: " <> show s
48+ Just r -> LBS.toStrict . encode <$> processSyncResult r
49+ , _jsaddleCallbacks_jsaddleJsData = LBS.toStrict $ ghcjsHelpers <> "\
50+ \runJSaddleBatch = (function() {\n\
51+ \ " <> initState <> "\n\
52+ \ return function(batch) {\n\
53+ \ " <> runBatch (\a -> "jsaddle.postMessage(JSON.stringify(" <> a <> "));")
54+ (Just (\a -> "JSON.parse(jsaddle.syncMessage(JSON.stringify(" <> a <> ")))")) <> "\
55+ \ };\n\
56+ \})();\n\
57+ \jsaddle.postReady();\n"
58+ }
59+ BS.useAsCString url $ \curl -> do
60+ writeIORef executorRef =<< startMainWidget_ a curl callbacks
61+
62+newtype JSExecutor = JSExecutor { unJSExecutor :: Ptr JSExecutor }
63+
64+foreign import ccall safe "Reflex_Dom_Android_MainWidget_start" startMainWidget_ :: HaskellActivity -> CString -> Ptr JSaddleCallbacksPtrs -> IO JSExecutor
65+
66+foreign import ccall safe "Reflex_Dom_Android_MainWidget_runJS" runJS :: JSExecutor -> CString -> CSize -> IO ()
67+
68+data JSaddleCallbacks = JSaddleCallbacks
69+ { _jsaddleCallbacks_jsaddleStart :: IO ()
70+ , _jsaddleCallbacks_jsaddleResult :: ByteString -> IO ()
71+ , _jsaddleCallbacks_jsaddleSyncResult :: ByteString -> IO ByteString
72+ , _jsaddleCallbacks_jsaddleJsData :: ByteString
73+ }
74+
75+data JSaddleCallbacksPtrs = JSaddleCallbacksPtrs
76+ { _jsaddleCallbacksPtrs_jsaddleStart :: !(FunPtr (IO ()))
77+ , _jsaddleCallbacksPtrs_jsaddleResult :: !(FunPtr (CString -> CSize -> IO ()))
78+ , _jsaddleCallbacksPtrs_jsaddleSyncResult :: !(FunPtr (CString -> CSize -> Ptr CString -> Ptr CSize -> IO ()))
79+ , _jsaddleCallbacksPtrs_jsaddleJsData :: !CString
80+ }
81+
82+foreign import ccall "wrapper" wrapIO :: IO () -> IO (FunPtr (IO ()))
83+foreign import ccall "wrapper" wrapCStringCSizeIO :: (CString -> CSize -> IO ()) -> IO (FunPtr (CString -> CSize -> IO ()))
84+foreign import ccall "wrapper" wrapCStringCSizeCStringCSizeIO :: (CString -> CSize -> Ptr CString -> Ptr CSize -> IO ()) -> IO (FunPtr (CString -> CSize -> Ptr CString -> Ptr CSize -> IO ()))
85+
86+newCStringFromByteString :: ByteString -> IO (CString, CSize)
87+newCStringFromByteString bs = BSU.unsafeUseAsCStringLen bs $ \(src, len) -> do
88+ dest <- mallocArray0 len
89+ copyArray dest src len
90+ poke (advancePtr dest len) 0
91+ return (dest, fromIntegral len)
92+
93+jsaddleCallbacksToPtrs :: JSaddleCallbacks -> IO JSaddleCallbacksPtrs
94+jsaddleCallbacksToPtrs jc = JSaddleCallbacksPtrs
95+ <$> wrapIO (_jsaddleCallbacks_jsaddleStart jc)
96+ <*> wrapCStringCSizeIO (\cstr len -> _jsaddleCallbacks_jsaddleResult jc =<< BS.packCStringLen (cstr, fromIntegral len))
97+ <*> wrapCStringCSizeCStringCSizeIO (\cstr len result resultLen -> do
98+ inStr <- BS.packCStringLen (cstr, fromIntegral len)
99+ outStr <- _jsaddleCallbacks_jsaddleSyncResult jc inStr
100+ (outStrBytes, outStrLen) <- newCStringFromByteString outStr
101+ poke result outStrBytes
102+ poke resultLen outStrLen)
103+ <*> (fst <$> newCStringFromByteString (_jsaddleCallbacks_jsaddleJsData jc))
104+
105+instance Storable JSaddleCallbacksPtrs where
106+ sizeOf _ = #{size JSaddleCallbacks}
107+ alignment _ = #{alignment JSaddleCallbacks}
108+ poke p jc = do
109+ #{poke JSaddleCallbacks, jsaddleStart} p $ _jsaddleCallbacksPtrs_jsaddleStart jc
110+ #{poke JSaddleCallbacks, jsaddleResult} p $ _jsaddleCallbacksPtrs_jsaddleResult jc
111+ #{poke JSaddleCallbacks, jsaddleSyncResult} p $ _jsaddleCallbacksPtrs_jsaddleSyncResult jc
112+ #{poke JSaddleCallbacks, jsaddleJsData} p $ _jsaddleCallbacksPtrs_jsaddleJsData jc
113+ peek p = JSaddleCallbacksPtrs
114+ <$> #{peek JSaddleCallbacks, jsaddleStart} p
115+ <*> #{peek JSaddleCallbacks, jsaddleResult} p
116+ <*> #{peek JSaddleCallbacks, jsaddleSyncResult} p
117+ <*> #{peek JSaddleCallbacks, jsaddleJsData} p
reflex-dom/src/Reflex/Dom.hsnew file+11
@@ -0,0 +1,11 @@
1+-- Disable haddocks on this module due to a bug on haddocks when selectively
2+-- reexporting on ghc > 8.2.
3+-- https://github.com/haskell/haddock/issues/979
4+{-# OPTIONS_HADDOCK hide, prune, ignore-exports #-}
5+module Reflex.Dom (module X) where
6+
7+import Foreign.JavaScript.Orphans ()
8+import Reflex.Dom.Core as X hiding (mainWidget, mainWidgetInElementById, mainWidgetWithCss,
9+ mainWidgetWithHead, mainWidgetWithHead', runApp',
10+ mainHydrationWidgetWithHead, mainHydrationWidgetWithHead')
11+import Reflex.Dom.Internal as X
reflex-dom/src/Reflex/Dom/Internal.hsnew file+122
@@ -0,0 +1,122 @@
1+{-# LANGUAGE CPP #-}
2+{-# LANGUAGE LambdaCase #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE RankNTypes #-}
5+{-# LANGUAGE TypeFamilies #-}
6+module Reflex.Dom.Internal
7+ ( module Main
8+ , run
9+ , mainWidget
10+ , mainWidgetWithHead, mainWidgetWithCss, mainWidgetWithHead', mainWidgetInElementById, runApp'
11+ , mainHydrationWidgetWithHead, mainHydrationWidgetWithHead'
12+ ) where
13+
14+import Data.ByteString (ByteString)
15+import Data.Text (Text)
16+import Reflex.Dom.Core (Widget)
17+import Reflex.Dom.Main as Main hiding
18+ (mainWidget, mainWidgetWithHead, mainWidgetWithCss,
19+ mainWidgetWithHead', mainWidgetInElementById, runApp',
20+ mainHydrationWidgetWithHead, mainHydrationWidgetWithHead')
21+import qualified Reflex.Dom.Main as Main
22+ (mainWidget, mainWidgetWithHead, mainWidgetWithCss,
23+ mainWidgetWithHead', mainWidgetInElementById, runApp',
24+ mainHydrationWidgetWithHead, mainHydrationWidgetWithHead')
25+
26+#if defined(ghcjs_HOST_OS)
27+run :: a -> a
28+run = id
29+#elif defined(MIN_VERSION_jsaddle_warp)
30+import Data.Maybe (maybe)
31+import Data.Monoid ((<>))
32+import Language.Javascript.JSaddle (JSM)
33+import qualified Language.Javascript.JSaddle.Warp as JW
34+import System.Environment (lookupEnv)
35+
36+run :: JSM () -> IO()
37+run jsm = do
38+ port <- maybe 3003 read <$> lookupEnv "JSADDLE_WARP_PORT"
39+ putStrLn $ "Running jsaddle-warp server on port " <> show port
40+ JW.run port jsm
41+#elif defined(MIN_VERSION_jsaddle_wkwebview)
42+#if defined(ios_HOST_OS)
43+import Data.Default
44+import Data.Monoid ((<>))
45+import Language.Javascript.JSaddle (JSM)
46+import Language.Javascript.JSaddle.WKWebView (run', mainBundleResourcePath)
47+import Language.Javascript.JSaddle.WKWebView.Internal (jsaddleMainHTMLWithBaseURL)
48+
49+-- TODO: upstream to jsaddle-wkwebview
50+run :: JSM () -> IO ()
51+run jsm = do
52+ let indexHtml = "<!DOCTYPE html><html><head></head><body></body></html>"
53+ baseUrl <- mainBundleResourcePath >>= \case
54+ Nothing -> do
55+ putStrLn "Reflex.Dom.run: unable to find main bundle resource path. Assets may not load properly."
56+ return ""
57+ Just p -> return $ "file://" <> p <> "/index.html"
58+ run' def $ jsaddleMainHTMLWithBaseURL indexHtml baseUrl jsm
59+#else
60+import Language.Javascript.JSaddle.WKWebView (run)
61+#endif
62+#elif defined(ANDROID)
63+import Android.HaskellActivity
64+import Control.Monad
65+import Control.Concurrent
66+import Data.Default
67+import Data.String
68+import Reflex.Dom.Android.MainWidget
69+import System.IO
70+import Language.Javascript.JSaddle (JSM)
71+
72+run :: JSM () -> IO ()
73+run jsm = do
74+ hSetBuffering stdout LineBuffering
75+ hSetBuffering stderr LineBuffering
76+ continueWithCallbacks $ def
77+ { _activityCallbacks_onCreate = \_ -> do
78+ a <- getHaskellActivity
79+ let startPage = fromString "file:///android_asset/index.html"
80+ startMainWidget a startPage jsm
81+ }
82+ forever $ threadDelay 1000000000
83+#elif defined(wasm32_HOST_ARCH)
84+import qualified Language.Javascript.JSaddle.Wasm as Wasm (run)
85+import Language.Javascript.JSaddle (JSM)
86+run :: JSM () -> IO ()
87+run = Wasm.run 0
88+#else
89+import Language.Javascript.JSaddle.WebKitGTK (run)
90+#endif
91+
92+mainWidget :: (forall x. Widget x ()) -> IO ()
93+mainWidget w = run $ Main.mainWidget w
94+{-# INLINE mainWidget #-}
95+
96+mainWidgetWithHead :: (forall x. Widget x ()) -> (forall x. Widget x ()) -> IO ()
97+mainWidgetWithHead h b = run $ Main.mainWidgetWithHead h b
98+{-# INLINE mainWidgetWithHead #-}
99+
100+mainWidgetWithCss :: ByteString -> (forall x. Widget x ()) -> IO ()
101+mainWidgetWithCss css w = run $ Main.mainWidgetWithCss css w
102+{-# INLINE mainWidgetWithCss #-}
103+
104+mainWidgetWithHead' :: (a -> Widget () b, b -> Widget () a) -> IO ()
105+mainWidgetWithHead' w = run $ Main.mainWidgetWithHead' w
106+{-# INLINE mainWidgetWithHead' #-}
107+
108+mainWidgetInElementById :: Text -> (forall x. Widget x ()) -> IO ()
109+mainWidgetInElementById eid w = run $ Main.mainWidgetInElementById eid w
110+{-# INLINE mainWidgetInElementById #-}
111+
112+runApp' :: (forall x. AppInput DomTimeline -> Widget x (AppOutput DomTimeline)) -> IO ()
113+runApp' app = run $ Main.runApp' app
114+{-# INLINE runApp' #-}
115+
116+mainHydrationWidgetWithHead :: (forall x. HydrationWidget x ()) -> (forall x. HydrationWidget x ()) -> IO ()
117+mainHydrationWidgetWithHead h b = run $ Main.mainHydrationWidgetWithHead h b
118+{-# INLINE mainHydrationWidgetWithHead #-}
119+
120+mainHydrationWidgetWithHead' :: HydrationWidget () () -> HydrationWidget () () -> IO ()
121+mainHydrationWidgetWithHead' h b = run $ Main.mainHydrationWidgetWithHead' h b
122+{-# INLINE mainHydrationWidgetWithHead' #-}
release.nixnew file+63
@@ -0,0 +1,63 @@
1+{ reflex-platform-fun ? import ./dep/reflex-platform
2+, supportedSystems ? ["x86_64-linux" "x86_64-darwin"]
3+}:
4+
5+let
6+ native-reflex-platform = reflex-platform-fun {};
7+ inherit (native-reflex-platform.nixpkgs) lib;
8+
9+ tests = system: import ./test { pkgs = (reflex-platform-fun { inherit system; }).nixpkgs; };
10+
11+ perPlatform = lib.genAttrs supportedSystems (system: let
12+ reflex-platform = reflex-platform-fun { inherit system; };
13+ compilers = [
14+ "ghc"
15+ "ghcjs"
16+ ] ++ lib.optionals (reflex-platform.androidSupport) [
17+ "ghcAndroidAarch64"
18+ "ghcAndroidAarch32"
19+ ] ++ lib.optionals (reflex-platform.iosSupport) [
20+ "ghcIosAarch64"
21+ ];
22+ compilerPkgs = lib.genAttrs compilers (ghc: let
23+ reflex-platform = reflex-platform-fun {
24+ inherit system;
25+ haskellOverlays = [
26+ # Use this package's source for reflex
27+ (self: super: {
28+ _dep = super._dep // {
29+ reflex-dom = builtins.filterSource (path: type: !(builtins.elem (baseNameOf path) [
30+ ".git"
31+ "dist"
32+ "dist-newstyle"
33+ ]) && !(builtins.elem path [
34+ ./CONTRIBUTING.md
35+ ./FAQ.md
36+ ./Quickref.md
37+ ./README.md
38+ ./release.nix
39+ ./test
40+ ])) ./.;
41+ };
42+ })
43+ ];
44+ };
45+ all = tests system // {
46+ inherit (reflex-platform.${ghc})
47+ reflex-dom-core
48+ reflex-dom
49+ ;
50+ };
51+ in all // {
52+ cache = reflex-platform.pinBuildInputs "reflex-${system}-${ghc}"
53+ (builtins.attrValues all);
54+ });
55+ in compilerPkgs // {
56+ cache = reflex-platform.pinBuildInputs "reflex-${system}"
57+ (map (a: a.cache) (builtins.attrValues compilerPkgs));
58+ });
59+
60+ metaCache = native-reflex-platform.pinBuildInputs "reflex-dom-everywhere"
61+ (map (a: a.cache) (builtins.attrValues perPlatform));
62+
63+in perPlatform // { inherit metaCache; }
src-ghc/Reflex/Dom/Internal/Foreign.hsdeleted−168
@@ -1,168 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE ForeignFunctionInterface #-}
3−{-# LANGUAGE LambdaCase #-}
4−{-# LANGUAGE OverloadedStrings #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−module Reflex.Dom.Internal.Foreign where
7−
8−import Control.Concurrent
9−import Control.Exception (bracket)
10−import Control.Lens hiding (set)
11−import Control.Monad
12−import Control.Monad.State.Strict hiding (forM, forM_, get, mapM, mapM_, sequence, sequence_)
13−import Data.ByteString (ByteString)
14−import qualified Data.ByteString as BS
15−import Data.Maybe
16−import Data.Monoid
17−import Data.Text (Text)
18−import qualified Data.Text as T
19−import Foreign.Marshal hiding (void)
20−import Foreign.Ptr
21−import GHCJS.DOM hiding (runWebGUI)
22−import GHCJS.DOM.Navigator
23−import GHCJS.DOM.Window
24−import Graphics.UI.Gtk hiding (Widget)
25−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSBase
26−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSObjectRef
27−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSStringRef
28−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSValueRef
29−import Graphics.UI.Gtk.WebKit.JavaScriptCore.WebFrame
30−import Graphics.UI.Gtk.WebKit.Types hiding (Event, Text, Widget)
31−import Graphics.UI.Gtk.WebKit.WebFrame
32−import Graphics.UI.Gtk.WebKit.WebInspector
33−import Graphics.UI.Gtk.WebKit.WebSettings
34−import Graphics.UI.Gtk.WebKit.WebView
35−import System.Directory
36−import System.Glib.FFI hiding (void)
37−
38−#ifndef mingw32_HOST_OS
39−import System.Posix.Signals
40−#endif
41−
42−quitWebView :: WebView -> IO ()
43−quitWebView wv = postGUIAsync $ do w <- widgetGetToplevel wv --TODO: Shouldn't this be postGUISync?
44− widgetDestroy w
45−
46−installQuitHandler :: WebView -> IO ()
47−#ifdef mingw32_HOST_OS
48−installQuitHandler wv = return () -- TODO: Maybe figure something out here for Windows users.
49−#else
50−installQuitHandler wv = void $ installHandler keyboardSignal (Catch (quitWebView wv)) Nothing
51−#endif
52−
53−makeDefaultWebView :: Text -> (WebView -> IO ()) -> IO ()
54−makeDefaultWebView userAgentKey main = do
55− _ <- initGUI
56− window <- windowNew
57− _ <- timeoutAddFull (yield >> return True) priorityHigh 10
58− windowSetDefaultSize window 900 600
59− windowSetPosition window WinPosCenter
60− scrollWin <- scrolledWindowNew Nothing Nothing
61− webView <- webViewNew
62− settings <- webViewGetWebSettings webView
63− userAgent <- settings `get` webSettingsUserAgent
64− settings `set` [ webSettingsUserAgent := userAgent <> " " <> userAgentKey
65− , webSettingsEnableUniversalAccessFromFileUris := True
66− , webSettingsEnableDeveloperExtras := True
67− ]
68− webViewSetWebSettings webView settings
69− window `containerAdd` scrollWin
70− scrollWin `containerAdd` webView
71− _ <- on window objectDestroy . liftIO $ mainQuit
72− widgetShowAll window
73− _ <- webView `on` loadFinished $ \_ -> do
74− main webView --TODO: Should probably only do this once
75− inspector <- webViewGetInspector webView
76− _ <- inspector `on` inspectWebView $ \_ -> do
77− inspectorWindow <- windowNew
78− windowSetDefaultSize inspectorWindow 900 600
79− inspectorScrollWin <- scrolledWindowNew Nothing Nothing
80− inspectorWebView <- webViewNew
81− inspectorWindow `containerAdd` inspectorScrollWin
82− inspectorScrollWin `containerAdd` inspectorWebView
83− widgetShowAll inspectorWindow
84− return inspectorWebView
85− wf <- webViewGetMainFrame webView
86− pwd <- getCurrentDirectory
87− webFrameLoadString wf "" Nothing $ "file://" <> pwd <> "/"
88− installQuitHandler webView
89− mainGUI
90−
91−runWebGUI :: (WebView -> IO ()) -> IO ()
92−runWebGUI = runWebGUI' "GHCJS"
93−
94−runWebGUI' :: Text -> (WebView -> IO ()) -> IO ()
95−runWebGUI' userAgentKey main = do
96− -- Are we in a java script inside some kind of browser
97− mbWindow <- currentWindow
98− case mbWindow of
99− Just window -> do
100− -- Check if we are running in javascript inside the the native version
101− Just n <- getNavigator window
102− agent <- getUserAgent n
103− unless ((" " <> userAgentKey) `T.isSuffixOf` agent) $ main (castToWebView window)
104− Nothing -> do
105− makeDefaultWebView userAgentKey main
106−
107−foreign import ccall "wrapper"
108− wrapper :: JSObjectCallAsFunctionCallback' -> IO JSObjectCallAsFunctionCallback
109−
110−toJSObject :: JSContextRef -> [Ptr OpaqueJSValue] -> IO JSObjectRef
111−toJSObject ctx args = do
112− o <- jsobjectmake ctx nullPtr nullPtr
113− iforM_ args $ \n a -> do
114− prop <- jsstringcreatewithutf8cstring $ show n
115− jsobjectsetproperty ctx o prop a 1 nullPtr
116− return o
117−
118−fromJSStringMaybe :: JSContextRef -> JSValueRef -> IO (Maybe Text)
119−fromJSStringMaybe c t = do
120− isNull <- jsvalueisnull c t
121− if isNull then return Nothing else do
122− j <- jsvaluetostringcopy c t nullPtr
123− l <- jsstringgetmaximumutf8cstringsize j
124− s <- allocaBytes (fromIntegral l) $ \ps -> do
125− _ <- jsstringgetutf8cstring'_ j ps (fromIntegral l)
126− peekCString ps
127− return $ Just $ T.pack s
128−
129−getLocationHost :: WebView -> IO Text
130−getLocationHost wv = withWebViewContext wv $ \c -> do
131− script <- jsstringcreatewithutf8cstring "location.host"
132− lh <- jsevaluatescript c script nullPtr nullPtr 1 nullPtr
133− lh' <- fromJSStringMaybe c lh
134− return $ fromMaybe "" lh'
135−
136−getLocationProtocol :: WebView -> IO Text
137−getLocationProtocol wv = withWebViewContext wv $ \c -> do
138− script <- jsstringcreatewithutf8cstring "location.protocol"
139− lp <- jsevaluatescript c script nullPtr nullPtr 1 nullPtr
140− lp' <- fromJSStringMaybe c lp
141− return $ fromMaybe "" lp'
142−
143−bsToArrayBuffer :: JSContextRef -> ByteString -> IO JSValueRef
144−bsToArrayBuffer c bs = do
145− elems <- forM (BS.unpack bs) $ \x -> jsvaluemakenumber c $ fromIntegral x
146− let numElems = length elems
147− bracket (mallocArray numElems) free $ \elemsArr -> do
148− pokeArray elemsArr elems
149− a <- jsobjectmakearray c (fromIntegral numElems) elemsArr nullPtr
150− newUint8Array <- jsstringcreatewithutf8cstring "new Uint8Array(this)"
151− jsevaluatescript c newUint8Array a nullPtr 1 nullPtr
152−
153−bsFromArrayBuffer :: JSContextRef -> JSValueRef -> IO ByteString
154−bsFromArrayBuffer c a = do
155− let getIntegral = fmap round . (\x -> jsvaluetonumber c x nullPtr)
156− getByteLength <- jsstringcreatewithutf8cstring "this.byteLength"
157− byteLength <- getIntegral =<< jsevaluatescript c getByteLength a nullPtr 1 nullPtr
158− toUint8Array <- jsstringcreatewithutf8cstring "new Uint8Array(this)"
159− uint8Array <- jsevaluatescript c toUint8Array a nullPtr 1 nullPtr
160− getIx <- jsstringcreatewithutf8cstring "this[0][this[1]]"
161− let arrayLookup i = do
162− i' <- jsvaluemakenumber c (fromIntegral i)
163− args <- toJSObject c [uint8Array, i']
164− getIntegral =<< jsevaluatescript c getIx args nullPtr 1 nullPtr
165− BS.pack <$> forM [0..byteLength-1] arrayLookup
166−
167−withWebViewContext :: WebView -> (JSContextRef -> IO a) -> IO a
168−withWebViewContext wv f = f =<< webFrameGetGlobalContext =<< webViewGetMainFrame wv
src-ghc/Reflex/Dom/WebSocket/Foreign.hsdeleted−83
@@ -1,83 +0,0 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE JavaScriptFFI #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NoMonomorphismRestriction #-}
9−{-# LANGUAGE PolyKinds #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE UndecidableInstances #-}
14−
15−module Reflex.Dom.WebSocket.Foreign where
16−
17−import Prelude hiding (all, concat, concatMap, div, mapM, mapM_, sequence, span)
18−
19−import Control.Exception
20−import Control.Monad.State
21−import Data.ByteString (ByteString)
22−import qualified Data.ByteString as BS
23−import Data.Text (Text)
24−import qualified Data.Text as T
25−import Data.Text.Encoding
26−import Foreign.Marshal hiding (void)
27−import Foreign.Ptr
28−import Foreign.Storable
29−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSBase
30−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSObjectRef
31−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSStringRef
32−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSValueRef
33−import Graphics.UI.Gtk.WebKit.WebView
34−
35−import Reflex.Dom.Internal.Foreign
36−
37−data JSWebSocket = JSWebSocket { wsValue :: JSValueRef
38− , wsContext :: JSContextRef
39− }
40−
41−newWebSocket :: WebView -> Text -> (ByteString -> IO ()) -> IO () -> IO () -> IO JSWebSocket
42−newWebSocket wv url onMessage onOpen onClose = withWebViewContext wv $ \c -> do
43− url' <- jsvaluemakestring c =<< jsstringcreatewithutf8cstring (T.unpack url)
44− newWSArgs <- toJSObject c [url']
45− newWS <- jsstringcreatewithutf8cstring "(function(that) { var ws = new WebSocket(that[0]); ws['binaryType'] = 'arraybuffer'; return ws; })(this)"
46− ws <- jsevaluatescript c newWS newWSArgs nullPtr 1 nullPtr
47− onMessage' <- wrapper $ \_ _ _ _ args _ -> do
48− e <- peekElemOff args 0
49− dataProp <- jsstringcreatewithutf8cstring "data"
50− msg <- jsobjectgetproperty c e dataProp nullPtr
51− msg' <- fromJSStringMaybe c msg
52− case msg' of
53− Nothing -> return ()
54− Just m -> onMessage $ encodeUtf8 m
55− jsvaluemakeundefined c
56− onMessageCb <- jsobjectmakefunctionwithcallback c nullPtr onMessage'
57− onOpen' <- wrapper $ \_ _ _ _ _ _ -> do
58− onOpen
59− jsvaluemakeundefined c
60− onOpenCb <- jsobjectmakefunctionwithcallback c nullPtr onOpen'
61− onClose' <- wrapper $ \_ _ _ _ _ _ -> do
62− onClose
63− jsvaluemakeundefined c
64− onCloseCb <- jsobjectmakefunctionwithcallback c nullPtr onClose'
65− o <- toJSObject c [ws, onMessageCb, onOpenCb, onCloseCb]
66− addCbs <- jsstringcreatewithutf8cstring "this[0]['onmessage'] = this[1]; this[0]['onopen'] = this[2]; this[0]['onclose'] = this[3];"
67− _ <- jsevaluatescript c addCbs o nullPtr 1 nullPtr
68− return $ JSWebSocket ws c
69−
70−webSocketSend :: JSWebSocket -> ByteString -> IO ()
71−webSocketSend (JSWebSocket ws c) bs = do
72− elems <- forM (BS.unpack bs) $ \x -> jsvaluemakenumber c $ fromIntegral x
73− let numElems = length elems
74− bs' <- bracket (mallocArray numElems) free $ \elemsArr -> do
75− pokeArray elemsArr elems
76− a <- jsobjectmakearray c (fromIntegral numElems) elemsArr nullPtr
77− newUint8Array <- jsstringcreatewithutf8cstring "new Uint8Array(this)"
78− jsevaluatescript c newUint8Array a nullPtr 1 nullPtr
79− send <- jsstringcreatewithutf8cstring "this[0]['send'](String['fromCharCode']['apply'](null, this[1]))"
80− sendArgs <- toJSObject c [ws, bs']
81− _ <- jsevaluatescript c send sendArgs nullPtr 1 nullPtr
82− return ()
83−
src-ghc/Reflex/Dom/Xhr/Foreign.hsdeleted−224
@@ -1,224 +0,0 @@
1−{-# LANGUAGE FlexibleInstances #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−{-# LANGUAGE QuasiQuotes #-}
4−{-# LANGUAGE TypeSynonymInstances #-}
5−module Reflex.Dom.Xhr.Foreign ( module Reflex.Dom.Xhr.Foreign
6− , XhrResponseType
7− ) where
8−
9−import Control.Concurrent.MVar
10−import Control.Exception.Base
11−import Control.Monad
12−import Data.Text (Text)
13−import qualified Data.Text as T
14−import GHCJS.DOM.File
15−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSBase
16−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSObjectRef
17−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSStringRef
18−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSValueRef
19−import Graphics.UI.Gtk.WebKit.Types hiding (Text)
20−import Reflex.Dom.Xhr.Exception
21−import Reflex.Dom.Xhr.ResponseType
22−import System.Glib.FFI
23−
24−import Reflex.Dom.Internal.Foreign
25−
26−import Text.RawString.QQ
27−
28−data XMLHttpRequest
29− = XMLHttpRequest { xhrValue :: JSValueRef
30− , xhrContext :: JSContextRef --TODO: Get rid of this
31− }
32− deriving (Eq, Ord)
33−
34−class IsXhrPayload a where
35− xmlHttpRequestSend :: XMLHttpRequest -> a -> IO ()
36−
37−instance IsXhrPayload () where
38− xmlHttpRequestSend xhr _ = xmlHttpRequestSendPayload xhr Nothing
39−
40−instance IsXhrPayload Text where
41− xmlHttpRequestSend xhr = xmlHttpRequestSendPayload xhr . Just
42−
43−instance IsXhrPayload File where
44− xmlHttpRequestSend = error "xmlHttpRequestSend{File}: not implemented"
45−
46−stringToJSValue :: JSContextRef -> Text -> IO JSValueRef
47−stringToJSValue ctx s = jsvaluemakestring ctx =<< jsstringcreatewithutf8cstring (T.unpack s)
48−
49−fromResponseType :: XhrResponseType -> Text
50−fromResponseType XhrResponseType_Default = ""
51−fromResponseType XhrResponseType_ArrayBuffer = "arraybuffer"
52−fromResponseType XhrResponseType_Blob = "blob"
53−fromResponseType XhrResponseType_Text = "text"
54−
55−toResponseType :: Text -> Maybe XhrResponseType
56−toResponseType "" = Just XhrResponseType_Default
57−toResponseType "arraybuffer" = Just XhrResponseType_ArrayBuffer
58−toResponseType "blob" = Just XhrResponseType_Blob
59−toResponseType "text" = Just XhrResponseType_Text
60−toResponseType _ = Nothing
61−
62−xmlHttpRequestNew :: WebView -> IO XMLHttpRequest
63−xmlHttpRequestNew wv = withWebViewContext wv $ \jsContext -> do
64− xhrScript <- jsstringcreatewithutf8cstring "new XMLHttpRequest()"
65− xhr' <- jsevaluatescript jsContext xhrScript nullPtr nullPtr 1 nullPtr
66− jsvalueprotect jsContext xhr'
67− return $ XMLHttpRequest xhr' jsContext
68−
69−xmlHttpRequestOpen :: XMLHttpRequest -> Text -> Text -> Bool -> Text -> Text -> IO ()
70−xmlHttpRequestOpen xhr method url async user password = do
71− let c = xhrContext xhr
72− method' <- stringToJSValue c method
73− url' <- stringToJSValue c url
74− async' <- jsvaluemakeboolean (xhrContext xhr) async
75− user' <- stringToJSValue c user
76− password' <- stringToJSValue c password
77− o <- toJSObject c [xhrValue xhr, method', url', async', user', password']
78− script <- jsstringcreatewithutf8cstring "this[0].open(this[1], this[2], this[3], this[4], this[5])"
79− _ <- jsevaluatescript c script o nullPtr 1 nullPtr
80− return ()
81−
82−xmlHttpRequestOnreadystatechange :: XMLHttpRequest -> IO () -> IO ()
83−xmlHttpRequestOnreadystatechange xhr userCallback = do
84− let c = xhrContext xhr
85− fp <- wrapper $ \_ _ _ _ _ _ -> do
86− userCallback
87− jsvaluemakeundefined c
88− cb <- jsobjectmakefunctionwithcallback c nullPtr fp
89− o <- toJSObject c [xhrValue xhr, cb]
90− script <- jsstringcreatewithutf8cstring "this[0].onreadystatechange=this[1]"
91− _ <- jsevaluatescript c script o nullPtr 1 nullPtr
92− return ()
93−
94−xmlHttpRequestGetReadyState :: XMLHttpRequest -> IO Word
95−xmlHttpRequestGetReadyState xhr = do
96− let c = xhrContext xhr
97− script <- jsstringcreatewithutf8cstring "this.readyState"
98− rs <- jsevaluatescript c script (xhrValue xhr) nullPtr 1 nullPtr
99− d <- jsvaluetonumber c rs nullPtr
100− return $ truncate d
101−
102−xmlHttpRequestGetResponseType :: XMLHttpRequest -> IO (Maybe XhrResponseType)
103−xmlHttpRequestGetResponseType xhr = do
104− script <- jsstringcreatewithutf8cstring "this.responseType"
105− rt <- jsevaluatescript (xhrContext xhr) script (xhrValue xhr) nullPtr 1 nullPtr
106− ms <- fromJSStringMaybe (xhrContext xhr) rt
107− return $ join $ fmap toResponseType ms
108−
109−xmlHttpRequestGetResponse :: XMLHttpRequest -> IO (Maybe XhrResponseBody)
110−xmlHttpRequestGetResponse xhr = do
111− let c = xhrContext xhr
112− mrt <- xmlHttpRequestGetResponseType xhr
113− script <- jsstringcreatewithutf8cstring "this.response"
114− t <- jsevaluatescript c script (xhrValue xhr) nullPtr 1 nullPtr
115− isNull <- jsvalueisnull c t
116− if isNull then return Nothing else case mrt of
117− Just XhrResponseType_ArrayBuffer -> Just . XhrResponseBody_ArrayBuffer <$> bsFromArrayBuffer c t
118− Just XhrResponseType_Blob -> Just . XhrResponseBody_Blob . Blob . castForeignPtr <$> newForeignPtr_ t
119− Just XhrResponseType_Default -> fmap XhrResponseBody_Default <$> fromJSStringMaybe c t
120− Just XhrResponseType_Text -> fmap XhrResponseBody_Text <$> fromJSStringMaybe c t
121− _ -> return Nothing
122−
123−xmlHttpRequestGetResponseText :: XMLHttpRequest -> IO (Maybe Text)
124−xmlHttpRequestGetResponseText xhr = do
125− let c = xhrContext xhr
126− script <- jsstringcreatewithutf8cstring "this.responseText"
127− t <- jsevaluatescript c script (xhrValue xhr) nullPtr 1 nullPtr
128− fromJSStringMaybe c t
129−
130−xmlHttpRequestSendPayload :: XMLHttpRequest -> Maybe Text -> IO ()
131−xmlHttpRequestSendPayload xhr payload = do
132− let c = xhrContext xhr
133− result <- newEmptyMVar
134− let wrapper' x = wrapper $ \_ _ _ _ _ _ -> putMVar result x >> jsvaluemakeundefined c
135− bracket (wrapper' $ Just XhrException_Aborted) freeHaskellFunPtr $ \a -> do
136− onAbort <- jsobjectmakefunctionwithcallback c nullPtr a
137− bracket (wrapper' $ Just XhrException_Error) freeHaskellFunPtr $ \e -> do
138− onError <- jsobjectmakefunctionwithcallback c nullPtr e
139− bracket (wrapper' Nothing) freeHaskellFunPtr $ \l -> do
140− onLoad <- jsobjectmakefunctionwithcallback c nullPtr l
141− d <- case payload of
142− Nothing -> jsvaluemakeundefined c
143− Just payload' -> stringToJSValue c payload'
144− o <- toJSObject c [xhrValue xhr, d, onError, onAbort, onLoad]
145− s <- jsstringcreatewithutf8cstring send
146− _ <- jsevaluatescript c s o nullPtr 1 nullPtr
147− takeMVar result >>= mapM_ throwIO
148− where
149− send = [r|
150− (function (xhr, d, onError, onAbort, onLoad) {
151− var clear;
152− var error = function () {
153− clear(); onError();
154− };
155− var abort = function () {
156− clear(); onAbort();
157− };
158− var load = function () {
159− clear(); onLoad();
160− };
161− clear = function () {
162− xhr.removeEventListener('error', error);
163− xhr.removeEventListener('abort', abort);
164− xhr.removeEventListener('load', load);
165− }
166− xhr.addEventListener('error', error);
167− xhr.addEventListener('abort', abort);
168− xhr.addEventListener('load', load);
169− if(d) {
170− xhr.send(d);
171− } else {
172− xhr.send();
173− }
174− })(this[0], this[1], this[2], this[3], this[4])
175− |]
176−
177−xmlHttpRequestSetRequestHeader :: XMLHttpRequest -> Text -> Text -> IO ()
178−xmlHttpRequestSetRequestHeader xhr header value = do
179− let c = xhrContext xhr
180− header' <- stringToJSValue c header
181− value' <- stringToJSValue c value
182− o <- toJSObject c [xhrValue xhr, header', value']
183− script <- jsstringcreatewithutf8cstring "this[0].setRequestHeader(this[1], this[2])"
184− _ <- jsevaluatescript c script o nullPtr 1 nullPtr
185− return ()
186−
187−xmlHttpRequestSetResponseType :: XMLHttpRequest -> Text -> IO ()
188−xmlHttpRequestSetResponseType xhr t = do
189− let c = xhrContext xhr
190− t' <- stringToJSValue c t
191− o <- toJSObject c [xhrValue xhr, t']
192− script <- jsstringcreatewithutf8cstring "this[0].responseType = this[1]"
193− _ <- jsevaluatescript c script o nullPtr 1 nullPtr
194− return ()
195−
196−xmlHttpRequestGetStatus :: XMLHttpRequest -> IO Word
197−xmlHttpRequestGetStatus xhr = do
198− let c = xhrContext xhr
199− script <- jsstringcreatewithutf8cstring "this.status"
200− s <- jsevaluatescript c script (xhrValue xhr) nullPtr 1 nullPtr
201− d <- jsvaluetonumber c s nullPtr
202− return $ truncate d
203−
204−xmlHttpRequestGetStatusText :: XMLHttpRequest -> IO Text
205−xmlHttpRequestGetStatusText xhr = do
206− let c = xhrContext xhr
207− script <- jsstringcreatewithutf8cstring "this.statusText"
208− t <- jsevaluatescript c script (xhrValue xhr) nullPtr 1 nullPtr
209− j <- jsvaluetostringcopy c t nullPtr
210− l <- jsstringgetmaximumutf8cstringsize j
211− s <- allocaBytes (fromIntegral l) $ \ps -> do
212− _ <- jsstringgetutf8cstring'_ j ps (fromIntegral l)
213− peekCString ps
214− return $ T.pack s
215−
216−xmlHttpRequestSetWithCredentials :: XMLHttpRequest -> Bool -> IO ()
217−xmlHttpRequestSetWithCredentials xhr b = do
218− let c = xhrContext xhr
219− b' <- jsvaluemakeboolean c b
220− o <- toJSObject c [xhrValue xhr, b']
221− script <- jsstringcreatewithutf8cstring "this[0].withCredentials = this[1]"
222− _ <- jsevaluatescript c script o nullPtr 1 nullPtr
223− return ()
224−
src-ghcjs/Reflex/Dom/Internal/Foreign.hsdeleted−43
@@ -1,43 +0,0 @@
1−{-# LANGUAGE ForeignFunctionInterface #-}
2−{-# LANGUAGE JavaScriptFFI #-}
3−module Reflex.Dom.Internal.Foreign ( module Reflex.Dom.Internal.Foreign
4− , runWebGUI
5− ) where
6−
7−import Data.ByteString (ByteString)
8−import qualified Data.ByteString as BS
9−import Foreign
10−import Foreign.C
11−import qualified GHCJS.Buffer as JS
12−import GHCJS.DOM
13−import GHCJS.DOM.Types
14−import qualified GHCJS.Marshal.Pure as JS
15−import GHCJS.Types
16−import JavaScript.TypedArray.ArrayBuffer as JS
17−
18−quitWebView :: WebView -> IO ()
19−quitWebView = error "quitWebView: unimplemented in GHCJS"
20−
21−foreign import javascript unsafe "location['host']" getLocationHost_ :: IO JSString
22−
23−getLocationHost :: FromJSString r => a -> IO r
24−getLocationHost _ = fmap fromJSString getLocationHost_
25−
26−foreign import javascript unsafe "location['protocol']" getLocationProtocol_ :: IO JSString
27−
28−getLocationProtocol :: FromJSString r => a -> IO r
29−getLocationProtocol _ = fmap fromJSString getLocationProtocol_
30−
31−withWebViewContext :: a -> (a -> IO b) -> IO b
32−withWebViewContext a f = f a
33−
34−foreign import javascript safe "new DataView($3,$1,$2)" js_dataView :: Int -> Int -> JSVal -> JSVal
35−
36−foreign import javascript unsafe "new Uint8Array($1_1['buf'], $1_2, $2)['buffer']" extractByteArray :: Ptr CChar -> Int -> IO JSVal
37−
38−bsToArrayBuffer :: a -> ByteString -> IO JSVal
39−bsToArrayBuffer _ bs = BS.useAsCString bs $ \cStr -> do
40− extractByteArray cStr $ BS.length bs
41−
42−bsFromArrayBuffer :: a -> JSVal -> IO ByteString
43−bsFromArrayBuffer _ ab = fmap (JS.toByteString 0 Nothing . JS.createFromArrayBuffer) $ JS.unsafeFreeze $ JS.pFromJSVal ab
src-ghcjs/Reflex/Dom/WebSocket/Foreign.hsdeleted−51
@@ -1,51 +0,0 @@
1−{-# LANGUAGE ForeignFunctionInterface #-}
2−{-# LANGUAGE JavaScriptFFI #-}
3−
4−module Reflex.Dom.WebSocket.Foreign where
5−
6−import Prelude hiding (all, concat, concatMap, div, mapM, mapM_, sequence, span)
7−
8−import Control.Monad.IO.Class
9−import Control.Monad.Reader
10−import Data.ByteString (ByteString)
11−import qualified Data.ByteString as BS
12−import Data.Text (Text)
13−import Data.Text.Encoding
14−import GHCJS.Buffer
15−import GHCJS.DOM.EventM (on)
16−import GHCJS.DOM.MessageEvent
17−import GHCJS.DOM.Types hiding (Text)
18−import GHCJS.DOM.WebSocket (closeEvent, message, open)
19−import qualified GHCJS.DOM.WebSocket as GD
20−import GHCJS.Foreign.Internal
21−import GHCJS.Marshal.Pure
22−import GHCJS.Types
23−import JavaScript.TypedArray.ArrayBuffer as JS
24−
25−data JSWebSocket = JSWebSocket { unWebSocket :: WebSocket }
26−
27−newWebSocket :: a -> Text -> (ByteString -> IO ()) -> IO () -> IO () -> IO JSWebSocket
28−newWebSocket _ url onMessage onOpen onClose = do
29− ws <- GD.newWebSocket url (Just [] :: Maybe [Text])
30− _ <- on ws open $ liftIO onOpen
31− GD.setBinaryType ws "arraybuffer"
32− _ <- on ws message $ do
33− e <- ask
34− d <- getData e
35− liftIO $ case jsTypeOf d of
36− String -> onMessage $ encodeUtf8 $ pFromJSVal d
37− _ -> do
38− ab <- unsafeFreeze $ pFromJSVal d
39− onMessage $ toByteString 0 Nothing $ createFromArrayBuffer ab
40− _ <- on ws closeEvent $ liftIO onClose
41− return $ JSWebSocket ws
42−
43−webSocketSend :: JSWebSocket -> ByteString -> IO ()
44−webSocketSend (JSWebSocket ws) bs = do
45− let (b, off, len) = fromByteString bs
46− ab <- ArrayBuffer <$> if BS.length bs == 0 --TODO: remove this logic when https://github.com/ghcjs/ghcjs-base/issues/49 is fixed
47− then jsval . getArrayBuffer <$> create 0
48− else return $ js_dataView off len $ jsval $ getArrayBuffer b
49− GD.send ws $ Just ab
50−
51−foreign import javascript safe "new DataView($3,$1,$2)" js_dataView :: Int -> Int -> JSVal -> JSVal
src/Foreign/JavaScript/TH.hsdeleted−519
@@ -1,519 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE EmptyDataDecls #-}
3−{-# LANGUAGE ExistentialQuantification #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE ForeignFunctionInterface #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE StandaloneDeriving #-}
12−{-# LANGUAGE TemplateHaskell #-}
13−{-# LANGUAGE TypeFamilies #-}
14−{-# LANGUAGE TypeSynonymInstances #-}
15−{-# LANGUAGE UndecidableInstances #-}
16−#ifdef __GHCJS__
17−{-# LANGUAGE JavaScriptFFI #-}
18−#endif
19−module Foreign.JavaScript.TH ( module Foreign.JavaScript.TH
20− , Safety (..)
21− ) where
22−
23−import Reflex.Class
24−import Reflex.Dom.Deletable.Class
25−import Reflex.Dom.PerformEvent.Class
26−import Reflex.Host.Class
27−
28−import Language.Haskell.TH
29−
30−#ifdef __GHCJS__
31−import qualified GHCJS.Buffer as JS
32−import GHCJS.DOM
33−import GHCJS.DOM.Types hiding (Text, fromJSString)
34−import qualified GHCJS.DOM.Types as JS
35−import qualified GHCJS.Foreign as JS
36−import qualified GHCJS.Foreign.Callback as JS
37−import qualified GHCJS.Foreign.Callback.Internal (Callback (..))
38−import qualified GHCJS.Marshal as JS
39−import qualified GHCJS.Marshal.Pure as JS
40−import qualified GHCJS.Types as JS
41−import qualified JavaScript.Array as JS
42−import qualified JavaScript.Array.Internal (SomeJSArray (..))
43−import qualified JavaScript.Object as JS
44−import qualified JavaScript.Object.Internal (Object (..))
45−import qualified JavaScript.TypedArray.ArrayBuffer as JSArrayBuffer
46−
47−import Data.Hashable
48−import Data.Word
49−import Foreign.C.Types
50−import Foreign.Ptr
51−import Text.Encoding.Z
52−#else
53−import Foreign.Marshal
54−import Graphics.UI.Gtk.WebKit.DOM.Node
55−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSBase
56−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSObjectRef
57−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSStringRef
58−import Graphics.UI.Gtk.WebKit.JavaScriptCore.JSValueRef
59−import Graphics.UI.Gtk.WebKit.JavaScriptCore.WebFrame
60−import Graphics.UI.Gtk.WebKit.WebView
61−import System.Glib.FFI
62−#endif
63−
64−import Control.Concurrent
65−import Control.Monad
66−import Control.Monad.Exception
67−import Control.Monad.Fix
68−import Control.Monad.IO.Class
69−import Control.Monad.Reader
70−import Control.Monad.Ref
71−import Control.Monad.State
72−import qualified Control.Monad.State.Strict as Strict
73−import Control.Monad.Trans.Control
74−import Data.ByteString (ByteString)
75−import qualified Data.ByteString as BS
76−import Data.Coerce
77−import Data.Monoid
78−import Data.Text (Text)
79−import qualified Data.Text as T
80−
81−class Monad m => HasWebView m where
82− type WebViewPhantom m :: *
83− askWebView :: m (WebViewSingleton (WebViewPhantom m))
84−
85−instance HasWebView m => HasWebView (ReaderT r m) where
86− type WebViewPhantom (ReaderT r m) = WebViewPhantom m
87− askWebView = lift askWebView
88−
89−instance HasWebView m => HasWebView (StateT r m) where
90− type WebViewPhantom (StateT r m) = WebViewPhantom m
91− askWebView = lift askWebView
92−
93−instance HasWebView m => HasWebView (Strict.StateT r m) where
94− type WebViewPhantom (Strict.StateT r m) = WebViewPhantom m
95− askWebView = lift askWebView
96−
97−newtype WithWebView x m a = WithWebView { unWithWebView :: ReaderT (WebViewSingleton x) m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadTrans, MonadException, MonadAsyncException)
98−
99−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (WithWebView x m) where
100− {-# INLINABLE newEventWithTrigger #-}
101− newEventWithTrigger = lift . newEventWithTrigger
102− {-# INLINABLE newFanEventWithTrigger #-}
103− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
104−
105−instance MonadSubscribeEvent t m => MonadSubscribeEvent t (WithWebView x m) where
106− {-# INLINABLE subscribeEvent #-}
107− subscribeEvent = lift . subscribeEvent
108−
109−instance MonadReflexHost t m => MonadReflexHost t (WithWebView x m) where
110− type ReadPhase (WithWebView x m) = ReadPhase m
111− {-# INLINABLE fireEventsAndRead #-}
112− fireEventsAndRead dm a = lift $ fireEventsAndRead dm a
113− {-# INLINABLE runHostFrame #-}
114− runHostFrame = lift . runHostFrame
115−
116−instance MonadSample t m => MonadSample t (WithWebView x m) where
117− {-# INLINABLE sample #-}
118− sample = lift . sample
119−
120−instance MonadHold t m => MonadHold t (WithWebView x m) where
121− {-# INLINABLE hold #-}
122− hold v0 = lift . hold v0
123− {-# INLINABLE holdDyn #-}
124− holdDyn v0 = lift . holdDyn v0
125− {-# INLINABLE holdIncremental #-}
126− holdIncremental v0 = lift . holdIncremental v0
127−
128−instance MonadTransControl (WithWebView x) where
129− type StT (WithWebView x) a = StT (ReaderT (WebViewSingleton x)) a
130− {-# INLINABLE liftWith #-}
131− liftWith = defaultLiftWith WithWebView unWithWebView
132− {-# INLINABLE restoreT #-}
133− restoreT = defaultRestoreT WithWebView
134−
135−instance PerformEvent t m => PerformEvent t (WithWebView x m) where
136− type Performable (WithWebView x m) = WithWebView x (Performable m)
137− {-# INLINABLE performEvent_ #-}
138− performEvent_ e = liftWith $ \run -> performEvent_ $ fmap run e
139− {-# INLINABLE performEvent #-}
140− performEvent e = liftWith $ \run -> performEvent $ fmap run e
141−
142−instance Deletable t m => Deletable t (WithWebView x m) where
143− {-# INLINABLE deletable #-}
144− deletable = liftThrough . deletable
145−
146−runWithWebView :: WithWebView x m a -> WebViewSingleton x -> m a
147−runWithWebView = runReaderT . unWithWebView
148−
149−instance (Monad m) => HasWebView (WithWebView x m) where
150− type WebViewPhantom (WithWebView x m) = x
151− askWebView = WithWebView ask
152−
153−instance MonadRef m => MonadRef (WithWebView x m) where
154− type Ref (WithWebView x m) = Ref m
155− newRef = lift . newRef
156− readRef = lift . readRef
157− writeRef r = lift . writeRef r
158−
159−instance MonadAtomicRef m => MonadAtomicRef (WithWebView x m) where
160− atomicModifyRef r = lift . atomicModifyRef r
161−
162−withWebViewSingleton :: WebView -> (forall x. WebViewSingleton x -> r) -> r
163−withWebViewSingleton wv f = f $ WebViewSingleton wv
164−
165−-- | A singleton type for a given WebView; we use this to statically guarantee that different WebViews (and thus different javscript contexts) don't get mixed up
166−newtype WebViewSingleton x = WebViewSingleton { unWebViewSingleton :: WebView }
167−
168−#ifdef __GHCJS__
169−type JSFFI_Internal = JS.MutableJSArray -> IO JS.JSVal
170−newtype JSFFI = JSFFI JSFFI_Internal
171−#else
172−newtype JSFFI = JSFFI String
173−#endif
174−
175−newtype JSFun x = JSFun { unJSFun :: JSRef x }
176−
177−instance ToJS x (JSFun x) where
178− withJS (JSFun r) f = f r
179−
180−instance FromJS x (JSFun x) where
181− fromJS = return . JSFun
182−
183−class IsJSContext x where
184− data JSRef x
185−
186−class (Monad m, MonadIO (JSM m), MonadFix (JSM m), MonadJS x (JSM m)) => HasJS x m | m -> x where
187− type JSM m :: * -> *
188− liftJS :: JSM m a -> m a
189−
190−instance HasJS x m => HasJS x (ReaderT r m) where
191− type JSM (ReaderT r m) = JSM m
192− liftJS = lift . liftJS
193−
194−-- | A Monad that is capable of executing JavaScript
195−class Monad m => MonadJS x m | m -> x where
196− runJS :: JSFFI -> [JSRef x] -> m (JSRef x)
197− forkJS :: m () -> m ThreadId
198− mkJSUndefined :: m (JSRef x)
199− isJSNull :: JSRef x -> m Bool
200− isJSUndefined :: JSRef x -> m Bool
201− fromJSBool :: JSRef x -> m Bool
202− fromJSString :: JSRef x -> m String
203− fromJSArray :: JSRef x -> m [JSRef x]
204− fromJSUint8Array :: JSRef x -> m ByteString
205− fromJSNumber :: JSRef x -> m Double
206− withJSBool :: Bool -> (JSRef x -> m r) -> m r
207− withJSString :: String -> (JSRef x -> m r) -> m r
208− withJSNumber :: Double -> (JSRef x -> m r) -> m r
209− withJSArray :: [JSRef x] -> (JSRef x -> m r) -> m r
210− withJSUint8Array :: ByteString -> (JSUint8Array x -> m r) -> m r
211− -- | Create a JSFun with zero arguments; should be equilvant to `syncCallback AlwaysRetain True` in GHCJS
212− mkJSFun :: ([JSRef x] -> m (JSRef x)) -> m (JSFun x) --TODO: Support 'this', exceptions
213− freeJSFun :: JSFun x -> m ()
214− setJSProp :: String -> JSRef x -> JSRef x -> m ()
215− getJSProp :: String -> JSRef x -> m (JSRef x)
216− withJSNode :: Node -> (JSRef x -> m r) -> m r
217−
218−#ifdef __GHCJS__
219−
220−data JSCtx_IO
221−
222−instance MonadIO m => HasJS JSCtx_IO (WithWebView x m) where
223− type JSM (WithWebView x m) = IO
224− liftJS = liftIO
225−
226−instance IsJSContext JSCtx_IO where
227− newtype JSRef JSCtx_IO = JSRef_IO { unJSRef_IO :: JS.JSVal }
228−
229−instance MonadJS JSCtx_IO IO where
230− runJS (JSFFI f) l = fmap JSRef_IO . f =<< JS.fromListIO (coerce l)
231− forkJS = forkIO
232− mkJSUndefined = return $ JSRef_IO JS.jsUndefined
233− isJSNull (JSRef_IO r) = return $ JS.isNull r
234− isJSUndefined (JSRef_IO r) = return $ JS.isUndefined r
235− fromJSBool (JSRef_IO r) = return $ JS.fromJSBool r
236− fromJSString (JSRef_IO r) = return $ JS.fromJSString $ JS.pFromJSVal r
237− fromJSArray (JSRef_IO r) = fmap coerce $ JS.toListIO $ coerce r
238− fromJSUint8Array (JSRef_IO r) = fmap (JS.toByteString 0 Nothing . JS.createFromArrayBuffer) $ JSArrayBuffer.unsafeFreeze $ JS.pFromJSVal r --TODO: Assert that this is immutable
239− fromJSNumber (JSRef_IO r) = do
240− Just n <- JS.fromJSVal r
241− return n
242− withJSBool b f = f $ JSRef_IO $ JS.toJSBool b
243− withJSString s f = f $ JSRef_IO $ JS.pToJSVal $ JS.toJSString s
244− withJSNumber n f = do
245− r <- JS.toJSVal n
246− f $ JSRef_IO r
247− withJSArray l f = do
248− r <- JS.fromListIO $ coerce l
249− f $ JSRef_IO $ coerce r
250− withJSUint8Array payload f = BS.useAsCString payload $ \cStr -> do
251− ba <- extractByteArray cStr $ BS.length payload
252− f $ JSUint8Array $ JSRef_IO ba
253− mkJSFun f = do
254− cb <- JS.syncCallback1' $ \args -> do
255− l <- JS.toListIO $ coerce args
256− JSRef_IO result <- f $ coerce l
257− return result
258− fmap (JSFun . JSRef_IO) $ funWithArguments $ coerce cb
259− freeJSFun (JSFun (JSRef_IO r)) = JS.releaseCallback $ coerce r
260− setJSProp s (JSRef_IO v) (JSRef_IO o) = JS.setProp (JS.toJSString s) v $ coerce o
261− getJSProp s (JSRef_IO o) = do
262− r <- JS.getProp (JS.toJSString s) $ coerce o
263− return $ JSRef_IO r
264− withJSNode n f = f $ JSRef_IO $ unNode n
265−
266−foreign import javascript unsafe "new Uint8Array($1_1.buf, $1_2, $2)" extractByteArray :: Ptr CChar -> Int -> IO JS.JSVal
267−
268−foreign import javascript unsafe "function(){ return $1(arguments); }" funWithArguments :: JS.Callback (JS.MutableJSArray -> IO a) -> IO JS.JSVal
269−
270−#else
271−
272−askJSContext :: MonadIO m => WithWebView x m JSContextRef
273−askJSContext = do
274− wv <- askWebView
275− liftIO $ webFrameGetGlobalContext =<< webViewGetMainFrame (unWebViewSingleton wv)
276−
277−-- | Make a JS string available that is not wrapped up as a JSValueRef
278−withJSStringRaw :: MonadAsyncException m => String -> (JSStringRef -> m r) -> m r
279−withJSStringRaw str a = do
280− bracket (liftIO $ jsstringcreatewithutf8cstring str) (liftIO . jsstringrelease) $ \strRef -> do
281− a strRef
282−
283−fromJSNumberRaw :: MonadIO m => JSValueRef -> WithWebView x m Double
284−fromJSNumberRaw val = do
285− jsContext <- askJSContext
286− liftIO $ jsvaluetonumber jsContext val nullPtr --TODO: Exceptions
287−
288−
289−data JSCtx_JavaScriptCore x
290−
291−instance IsJSContext (JSCtx_JavaScriptCore x) where
292− newtype JSRef (JSCtx_JavaScriptCore x) = JSRef_JavaScriptCore { unJSRef_JavaScriptCore :: JSValueRef }
293−
294−instance MonadIO m => HasJS (JSCtx_JavaScriptCore x) (WithWebView x m) where
295− type JSM (WithWebView x m) = WithWebView x IO
296− liftJS a = do
297− wv <- askWebView
298− liftIO $ runWithWebView a wv
299−
300−instance MonadJS (JSCtx_JavaScriptCore x) (WithWebView x IO) where
301− runJS (JSFFI body) args = do
302− jsContext <- askJSContext
303− withJSArray args $ \(JSRef_JavaScriptCore this) -> liftIO $ do
304− result <- bracket (jsstringcreatewithutf8cstring body) jsstringrelease $ \script -> jsevaluatescript jsContext script this nullPtr 1 nullPtr
305− return $ JSRef_JavaScriptCore result --TODO: Protect and unprotect result
306− forkJS a = do
307− wv <- askWebView
308− liftIO $ forkIO $ runWithWebView a wv
309− mkJSUndefined = do
310− jsContext <- askJSContext
311− fmap JSRef_JavaScriptCore $ liftIO $ jsvaluemakeundefined jsContext
312− isJSNull (JSRef_JavaScriptCore r) = do
313− jsContext <- askJSContext
314− liftIO $ jsvalueisnull jsContext r
315− isJSUndefined (JSRef_JavaScriptCore r) = do
316− jsContext <- askJSContext
317− liftIO $ jsvalueisundefined jsContext r
318− fromJSBool (JSRef_JavaScriptCore r) = do
319− jsContext <- askJSContext
320− liftIO $ jsvaluetoboolean jsContext r
321− fromJSString (JSRef_JavaScriptCore r) = do
322− jsContext <- askJSContext
323− liftIO $ do
324− s <- jsvaluetostringcopy jsContext r nullPtr --TODO: Deal with exceptions
325− l <- jsstringgetmaximumutf8cstringsize s
326− allocaBytes (fromIntegral l) $ \ps -> do
327− _ <- jsstringgetutf8cstring'_ s ps (fromIntegral l)
328− peekCString ps
329− withJSBool b a = do
330− jsContext <- askJSContext
331− valRef <- liftIO $ jsvaluemakeboolean jsContext b
332− a $ JSRef_JavaScriptCore valRef
333− withJSString str a = do
334− jsContext <- askJSContext
335− withJSStringRaw str $ \strRef -> do
336− valRef <- liftIO $ jsvaluemakestring jsContext strRef
337− a $ JSRef_JavaScriptCore valRef --TODO: Protect/unprotect valRef
338− withJSNumber n a = do
339− jsContext <- askJSContext
340− valRef <- liftIO $ jsvaluemakenumber jsContext n
341− a $ JSRef_JavaScriptCore valRef --TODO: Protect/unprotect valRef
342− withJSArray elems a = do
343− jsContext <- askJSContext
344− let numElems = length elems
345− bracket (liftIO $ mallocArray numElems) (liftIO . free) $ \elemsArr -> do
346− liftIO $ pokeArray elemsArr $ coerce elems
347− bracket (liftIO $ jsobjectmakearray jsContext (fromIntegral numElems) elemsArr nullPtr) (const $ return ()) $ \arrRef -> do --TODO: Do we need to protect/unprotect the array object?
348− a $ JSRef_JavaScriptCore arrRef --TODO: Protect/unprotect valRef
349− --TODO: When supported by webkitgtk3-javascriptcore, go directly from C string to Uint8Array without creating each item individually
350− withJSUint8Array payload f = withJSArrayFromList (BS.unpack payload) $ \x -> do
351− payloadRef <- runJS (JSFFI "new Uint8Array(this[0])") [x]
352− f $ JSUint8Array payloadRef
353− fromJSArray (JSRef_JavaScriptCore a) = do
354− jsContext <- askJSContext
355− lenRef <- withJSStringRaw "length" $ \lengthStr -> do
356− liftIO $ jsobjectgetproperty jsContext a lengthStr nullPtr --TODO: Exceptions
357− lenDouble <- fromJSNumberRaw lenRef
358− let len = round lenDouble
359− liftIO $ forM [0..len-1] $ \i -> do
360− JSRef_JavaScriptCore <$> jsobjectgetpropertyatindex jsContext a i nullPtr --TODO: Exceptions
361− fromJSUint8Array a = do
362− vals <- fromJSArray a
363− doubles <- mapM fromJSNumber vals
364− return $ BS.pack $ map round doubles
365− fromJSNumber (JSRef_JavaScriptCore val) = do
366− jsContext <- askJSContext
367− liftIO $ jsvaluetonumber jsContext val nullPtr --TODO: Exceptions
368− mkJSFun a = do
369− wv <- askWebView
370− jsContext <- askJSContext
371− cb <- liftIO $ mkJSObjectCallAsFunctionCallback $ \_ _ _ argc argv _ -> do --TODO: Use the exception pointer to handle haskell exceptions
372− args <- forM [0..fromIntegral (argc-1)] $ \n -> do
373− x <- peekElemOff argv n
374− jsvalueprotect jsContext x
375− return $ JSRef_JavaScriptCore x --TODO: Unprotect eventually
376− unJSRef_JavaScriptCore <$> runWithWebView (a args) wv
377− cbRef <- liftIO $ jsobjectmakefunctionwithcallback jsContext nullPtr cb
378− liftIO $ jsvalueprotect jsContext cbRef
379− return $ JSFun $ JSRef_JavaScriptCore cbRef
380− freeJSFun (JSFun (JSRef_JavaScriptCore f)) = do
381− jsContext <- askJSContext
382− liftIO $ jsvalueunprotect jsContext f
383− setJSProp propName (JSRef_JavaScriptCore valRef) (JSRef_JavaScriptCore objRef) = do
384− withJSStringRaw propName $ \propNameRaw -> do
385− jsContext <- askJSContext
386− liftIO $ jsobjectsetproperty jsContext objRef propNameRaw valRef 0 nullPtr --TODO: property attribute, exceptions
387− getJSProp propName (JSRef_JavaScriptCore objRef) = do
388− withJSStringRaw propName $ \propNameRaw -> do
389− jsContext <- askJSContext
390− liftIO $ JSRef_JavaScriptCore <$> jsobjectgetproperty jsContext objRef propNameRaw nullPtr --TODO: property attribute, exceptions
391− withJSNode = error "withJSNode is only supported in ghcjs"
392−
393−#endif
394−
395−class FromJS x a where
396− fromJS :: MonadJS x m => JSRef x -> m a
397−
398−instance FromJS x () where
399− fromJS _ = return () --TODO: Should this do some kind of checking for the js value?
400−
401−instance FromJS x Bool where
402− fromJS = fromJSBool
403−
404−instance ToJS x Bool where
405− withJS = withJSBool
406−
407−instance FromJS x String where
408− fromJS = fromJSString
409−
410−instance FromJS x Text where
411− fromJS s = T.pack <$> fromJSString s
412−
413−instance FromJS x a => FromJS x (Maybe a) where
414− fromJS x = do
415− n <- isJSNull x
416− if n then return Nothing else Just <$> fromJS x
417−
418−class ToJS x a where
419− withJS :: MonadJS x m => a -> (JSRef x -> m r) -> m r
420−
421−instance ToJS x (JSRef x) where
422− withJS r = ($ r)
423−
424−instance FromJS x (JSRef x) where
425− fromJS = return
426−
427−instance ToJS x String where
428− withJS = withJSString
429−
430−instance ToJS x Text where
431− withJS = withJSString . T.unpack
432−
433−newtype JSArray a = JSArray { unJSArray :: [a] }
434−
435−instance ToJS x a => ToJS x (JSArray a) where
436− withJS = withJSArrayFromList . unJSArray
437−
438−instance FromJS x a => FromJS x (JSArray a) where
439− fromJS = fmap JSArray . mapM fromJS <=< fromJSArray
440−
441−withJSArrayFromList :: (ToJS x a, MonadJS x m) => [a] -> (JSRef x -> m r) -> m r
442−withJSArrayFromList as f = go as []
443− where go [] jsRefs = withJSArray (reverse jsRefs) f
444− go (h:t) jsRefs = withJS h $ \hRef -> go t (hRef : jsRefs)
445−
446−newtype JSUint8Array x = JSUint8Array { unJSUint8Array :: JSRef x }
447−
448−instance ToJS x (JSUint8Array x) where
449− withJS (JSUint8Array r) = ($ r)
450−
451−instance FromJS x (JSUint8Array x) where
452− fromJS = return . JSUint8Array
453−
454−instance ToJS x Word8 where
455− withJS n = withJSNumber $ fromIntegral n --TODO: Check things; throw exceptions
456−
457−instance ToJS x Int where
458− withJS n = withJSNumber $ fromIntegral n --TODO: Check things; throw exceptions
459−
460−instance FromJS x Int where
461− fromJS = fmap round . fromJSNumber --TODO: Check things; throw exceptions
462−
463−instance ToJS x Double where
464− withJS = withJSNumber
465−
466−instance FromJS x Double where
467− fromJS = fromJSNumber
468−
469−instance ToJS x Node where
470− withJS = withJSNode
471−
472−
473−importJS :: Safety -> String -> String -> Q Type -> Q [Dec]
474−importJS safety body name qt = do
475− t <- qt
476− let (argTypes, _) = parseType t
477− argNames <- forM argTypes $ \_ -> do
478− arg <- newName "arg"
479− argRef <- newName "argRef"
480− return (arg, argRef)
481− (jsffiDecs, jsffiExp) <- mkJSFFI safety body
482− let go [] = [| runJS $(return jsffiExp) $(listE $ map (varE . snd) argNames) >>= fromJS
483− |]
484− go ((arg, argRef) : args) = [| withJS $(varE arg) $ $(lamE [varP argRef] $ go args) |]
485− e <- lamE (map (varP. fst) argNames) $ go argNames
486− let n = mkName name
487− return $ jsffiDecs ++
488− [ SigD n t
489− , ValD (VarP n) (NormalB e) []
490− ]
491−
492−mkJSFFI :: Safety -> String -> Q ([Dec], Exp)
493−#ifdef __GHCJS__
494−mkJSFFI safety body = do
495− -- n <- newName "jsffi" --TODO: Should use newName, but that doesn't seem to work with ghcjs
496− l <- location
497− n <- newName $ "jsffi_" <> zEncodeString (loc_package l <> ":" <> loc_module l) <> "_" <> show (abs (hash (show safety, body)))
498− t <- [t| JSFFI_Internal |]
499− let wrappedBody = "(function(){ return (" <> body <> "); }).apply($1)"
500− let decs = [ForeignD $ ImportF JavaScript safety wrappedBody n t]
501− e <- [| JSFFI $(varE n) |]
502− return (decs, e)
503−#else
504−mkJSFFI _ body = do
505− e <- [| JSFFI body |]
506− return ([], e)
507−#endif
508−
509−parseType :: Type -> ([Type], Type)
510−parseType (ForallT _ [AppT (AppT (ConT monadJs) (VarT _)) (VarT m)] funType)
511− | monadJs == ''MonadJS = go funType
512− where go t = case t of
513− AppT (AppT ArrowT arg) t' ->
514− let (args, result) = go t'
515− in (arg : args, result)
516− AppT (VarT m') result
517− | m' == m -> ([], result)
518− _ -> error $ "parseType: can't parse type " <> show t
519−parseType t = error $ "parseType: can't parse type " <> show t
src/Reflex/Dom.hsdeleted−17
@@ -1,17 +0,0 @@
1−module Reflex.Dom (module X) where
2−
3−import Reflex as X
4−import Reflex.Dom.Builder.Class as X
5−import Reflex.Dom.Builder.Immediate as X
6−import Reflex.Dom.Builder.Static as X
7−import Reflex.Dom.Class as X
8−import Reflex.Dom.DynamicWriter as X
9−import Reflex.Dom.Internal as X
10−import Reflex.Dom.Location as X
11−import Reflex.Dom.Old as X
12−import Reflex.Dom.PerformEvent.Class as X
13−import Reflex.Dom.PostBuild.Class as X
14−import Reflex.Dom.Time as X
15−import Reflex.Dom.WebSocket as X
16−import Reflex.Dom.Widget as X
17−import Reflex.Dom.Xhr as X
src/Reflex/Dom/Builder/Class.hsdeleted−375
@@ -1,375 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE DefaultSignatures #-}
4−{-# LANGUAGE DeriveFunctor #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE LambdaCase #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE OverloadedStrings #-}
11−{-# LANGUAGE PolyKinds #-}
12−{-# LANGUAGE RankNTypes #-}
13−{-# LANGUAGE ScopedTypeVariables #-}
14−{-# LANGUAGE TemplateHaskell #-}
15−{-# LANGUAGE TypeFamilies #-}
16−{-# LANGUAGE UndecidableInstances #-}
17−module Reflex.Dom.Builder.Class
18− ( module Reflex.Dom.Builder.Class
19− , module Reflex.Dom.Builder.Class.Events
20− , module Reflex.Dom.Deletable.Class
21− ) where
22−
23−import Reflex
24−import Reflex.Dom.Builder.Class.Events
25−import Reflex.Dom.Deletable.Class
26−
27−import qualified Control.Category
28−import Control.Lens hiding (element)
29−import Control.Monad.Reader
30−import Control.Monad.Trans.Control
31−import Data.Default
32−import Data.Functor.Misc
33−import Data.Map (Map)
34−import Data.Proxy
35−import Data.Semigroup
36−import Data.Text (Text)
37−import Data.Type.Coercion
38−import GHC.Exts (Constraint)
39−
40−class Default (EventSpec d EventResult) => DomSpace d where
41− type EventSpec d :: (EventTag -> *) -> *
42− type RawTextNode d :: *
43− type RawElement d :: *
44− type RawInputElement d :: *
45− type RawTextAreaElement d :: *
46−
47−-- | @'DomBuilder' t m@ indicates that @m@ is a 'Monad' capable of building dynamic DOM in the 'Reflex' timeline @t@
48−class (Monad m, Reflex t, Deletable t m, DomSpace (DomBuilderSpace m)) => DomBuilder t m | m -> t where
49− type DomBuilderSpace m :: *
50− textNode :: TextNodeConfig t -> m (TextNode (DomBuilderSpace m) t)
51− element :: Text -> ElementConfig er t m -> m a -> m (Element er (DomBuilderSpace m) t, a)
52− -- | Create a placeholder in the DOM, with the ability to insert new DOM before it
53− -- The provided DOM will be executed after the current frame, so it will not be affected by any occurrences that are concurrent with the occurrence that created it
54− placeholder :: PlaceholderConfig above t m -> m (Placeholder above t)
55− inputElement :: InputElementConfig er t m -> m (InputElement er (DomBuilderSpace m) t)
56− textAreaElement :: TextAreaElementConfig er t m -> m (TextAreaElement er (DomBuilderSpace m) t)
57− placeRawElement :: RawElement (DomBuilderSpace m) -> m ()
58− wrapRawElement :: RawElement (DomBuilderSpace m) -> RawElementConfig er t m -> m (Element er (DomBuilderSpace m) t)
59−
60−type Namespace = Text
61−
62−data TextNodeConfig t
63− = TextNodeConfig { _textNodeConfig_initialContents :: Text
64− , _textNodeConfig_setContents :: Event t Text
65− }
66−
67−instance (Reflex t) => Default (TextNodeConfig t) where
68− {-# INLINABLE def #-}
69− def = TextNodeConfig
70− { _textNodeConfig_initialContents = mempty
71− , _textNodeConfig_setContents = never
72− }
73−
74−data TextNode d t = TextNode
75− { _textNode_raw :: RawTextNode d
76− }
77−
78−type AttributeName = (Maybe Namespace, Text)
79−
80−data Propagation
81− = Propagation_Continue
82− | Propagation_Stop
83− | Propagation_StopImmediate
84− deriving (Show, Read, Eq, Ord)
85−
86−instance Semigroup Propagation where
87− {-# INLINABLE (<>) #-}
88− (<>) = max
89−
90−instance Monoid Propagation where
91− {-# INLINABLE mempty #-}
92− mempty = Propagation_Continue
93− {-# INLINABLE mappend #-}
94− mappend = (<>)
95−
96−data EventFlags = EventFlags --TODO: Monoid; ways of building each flag
97− { _eventFlags_propagation :: Propagation
98− , _eventFlags_preventDefault :: Bool
99− }
100−
101−instance Semigroup EventFlags where
102− {-# INLINABLE (<>) #-}
103− EventFlags p pd <> EventFlags p' pd' = EventFlags (p <> p') (pd || pd')
104−
105−instance Monoid EventFlags where
106− {-# INLINABLE mempty #-}
107− mempty = EventFlags Propagation_Continue False
108− {-# INLINABLE mappend #-}
109− mappend = (<>)
110−
111−preventDefault :: EventFlags
112−preventDefault = mempty { _eventFlags_preventDefault = True }
113−
114−stopPropagation :: EventFlags
115−stopPropagation = mempty { _eventFlags_propagation = Propagation_Stop }
116−
117−data ElementConfig er t m
118− = ElementConfig { _elementConfig_namespace :: Maybe Namespace
119− , _elementConfig_initialAttributes :: Map AttributeName Text
120− , _elementConfig_modifyAttributes :: Event t (Map AttributeName (Maybe Text))
121− , _elementConfig_eventSpec :: EventSpec (DomBuilderSpace m) er
122− }
123−
124−instance (Reflex t, er ~ EventResult, DomBuilder t m) => Default (ElementConfig er t m) where
125− {-# INLINABLE def #-}
126− def = ElementConfig
127− { _elementConfig_namespace = Nothing
128− , _elementConfig_initialAttributes = mempty
129− , _elementConfig_modifyAttributes = never
130− , _elementConfig_eventSpec = def
131− }
132−
133−data Element er d t
134− = Element { _element_events :: EventSelector t (WrapArg er EventName) --TODO: EventSelector should have two arguments
135− , _element_raw :: RawElement d
136− }
137−
138−data PlaceholderConfig above t m
139− = PlaceholderConfig { _placeholderConfig_insertAbove :: Event t (m above)
140− , _placeholderConfig_deleteSelf :: Event t ()
141− }
142−
143−instance Reflex t => Default (PlaceholderConfig above t m) where
144− {-# INLINABLE def #-}
145− def = PlaceholderConfig
146− { _placeholderConfig_insertAbove = never
147− , _placeholderConfig_deleteSelf = never
148− }
149−
150−data Placeholder above t
151− = Placeholder { _placeholder_insertedAbove :: Event t above
152− , _placeholder_deletedSelf :: Event t ()
153− }
154−
155−data InputElementConfig er t m
156− = InputElementConfig { _inputElementConfig_initialValue :: Text
157− , _inputElementConfig_setValue :: Event t Text
158− , _inputElementConfig_initialChecked :: Bool
159− , _inputElementConfig_setChecked :: Event t Bool
160− , _inputElementConfig_elementConfig :: ElementConfig er t m
161− }
162−
163−instance (Reflex t, er ~ EventResult, DomBuilder t m) => Default (InputElementConfig er t m) where
164− {-# INLINABLE def #-}
165− def = InputElementConfig
166− { _inputElementConfig_initialValue = ""
167− , _inputElementConfig_setValue = never
168− , _inputElementConfig_initialChecked = False
169− , _inputElementConfig_setChecked = never
170− , _inputElementConfig_elementConfig = def
171− }
172−
173−data InputElement er d t
174− = InputElement { _inputElement_value :: Dynamic t Text
175− , _inputElement_checked :: Dynamic t Bool
176− , _inputElement_checkedChange :: Event t Bool
177− , _inputElement_input :: Event t Text
178− , _inputElement_hasFocus :: Dynamic t Bool
179− , _inputElement_element :: Element er d t
180− , _inputElement_raw :: RawInputElement d
181− }
182−
183−data TextAreaElementConfig er t m
184− = TextAreaElementConfig { _textAreaElementConfig_initialValue :: Text
185− , _textAreaElementConfig_setValue :: Event t Text
186− , _textAreaElementConfig_elementConfig :: ElementConfig er t m
187− }
188−
189−instance (Reflex t, er ~ EventResult, DomBuilder t m) => Default (TextAreaElementConfig er t m) where
190− {-# INLINABLE def #-}
191− def = TextAreaElementConfig
192− { _textAreaElementConfig_initialValue = ""
193− , _textAreaElementConfig_setValue = never
194− , _textAreaElementConfig_elementConfig = def
195− }
196−
197−data TextAreaElement er d t
198− = TextAreaElement { _textAreaElement_value :: Dynamic t Text
199− , _textAreaElement_input :: Event t Text
200− , _textAreaElement_hasFocus :: Dynamic t Bool
201− , _textAreaElement_element :: Element er d t
202− , _textAreaElement_raw :: RawTextAreaElement d
203− }
204−
205−extractRawElementConfig :: ElementConfig er t m -> RawElementConfig er t m
206−extractRawElementConfig cfg = RawElementConfig
207− { _rawElementConfig_modifyAttributes = _elementConfig_modifyAttributes cfg
208− , _rawElementConfig_eventSpec = _elementConfig_eventSpec cfg
209− }
210−
211−data RawElementConfig er t m = RawElementConfig
212− { _rawElementConfig_modifyAttributes :: Event t (Map AttributeName (Maybe Text))
213− , _rawElementConfig_eventSpec :: EventSpec (DomBuilderSpace m) er
214− }
215−
216−instance (Reflex t, DomSpace (DomBuilderSpace m)) => Default (RawElementConfig EventResult t m) where
217− def = RawElementConfig
218− { _rawElementConfig_modifyAttributes = never
219− , _rawElementConfig_eventSpec = def
220− }
221−
222−makeLenses ''TextNodeConfig
223−makeLenses ''ElementConfig
224−makeLenses ''PlaceholderConfig
225−makeLenses ''InputElementConfig
226−makeLenses ''TextAreaElementConfig
227−makeLenses ''RawElementConfig
228−
229−class CanDeleteSelf t a | a -> t where
230− deleteSelf :: Lens' a (Event t ())
231−
232−instance CanDeleteSelf t (PlaceholderConfig above t m) where
233− {-# INLINABLE deleteSelf #-}
234− deleteSelf = placeholderConfig_deleteSelf
235−
236−class InsertAbove t m above above' a a' | a -> t m above, a' -> t m above', a above' -> a', a' above -> a where
237− insertAbove :: Lens a a' (Event t (m above)) (Event t (m above'))
238−
239−instance InsertAbove t m above above' (PlaceholderConfig above t m) (PlaceholderConfig above' t m) where
240− insertAbove = placeholderConfig_insertAbove
241−
242−class InitialAttributes a where
243− initialAttributes :: Lens' a (Map AttributeName Text)
244−
245−instance InitialAttributes (ElementConfig er t m) where
246− {-# INLINABLE initialAttributes #-}
247− initialAttributes = elementConfig_initialAttributes
248−
249−class ModifyAttributes t a | a -> t where
250− modifyAttributes :: Lens' a (Event t (Map AttributeName (Maybe Text)))
251−
252−instance ModifyAttributes t (ElementConfig er t m) where
253− {-# INLINABLE modifyAttributes #-}
254− modifyAttributes = elementConfig_modifyAttributes
255−
256−instance ModifyAttributes t (RawElementConfig er t m) where
257− {-# INLINABLE modifyAttributes #-}
258− modifyAttributes = rawElementConfig_modifyAttributes
259−
260−class HasNamespace a where
261− namespace :: Lens' a (Maybe Namespace)
262−
263−instance HasNamespace (ElementConfig er t m) where
264− {-# INLINABLE namespace #-}
265− namespace = elementConfig_namespace
266−
267−-- * Convenience functions
268−
269−--TODO: Move/replace
270−class Functor1 (f :: (k -> *) -> *) where
271− type Functor1Constraint f (a :: k -> *) (b :: k -> *) :: Constraint
272− type Functor1Constraint f a b = ()
273− fmap1 :: Functor1Constraint f a b => (forall x. a x -> b x) -> f a -> f b
274−
275−instance Functor1 (ElementConfig er t) where
276− type Functor1Constraint (ElementConfig er t) a b = DomBuilderSpace a ~ DomBuilderSpace b
277− {-# INLINABLE fmap1 #-}
278− fmap1 _ cfg = cfg
279− { _elementConfig_eventSpec = _elementConfig_eventSpec cfg
280− }
281−
282−instance Reflex t => Functor1 (PlaceholderConfig above t) where
283− {-# INLINABLE fmap1 #-}
284− fmap1 f cfg = cfg
285− { _placeholderConfig_insertAbove = f <$> _placeholderConfig_insertAbove cfg
286− }
287−
288−instance Functor1 (InputElementConfig er t) where
289− type Functor1Constraint (InputElementConfig er t) a b = Functor1Constraint (ElementConfig er t) a b
290− fmap1 f cfg = cfg & inputElementConfig_elementConfig %~ fmap1 f
291−
292−instance Functor1 (TextAreaElementConfig er t) where
293− type Functor1Constraint (TextAreaElementConfig er t) a b = Functor1Constraint (ElementConfig er t) a b
294− fmap1 f cfg = cfg & textAreaElementConfig_elementConfig %~ fmap1 f
295−
296−instance Functor1 (RawElementConfig er t) where
297− type Functor1Constraint (RawElementConfig er t) a b = DomBuilderSpace a ~ DomBuilderSpace b
298− {-# INLINABLE fmap1 #-}
299− fmap1 _ cfg = cfg
300− { _rawElementConfig_eventSpec = _rawElementConfig_eventSpec cfg
301− }
302−
303−class HasDomEvent t target eventName where
304− type DomEventType target eventName :: *
305− domEvent :: EventName eventName -> target -> Event t (DomEventType target eventName)
306−
307−instance Reflex t => HasDomEvent t (Element EventResult d t) en where
308− type DomEventType (Element EventResult d t) en = EventResultType en
309− {-# INLINABLE domEvent #-}
310− domEvent en e = unEventResult <$> Reflex.select (_element_events e) (WrapArg en)
311−
312−instance Reflex t => HasDomEvent t (InputElement EventResult d t) en where
313− type DomEventType (InputElement EventResult d t) en = EventResultType en
314− {-# INLINABLE domEvent #-}
315− domEvent en = domEvent en . _inputElement_element
316−
317−instance Reflex t => HasDomEvent t (TextAreaElement EventResult d t) en where
318− type DomEventType (TextAreaElement EventResult d t) en = EventResultType en
319− {-# INLINABLE domEvent #-}
320− domEvent en = domEvent en . _textAreaElement_element
321−
322−instance DomBuilder t m => DomBuilder t (ReaderT r m) where
323− type DomBuilderSpace (ReaderT r m) = DomBuilderSpace m
324− {-# INLINABLE textNode #-}
325− textNode = liftTextNode
326− element = liftElement
327− placeholder = liftPlaceholder
328− inputElement = liftInputElement
329− textAreaElement = liftTextAreaElement
330− placeRawElement = lift . placeRawElement
331− wrapRawElement = liftWrapRawElement
332−
333−type LiftDomBuilder t f m =
334− ( Reflex t
335− , MonadTransControlStateless f
336− , Monad m
337− , DomBuilder t m
338− , DomBuilderSpace (f m) ~ DomBuilderSpace m
339− )
340−
341−class MonadTransControl t => MonadTransControlStateless t where
342− stTCoercion :: proxy t -> Coercion (StT t a) a
343− default stTCoercion :: proxy t -> Coercion a a
344− stTCoercion _ = Control.Category.id
345−
346−toStT :: MonadTransControlStateless t => proxy t -> a -> StT t a
347−toStT = coerceWith . sym . stTCoercion
348−
349−fromStT :: MonadTransControlStateless t => proxy t -> StT t a -> a
350−fromStT = coerceWith . stTCoercion
351−
352−instance MonadTransControlStateless (ReaderT r)
353−
354−type RunStateless t = forall n b. Monad n => t n b -> n b
355−
356−liftWithStateless :: forall m t a. (Monad m, MonadTransControlStateless t) => (RunStateless t -> m a) -> t m a
357−liftWithStateless a = liftWith $ \run -> a $ \x -> fromStT (Proxy :: Proxy t) <$> run x
358−
359−liftTextNode :: (MonadTrans f, DomBuilder t m) => TextNodeConfig t -> f m (TextNode (DomBuilderSpace m) t)
360−liftTextNode = lift . textNode
361−
362−liftElement :: LiftDomBuilder t f m => Text -> ElementConfig er t (f m) -> f m a -> f m (Element er (DomBuilderSpace m) t, a)
363−liftElement elementTag cfg child = liftWithStateless $ \run -> element elementTag (fmap1 run cfg) $ run child
364−
365−liftPlaceholder :: LiftDomBuilder t f m => PlaceholderConfig above t (f m) -> f m (Placeholder above t)
366−liftPlaceholder cfg = liftWithStateless $ \run -> placeholder $ fmap1 run cfg
367−
368−liftInputElement :: LiftDomBuilder t f m => InputElementConfig er t (f m) -> f m (InputElement er (DomBuilderSpace m) t)
369−liftInputElement cfg = liftWithStateless $ \run -> inputElement $ fmap1 run cfg
370−
371−liftTextAreaElement :: LiftDomBuilder t f m => TextAreaElementConfig er t (f m) -> f m (TextAreaElement er (DomBuilderSpace m) t)
372−liftTextAreaElement cfg = liftWithStateless $ \run -> textAreaElement $ fmap1 run cfg
373−
374−liftWrapRawElement :: LiftDomBuilder t f m => RawElement (DomBuilderSpace m) -> RawElementConfig er t (f m) -> f m (Element er (DomBuilderSpace m) t)
375−liftWrapRawElement e es = liftWithStateless $ \run -> wrapRawElement e $ fmap1 run es
src/Reflex/Dom/Builder/Class/Events.hsdeleted−164
@@ -1,164 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE GADTs #-}
3−{-# LANGUAGE KindSignatures #-}
4−{-# LANGUAGE PolyKinds #-}
5−{-# LANGUAGE TemplateHaskell #-}
6−{-# LANGUAGE TypeFamilies #-}
7−module Reflex.Dom.Builder.Class.Events where
8−
9−import Data.GADT.Compare.TH
10−
11−data EventTag
12− = AbortTag
13− | BlurTag
14− | ChangeTag
15− | ClickTag
16− | ContextmenuTag
17− | DblclickTag
18− | DragTag
19− | DragendTag
20− | DragenterTag
21− | DragleaveTag
22− | DragoverTag
23− | DragstartTag
24− | DropTag
25− | ErrorTag
26− | FocusTag
27− | InputTag
28− | InvalidTag
29− | KeydownTag
30− | KeypressTag
31− | KeyupTag
32− | LoadTag
33− | MousedownTag
34− | MouseenterTag
35− | MouseleaveTag
36− | MousemoveTag
37− | MouseoutTag
38− | MouseoverTag
39− | MouseupTag
40− | MousewheelTag
41− | ScrollTag
42− | SelectTag
43− | SubmitTag
44− | WheelTag
45− {-
46− | BeforecutTag
47− | CutTag
48− | BeforecopyTag
49− | CopyTag
50− | BeforepasteTag
51− | PasteTag
52−-}
53− | ResetTag
54− | SearchTag
55−-- | SelectstartTag
56− | TouchstartTag
57− | TouchmoveTag
58− | TouchendTag
59− | TouchcancelTag
60−
61−data EventName :: EventTag -> * where
62− Abort :: EventName 'AbortTag
63− Blur :: EventName 'BlurTag
64− Change :: EventName 'ChangeTag
65− Click :: EventName 'ClickTag
66− Contextmenu :: EventName 'ContextmenuTag
67− Dblclick :: EventName 'DblclickTag
68− Drag :: EventName 'DragTag
69− Dragend :: EventName 'DragendTag
70− Dragenter :: EventName 'DragenterTag
71− Dragleave :: EventName 'DragleaveTag
72− Dragover :: EventName 'DragoverTag
73− Dragstart :: EventName 'DragstartTag
74− Drop :: EventName 'DropTag
75− Error :: EventName 'ErrorTag
76− Focus :: EventName 'FocusTag
77− Input :: EventName 'InputTag
78− Invalid :: EventName 'InvalidTag
79− Keydown :: EventName 'KeydownTag
80− Keypress :: EventName 'KeypressTag
81− Keyup :: EventName 'KeyupTag
82− Load :: EventName 'LoadTag
83− Mousedown :: EventName 'MousedownTag
84− Mouseenter :: EventName 'MouseenterTag
85− Mouseleave :: EventName 'MouseleaveTag
86− Mousemove :: EventName 'MousemoveTag
87− Mouseout :: EventName 'MouseoutTag
88− Mouseover :: EventName 'MouseoverTag
89− Mouseup :: EventName 'MouseupTag
90− Mousewheel :: EventName 'MousewheelTag
91− Scroll :: EventName 'ScrollTag
92− Select :: EventName 'SelectTag
93− Submit :: EventName 'SubmitTag
94− Wheel :: EventName 'WheelTag
95− {-
96− Beforecut :: EventName 'BeforecutTag
97− Cut :: EventName 'CutTag
98− Beforecopy :: EventName 'BeforecopyTag
99− Copy :: EventName 'CopyTag
100− Beforepaste :: EventName 'BeforepasteTag
101− Paste :: EventName 'PasteTag
102−-}
103− Reset :: EventName 'ResetTag
104− Search :: EventName 'SearchTag
105−-- Selectstart :: EventName 'SelectstartTag
106− Touchstart :: EventName 'TouchstartTag
107− Touchmove :: EventName 'TouchmoveTag
108− Touchend :: EventName 'TouchendTag
109− Touchcancel :: EventName 'TouchcancelTag
110−
111−newtype EventResult en = EventResult { unEventResult :: EventResultType en }
112−
113−type family EventResultType (en :: EventTag) :: * where
114− EventResultType 'ClickTag = ()
115− EventResultType 'DblclickTag = ()
116− EventResultType 'KeypressTag = Int
117− EventResultType 'KeydownTag = Int
118− EventResultType 'KeyupTag = Int
119− EventResultType 'ScrollTag = Int
120− EventResultType 'MousemoveTag = (Int, Int)
121− EventResultType 'MousedownTag = (Int, Int)
122− EventResultType 'MouseupTag = (Int, Int)
123− EventResultType 'MouseenterTag = ()
124− EventResultType 'MouseleaveTag = ()
125− EventResultType 'FocusTag = ()
126− EventResultType 'BlurTag = ()
127− EventResultType 'ChangeTag = ()
128− EventResultType 'DragTag = ()
129− EventResultType 'DragendTag = ()
130− EventResultType 'DragenterTag = ()
131− EventResultType 'DragleaveTag = ()
132− EventResultType 'DragoverTag = ()
133− EventResultType 'DragstartTag = ()
134− EventResultType 'DropTag = ()
135− EventResultType 'AbortTag = ()
136− EventResultType 'ContextmenuTag = ()
137− EventResultType 'ErrorTag = ()
138− EventResultType 'InputTag = ()
139− EventResultType 'InvalidTag = ()
140− EventResultType 'LoadTag = ()
141− EventResultType 'MouseoutTag = ()
142− EventResultType 'MouseoverTag = ()
143− EventResultType 'MousewheelTag = ()
144− EventResultType 'SelectTag = ()
145− EventResultType 'SubmitTag = ()
146− {-
147− EventResultType 'BeforecutTag = ()
148− EventResultType 'CutTag = ()
149− EventResultType 'BeforecopyTag = ()
150− EventResultType 'CopyTag = ()
151− EventResultType 'BeforepasteTag = ()
152− EventResultType 'PasteTag = ()
153−-}
154− EventResultType 'ResetTag = ()
155− EventResultType 'SearchTag = ()
156−-- EventResultType 'SelectstartTag = ()
157− EventResultType 'TouchstartTag = ()
158− EventResultType 'TouchmoveTag = ()
159− EventResultType 'TouchendTag = ()
160− EventResultType 'TouchcancelTag = ()
161− EventResultType 'WheelTag = ()
162−
163−deriveGEq ''EventName
164−deriveGCompare ''EventName
src/Reflex/Dom/Builder/Immediate.hsdeleted−789
@@ -1,789 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE EmptyDataDecls #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7−{-# LANGUAGE LambdaCase #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE OverloadedStrings #-}
10−{-# LANGUAGE PolyKinds #-}
11−{-# LANGUAGE RankNTypes #-}
12−{-# LANGUAGE ScopedTypeVariables #-}
13−{-# LANGUAGE TemplateHaskell #-}
14−{-# LANGUAGE TypeFamilies #-}
15−{-# LANGUAGE TypeOperators #-}
16−{-# LANGUAGE UndecidableInstances #-}
17−module Reflex.Dom.Builder.Immediate where
18−
19−import Foreign.JavaScript.TH
20−import Reflex
21−import Reflex.Dom.Builder.Class
22−import Reflex.Dom.PerformEvent.Class
23−import Reflex.Dom.PostBuild.Class
24−import Reflex.Host.Class
25−
26−import Control.Concurrent.Chan
27−import Control.Lens hiding (element)
28−import Control.Monad.Exception
29−import Control.Monad.Reader
30−import Control.Monad.Ref
31−import Control.Monad.Trans.Control
32−import Data.Bitraversable
33−import Data.Default
34−import Data.Dependent.Map (DMap)
35−import qualified Data.Dependent.Map as DMap
36−import Data.Dependent.Sum
37−import Data.Functor.Misc
38−import Data.IORef
39−import Data.Maybe
40−import Data.Text (Text)
41−import GHCJS.DOM.Document (Document, createDocumentFragment, createElement, createElementNS, createTextNode)
42−import GHCJS.DOM.Element (getScrollTop, removeAttribute, removeAttributeNS, setAttribute, setAttributeNS)
43−import qualified GHCJS.DOM.Element as Element
44−import qualified GHCJS.DOM.Event as Event
45−import GHCJS.DOM.EventM (EventM, event, on)
46−import qualified GHCJS.DOM.EventM as DOM
47−import qualified GHCJS.DOM.HTMLInputElement as Input
48−import qualified GHCJS.DOM.HTMLTextAreaElement as TextArea
49−import GHCJS.DOM.MouseEvent
50−import GHCJS.DOM.Node (appendChild, getOwnerDocument, getParentNode, getPreviousSibling, insertBefore,
51− removeChild, setNodeValue, toNode)
52−import GHCJS.DOM.Types (FocusEvent, IsElement, IsEvent, IsNode, KeyboardEvent, Node, ToDOMString, TouchEvent,
53− WheelEvent, castToHTMLInputElement, castToHTMLTextAreaElement)
54−import qualified GHCJS.DOM.Types as DOM
55−import GHCJS.DOM.UIEvent
56−import qualified GHCJS.DOM.Window as Window
57−
58−import Debug.Trace hiding (traceEvent)
59−
60−data TriggerRef t a = TriggerRef { unTriggerRef :: IORef (Maybe (EventTrigger t a)) }
61−
62−data TriggerInvocation a = TriggerInvocation a (IO ())
63−
64−data ImmediateDomBuilderEnv t
65− = ImmediateDomBuilderEnv { _immediateDomBuilderEnv_document :: Document
66− , _immediateDomBuilderEnv_parent :: Node
67− , _immediateDomBuilderEnv_events :: Chan [DSum (TriggerRef t) TriggerInvocation]
68− }
69−
70−newtype ImmediateDomBuilderT t m a = ImmediateDomBuilderT { unImmediateDomBuilderT :: ReaderT (ImmediateDomBuilderEnv t) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
71−
72−instance MonadTransControl (ImmediateDomBuilderT t) where
73− type StT (ImmediateDomBuilderT t) a = StT (ReaderT (ImmediateDomBuilderEnv t)) a
74− liftWith = defaultLiftWith ImmediateDomBuilderT unImmediateDomBuilderT
75− restoreT = defaultRestoreT ImmediateDomBuilderT
76−
77−instance MonadTrans (ImmediateDomBuilderT t) where
78− lift = ImmediateDomBuilderT . lift
79−
80−{-# INLINABLE runImmediateDomBuilderT #-}
81−runImmediateDomBuilderT :: ImmediateDomBuilderT t m a -> ImmediateDomBuilderEnv t -> m a
82−runImmediateDomBuilderT (ImmediateDomBuilderT a) = runReaderT a
83−
84−{-# INLINABLE askDocument #-}
85−askDocument :: Monad m => ImmediateDomBuilderT t m Document
86−askDocument = ImmediateDomBuilderT $ asks _immediateDomBuilderEnv_document
87−
88−{-# INLINABLE askParent #-}
89−askParent :: Monad m => ImmediateDomBuilderT t m Node
90−askParent = ImmediateDomBuilderT $ asks _immediateDomBuilderEnv_parent
91−
92−{-# INLINABLE askEvents #-}
93−askEvents :: Monad m => ImmediateDomBuilderT t m (Chan [DSum (TriggerRef t) TriggerInvocation])
94−askEvents = ImmediateDomBuilderT $ asks _immediateDomBuilderEnv_events
95−
96−{-# INLINABLE append #-}
97−append :: (IsNode n, MonadIO m) => n -> ImmediateDomBuilderT t m ()
98−append n = do
99− p <- askParent
100− _ <- liftIO $ appendChild p $ Just n
101− return ()
102−
103−{-# INLINABLE textNodeInternal #-}
104−textNodeInternal :: (MonadIO m, ToDOMString contents) => contents -> ImmediateDomBuilderT t m DOM.Text
105−textNodeInternal t = do
106− doc <- askDocument
107− Just n <- liftIO $ createTextNode doc t
108− append n
109− return n
110−
111−-- | s and e must both be children of the same node and s must precede e
112−{-# INLINABLE deleteBetweenInclusive #-}
113−deleteBetweenInclusive :: (MonadIO m, IsNode start, IsNode end) => start -> end -> m ()
114−deleteBetweenInclusive s e = do
115− mCurrentParent <- getParentNode e -- May be different than it was at initial construction, e.g., because the parent may have dumped us in from a DocumentFragment
116− case mCurrentParent of
117− Nothing -> return () --TODO: Is this the right behavior?
118− Just currentParent -> do
119− let go = do
120− Just x <- getPreviousSibling e -- This can't be Nothing because we should hit 's' first
121− _ <- removeChild currentParent $ Just x
122− when (toNode s /= toNode x) go
123− go
124− _ <- removeChild currentParent $ Just e
125− return ()
126−
127−type SupportsImmediateDomBuilder t m = (Reflex t, MonadIO m, MonadHold t m, MonadFix m, PerformEvent t m, Performable m ~ m, MonadReflexCreateTrigger t m, Deletable t m, MonadRef m, Ref m ~ Ref IO)
128−
129−newtype EventFilterTriggerRef t er (en :: EventTag) = EventFilterTriggerRef (IORef (Maybe (EventTrigger t (er en))))
130−
131−wrap :: forall m er t. SupportsImmediateDomBuilder t m => RawElement GhcjsDomSpace -> RawElementConfig er t (ImmediateDomBuilderT t m) -> ImmediateDomBuilderT t m (Element er GhcjsDomSpace t)
132−wrap e cfg = do
133− events <- askEvents
134− lift $ performEvent_ $ ffor (cfg ^. modifyAttributes) $ imapM_ $ \(mAttrNamespace, n) mv -> case mAttrNamespace of
135− Nothing -> maybe (removeAttribute e n) (setAttribute e n) mv
136− Just ns -> maybe (removeAttributeNS e (Just ns) n) (setAttributeNS e (Just ns) n) mv
137− eventTriggerRefs :: DMap EventName (EventFilterTriggerRef t er) <- liftIO $ fmap DMap.fromList $ forM (DMap.toList $ _ghcjsEventSpec_filters $ _rawElementConfig_eventSpec cfg) $ \(en :=> GhcjsEventFilter f) -> do
138− triggerRef <- newIORef Nothing
139− _ <- elementOnEventName en e $ do
140− evt <- DOM.event
141− (flags, k) <- liftIO $ f $ GhcjsDomEvent evt
142− when (_eventFlags_preventDefault flags) $ withIsEvent en DOM.preventDefault
143− case _eventFlags_propagation flags of
144− Propagation_Continue -> return ()
145− Propagation_Stop -> withIsEvent en DOM.stopPropagation
146− Propagation_StopImmediate -> withIsEvent en DOM.stopImmediatePropagation
147− mv <- liftIO k --TODO: Only do this when the event is subscribed
148− liftIO $ forM_ mv $ \v -> writeChan events [TriggerRef triggerRef :=> TriggerInvocation v (return ())]
149− return $ en :=> EventFilterTriggerRef triggerRef
150− es <- newFanEventWithTrigger $ \(WrapArg en) t -> do
151− case DMap.lookup en eventTriggerRefs of
152− Just (EventFilterTriggerRef r) -> do
153− writeIORef r $ Just t
154− return $ do
155− writeIORef r Nothing
156− Nothing -> elementOnEventName en e $ do
157− evt <- DOM.event
158− let h = _ghcjsEventSpec_handler $ _rawElementConfig_eventSpec cfg
159− mv <- liftIO $ h (en, GhcjsDomEvent evt)
160− case mv of
161− Nothing -> return ()
162− Just v -> liftIO $ do
163− --TODO: I don't think this is quite right: if a new trigger is created between when this is enqueued and when it fires, this may not work quite right
164− ref <- newIORef $ Just t
165− writeChan events [TriggerRef ref :=> TriggerInvocation v (return ())]
166− return $ Element es e
167−
168−{-# INLINABLE makeElement #-}
169−makeElement :: forall er t m a. SupportsImmediateDomBuilder t m => Text -> ElementConfig er t (ImmediateDomBuilderT t m) -> ImmediateDomBuilderT t m a -> ImmediateDomBuilderT t m ((Element er GhcjsDomSpace t, a), DOM.HTMLElement)
170−makeElement elementTag cfg child = do
171− doc <- askDocument
172− events <- askEvents
173− Just e <- ImmediateDomBuilderT $ fmap DOM.castToHTMLElement <$> case cfg ^. namespace of
174− Nothing -> createElement doc (Just elementTag)
175− Just ens -> createElementNS doc (Just ens) (Just elementTag)
176− ImmediateDomBuilderT $ iforM_ (cfg ^. initialAttributes) $ \(mAttrNamespace, n) v -> case mAttrNamespace of
177− Nothing -> setAttribute e n v
178− Just ans -> setAttributeNS e (Just ans) n v
179− result <- lift $ runImmediateDomBuilderT child $ ImmediateDomBuilderEnv
180− { _immediateDomBuilderEnv_parent = toNode e
181− , _immediateDomBuilderEnv_document = doc
182− , _immediateDomBuilderEnv_events = events
183− }
184− append e
185− wrapped <- wrap e $ extractRawElementConfig cfg
186− return ((wrapped, result), e)
187−
188−newtype GhcjsDomHandler a b = GhcjsDomHandler { unGhcjsDomHandler :: a -> IO b }
189−
190−newtype GhcjsDomHandler1 a b = GhcjsDomHandler1 { unGhcjsDomHandler1 :: forall (x :: EventTag). a x -> IO (b x) }
191−
192−newtype GhcjsDomEvent en = GhcjsDomEvent { unGhcjsDomEvent :: EventType en }
193−
194−data GhcjsDomSpace
195−
196−instance DomSpace GhcjsDomSpace where
197− type EventSpec GhcjsDomSpace = GhcjsEventSpec
198− type RawTextNode GhcjsDomSpace = DOM.Text
199− type RawElement GhcjsDomSpace = DOM.HTMLElement
200− type RawInputElement GhcjsDomSpace = DOM.HTMLInputElement
201− type RawTextAreaElement GhcjsDomSpace = DOM.HTMLTextAreaElement
202−
203−newtype GhcjsEventFilter er en = GhcjsEventFilter (GhcjsDomEvent en -> IO (EventFlags, IO (Maybe (er en))))
204−
205−data Pair1 (f :: k -> *) (g :: k -> *) (a :: k) = Pair1 (f a) (g a)
206−
207−data Maybe1 f a = Nothing1 | Just1 (f a)
208−
209−data GhcjsEventSpec er = GhcjsEventSpec
210− { _ghcjsEventSpec_filters :: DMap EventName (GhcjsEventFilter er)
211− , _ghcjsEventSpec_handler :: forall en. (EventName en, GhcjsDomEvent en) -> IO (Maybe (er en))
212− }
213−
214−instance er ~ EventResult => Default (GhcjsEventSpec er) where
215− def = GhcjsEventSpec
216− { _ghcjsEventSpec_filters = mempty
217− , _ghcjsEventSpec_handler = \(en, GhcjsDomEvent evt) -> do
218− Just t <- withIsEvent en $ Event.getTarget evt --TODO: Rework this; defaultDomEventHandler shouldn't need to take this as an argument
219− runReaderT (defaultDomEventHandler (Element.castToElement t) en) evt
220− }
221−
222−instance SupportsImmediateDomBuilder t m => DomBuilder t (ImmediateDomBuilderT t m) where
223− type DomBuilderSpace (ImmediateDomBuilderT t m) = GhcjsDomSpace
224− {-# INLINABLE textNode #-}
225− textNode (TextNodeConfig initialContents eSetContents) = do
226− n <- textNodeInternal initialContents
227− lift $ performEvent_ $ ffor eSetContents $ \t -> setNodeValue n (Just t)
228− return $ TextNode n
229− {-# INLINABLE element #-}
230− element elementTag cfg child = fst <$> makeElement elementTag cfg child
231− {-# INLINABLE placeholder #-}
232− placeholder (PlaceholderConfig toInsertAbove delete) = liftThrough (deletable delete) $ do
233− n <- textNodeInternal ("" :: Text)
234− insertedAbove <- insertImmediateAbove n toInsertAbove
235− --Note: "deleteSelf" must come after "insertAbove", because we need to be able to insert above in the same frame that we delete
236− deleted <- lift $ performEvent $ ffor delete $ \_ -> do
237− mp <- getParentNode n
238− forM_ mp $ \p -> removeChild p $ Just n
239− return $ Placeholder insertedAbove deleted
240− {-# INLINABLE inputElement #-}
241− inputElement cfg = do
242− ((e, _), domElement) <- makeElement "input" (cfg ^. inputElementConfig_elementConfig) $ return ()
243− let domInputElement = castToHTMLInputElement domElement
244− Input.setValue domInputElement $ Just (cfg ^. inputElementConfig_initialValue)
245− Just v0 <- Input.getValue domInputElement
246− let getMyValue = fromMaybe "" <$> Input.getValue domInputElement
247− valueChangedByUI <- performEvent $ getMyValue <$ Reflex.select (_element_events e) (WrapArg Input)
248− valueChangedBySetValue <- performEvent $ ffor (cfg ^. inputElementConfig_setValue) $ \v' -> do
249− Input.setValue domInputElement $ Just v'
250− getMyValue -- We get the value after setting it in case the browser has mucked with it somehow
251− v <- holdDyn v0 $ leftmost
252− [ valueChangedBySetValue
253− , valueChangedByUI
254− ]
255− Input.setChecked domInputElement $ _inputElementConfig_initialChecked cfg
256− checkedChangedByUI <- wrapDomEvent domInputElement (`on` Element.click) $ do
257− Input.getChecked domInputElement
258− checkedChangedBySetChecked <- performEvent $ ffor (_inputElementConfig_setChecked cfg) $ \newChecked -> do
259− oldChecked <- Input.getChecked domInputElement
260− if newChecked /= oldChecked
261− then do Input.setChecked domInputElement newChecked
262− return $ Just newChecked
263− else return Nothing
264− c <- holdDyn (_inputElementConfig_initialChecked cfg) $ leftmost
265− [ fmapMaybe id checkedChangedBySetChecked
266− , checkedChangedByUI
267− ]
268− let initialFocus = False --TODO: Is this correct?
269− hasFocus <- holdDyn initialFocus $ leftmost
270− [ False <$ Reflex.select (_element_events e) (WrapArg Blur)
271− , True <$ Reflex.select (_element_events e) (WrapArg Focus)
272− ]
273− return $ InputElement
274− { _inputElement_value = v
275− , _inputElement_checked = uniqDyn c
276− , _inputElement_checkedChange = checkedChangedByUI
277− , _inputElement_input = valueChangedByUI
278− , _inputElement_hasFocus = hasFocus
279− , _inputElement_element = e
280− , _inputElement_raw = domInputElement
281− }
282− {-# INLINABLE textAreaElement #-}
283− textAreaElement cfg = do --TODO
284− ((e, _), domElement) <- makeElement "textarea" (cfg ^. textAreaElementConfig_elementConfig) $ return ()
285− let domTextAreaElement = castToHTMLTextAreaElement domElement
286− Just v0 <- TextArea.getValue domTextAreaElement
287− let getMyValue = fromMaybe "" <$> TextArea.getValue domTextAreaElement
288− valueChangedByUI <- performEvent $ getMyValue <$ Reflex.select (_element_events e) (WrapArg Input)
289− valueChangedBySetValue <- performEvent $ ffor (cfg ^. textAreaElementConfig_setValue) $ \v' -> do
290− TextArea.setValue domTextAreaElement $ Just v'
291− getMyValue -- We get the value after setting it in case the browser has mucked with it somehow
292− v <- holdDyn v0 $ leftmost
293− [ valueChangedBySetValue
294− , valueChangedByUI
295− ]
296− let initialFocus = False --TODO: Is this correct?
297− hasFocus <- holdDyn initialFocus $ leftmost
298− [ False <$ Reflex.select (_element_events e) (WrapArg Blur)
299− , True <$ Reflex.select (_element_events e) (WrapArg Focus)
300− ]
301− return $ TextAreaElement
302− { _textAreaElement_value = v
303− , _textAreaElement_input = valueChangedByUI
304− , _textAreaElement_hasFocus = hasFocus
305− , _textAreaElement_element = e
306− , _textAreaElement_raw = domTextAreaElement
307− }
308− placeRawElement = append
309− wrapRawElement = wrap
310−
311−{-# INLINABLE insertImmediateAbove #-}
312−insertImmediateAbove :: (Reflex t, IsNode placeholder, PerformEvent t m, MonadIO (Performable m)) => placeholder -> Event t (ImmediateDomBuilderT t (Performable m) a) -> ImmediateDomBuilderT t m (Event t a)
313−insertImmediateAbove n toInsertAbove = do
314− events <- askEvents
315− lift $ performEvent $ ffor toInsertAbove $ \new -> do
316− Just doc <- getOwnerDocument n
317− Just df <- createDocumentFragment doc
318− result <- runImmediateDomBuilderT new $ ImmediateDomBuilderEnv
319− { _immediateDomBuilderEnv_parent = toNode df
320− , _immediateDomBuilderEnv_document = doc
321− , _immediateDomBuilderEnv_events = events
322− }
323− mp <- getParentNode n
324− case mp of
325− Nothing -> trace "ImmediateDomBuilderT: placeholder: Warning: (getParentNode n) returned Nothing" $ return ()
326− Just p -> void $ insertBefore p (Just df) (Just n) -- If there's no parent, that means we've been removed from the DOM; this should not happen if the we're removing ourselves from the performEvent properly
327− return result
328−
329−instance SupportsImmediateDomBuilder t m => Deletable t (ImmediateDomBuilderT t m) where
330− {-# INLINABLE deletable #-}
331− deletable delete child = liftThrough (deletable delete) $ do
332− top <- textNodeInternal ("" :: Text)
333− result <- child
334− bottom <- textNodeInternal ("" :: Text)
335− lift $ performEvent_ $ ffor delete $ \_ -> do
336− deleteBetweenInclusive top bottom
337− return result
338−
339−instance PerformEvent t m => PerformEvent t (ImmediateDomBuilderT t m) where
340− type Performable (ImmediateDomBuilderT t m) = Performable m
341− {-# INLINABLE performEvent_ #-}
342− performEvent_ e = lift $ performEvent_ e
343− {-# INLINABLE performEvent #-}
344− performEvent e = lift $ performEvent e
345−
346−instance PostBuild t m => PostBuild t (ImmediateDomBuilderT t m) where
347− {-# INLINABLE getPostBuild #-}
348− getPostBuild = lift getPostBuild
349−
350−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ImmediateDomBuilderT t m) where
351− {-# INLINABLE newEventWithTrigger #-}
352− newEventWithTrigger = lift . newEventWithTrigger
353− {-# INLINABLE newFanEventWithTrigger #-}
354− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
355−
356−instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (ImmediateDomBuilderT t m) where
357− {-# INLINABLE newTriggerEvent #-}
358− newTriggerEvent = do
359− (e, t) <- newTriggerEventWithOnComplete
360− return (e, \a -> t a $ return ())
361− {-# INLINABLE newTriggerEventWithOnComplete #-}
362− newTriggerEventWithOnComplete = do
363− events <- askEvents
364− (eResult, reResultTrigger) <- lift newEventWithTriggerRef
365− return $ (,) eResult $ \a cb -> writeChan events [TriggerRef reResultTrigger :=> TriggerInvocation a cb]
366− {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
367− newEventWithLazyTriggerWithOnComplete f = do
368− events <- askEvents
369− lift $ newEventWithTrigger $ \t -> f $ \a cb -> do
370− reResultTrigger <- newIORef $ Just t
371− writeChan events [TriggerRef reResultTrigger :=> TriggerInvocation a cb]
372−
373−instance HasWebView m => HasWebView (ImmediateDomBuilderT t m) where
374− type WebViewPhantom (ImmediateDomBuilderT t m) = WebViewPhantom m
375− askWebView = lift askWebView
376−
377−instance MonadRef m => MonadRef (ImmediateDomBuilderT t m) where
378− type Ref (ImmediateDomBuilderT t m) = Ref m
379− {-# INLINABLE newRef #-}
380− newRef = lift . newRef
381− {-# INLINABLE readRef #-}
382− readRef = lift . readRef
383− {-# INLINABLE writeRef #-}
384− writeRef r = lift . writeRef r
385−
386−instance MonadAtomicRef m => MonadAtomicRef (ImmediateDomBuilderT t m) where
387− {-# INLINABLE atomicModifyRef #-}
388− atomicModifyRef r = lift . atomicModifyRef r
389−
390−instance (HasJS x m, ReflexHost t) => HasJS x (ImmediateDomBuilderT t m) where
391− type JSM (ImmediateDomBuilderT t m) = JSM m
392− liftJS = lift . liftJS
393−
394−type family EventType en where
395− EventType 'AbortTag = UIEvent
396− EventType 'BlurTag = FocusEvent
397− EventType 'ChangeTag = DOM.Event
398− EventType 'ClickTag = MouseEvent
399− EventType 'ContextmenuTag = MouseEvent
400− EventType 'DblclickTag = MouseEvent
401− EventType 'DragTag = MouseEvent
402− EventType 'DragendTag = MouseEvent
403− EventType 'DragenterTag = MouseEvent
404− EventType 'DragleaveTag = MouseEvent
405− EventType 'DragoverTag = MouseEvent
406− EventType 'DragstartTag = MouseEvent
407− EventType 'DropTag = MouseEvent
408− EventType 'ErrorTag = UIEvent
409− EventType 'FocusTag = FocusEvent
410− EventType 'InputTag = DOM.Event
411− EventType 'InvalidTag = DOM.Event
412− EventType 'KeydownTag = KeyboardEvent
413− EventType 'KeypressTag = KeyboardEvent
414− EventType 'KeyupTag = KeyboardEvent
415− EventType 'LoadTag = UIEvent
416− EventType 'MousedownTag = MouseEvent
417− EventType 'MouseenterTag = MouseEvent
418− EventType 'MouseleaveTag = MouseEvent
419− EventType 'MousemoveTag = MouseEvent
420− EventType 'MouseoutTag = MouseEvent
421− EventType 'MouseoverTag = MouseEvent
422− EventType 'MouseupTag = MouseEvent
423− EventType 'MousewheelTag = MouseEvent
424− EventType 'ScrollTag = UIEvent
425− EventType 'SelectTag = UIEvent
426− EventType 'SubmitTag = DOM.Event
427− EventType 'WheelTag = WheelEvent
428− {-
429− EventType 'BeforecutTag = DOM.Event
430− EventType 'CutTag = DOM.Event
431− EventType 'BeforecopyTag = DOM.Event
432− EventType 'CopyTag = DOM.Event
433− EventType 'BeforepasteTag = DOM.Event
434− EventType 'PasteTag = DOM.Event
435−-}
436− EventType 'ResetTag = DOM.Event
437− EventType 'SearchTag = DOM.Event
438−-- EventType 'SelectstartTag = DOM.Event
439− EventType 'TouchstartTag = TouchEvent
440− EventType 'TouchmoveTag = TouchEvent
441− EventType 'TouchendTag = TouchEvent
442− EventType 'TouchcancelTag = TouchEvent
443−
444−{-# INLINABLE defaultDomEventHandler #-}
445−defaultDomEventHandler :: IsElement e => e -> EventName en -> EventM e (EventType en) (Maybe (EventResult en))
446−defaultDomEventHandler e evt = fmap (Just . EventResult) $ case evt of
447− Click -> return ()
448− Dblclick -> return ()
449− Keypress -> getKeyEvent
450− Scroll -> getScrollTop e
451− Keydown -> getKeyEvent
452− Keyup -> getKeyEvent
453− Mousemove -> getMouseEventCoords
454− Mouseup -> getMouseEventCoords
455− Mousedown -> getMouseEventCoords
456− Mouseenter -> return ()
457− Mouseleave -> return ()
458− Focus -> return ()
459− Blur -> return ()
460− Change -> return ()
461− Drag -> return ()
462− Dragend -> return ()
463− Dragenter -> return ()
464− Dragleave -> return ()
465− Dragover -> return ()
466− Dragstart -> return ()
467− Drop -> return ()
468− Abort -> return ()
469− Contextmenu -> return ()
470− Error -> return ()
471− Input -> return ()
472− Invalid -> return ()
473− Load -> return ()
474− Mouseout -> return ()
475− Mouseover -> return ()
476− Select -> return ()
477− Submit -> return ()
478− {-
479− Beforecut -> return ()
480− Cut -> return ()
481− Beforecopy -> return ()
482− Copy -> return ()
483− Beforepaste -> return ()
484− Paste -> return ()
485−-}
486− Reset -> return ()
487− Search -> return ()
488−-- Selectstart -> return ()
489− Touchstart -> return ()
490− Touchmove -> return ()
491− Touchend -> return ()
492− Touchcancel -> return ()
493− Mousewheel -> return ()
494− Wheel -> return ()
495−
496−{-# INLINABLE defaultDomWindowEventHandler #-}
497−defaultDomWindowEventHandler :: DOM.Window -> EventName en -> EventM DOM.Window (EventType en) (Maybe (EventResult en))
498−defaultDomWindowEventHandler w evt = fmap (Just . EventResult) $ case evt of
499− Click -> return ()
500− Dblclick -> return ()
501− Keypress -> getKeyEvent
502− Scroll -> Window.getScrollY w
503− Keydown -> getKeyEvent
504− Keyup -> getKeyEvent
505− Mousemove -> getMouseEventCoords
506− Mouseup -> getMouseEventCoords
507− Mousedown -> getMouseEventCoords
508− Mouseenter -> return ()
509− Mouseleave -> return ()
510− Focus -> return ()
511− Blur -> return ()
512− Change -> return ()
513− Drag -> return ()
514− Dragend -> return ()
515− Dragenter -> return ()
516− Dragleave -> return ()
517− Dragover -> return ()
518− Dragstart -> return ()
519− Drop -> return ()
520− Abort -> return ()
521− Contextmenu -> return ()
522− Error -> return ()
523− Input -> return ()
524− Invalid -> return ()
525− Load -> return ()
526− Mouseout -> return ()
527− Mouseover -> return ()
528− Select -> return ()
529− Submit -> return ()
530− {-
531− Beforecut -> return ()
532− Cut -> return ()
533− Beforecopy -> return ()
534− Copy -> return ()
535− Beforepaste -> return ()
536− Paste -> return ()
537−-}
538− Reset -> return ()
539− Search -> return ()
540−-- Selectstart -> return ()
541− Touchstart -> return ()
542− Touchmove -> return ()
543− Touchend -> return ()
544− Touchcancel -> return ()
545− Mousewheel -> return ()
546− Wheel -> return ()
547−
548−{-# INLINABLE withIsEvent #-}
549−withIsEvent :: EventName en -> (IsEvent (EventType en) => r) -> r
550−withIsEvent en r = case en of
551− Click -> r
552− Dblclick -> r
553− Keypress -> r
554− Scroll -> r
555− Keydown -> r
556− Keyup -> r
557− Mousemove -> r
558− Mouseup -> r
559− Mousedown -> r
560− Mouseenter -> r
561− Mouseleave -> r
562− Focus -> r
563− Blur -> r
564− Change -> r
565− Drag -> r
566− Dragend -> r
567− Dragenter -> r
568− Dragleave -> r
569− Dragover -> r
570− Dragstart -> r
571− Drop -> r
572− Abort -> r
573− Contextmenu -> r
574− Error -> r
575− Input -> r
576− Invalid -> r
577− Load -> r
578− Mouseout -> r
579− Mouseover -> r
580− Select -> r
581− Submit -> r
582− {-
583− Beforecut -> r
584− Cut -> r
585− Beforecopy -> r
586− Copy -> r
587− Beforepaste -> r
588− Paste -> r
589−-}
590− Reset -> r
591− Search -> r
592−-- Selectstart -> r
593− Touchstart -> r
594− Touchmove -> r
595− Touchend -> r
596− Touchcancel -> r
597− Mousewheel -> r
598− Wheel -> r
599−
600−{-# INLINABLE elementOnEventName #-}
601−elementOnEventName :: IsElement e => EventName en -> e -> EventM e (EventType en) () -> IO (IO ())
602−elementOnEventName en e = case en of
603− Abort -> on e Element.abort
604− Blur -> on e Element.blurEvent
605− Change -> on e Element.change
606− Click -> on e Element.click
607− Contextmenu -> on e Element.contextMenu
608− Dblclick -> on e Element.dblClick
609− Drag -> on e Element.drag
610− Dragend -> on e Element.dragEnd
611− Dragenter -> on e Element.dragEnter
612− Dragleave -> on e Element.dragLeave
613− Dragover -> on e Element.dragOver
614− Dragstart -> on e Element.dragStart
615− Drop -> on e Element.drop
616− Error -> on e Element.error
617− Focus -> on e Element.focusEvent
618− Input -> on e Element.input
619− Invalid -> on e Element.invalid
620− Keydown -> on e Element.keyDown
621− Keypress -> on e Element.keyPress
622− Keyup -> on e Element.keyUp
623− Load -> on e Element.load
624− Mousedown -> on e Element.mouseDown
625− Mouseenter -> on e Element.mouseEnter
626− Mouseleave -> on e Element.mouseLeave
627− Mousemove -> on e Element.mouseMove
628− Mouseout -> on e Element.mouseOut
629− Mouseover -> on e Element.mouseOver
630− Mouseup -> on e Element.mouseUp
631− Mousewheel -> on e Element.mouseWheel
632− Scroll -> on e Element.scroll
633− Select -> on e Element.select
634− Submit -> on e Element.submit
635− Wheel -> on e Element.wheel
636− {-
637− Beforecut -> on e Element.beforeCut
638− Cut -> on e Element.cut
639− Beforecopy -> on e Element.beforeCopy
640− Copy -> on e Element.copy
641− Beforepaste -> on e Element.beforePaste
642− Paste -> on e Element.paste
643−-}
644− Reset -> on e Element.reset
645− Search -> on e Element.search
646−-- Selectstart -> on e Element.selectStart
647− Touchstart -> on e Element.touchStart
648− Touchmove -> on e Element.touchMove
649− Touchend -> on e Element.touchEnd
650− Touchcancel -> on e Element.touchCancel
651−
652−{-# INLINABLE windowOnEventName #-}
653−windowOnEventName :: EventName en -> DOM.Window -> EventM DOM.Window (EventType en) () -> IO (IO ())
654−windowOnEventName en e = case en of
655− Abort -> on e Window.abort
656− Blur -> on e Window.blurEvent
657− Change -> on e Window.change
658− Click -> on e Window.click
659− Contextmenu -> on e Window.contextMenu
660− Dblclick -> on e Window.dblClick
661− Drag -> on e Window.drag
662− Dragend -> on e Window.dragEnd
663− Dragenter -> on e Window.dragEnter
664− Dragleave -> on e Window.dragLeave
665− Dragover -> on e Window.dragOver
666− Dragstart -> on e Window.dragStart
667− Drop -> on e Window.drop
668− Error -> on e Window.error
669− Focus -> on e Window.focusEvent
670− Input -> on e Window.input
671− Invalid -> on e Window.invalid
672− Keydown -> on e Window.keyDown
673− Keypress -> on e Window.keyPress
674− Keyup -> on e Window.keyUp
675− Load -> on e Window.load
676− Mousedown -> on e Window.mouseDown
677− Mouseenter -> on e Window.mouseEnter
678− Mouseleave -> on e Window.mouseLeave
679− Mousemove -> on e Window.mouseMove
680− Mouseout -> on e Window.mouseOut
681− Mouseover -> on e Window.mouseOver
682− Mouseup -> on e Window.mouseUp
683− Mousewheel -> on e Window.mouseWheel
684− Scroll -> on e Window.scrollEvent
685− Select -> on e Window.select
686− Submit -> on e Window.submit
687− Wheel -> on e Window.wheel
688− {-
689− Beforecut -> on e Window.beforeCut
690− Cut -> on e Window.cut
691− Beforecopy -> on e Window.beforeCopy
692− Copy -> on e Window.copy
693− Beforepaste -> on e Window.beforePaste
694− Paste -> on e Window.paste
695−-}
696− Reset -> on e Window.reset
697− Search -> on e Window.search
698−-- Selectstart -> on e Window.selectStart
699− Touchstart -> on e Window.touchStart
700− Touchmove -> on e Window.touchMove
701− Touchend -> on e Window.touchEnd
702− Touchcancel -> on e Window.touchCancel
703−
704−{-# INLINABLE wrapDomEvent #-}
705−wrapDomEvent :: TriggerEvent t m => e -> (e -> EventM e event () -> IO (IO ())) -> EventM e event a -> m (Event t a)
706−wrapDomEvent el elementOnevent getValue = wrapDomEventMaybe el elementOnevent $ fmap Just getValue
707−
708−{-# INLINABLE subscribeDomEvent #-}
709−subscribeDomEvent :: (EventM e event () -> IO (IO ()))
710− -> EventM e event (Maybe a)
711− -> Chan [DSum (TriggerRef t) TriggerInvocation]
712− -> EventTrigger t a
713− -> IO (IO ())
714−subscribeDomEvent elementOnevent getValue eventChan et = elementOnevent $ do
715− mv <- getValue
716− forM_ mv $ \v -> liftIO $ do
717− --TODO: I don't think this is quite right: if a new trigger is created between when this is enqueued and when it fires, this may not work quite right
718− etr <- newIORef $ Just et
719− writeChan eventChan [TriggerRef etr :=> TriggerInvocation v (return ())]
720−
721−{-# INLINABLE wrapDomEventMaybe #-}
722−wrapDomEventMaybe :: TriggerEvent t m
723− => e
724− -> (e -> EventM e event () -> IO (IO ()))
725− -> EventM e event (Maybe a)
726− -> m (Event t a)
727−wrapDomEventMaybe el elementOnevent getValue = do
728− newEventWithLazyTriggerWithOnComplete $ \trigger -> elementOnevent el $ do
729− mv <- getValue
730− forM_ mv $ \v -> liftIO $ trigger v $ return ()
731−
732−{-# INLINABLE wrapDomEventsMaybe #-}
733−wrapDomEventsMaybe :: (MonadIO m, MonadReflexCreateTrigger t m)
734− => e
735− -> (forall en. IsEvent (EventType en) => EventName en -> EventM e (EventType en) (Maybe (f en)))
736− -> (forall en. EventName en -> e -> EventM e (EventType en) () -> IO (IO ()))
737− -> ImmediateDomBuilderT t m (EventSelector t (WrapArg f EventName))
738−wrapDomEventsMaybe target handlers onEventName = do
739− eventChan <- askEvents
740− e <- lift $ newFanEventWithTrigger $ \(WrapArg en) -> withIsEvent en $ subscribeDomEvent (onEventName en target) (handlers en) eventChan
741− return $! e
742−
743−{-# INLINABLE getKeyEvent #-}
744−getKeyEvent :: EventM e KeyboardEvent Int
745−getKeyEvent = do
746− e <- event
747− which <- getWhich e
748− if which /= 0 then return which else do
749− charCode <- getCharCode e
750− if charCode /= 0 then return charCode else
751− getKeyCode e
752−
753−{-# INLINABLE getMouseEventCoords #-}
754−getMouseEventCoords :: EventM e MouseEvent (Int, Int)
755−getMouseEventCoords = do
756− e <- event
757− bisequence (getX e, getY e)
758−
759−instance MonadSample t m => MonadSample t (ImmediateDomBuilderT t m) where
760− {-# INLINABLE sample #-}
761− sample = lift . sample
762−
763−instance MonadHold t m => MonadHold t (ImmediateDomBuilderT t m) where
764− {-# INLINABLE hold #-}
765− hold v0 v' = lift $ hold v0 v'
766− {-# INLINABLE holdDyn #-}
767− holdDyn v0 v' = lift $ holdDyn v0 v'
768− {-# INLINABLE holdIncremental #-}
769− holdIncremental v0 v' = lift $ holdIncremental v0 v'
770−
771−data WindowConfig t = WindowConfig -- No config options yet
772−
773−instance Default (WindowConfig t) where
774− def = WindowConfig
775−
776−data Window t = Window
777− { _window_events :: EventSelector t (WrapArg EventResult EventName)
778− , _window_raw :: DOM.Window
779− }
780−
781−wrapWindow :: (MonadIO m, MonadReflexCreateTrigger t m) => DOM.Window -> WindowConfig t -> ImmediateDomBuilderT t m (Window t)
782−wrapWindow wv _ = do
783− events <- wrapDomEventsMaybe wv (defaultDomWindowEventHandler wv) windowOnEventName
784− return $ Window
785− { _window_events = events
786− , _window_raw = wv
787− }
788−
789−makeLenses ''GhcjsEventSpec
src/Reflex/Dom/Builder/Static.hsdeleted−194
@@ -1,194 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE DeriveGeneric #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
8−{-# LANGUAGE LambdaCase #-}
9−{-# LANGUAGE MultiParamTypeClasses #-}
10−{-# LANGUAGE OverloadedStrings #-}
11−{-# LANGUAGE PolyKinds #-}
12−{-# LANGUAGE RankNTypes #-}
13−{-# LANGUAGE ScopedTypeVariables #-}
14−{-# LANGUAGE TypeFamilies #-}
15−{-# LANGUAGE TypeOperators #-}
16−{-# LANGUAGE UndecidableInstances #-}
17−module Reflex.Dom.Builder.Static where
18−
19−import Blaze.ByteString.Builder.Html.Utf8
20−import Control.Lens hiding (element)
21−import Control.Monad.Exception
22−import Control.Monad.Identity
23−import Control.Monad.Ref
24−import Control.Monad.State.Strict
25−import Control.Monad.Trans.Control
26−import Data.ByteString (ByteString)
27−import Data.ByteString.Builder (toLazyByteString)
28−import qualified Data.ByteString.Lazy as BL
29−import Data.Default
30−import Data.Dependent.Sum (DSum (..))
31−import qualified Data.Map as Map
32−import Data.Monoid
33−import Data.Text.Encoding
34−import GHC.Generics
35−import Reflex
36−import Reflex.Dom.Builder.Class
37−import Reflex.Dom.PerformEvent.Base
38−import Reflex.Dom.PerformEvent.Class
39−import Reflex.Dom.PostBuild.Class
40−import Reflex.Dom.Widget.Basic (applyMap)
41−import Reflex.Host.Class
42−
43−
44−newtype StaticDomBuilderT t m a = StaticDomBuilderT
45− { unStaticDomBuilderT :: StateT [Behavior t ByteString] m a -- Accumulated Html will be in revesed order
46− }
47− deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException)
48−
49−instance MonadTransControl (StaticDomBuilderT t) where
50− type StT (StaticDomBuilderT t) a = StT (StateT [Behavior t ByteString]) a
51− liftWith = defaultLiftWith StaticDomBuilderT unStaticDomBuilderT
52− restoreT = defaultRestoreT StaticDomBuilderT
53−
54−instance MonadTrans (StaticDomBuilderT t) where
55− lift = StaticDomBuilderT . lift
56−
57−runStaticDomBuilderT :: (Monad m, Reflex t) => StaticDomBuilderT t m a -> m (a, Behavior t ByteString)
58−runStaticDomBuilderT (StaticDomBuilderT a) = do
59− (result, a') <- runStateT a []
60− return (result, mconcat $ reverse a')
61−
62−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StaticDomBuilderT t m) where
63− {-# INLINABLE newEventWithTrigger #-}
64− newEventWithTrigger = lift . newEventWithTrigger
65− {-# INLINABLE newFanEventWithTrigger #-}
66− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
67−
68−instance PerformEvent t m => PerformEvent t (StaticDomBuilderT t m) where
69− type Performable (StaticDomBuilderT t m) = Performable m
70− {-# INLINABLE performEvent_ #-}
71− performEvent_ e = lift $ performEvent_ e
72− {-# INLINABLE performEvent #-}
73− performEvent e = lift $ performEvent e
74−
75−instance MonadSample t m => MonadSample t (StaticDomBuilderT t m) where
76− {-# INLINABLE sample #-}
77− sample = lift . sample
78−
79−instance MonadHold t m => MonadHold t (StaticDomBuilderT t m) where
80− {-# INLINABLE hold #-}
81− hold v0 v' = lift $ hold v0 v'
82− {-# INLINABLE holdDyn #-}
83− holdDyn v0 v' = lift $ holdDyn v0 v'
84− {-# INLINABLE holdIncremental #-}
85− holdIncremental v0 v' = lift $ holdIncremental v0 v'
86−
87−instance (Reflex t, Monad m, MonadHold t (StateT [Behavior t ByteString] m)) => Deletable t (StaticDomBuilderT t m) where
88− {-# INLINABLE deletable #-}
89− deletable delete (StaticDomBuilderT a) = StaticDomBuilderT $ do
90− (result, a') <- lift $ runStateT a []
91− let html = mconcat $ reverse a'
92− b <- hold html (mempty <$ delete)
93− modify (join b:)
94− return result
95−
96−instance (Monad m, Ref m ~ Ref IO, Reflex t) => TriggerEvent t (StaticDomBuilderT t m) where
97− {-# INLINABLE newTriggerEvent #-}
98− newTriggerEvent = return (never, const $ return ())
99− {-# INLINABLE newTriggerEventWithOnComplete #-}
100− newTriggerEventWithOnComplete = return (never, \_ _ -> return ())
101− {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}
102− newEventWithLazyTriggerWithOnComplete _ = return never
103−
104−type SupportsStaticDomBuilder t m = (Reflex t, MonadIO m, MonadHold t m, MonadFix m, PerformEvent t m, Performable m ~ m, MonadReflexCreateTrigger t m, Deletable t m, MonadRef m, Ref m ~ Ref IO)
105−
106−data StaticDomSpace
107−
108−-- | Static documents never produce any events, so this type has no inhabitants
109−data StaticDomEvent (a :: k)
110−
111−-- | Static documents don't process events, so all handlers are equivalent
112−data StaticDomHandler (a :: k) (b :: k) = StaticDomHandler
113−
114−data StaticEventSpec (er :: EventTag -> *) = StaticEventSpec deriving (Generic)
115−
116−instance Default (StaticEventSpec er)
117−
118−instance DomSpace StaticDomSpace where
119− type EventSpec StaticDomSpace = StaticEventSpec
120− type RawTextNode StaticDomSpace = ()
121− type RawElement StaticDomSpace = ()
122− type RawInputElement StaticDomSpace = ()
123− type RawTextAreaElement StaticDomSpace = ()
124−
125−instance SupportsStaticDomBuilder t m => DomBuilder t (StaticDomBuilderT t m) where
126− type DomBuilderSpace (StaticDomBuilderT t m) = StaticDomSpace
127− {-# INLINABLE textNode #-}
128− textNode (TextNodeConfig initialContents setContents) = StaticDomBuilderT $ do
129− --TODO: Do not escape quotation marks; see https://stackoverflow.com/questions/25612166/what-characters-must-be-escaped-in-html-5
130− let escape = BL.toStrict . toLazyByteString . fromHtmlEscapedText
131− modify . (:) <=< hold (escape initialContents) $ fmap escape setContents
132− return $ TextNode ()
133− {-# INLINABLE element #-}
134− element elementTag cfg child = do
135− let toAttr (_mns, k) v = encodeUtf8 k <> "=\"" <> BL.toStrict (toLazyByteString $ fromHtmlEscapedText v) <> "\""
136− es <- newFanEventWithTrigger $ \_ _ -> return (return ())
137− StaticDomBuilderT $ do
138− (result, innerHtml) <- lift $ runStaticDomBuilderT child
139− attrs0 <- foldDyn applyMap (cfg ^. initialAttributes) (cfg ^. modifyAttributes)
140− let attrs1 = ffor (current attrs0) $ mconcat . fmap (\(k, v) -> " " <> toAttr k v) . Map.toList
141− let tagBS = encodeUtf8 elementTag
142− let open = mconcat [constant ("<" <> tagBS <> " "), attrs1, constant ">"]
143− let close = constant $ "</" <> tagBS <> ">" -- TODO handle elements without closing tags
144− modify $ (:) $ mconcat [open, innerHtml, close]
145− return (Element es (), result)
146− {-# INLINABLE placeholder #-}
147− placeholder (PlaceholderConfig toInsertAbove _delete) = StaticDomBuilderT $ do
148− result <- lift $ performEvent (fmap runStaticDomBuilderT toInsertAbove)
149− acc <- foldDyn (:) [] (fmap snd result)
150− modify $ (:) $ join $ mconcat . reverse <$> current acc
151− return $ Placeholder (fmap fst result) never
152− {-# INLINABLE inputElement #-}
153− inputElement cfg = do
154− (e, _result) <- element "input" (cfg ^. inputElementConfig_elementConfig) $ return ()
155− let v0 = constDyn $ cfg ^. inputElementConfig_initialValue
156− let c0 = constDyn $ cfg ^. inputElementConfig_initialChecked
157− let hasFocus = constDyn False -- TODO should this be coming from initialAtttributes
158− return $ InputElement
159− { _inputElement_value = v0
160− , _inputElement_checked = c0
161− , _inputElement_checkedChange = never
162− , _inputElement_input = never
163− , _inputElement_hasFocus = hasFocus
164− , _inputElement_element = e
165− , _inputElement_raw = ()
166− }
167− {-# INLINABLE textAreaElement #-}
168− textAreaElement cfg = do
169− --TODO: Support setValue event
170− (e, _domElement) <- element "textarea" (cfg ^. textAreaElementConfig_elementConfig) $ return ()
171− let v0 = constDyn $ cfg ^. textAreaElementConfig_initialValue
172− let hasFocus = constDyn False -- TODO should this be coming from initialAtttributes
173− return $ TextAreaElement
174− { _textAreaElement_value = v0
175− , _textAreaElement_input = never
176− , _textAreaElement_hasFocus = hasFocus
177− , _textAreaElement_element = e
178− , _textAreaElement_raw = ()
179− }
180− placeRawElement () = return ()
181− wrapRawElement () _ = return $ Element (EventSelector $ const never) ()
182−
183−--TODO: Make this more abstract --TODO: Put the WithWebView underneath PerformEventT - I think this would perform better
184−type StaticWidget x = PostBuildT Spider (StaticDomBuilderT Spider (PerformEventT Spider (SpiderHost Global)))
185−
186−renderStatic :: StaticWidget x a -> IO (a, ByteString)
187−renderStatic w = do
188− runSpiderHost $ do
189− (postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
190− ((res, bs), FireCommand fire) <- hostPerformEventT $ runStaticDomBuilderT (runPostBuildT w postBuild)
191− mPostBuildTrigger <- readRef postBuildTriggerRef
192− forM_ mPostBuildTrigger $ \postBuildTrigger -> fire [postBuildTrigger :=> Identity ()] $ return ()
193− bs' <- sample bs
194− return (res, bs')
src/Reflex/Dom/Deletable/Class.hsdeleted−17
@@ -1,17 +0,0 @@
1−{-# LANGUAGE FlexibleInstances #-}
2−{-# LANGUAGE FunctionalDependencies #-}
3−{-# LANGUAGE MultiParamTypeClasses #-}
4−{-# LANGUAGE UndecidableInstances #-}
5−module Reflex.Dom.Deletable.Class where
6−
7−import Reflex
8−
9−import Control.Monad.Reader
10−import Control.Monad.Trans.Control
11−
12−class (Reflex t, Monad m) => Deletable t m | m -> t where
13− deletable :: Event t () -> m a -> m a
14−
15−instance Deletable t m => Deletable t (ReaderT r m) where
16− {-# INLINABLE deletable #-}
17− deletable = liftThrough . deletable
src/Reflex/Dom/DynamicWriter.hsdeleted−241
@@ -1,241 +0,0 @@
1−{-# LANGUAGE CPP #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FunctionalDependencies #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE RecursiveDo #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE TypeFamilies #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−module Reflex.Dom.DynamicWriter where
13−
14−import Control.Lens hiding (element)
15−import Control.Monad.Exception
16−import Control.Monad.IO.Class
17−import Control.Monad.Reader
18−import Control.Monad.Ref
19−import Control.Monad.State.Strict
20−import Data.Dependent.Map (DMap)
21−import Data.Foldable
22−import Data.Functor.Compose
23−import Data.Functor.Misc
24−import Data.List.NonEmpty (NonEmpty, nonEmpty)
25−import Data.Map (Map)
26−import qualified Data.Map as Map
27−import Data.Semigroup
28−import Data.Traversable
29−import Reflex
30−import Reflex.Dom.Builder.Class
31−import Reflex.Dom.Class
32−import Reflex.Dom.PerformEvent.Class
33−import Reflex.Dom.PostBuild.Class
34−import Reflex.Host.Class
35−
36−instance MonadTrans (DynamicWriterT t w) where
37− lift = DynamicWriterT . lift
38−
39−data PatchMap a where
40− PatchMap :: Ord k => Map k (Maybe v) -> PatchMap (Map k v)
41−
42−instance Patch PatchMap where
43− apply (PatchMap p) old = Just $! insertions `Map.union` (old `Map.difference` deletions) --TODO: return Nothing sometimes --Note: the strict application here is critical to ensuring that incremental merges don't hold onto all their prerequisite events forever; can we make this more robust?
44− where insertions = Map.mapMaybeWithKey (const id) p
45− deletions = Map.mapMaybeWithKey (const nothingToJust) p
46− nothingToJust = \case
47− Nothing -> Just ()
48− Just _ -> Nothing
49−
50−instance Ord k => Semigroup (PatchMap (Map k v)) where
51− PatchMap a <> PatchMap b = PatchMap $ a `mappend` b --TODO: Add a semigroup instance for Map
52− -- PatchMap is idempotent, so stimes n is id for every n
53−#if MIN_VERSION_semigroups(0,17,0)
54− stimes = stimesIdempotentMonoid
55−#else
56− times1p n x = case compare n 0 of
57− LT -> error "stimesIdempotentMonoid: negative multiplier"
58− EQ -> mempty
59− GT -> x
60−#endif
61−
62−instance Ord k => Monoid (PatchMap (Map k v)) where
63− mempty = PatchMap mempty
64− mappend = (<>)
65−
66−mconcatIncremental :: (Reflex t, MonadHold t m, MonadFix m, Monoid v) => Map k v -> Event t (PatchMap (Map k v)) -> m (Dynamic t v)
67−mconcatIncremental m0 e = do
68− d <- foldDynMaybe apply m0 e
69− return $ fmap (mconcat . Map.elems) d
70−
71−mapIncrementalMapValuesWithKey :: Reflex t => (k -> v -> v') -> Incremental t PatchMap (Map k v) -> Incremental t PatchMap (Map k v')
72−mapIncrementalMapValuesWithKey f = unsafeMapIncremental (Map.mapWithKey f) $ \(PatchMap m) -> PatchMap $ Map.mapWithKey (\k mv -> fmap (f k) mv) m
73−
74−mapIncrementalMapValues :: Reflex t => (v -> v') -> Incremental t PatchMap (Map k v) -> Incremental t PatchMap (Map k v')
75−mapIncrementalMapValues f = mapIncrementalMapValuesWithKey $ const f
76−
77−unsafeMapIncremental :: (Reflex t, Patch p, Patch p') => (a -> a') -> (p a -> p' a') -> Incremental t p a -> Incremental t p' a'
78−unsafeMapIncremental f g a = unsafeBuildIncremental (fmap f $ sample $ currentIncremental a) $ g <$> updatedIncremental a
79−
80−incrementalExtractFunctorDMap :: Reflex t => Incremental t PatchMap (Map k (f v)) -> Incremental t PatchDMap (DMap (Const2 k v) f)
81−incrementalExtractFunctorDMap = unsafeMapIncremental mapWithFunctorToDMap $ \(PatchMap m) -> PatchDMap $ mapWithFunctorToDMap $ fmap Compose m
82−
83−mergeIncrementalMap :: (Reflex t, Ord k) => Incremental t PatchMap (Map k (Event t v)) -> Event t (Map k v)
84−mergeIncrementalMap = fmap dmapToMap . mergeIncremental . incrementalExtractFunctorDMap
85−
86−holdIncrementalReplaceableMap :: forall t k v m. (MonadFix m, MonadHold t m, Reflex t, Ord k) => Map k (Replaceable t v) -> Event t (PatchMap (Map k (Replaceable t v))) -> m (Incremental t PatchMap (Map k v))
87−holdIncrementalReplaceableMap m0 m' = do
88− rec vals <- holdIncremental m0 $ m' <> valChanges
89− let valChanges = fmap PatchMap $ mergeIncrementalMap $ mapIncrementalMapValues _replaceable_modify vals
90− return $ mapIncrementalMapValues _replaceable_value vals
91−
92−mergeDynIncremental :: (Reflex t, Ord k) => Incremental t PatchMap (Map k (Dynamic t v)) -> Incremental t PatchMap (Map k v)
93−mergeDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues
94− where changedValues = fmap (PatchMap . fmap Just) $ mergeIncrementalMap $ mapIncrementalMapValues updated a
95− addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m
96−
97−data Replaceable t w = Replaceable
98− { _replaceable_value :: w
99− , _replaceable_modify :: Event t (Maybe (Replaceable t w)) -- "Please delete" is represented with an event of Nothing; all subsequent events will be ignored
100− }
101−
102−type DynamicWriterAccumulator t w = [Replaceable t (Dynamic t w)]
103−
104−newtype DynamicWriterT t w m a = DynamicWriterT { unDynamicWriterT :: StateT (DynamicWriterAccumulator t w) m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadHold t, MonadSample t, MonadAsyncException, MonadException) -- The list is kept in reverse order
105−
106−instance HasWebView m => HasWebView (DynamicWriterT t w m) where
107− type WebViewPhantom (DynamicWriterT t w m) = WebViewPhantom m
108− askWebView = lift askWebView
109−
110−instance MonadRef m => MonadRef (DynamicWriterT t w m) where
111− type Ref (DynamicWriterT t w m) = Ref m
112− newRef = lift . newRef
113− readRef = lift . readRef
114− writeRef r = lift . writeRef r
115−
116−instance MonadAtomicRef m => MonadAtomicRef (DynamicWriterT t w m) where
117− atomicModifyRef r = lift . atomicModifyRef r
118−
119−instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (DynamicWriterT t w m) where
120− newEventWithTrigger = lift . newEventWithTrigger
121− newFanEventWithTrigger f = lift $ newFanEventWithTrigger f
122−
123−runDynamicWriterTInternal :: DynamicWriterT t w m a -> m (a, DynamicWriterAccumulator t w)
124−runDynamicWriterTInternal (DynamicWriterT a) = runStateT a []
125−
126−mconcatIncrementalReplaceableDynMap :: forall m t k v. (MonadFix m, MonadHold t m, Reflex t, Monoid v, Ord k) => Map k (Replaceable t (Dynamic t v)) -> Event t (PatchMap (Map k (Replaceable t (Dynamic t v)))) -> Event t () -> m (Replaceable t (Dynamic t v))
127−mconcatIncrementalReplaceableDynMap m0 m' additionsCeased = do
128− rec vals <- holdIncremental m0 $ m' <> valChanges
129− let valChanges = fmap PatchMap $ mergeIncrementalMap $ mapIncrementalMapValues _replaceable_modify vals
130− let i = mapIncrementalMapValues _replaceable_value vals
131− noMoreAdditions <- holdDyn False $ True <$ additionsCeased
132− let replaceSelf nma x = do
133− guard nma
134− case Map.toList x of
135− [] -> return Nothing -- Delete self
136− [(_, n)] -> return $ Just n --TODO: What if this one is also replacing itself simultaneously?
137− _ -> mzero
138− result = fmap (mconcat . Map.elems) $ incrementalToDynamic $ mergeDynIncremental i
139− return $ Replaceable result $ fmapMaybe id $ updated $ zipDynWith replaceSelf noMoreAdditions $ incrementalToDynamic vals
140−
141−runDynamicWriterT :: (MonadFix m, Reflex t, MonadHold t m, Monoid w) => DynamicWriterT t w m a -> m (a, Dynamic t w)
142−runDynamicWriterT (DynamicWriterT a) = do
143− (result, ws) <- runStateT a []
144− Replaceable w _ <- mconcatIncrementalReplaceableDynMap (Map.fromList $ zip [1 :: Int ..] $ reverse ws) never never
145− return (result, w)
146−
147−class Monad m => MonadDynamicWriter t w m | m -> t w where
148− tellDyn :: Dynamic t w -> m ()
149−
150−instance (Monad m, Reflex t) => MonadDynamicWriter t w (DynamicWriterT t w m) where
151− tellDyn w = DynamicWriterT $ modify (Replaceable w never :)
152−
153−instance MonadReader r m => MonadReader r (DynamicWriterT t w m) where
154− ask = lift ask
155− local f (DynamicWriterT a) = DynamicWriterT $ mapStateT (local f) a
156− reader = lift . reader
157−
158−liftDynamicWriterTThroughSync :: Monad m' => (m (a, DynamicWriterAccumulator t w) -> m' (b, (a, DynamicWriterAccumulator t w))) -> DynamicWriterT t w m a -> DynamicWriterT t w m' (b, a)
159−liftDynamicWriterTThroughSync f (DynamicWriterT child) = DynamicWriterT $ do
160− s <- get
161− (b, (a, newS)) <- lift $ f $ runStateT child s
162− put newS
163− return (b, a)
164−
165−{-# INLINABLE liftDynamicWriterTElementConfig #-}
166−liftDynamicWriterTElementConfig :: ElementConfig er t (DynamicWriterT t w m) -> ElementConfig er t m
167−liftDynamicWriterTElementConfig cfg = cfg
168− { _elementConfig_eventSpec = _elementConfig_eventSpec cfg
169− }
170−
171−instance (DomBuilder t m, Monoid w, MonadHold t m, MonadFix m) => DomBuilder t (DynamicWriterT t w m) where
172− type DomBuilderSpace (DynamicWriterT t w m) = DomBuilderSpace m
173− textNode = liftTextNode
174− element elementTag cfg (DynamicWriterT child) = DynamicWriterT $ do
175− s <- get
176− let cfg' = liftDynamicWriterTElementConfig cfg
177− (el, (a, newS)) <- lift $ element elementTag cfg' $ runStateT child s
178− put newS
179− return (el, a)
180− placeholder cfg = do
181− let cfg' = cfg
182− { _placeholderConfig_insertAbove = runDynamicWriterTInternal <$> _placeholderConfig_insertAbove cfg
183− }
184− let manageChildren :: Event t (NonEmpty (Replaceable t (Dynamic t w))) -- ^ Add nodes on the right; these are in reverse order
185− -> Event t () -- ^ No more nodes will be added after this event fires
186− -> m (Replaceable t (Dynamic t w))
187− manageChildren newChildren additionsCeased = do
188− rec nextId <- hold (0 :: Int) newNextId -- We assume this will never wrap around
189− let numberedNewChildren :: Event t (Int, PatchMap (Map Int (Replaceable t (Dynamic t w))))
190− numberedNewChildren = flip pushAlways newChildren $ \rcs -> do
191− let cs = reverse $ toList rcs
192− myFirstId <- sample nextId
193− let (myNextId, numbered) = mapAccumL (\n v -> (succ n, (n, Just v))) myFirstId cs
194− return (myNextId, PatchMap $ Map.fromList numbered)
195− newNextId = fst <$> numberedNewChildren
196− mconcatIncrementalReplaceableDynMap Map.empty (snd <$> numberedNewChildren) additionsCeased
197− rec children <- lift $ manageChildren childOutputs $ cfg ^. deleteSelf
198− p <- DynamicWriterT $ do
199− modify (children:)
200− lift $ placeholder cfg'
201− let result = fst <$> _placeholder_insertedAbove p
202− childOutputs = fmapMaybe (nonEmpty . snd) $ _placeholder_insertedAbove p
203− return $ p
204− { _placeholder_insertedAbove = result
205− }
206− inputElement cfg = lift $ inputElement $ cfg & inputElementConfig_elementConfig %~ liftDynamicWriterTElementConfig
207− textAreaElement cfg = lift $ textAreaElement $ cfg & textAreaElementConfig_elementConfig %~ liftDynamicWriterTElementConfig
208− placeRawElement = lift . placeRawElement
209− wrapRawElement e cfg = lift $ wrapRawElement e $ cfg
210− { _rawElementConfig_eventSpec = _rawElementConfig_eventSpec cfg
211− }
212−
213−instance (Deletable t m, Reflex t, Monoid w, MonadHold t m, MonadFix m) => Deletable t (DynamicWriterT t w m) where
214− deletable delete child = do
215− (result, output) <- lift $ deletable delete $ runDynamicWriterT child
216− DynamicWriterT $ modify (Replaceable output (Nothing <$ delete) :)
217− return result
218−
219−instance PerformEvent t m => PerformEvent t (DynamicWriterT t w m) where
220− type Performable (DynamicWriterT t w m) = Performable m
221− performEvent_ = lift . performEvent_
222− performEvent = lift . performEvent
223−
224−instance TriggerEvent t m => TriggerEvent t (DynamicWriterT t w m) where
225− newTriggerEvent = lift newTriggerEvent
226− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
227− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
228−
229−instance PostBuild t m => PostBuild t (DynamicWriterT t w m) where
230− getPostBuild = lift getPostBuild
231−
232−instance MonadDynamicWriter t w m => MonadDynamicWriter t w (ReaderT r m) where
233− tellDyn = lift . tellDyn
234−
235−instance MonadState s m => MonadState s (DynamicWriterT t w m) where
236− get = lift get
237− put = lift . put
238−
239−instance HasJS x m => HasJS x (DynamicWriterT t w m) where
240− type JSM (DynamicWriterT t w m) = JSM m
241− liftJS = lift . liftJS
src/Reflex/Dom/Internal.hsdeleted−124
@@ -1,124 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE FlexibleInstances #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE LambdaCase #-}
6−{-# LANGUAGE MultiParamTypeClasses #-}
7−{-# LANGUAGE NoMonomorphismRestriction #-}
8−{-# LANGUAGE RankNTypes #-}
9−{-# LANGUAGE RecursiveDo #-}
10−{-# LANGUAGE ScopedTypeVariables #-}
11−{-# LANGUAGE TypeFamilies #-}
12−{-# LANGUAGE TypeOperators #-}
13−{-# LANGUAGE UndecidableInstances #-}
14−module Reflex.Dom.Internal where
15−
16−import Prelude hiding (concat, mapM, mapM_, sequence, sequence_)
17−
18−import Reflex.Dom.Builder.Immediate
19−import Reflex.Dom.Class
20−import Reflex.Dom.Internal.Foreign
21−import Reflex.Dom.PerformEvent.Base
22−import Reflex.Dom.PostBuild.Class
23−import Reflex.Host.Class
24−import Reflex.Spider (Global, Spider, SpiderHost, runSpiderHost)
25−
26−import Control.Concurrent
27−import Control.Lens
28−import Control.Monad
29−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
30−import Control.Monad.Ref
31−import Data.ByteString (ByteString)
32−import Data.Dependent.Sum (DSum (..))
33−import Data.IORef
34−import Data.Maybe
35−import Data.Monoid ((<>))
36−import qualified Data.Text as T
37−import Data.Text.Encoding
38−import GHCJS.DOM hiding (runWebGUI)
39−import GHCJS.DOM.Document
40−import GHCJS.DOM.Element
41−import GHCJS.DOM.Node
42−import qualified GHCJS.DOM.Types as DOM
43−
44−{-# INLINABLE mainWidget #-}
45−mainWidget :: (forall x. Widget x ()) -> IO ()
46−mainWidget w = runWebGUI $ \webView -> withWebViewSingleton webView $ \webViewSing -> do
47− Just doc <- fmap DOM.castToHTMLDocument <$> webViewGetDomDocument webView
48− Just body <- getBody doc
49− attachWidget body webViewSing w
50−
51−--TODO: The x's should be unified here
52−{-# INLINABLE mainWidgetWithHead #-}
53−mainWidgetWithHead :: (forall x. Widget x ()) -> (forall x. Widget x ()) -> IO ()
54−mainWidgetWithHead h b = runWebGUI $ \webView -> withWebViewSingleton webView $ \webViewSing -> do
55− Just doc <- fmap DOM.castToHTMLDocument <$> webViewGetDomDocument webView
56− Just headElement <- fmap DOM.castToHTMLElement <$> getHead doc
57− attachWidget headElement webViewSing h
58− Just body <- getBody doc
59− attachWidget body webViewSing b
60−
61−{-# INLINABLE mainWidgetWithCss #-}
62−mainWidgetWithCss :: ByteString -> (forall x. Widget x ()) -> IO ()
63−mainWidgetWithCss css w = runWebGUI $ \webView -> withWebViewSingleton webView $ \webViewSing -> do
64− Just doc <- fmap DOM.castToHTMLDocument <$> webViewGetDomDocument webView
65− Just headElement <- fmap DOM.castToHTMLElement <$> getHead doc
66− setInnerHTML headElement . Just $ "<style>" <> T.unpack (decodeUtf8 css) <> "</style>" --TODO: Fix this
67− Just body <- getBody doc
68− attachWidget body webViewSing w
69−
70−type Widget x = PostBuildT Spider (ImmediateDomBuilderT Spider (WithWebView x (PerformEventT Spider (SpiderHost Global)))) --TODO: Make this more abstract --TODO: Put the WithWebView underneath PerformEventT - I think this would perform better
71−
72−{-# INLINABLE attachWidget #-}
73−attachWidget :: DOM.IsElement e => e -> WebViewSingleton x -> Widget x a -> IO a
74−attachWidget rootElement wv w = fst <$> attachWidget' rootElement wv w
75−
76−{-# INLINABLE attachWidget' #-}
77−attachWidget' :: DOM.IsElement e => e -> WebViewSingleton x -> Widget x a -> IO (a, FireCommand Spider (SpiderHost Global))
78−attachWidget' rootElement wv w = do
79− Just doc <- getOwnerDocument rootElement
80− Just df <- createDocumentFragment doc
81− events <- newChan
82− (result, fc@(FireCommand fire)) <- runSpiderHost $ do
83− (postBuild, postBuildTriggerRef) <- newEventWithTriggerRef
84− let builderEnv = ImmediateDomBuilderEnv
85− { _immediateDomBuilderEnv_document = doc
86− , _immediateDomBuilderEnv_parent = toNode df
87− , _immediateDomBuilderEnv_events = events
88− }
89− results@(_, FireCommand fire) <- hostPerformEventT $ runWithWebView (runImmediateDomBuilderT (runPostBuildT w postBuild) builderEnv) wv
90− mPostBuildTrigger <- readRef postBuildTriggerRef
91− forM_ mPostBuildTrigger $ \postBuildTrigger -> fire [postBuildTrigger :=> Identity ()] $ return ()
92− return results
93− void $ forkIO $ forever $ do
94− ers <- readChan events
95− _ <- postGUISync $ runSpiderHost $ do
96− mes <- liftIO $ forM ers $ \(TriggerRef er :=> TriggerInvocation a _) -> do
97− me <- readIORef er
98− return $ fmap (\e -> e :=> Identity a) me
99− _ <- fire (catMaybes mes) $ return ()
100− liftIO $ forM_ ers $ \(_ :=> TriggerInvocation _ cb) -> cb
101− return ()
102− setInnerHTML rootElement $ Just (""::String)
103− _ <- appendChild rootElement $ Just df
104− return (result, fc)
105−
106−data AppInput t = AppInput
107− { _appInput_window :: Window t
108− }
109−
110−data AppOutput t = AppOutput --TODO: Add quit event
111− { _appOutput_windowConfig :: WindowConfig t
112− }
113−
114−runApp' :: (t ~ Spider) => (forall x. AppInput t -> Widget x (AppOutput t)) -> IO ()
115−runApp' app = runWebGUI $ \webView -> withWebViewSingleton webView $ \webViewSing -> do
116− Just doc <- fmap DOM.castToHTMLDocument <$> webViewGetDomDocument webView
117− Just body <- getBody doc
118− Just win <- getDefaultView doc
119− rec o <- attachWidget body webViewSing $ do
120− w <- lift $ wrapWindow win $ _appOutput_windowConfig o
121− app $ AppInput
122− { _appInput_window = w
123− }
124− return ()
src/Reflex/Dom/Location.hsdeleted−13
@@ -1,13 +0,0 @@
1−module Reflex.Dom.Location (getLocationHost, getLocationProtocol) where
2−
3−import Data.Text (Text)
4−import Reflex.Dom.Class
5−import qualified Reflex.Dom.Internal.Foreign as F
6−
7−import Control.Monad.IO.Class
8−
9−getLocationHost :: (MonadIO m) => WebViewSingleton x -> m Text
10−getLocationHost (WebViewSingleton wv) = liftIO $ F.getLocationHost wv
11−
12−getLocationProtocol :: (MonadIO m) => WebViewSingleton x -> m Text
13−getLocationProtocol (WebViewSingleton wv) = liftIO $ F.getLocationProtocol wv
src/Reflex/Dom/PerformEvent/Base.hsdeleted−177
@@ -1,177 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE RankNTypes #-}
6−{-# LANGUAGE RecursiveDo #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE StandaloneDeriving #-}
9−{-# LANGUAGE TypeFamilies #-}
10−{-# LANGUAGE TypeOperators #-}
11−{-# LANGUAGE UndecidableInstances #-}
12−module Reflex.Dom.PerformEvent.Base where
13−
14−import Foreign.JavaScript.TH
15−import Reflex
16−import Reflex.Dom.Deletable.Class
17−import Reflex.Dom.PerformEvent.Class
18−import Reflex.Host.Class
19−
20−import Control.Lens
21−import Control.Monad.Exception
22−import Control.Monad.Identity
23−import Control.Monad.Ref
24−import Control.Monad.State.Strict
25−import Data.Align
26−import Data.Dependent.Map (DMap)
27−import qualified Data.Dependent.Map as DMap
28−import Data.Dependent.Sum
29−import Data.Functor.Compose
30−import Data.Functor.Misc
31−import Data.Maybe
32−import Data.Semigroup
33−import Data.These
34−import Data.Word
35−
36−newtype EventTriggerRef t m a = EventTriggerRef { unEventTriggerRef :: Ref m (Maybe (EventTrigger t a)) }
37−
38−newtype FireCommand t m = FireCommand { runFireCommand :: forall a. [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m [a] } --TODO: The handling of this ReadPhase seems wrong, or at least inelegant; how do we actually make the decision about what order frames run in?
39−
40−newtype PerformEventT t m a = PerformEventT { unPerformEventT :: StateT [Event t (These (PerformEventT t m [DSum (EventTriggerRef t m) Identity]) ())] (HostFrame t) a }
41−
42−deriving instance ReflexHost t => Functor (PerformEventT t m)
43−deriving instance ReflexHost t => Applicative (PerformEventT t m)
44−deriving instance ReflexHost t => Monad (PerformEventT t m)
45−deriving instance ReflexHost t => MonadFix (PerformEventT t m)
46−deriving instance (ReflexHost t, MonadIO (HostFrame t)) => MonadIO (PerformEventT t m)
47−deriving instance (ReflexHost t, MonadException (HostFrame t)) => MonadException (PerformEventT t m)
48−
49−instance (ReflexHost t, MonadAsyncException (HostFrame t)) => MonadAsyncException (PerformEventT t m) where
50− mask f = PerformEventT $ mask $ \unmask -> unPerformEventT $ f $ PerformEventT . unmask . unPerformEventT
51−
52−instance (ReflexHost t, HasWebView (HostFrame t)) => HasWebView (PerformEventT t m) where
53− type WebViewPhantom (PerformEventT t m) = WebViewPhantom (HostFrame t)
54− askWebView = PerformEventT $ lift askWebView
55−
56−instance (ReflexHost t, Ref m ~ Ref IO, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO) => PerformEvent t (PerformEventT t m) where
57− type Performable (PerformEventT t m) = PerformEventT t m
58− {-# INLINABLE performEvent_ #-}
59− performEvent_ = PerformEventT . modify . (:) . fmap (This . (>> return []))
60− {-# INLINABLE performEvent #-}
61− performEvent e = PerformEventT $ do
62− (eResult, reResultTrigger) <- newEventWithTriggerRef
63− modify $ (:) $ ffor e $ \o -> This $ do
64− result <- o
65− return [EventTriggerRef reResultTrigger :=> Identity result]
66− return eResult
67−
68−instance (ReflexHost t, Monad (HostFrame t), Ref (HostFrame t) ~ Ref IO, Ref m ~ Ref IO) => Deletable t (PerformEventT t m) where
69− {-# INLINABLE deletable #-}
70− deletable d a = PerformEventT $ do
71− (result, reverseEventsToPerform) <- lift $ runStateT (unPerformEventT a) []
72− let (numberedEvents, _) = numberWith (\n e -> Const2 n :=> e) (reverse reverseEventsToPerform) (1 :: Word64)
73− eventToPerform <- lift $ mergePerformEventsAndAdd (DMap.fromList numberedEvents) never
74− modify (align eventToPerform d :)
75− return result
76−
77−instance ReflexHost t => MonadReflexCreateTrigger t (PerformEventT t m) where
78− {-# INLINABLE newEventWithTrigger #-}
79− newEventWithTrigger = PerformEventT . lift . newEventWithTrigger
80− {-# INLINABLE newFanEventWithTrigger #-}
81− newFanEventWithTrigger f = PerformEventT $ lift $ newFanEventWithTrigger f
82−
83−{-# INLINABLE numberWith #-}
84−numberWith :: (Enum n, Traversable t) => (n -> a -> b) -> t a -> n -> (t b, n)
85−numberWith f t n0 = flip runState n0 $ forM t $ \x -> state $ \n -> (f n x, succ n)
86−
87−{-# INLINABLE mergePerformEventsAndAdd #-}
88−mergePerformEventsAndAdd :: forall t m. ReflexHost t
89− => DMap (Const2 Word64 (These (PerformEventT t m [DSum (EventTriggerRef t m) Identity]) ())) (Event t)
90− -> Event t (PatchDMap (DMap (Const2 Word64 (These (PerformEventT t m [DSum (EventTriggerRef t m) Identity]) ())) (Event t)))
91− -> HostFrame t (Event t (PerformEventT t m [DSum (EventTriggerRef t m) Identity]))
92−mergePerformEventsAndAdd initial eAddNew = do
93− rec events :: Incremental t PatchDMap (DMap (Const2 Word64 (These (PerformEventT t m [DSum (EventTriggerRef t m) Identity]) ())) (Event t))
94− <- holdIncremental initial $ eAddNew <> eDelete --TODO: Eliminate empty firings
95− let event = mergeWith DMap.union [mergeIncremental events, coincidence (fmap (\(PatchDMap m) -> merge $ DMap.mapMaybeWithKey (const getCompose) m) eAddNew)]
96− eventToPerform :: Event t (PerformEventT t m [DSum (EventTriggerRef t m) Identity])
97− eventToPerform = ffor event $
98− fmap concat .
99− sequence .
100− fmapMaybe (\(Const2 _ :=> Identity x) -> x ^? here) .
101− DMap.toList
102− eDelete :: Event t (PatchDMap (DMap (Const2 Word64 (These (PerformEventT t m [DSum (EventTriggerRef t m) Identity]) ())) (Event t)))
103− eDelete = fforMaybe event $
104− fmap (PatchDMap . DMap.fromList) .
105− (\l -> if null l then Nothing else Just l) .
106− fmapMaybe (\(Const2 k :=> Identity x) -> (Const2 k :=> Compose Nothing) <$ x ^? there) .
107− DMap.toList
108− return eventToPerform
109−
110−{-# INLINABLE runPerformEventT #-}
111−runPerformEventT :: forall t m a. (ReflexHost t, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO, Ref m ~ Ref IO) => PerformEventT t m a -> HostFrame t (a, Event t (HostFrame t [DSum (EventTriggerRef t m) Identity]))
112−runPerformEventT (PerformEventT a) = do
113− (result, reverseEventsToPerform) <- runStateT a []
114− (eAddNew, reAddNewTrigger) <- newEventWithTriggerRef
115− let (numberedEvents, nextNumber) = numberWith (\n e -> Const2 n :=> e) (reverse reverseEventsToPerform) (1 :: Word64)
116− nextNumberRef <- newRef nextNumber
117− let runResult :: PerformEventT t m [DSum (EventTriggerRef t m) Identity] -> HostFrame t [DSum (EventTriggerRef t m) Identity]
118− runResult (PerformEventT r) = do
119− (followups, reverseNewEventsToPerform) <- runStateT r []
120− oldN <- readRef nextNumberRef
121− let (numberedNewEvents, newN) = numberWith (\n e -> Const2 n :=> Compose (Just e)) (reverse reverseNewEventsToPerform) oldN
122− if newN == oldN then return followups else do
123− writeRef nextNumberRef newN
124− return $ (EventTriggerRef reAddNewTrigger :=> Identity (PatchDMap (DMap.fromList numberedNewEvents))) : followups
125− eventToPerform <- mergePerformEventsAndAdd (DMap.fromList numberedEvents) eAddNew
126− return (result, runResult <$> eventToPerform)
127−
128−{-# INLINABLE hostPerformEventT #-}
129−hostPerformEventT :: forall t m a. (Monad m, MonadSubscribeEvent t m, MonadReflexHost t m, MonadRef m, Ref m ~ Ref IO, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO) => PerformEventT t m a -> m (a, FireCommand t m)
130−hostPerformEventT a = do
131− (result, eventToPerform) <- runHostFrame $ runPerformEventT a
132− eventToPerformHandle <- subscribeEvent eventToPerform
133− return $ (,) result $ FireCommand $ \triggers (readPhase :: ReadPhase m a') -> do
134− let go :: [DSum (EventTrigger t) Identity] -> m [a']
135− go ts = do
136− (result', mToPerform) <- fireEventsAndRead ts $ do
137− mToPerform <- sequence =<< readEvent eventToPerformHandle
138− result' <- readPhase
139− return (result', mToPerform)
140− case mToPerform of
141− Nothing -> return [result']
142− Just toPerform -> do
143− followupEventTriggerRefs <- runHostFrame toPerform
144− followupEventTriggers <- forM followupEventTriggerRefs $ \(EventTriggerRef rt :=> x) -> do
145− mt <- readRef rt
146− return $ fmap (:=> x) mt
147− fmap (result':) $ go $ catMaybes followupEventTriggers
148− go triggers
149−
150−instance ReflexHost t => MonadSample t (PerformEventT t m) where
151− {-# INLINABLE sample #-}
152− sample = PerformEventT . lift . sample
153−
154−instance (ReflexHost t, MonadHold t m) => MonadHold t (PerformEventT t m) where
155− {-# INLINABLE hold #-}
156− hold v0 v' = PerformEventT $ lift $ hold v0 v'
157− {-# INLINABLE holdDyn #-}
158− holdDyn v0 v' = PerformEventT $ lift $ holdDyn v0 v'
159− {-# INLINABLE holdIncremental #-}
160− holdIncremental v0 v' = PerformEventT $ lift $ holdIncremental v0 v'
161−
162−instance (MonadRef (HostFrame t), ReflexHost t) => MonadRef (PerformEventT t m) where
163− type Ref (PerformEventT t m) = Ref (HostFrame t)
164− {-# INLINABLE newRef #-}
165− newRef = PerformEventT . lift . newRef
166− {-# INLINABLE readRef #-}
167− readRef = PerformEventT . lift . readRef
168− {-# INLINABLE writeRef #-}
169− writeRef r = PerformEventT . lift . writeRef r
170−
171−instance (MonadAtomicRef (HostFrame t), ReflexHost t) => MonadAtomicRef (PerformEventT t m) where
172− {-# INLINABLE atomicModifyRef #-}
173− atomicModifyRef r = PerformEventT . lift . atomicModifyRef r
174−
175−instance (HasJS x (HostFrame t), ReflexHost t) => HasJS x (PerformEventT t m) where
176− type JSM (PerformEventT t m) = JSM (HostFrame t)
177− liftJS = PerformEventT . lift . liftJS
src/Reflex/Dom/PerformEvent/Class.hsdeleted−46
@@ -1,46 +0,0 @@
1−{-# LANGUAGE FlexibleContexts #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FunctionalDependencies #-}
4−{-# LANGUAGE MultiParamTypeClasses #-}
5−{-# LANGUAGE RankNTypes #-}
6−{-# LANGUAGE ScopedTypeVariables #-}
7−{-# LANGUAGE TypeFamilies #-}
8−{-# LANGUAGE TypeOperators #-}
9−{-# LANGUAGE UndecidableInstances #-}
10−module Reflex.Dom.PerformEvent.Class where
11−
12−import Reflex
13−
14−import Control.Monad.Reader
15−
16−class (Reflex t, Monad (Performable m), Monad m) => PerformEvent t m | m -> t where
17− type Performable m :: * -> *
18− performEvent :: Event t (Performable m a) -> m (Event t a)
19− performEvent_ :: Event t (Performable m ()) -> m ()
20−
21−--TODO: Shouldn't have IO hard-coded
22−class Monad m => TriggerEvent t m | m -> t where
23− newTriggerEvent :: m (Event t a, a -> IO ())
24− newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) --TODO: This and newTriggerEvent should be unified somehow
25− newEventWithLazyTriggerWithOnComplete :: ((a -> IO () -> IO ()) -> IO (IO ())) -> m (Event t a)
26−
27−{-# INLINABLE performEventAsync #-}
28−performEventAsync :: (TriggerEvent t m, PerformEvent t m) => Event t ((a -> IO ()) -> Performable m ()) -> m (Event t a)
29−performEventAsync e = do
30− (eOut, triggerEOut) <- newTriggerEvent
31− performEvent_ $ fmap ($ triggerEOut) e
32− return eOut
33−
34−instance PerformEvent t m => PerformEvent t (ReaderT r m) where
35− type Performable (ReaderT r m) = ReaderT r (Performable m)
36− performEvent_ e = do
37− r <- ask
38− lift $ performEvent_ $ flip runReaderT r <$> e
39− performEvent e = do
40− r <- ask
41− lift $ performEvent $ flip runReaderT r <$> e
42−
43−instance TriggerEvent t m => TriggerEvent t (ReaderT r m) where
44− newTriggerEvent = lift newTriggerEvent
45− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
46− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
src/Reflex/Dom/PostBuild/Class.hsdeleted−128
@@ -1,128 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE FunctionalDependencies #-}
4−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE RecursiveDo #-}
7−{-# LANGUAGE ScopedTypeVariables #-}
8−{-# LANGUAGE TypeFamilies #-}
9−{-# LANGUAGE TypeOperators #-}
10−{-# LANGUAGE UndecidableInstances #-}
11−module Reflex.Dom.PostBuild.Class where
12−
13−import Control.Lens hiding (element)
14−import Control.Monad.Exception
15−import Control.Monad.Reader
16−import Control.Monad.Ref
17−import Control.Monad.Trans.Control
18−import Foreign.JavaScript.TH
19−import Reflex
20−import Reflex.Dom.Builder.Class
21−import Reflex.Dom.PerformEvent.Class
22−import Reflex.Host.Class
23−
24−class (Reflex t, Monad m) => PostBuild t m | m -> t where
25− getPostBuild :: m (Event t ())
26−
27−newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadTrans, MonadException, MonadAsyncException)
28−
29−instance MonadTransControl (PostBuildT t) where
30− type StT (PostBuildT t) a = StT (ReaderT (Event t ())) a
31− {-# INLINABLE liftWith #-}
32− liftWith = defaultLiftWith PostBuildT unPostBuildT
33− {-# INLINABLE restoreT #-}
34− restoreT = defaultRestoreT PostBuildT
35−
36−instance (Reflex t, Monad m) => PostBuild t (PostBuildT t m) where
37− {-# INLINABLE getPostBuild #-}
38− getPostBuild = PostBuildT ask
39−
40−instance Deletable t m => Deletable t (PostBuildT t m) where
41− {-# INLINABLE deletable #-}
42− deletable = liftThrough . deletable
43−
44−{-# INLINABLE liftPostBuildTElementConfig #-}
45−liftPostBuildTElementConfig :: ElementConfig er t (PostBuildT t m) -> ElementConfig er t m
46−liftPostBuildTElementConfig cfg = cfg
47− { _elementConfig_eventSpec = _elementConfig_eventSpec cfg
48− }
49−
50−instance (DomBuilder t m, PerformEvent t m, MonadFix m, MonadHold t m) => DomBuilder t (PostBuildT t m) where
51− type DomBuilderSpace (PostBuildT t m) = DomBuilderSpace m
52− {-# INLINABLE textNode #-}
53− textNode = lift . textNode
54− {-# INLINABLE element #-}
55− element t cfg child = liftWith $ \run -> element t (liftPostBuildTElementConfig cfg) $ run child
56− {-# INLINABLE placeholder #-}
57− placeholder cfg = lift $ do
58− rec childPostBuild <- deletable (_placeholder_deletedSelf p) $ performEvent $ return () <$ _placeholder_insertedAbove p
59− p <- placeholder $ cfg
60− { _placeholderConfig_insertAbove = ffor (_placeholderConfig_insertAbove cfg) $ \a -> runPostBuildT a =<< headE childPostBuild
61− }
62− return p
63− {-# INLINABLE inputElement #-}
64− inputElement cfg = lift $ inputElement $ cfg & inputElementConfig_elementConfig %~ liftPostBuildTElementConfig
65− {-# INLINABLE textAreaElement #-}
66− textAreaElement cfg = lift $ textAreaElement $ cfg & textAreaElementConfig_elementConfig %~ liftPostBuildTElementConfig
67− placeRawElement = lift . placeRawElement
68− wrapRawElement e cfg = liftWith $ \run -> wrapRawElement e $ fmap1 run cfg
69−
70−instance MonadSample t m => MonadSample t (PostBuildT t m) where
71− {-# INLINABLE sample #-}
72− sample = lift . sample
73−
74−instance MonadHold t m => MonadHold t (PostBuildT t m) where
75− {-# INLINABLE hold #-}
76− hold v0 = lift . hold v0
77− {-# INLINABLE holdDyn #-}
78− holdDyn v0 = lift . holdDyn v0
79− {-# INLINABLE holdIncremental #-}
80− holdIncremental v0 = lift . holdIncremental v0
81−
82−instance PerformEvent t m => PerformEvent t (PostBuildT t m) where
83− type Performable (PostBuildT t m) = PostBuildT t (Performable m)
84− {-# INLINABLE performEvent_ #-}
85− performEvent_ e = liftWith $ \run -> performEvent_ $ fmap run e
86− {-# INLINABLE performEvent #-}
87− performEvent e = liftWith $ \run -> performEvent $ fmap run e
88−
89−instance (ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where
90− {-# INLINABLE newEventWithTrigger #-}
91− newEventWithTrigger = PostBuildT . lift . newEventWithTrigger
92− {-# INLINABLE newFanEventWithTrigger #-}
93− newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f
94−
95−instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where
96− {-# INLINABLE newTriggerEvent #-}
97− newTriggerEvent = lift newTriggerEvent
98− {-# INLINABLE newTriggerEventWithOnComplete #-}
99− newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete
100− newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete
101−
102−instance MonadRef m => MonadRef (PostBuildT t m) where
103− type Ref (PostBuildT t m) = Ref m
104− {-# INLINABLE newRef #-}
105− newRef = lift . newRef
106− {-# INLINABLE readRef #-}
107− readRef = lift . readRef
108− {-# INLINABLE writeRef #-}
109− writeRef r = lift . writeRef r
110−
111−instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where
112− {-# INLINABLE atomicModifyRef #-}
113− atomicModifyRef r = lift . atomicModifyRef r
114−
115−instance (HasJS x m, ReflexHost t) => HasJS x (PostBuildT t m) where
116− type JSM (PostBuildT t m) = JSM m
117− liftJS = lift . liftJS
118−
119−instance HasWebView m => HasWebView (PostBuildT t m) where
120− type WebViewPhantom (PostBuildT t m) = WebViewPhantom m
121− askWebView = lift askWebView
122−
123−{-# INLINABLE runPostBuildT #-}
124−runPostBuildT :: PostBuildT t m a -> Event t () -> m a
125−runPostBuildT (PostBuildT a) = runReaderT a
126−
127−instance PostBuild t m => PostBuild t (ReaderT r m) where
128− getPostBuild = lift getPostBuild
src/Reflex/Dom/Time.hsdeleted−184
@@ -1,184 +0,0 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE MultiParamTypeClasses #-}
4−{-# LANGUAGE RecursiveDo #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−{-# LANGUAGE TypeFamilies #-}
7−module Reflex.Dom.Time where
8−
9−import Reflex
10−import Reflex.Dom.PerformEvent.Class
11−import Reflex.Dom.PostBuild.Class
12−
13−import Control.Concurrent
14−import qualified Control.Concurrent.Thread.Delay as Concurrent
15−import Control.Monad
16−import Control.Monad.Fix
17−import Control.Monad.IO.Class
18−import Data.Fixed
19−import Data.Time.Clock
20−import Data.Typeable
21−import System.Random
22−
23−data TickInfo
24− = TickInfo { _tickInfo_lastUTC :: UTCTime
25− -- ^ UTC time immediately after the last tick.
26− , _tickInfo_n :: Integer
27− -- ^ Number of time periods since t0
28− , _tickInfo_alreadyElapsed :: NominalDiffTime
29− -- ^ Amount of time already elapsed in the current tick period.
30− }
31− deriving (Eq, Ord, Show, Typeable)
32−
33−-- | Special case of tickLossyFrom that uses the post-build event to start the
34−-- tick thread.
35−tickLossy :: (PostBuild t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m) => NominalDiffTime -> UTCTime -> m (Event t TickInfo)
36−tickLossy dt t0 = tickLossyFrom dt t0 =<< getPostBuild
37−
38−-- | Send events over time with the given basis time and interval
39−-- If the system starts running behind, occurrences will be dropped rather than buffered
40−-- Each occurrence of the resulting event will contain the index of the current interval, with 0 representing the basis time
41−tickLossyFrom
42− :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)
43− => NominalDiffTime
44− -> UTCTime
45− -> Event t a
46− -- ^ Event that starts a tick generation thread. Usually you want this to
47− -- be something like the result of getPostBuild that only fires once. But
48− -- there could be uses for starting multiple timer threads.
49− -> m (Event t TickInfo)
50−tickLossyFrom dt t0 e = do
51− rec result <- performEventAsync $ callAtNextInterval <$> leftmost [() <$ e, () <$ result]
52− return result
53− where callAtNextInterval _ cb = void $ liftIO $ forkIO $ do
54− tick <- getCurrentTick dt t0
55− Concurrent.delay $ ceiling $ (dt - _tickInfo_alreadyElapsed tick) * 1000000
56− cb tick
57−
58−clockLossy :: (MonadIO m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), PostBuild t m, MonadHold t m, MonadFix m) => NominalDiffTime -> UTCTime -> m (Dynamic t TickInfo)
59−clockLossy dt t0 = do
60− initial <- liftIO $ getCurrentTick dt t0
61− e <- tickLossy dt t0
62− holdDyn initial e
63−
64−getCurrentTick :: NominalDiffTime -> UTCTime -> IO TickInfo
65−getCurrentTick dt t0 = do
66− t <- getCurrentTime
67− let offset = t `diffUTCTime` t0
68− (n, alreadyElapsed) = offset `divMod'` dt
69− return $ TickInfo t n alreadyElapsed
70−
71−-- | Delay an Event's occurrences by a given amount in seconds.
72−delay :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
73−delay dt e = performEventAsync $ ffor e $ \a cb -> liftIO $ void $ forkIO $ do
74− Concurrent.delay $ ceiling $ dt * 1000000
75− cb a
76−
77−-- | Send events with Poisson timing with the given basis and rate
78−-- Each occurence of the resulting event will contain the index of
79−-- the current interval, with 0 representing the basis time
80−poissonLossyFrom
81− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
82− => g
83− -> Double
84− -- ^ Poisson event rate (Hz)
85− -> UTCTime
86− -- ^ Baseline time for events
87− -> Event t a
88− -- ^ Event that starts a tick generation thread. Usually you want this to
89− -- be something like the result of getPostBuild that only fires once. But
90− -- there could be uses for starting multiple timer threads.
91− -- Start sending events in response to the event parameter.
92− -> m (Event t TickInfo)
93−poissonLossyFrom rnd rate = inhomogeneousPoissonFrom rnd (constant rate) rate
94−
95−
96−-- | Send events with Poisson timing with the given basis and rate
97−-- Each occurence of the resulting event will contain the index of
98−-- the current interval, with 0 representing the basis time.
99−-- Automatically begin sending events when the DOM is built
100−poissonLossy
101− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
102− => g
103− -> Double
104− -- ^ Poisson event rate (Hz)
105− -> UTCTime
106− -- ^ Baseline time for events
107− -> m (Event t TickInfo)
108−poissonLossy rnd rate t0 = poissonLossyFrom rnd rate t0 =<< getPostBuild
109−
110−-- | Send events with inhomogeneous Poisson timing with the given basis
111−-- and variable rate. Provide a maxRate that you expect to support.
112−inhomogeneousPoissonFrom
113− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m)
114− => g
115− -> Behavior t Double
116− -> Double
117− -> UTCTime
118− -> Event t a
119− -> m (Event t TickInfo)
120−inhomogeneousPoissonFrom rnd rate maxRate t0 e = do
121−
122− -- Create a thread for producing homogeneous poisson events
123− -- along with random Doubles (usage of Double's explained below)
124− ticksWithRateRand <- performEventAsync $
125− fmap callAtNextInterval e
126−
127− -- Filter homogeneous events according to associated
128− -- random values and the current rate parameter
129− return $ attachWithMaybe filterFun rate ticksWithRateRand
130−
131− where
132−
133− -- Inhomogeneous poisson processes are built from faster
134− -- homogeneous ones by randomly dropping events from the
135− -- fast process. For each fast homogeneous event, choose
136− -- a uniform random sample from (0, rMax). If the
137− -- inhomogeneous rate at this moment is greater than the
138− -- random sample, then keep this event, otherwise drop it
139− filterFun :: Double -> (TickInfo, Double) -> Maybe TickInfo
140− filterFun r (tInfo, p)
141− | r >= p = Just tInfo
142− | otherwise = Nothing
143−
144− callAtNextInterval _ cb = void $ liftIO $ forkIO $ go t0 rnd cb 0
145−
146− go tTargetLast lastGen cb lastN = do
147− t <- getCurrentTime
148−
149− -- Generate random numbers for this poisson interval (u)
150− -- and sample-retention likelihood (p)
151− let (u, nextGen) = randomR (0,1) lastGen
152− (p :: Double, nextGen') = randomR (0,maxRate) nextGen
153−
154− -- Inter-event interval is drawn from exponential
155− -- distribution accourding to u
156− let dt = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime
157− nEvents = lastN + 1
158− alreadyElapsed = diffUTCTime t tTargetLast
159− tTarget = addUTCTime dt tTargetLast
160− thisDelay = realToFrac $ diffUTCTime tTarget t :: Double
161− Concurrent.delay $ ceiling $ thisDelay * 1000000
162− _ <- cb (TickInfo t nEvents alreadyElapsed, p)
163− go tTarget nextGen' cb nEvents
164−
165−-- | Send events with inhomogeneous Poisson timing with the given basis
166−-- and variable rate. Provide a maxRate that you expect to support
167−inhomogeneousPoisson
168− :: (RandomGen g, MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, PostBuild t m)
169− => g
170− -> Behavior t Double
171− -> Double
172− -> UTCTime
173− -> m (Event t TickInfo)
174−inhomogeneousPoisson rnd rate maxRate t0 =
175− inhomogeneousPoissonFrom rnd rate maxRate t0 =<< getPostBuild
176−
177−-- | Block occurrences of an Event until the given number of seconds elapses without
178−-- the Event firing, at which point the last occurrence of the Event will fire.
179−debounce :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t a)
180−debounce dt e = do
181− n :: Dynamic t Integer <- count e
182− let tagged = attachPromptlyDynWith (,) n e
183− delayed <- delay dt tagged
184− return $ attachWithMaybe (\n' (t, v) -> if n' == t then Just v else Nothing) (current n) delayed
src/Reflex/Dom/WebSocket.hsdeleted−97
@@ -1,97 +0,0 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
2−{-# LANGUAGE ConstraintKinds #-}
3−{-# LANGUAGE DeriveDataTypeable #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE ForeignFunctionInterface #-}
8−{-# LANGUAGE GADTs #-}
9−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
10−{-# LANGUAGE JavaScriptFFI #-}
11−{-# LANGUAGE MultiParamTypeClasses #-}
12−{-# LANGUAGE NoMonomorphismRestriction #-}
13−{-# LANGUAGE PolyKinds #-}
14−{-# LANGUAGE RankNTypes #-}
15−{-# LANGUAGE RecursiveDo #-}
16−{-# LANGUAGE ScopedTypeVariables #-}
17−{-# LANGUAGE StandaloneDeriving #-}
18−{-# LANGUAGE TemplateHaskell #-}
19−{-# LANGUAGE TypeFamilies #-}
20−{-# LANGUAGE UndecidableInstances #-}
21−
22−module Reflex.Dom.WebSocket where
23−
24−import Prelude hiding (all, concat, concatMap, div, mapM, mapM_, sequence, span)
25−
26−import Reflex
27−import Reflex.Dom.Class
28−import Reflex.Dom.PerformEvent.Class
29−import Reflex.Dom.PostBuild.Class
30−import Reflex.Dom.WebSocket.Foreign
31−
32−import Control.Concurrent
33−import Control.Concurrent.STM
34−import Control.Exception (SomeException, catch)
35−import Control.Lens
36−import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
37−import Control.Monad.IO.Class
38−import Control.Monad.State
39−import Data.ByteString (ByteString)
40−import Data.Default
41−import Data.IORef
42−import Data.Maybe (isJust)
43−import Data.Text
44−
45−data WebSocketConfig t
46− = WebSocketConfig { _webSocketConfig_send :: Event t [ByteString]
47− }
48−
49−instance Reflex t => Default (WebSocketConfig t) where
50− def = WebSocketConfig never
51−
52−data WebSocket t
53− = WebSocket { _webSocket_recv :: Event t ByteString
54− , _webSocket_open :: Event t ()
55− }
56−
57−webSocket :: (MonadIO m, MonadIO (Performable m), HasWebView m, PerformEvent t m, TriggerEvent t m, PostBuild t m) => Text -> WebSocketConfig t -> m (WebSocket t)
58−webSocket url config = do
59− wv <- fmap unWebViewSingleton askWebView
60− (eRecv, onMessage) <- newTriggerEvent
61− currentSocketRef <- liftIO $ newIORef Nothing
62− --TODO: Disconnect if value no longer needed
63− (eOpen, triggerEOpen) <- newTriggerEventWithOnComplete
64− payloadQueue <- liftIO newTQueueIO
65− isOpen <- liftIO newEmptyTMVarIO
66− let onOpen = triggerEOpen () $ do
67− liftIO $ void $ atomically $ tryPutTMVar isOpen ()
68− --TODO: Is the fork necessary, or do event handlers run in their own threads automatically?
69− onClose = void $ forkIO $ do
70− _ <- liftIO $ atomically $ tryTakeTMVar isOpen
71− liftIO $ writeIORef currentSocketRef Nothing
72− liftIO $ threadDelay 1000000
73− start
74− start = do
75− ws <- liftIO $ newWebSocket wv url onMessage onOpen onClose
76− liftIO $ writeIORef currentSocketRef $ Just ws
77− return ()
78− performEvent_ . (liftIO start <$) =<< getPostBuild
79− performEvent_ $ ffor (_webSocketConfig_send config) $ \payloads -> forM_ payloads $ \payload ->
80− liftIO $ atomically $ writeTQueue payloadQueue payload
81−
82− _ <- liftIO $ forkIO $ forever $ do
83− payload <- atomically $ do
84− pl <- readTQueue payloadQueue
85− open <- tryReadTMVar isOpen
86− if isJust open then return pl else retry
87−
88− mws <- liftIO $ readIORef currentSocketRef
89− success <- case mws of
90− Nothing -> return False
91− Just ws -> liftIO ((webSocketSend ws payload >> return True)
92− `catch`
93− (\(_ :: SomeException) -> return False))
94− unless success $ atomically $ unGetTQueue payloadQueue payload
95− return $ WebSocket eRecv eOpen
96−
97−makeLensesWith (lensRules & simpleLenses .~ True) ''WebSocketConfig
src/Reflex/Dom/Widget/Basic.hsdeleted−421
@@ -1,421 +0,0 @@
1−{-# LANGUAGE ConstraintKinds #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE LambdaCase #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE OverloadedStrings #-}
9−{-# LANGUAGE RankNTypes #-}
10−{-# LANGUAGE RecursiveDo #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeFamilies #-}
13−module Reflex.Dom.Widget.Basic where
14−
15−import Reflex.Dom.Builder.Class
16−import Reflex.Dom.Class
17−import Reflex.Dom.Internal.Foreign ()
18−import Reflex.Dom.PostBuild.Class
19−
20−import Control.Arrow
21−import Control.Lens hiding (children, element)
22−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence, sequence_)
23−import Data.Align
24−import Data.Default
25−import Data.Either
26−import Data.Foldable
27−import Data.Functor.Misc
28−import Data.Map (Map)
29−import qualified Data.Map as Map
30−import Data.Maybe
31−import Data.Semigroup
32−import Data.Set (Set)
33−import qualified Data.Set as Set
34−import Data.Text (Text)
35−import qualified Data.Text as T
36−import Data.These
37−import Data.Traversable
38−import Prelude hiding (mapM, mapM_, sequence, sequence_)
39−import Reflex
40−
41−widgetHoldInternal :: DomBuilder t m => m a -> Event t (m b) -> m (a, Event t b)
42−widgetHoldInternal child0 child' = do
43− childResult0 <- deletable (void child') child0
44− childResult' <- placeholder $ def & placeholderConfig_insertAbove .~ fmap (deletable (void child')) child'
45− return (childResult0, _placeholder_insertedAbove childResult')
46−
47−-- | Breaks the given Map into pieces based on the given Set. Each piece will contain only keys that are less than the key of the piece, and greater than or equal to the key of the piece with the next-smaller key. There will be one additional piece containing all keys from the original Map that are larger or equal to the largest key in the Set.
48−-- Either k () is used instead of Maybe k so that the resulting map of pieces is sorted so that the additional piece has the largest key.
49−-- No empty pieces will be included in the output.
50−
51−--TODO: This can probably be done more efficiently by dividing and conquering, re-using the structure of the Set instead of going through the Set linearally
52−partitionMapBySetLT :: forall k v. Ord k => Set k -> Map k v -> Map (Either k ()) (Map k v)
53−partitionMapBySetLT s m0 = Map.fromDistinctAscList $ go (Set.toAscList s) m0
54− where go :: [k] -> Map k v -> [(Either k (), Map k v)]
55− go [] m = if Map.null m
56− then []
57− else [(Right (), m)]
58− go (h:t) m = let (lt, eq, gt) = Map.splitLookup h m
59− geq = maybe id (Map.insert h) eq gt
60− in if Map.null lt
61− then go t geq
62− else (Left h, lt) : go t geq
63−
64−newtype ChildResult t k a = ChildResult { unChildResult :: (a, Event t (Map k (Maybe (ChildResult t k a)))) }
65−
66−listHoldWithKey :: forall t m k v a. (Ord k, DomBuilder t m, MonadHold t m, MonadFix m) => Map k v -> Event t (Map k (Maybe v)) -> (k -> v -> m a) -> m (Dynamic t (Map k a))
67−listHoldWithKey initialChildren modifyChildren buildChild = do
68− let deleteChildSelector = fanMap $ fmap void modifyChildren
69− liveChildren :: Dynamic t (Set k) <- foldDyn applyMapKeysSet (Map.keysSet initialChildren) modifyChildren
70− let placeChildSelector = fanMap $ attachWith partitionMapBySetLT (current liveChildren) $ fmap (Map.mapMaybe id) modifyChildren
71− buildAugmentedChild :: k -> v -> m (ChildResult t k a)
72− buildAugmentedChild k v = do
73− let delete = select deleteChildSelector $ Const2 k
74− myCfg = def
75− & insertAbove .~ fmap (imapM buildAugmentedChild) (select placeChildSelector $ Const2 $ Left k)
76− & deleteSelf .~ delete
77− ph <- placeholder myCfg
78− result <- deletable delete $ buildChild k v
79− return $ ChildResult (result, (fmap Just <$> _placeholder_insertedAbove ph) <> (Map.singleton k Nothing <$ _placeholder_deletedSelf ph)) --Note: we could also use the "deleted" output on deletable, if it had one; we're using this so that everything changes all at once, instead of deletions being prompt and insertions being delayed
80− rec initialAugmentedResults <- iforM initialChildren buildAugmentedChild
81− augmentedResults <- foldDyn applyMap initialAugmentedResults $ newInsertedBelow <> newInsertedAbove
82− let newInsertedAbove = switch $ mconcat . reverse . fmap (snd . unChildResult) . Map.elems <$> current augmentedResults
83− belowAll <- placeholder $ def & placeholderConfig_insertAbove .~ fmap (imapM buildAugmentedChild) (select placeChildSelector $ Const2 $ Right ())
84− let newInsertedBelow = fmap Just <$> _placeholder_insertedAbove belowAll
85− return $ fmap (fmap (fst . unChildResult)) augmentedResults
86−
87−text :: DomBuilder t m => Text -> m ()
88−text t = void $ textNode $ def & textNodeConfig_initialContents .~ t
89−
90−dynText :: forall t m. (PostBuild t m, DomBuilder t m) => Dynamic t Text -> m ()
91−dynText t = do
92− postBuild <- getPostBuild
93− void $ textNode $ (def :: TextNodeConfig t) & textNodeConfig_setContents .~ leftmost
94− [ updated t
95− , tag (current t) postBuild
96− ]
97−
98−display :: (PostBuild t m, DomBuilder t m, Show a) => Dynamic t a -> m ()
99−display = dynText . fmap (T.pack . show)
100−
101−button :: DomBuilder t m => Text -> m (Event t ())
102−button t = do
103− (e, _) <- element "button" def $ text t
104− return $ domEvent Click e
105−
106−--TODO: Should this be renamed to 'widgetView' for consistency with 'widgetHold'?
107−-- | Given a Dynamic of widget-creating actions, create a widget that is recreated whenever the Dynamic updates.
108−-- The returned Event of widget results occurs when the Dynamic does.
109−-- Note: Often, the type 'a' is an Event, in which case the return value is an Event-of-Events that would typically be flattened (via 'switchPromptly').
110−dyn :: (DomBuilder t m, PostBuild t m) => Dynamic t (m a) -> m (Event t a)
111−dyn child = do
112− postBuild <- getPostBuild
113− let newChild = leftmost [updated child, tag (current child) postBuild]
114− snd <$> widgetHoldInternal (return ()) newChild
115−
116−-- | Given an initial widget and an Event of widget-creating actions, create a widget that is recreated whenever the Event fires.
117−-- The returned Dynamic of widget results occurs when the Event does.
118−-- Note: Often, the type 'a' is an Event, in which case the return value is a Dynamic-of-Events that would typically be flattened.
119−widgetHold :: (DomBuilder t m, MonadHold t m) => m a -> Event t (m a) -> m (Dynamic t a)
120−widgetHold child0 newChild = do
121− (result0, newResult) <- widgetHoldInternal child0 newChild
122− holdDyn result0 newResult
123−
124−diffMapNoEq :: (Ord k) => Map k v -> Map k v -> Map k (Maybe v)
125−diffMapNoEq olds news = flip Map.mapMaybe (align olds news) $ \case
126− This _ -> Just Nothing
127− These _ new -> Just $ Just new
128− That new -> Just $ Just new
129−
130−diffMap :: (Ord k, Eq v) => Map k v -> Map k v -> Map k (Maybe v)
131−diffMap olds news = flip Map.mapMaybe (align olds news) $ \case
132− This _ -> Just Nothing
133− These old new
134− | old == new -> Nothing
135− | otherwise -> Just $ Just new
136− That new -> Just $ Just new
137−
138−applyMap :: Ord k => Map k (Maybe v) -> Map k v -> Map k v
139−applyMap patch old = insertions `Map.union` (old `Map.difference` deletions)
140− where (deletions, insertions) = mapPartitionEithers $ maybeToEither <$> patch
141− maybeToEither = \case
142− Nothing -> Left ()
143− Just r -> Right r
144−
145−mapPartitionEithers :: Map k (Either a b) -> (Map k a, Map k b)
146−mapPartitionEithers m = (fromLeft <$> ls, fromRight <$> rs)
147− where (ls, rs) = Map.partition isLeft m
148− fromLeft (Left l) = l
149− fromLeft _ = error "mapPartitionEithers: fromLeft received a Right value; this should be impossible"
150− fromRight (Right r) = r
151− fromRight _ = error "mapPartitionEithers: fromRight received a Left value; this should be impossible"
152−
153−-- | Apply a map patch to a set
154−-- > applyMapKeysSet patch (Map.keysSet m) == Map.keysSet (applyMap patch m)
155−applyMapKeysSet :: Ord k => Map k (Maybe v) -> Set k -> Set k
156−applyMapKeysSet patch old = Map.keysSet insertions `Set.union` (old `Set.difference` Map.keysSet deletions)
157− where (insertions, deletions) = Map.partition isJust patch
158−
159−--TODO: Something better than Dynamic t (Map k v) - we want something where the Events carry diffs, not the whole value
160−listWithKey :: forall t k v m a. (Ord k, DomBuilder t m, PostBuild t m, MonadFix m, MonadHold t m) => Dynamic t (Map k v) -> (k -> Dynamic t v -> m a) -> m (Dynamic t (Map k a))
161−listWithKey vals mkChild = do
162− postBuild <- getPostBuild
163− rec sentVals :: Dynamic t (Map k v) <- foldDyn applyMap Map.empty changeVals
164− let changeVals :: Event t (Map k (Maybe v))
165− changeVals = attachWith diffMapNoEq (current sentVals) $ leftmost
166− [ updated vals
167− , tag (current vals) postBuild --TODO: This should probably be added to the attachWith, not to the updated; if we were using diffMap instead of diffMapNoEq, I think it might not work
168− ]
169− listWithKeyShallowDiff Map.empty changeVals $ \k v0 dv -> do
170− mkChild k =<< holdDyn v0 dv
171−
172−{-# DEPRECATED listWithKey' "listWithKey' has been renamed to listWithKeyShallowDiff; also, its behavior has changed to fix a bug where children were always rebuilt (never updated)" #-}
173−listWithKey' :: (Ord k, DomBuilder t m, MonadFix m, MonadHold t m) => Map k v -> Event t (Map k (Maybe v)) -> (k -> v -> Event t v -> m a) -> m (Dynamic t (Map k a))
174−listWithKey' = listWithKeyShallowDiff
175−
176−-- | Display the given map of items (in key order) using the builder function provided, and update it with the given event. 'Nothing' update entries will delete the corresponding children, and 'Just' entries will create them if they do not exist or send an update event to them if they do.
177−listWithKeyShallowDiff :: (Ord k, DomBuilder t m, MonadFix m, MonadHold t m) => Map k v -> Event t (Map k (Maybe v)) -> (k -> v -> Event t v -> m a) -> m (Dynamic t (Map k a))
178−listWithKeyShallowDiff initialVals valsChanged mkChild = do
179− let childValChangedSelector = fanMap $ fmap (Map.mapMaybe id) valsChanged
180− sentVals <- foldDyn applyMap Map.empty $ fmap (fmap void) valsChanged
181− let relevantPatch patch _ = case patch of
182− Nothing -> Just Nothing -- Even if we let a Nothing through when the element doesn't already exist, this doesn't cause a problem because it is ignored
183− Just _ -> Nothing -- We don't want to let spurious re-creations of items through
184− listHoldWithKey initialVals (attachWith (flip (Map.differenceWith relevantPatch)) (current sentVals) valsChanged) $ \k v ->
185− mkChild k v $ Reflex.select childValChangedSelector $ Const2 k
186−
187−--TODO: Something better than Dynamic t (Map k v) - we want something where the Events carry diffs, not the whole value
188−-- | Create a dynamically-changing set of Event-valued widgets.
189−-- This is like listWithKey, specialized for widgets returning (Event t a). listWithKey would return 'Dynamic t (Map k (Event t a))' in this scenario, but listViewWithKey flattens this to 'Event t (Map k a)' via 'switch'.
190−listViewWithKey :: (Ord k, DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => Dynamic t (Map k v) -> (k -> Dynamic t v -> m (Event t a)) -> m (Event t (Map k a))
191−listViewWithKey vals mkChild = switch . fmap mergeMap <$> listViewWithKey' vals mkChild
192−
193−listViewWithKey' :: (Ord k, DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => Dynamic t (Map k v) -> (k -> Dynamic t v -> m a) -> m (Behavior t (Map k a))
194−listViewWithKey' vals mkChild = current <$> listWithKey vals mkChild
195−
196−-- | Create a dynamically-changing set of widgets, one of which is selected at any time.
197−selectViewListWithKey :: forall t m k v a. (DomBuilder t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
198− => Dynamic t k -- ^ Current selection key
199− -> Dynamic t (Map k v) -- ^ Dynamic key/value map
200− -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a)) -- ^ Function to create a widget for a given key from Dynamic value and Dynamic Bool indicating if this widget is currently selected
201− -> m (Event t (k, a)) -- ^ Event that fires when any child's return Event fires. Contains key of an arbitrary firing widget.
202−selectViewListWithKey selection vals mkChild = do
203− let selectionDemux = demux selection -- For good performance, this value must be shared across all children
204− selectChild <- listWithKey vals $ \k v -> do
205− let selected = demuxed selectionDemux k
206− selectSelf <- mkChild k v selected
207− return $ fmap ((,) k) selectSelf
208− return $ switchPromptlyDyn $ leftmost . Map.elems <$> selectChild
209−
210−selectViewListWithKey_ :: forall t m k v a. (DomBuilder t m, Ord k, PostBuild t m, MonadHold t m, MonadFix m)
211− => Dynamic t k -- ^ Current selection key
212− -> Dynamic t (Map k v) -- ^ Dynamic key/value map
213− -> (k -> Dynamic t v -> Dynamic t Bool -> m (Event t a)) -- ^ Function to create a widget for a given key from Dynamic value and Dynamic Bool indicating if this widget is currently selected
214− -> m (Event t k) -- ^ Event that fires when any child's return Event fires. Contains key of an arbitrary firing widget.
215−selectViewListWithKey_ selection vals mkChild = fmap fst <$> selectViewListWithKey selection vals mkChild
216−
217−{-
218−{-# INLINABLE elWith #-}
219−elWith :: (DomBuilder t m, Attributes m attrs) => Text -> ElConfig attrs -> m a -> m a
220−elWith elementTag cfg child = do
221− (_, result) <- buildElementNS (cfg ^. namespace) elementTag (cfg ^. attributes) child
222− return result
223−
224−{-# INLINABLE elWith' #-}
225−elWith' :: (DomBuilder t m, Attributes m attrs) => Text -> ElConfig attrs -> m a -> m (El t, a)
226−elWith' elementTag cfg child = do
227− (e, result) <- buildElementNS (cfg ^. namespace) elementTag (cfg ^. attributes) child
228− e' <- wrapElement defaultDomEventHandler e
229− return (e', result)
230−
231−{-# INLINABLE emptyElWith #-}
232−emptyElWith :: (DomBuilder t m, Attributes m attrs) => Text -> ElConfig attrs -> m ()
233−emptyElWith elementTag cfg = do
234− _ <- buildEmptyElementNS (cfg ^. namespace) elementTag (cfg ^. attributes)
235− return ()
236−
237−{-# INLINABLE emptyElWith' #-}
238−emptyElWith' :: (DomBuilder t m, Attributes m attrs) => Text -> ElConfig attrs -> m (El t)
239−emptyElWith' elementTag cfg = do
240− wrapElement defaultDomEventHandler =<< buildEmptyElementNS (cfg ^. namespace) elementTag (cfg ^. attributes)
241−-}
242−
243−{-# INLINABLE el #-}
244−el :: forall t m a. DomBuilder t m => Text -> m a -> m a
245−el elementTag child = snd <$> el' elementTag child
246−
247−{-# INLINABLE elAttr #-}
248−elAttr :: forall t m a. DomBuilder t m => Text -> Map Text Text -> m a -> m a
249−elAttr elementTag attrs child = snd <$> elAttr' elementTag attrs child
250−
251−{-# INLINABLE elClass #-}
252−elClass :: forall t m a. DomBuilder t m => Text -> Text -> m a -> m a
253−elClass elementTag c child = snd <$> elClass' elementTag c child
254−
255−{-# INLINABLE elDynAttr #-}
256−elDynAttr :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t (Map Text Text) -> m a -> m a
257−elDynAttr elementTag attrs child = snd <$> elDynAttr' elementTag attrs child
258−
259−{-# INLINABLE elDynClass #-}
260−elDynClass :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t Text -> m a -> m a
261−elDynClass elementTag c child = snd <$> elDynClass' elementTag c child
262−
263−{-# INLINABLE el' #-}
264−el' :: forall t m a. DomBuilder t m => Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
265−el' elementTag = element elementTag def
266−
267−{-# INLINABLE elAttr' #-}
268−elAttr' :: forall t m a. DomBuilder t m => Text -> Map Text Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
269−elAttr' elementTag attrs = element elementTag $ def
270− & initialAttributes .~ Map.mapKeys (\k -> (Nothing, k)) attrs
271−
272−{-# INLINABLE elClass' #-}
273−elClass' :: forall t m a. DomBuilder t m => Text -> Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
274−elClass' elementTag c = elAttr' elementTag ("class" =: c)
275−
276−{-# INLINABLE elDynAttr' #-}
277−elDynAttr' :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t (Map Text Text) -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
278−elDynAttr' = elDynAttrNS' Nothing
279−
280−{-# INLINABLE elDynClass' #-}
281−elDynClass' :: forall t m a. (DomBuilder t m, PostBuild t m) => Text -> Dynamic t Text -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
282−elDynClass' elementTag c = elDynAttr' elementTag (fmap ("class" =:) c)
283−
284−{-# INLINABLE elDynAttrNS' #-}
285−elDynAttrNS' :: forall t m a. (DomBuilder t m, PostBuild t m) => Maybe Text -> Text -> Dynamic t (Map Text Text) -> m a -> m (Element EventResult (DomBuilderSpace m) t, a)
286−elDynAttrNS' mns elementTag attrs child = do
287− modifyAttrs <- dynamicAttributesToModifyAttributes attrs
288− let cfg = def
289− & elementConfig_namespace .~ mns
290− & modifyAttributes .~ modifyAttrs
291− element elementTag cfg child
292−
293−dynamicAttributesToModifyAttributes :: PostBuild t m => Dynamic t (Map Text Text) -> m (Event t (Map AttributeName (Maybe Text)))
294−dynamicAttributesToModifyAttributes d = do
295− postBuild <- getPostBuild
296− let modificationsNeeded = flip pushAlways (align postBuild $ updated d) $ \case
297− This () -> fmap (fmap Just) $ sample $ current d
298− These () new -> return $ fmap Just new
299− That new -> do
300− old <- sample $ current d
301− return $ diffMap old new
302− return $ Map.fromList . fmap (\(k, v) -> ((Nothing, k), v)) . Map.toList <$> modificationsNeeded
303−
304−--------------------------------------------------------------------------------
305−-- Copied and pasted from Reflex.Widget.Class
306−--------------------------------------------------------------------------------
307−
308−-- | Create a dynamically-changing set of widgets from a Dynamic key/value map.
309−-- Unlike the 'withKey' variants, the child widgets are insensitive to which key they're associated with.
310−list :: (Ord k, DomBuilder t m, MonadHold t m, PostBuild t m, MonadFix m) => Dynamic t (Map k v) -> (Dynamic t v -> m a) -> m (Dynamic t (Map k a))
311−list dm mkChild = listWithKey dm (\_ dv -> mkChild dv)
312−
313−-- | Create a dynamically-changing set of widgets from a Dynamic list.
314−simpleList :: (DomBuilder t m, MonadHold t m, PostBuild t m, MonadFix m) => Dynamic t [v] -> (Dynamic t v -> m a) -> m (Dynamic t [a])
315−simpleList xs mkChild = fmap (fmap (map snd . Map.toList)) $ flip list mkChild $ fmap (Map.fromList . zip [(1::Int)..]) xs
316−
317−{-
318−schedulePostBuild x = performEvent_ . (x <$) =<< getPostBuild
319−
320−elDynHtml' :: DomBuilder t m => Text -> Dynamic t Text -> m (El t)
321−elDynHtml' elementTag html = do
322− e <- buildEmptyElement elementTag (Map.empty :: Map Text Text)
323− schedulePostBuild $ setInnerHTML e . Just =<< sample (current html)
324− performEvent_ $ fmap (setInnerHTML e . Just) $ updated html
325− wrapElement defaultDomEventHandler e
326−
327−elDynHtmlAttr' :: DomBuilder t m => Text -> Map Text Text -> Dynamic t Text -> m (El t)
328−elDynHtmlAttr' elementTag attrs html = do
329− e <- buildEmptyElement elementTag attrs
330− schedulePostBuild $ setInnerHTML e . Just =<< sample (current html)
331− performEvent_ $ fmap (setInnerHTML e . Just) $ updated html
332− wrapElement defaultDomEventHandler e
333−-}
334−
335−data Link t
336− = Link { _link_clicked :: Event t ()
337− }
338−
339−linkClass :: DomBuilder t m => Text -> Text -> m (Link t)
340−linkClass s c = do
341− (l,_) <- elAttr' "a" ("class" =: c) $ text s
342− return $ Link $ domEvent Click l
343−
344−link :: DomBuilder t m => Text -> m (Link t)
345−link s = linkClass s ""
346−
347−newtype Workflow t m a = Workflow { unWorkflow :: m (a, Event t (Workflow t m a)) }
348−
349−workflow :: forall t m a. (DomBuilder t m, MonadFix m, MonadHold t m) => Workflow t m a -> m (Dynamic t a)
350−workflow w0 = do
351− rec eResult <- widgetHold (unWorkflow w0) $ fmap unWorkflow $ switch $ snd <$> current eResult
352− return $ fmap fst eResult
353−
354−workflowView :: forall t m a. (DomBuilder t m, MonadFix m, MonadHold t m, PostBuild t m) => Workflow t m a -> m (Event t a)
355−workflowView w0 = do
356− rec eResult <- dyn . fmap unWorkflow =<< holdDyn w0 eReplace
357− eReplace <- fmap switch $ hold never $ fmap snd eResult
358− return $ fmap fst eResult
359−
360−mapWorkflow :: (DomBuilder t m) => (a -> b) -> Workflow t m a -> Workflow t m b
361−mapWorkflow f (Workflow x) = Workflow (fmap (f *** fmap (mapWorkflow f)) x)
362−
363−divClass :: forall t m a. DomBuilder t m => Text -> m a -> m a
364−divClass = elClass "div"
365−
366−dtdd :: forall t m a. DomBuilder t m => Text -> m a -> m a
367−dtdd h w = do
368− el "dt" $ text h
369− el "dd" w
370−
371−blank :: forall m. Monad m => m ()
372−blank = return ()
373−
374−-- | A widget to display a table with static columns and dynamic rows.
375−tableDynAttr :: forall t m r k v. (Ord k, DomBuilder t m, MonadHold t m, PostBuild t m, MonadFix m)
376− => Text -- ^ Class applied to <table> element
377− -> [(Text, k -> Dynamic t r -> m v)] -- ^ Columns of (header, row key -> row value -> child widget)
378− -> Dynamic t (Map k r) -- ^ Map from row key to row value
379− -> (k -> m (Dynamic t (Map Text Text))) -- ^ Function to compute <tr> element attributes from row key
380− -> m (Dynamic t (Map k (Element EventResult (DomBuilderSpace m) t, [v]))) -- ^ Map from row key to (El, list of widget return values)
381−tableDynAttr klass cols dRows rowAttrs = elAttr "div" (Map.singleton "style" "zoom: 1; overflow: auto; background: white;") $ do
382− elAttr "table" (Map.singleton "class" klass) $ do
383− el "thead" $ el "tr" $ do
384− mapM_ (\(h, _) -> el "th" $ text h) cols
385− el "tbody" $ do
386− listWithKey dRows (\k r -> do
387− dAttrs <- rowAttrs k
388− elDynAttr' "tr" dAttrs $ mapM (\x -> el "td" $ snd x k r) cols)
389−
390−--TODO preselect a tab on open
391−-- | A widget to construct a tabbed view that shows only one of its child widgets at a time.
392−-- Creates a header bar containing a <ul> with one <li> per child; clicking a <li> displays
393−-- the corresponding child and hides all others.
394−tabDisplay :: forall t m k. (MonadFix m, DomBuilder t m, MonadHold t m, PostBuild t m, Ord k)
395− => Text -- ^ Class applied to <ul> element
396− -> Text -- ^ Class applied to currently active <li> element
397− -> Map k (Text, m ()) -- ^ Map from (arbitrary) key to (tab label, child widget)
398− -> m ()
399−tabDisplay ulClass activeClass tabItems = do
400− let t0 = listToMaybe $ Map.keys tabItems
401− rec currentTab :: Demux t (Maybe k) <- elAttr "ul" ("class" =: ulClass) $ do
402− tabClicksList :: [Event t k] <- Map.elems <$> imapM (\k (s,_) -> headerBarLink s k $ demuxed currentTab (Just k)) tabItems
403− let eTabClicks :: Event t k = leftmost tabClicksList
404− fmap demux $ holdDyn t0 $ fmap Just eTabClicks
405− el "div" $ do
406− iforM_ tabItems $ \k (_, w) -> do
407− let isSelected = demuxed currentTab $ Just k
408− attrs = ffor isSelected $ \s -> if s then Map.empty else Map.singleton "style" "display:none;"
409− elDynAttr "div" attrs w
410− return ()
411− where
412− headerBarLink :: Text -> k -> Dynamic t Bool -> m (Event t k)
413− headerBarLink x k isSelected = do
414− let attrs = fmap (\b -> if b then Map.singleton "class" activeClass else Map.empty) isSelected
415− elDynAttr "li" attrs $ do
416− a <- link x
417− return $ fmap (const k) (_link_clicked a)
418−
419−class HasAttributes a where
420− type Attrs a :: *
421− attributes :: Lens' a (Attrs a)
src/Reflex/Dom/Xhr.hsdeleted−272
@@ -1,272 +0,0 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−{-# LANGUAGE DeriveFunctor #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE GADTs #-}
5−{-# LANGUAGE MultiParamTypeClasses #-}
6−{-# LANGUAGE OverloadedStrings #-}
7−{-# LANGUAGE TemplateHaskell #-}
8−module Reflex.Dom.Xhr
9− ( XMLHttpRequest
10− , XhrRequest (..)
11− , XhrRequestConfig (..)
12− , XhrResponse (..)
13− , XhrResponseBody (..)
14− , XhrResponseType (..)
15− , XhrException (..)
16− , IsXhrPayload (..)
17− , _xhrResponse_body
18− , decodeText
19− , decodeXhrResponse
20− , getAndDecode
21− , getMay
22− , newXMLHttpRequest
23− , newXMLHttpRequestWithError
24− , performMkRequestAsync
25− , performMkRequestsAsync
26− , performRequestAsync
27− , performRequestAsyncWithError
28− , performRequestsAsync
29− , performRequestsAsyncWithError
30− , postJson
31− , xhrRequest
32− , xhrRequestConfig_headers
33− , xhrRequestConfig_password
34− , xhrRequestConfig_responseType
35− , xhrRequestConfig_sendData
36− , xhrRequestConfig_user
37− , xhrRequestConfig_withCredentials
38− , xhrRequest_config
39− , xhrRequest_method
40− , xhrRequest_url
41− , xhrResponse_body
42− , xhrResponse_response
43− , xhrResponse_responseText
44− , xhrResponse_status
45− , xhrResponse_statusText
46− , xmlHttpRequestGetReadyState
47− , xmlHttpRequestGetResponseText
48− , xmlHttpRequestGetStatus
49− , xmlHttpRequestGetStatusText
50− , xmlHttpRequestNew
51− , xmlHttpRequestOnreadystatechange
52− , xmlHttpRequestOpen
53− , xmlHttpRequestSetRequestHeader
54− , xmlHttpRequestSetResponseType
55− )
56−where
57−
58−import Reflex
59−import Reflex.Dom.Class
60−import Reflex.Dom.PerformEvent.Class
61−import Reflex.Dom.Xhr.Exception
62−import Reflex.Dom.Xhr.Foreign
63−import Reflex.Dom.Xhr.ResponseType
64−
65−import Control.Concurrent
66−import Control.Exception (handle)
67−import Control.Lens
68−import Control.Monad hiding (forM)
69−import Control.Monad.IO.Class
70−import Data.Aeson
71−import Data.Aeson.Encode
72−import qualified Data.ByteString.Lazy as BL
73−import Data.Default
74−import Data.Map (Map)
75−import qualified Data.Map as Map
76−import Data.Maybe
77−import Data.Text (Text)
78−import Data.Text.Encoding
79−import qualified Data.Text.Lazy as LT
80−import qualified Data.Text.Lazy.Builder as B
81−import Data.Traversable
82−import Data.Typeable
83−
84−data XhrRequest a
85− = XhrRequest { _xhrRequest_method :: Text
86− , _xhrRequest_url :: Text
87− , _xhrRequest_config :: XhrRequestConfig a
88− }
89− deriving (Show, Read, Eq, Ord, Typeable, Functor)
90−
91−data XhrRequestConfig a
92− = XhrRequestConfig { _xhrRequestConfig_headers :: Map Text Text
93− , _xhrRequestConfig_user :: Maybe Text
94− , _xhrRequestConfig_password :: Maybe Text
95− , _xhrRequestConfig_responseType :: Maybe XhrResponseType
96− , _xhrRequestConfig_sendData :: a
97− , _xhrRequestConfig_withCredentials :: Bool
98− }
99− deriving (Show, Read, Eq, Ord, Typeable, Functor)
100−
101−data XhrResponse
102− = XhrResponse { _xhrResponse_status :: Word
103− , _xhrResponse_statusText :: Text
104− , _xhrResponse_response :: Maybe XhrResponseBody
105− , _xhrResponse_responseText :: Maybe Text
106− }
107− deriving (Typeable)
108−
109−{-# DEPRECATED _xhrResponse_body "Use _xhrResponse_response or _xhrResponse_responseText instead." #-}
110−_xhrResponse_body :: XhrResponse -> Maybe Text
111−_xhrResponse_body = _xhrResponse_responseText
112−
113−{-# DEPRECATED xhrResponse_body "Use xhrResponse_response or xhrResponse_responseText instead." #-}
114−xhrResponse_body :: Lens XhrResponse XhrResponse (Maybe Text) (Maybe Text)
115−xhrResponse_body = lens _xhrResponse_responseText (\r t -> r { _xhrResponse_responseText = t })
116−
117−instance a ~ () => Default (XhrRequestConfig a) where
118− def = XhrRequestConfig { _xhrRequestConfig_headers = Map.empty
119− , _xhrRequestConfig_user = Nothing
120− , _xhrRequestConfig_password = Nothing
121− , _xhrRequestConfig_responseType = Nothing
122− , _xhrRequestConfig_sendData = ()
123− , _xhrRequestConfig_withCredentials = False
124− }
125−
126−-- | Construct a request object from method, URL, and config record.
127−xhrRequest :: Text -> Text -> XhrRequestConfig a -> XhrRequest a
128−xhrRequest = XhrRequest
129−
130−-- | Make a new asyncronous XHR request. This does not block (it forks),
131−-- and returns an XHR object immediately (which you can use to abort
132−-- the XHR connection), and will pass an exception ('XhrException') to the
133−-- continuation if the connection cannot be made (or is aborted).
134−newXMLHttpRequestWithError
135− :: (HasWebView m, MonadIO m, IsXhrPayload a)
136− => XhrRequest a
137− -- ^ The request to make.
138− -> (Either XhrException XhrResponse -> IO ())
139− -- ^ A continuation to be called once a response comes back, or in
140− -- case of error.
141− -> m XMLHttpRequest
142− -- ^ The XHR request, which could for example be aborted.
143−newXMLHttpRequestWithError req cb = do
144− wv <- askWebView
145− xhr <- liftIO $ xmlHttpRequestNew $ unWebViewSingleton wv
146− void $ liftIO $ forkIO $ handle (cb . Left) $ void $ do
147− let c = _xhrRequest_config req
148− rt = _xhrRequestConfig_responseType c
149− creds = _xhrRequestConfig_withCredentials c
150− xmlHttpRequestOpen
151− xhr
152− (_xhrRequest_method req)
153− (_xhrRequest_url req)
154− True
155− (fromMaybe "" $ _xhrRequestConfig_user c)
156− (fromMaybe "" $ _xhrRequestConfig_password c)
157− iforM_ (_xhrRequestConfig_headers c) $ xmlHttpRequestSetRequestHeader xhr
158− maybe (return ()) (xmlHttpRequestSetResponseType xhr . fromResponseType) rt
159− xmlHttpRequestSetWithCredentials xhr creds
160− _ <- xmlHttpRequestOnreadystatechange xhr $ do
161− readyState <- liftIO $ xmlHttpRequestGetReadyState xhr
162− status <- liftIO $ xmlHttpRequestGetStatus xhr
163− statusText <- liftIO $ xmlHttpRequestGetStatusText xhr
164− when (readyState == 4) $ do
165− t <- if rt == Just XhrResponseType_Text || isNothing rt
166− then liftIO $ xmlHttpRequestGetResponseText xhr
167− else return Nothing
168− r <- liftIO $ xmlHttpRequestGetResponse xhr
169− _ <- liftIO $ cb $ Right $ XhrResponse
170− { _xhrResponse_status = status
171− , _xhrResponse_statusText = statusText
172− , _xhrResponse_response = r
173− , _xhrResponse_responseText = t
174− }
175− return ()
176− _ <- xmlHttpRequestSend xhr (_xhrRequestConfig_sendData c)
177− return ()
178− return xhr
179−
180−newXMLHttpRequest :: (HasWebView m, MonadIO m, IsXhrPayload a) => XhrRequest a -> (XhrResponse -> IO ()) -> m XMLHttpRequest
181−newXMLHttpRequest req cb = newXMLHttpRequestWithError req $ mapM_ cb
182−
183−-- | Given Event of requests, issue them when the Event fires.
184−-- Returns Event of corresponding responses.
185−--
186−-- The request is processed asynchronously, therefore handling does
187−-- not block or cause a delay while creating the connection.
188−performRequestAsyncWithError
189− :: (MonadIO (Performable m), HasWebView (Performable m), PerformEvent t m, TriggerEvent t m, IsXhrPayload a)
190− => Event t (XhrRequest a)
191− -> m (Event t (Either XhrException XhrResponse))
192−performRequestAsyncWithError = performRequestAsync' newXMLHttpRequestWithError . fmap return
193−
194−-- | Given Event of request, issue them when the Event fires. Returns Event of corresponding response.
195−performRequestAsync :: (MonadIO (Performable m), HasWebView (Performable m), PerformEvent t m, TriggerEvent t m, IsXhrPayload a) => Event t (XhrRequest a) -> m (Event t XhrResponse)
196−performRequestAsync = performRequestAsync' newXMLHttpRequest . fmap return
197−
198−-- | Given Event with an action that creates a request, build and issue the request when the Event fires. Returns Event of corresponding response.
199−performMkRequestAsync :: (MonadIO (Performable m), HasWebView (Performable m), PerformEvent t m, TriggerEvent t m, IsXhrPayload a) => Event t (Performable m (XhrRequest a)) -> m (Event t XhrResponse)
200−performMkRequestAsync = performRequestAsync' newXMLHttpRequest
201−
202−performRequestAsync' :: (MonadIO (Performable m), PerformEvent t m, TriggerEvent t m) => (XhrRequest p -> (a -> IO ()) -> Performable m XMLHttpRequest) -> Event t (Performable m (XhrRequest p)) -> m (Event t a)
203−performRequestAsync' newXhr req = performEventAsync $ ffor req $ \hr cb -> do
204− r <- hr
205− _ <- newXhr r $ liftIO . cb
206− return ()
207−
208−-- | Issues a collection of requests when the supplied Event fires.
209−-- When ALL requests from a given firing complete, the results are
210−-- collected and returned via the return Event.
211−--
212−-- The requests are processed asynchronously, therefore handling does
213−-- not block or cause a delay while creating the connection.
214−--
215−-- Order of request execution and completion is not guaranteed, but
216−-- order of creation and the collection result is preserved.
217−performRequestsAsyncWithError
218− :: (MonadIO (Performable m), HasWebView (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f, IsXhrPayload a)
219− => Event t (f (XhrRequest a)) -> m (Event t (f (Either XhrException XhrResponse)))
220−performRequestsAsyncWithError = performRequestsAsync' newXMLHttpRequestWithError . fmap return
221−
222−-- | Issues a collection of requests when the supplied Event fires. When ALL requests from a given firing complete, the results are collected and returned via the return Event.
223−performRequestsAsync :: (MonadIO (Performable m), HasWebView (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f, IsXhrPayload a) => Event t (f (XhrRequest a)) -> m (Event t (f XhrResponse))
224−performRequestsAsync = performRequestsAsync' newXMLHttpRequest . fmap return
225−
226−-- | Builds and issues a collection of requests when the supplied Event fires. When ALL requests from a given firing complete, the results are collected and returned via the return Event.
227−performMkRequestsAsync :: (MonadIO (Performable m), HasWebView (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f, IsXhrPayload a) => Event t (Performable m (f (XhrRequest a))) -> m (Event t (f XhrResponse))
228−performMkRequestsAsync = performRequestsAsync' newXMLHttpRequest
229−
230−performRequestsAsync' :: (MonadIO (Performable m), PerformEvent t m, TriggerEvent t m, Traversable f) => (XhrRequest b -> (a -> IO ()) -> Performable m XMLHttpRequest) -> Event t (Performable m (f (XhrRequest b))) -> m (Event t (f a))
231−performRequestsAsync' newXhr req = performEventAsync $ ffor req $ \hrs cb -> do
232− rs <- hrs
233− resps <- forM rs $ \r -> do
234− resp <- liftIO newEmptyMVar
235− _ <- newXhr r $ liftIO . putMVar resp
236− return resp
237− _ <- liftIO $ forkIO $ cb =<< forM resps takeMVar
238− return ()
239−
240−-- | Simplified interface to "GET" URLs and return decoded results.
241−getAndDecode :: (MonadIO m, MonadIO (Performable m), PerformEvent t m, HasWebView (Performable m), TriggerEvent t m, FromJSON a) => Event t Text -> m (Event t (Maybe a))
242−getAndDecode url = do
243− r <- performRequestAsync $ fmap (\x -> XhrRequest "GET" x def) url
244− return $ fmap decodeXhrResponse r
245−
246−-- | Create a "POST" request from an URL and thing with a JSON representation
247−postJson :: (ToJSON a) => Text -> a -> XhrRequest Text
248−postJson url a =
249− XhrRequest "POST" url $ def { _xhrRequestConfig_headers = headerUrlEnc
250− , _xhrRequestConfig_sendData = body
251− }
252− where headerUrlEnc = "Content-type" =: "application/json"
253− body = LT.toStrict $ B.toLazyText $ encodeToTextBuilder $ toJSON a
254−
255−getMay :: (Monad m, Reflex t) => (Event t a -> m (Event t b)) -> Event t (Maybe a) -> m (Event t (Maybe b))
256−getMay f e = do
257− e' <- f (fmapMaybe id e)
258− return $ leftmost [fmap Just e', fmapMaybe (maybe (Just Nothing) (const Nothing)) e]
259−
260−decodeText :: FromJSON a => Text -> Maybe a
261−decodeText = decode . BL.fromStrict . encodeUtf8
262−
263−-- | Convenience function to decode JSON-encoded responses.
264−decodeXhrResponse :: FromJSON a => XhrResponse -> Maybe a
265−decodeXhrResponse = join . fmap decodeText . _xhrResponse_responseText
266−
267−concat <$> mapM makeLenses
268− [ ''XhrRequest
269− , ''XhrRequestConfig
270− , ''XhrResponse
271− ]
272−
src/Reflex/Dom/Xhr/ResponseType.hsdeleted−21
@@ -1,21 +0,0 @@
1−{-# LANGUAGE DeriveDataTypeable #-}
2−
3−module Reflex.Dom.Xhr.ResponseType where
4−
5−import Data.ByteString (ByteString)
6−import Data.Text (Text)
7−import Data.Typeable
8−import GHCJS.DOM.Blob (Blob)
9−
10−data XhrResponseType = XhrResponseType_Default
11− | XhrResponseType_ArrayBuffer
12− | XhrResponseType_Blob
13− | XhrResponseType_Text
14− deriving (Show, Read, Eq, Ord, Typeable)
15−
16−data XhrResponseBody = XhrResponseBody_Default Text
17− | XhrResponseBody_Text Text
18− | XhrResponseBody_Blob Blob
19− | XhrResponseBody_ArrayBuffer ByteString
20− deriving (Eq)
21−
test/default.nixnew file+10
@@ -0,0 +1,10 @@
1+{ pkgs ? (import ../dep/reflex-platform {}).nixpkgs }:
2+{
3+ test-reflex-dom-reexports = pkgs.runCommand "test-reflex-dom-reexports" {} (
4+ let
5+ ghc = pkgs.haskellPackages.ghcWithPackages (p: [p.Cabal]);
6+ in ''
7+ ${ghc}/bin/runhaskell ${./reflex-dom-reexports.hs} ${../reflex-dom/reflex-dom.cabal} ${../reflex-dom-core/reflex-dom-core.cabal}
8+ touch "$out"
9+ '');
10+}
test/hlint.hsdeleted−12
@@ -1,12 +0,0 @@
1−import Language.Haskell.HLint3 (hlint)
2−import System.Exit (exitFailure, exitSuccess)
3−
4−main :: IO ()
5−main = do
6− ideas <- hlint
7− [ "."
8− , "--ignore=Redundant do"
9− , "--ignore=Use camelCase"
10− , "--ignore=Redundant $"
11− ]
12− if null ideas then exitSuccess else exitFailure
test/reflex-dom-reexports.hsnew file+72
@@ -0,0 +1,72 @@
1+-- This tests that reflex-dom re-exports all of reflex-dom-core's modules.
2+-- Without this test they easily drift.
3+module Main where
4+
5+import Control.Monad (when)
6+import Data.List (intercalate)
7+import Data.Maybe (fromMaybe, isNothing, mapMaybe)
8+import qualified Data.Set as Set
9+import Distribution.Types.PackageName (mkPackageName)
10+import Distribution.Compiler (CompilerFlavor (GHC))
11+import Distribution.ModuleName (ModuleName, components)
12+import Distribution.PackageDescription.Parsec (parseGenericPackageDescription)
13+import qualified Distribution.Parsec.Common as Dist
14+import Distribution.Parsec.ParseResult (runParseResult)
15+import qualified Distribution.System as Dist
16+import Distribution.Types.BuildInfo (buildable, defaultExtensions, defaultLanguage, hsSourceDirs, options)
17+import Distribution.Types.CondTree (simplifyCondTree)
18+import Distribution.Types.GenericPackageDescription (ConfVar (Arch, Impl, OS), condLibrary)
19+import Distribution.Types.Library (exposedModules, libBuildInfo, reexportedModules)
20+import Distribution.Types.ModuleReexport (ModuleReexport, moduleReexportOriginalName, moduleReexportOriginalPackage)
21+import Distribution.Utils.Generic (toUTF8BS, readUTF8File)
22+import System.Environment (getArgs)
23+import qualified System.Info
24+
25+main :: IO ()
26+main = do
27+ [reflexDomFile, reflexDomCoreFile] <- getArgs
28+ (_, reflexDomReexports) <- parseCabalExports reflexDomFile
29+ (reflexDomCoreExports', _) <- parseCabalExports reflexDomCoreFile
30+
31+ let
32+ reflexDomCoreExports = Set.fromList reflexDomCoreExports'
33+ reflexDomCorePackageName = mkPackageName "reflex-dom-core"
34+ reflexDomReexportsFromCore
35+ = Set.fromList
36+ $ mapMaybe (\x -> if let origPackage = moduleReexportOriginalPackage x
37+ in isNothing origPackage || origPackage == Just reflexDomCorePackageName
38+ then Just $ moduleReexportOriginalName x
39+ else Nothing
40+ )
41+ reflexDomReexports
42+
43+ when (reflexDomCoreExports /= reflexDomReexportsFromCore) $ do
44+ error $ intercalate "\n\t"
45+ $ "reflex-dom does not re-export the following modules from reflex-dom-core:"
46+ : map
47+ (intercalate "." . components)
48+ (Set.toAscList $ reflexDomCoreExports `Set.difference` reflexDomReexportsFromCore)
49+
50+ putStrLn "Test passed."
51+
52+parseCabalExports :: FilePath -> IO ([ModuleName], [ModuleReexport])
53+parseCabalExports file = do
54+ contents <- readUTF8File file
55+ let
56+ (warnings, result) = runParseResult $ parseGenericPackageDescription $ toUTF8BS contents
57+ osConfVar = case System.Info.os of
58+ "linux" -> Just Dist.Linux
59+ "darwin" -> Just Dist.OSX
60+ _ -> error "Unrecognized System.Info.os"
61+ archConfVar = Just Dist.X86_64
62+ evalConfVar v = Right $ case v of
63+ OS osVar -> Just osVar == osConfVar
64+ Arch archVar -> Just archVar == archConfVar
65+ Impl GHC _ -> True
66+ _ -> False
67+ pure $ case condLibrary <$> result of
68+ Right (Just condLib) ->
69+ let (_, lib) = simplifyCondTree evalConfVar condLib
70+ in (exposedModules lib, reexportedModules lib)
71+ Right Nothing -> error $ "Haskell package has no library component: " <> file
72+ Left (_, errors) -> error $ "Failed to parse " <> file <> ":\n" <> unlines (map show errors)