Title: CSS Route Matching
Status: ED
Work Status: Exploring
Shortname: css-navigation
Level: 1
Group: csswg
ED: https://drafts.csswg.org/css-navigation-1/
!Issue Tracking: w3c/csswg-drafts#12594
Editor: L. David Baron, Google https://www.google.com/, https://dbaron.org/, w3cid 15393
Editor: Noam Rosenthal, Google https://www.google.com/, w3cid 121539
Abstract: This module contains conditional CSS rules for styling conditioned on the current URL
        or conditioned on the status of navigating between particular URLs.
url: https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-navigationtransition-from
    type: dfn; spec: html; text: from entry;
url: https://html.spec.whatwg.org/multipage/nav-history-apis.html#window-navigation-api
    type: dfn; spec: html; text: navigation API;
url: https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-current-entry
    type: dfn; spec: html; text: current entry; for: navigation API;
url: https://html.spec.whatwg.org/multipage/nav-history-apis.html#ongoing-navigate-event
    type: dfn; spec: html; text: ongoing navigate event;
url: https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-navigation-transition
    type: dfn; spec: html; text: transition;
url: https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-activation
    type: dfn; spec: html; text: activation;
url: https://html.spec.whatwg.org/multipage/browsing-the-web.html#has-been-revealed
    type: dfn; spec: html; text: has been revealed;
url: https://html.spec.whatwg.org/multipage/browsing-the-web.html#ongoing-navigation
    type: dfn; spec: html; text: ongoing navigation;
url: https://drafts.csswg.org/css-view-transitions-1/#capture-the-image
    type: dfn; spec: css-view-transitions-1; text: capture the image;

Defining URL patterns in CSS

The <> value type

<> = <> | <> | <>
<> = <>
A <> is defined to match a [=/URL=]-or-null input if input is non-null, and:
: the <> is a <> :: [=URL pattern/match|match a URL pattern=] is non-null given urlPattern as the [=URL pattern=] represented by the ''@route'' rule referenced by the name and input as input. : the <> is a <> :: [=URL pattern/match|match a URL pattern=] is non-null given urlPattern as the [=URL pattern=] represented by the function (see [=create a URL pattern for url-pattern()=]) and input as input. : the <> is a <> :: The given [=/URL=] [=url/equals=] input.

Declaring named URL patterns: the ''@route'' rule

The @route rule is an at-rule that associates an author-defined name with a [=URL pattern=]. This name can be referenced in ''@navigation'' rules and in '':active-navigation()'' pseudo-classes. The syntax of the ''@route'' rule is described by the <> production in:
<> = @route <> { <> }
This means that the rule accepts a sequence of descriptors that have the syntax of declarations. However, in valid style sheets the only descriptors must match the <> production below. Any other descriptors are ignored.
<> = <> |
                     <> |
                     <>
<> = pattern : <>
<> = <> : <>
<> = protocol | hostname | port | pathname |
                         search | hash
<> = base-url : stylesheet | document | <>
If two valid descriptors in a single rule have the same name, the last one is used and the others are ignored. If a rule has both a valid <> and a valid <> then it is ignored. The ''@route'' rule can be defined in one of two ways: : with the pattern descriptor :: in this case the URL pattern represented is the result of invoking [=create a URL pattern for url-pattern()=] given arg as the argument to the ''url-pattern()'' function and baseURLSpecifier as the (optional) value of the rule's <>. : with the other descriptors named by <> :: In this case the URL pattern represented is the result of invoking [=URL pattern/create|create a URL pattern=] given input as {{URLPatternInit}} constructed from the descriptors and their values. Each dictionary member is given the value of the descriptor with the same name, except the baseURL member is given the result of [=create a URL for a base descriptor=] given baseURLSpecifier as the (optional) value of the rule's <>. ISSUE: Should this use <>, <>, or <> for the route names? ISSUE: Should we use base-url or just base as the descriptor name? NOTE: The list of allowed init descriptors does not include username or password since they seem unlikely to be useful.
It's possible that this syntax with init descriptors in the ''@route'' rule would make more sense as part of the ''url-pattern()'' function (that is, as an alternate syntax for what goes inside the function). This would also give us the option to remove the braces from the syntax of the ''@route'' rule and make it more like ''@import'' or ''@namespace''. This does remove a potential future extensibility point, but it could also be added back later if we need it.
Either this rule:
@route --movie-list {
  pattern: url-pattern("/movies");
}
or this rule:
@route --movie-list {
  pathname: "/movies";
}
define an ''@route'' rule that associates the name --movie-list with the URL "/movies" resolved relative to the style sheet.
NOTE: The bracing syntax also allows for future expansion if needed. NOTE: Some of the design discussion for this feature has been in w3c/csswg-drafts#12594.

