Repository navigation
Expand file tree
/
Copy pathFF.hs
More file actions
735 lines (669 loc) · 23.3 KB
/
Copy pathFF.hs
File metadata and controls
735 lines (669 loc) · 23.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ImportQualifiedPost #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module FF (
NoteFilter (..),
cmdDeleteContact,
cmdDeleteNote,
cmdDone,
cmdEdit,
cmdNewContact,
cmdNewNote,
cmdPostpone,
cmdSearch,
cmdUnarchive,
defaultNoteFilter,
fromRga,
fromRgaM,
getContactSamples,
viewTaskSamples,
getUtcToday,
viewWikiSamples,
load,
filterTasksByStatus,
loadAllTagTexts,
loadAllTags,
loadAllNotes,
loadTagsByRefs,
noDataDirectoryMessage,
splitModes,
splitModesBy,
sponsors,
takeSamples,
updateTrackedNotes,
cmdAddTagToGroup,
groupByTagGroup,
viewNote,
viewNoteSample,
)
where
import Control.Applicative ((<|>))
import Control.Monad (unless, void, when)
import Control.Monad.Except (throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State.Strict (MonadState, evalState, state)
import Control.Monad.Trans (lift)
import Data.Foldable (for_, toList, traverse_)
import Data.Function (on, (&))
import Data.HashMap.Strict (HashMap)
import Data.HashMap.Strict qualified as HashMap
import Data.HashSet (HashSet)
import Data.HashSet qualified as HashSet
import Data.List (find, genericLength, sortOn)
import Data.List.NonEmpty (NonEmpty ((:|)))
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (catMaybes, fromMaybe, isJust, mapMaybe)
import Data.Set (Set, disjoint, isSubsetOf, (\\))
import Data.Set qualified as Set
import Data.Text (Text, isInfixOf, toCaseFold)
import Data.Text qualified as Text
import Data.Time (
Day,
UTCTime,
addDays,
getCurrentTime,
toModifiedJulianDay,
utctDay,
)
import Data.Traversable (for)
import GHC.Stack (HasCallStack)
import RON.Data (
MonadObjectState,
ObjectStateT,
evalObjectState,
newObjectFrame,
readObject,
)
import RON.Data.RGA (RGA (RGA))
import RON.Data.RGA qualified as RGA
import RON.Epoch qualified as Epoch
import RON.Error (MonadE, throwErrorText)
import RON.Event (ReplicaClock)
import RON.Event qualified as Event
import RON.Storage (
Collection,
createDocument,
decodeDocId,
docIdFromUuid,
loadDocument,
modify,
)
import RON.Storage.Backend (
DocId (DocId),
Document (Document, objectFrame, versions),
MonadStorage (getDocuments),
)
import RON.Types (ObjectFrame (ObjectFrame, uuid), ObjectRef (ObjectRef))
import System.Random (StdGen, mkStdGen, randoms, split)
import FF.Config (ConfigUI (ConfigUI))
import FF.Config qualified
import FF.Options (
Assign (Clear, Set),
Edit (..),
New (..),
Tags (..),
TagsRequest (..),
assignToMaybe,
)
import FF.Types (
Contact (..),
ContactId,
ContactSample,
Entity (..),
EntityDoc,
EntityView,
Limit,
ModeMap,
Note (..),
NoteId,
NoteSample,
NoteStatus (..),
Sample (..),
Status (..),
Tag (..),
TagGroup (..),
Track (..),
View (..),
contact_name_clear,
contact_status_clear,
loadNote,
note_end_clear,
note_end_read,
note_end_set,
note_start_clear,
note_start_read,
note_start_set,
note_status_clear,
note_status_read,
note_status_set,
note_tags_add,
note_tags_clear,
note_tags_read,
note_tags_remove,
note_text_clear,
note_text_zoom,
note_track_read,
tagGroup_member_add,
taskMode,
uuidToText,
)
load :: (Collection a, MonadStorage m) => DocId a -> m (EntityDoc a)
load docid = do
document <- loadDocument docid
entityVal <- evalObjectState document.objectFrame readObject
pure
Entity
{ entityId = docid
, entityVal
, entityVersion = maximum document.versions
}
loadAll :: (Collection a, MonadStorage m) => m [EntityDoc a]
loadAll = getDocuments >>= traverse load
loadAllNotes :: (MonadStorage m) => m [EntityDoc Note]
loadAllNotes = getDocuments >>= traverse loadNote
loadContacts :: (MonadStorage m) => Status -> m [EntityDoc Contact]
loadContacts status =
filter ((== Just status) . (.contact_status) . (.entityVal)) <$> loadAll
loadAllTags :: (MonadStorage m) => m [EntityDoc Tag]
loadAllTags = loadAll
-- | Load all tags as texts
loadAllTagTexts :: (MonadStorage m) => m (Set Text)
loadAllTagTexts =
Set.fromList . mapMaybe ((.tag_text) . (.entityVal)) <$> loadAllTags
-- | Load 'Tag' references only for text strings existing in the collection.
loadTagRefsByText ::
(Foldable f, MonadStorage m) => f Text -> m (Set (ObjectRef Tag))
loadTagRefsByText queryTags = do
allTags <- loadAll
pure $
Set.fromList
[ docIdToRef entityId
| Entity{entityId, entityVal = Tag{tag_text = Just tag}} <- allTags
, tag `elem` queryTags
]
loadTagsByRefs ::
(MonadStorage m) =>
HashSet (ObjectRef Tag) -> m (HashMap (ObjectRef Tag) Text)
loadTagsByRefs refs =
HashMap.fromList . catMaybes <$> for (toList refs) \ref ->
fmap (ref,) . (.tag_text) . (.entityVal) <$> load (refToDocId ref)
-- | Create tag objects with given texts.
createTags :: (MonadStorage m) => Set Text -> m (Set (ObjectRef Tag))
createTags tags =
Set.fromList <$> for (toList tags) \tag -> do
tagFrame@ObjectFrame{uuid} <-
newObjectFrame Tag{tag_text = Just tag, tag_desc = Nothing}
_ <- createDocument tagFrame
pure $ ObjectRef uuid
{- | Add new tags to Collection of tags.
It doesn't create tags that are in the collection already.
It returns references that should be added to note_tags.
References may content ones that note_tags has already.
-}
getOrCreateTags ::
(Foldable f, MonadStorage m) => f Text -> m (Set (ObjectRef Tag))
getOrCreateTags tags
| null tags = pure Set.empty
| otherwise = do
allTags <- loadAllTagTexts
existentTagRefs <- loadTagRefsByText tags
let newTags = Set.fromList (toList tags) \\ allTags
createdTagRefs <- createTags newTags
pure $ existentTagRefs <> createdTagRefs
viewNote ::
(HasCallStack, MonadStorage m) => EntityDoc Note -> m (EntityView Note)
viewNote (Entity noteId note version) = do
tagsLoaded <- loadTagsByRefs tagRefs
let tags =
Map.fromList
[ (uuidToText uuid, tag)
| (ObjectRef uuid, tag) <- HashMap.toList tagsLoaded
]
let created = docIdToTime noteId
let lastUpdated = docIdToTime $ DocId version
let nv = NoteView{note, tags, created, lastUpdated}
pure $ Entity noteId nv version
where
tagRefs = HashSet.fromList note_tags
Note{note_tags} = note
docIdToTime :: (HasCallStack) => DocId a -> UTCTime
docIdToTime docid@(DocId rawdocid) =
decodeDocId docid
& fromMaybe (error $ "can't parse " <> show rawdocid)
& snd
& Event.unsafeDecodeEvent
& (.time)
& Event.timeValue
& Epoch.decode
viewNoteSample :: (MonadStorage m) => Sample (EntityDoc Note) -> m NoteSample
viewNoteSample Sample{items, total} = do
noteviews <- traverse viewNote items
pure Sample{items = noteviews, total}
getContactSamples :: (MonadStorage m) => Status -> m ContactSample
getContactSamples = getContactSamplesWith $ const True
getContactSamplesWith ::
(MonadStorage m) =>
-- | predicate to filter contacts by text
(Text -> Bool) ->
-- | filter by status
Status ->
m ContactSample
getContactSamplesWith predicate status = do
contacts <- loadContacts status
let items = filter predicate' contacts
pure Sample{items, total = genericLength items}
where
predicate' =
predicate . Text.pack . fromRgaM . (.contact_name) . (.entityVal)
fromRga :: RGA a -> [a]
fromRga (RGA xs) = xs
fromRgaM :: Maybe (RGA a) -> [a]
fromRgaM = maybe [] fromRga
filterTasksByStatus :: Status -> [EntityDoc Note] -> [EntityDoc Note]
filterTasksByStatus status =
filter $ (Just (TaskStatus status) ==) . (.note_status) . (.entityVal)
filterWikis :: [EntityDoc Note] -> [EntityDoc Note]
filterWikis = filter $ (Just Wiki ==) . (.note_status) . (.entityVal)
data NoteFilter = NoteFilter
{ status :: Status
, tags :: TagsRequest
, textPredicate :: Text -> Bool
}
defaultNoteFilter :: NoteFilter
defaultNoteFilter =
NoteFilter
{ status = Active
, tags = EmptyTagsRequest
, textPredicate = const True
}
viewTaskSamples ::
(HasCallStack, MonadStorage m) =>
NoteFilter ->
ConfigUI ->
Maybe Limit ->
-- | today
Day ->
[EntityDoc Note] ->
m (ModeMap NoteSample)
viewTaskSamples noteFilter config limit today notes = do
-- filter unrefined tasks
let notes' =
filter notePredicate $ filterTasksByStatus noteFilter.status notes
-- refine tasks
tasks <- traverse viewNote notes'
-- filter refined tasks
let tasks' = filter noteViewPredicate tasks
-- prepare result
pure . takeSamples limit . shuffleOrSort $ splitModes today tasks'
where
gen = mkStdGen . fromIntegral $ toModifiedJulianDay today
shuffleOrSort
| config.shuffle = shuffleTraverseItems gen
| otherwise =
-- in sorting by entityId no business-logic is involved,
-- it's just for determinism
fmap $
sortOn \Entity{entityId, entityVal} ->
(entityVal.note.note_start, entityId)
notePredicate Entity{entityVal = Note{note_text}} =
noteFilter.textPredicate $ Text.pack $ fromRgaM note_text
tagPredicate =
case noteFilter.tags of
EmptyTagsRequest -> const True
TagsContain Tags{require, exclude} ->
\ts -> require `isSubsetOf` ts && exclude `disjoint` ts
TagsAbsent -> null
noteViewPredicate Entity{entityVal = NoteView{tags}} =
tagPredicate $ Set.fromList $ toList tags
viewWikiSamples ::
(MonadStorage m) =>
ConfigUI ->
Maybe Limit ->
-- | today
Day ->
[EntityDoc Note] ->
m NoteSample
viewWikiSamples = toWikiSamplesWith $ const True
toWikiSamplesWith ::
(MonadStorage m) =>
-- | predicate to filter tasks by text
(Text -> Bool) ->
ConfigUI ->
Maybe Limit ->
-- | today
Day ->
[EntityDoc Note] ->
m NoteSample
toWikiSamplesWith predicate ConfigUI{shuffle} limit today notes =
viewNoteSample $ toSample $ shuffleOrSort wikis2
where
wikis0 = filterWikis notes
wikis1 = filter predicate' wikis0
wikis2 =
case limit of
Nothing -> wikis1
Just l -> take (fromIntegral l) wikis1
predicate'
8000
= predicate . Text.pack . fromRgaM . (.note_text) . (.entityVal)
toSample ys = Sample ys $ genericLength ys
gen = mkStdGen . fromIntegral $ toModifiedJulianDay today
shuffleOrSort
| shuffle = shuffleItems gen
| otherwise =
-- in sorting by entityId no business-logic is involved,
-- it's just for determinism
sortOn (.entityId)
shuffleItems :: StdGen -> [b] -> [b]
shuffleItems gen = (`evalState` gen) . shuf
shuf :: (MonadState StdGen m) => [b] -> m [b]
shuf xs = do
g <- state split
pure . map snd . sortOn fst $ zip (randoms g :: [Int]) xs
shuffleTraverseItems :: (Traversable t) => StdGen -> t [b] -> t [b]
shuffleTraverseItems gen = (`evalState` gen) . traverse shuf
splitModesBy :: (note -> Note) -> Day -> [note] -> ModeMap [note]
splitModesBy f today = Map.unionsWith (++) . map singleton
where
singleton task = Map.singleton (taskMode today $ f task) [task]
splitModes :: Day -> [EntityView Note] -> ModeMap [EntityView Note]
splitModes = splitModesBy ((.note) . (.entityVal))
takeSamples :: Maybe Limit -> ModeMap [a] -> ModeMap (Sample a)
takeSamples Nothing = fmap mkSample
where
mkSample ys = Sample ys $ genericLength ys
takeSamples (Just limit) = (`evalState` limit) . traverse takeSample
where
takeSample xs =
state \n ->
( Sample{items = take (fromIntegral n) xs, total = len}
, n `natSub` len
)
where
len = genericLength xs
a `natSub` b
| a <= b = 0
| otherwise = a - b
updateTrackedNote ::
(MonadStorage m) =>
-- | selection of all aready tracked notes
HashMap Track NoteId ->
-- | external note (with tags) to insert
View Note ->
m ()
updateTrackedNote oldNotes NoteView{note, tags} =
case note.note_track of
Just track -> do
newRefs <- getOrCreateTags tags
case HashMap.lookup track oldNotes of
Nothing -> do
obj <- newObjectFrame note{note_tags = toList newRefs}
void $ createDocument obj
Just noteid ->
void $ modify noteid do
note_status_setIfDiffer note.note_status
note_text_zoom $ RGA.edit text
-- Add new tags
currentRefs <- Set.fromList <$> note_tags_read
traverse_ note_tags_add $ newRefs \\ currentRefs
traverse_ note_tags_remove $ currentRefs \\ newRefs
Nothing ->
throwError "External note is expected to be supplied with tracking"
where
text = fromRgaM note.note_text
updateTrackedNotes :: (MonadStorage m) => [View Note] -> m ()
updateTrackedNotes newNotes = do
-- TODO(2018-10-22, https://github.com/ff-notes/ron/issues/116, cblp) index
-- notes by track in the database and select specific note by its track
notes <- getDocuments
oldNotesM <-
for notes \noteId -> do
Document{objectFrame} <- loadDocument noteId
mTrack <- evalObjectState objectFrame note_track_read
pure $ (,noteId) <$> mTrack
let oldNotes = HashMap.fromList $ catMaybes oldNotesM
for_ newNotes $ updateTrackedNote oldNotes
cmdNewNote :: (MonadStorage m) => New -> Day -> m (EntityDoc Note)
cmdNewNote New{text, start, end, isWiki, tags} today = do
let start' = fromMaybe today start
for_ end $ assertStartBeforeEnd start'
(status, note_end, noteStart) <-
case end of
_ | not isWiki -> pure (TaskStatus Active, end, start')
Nothing -> pure (Wiki, Nothing, today)
Just _ -> throwError "A wiki must have no end date."
refs <- getOrCreateTags tags
let note =
Note
{ note_end
, note_start = Just noteStart
, note_status = Just status
, note_text = Just $ RGA $ Text.unpack text
, note_tags = toList refs
, note_track = Nothing
, note_links = []
, note_recurring = Nothing
}
obj@ObjectFrame{uuid} <- newObjectFrame note
doc <- createDocument obj
pure $ Entity (docIdFromUuid uuid) note $ maximum doc.versions
cmdNewContact :: (MonadStorage m) => Text -> m (EntityDoc Contact)
cmdNewContact name = do
let contact =
Contact
{ contact_name = Just $ RGA $ Text.unpack name
, contact_status = Just Active
}
obj@ObjectFrame{uuid} <- newObjectFrame contact
doc <- createDocument obj
pure $ Entity (docIdFromUuid uuid) contact $ maximum doc.versions
cmdDeleteContact :: (MonadStorage m) => ContactId -> m (EntityDoc Contact)
cmdDeleteContact cid =
modifyAndView cid do
contact_status_clear
contact_name_clear
cmdSearch ::
(MonadStorage m) =>
-- | query
Text ->
-- | search within archived tasks or contacts
Status ->
ConfigUI ->
Maybe Limit ->
-- | today
Day ->
TagsRequest ->
m (ModeMap NoteSample, NoteSample, ContactSample)
cmdSearch substr status ui limit today tags = do
notes <- loadAllNotes
tasks <- viewTaskSamples noteFilter ui limit today notes
wikis <- toWikiSamplesWith textPredicate ui limit today notes
contacts <- getContactSamplesWith textPredicate status
pure (tasks, wikis, contacts)
where
noteFilter = NoteFilter{status, tags, textPredicate}
textPredicate = substr & (isInfixOf `on` toCaseFold)
cmdDeleteNote :: (MonadStorage m) => NoteId -> m (EntityDoc Note)
cmdDeleteNote nid =
modifyAndView nid do
assertNoteIsNative
note_status_clear
note_text_clear
note_start_clear
note_end_clear
note_tags_clear
cmdDone :: (MonadStorage m) => NoteId -> m (EntityDoc Note)
cmdDone nid =
modifyAndView nid do
assertNoteIsNative
note_status_set $ TaskStatus Archived
cmdUnarchive :: (MonadStorage m) => NoteId -> m (EntityDoc Note)
cmdUnarchive nid =
modifyAndView nid $ note_status_set $ TaskStatus Active
cmdEdit :: (MonadStorage m) => Edit -> (Text -> m Text) -> m [EntityDoc Note]
cmdEdit edit input =
case edit of
Edit{ids = _ :| _ : _, text = Just _} ->
throwError "Can't edit content of multiple notes"
Edit{ids = nid :| [], start = Nothing, end = Nothing}
| null edit.addTags
, null edit.deleteTags ->
(: []) <$> modifyAndView nid do
assertNoteIsNative
note_text_zoom do
noteText' <-
case edit.text of
Just noteText' -> pure noteText'
Nothing -> do
noteText <- RGA.getText
lift . lift $ input noteText
RGA.editText noteText'
Edit{ids, text, start, end, addTags, deleteTags} -> do
refsToAdd <- getOrCreateTags addTags
refsToDelete <- loadTagRefsByText deleteTags
for (toList ids) \nid ->
modifyAndView nid do
-- check text editability
for_ text $ const assertNoteIsNative
-- check start and end editability
when (isJust start || isJust end) do
status <- note_status_read
when (status == Just Wiki) $
throwError "Wiki dates are immutable"
-- check start and end relation
do
curStart <- note_start_read
curEnd <- note_end_read
let newStartEnd =
(,)
<$> (start <|> curStart)
<*> (end' <|> curEnd)
end' = end >>= assignToMaybe
for_ newStartEnd $
uncurry assertStartBeforeEnd
-- update
for_ end \case
Clear -> note_end_clear
Set e -> note_end_set e
for_ start note_start_set
for_ text $ note_text_zoom . RGA.editText
-- add new tags
unless (null addTags) do
currentRefs <- Set.fromList <$> note_tags_read
-- skip tags if note_tags has them already
let newRefs = refsToAdd \\ currentRefs
mapM_ note_tags_add newRefs
-- delete tags
unless (null deleteTags) $
mapM_ note_tags_remove refsToDelete
cmdPostpone :: (MonadIO m, MonadStorage m) => NoteId -> m (EntityDoc Note)
cmdPostpone nid =
modifyAndView nid do
today <- getUtcToday
start <- note_start_read
let start' = addDays 1 $ maybe today (max today) start
note_start_set start'
mEnd <- note_end_read
case mEnd of
Just end | end < start' -> note_end_set start'
_ -> pure ()
modifyAndView ::
(Collection a, MonadStorage m) =>
DocId a ->
ObjectStateT a m () ->
m (EntityDoc a)
modifyAndView docid f = do
_ <- modify docid $ f *> readObject
load docid
getUtcToday :: (MonadIO io) => io Day
getUtcToday = liftIO $ utctDay <$> getCurrentTime
assertStartBeforeEnd :: (MonadE m) => Day -> Day -> m ()
assertStartBeforeEnd start end =
unless (start <= end) $ throwError "task cannot end before it is started"
note_status_setIfDiffer ::
(MonadE m, MonadObjectState Note m, ReplicaClock m) =>
Maybe NoteStatus ->
m ()
note_status_setIfDiffer newStatus = do
curStatus <- note_status_read
when (curStatus /= newStatus) $
maybe note_status_clear note_status_set newStatus
assertNoteIsNative :: (MonadE m, MonadObjectState Note m) => m ()
assertNoteIsNative = do
tracking <- note_track_read
for_ tracking \Track{track_url} ->
throwErrorText $
"A tracked note must be edited in its source"
<> maybe "" (": " <>) track_url
noDataDirectoryMessage :: String
noDataDirectoryMessage =
"Data directory isn't set, run `ff config dataDir --help`"
sponsors :: [Text]
sponsors = ["Alexander Granin", "Nadezda"]
refToDocId :: ObjectRef a -> DocId a
refToDocId (ObjectRef uid) = docIdFromUuid uid
docIdToRef :: DocId a -> ObjectRef a
docIdToRef docId =
case decodeDocId docId of
Nothing -> error "Decode UUID from DocId failed. DocId is "
Just (_, uid) -> ObjectRef uid
findTagGroupByName ::
(MonadStorage m) => Text -> m (Maybe (EntityDoc TagGroup))
findTagGroupByName name =
find
( \Entity{entityVal = TagGroup{tagGroup_name}} ->
tagGroup_name == Just name
)
<$> loadAll
groupByTagGroup ::
(MonadStorage m) =>
Text -> [EntityDoc Note] -> m (Map (Set Text) NoteSample)
groupByTagGroup tagGroupName notes = do
mGroup <- findTagGroupByName tagGroupName
case mGroup of
Nothing -> pure Map.empty
Just Entity{entityVal = TagGroup{tagGroup_member}} -> do
let memberUuids =
Set.fromList
[uuidToText uuid | ObjectRef uuid <- tagGroup_member]
tasks <- traverse viewNote notes
pure $
Map.fromListWith
appendSamples
[ (matchedTags, Sample{items = [task], total = 1})
| task@Entity{entityVal = NoteView{tags}} <- tasks
, let matchedTags =
Set.fromList
. Map.elems
$ Map.restrictKeys tags memberUuids
]
where
appendSamples
Sample{items = a, total = ta}
Sample{items = b, total = tb} =
Sample{items = a ++ b, total = ta + tb}
cmdAddTagToGroup ::
(MonadStorage m) => Text -> Text -> m (EntityDoc TagGroup)
cmdAddTagToGroup tagText groupName = do
tagRefs <- getOrCreateTags [tagText]
let tagRef = Set.findMin tagRefs
mGroup <- findTagGroupByName groupName
case mGroup of
Just Entity{entityId} ->
modifyAndView entityId $ tagGroup_member_add tagRef
Nothing -> do
let group =
TagGroup
{ tagGroup_name = Just groupName
, tagGroup_exclusive = Just True
, tagGroup_member = [tagRef]
}
obj@ObjectFrame{uuid} <- newObjectFrame group
doc <- createDocument obj
pure $ Entity (docIdFromUuid uuid) group $ maximum doc.versions