@@ -0,0 +1,246 @@
1+{-# LANGUAGE DeriveFoldable #-}
2+{-# LANGUAGE DeriveFunctor #-}
3+{-# LANGUAGE DeriveTraversable #-}
4+{-# LANGUAGE FlexibleContexts #-}
5+{-# LANGUAGE LambdaCase #-}
6+{-# LANGUAGE PatternGuards #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE StandaloneDeriving #-}
9+{-# LANGUAGE TypeFamilies #-}
10+{-# LANGUAGE UndecidableInstances #-}
11+-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
12+-- another
13+module Reflex.Patch.MapWithMove2 where
14+
15+import Reflex.Patch.Class
16+
17+import Control.Arrow
18+import Control.Monad.State
19+import Data.Foldable
20+import Data.Function
21+import Data.List
22+import Data.Map (Map)
23+import qualified Data.Map as Map
24+import Data.Maybe
25+import Data.Semigroup
26+import qualified Data.Set as Set
27+import Data.These
28+import Data.Tuple
29+
30+-- | Patch a DMap with additions, deletions, and moves. Invariant: If key @k1@
31+-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
32+-- and vice versa. There should never be any unpaired From/To keys.
33+newtype PatchMapWithMove2 k p = PatchMapWithMove2 (Map k (NodeInfo k p))
34+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithMove2 k p)
35+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithMove2 k p)
36+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithMove2 k p)
37+
38+-- | Holds the information about each key: where its new value should come from,
39+-- and where its old value should go to
40+data NodeInfo k p = NodeInfo
41+ { _nodeInfo_from :: !(From k p)
42+ -- ^ Where do we get the new value for this key?
43+ , _nodeInfo_to :: !(To k)
44+ -- ^ If the old value is being kept (i.e. moved rather than deleted or
45+ -- replaced), where is it going?
46+ }
47+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
48+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
49+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
50+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
51+
52+-- | Create a 'PatchMapWithMove2', validating it
53+patchMapWithMove2 :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithMove2 k p)
54+patchMapWithMove2 m = if valid then Just $ PatchMapWithMove2 m else Nothing
55+ where valid = forwardLinks == backwardLinks
56+ forwardLinks = Map.mapMaybe _nodeInfo_to m
57+ backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
58+ case _nodeInfo_from p of
59+ From_Move from _ -> Just (from, to)
60+ _ -> Nothing
61+
62+-- | Create a 'PatchMapWithMove2' that inserts everything in the given 'Map'
63+patchMapWithMove2InsertAll :: Map k (PatchTarget p) -> PatchMapWithMove2 k p
64+patchMapWithMove2InsertAll m = PatchMapWithMove2 $ flip fmap m $ \v -> NodeInfo
65+ { _nodeInfo_from = From_Insert v
66+ , _nodeInfo_to = Nothing
67+ }
68+
69+-- | Extract the internal representation of the 'PatchMapWithMove2'
70+unPatchMapWithMove2 :: PatchMapWithMove2 k p -> Map k (NodeInfo k p)
71+unPatchMapWithMove2 (PatchMapWithMove2 p) = p
72+
73+-- | Warning: when using this function, you must ensure that the invariants of
74+-- 'PatchMapWithMove2' are preserved; they will not be checked.
75+unsafePatchMapWithMove2 :: Map k (NodeInfo k p) -> PatchMapWithMove2 k p
76+unsafePatchMapWithMove2 = PatchMapWithMove2
77+
78+-- | Describe how a key's new value should be produced
79+data From k p
80+ = From_Insert (PatchTarget p) -- ^ Insert the given value here
81+ | From_Delete -- ^ Delete the existing value, if any, from here
82+ | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
83+
84+deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
85+deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
86+deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
87+deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
88+
89+-- | Describe where a key's old value will go. If this is 'Just', that means
90+-- the key's old value will be moved to the given other key; if it is 'Nothing',
91+-- that means it will be deleted.
92+type To = Maybe
93+
94+-- | Apply the insertions, deletions, and moves to a given 'Map'
95+instance (Ord k, Patch p) => Patch (PatchMapWithMove2 k p) where
96+ type PatchTarget (PatchMapWithMove2 k p) = Map k (PatchTarget p)
97+ apply (PatchMapWithMove2 m) 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?
98+ where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
99+ From_Insert v -> Just v
100+ From_Move k p -> applyAlways p <$> Map.lookup k old
101+ From_Delete -> Nothing
102+ deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
103+ From_Delete -> Just ()
104+ _ -> Nothing
105+
106+-- | Returns all the new elements that will be added to the 'Map'
107+patchMapWithMove2NewElements :: PatchMapWithMove2 k p -> [PatchTarget p]
108+patchMapWithMove2NewElements = Map.elems . patchMapWithMove2NewElementsMap
109+
110+patchMapWithMove2NewElementsMap :: PatchMapWithMove2 k p -> Map k (PatchTarget p)
111+patchMapWithMove2NewElementsMap (PatchMapWithMove2 p) = Map.mapMaybe f p
112+ where f ni = case _nodeInfo_from ni of
113+ From_Insert v -> Just v
114+ From_Move _ _ -> Nothing
115+ From_Delete -> Nothing
116+
117+-- | Create a 'PatchMapWithMove2' that, if applied to the given 'Map', will sort
118+-- its values using the given ordering function. The set keys of the 'Map' is
119+-- not changed.
120+patchThatSortsMapWith :: (Ord k, Monoid p) => (PatchTarget p -> PatchTarget p -> Ordering) -> Map k (PatchTarget p) -> PatchMapWithMove2 k p
121+patchThatSortsMapWith cmp m = PatchMapWithMove2 $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
122+ where unsorted = Map.toList m
123+ sorted = sortBy (cmp `on` snd) unsorted
124+ f (to, _) (from, _) = if to == from then Nothing else
125+ Just (from, to)
126+ reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
127+ g (to, _) (from, _) = if to == from then Nothing else
128+ let Just movingTo = Map.lookup from reverseMapping
129+ in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
130+
131+-- | Create a 'PatchMapWithMove2' that, if applied to the first 'Map' provided,
132+-- will produce a 'Map' with the same values as the second 'Map' but with the
133+-- values sorted with the given ordering function.
134+patchThatChangesAndSortsMapWith :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p) => (PatchTarget p -> PatchTarget p -> Ordering) -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithMove2 k p
135+patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
136+ where newList = Map.toList newByIndexUnsorted
137+ newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
138+
139+-- | Create a 'PatchMapWithMove2' that, if applied to the first 'Map' provided,
140+-- will produce the second 'Map'.
141+patchThatChangesMap :: (Ord k, Ord (PatchTarget p), Monoid p) => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithMove2 k p
142+patchThatChangesMap oldByIndex newByIndex = patch
143+ where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
144+ (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
145+ let f k v = do
146+ remainingValues <- get
147+ let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
148+ then Map.delete v remainingValues
149+ else Map.insert v remainingKeys remainingValues
150+ case Map.lookup v remainingValues of
151+ Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
152+ Just fromKs ->
153+ if k `Set.member` fromKs
154+ then do
155+ putRemainingKeys $ Set.delete k fromKs
156+ return $ NodeInfo (From_Move k mempty) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
157+ else do
158+ (fromK, remainingKeys) <- return . fromJust $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
159+ putRemainingKeys remainingKeys
160+ return $ NodeInfo (From_Move fromK mempty) $ Just undefined
161+ Map.traverseWithKey f newByIndex
162+ unusedOldKeys = fold unusedValuesByValue
163+ pointlessMove k = \case
164+ From_Move k' _ | k == k' -> True
165+ _ -> False
166+ keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
167+ then Just undefined
168+ else Nothing
169+ patch = unsafePatchMapWithMove2 $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
170+
171+-- | Change the 'From' value of a 'NodeInfo'
172+nodeInfoMapFrom :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
173+nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
174+
175+-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
176+-- 'Applicative', 'Monad', etc.) action to get the new value
177+nodeInfoMapMFrom :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
178+nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
179+
180+-- | Set the 'To' field of a 'NodeInfo'
181+nodeInfoSetTo :: To k -> NodeInfo k v -> NodeInfo k v
182+nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
183+
184+-- |Helper data structure used for composing patches using the monoid instance.
185+data Fixup k v
186+ = Fixup_Delete
187+ | Fixup_Update (These (From k v) (To k))
188+
189+-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
190+instance (Ord k, Monoid p, Eq p, Patch p) => Semigroup (PatchMapWithMove2 k p) where
191+ PatchMapWithMove2 ma <> PatchMapWithMove2 mb = PatchMapWithMove2 m
192+ where
193+ connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
194+ h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
195+ h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
196+ (Just toAfter, From_Move fromBefore p)
197+ | fromBefore == toAfter && p == mempty
198+ -> [(toAfter, Fixup_Delete)]
199+ | otherwise
200+ -> [ (toAfter, Fixup_Update (This editBefore))
201+ , (fromBefore, Fixup_Update (That mToAfter))
202+ ]
203+ (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
204+ (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
205+ (Nothing, _) -> []
206+ mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
207+ mergeFixups _ (Fixup_Update a) (Fixup_Update b)
208+ | This x <- a, That y <- b
209+ = Fixup_Update $ These x y
210+ | That y <- a, This x <- b
211+ = Fixup_Update $ These x y
212+ mergeFixups _ _ _ = error "PatchMapWithMove2: incompatible fixups"
213+ fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
214+ combineNodeInfos _ nia nib = NodeInfo
215+ { _nodeInfo_from = _nodeInfo_from nia
216+ , _nodeInfo_to = _nodeInfo_to nib
217+ }
218+ applyFixup _ ni = \case
219+ Fixup_Delete -> Nothing
220+ Fixup_Update u -> Just $ NodeInfo
221+ { _nodeInfo_from = case _nodeInfo_from ni of
222+ f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
223+ Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
224+ Just (From_Insert v) -> From_Insert $ applyAlways p' v
225+ Just From_Delete -> From_Delete
226+ Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
227+ _ -> error "PatchMapWithMove2: fixup for non-move From"
228+ , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
229+ }
230+ m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
231+ getHere :: These a b -> Maybe a
232+ getHere = \case
233+ This a -> Just a
234+ These a _ -> Just a
235+ That _ -> Nothing
236+ getThere :: These a b -> Maybe b
237+ getThere = \case
238+ This _ -> Nothing
239+ These _ b -> Just b
240+ That b -> Just b
241+
242+--TODO: Figure out how to implement this in terms of PatchDMapWithMove rather than duplicating it here
243+-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
244+instance (Ord k, Monoid p, Eq p, Patch p) => Monoid (PatchMapWithMove2 k p) where
245+ mempty = PatchMapWithMove2 mempty
246+ mappend = (<>)