The ''url-pattern()'' function

The url-pattern() function represents a [=URL pattern=], which can be used to match URLs.
<> = url-pattern( <> )
This function represents the [=URL pattern=] resulting from invoking [=create a URL pattern for url-pattern()=] with its string argument. The syntax used in the ''url-pattern()'' function follows that of [=URL Pattern=]. It is a [=pattern string=] directly based on the syntax used by the popular path-to-regexp JavaScript library.
Pattern strings can contain capture groups, which by default match the shortest possible string, up to a component-specific separator (/ in the pathname, . in the hostname). For example, the pathname pattern "/movies/:id" will match "/movies/123" but not "/movies/123/cast". A regular expression enclosed in parentheses can also be used instead, so the pathname pattern "/blog/:id(\\d+)" will match "/movies/123" but not "/movies/css". You may also omit the name of the capture group by using only a regular expression, for example "/blog/(\\d+)". A group can also be made optional by using the ? modifier or by wrapping it in braces. For example, the patterns "/movies/:id?" and "/movies{/:id}" will match both "/movies" and "/movies/123" (but not "/movies/"). A full wildcard * can also be used to match as much as possible, as in the pattern "/*/movies". This too can be given a name, for example "/*lang/movies".
The steps of the create a URL pattern for url-pattern() algorithm, given a string arg and an optional baseURLSpecifier which can be ''document'', ''stylesheet'', or a URL, are: 1. Let baseURL be the result of [=create a URL for a base descriptor=] given baseURLSpecifier. 1. Return the result of [=URL pattern/create|create a URL pattern=] given arg, baseURL, and an empty [=map=]. NOTE: This function requires that its argument is quoted. This differs from the ''url()'' function, which allows its argument to be quoted or unquoted. The create a URL for a base descriptor algorithm, given an optional baseURLSpecifier which can be ''document'', ''stylesheet'', or a URL, is:
: if baseURLSpecifier is not present or is ''stylesheet'' :: the [=style resource base URL=] of the rule or declaration block containing the ''url-pattern()'' function. : if baseURLSpecifier is ''document'' :: the [=document base URL=] of the document : if baseURLSpecifier is a URL :: baseURLSpecifier
This rule:
@route --movie-detail {
  pattern: url-pattern("/movies/:id");
}
defines an ''@route'' rule that associates the name --movie-detail with any URL that matches the [=URL pattern=] /movies/:id. Any of the following URLs (relative to the style sheet) match:
  • /movies/123
  • /movies/456
  • /movies/something
These URLs will not match:
  • /movies/123/ — The trailing slash is not matched by the pattern
  • /movies/456/extra — The /extra is not matched by the pattern
