jeongoon/elmnt-scrollpicker/2.0.0

Elmnt.BaseScrollPicker

This module is an implementation of picker by scrolling and basic view type is elm-ui. and animation can be done a bit tricky but easily thanks to elm-style-animation. Due to some non-standard way to hiding scrollbar, elm-css is also required.

Note: Type annotation is probably too long to see. However, it might be useful if you want add some feature with your own picker model.

Type

type alias MinimalState vt msg =
{ idString : String
, optionIds : List String
, optionIdToRecordDict : Dict String (Option vt msg)
, targetIdString : Maybe String
, pseudoAnimState : State msg
, lastScrollClock : Posix
, scrollTraceMP : Set Int
, finalTargetScrollPosMP : Int
, scrollStopCheckTime : Int
}

Provide Minimal model (or state) to work with. most of funciton in this module works well with your own record type generally, as I used more generic type constraint in function definition

..
, pseudoAnimState : Animation.Messenger.State msg
..

Note: elm-style-animation module doesn't supply low-level functions to get intermediate states of animation so I need more research but now I'm using renderPairs function to get the states of current values in 'String' format which will be traslated into number. Even though one state value is used, I need to use Animation.style function to generate the state which can contain a lot more information

= Horizontal
| Vertical

Picker direction

= Start
| End

this type is for general use, and also used in the picker shading part from the beginning and the end.

type alias Option vt msg =
{ idString : String
, index : Int
, value : vt
, element : Element msg
}

Option record for each item in the list from which user will choose.

This record depends on the type of value and element (Element)

type Msg vt msg
= SyncLastScroll Posix Bool
| OnScroll
| OnKey String
| TriggerSnapping Posix
| CheckInitialTargetOption
(List (Option vt msg))
(Option vt msg)
(List (Option vt msg))
| DetermineTargetOption
(Result
( List (Option vt msg), Maybe ( String, Float ) )
)
| SetSnapToTargetOption String Float Float
| MoveToTargetOption String
| ScrollPickerSuccess (Option vt msg)
| ScrollPickerFailure Error
| Animate Msg
| AnimateSnapping Int
| NoOp

Msg chain generally covers the following steps

1. Detect any scroll which has delayed 'Cmd' to check
   whether scrolling is stopped or not.
2. If scroll stopped, trigger snapping to nearst item.
3. Find and decide which item will be target to snap.
4. Do animation related to snapping
5. Inform the snapping is done so outside world is able
   to know the which item(Option) is selected.

Unfortunately we need own Msg here which means you might need to map over those message into your own Msg type.

There are examples in this module regarding message mapping you could possibly search keyword 'messageMap' where I need to map the Msg' into msg'

type Msg vt msg
    = SyncLastScroll            Time.Posix Bool
    | OnScroll
    | TriggerSnapping           Time.Posix
    | CheckInitialTargetOption
          (List (Option vt msg))
          -- ^ options before the sample
          (Option vt msg)
          -- ^ initial sample to check
          (List (Option vt msg))
          -- ^ options after the sample

    | DetermineTargetOption
          (Result Error (List (Option vt msg)
                              --^  other candidates
                        , Maybe ( String
                                  --^ current name of closest
                                  --  Option
                                 , Float )
                                 --^ current closest position
                                 --   of an Option
                        )
          )
          

    | SetSnapToTargetOption     String Float Float
                                -- ^ id, frame position,
                                --   relative pos to snap
    | MoveToTargetOption        String
    | ScrollPickerSuccess       (Option vt msg)
    | ScrollPickerFailure       Error
    | Animate                   Animation.Msg
    | AnimateSnapping           Int
    | NoOp
type Error

Error used for Task x a

XXX: this module doesn't really analyse the error status very well, but those data types are explaining the stauts in the code instead of any other types of comments.

State(picker model) Creation, Modification and Query

initMinimalState : String -> MinimalState vt msg

