aboutsummaryrefslogtreecommitdiff
path: root/src/client/Model/Translations.elm
blob: 9b314e1c600c362717ce4cfae11bdcb89151126a (plain)
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
module Model.Translations exposing
  ( translationsDecoder
  , Translations
  , Translation
  , getMessage
  , getParamMessage
  )

import Maybe exposing (withDefault)
import Json.Decode as Decode exposing (Decoder)
import String

type alias Translations = List Translation

translationsDecoder : Decoder Translations
translationsDecoder = Decode.list translationDecoder

type alias Translation =
  { key : String
  , message : List MessagePart
  }

getTranslation : String -> Translations -> Maybe (List MessagePart)
getTranslation key translations =
  translations
    |> List.filter (\translation -> String.toLower translation.key == String.toLower key)
    |> List.head
    |> Maybe.map .message

translationDecoder : Decoder Translation
translationDecoder =
  Decode.map2 Translation
    (Decode.field "key" Decode.string)
    (Decode.field "message" (Decode.list partDecoder))

type MessagePart =
  Order Int
  | Str String

partDecoder : Decoder MessagePart
partDecoder = (Decode.field "tag" Decode.string) |> Decode.andThen partDecoderWithTag

partDecoderWithTag : String -> Decoder MessagePart
partDecoderWithTag tag =
  case tag of
    "Order" -> Decode.map Order (Decode.field "contents" Decode.int)
    _ -> Decode.map Str (Decode.field "contents" Decode.string)

-----

getMessage : Translations -> String -> String
getMessage = getParamMessage []

getParamMessage : List String -> Translations -> String -> String
getParamMessage values translations key =
  getTranslation key translations
    |> Maybe.map (\parts -> String.concat (List.map (replacePart values) parts))
    |> withDefault key

replacePart : List String -> MessagePart -> String
replacePart values part =
  case part of
    Str str -> str
    Order n ->
      values
        |> List.drop (n - 1)
        |> List.head
        |> withDefault ("{" ++ (toString n) ++ "}")