To have the --movie-details route match only numeric :id values, define the route eiter as:
@route --movie-detail {
  pattern: url-pattern("/movies/:id(\\d+)");
}
or as:
@route --movie-detail {
  pattern: url-pattern("/movies/(\\d+)");
}
This way, /movies/something won’t be matched by the route. NOTE: Even though the capture groups are not currently exposed, it is recommended to give the capture groups a name for future use.
Should the default always be ''stylesheet''? For use of ''url-pattern()'' in ''@navigation'', it's likely more useful for the base URL to be the document URL rather than the style sheet URL. However, it would be very awkward for ''url-pattern()'' to be inconsistent with ''url()''. Also see other proposed uses of {{URLPattern}} in CSS in , for '':local-link''.
To serialize a ''url-pattern()'' function f, [=serialize a function=] f, using [=serialize a string=] on the single argument to serialize f's contents. NOTE: This is defined this way because {{URLPattern}} intentionally does not provide a serialization. This specification defines a new '':link-to()'' functional pseudo-class that matches link elements that link to a certain URL.
A simple example of a '':link-to()'' selector is this one, which matches any links that link to the site's homepage:
:link-to(url-pattern("/")) {
  font-weight: bold;
}
Passing in a named route is also possible:
@route --homepage {
  pattern: url-pattern("/");
}

:link-to(--homepage) {
  font-weight: bold;
}
Because there is no dynamic part in the homepage URL, you might be tempted to pass in a <> directly:
:link-to(url("/")) {
  font-weight: bold;
}
However, url("/") won't match URLs such as /#scroll-to-here or /?utm_id=something so it is recommended to use the <> or <> variants, or use the following alternative:
@route --homepage {
  pathname: "/";
  base-url: document;
}

:link-to(--homepage) {
  font-weight: bold;
}
The '':link-to()'' pseudo-class takes a single argument, a <>, and the pseudo-class matches any element where both: * the element matches '':any-link'' * the <> [=route-location/matches=] the target of the link

The '':active-navigation()'' pseudo-class

This specification defines a new '':active-navigation()'' functional pseudo-class that matches link elements that link to a certain URL that is related to a navigation that is currently active. The '':active-navigation()'' pseudo-class takes a single argument, a <>, and the pseudo-class matches any element where: * the element matches '':any-link'' * the target of the link matches the <>, as defined below.
<> =
  <>? [ <> | link-href ]?
<> = at | with | from | to
ISSUE: Should we use ''at''/''with''/''from''/''to'' or ''current''/''other''/''from''/''to''? An <> matches the target linkTarget of the link when the following steps return true: 1. Let navigationURL be the [=current navigation URL=] of the document given the <> in <> (default ''with''). 1. If navigationURL is null, return false. 1. If ''link-href'' is present, or a <> is not provided: 1. Return true if linkTarget [=url/equals=] navigationURL; Otherwise false. 1. If a <> is present: 1. Let targetMatchResult be the result of [=URL pattern/match|matching a URL pattern=] given urlPattern and linkTarget. 1. Let navigationMatchResult be the result of [=URL pattern/match|matching a URL pattern=] given urlPattern and navigationURL. 1. If navigationMatchResult or targetMatchResult is null, return false. 1. For each property prop of {{URLPatternResult}} that is a {{URLPatternComponentResult}}: 1. If {{URLPatternComponentResult/groups}} of prop of targetMatchResult is not equal to {{URLPatternComponentResult/groups}} of prop of navigationMatchResult, then return false. ISSUE: Need to formally define equality of ordered maps. 1. Return true.
The difference between '':link-to()'' and '':active-navigation()'' is that the latter is only active while a navigation is in progress. Consider this example:
@route --homepage {
  pattern: url-pattern("/");
}

:link-to(--homepage) {
  color: lime;
}

:active-navigation(--homepage) {
  color: hotpink;
}
Links that link to the --homepage get a lime color. When navigating to or from the --homepage, their color changes to hotpink for as long as the animation is active. Once the navigation has completed, the '':active-navigation()'' selector no longer applies, and those links revert back to lime.
In the following examples, all links that link to the --movie-detail route, get a lime color when a navigation is in progress.
@route --movie-detail {
  pattern: url-pattern("/movies/:id");
}

:active-navigation(--movie-detail) {
  color: lime;
}
By adding the following selectors that use a <>, the behavior changes a bit.
:active-navigation(from --movie-detail) {
  color: hotpink;
}