Helper function to initialise the minimal model. You can call setOptions after this.

    initMinimalState "myPicker"
        |> setOptions
           String.fromInt
           [ ( 1, Element.text "1" )
           , ( 2, Element.text "2" )
           ...
(vt -> String)
-> List ( vt, Element msg )
-> { state
| idString : String
, optionIds : List String
, optionIdToRecordDict : Dict String (Option vt msg)
}
-> { state
| idString : String
, optionIds : List String
, optionIdToRecordDict : Dict String (Option vt msg)
}

Save options from the list of pair of ( data, Element ) option Ids are stored separately and details stored in a Dict there is no way to know how to make data value to string you should suggest the function (vt -> String)

{ state
| optionIds : List String
, optionIdToRecordDict : Dict String (Option vt msg)
}
-> List (Option vt msg)

get a list of Option record data from the whole options by searching option ID in a Dict.

The order of options in the same one of optionID list.

Int
-> { state | scrollStopCheckTime : Int }
-> { state | scrollStopCheckTime : Int }

Every scroll is being watched to check whether it is stopped at the moment and this function will change the timing to wait until checking.

Limitation: minimum value is 75 (ms). Animation will fail or work unexpectedly under 75 ms.

anyNewOptionSelected : Msg vt msg -> Maybe (Option vt msg)

Check the Msg, and return if there is any new selected option

please check this [Example][exampleUpdate].

Update

{ a
| messageMapWith : String -> Msg vt msg -> msg
, pickerDirection : Direction
}
-> Msg vt msg
-> { b
| idString : String
, lastScrollClock : Posix
, scrollTraceMP : Set Int
, finalTargetScrollPosMP : Int
, scrollStopCheckTime : Int
, optionIdToRecordDict : Dict String (Option vt msg)
, optionIds : List String
, pseudoAnimState : State msg
, targetIdString : Maybe String
}
-> ( { b
| idString : String
, lastScrollClock : Posix
, scrollTraceMP : Set Int
, finalTargetScrollPosMP : Int
, scrollStopCheckTime : Int
, optionIdToRecordDict : Dict String (Option vt msg)
, optionIds : List String
, pseudoAnimState : State msg
, targetIdString : Maybe String
}
, Cmd msg
)

updateWith function needs your own app model to ask to get messageMapWith and pickerDirection from it. So if you want to use multiple picker, you can keep the same information in the same place in benefit.

As other update function supposed to do, updateWith also does the job described in the Msg of the module.

Subscriptions

List
{ state
| idString : String
, lastScrollClock : Posix
, scrollTraceMP : Set Int
, finalTargetScrollPosMP : Int
, scrollStopCheckTime : Int
, optionIdToRecordDict : Dict String (Option vt msg)
, optionIds : List String
, pseudoAnimState : State msg
, targetIdString : Maybe String
}
-> { model | messageMapWith : String -> Msg vt msg -> msg }
-> Sub msg

Pass the list of the scroll states with your own application model to inform the function messageMapWith function, and you will get subscription (Sub msg).

Important: no animation will work withought subscriptions!!!

View

{ appModel
| messageMapWith : String -> Msg vt msg -> msg
, pickerDirection : Direction
}
-> BaseTheme
{ palette
| accent : Color
, surface : Color
, background : Color
, on : { paletteOn | background : Color, surface : Color }
, toElmUiColor : Color -> Color
}
msg
-> { state
| idString : String
, optionIds : List String
, optionIdToRecordDict : Dict String (Option vt msg)
}
-> Element msg

Generating Element with theme setting and state value each function only try to some state value in the whole record so if you can apply this funciton with additional state you might want to use.

BaseTheme DOES NOT use all the color in the Palette. the Colors used in the theme are 'accent', 'surface', 'background' 'on.background', 'on.surface'. as you can see in the long signature

This means the color listed above are should be in your own palette at least, even if you are using your own color accessor(function) with your theme.

defaultTheme : BaseTheme Palette msg

All setting values are set to Theme.Default, which can be applied to scrollPicker function.

...
exampleView model
    = let
        theme
            = defaultTheme

        picker
            = viewAsElement model theme

...
type alias BaseTheme palette msg =
{ palette : palette
, borderWidth : Value Int
, borderColorFn : Value (palette -> Color)
, shadingColorFn : Value (palette -> Color)
, focusColorFn : Value (palette -> Color)
, backgroundColorFn : Value (palette -> Color)
, fontColorFn : Value (palette -> Color)
, fontSize : Value Int
, shadeLength : Value Int
, pickerLength : Value Int
, pickerWidth : Value Int
, shadeAttrsFn :
Value (Direction -> StartEnd -> List (Attribute msg))
}

An example settings value type in use here

type alias BaseSettings compatible msg =
{ lengthSetter : Length -> Attribute msg
, widthSetter : Length -> Attribute msg
, longitudinalContainer :
List (Attribute msg) -> List (Element msg) -> Element msg
, ancherString : String
, windowEdges :
{ top : Int
, right : Int
, bottom : Int
, left : Int
}
, centerLateral : Attribute msg
, cssWidthSetter : LengthOrAuto compatible -> Style
, cssOverFlowLongitudinal : Overflow compatible -> Style
, cssOverFlowLateral : Overflow compatible -> Style
, fontSize : Int
, shadeLength : Int
, borderWidth : Int
, pickerLength : Int
, pickerWidth : Int
}

Settings generated from the picker Direction for function such as 'viewAsElement' and 'defaultShadeAttrsWith'.

Helper functions

getOptionIdString : (vt -> String) -> String -> vt -> String

make option id string value for 'Option.idString' which will be useful if you want to access the id on the page.

Low-level Data types and functions

isSnapping : { state | targetIdString : Maybe String } -> Bool

minimal testing function if the picker is snapping to some item at the moment

{ state
| targetIdString : Maybe String
, finalTargetScrollPosMP : Int
, scrollTraceMP : Set Int
, pseudoAnimState : State msg
}
-> { state
| targetIdString : Maybe String
, finalTargetScrollPosMP : Int
, scrollTraceMP : Set Int
, pseudoAnimState : State msg
}

reset some states for runtime to stop snapping which includes current target, scroll position to snap to, clock when scroll happened etc.

Note: this function only try to stop snapping but asynchronous messasing will produce more animation after calling this function, so keep in mind that animation for snapping is not guaranteed to be done even if call this function in `model' part.

Int
-> { state | scrollStopCheckTime : Int }
-> { state | scrollStopCheckTime : Int }

You can test any value -- even under 75 ms -- however which is not recommended

Takes the direction of picker and gives the shade length

BaseTheme
{ palette
| accent : Color
, surface : Color
, background : Color
, on : { paletteOn | background : Color, surface : Color }
, toElmUiColor : Color -> Color
}
msg
-> List (Attribute msg)

and helper function for shade elm-ui attributes (List Element.Attribute)

-> { theme
| fontSize : Value Int
, borderWidth : Value Int
, shadeLength : Value Int
, pickerLength : Value Int
, pickerWidth : Value Int
}
-> BaseSettings compatible msg

Generate setting values for a picker which has Direction

type alias Geom =
{ x : Float
, y : Float
, width : Float
, height : Float
}

geometry data type which can be seen in 'Browser.Dom.Viewport'

getCenterPosOf : (Geom -> Float) -> (Geom -> Float) -> (rec -> Geom) -> rec -> Float

Browser.Dom.Viewport, Browser.Dom.Element share basic record accessor like .x .y .width .height

getCenterPosOf function try to get center poisition of the some field.

ex) to get center 'y' position of viewport, you can try

getCenterPosOf .y .height .viewport aRecord
(Geom -> Float)
-> (Geom -> Float)
-> { state
| optionIdToRecordDict : Dict String (Option vt msg)
, optionIds : List String
}
-> { vp
| scene : { d | height : Float, width : Float }
, viewport : Geom
}
-> OptionPartition vt msg

when all the items are distributed uniformly, it might be easier to get the option to focus(for snapping). partitionOptions will provide one candidate to snap and previous options prior to current one and next options as well. Calulating relative position in Viewport probably be only way to test whether the target is correct one or not, however you might need to check around current candidate.

(Geom -> Float)
-> (Geom -> Float)
-> { pos | element : Geom, viewport : Geom }
-> Float

To get relative position of element in the viewport.

you need to apply position accessor and length accessor which are normally .x and .width for Horizontal scroll picker and .y and .height for Vertical scroll picker.

Note: the element is got from getElement, viewport is got from getViewport

taskTargetOptionRelPosHelper : (Geom -> Float) -> (Geom -> Float) -> String -> String -> Task Error Float

A Task helper function to get relative distance of the item from frame which is measured from the center position of each other. This value has sign -- negtative value shows that the item is left or above the centre of view frame

taskGetViewport : String -> Task Error Viewport

Task helper to get viewport of the item id.

taskGetViewportPosHelper : (Geom -> Float) -> String -> Task Error Float

Task helper to retreive the position. posAccessor

toMilliPixel : Float -> Int

An utility which converts an floating value to an integer value which contains upto milli of base unit (pixel in this case)

fromMilliPixel : Int -> Float

An utility which converts an integer value(which contains up to thousandth value of original) to an float value.

(String -> Msg -> msg)
-> List { a | idString : String, pseudoAnimState : State msg }
-> Sub msg

FIXME

- add keyboard input support