### Run Elm URL Examples Source: https://github.com/elm/url/blob/master/examples/README.md Navigate to the examples directory and start the Elm reactor to view examples in the browser. ```bash git clone https://github.com/elm/url cd url cd examples elm reactor ``` -------------------------------- ### Create Http URL Record Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url.md Example of constructing a Url record for an HTTP URL. ```elm httpUrl : { protocol : Protocol host : String port_ : Maybe Int path : String query : Maybe String fragment : Maybe String } httpUrl = { protocol = Http host = "example.com" port_ = Nothing path = "/" query = Nothing fragment = Nothing } ``` -------------------------------- ### Create Https URL Record Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url.md Example of constructing a Url record for an HTTPS URL. ```elm httpsUrl : { protocol : Protocol host : String port_ : Maybe Int path : String query : Maybe String fragment : Maybe String } httpsUrl = { protocol = Https host = "example.com" port_ = Nothing path = "/secure" query = Nothing fragment = Nothing } ``` -------------------------------- ### Operator Precedence Example Source: https://github.com/elm/url/blob/master/_autodocs/FUNCTION_INDEX.md Demonstrates the precedence of the and operators in URL parsing. The operator has higher precedence. ```elm s "blog" int Query.string "sort" -- Parses as: (s "blog" int) (Query.string "sort") ``` -------------------------------- ### Example Usage of String Parser Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md Demonstrates how the `string` parser captures path segments. It matches segments like "alice" or "42" but not the root path "/". ```elm import Url.Parser exposing (Parser, string) -- Matches: /alice/ ==> Just "alice" -- Matches: /bob ==> Just "bob" -- Matches: /42/ ==> Just "42" -- Fails: / ==> Nothing ``` -------------------------------- ### Url.percentDecode Examples Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url.md Demonstrates decoding of ASCII, UTF-8, and invalid percent-encoded strings using Url.percentDecode. Returns Nothing for malformed inputs. ```elm Url.percentDecode "hat" -- Just "hat" ``` ```elm Url.percentDecode "to%20be" -- Just "to be" ``` ```elm Url.percentDecode "99%25" -- Just "99%" ``` ```elm Url.percentDecode "%24" -- Just "$" ``` ```elm Url.percentDecode "%C2%A2" -- Just "¢" ``` ```elm Url.percentDecode "%E2%82%AC" -- Just "€" ``` ```elm Url.percentDecode "%" -- Nothing (incomplete) ``` ```elm Url.percentDecode "%XY" -- Nothing (not hex digits) ``` ```elm Url.percentDecode "%C2" -- Nothing (incomplete UTF-8 sequence) ``` -------------------------------- ### Parse Optional Query Parameters with Maybe Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Use `Maybe` to handle query parameters that may or may not be present. This example defines a route for blog list items with optional search, author, and sort parameters. ```elm import Url.Parser.Query as Query type Route = BlogList BlogListParams | NotFound type alias BlogListParams = { search : Maybe String , author : Maybe String , sort : Maybe SortOrder } type SortOrder = Newest | Oldest | Popular sortOrder : Query.Parser (Maybe SortOrder) sortOrder = Query.enum "sort" (Dict.fromList [ ("newest", Newest) , ("oldest", Oldest) , ("popular", Popular) ]) blogListParams : Query.Parser BlogListParams blogListParams = Query.map3 BlogListParams (Query.string "search") (Query.string "author") sortOrder routeParser : Parser (Route -> a) a routeParser = oneOf [ map BlogList (s "blog" query blogListParams) ] -- Matches: -- /blog -> BlogList { search = Nothing, author = Nothing, sort = Nothing } -- /blog?search=elm -> BlogList { search = Just "elm", author = Nothing, sort = Nothing } -- /blog?search=elm&author=evan -> BlogList { search = Just "elm", author = Just "evan", sort = Nothing } -- /blog?sort=popular -> BlogList { search = Nothing, author = Nothing, sort = Just Popular } ``` -------------------------------- ### Type Inference Example for Elm URL Parser Source: https://github.com/elm/url/blob/master/_autodocs/ARCHITECTURE.md Demonstrates type inference for a composed Elm URL parser, showing the expected input types (String, Int) and the resulting output type. ```elm s "user" string s "comment" int -- Type: Parser (String -> Int -> a) a -- Indicates: expects String and Int, produces some value of type a ``` -------------------------------- ### absolute Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-builder.md Creates an absolute URL starting with `/`. Path segments are joined with `/`, and query parameters are automatically percent-encoded. Returns just `/` if both path and parameters are empty. ```APIDOC ## Function: absolute ### Description Creates an absolute URL starting with `/`. Useful for constructing URLs relative to the current origin. ### Parameters #### Path Parameters - **pathSegments** (`List String`) - Required - Path segments as individual strings - **parameters** (`List QueryParameter`) - Required - Query parameters created with `string` or `int` ### Return Type `String` — An absolute URL string starting with `/`. ### Behavior - Path segments are joined with `/` - Query parameters are automatically percent-encoded - Returns just `/` if both path and parameters are empty - Leading slash is always present ### Examples ```elm Url.Builder.absolute [] [] -- "/" Url.Builder.absolute [ "packages", "elm", "core" ] [] -- "/packages/elm/core" Url.Builder.absolute [ "blog", "42" ] [] -- "/blog/42" Url.Builder.absolute [ "products" ] [ Url.Builder.string "search" "hat", Url.Builder.int "page" 2 ] -- "/products?search=hat&page=2" Url.Builder.absolute [ "docs" ] [ Url.Builder.string "q" "what is a list?" ] -- "/docs?q=what%20is%20a%20list%3F" ``` ``` -------------------------------- ### Create Absolute URL Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-builder.md Use `absolute` to create URLs starting with `/`. It joins path segments with `/` and automatically percent-encodes query parameters. Returns just `/` if path and parameters are empty. ```elm Url.Builder.absolute [] [] -- "/" ``` ```elm Url.Builder.absolute [ "packages", "elm", "core" ] [] -- "/packages/elm/core" ``` ```elm Url.Builder.absolute [ "blog", "42" ] [] -- "/blog/42" ``` ```elm Url.Builder.absolute [ "products" ] [ Url.Builder.string "search" "hat", Url.Builder.int "page" 2 ] -- "/products?search=hat&page=2" ``` ```elm Url.Builder.absolute [ "docs" ] [ Url.Builder.string "q" "what is a list?" ] -- "/docs?q=what%20is%20a%20list%3F" ``` -------------------------------- ### fromString Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url.md Attempts to parse a URL string into a `Url` record. The string must start with either `http://` or `https://`. If parsing fails, returns `Nothing`. ```APIDOC ## Function: fromString ### Signature ```elm fromString : String -> Maybe Url ``` ### Description Attempts to parse a URL string into a `Url` record. The string must start with either `http://` or `https://`. If parsing fails, returns `Nothing`. ### Parameters #### Path Parameters - **str** (String) - Required - The URL string to parse ### Return Type `Maybe Url` — A `Url` record if parsing succeeds, `Nothing` if the URL is invalid. ### Parsing Rules - Must start with `http://` or `https://` (case-sensitive) - Host cannot be empty - Userinfo (e.g., `user@host`) is disallowed - Port must be a valid integer after the colon - Path always defaults to `/` if not specified - Query and fragment are kept in percent-encoded form (not decoded) ### Failure Cases - `Nothing` if the string lacks a protocol - `Nothing` if the URL contains userinfo (`@`) - `Nothing` if the host is empty - `Nothing` if the port is not a valid integer ### Examples ```elm Url.fromString "https://example.com:443" -- Just -- { protocol = Https -- , host = "example.com" -- , port_ = Just 443 -- , path = "/" -- , query = Nothing -- , fragment = Nothing -- } Url.fromString "https://example.com/hats?q=top%20hat" -- Just -- { protocol = Https -- , host = "example.com" -- , port_ = Nothing -- , path = "/hats" -- , query = Just "q=top%20hat" -- , fragment = Nothing -- } Url.fromString "http://example.com/core/List/#map" -- Just -- { protocol = Http -- , host = "example.com" -- , port_ = Nothing -- , path = "/core/List/" -- , query = Nothing -- , fragment = Just "map" -- } Url.fromString "example.com:443" -- Nothing (no protocol) Url.fromString "http://tom@example.com" -- Nothing (userinfo not allowed) Url.fromString "http://#cats" -- Nothing (no host) ``` ``` -------------------------------- ### Build Absolute URL with Root Type Source: https://github.com/elm/url/blob/master/_autodocs/types.md Constructs an absolute URL using the Url.Builder.custom function with the Absolute root type. The URL will start with a '/'. ```elm import Url.Builder url1 = Url.Builder.custom Url.Builder.Absolute ["products"] [] Nothing -- "/products" ``` -------------------------------- ### Parsing Multiple Query Parameters in Elm Source: https://github.com/elm/url/blob/master/_autodocs/ARCHITECTURE.md Defines a parser for extracting multiple query parameters into a record. This example shows how to parse a 'q' string and a 'page' integer. ```elm type alias SearchParams = { query : Maybe String, page : Maybe Int } searchParams : Query.Parser SearchParams searchParams = map2 SearchParams (Query.string "q") (Query.int "page") -- Use with path parser: route = map SearchRoute (s "search" query searchParams) ``` -------------------------------- ### Parse Repeated Query Parameters Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Handle query parameters that can appear multiple times. This example shows parsing repeated tags and IDs, as well as comma-separated values. ```elm import Url.Parser.Query as Query -- Parse multiple tags like ?tag=elm&tag=functional&tag=web tags : Query.Parser (List String) tags = Query.custom "tag" identity -- Parse multiple IDs as integers ids : Query.Parser (List Int) ids = Query.custom "id" (List.filterMap String.toInt) -- Parse comma-separated values commaSeparated : String -> Query.Parser (List String) commaSeparated key = Query.custom key <| \values -> case values of [csv] -> String.split "," csv _ -> [] type Route = Items (List Int) | Tagged (List String) routeParser : Parser (Route -> a) a routeParser = oneOf [ map Items (s "items" query ids) , map Tagged (s "tagged" query tags) ] -- Matches: -- /items?id=1&id=2&id=3 -> Items [1, 2, 3] -- /tagged?tag=elm&tag=functional -> Tagged ["elm", "functional"] ``` -------------------------------- ### Parse Complex Routes with Query Filters Source: https://github.com/elm/url/blob/master/_autodocs/README.md Defines a route parser that includes query parameters with type filtering. This example demonstrates parsing a 'products' route with optional search, page, and stock filters. It uses `Url.Parser.Query` for handling query parameters. ```elm import Url.Parser as P import Url.Parser.Query as Q type Route = Products ProductFilters type alias ProductFilters = { search : Maybe String, page : Maybe Int, inStock : Maybe Bool } filters : Q.Parser ProductFilters filters = Q.map3 ProductFilters (Q.string "q") (Q.int "page") (Q.enum "stock" (Dict.fromList [ ("yes", True), ("no", False) ])) route = P.oneOf [ P.map Products (P.s "products" P.query filters) ] ``` -------------------------------- ### apply pattern for more than eight parameters Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser-query.md Demonstrates how to use the `apply` pattern to handle more than eight query parameters by chaining parsers. ```APIDOC ## For More Than Eight Parameters: If you need more than eight parameters, you can use the `apply` pattern: ### Signature ```elm apply : Parser a -> Parser (a -> b) -> Parser b apply argParser funcParser = Query.map2 (<|) funcParser argParser ``` ### Usage with many parameters ```elm import Url.Parser.Query as Query type alias ComplexQuery = ... query : Parser ComplexQuery query = Query.map ComplexQuery (Query.string "p1") |> apply (Query.string "p2") |> apply (Query.string "p3") |> apply (Query.string "p4") |> apply (Query.string "p5") |> apply (Query.string "p6") |> apply (Query.string "p7") |> apply (Query.string "p8") |> apply (Query.string "p9") ``` ``` -------------------------------- ### Provide Default Values for Pagination Parameters Source: https://github.com/elm/url/blob/master/_autodocs/QUERY_PARAMETERS_GUIDE.md Use `Maybe.withDefault` to set default values for pagination parameters like page number and limit when they are not present in the query string. ```elm import Url.Parser.Query as Query type alias PaginationParams = { page : Int , limit : Int } pagination : Query.Parser PaginationParams pagination = Query.map2 PaginationParams (Query.map (Maybe.withDefault 1) (Query.int "page")) (Query.map (Maybe.withDefault 10) (Query.int "limit")) ``` -------------------------------- ### Url.Builder.string / Url.Builder.int Source: https://github.com/elm/url/blob/master/_autodocs/README.md Builds a URL with query parameters using string or integer values. ```APIDOC ## Url.Builder.string / Url.Builder.int ### Description Builds a URL with query parameters using string or integer values. ### Function Signature `Url.Builder.string : String -> String -> Url.QueryParam Url.Builder.int : String -> Int -> Url.QueryParam` ### Example ```elm Builder.absolute ["search"] [Builder.string "q" "elm"] ``` ``` -------------------------------- ### Get URL Query Parameter Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Retrieves the value of a specific query parameter from a given URL. Returns Nothing if the parameter is not found or the URL is malformed. ```elm getQueryParam : String -> Url -> Maybe String getQueryParam paramName url = case parse (query (Query.string paramName)) url of Nothing -> Nothing Just value -> value ``` ```elm getQueryParam "q" (case Url.fromString "https://example.com/search?q=elm" of Ok u -> u) -- Just "elm" ``` -------------------------------- ### Browser Application URL Handling Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md Demonstrates how to integrate `Url.Parser.parse` within a browser application's `init` and `update` functions to handle URL changes and parse the current route. This is crucial for single-page applications. ```elm import Browser import Url exposing (Url) import Url.Parser as P exposing (Parser, () ) type Route = Home | Post Int parser : Parser (Route -> a) a parser = P.oneOf [ P.map Home P.top , P.map Post (P.s "post" P.int) ] type Msg = UrlChanged Url | LinkClicked update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of UrlChanged url -> -- Parse the new URL and update the route let newRoute = P.parse parser url in ... init : Url -> ( Model, Cmd Msg ) init url = -- Parse the initial URL let initialRoute = P.parse parser url in ... ``` -------------------------------- ### Conditionally Parse Filter Values Source: https://github.com/elm/url/blob/master/_autodocs/QUERY_PARAMETERS_GUIDE.md Implement conditional parsing for a parameter like 'filter'. This example accepts a single value or no value, rejecting multiple occurrences of the same parameter. ```elm import Url.Parser.Query as Query -- Parse differently based on filter type filterValue : Query.Parser (Maybe String) filterValue = Query.custom "filter" \values -> case values of [single] -> Just single [] -> Nothing _ -> Nothing -- reject multiple values ``` -------------------------------- ### Url.Builder.custom Source: https://github.com/elm/url/blob/master/_autodocs/README.md Builds a custom URL with specified scheme, path, query parameters, and fragment. ```APIDOC ## Url.Builder.custom ### Description Builds a custom URL with specified scheme, path, query parameters, and fragment. ### Function Signature `Url.Builder.custom : Url.Scheme -> List String -> List String -> Maybe String -> Url.Url` ### Example ```elm Builder.custom Absolute ["docs"] [] (Just "intro") ``` ``` -------------------------------- ### Defining and Parsing Routes Source: https://github.com/elm/url/blob/master/_autodocs/README.md Sets up a routing system for single-page applications by defining a Route type and a parser. This is used within the Browser.application's init and onUrlChange callbacks to map URLs to application states. ```elm -- Define routes, parse URLs in Browser.application type Route = Home | Blog Int route = Url.Parser.oneOf [ Url.Parser.map Home Url.Parser.top , Url.Parser.map Blog (Url.Parser.s "blog" Url.Parser.int) ] -- In init and onUrlChange callbacks: Url.Parser.parse route url ``` -------------------------------- ### Combine String Parser with Path Prefix Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md Shows how to combine the `string` parser with a literal path segment using the `` operator to define a more specific route. ```elm userProfile : Parser (String -> a) a userProfile = s "user" string -- Matches: /user/alice, /user/bob ``` -------------------------------- ### Building a URL String Source: https://github.com/elm/url/blob/master/_autodocs/README.md Constructs an absolute URL string from a list of path segments and query parameters. Query parameters are provided as key-value pairs. ```elm -- Path segments + query params → String Url.Builder.absolute [ "products" ] [ Url.Builder.string "q" "elm" ] -- Result: "/products?q=elm" ``` -------------------------------- ### Execution Source: https://github.com/elm/url/blob/master/_autodocs/FUNCTION_INDEX.md Execute a defined parser against a URL. ```APIDOC ## Execution ### `parse` - **Purpose**: Run a parser on a URL and extract the route. - **Signature**: `Parser (a -> a) a -> Url -> Maybe a` ``` -------------------------------- ### Url.Builder Module - URL Constructors Source: https://github.com/elm/url/blob/master/_autodocs/FUNCTION_INDEX.md Functions for constructing various types of URLs. ```APIDOC ## Url.Builder Module - URL Constructors ### `absolute` #### Description Build absolute URLs starting with `/`. #### Signature `List String -> List QueryParameter -> String` ### `relative` #### Description Build relative URLs without a leading `/`. #### Signature `List String -> List QueryParameter -> String` ### `crossOrigin` #### Description Build full URLs including the protocol and host. #### Signature `String -> List String -> List QueryParameter -> String` ### `custom` #### Description Build URLs with an optional fragment identifier. #### Signature `Root -> List String -> List QueryParameter -> Maybe String -> String` ``` -------------------------------- ### custom Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-builder.md Creates a custom URL with optional control over the fragment (hash). Combines the flexibility of `absolute`, `relative`, and `crossOrigin` with the ability to add a URL fragment. ```APIDOC ## Function: custom ### Description Creates a custom URL with optional control over the fragment (hash). Combines the flexibility of `absolute`, `relative`, and `crossOrigin` with the ability to add a URL fragment. ### Signature ```elm custom : Root -> List String -> List QueryParameter -> Maybe String -> String ``` ### Parameters - `root` (Root) - The type of root: `Absolute`, `Relative`, or `CrossOrigin` with a base URL. - `pathSegments` (List String) - Path segments as individual strings. - `parameters` (List QueryParameter) - Query parameters created with `string` or `int`. - `maybeFragment` (Maybe String) - Optional fragment (the part after `#`). ### Return Type `String` - A URL string with optional fragment. ### Behavior - Constructs the base URL using the `Root` specification. - Appends path segments joined with `/`. - Appends query parameters (percent-encoded). - If a fragment is provided, appends `#` followed by the fragment. ### Examples ```elm Url.Builder.custom Url.Builder.Absolute [ "packages", "elm", "core", "latest", "String" ] [] (Just "length") -- "/packages/elm/core/latest/String#length" Url.Builder.custom Url.Builder.Relative [ "there" ] [ Url.Builder.string "name" "ferret" ] Nothing -- "there?name=ferret" Url.Builder.custom (Url.Builder.CrossOrigin "https://example.com:8042") [ "over", "there" ] [ Url.Builder.string "name" "ferret" ] (Just "nose") -- "https://example.com:8042/over/there?name=ferret#nose" Url.Builder.custom Url.Builder.Absolute [ "docs" ] [ Url.Builder.string "version" "1.0" ] (Just "introduction") -- "/docs?version=1.0#introduction" ``` ``` -------------------------------- ### custom Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser-query.md Creates a custom query parser for advanced use cases. The function receives all values for a given parameter as a list. ```APIDOC ## Function: custom ```elm custom : String -> (List String -> a) -> Parser a ``` Creates a custom query parser for advanced use cases. The function receives all values for a given parameter as a list. ### Parameters - **key** (`String`) - The query parameter name to look for - **func** (`List String -> a`) - A function that processes the list of values and returns a result **Return Type:** `Parser a` — A parser that applies the function to the list of parameter values. **Behavior:** - If the parameter is not present, the function receives an empty list - If the parameter appears once, the function receives a list with one element - If the parameter appears multiple times, the function receives a list with all values - The function is always called, even if the list is empty **Use Cases:** - Handling repeated parameters (e.g., `?id=2&id=7`) - Custom validation or filtering - Complex transformations **Examples:** ```elm import Url.Parser.Query as Query -- Handle multiple values for the same parameter posts : Parser (List Int) posts = Query.custom "post" (List.filterMap String.toInt) -- Query string: ?post=2 -- Result: [2] -- Query string: ?post=2&post=7 -- Result: [2, 7] -- Query string: ?post=2&post=x -- Result: [2] -- Query string: ?hats=2 -- Result: [] -- Custom validation tags : Parser (List String) tags = Query.custom "tag" identity -- Query string: ?tag=elm&tag=functional&tag=web -- Result: ["elm", "functional", "web"] -- Comma-separated values in a single parameter commaSeparated : Parser (List String) commaSeparated = Query.custom "items" <| \values -> case values of [comma_separated] -> String.split "," comma_separated _ -> [] -- Query string: ?items=apple,banana,cherry -- Result: ["apple", "banana", "cherry"] ``` **Source:** `src/Url/Parser/Query.elm:152` ``` -------------------------------- ### Combine Parsers Sequentially with Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md Use the operator to chain parsers, matching path segments one after another. Both parsers must succeed for the combined parser to succeed. The result of the first parser is passed to the second. ```elm import Url.Parser exposing (Parser, string, int, s, () ) -- Two parsers in sequence userBlog : Parser (String -> Int -> a) a userBlog = s "user" string s "blog" int -- Matches: /user/alice/blog/42 ==> Just ("alice", 42) -- Fails: /user/alice ==> Nothing -- Fails: /user/alice/posts/42 ==> Nothing -- Three or more parsers comment : Parser (String -> Int -> Int -> a) a comment = s "user" string s "comment" int s "reply" int -- Matches: /user/bob/comment/42/reply/7 ``` -------------------------------- ### Url.Builder Module - Query Parameter Functions Source: https://github.com/elm/url/blob/master/_autodocs/FUNCTION_INDEX.md Functions for creating and converting URL query parameters. ```APIDOC ## Url.Builder Module - Query Parameter Functions ### `string` #### Description Create an encoded string query parameter. #### Signature `String -> String -> QueryParameter` ### `int` #### Description Create an encoded integer query parameter. #### Signature `String -> Int -> QueryParameter` ### `toQuery` #### Description Convert a list of `QueryParameter`s into a query string. This conversion is automatic when building URLs. #### Signature `List QueryParameter -> String` ``` -------------------------------- ### URL Building Flow in Elm Source: https://github.com/elm/url/blob/master/_autodocs/ARCHITECTURE.md Details the process of constructing a string URL from path segments, query parameters, and a fragment using Elm's Url.Builder functions, with automatic percent-encoding. ```elm Path segments: List String Query parameters: List QueryParameter Fragment: Maybe String ↓ Url.Builder functions (absolute, relative, crossOrigin, custom) ↓ String URL (with automatic percent-encoding) ``` -------------------------------- ### Handling More Than Eight Parameters with apply Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser-query.md For URLs with more than eight query parameters, use the `apply` pattern in conjunction with `map2` and `map`. This allows for a flexible way to chain parsers for an arbitrary number of parameters. ```elm apply : Parser a -> Parser (a -> b) -> Parser b apply argParser funcParser = Query.map2 (<|) funcParser argParser -- Usage with many parameters type alias ComplexQuery = ... query : Parser ComplexQuery query = Query.map ComplexQuery (Query.string "p1") |> apply (Query.string "p2") |> apply (Query.string "p3") |> apply (Query.string "p4") |> apply (Query.string "p5") |> apply (Query.string "p6") |> apply (Query.string "p7") |> apply (Query.string "p8") |> apply (Query.string "p9") ``` -------------------------------- ### string Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md A primitive parser that matches any non-empty path segment and captures it as a String. It skips empty segments and returns Nothing for the root path. ```APIDOC ## string ### Description A primitive parser that matches any non-empty path segment and captures it as a `String`. It skips empty segments (e.g., trailing slashes) and returns `Nothing` when encountering the root path `/`. ### Function Signature ```elm string : Parser (String -> a) a ``` ### Examples ```elm import Url.Parser exposing (Parser, string) -- Matches: /alice/ ==> Just "alice" -- Matches: /bob ==> Just "bob" -- Matches: /42/ ==> Just "42" -- Fails: / ==> Nothing userProfile : Parser (String -> a) a userProfile = s "user" string -- Matches: /user/alice, /user/bob ``` ``` -------------------------------- ### () Operator Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md Combines a path parser with a query parser, allowing for parsing of both the path and query string in a single operation. The path segments are parsed first, followed by the query parameters. Both must succeed for the combined parser to succeed, but query parameters are optional. ```APIDOC ## () Operator ### Description Combines a path parser with a query parser. Allows parsing both the path and query string in a single parser. ### Method N/A (Operator) ### Endpoint N/A (Operator) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```elm import Url.Parser exposing (Parser, int, s, map, oneOf, () , ()) import Url.Parser.Query as Query type Route = Overview (Maybe String) | Post Int blog : Parser (Route -> a) a blog = oneOf [ map Overview (s "blog" Query.string "q") , map Post (s "blog" int) ] ``` ### Response #### Success Response - **Type:** `Parser a b` - **Description:** A combined parser for path and query. #### Response Example ``` -- Results: -- /blog/ ==> Just (Overview Nothing) -- /blog/?q=wolf ==> Just (Overview (Just "wolf")) -- /blog/42 ==> Just (Post 42) -- /blog/42?q=wolf ==> Just (Post 42) ``` ``` -------------------------------- ### Url.Builder Module Type Signatures Source: https://github.com/elm/url/blob/master/_autodocs/README.md Signatures for building absolute, relative, and cross-origin URLs, including custom URL construction and query parameter handling. ```elm absolute : List String -> List QueryParameter -> String ``` ```elm relative : List String -> List QueryParameter -> String ``` ```elm crossOrigin : String -> List String -> List QueryParameter -> String ``` ```elm custom : Root -> List String -> List QueryParameter -> Maybe String -> String ``` ```elm string : String -> String -> QueryParameter ``` ```elm int : String -> Int -> QueryParameter ``` ```elm toQuery : List QueryParameter -> String ``` -------------------------------- ### Build Cross-Origin URL with Root Type Source: https://github.com/elm/url/blob/master/_autodocs/types.md Constructs a full URL with protocol and host using the Url.Builder.custom function and the CrossOrigin root type. Requires a base URL string. ```elm import Url.Builder url3 = Url.Builder.custom (Url.Builder.CrossOrigin "https://example.com") ["products"] [] Nothing -- "https://example.com/products" ``` -------------------------------- ### Programmatically Navigate with Browser.Navigation Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Change the browser's URL from within an Elm update function. Requires importing `Browser.Navigation` and using `pushUrl` with a navigation key and a generated URL. ```elm import Browser.Navigation as Nav type Msg = GoHome | GoToBlog Int | GoToSearch String update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of GoHome -> ( model, Nav.pushUrl model.key (Builder.absolute [] []) ) GoToBlog id -> ( model, Nav.pushUrl model.key (Builder.absolute [ "blog", String.fromInt id ] []) ) GoToSearch query -> ( model, Nav.pushUrl model.key (searchLink query 1) ) ``` -------------------------------- ### Url.Parser.s / Url.Parser.string / Url.Parser.int Source: https://github.com/elm/url/blob/master/_autodocs/README.md Defines path parsers for string literals, strings, and integers. ```APIDOC ## Url.Parser.s / Url.Parser.string / Url.Parser.int ### Description Defines path parsers for string literals, strings, and integers. ### Function Signature `Url.Parser.s : String -> Url.Parser.Parser ()` `Url.Parser.string : Url.Parser.Parser String` `Url.Parser.int : Url.Parser.Parser Int` ### Example ```elm s "blog" int ``` ``` -------------------------------- ### Parse URLs with Default Query Parameters Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Define a parser that combines path and query parameter parsing, providing default values for missing parameters. This is useful for handling optional query string values gracefully. ```elm import Url.Parser.Query as Query type Route = SearchResults SearchParams | NotFound type alias SearchParams = { query : String , page : Int , perPage : Int } -- Define defaults inline using map searchParams : Query.Parser SearchParams searchParams = Query.map3 SearchParams (Query.map (Maybe.withDefault "") (Query.string "q")) (Query.map (Maybe.withDefault 1) (Query.int "page")) (Query.map (Maybe.withDefault 10) (Query.int "per_page")) routeParser : Parser (Route -> a) a routeParser = oneOf [ map SearchResults (s "search" query searchParams) ] -- Usage: -- /search -> SearchResults { query = "", page = 1, perPage = 10 } -- /search?q=elm -> SearchResults { query = "elm", page = 1, perPage = 10 } -- /search?q=elm&page=2 -> SearchResults { query = "elm", page = 2, perPage = 10 } -- /search?q=elm&page=2&per_page=20 -> SearchResults { query = "elm", page = 2, perPage = 20 } ``` -------------------------------- ### Try Multiple Parsers with oneOf Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md Use `oneOf` to try a list of parsers in order. The first one to succeed determines the result. Place more specific patterns earlier in the list. ```elm import Url.Parser exposing (Parser, string, int, s, map, oneOf, () ) type Route = Topic String | Blog Int | User String | Comment String Int route : Parser (Route -> a) a route = oneOf [ map Topic (s "topic" string) , map Blog (s "blog" int) , map User (s "user" string) , map Comment (s "user" string s "comment" int) ] -- Results: -- /topic/wolf ==> Just (Topic "wolf") -- /blog/42 ==> Just (Blog 42) -- /user/sam/ ==> Just (User "sam") -- /user/bob/comment/42 ==> Just (Comment "bob" 42) -- /unknown ==> Nothing ``` -------------------------------- ### Build Absolute URL with Query Parameters Source: https://github.com/elm/url/blob/master/_autodocs/README.md Constructs an absolute URL with specified path segments and query parameters. This is useful for creating links to external resources or specific API endpoints. Note the automatic URL encoding of parameter values. ```elm import Url.Builder as Builder url = Builder.absolute [ "search" ] [ Builder.string "q" "elm programming" , Builder.int "page" 2 ] -- Result: "/search?q=elm%20programming&page=2" ``` -------------------------------- ### Create Integer Query Parameter Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-builder.md Creates a percent-encoded query parameter with an integer value. This is a convenience function equivalent to using `string` with `String.fromInt`. The key is percent-encoded, while the integer is converted to a string as-is. ```elm Url.Builder.absolute [ "products" ] [ Url.Builder.string "search" "hat", Url.Builder.int "page" 2 ] -- "/products?search=hat&page=2" ``` ```elm Url.Builder.absolute [ "blog", "42" ] [ Url.Builder.int "offset" 10, Url.Builder.int "limit" 20 ] -- "/blog/42?offset=10&limit=20" ``` -------------------------------- ### oneOf Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser.md Tries multiple parsers in order, returning the result of the first one that succeeds. If multiple parsers could match, the first in the list wins. ```APIDOC ## Function: oneOf ```elm oneOf : List (Parser a b) -> Parser a b ``` Tries multiple parsers in order, returning the result of the first one that succeeds. If multiple parsers could match, the first in the list wins. ### Parameters - `parsers` (List (Parser a b)) - A list of parsers to try ### Return Type `Parser a b` — A parser that attempts each parser in sequence. ### Behavior - Parsers are attempted in list order - Returns `Just result` from the first successful parser - Returns `Nothing` if all parsers fail - Order matters—more specific patterns should come before general ones ### Examples ```elm import Url.Parser exposing (Parser, string, int, s, map, oneOf, () ) type Route = Topic String | Blog Int | User String | Comment String Int route : Parser (Route -> a) a route = oneOf [ map Topic (s "topic" string) , map Blog (s "blog" int) , map User (s "user" string) , map Comment (s "user" string s "comment" int) ] -- Results: -- /topic/wolf ==> Just (Topic "wolf") -- /blog/42 ==> Just (Blog 42) -- /user/sam/ ==> Just (User "sam") -- /user/bob/comment/42 ==> Just (Comment "bob" 42) -- /unknown ==> Nothing ``` **Best Practice:** Place more specific patterns earlier. For instance, `Comment` is more specific than `User`, so it should come first. **Source:** `src/Url/Parser.elm:248` ``` -------------------------------- ### Combine Path and Query Parameters for Routing Source: https://github.com/elm/url/blob/master/_autodocs/QUERY_PARAMETERS_GUIDE.md Use this snippet to define routes that include both path segments and query parameters. It maps query parameters like 'q' and 'page' to a `SearchParams` record. ```elm import Url.Parser exposing (Parser, () , ()) import Url.Parser.Query as Query type Route = SearchResults SearchParams | NotFound type alias SearchParams = { query : Maybe String , page : Maybe Int } searchParams : Query.Parser SearchParams searchParams = Query.map2 SearchParams (Query.string "q") (Query.int "page") route : Parser (Route -> a) a route = Url.Parser.oneOf [ Url.Parser.map SearchResults (Url.Parser.s "search" searchParams) ] -- Matches: -- /search?q=elm&page=2 → SearchResults { query = Just "elm", page = Just 2 } -- /search?q=elm → SearchResults { query = Just "elm", page = Nothing } -- /search → SearchResults { query = Nothing, page = Nothing } ``` -------------------------------- ### Build Cross-Origin Links with Elm Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Utilize `Url.Builder.crossOrigin` to construct URLs for external services, APIs, or documentation sites. This is essential for integrating with third-party resources. ```elm import Url.Builder as Builder -- API endpoints apiBase : String apiBase = "https://api.example.com" getUser : Int -> String getUser userId = Builder.crossOrigin apiBase [ "v1", "users", String.fromInt userId ] [] searchAPI : String -> Int -> String searchAPI query page = Builder.crossOrigin apiBase [ "v1", "search" ] [ Builder.string "q" query , Builder.int "page" page ] -- External documentation links elmDocsLink : String -> String elmDocsLink module_ = Builder.crossOrigin "https://package.elm-lang.org" [ "packages", "elm", "core", "latest", module_ ] [] -- Results: -- getUser 42 -- -> "https://api.example.com/v1/users/42" -- searchAPI "elm" 2 -- -> "https://api.example.com/v1/search?q=elm&page=2" -- elmDocsLink "String" -- -> "https://package.elm-lang.org/packages/elm/core/latest/String" ``` -------------------------------- ### URL Parsing Flow in Elm Source: https://github.com/elm/url/blob/master/_autodocs/ARCHITECTURE.md Illustrates the step-by-step process of parsing a string URL into a structured record and then into typed route data using Elm's Url module. ```elm String URL ↓ Url.fromString ↓ Url record { protocol, host, port_, path, query, fragment } ↓ Url.Parser.parse (with Url.Parser and Url.Parser.Query parsers) ↓ Typed Route / Application Data ``` -------------------------------- ### Generate Type-Safe Blog Post URL Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Constructs a relative URL string for a blog post using a typed route segment. Ensures consistency in URL structure. ```elm -- Define path segments as typed records type alias BlogRoute = Int -- Helper functions ensure consistency blogPostPath : BlogRoute -> String blogPostPath postId = Builder.relative [ "blog", String.fromInt postId ] [] ``` -------------------------------- ### Convert Protocol to String Source: https://github.com/elm/url/blob/master/_autodocs/types.md Pattern matches on the Protocol type to return its string representation. Useful for constructing full URLs. ```elm protocolString : Protocol -> String protocolString protocol = case protocol of Http -> "http://" Https -> "https://" ``` -------------------------------- ### Url.Builder.absolute Source: https://github.com/elm/url/blob/master/_autodocs/README.md Builds an absolute URL with the given path segments. ```APIDOC ## Url.Builder.absolute ### Description Builds an absolute URL with the given path segments. ### Function Signature `Url.Builder.absolute : List String -> List String -> Url.Url` ### Example ```elm Builder.absolute ["blog"] [] ``` ``` -------------------------------- ### Create Custom URL with Fragment Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-builder.md Constructs a custom URL with optional control over the fragment (hash). Combines the flexibility of `absolute`, `relative`, and `crossOrigin` with the ability to add a URL fragment. ```elm Url.Builder.custom Url.Builder.Absolute [ "packages", "elm", "core", "latest", "String" ] [] (Just "length") ``` ```elm Url.Builder.custom Url.Builder.Relative [ "there" ] [ Url.Builder.string "name" "ferret" ] Nothing ``` ```elm Url.Builder.custom (Url.Builder.CrossOrigin "https://example.com:8042") [ "over", "there" ] [ Url.Builder.string "name" "ferret" ] (Just "nose") ``` ```elm Url.Builder.custom Url.Builder.Absolute [ "docs" ] [ Url.Builder.string "version" "1.0" ] (Just "introduction") ``` -------------------------------- ### Building a Single-Page App Router with Elm Parsers Source: https://github.com/elm/url/blob/master/_autodocs/ARCHITECTURE.md Defines a route parser for a single-page application. Use this in your init and update functions to parse the current URL into a Route type. ```elm type Route = Home | BlogPost Int | NotFound routeParser : Parser (Route -> a) a routeParser = oneOf [ map Home top , map BlogPost (s "blog" int) ] -- In init and update: let route = parse routeParser url ``` -------------------------------- ### Build URLs with Query Parameters Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Generate URLs programmatically using Url.Builder. This pattern is essential for creating dynamic links within your Elm application, especially when query parameters are involved. ```elm import Url.Builder as Builder -- Build links homeLink : String homeLink = Builder.absolute [] [] blogLink : Int -> String blogLink postId = Builder.absolute [ "blog", String.fromInt postId ] [] searchLink : String -> Int -> String searchLink query page = Builder.absolute [ "search" ] [ Builder.string "q" query , Builder.int "page" page ] -- Usage in HTML import Html exposing (a, text) import Html.Attributes exposing (href) viewSearchLink : Html msg viewSearchLink = a [ href (searchLink "elm" 1) ] [ text "Search for Elm" ] -- Results in: Search for Elm ``` -------------------------------- ### string Function Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-builder.md Creates a percent-encoded query parameter with string values for use in URL construction. ```APIDOC ## Function: string ```elm string : String -> String -> QueryParameter ``` Creates a percent-encoded query parameter with string values. ### Parameters - **key** (`String`) - The parameter name (automatically percent-encoded) - **value** (`String`) - The parameter value (automatically percent-encoded) ### Return Type `QueryParameter` — A query parameter ready to use with builder functions. ### Behavior - Both key and value are percent-encoded using `Url.percentEncode` - Can be used with `absolute`, `relative`, `crossOrigin`, or `custom` - Spaces and special characters are automatically escaped ### Examples ```elm Url.Builder.absolute [ "products" ] [ Url.Builder.string "search" "hat" ] -- "/products?search=hat" Url.Builder.absolute [ "products" ] [ Url.Builder.string "search" "coffee table" ] -- "/products?search=coffee%20table" Url.Builder.absolute [ "search" ] [ Url.Builder.string "q" "what is this?" ] -- "/search?q=what%20is%20this%3F" ``` ``` -------------------------------- ### Create Pretty URLs with Path Segments in Elm Source: https://github.com/elm/url/blob/master/_autodocs/USAGE_PATTERNS.md Construct user-friendly and SEO-optimized URLs using path segments for hierarchical data like blog posts. This pattern is suitable when the URL structure reflects the resource hierarchy. ```elm -- Pretty URLs using path segments (better for SEO, user-friendly) blogLink : String -> Int -> String blogLink author postId = Builder.absolute [ "blog", author, String.fromInt postId ] [] ``` -------------------------------- ### Define a Query Parser for a String Source: https://github.com/elm/url/blob/master/_autodocs/api-reference/url-parser-query.md Creates a parser for a string query parameter. Returns `Just value` if the parameter appears exactly once with a non-empty value, and `Nothing` otherwise (e.g., not present, appears multiple times, or has an empty value). ```elm import Url.Parser.Query as Query search : Parser (Maybe String) search = Query.string "search" ```