:active-navigation(to --movie-detail) {
  color: yellow;
}
When navigating from /movies/1 to /movies/2:
  • Links that link to the --movie-detail route with any :id get a lime color during the navigation.
  • Links that link to the --movie-detail route whose target is /movies/1 (the “from” page) get a hotpink color during the navigation.
  • Links that link to the --movie-detail route whose target is /movies/2 (the “to” page) get a yellow color during the navigation.
When navigating from /movies/2 to /:
  • Links that link to the --movie-detail route with any :id get a lime color during the navigation.
  • Links that link to the --movie-detail route whose target is /movies/3 (the “from” page) get a hotpink color during the navigation.
When navigating from / to /movies/3:
  • Links that link to the --movie-detail route with any :id get a lime color during the navigation.
  • Links that link to the --movie-detail route whose target is /movies/3 (the “to” page) get a yellow color during the navigation.
A an example of the '':active-navigation()'' pseudo-class is this example which creates a view transition between a item in a list that contains a link (in this document) and the details page for that link (in a different document). This transition works even when the navigation is a back/forward navigation and even if the user has used a language selector UI to change the page into a different language (and thus change the URL). The use of the '':link-to()'' pseudo-class ensures that the view transition animations from or to the correct item in the list by matching the relevant parts of the navigation URL to the link URL.
@view-transition {
  /* allow cross-document view transitions */
  navigation: auto;
}

@route --movie-detail {
  /* match URLs like /en/movies/123 which is the English page
     about a movie with ID 123.  Be careful to specify the
     language part with a "*" but the ID part with a named
     :id parameter so that matching will require equal IDs
     but allow differences of language. */
  pattern: url-pattern("/*/movies/:id");
}

/* capture the overall area representing the movie, and a
   sub-area for its poster image */

/* match an element with class movie-container with a child
   link that links to a movie whose id is the same as the
   movie we are currently navigating to or from.  (lang can
   be different, though.)

   This depends on the --movie-detail route
   declaring the ID but not the language with a named
   parameter, and the use of the 'with' keyword.

   This means that both the of the link and the other URL of
   the current navigation match the URL pattern defined by
   the "@route --movie-detail" rule, and that the
   id named group from both matches be the same.  (However,
   the URLs can be different because the * part of the
   match, containing the language, can be different.)
   */
.movie-container:has(
    > .movie-title:active-navigation(with --movie-detail)) {

  view-transition-name: movie-container;

  > .movie-poster {
    view-transition-name: movie-poster;
  }

  /* leave the default cross-fade animation for both image
     captures */
}
NOTE: Some of the design discussion for this feature has been in w3c/csswg-drafts#13163. This specification defines a new '':trigger-link'' that matches link elements that trigger the current navigation. The '':trigger-link'' pseudo-class matches any element where both: * the element matches '':any-link'' * the [=current navigation state=] is not null, and element is its [=navigation state/source element=]. Issue: should this apply to forms or submit buttons?
A simple example of a '':trigger-link'' selector is this one, which sets the ''view-transition-name'' for an image thumbnail that is a child of the link that triggers the current navigation.
:trigger-link .thumb {
  view-transition-name: active-image;
}

Conditional rules for navigation queries

Navigation queries: the ''@navigation'' rule

The @navigation rule is a conditional group rule whose condition tests characteristics of the current URL or of the state of navigation between two URLs. These queries are called navigation queries. Authors can use it to: * write style sheets that apply to multiple pages but behave somewhat differently between those pages, * write style sheets that apply to single page applications that change their URL over time, so that style changes when the URL changes, and * write style sheets that declaratively start view transitions (or make other appropriate style changes) in response to navigations. The syntax of the condition in the ''@navigation'' rule is similar to that defined for <> in [[CSS-CONDITIONAL-3]]. Negation, conjunction, and disjunction are all needed so that authors can specify the interaction of multiple styles in ways that are most intuitive and require the simplest code.
The ''@navigation'' rule can be used in simple cases to define styles that only affect a particular page:
@navigation (at: url-pattern("/")) {
  /* These styles only apply to the site's homepage
     (including any URL with a search or hash). */
}
The ''@navigation'' rule can also be used to define styles that are used when a certain navigation is in progress. This is particularly useful for defining styles that cause [=view transitions=].
@route --search-results-page {
  pattern: url-pattern("/search-results");
}
@route --product-page {
  pattern: url-pattern("/product/:id");
}

