Browser.Dom.getViewport return value

The type signature for Browser.Dom.getViewport shows that it returns Task x Viewport where Viewport is defined as

type alias Viewport =
    { scene :
          { width : Float
          , height : Float
          }
    , viewport :
          { x : Float
          , y : Float
          , width : Float
          , height : Float
          }
    }

I want to access the Viewport.viewport width and height fields. How do I get access to them? I tried using Debug.toString to get a clue but it just returns <internals>, which was no help.

I am not 100% clear on what you are asking. In particular, I am not sure if you are looking for a way to access the definition, or the value at runtime.

Assuming the runtime value:
Browser.Dom.getViewport returns a Task.
Tasks do not do anything by themselves, but need to be “started”.
Depending on whether the task can fail or not, you can use either Task.attempt or Task.perform. They take a callback message, so that they can notify your update when they are done.

The parts of the documentation might be of more help than my explanation:
https://package.elm-lang.org/packages/elm/core/latest/Task#perform
https://guide.elm-lang.org/effects/

So, to access the value at runtime, you must kick off the Task, and read the value that it gives back.
The viewport value will exist under .viewport, of the name that you assign it to. You can start the task either as the result of user interaction, or even in the second argument to the init tuple.

Here’s a quick example that shows this:
https://ellie-app.com/3nw5FhVJYL4a1

(Sorry if I misunderstood your question, happy to follow up :slight_smile: )

8 Likes

Sorry if my question was unclear, but you answered it exactly. Thanks! I’m still sketchy on some fundamentals such as Tasks but your Ellie illustrates how to do this perfectly. Thanks again.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.