@navigation (from: --search-results-page) and
            (to: --product-page) {
  /* These styles apply when a navigation is in progress
     from a search results page to a product page (as
     defined by the @route rules above), but not in the
     reverse direction. */
}

@navigation (between: --search-results-page and --product-page) {
  /* These styles apply when a navigation is in progress
     between a search results page and a product page (as
     defined by the @route rules above), in either
     direction. */
}
The syntax of the ''@navigation'' rule is:
@navigation <> {
  <>
}
with <> defined as:
<> = not <>
                     | <> [ and <> ]*
                     | <> [ or <> ]*
<> = ( <> ) | ( <> ) | <>
<> = <> |
                    <> |
                    <> |
                    <>

<> = <> : <>
<> = at | with | from | to

<> =
    between : <> and <>

<> = history : <>
<> = traverse | back | forward | reload

<> = phase : <>
<> = loading | ready | committed
ISSUE: Should we use ''at''/''with''/''from''/''to'' or ''current''/''other''/''from''/''to''? The above grammar is purposely very loose for forwards-compatibility reasons, since the <> production allows for substantial future extensibility. Any ''@navigation'' rule that does not parse according to the grammar above (that is, a rule that does not match this loose grammar which includes the <> production) is invalid. Style sheets must not use such a rule and processors must ignore such a rule (including all of its contents). Many of these grammar terms are associated with a boolean result, as follows: : <> :: : not <> :: The result is the negation of the <> term. : <> [ and <> ]* :: The result is true if all of the <> child terms are true, and false otherwise. : <> [ or <> ]* :: The result is false if all of the <> child terms are false, and true otherwise. : <> :: The result is the result of the child subexpression. : <> :: The result is true if the <> [=route-location/matches=] [=current navigation URL=] of the document given the <>. : <> :: : between: <> and <> :: The result is true if the [=current navigation URL=] from of the document given ''from'' is non-null, the [=current navigation URL=] to of the document ''to'' is non-null, one of the two <>s [=route-location/matches=] from, and the other of the two <>s [=route-location/matches=] to. : <> :: : history: traverse :: True if the [=current navigation type=] is {{NavigationType/traverse}}. : history: back :: True if the [=current navigation type=] is {{NavigationType/traverse}} and the document's [=current navigation state=]'s [=navigation state/new index=] is less than its [=navigation state/old index=]. : history: forward :: True if the [=current navigation type=] is {{NavigationType/traverse}} and the document's [=current navigation state=]'s [=navigation state/new index=] is greater than its [=navigation state/old index=]. : history: reload :: True if the [=current navigation type=] is {{NavigationType/reload}}. : <> :: The [=current navigation state=] is not null, and its [=navigation state/phase=] matches the given ''phase'' value. : <> :: The result is false. Authors must not use <> in their stylesheets. It exists only for future-compatibility, so that new syntax additions do not invalidate too much of a <> in older user agents. The condition of the ''@navigation'' rule is the result of the <> in its prelude. NOTE: Some of the design discussion for this feature has been in w3c/csswg-drafts#12594 and w3c/csswg-drafts#8209. This specification defines an additional function for the ''@when'' rule:
navigation() = navigation( <> )
The ''@when/navigation()'' function is associated with the boolean result that its contained condition is associated with. This specification defines an additional function for the ''if()'' function's <> production:
navigation() = navigation( <> )
ISSUE: This should probably have a more formal definition of the function, but I can't find the formal definitions of the existing ''if()'' functions to model it after.

Processing model

The at rules and pseudo-classes defined in this document rely on the [=current navigation state=]. A navigation state is a [=struct=] with the following items:
: old URL : new URL :: a [=/URL=] : type :: a {{NavigationType}} : old index : new index :: an integer : phase :: `loading`, `ready`, or `committed`. : source element :: null or an {{Element}}.
To get the current navigation state of a {{Document}} |document|: 1. If |document| is not [=Document/fully active=], return null. 1. Let |navigation| be |document|'s [=relevant global object=]'s [=navigation API=]. 1. Let |activation| be |navigation|'s {{Navigation/activation}}. 1. If |document| has not [=has been revealed|been revealed=]: 1. If |activation| is null, return null. 1. [=Assert=]: |activation|'s {{NavigationActivation/entry}} is not null. 1. Return a new [=navigation state=] whose [=navigation state/old URL=] is |activation|'s {{NavigationActivation/from}}'s {{NavigationHistoryEntry/url}}, [=navigation state/new URL=] is |activation|'s {{NavigationActivation/entry}}'s {{NavigationHistoryEntry/url}}, [=navigation state/type=] is |activation|'s {{NavigationActivation/navigationType}}, [=navigation state/old index=] is |activation|'s {{NavigationActivation/from}}'s {{NavigationHistoryEntry/index}}, [=navigation state/new index=] is |activation|'s {{NavigationActivation/entry}}'s {{NavigationHistoryEntry/index}}, [=navigation state/phase=] is `committed`, and [=navigation state/source element=] is null. Note: this means that navigations that occur before the page is revealed, e.g. calling {{History/pushState()}} in the head do not reflect in CSS. 1. Let |navigateEvent| be the [=ongoing navigate event=] of |navigation|. 1. Let |phase| be `loading`. 1. If |navigateEvent| is null and |navigation|'s [=traversing navigate event=] is not null: 1. Set |navigateEvent| to |navigation|'s [=traversing navigate event=]. 1. Set |phase| to `ready`. 1. If |navigateEvent| is null, return null. 1. Return a new [=navigation state=] whose [=navigation state/old URL=] is |document|'s [=Document/URL=], [=navigation state/new URL=] is |navigateEvent|'s {{NavigateEvent/destination}}'s {{NavigationDestination/url}}, [=navigation state/type=] is |ongoingNavigateEvent|'s {{NavigateEvent/navigationType}}, [=navigation state/old index=] is |navigation|'s [=navigation API/current entry=]'s {{NavigationHistoryEntry/index}}, [=navigation state/new index=] is |navigateEvent|'s {{NavigateEvent/destination}}'s {{NavigationDestination/index}}, [=navigation state/phase=] is |phase|, and [=navigation state/source element=] is |ongoingNavigateEvent|'s {{NavigateEvent/sourceElement}}.
To get the current navigation URL given a {{Document}} |document| and a <> |relation|: 1. Let |state| be |document|'s [=current navigation state=]. 1. If |state| is null, return null. 1. Return the result of switching on |relation|:
: ''to'' :: |state|'s [=navigation state/new URL=]. : ''from'' :: |state|'s [=navigation state/old URL=]. : ''at'' :: |state|'s [=navigation state/new URL=] if |state|'s [=navigation state/phase=] is `committed`; Otherwise |state|'s [=navigation state/old URL=]. : ''with'' :: |state|'s [=navigation state/old URL=] if |state|'s [=navigation state/phase=] is `committed`; Otherwise |state|'s [=navigation state/new URL=].
To get the current navigation type of a [=/document=] |document|: 1. If |document|'s [=current navigation state=] is non-null, return its [=navigation state/type=]. 1. Return null. The traversing navigate event is the [=ongoing navigate event=] which was reset when the [=ongoing navigation=] is set to `traversal`. ISSUE: Improve integration with the HTML standard, especially the concept of [=traversing navigate event=] and unexported definitions.

Privacy Considerations

ISSUE: To be written.

Security Considerations

ISSUE: To be written.