<pre class='metadata'>
Title: CSS Spatial Navigation Level 1
Shortname: css-nav
Level: 1
Status: ED
Work Status: exploring
Group: csswg
TR: https://www.w3.org/TR/css-nav-1/
ED: https://drafts.csswg.org/css-nav-1/
Previous Version: https://www.w3.org/TR/2019/WD-css-nav-1-20190423/
Previous Version: https://www.w3.org/TR/2019/WD-css-nav-1-20191126/
Editor: Jihye Hong, LG Electronics, jh.hong@lge.com, w3cid 79168
Editor: Florian Rivoal, Invited Expert, https://florian.rivoal.net, w3cid 43241
Abstract: This specification defines a general model for navigating the focus using the arrow keys,
    as well as related CSS, JavaScript features and Events.
At risk: {{getSpatialNavigationContainer()}}
At risk: {{focusableAreas()}}
At risk: 'spatial-navigation-contain'
At risk: ''spatial-navigation-action: scroll''
At risk: 'spatial-navigation-function'
</pre>
<pre class="anchors">
spec: ui-events; urlPrefix: https://w3c.github.io/uievents/;
    type: event;
        text: keydown
        text: click
    type: dfn;
        text: event target
spec: html; urlPrefix: https://html.spec.whatwg.org/multipage/;
    urlPrefix: interaction.html
        type: dfn;
            text: control group
            text: currently focused area of a top-level browsing context
            text: DOM anchor
            text: expressly inert
            text: focusable area
            text: sequential focus navigation order
            text: sequential focus navigation starting point
            text: sequential navigation search algorithm
            text: tabindex; url: #attr-tabindex
    urlPrefix: rendering.html
        type: dfn;
            text: being rendered; url: #being-rendered
    urlPrefix: semantics-other.html
        type: dfn;
            text: actually disabled; url: #concept-element-disabled
    urlPrefix: browsers.html
        type: dfn;
            text: browsing context
    urlPrefix: dom.html
        type: dfn;
            text: the body element; url: #the-body-element-2
    urlPrefix: infrastructure.html
        type: dfn;
            text: removed; url: #nodes-are-removed
spec: dom; urlPrefix: https://dom.spec.whatwg.org/
    type: dfn;
        text: document element
spec: feature-policy; urlPrefix: https://w3c.github.io/webappsec-feature-policy/;
    type: dfn;
        text: is enabled; url: #is-feature-enabled
        text: default allowlist; url: #default-allowlist
        text: policy-controlled feature; url: #policy-controlled-feature
spec: overscroll-behavior; urlPrefix: https://drafts.csswg.org/css-overscroll-behavior-1/;
    type: dfn;
        text: scroll boundary
spec: css2; urlPrefix: https://drafts.csswg.org/css2/
    urlPrefix: box.html
        type: dfn;
            text: border box; url: #x14
    urlPrefix: zindex.html
        type: dfn;
            text: painting order; url: #painting-order
</pre>
<pre class=link-defaults>
spec:html; type:method; for:HTMLOrSVGElement; text:focus()
</pre>
<style>
code.key {
    border: solid 1px;
    border-radius: 0.5ch;
    padding: 1px 5px;
}
.output {
    background: white;
    padding: 1em;
}
</style>
<style>
#api-check:checked ~ .api,
#api-check:checked ~ * .api {
	display: none;
}
#cssapi-check:checked ~ .cssapi,
#cssapi-check:checked ~ * .cssapi {
	display: none;
}
#verbose-check:checked ~ .verbose,
#verbose-check:checked ~ * .verbose {
	display: none;
}
</style>


This specification is rather long.
To make it easier to read and focus on a particular area,
a few checkboxes are provided below.
Checking them hides part of the specification.
This is only meant as a reading aid,
the specification remains the full document.

<input type=checkbox id=api-check> <label for=api-check>Hide JavaScript APIs, including events</label><br>
<input type=checkbox id=cssapi-check> <label for=cssapi-check>Hide CSS properties that enable selecting behavior variants, and related information</label><br>
<input type=checkbox id=verbose-check> <label for=verbose-check>Hide informative sections that explain and summarize normative sections without adding more information</label><br>

<h2 id="intro" class=non-normative>
Introduction</h2>

<em>This section is not normative.</em>

Historically, most browsers have not offered features to let the user move the focus directionally.
Some, such as TV browsers, have enabled the user to move the focus using the arrow keys out of necessity,
since no other input mechanism is available on a typical TV remote control.

Others have enabled different key combinations to control spatial navigation,
such as pressing the <code class=key>Shift</code> key together with arrow keys.

This ability to move around the page directionally is called <dfn lt="spatial navigation | spatialNavigation" export>spatial navigation</dfn>.

<a>Spatial navigation</a> can be useful for a web page built using a grid-like layout,
or other predominantly non linear layouts.
The figure below represents a photo gallery arranged in a grid layout.
If the user presses the <code class=key>Tab</code> key to move focus around the images,
they need to press the key many times to reach the desired image element.

<figure>
    <img alt="When elements are laid out in a grid pattern, spatial navigation makes it much easier to predict and control where focus should move to." src="images/gallery-app.png" style="width: 500px;"/>
    <figcaption>Photo gallery application example using a grid layout</figcaption>
</figure>

Also, <a>spatial navigation</a> moves the focus to the predictable element for users
because it moves the focus among focusable elements depending on their position.
Sometimes elements on the page aren’t arranged independently of their source order.
Therefore unlike <a>spatial navigation</a>, sequential navigation using the <code class=key>Tab</code> key makes focus navigation unpredictable.

While arrow keys are naturally suited to control spatial navigation,
no previous specification describes how that should work,
or how it may be controlled.
<span class=api>This specification introduces a processing model for spatial navigation,
as well as APIs
enabling the author to control and override how spatial navigation works.</span>

Note: Some aspects of this specification, such as the JavaScript Events and APIs
could also be extended to sequential navigation,
in order to make sure that keyboard navigation has a consistent and well defined model in general.

Note: As a general principle,
keyboard navigation,
and spatial navigation in particular,
should be possible to use and control without JavaScript<span class=cssapi>,
and declarative solutions are therefore preferred.
Since spatial navigation depends on layout,
that means CSS is typically the right mechanism to define
spatial navigation related controls</span>.
<span class=api>However, in the spirit of the <a href="https://github.com/extensibleweb/manifesto">Extensible Web Manifesto</a> [[EXTENSIBLE]],
we feel it is important to provide the right JavaScript primitives
to let the author experiment and explore the problem space.
More declarative features may be added later,
based on feedback and experience acquired through such JavaScript usage.</span>

Note: A few features are marked <dfn noexport>at-risk</dfn>.
The editors of this specification believe
they represent an important part of the user or author experience
of the features defined in the specification.
At the same time, the core functionality of this specification
can be implemented without implementing these
so it seems possible that implementers may choose to down-prioritize them
to reduce the scope of the first implementation.
While it is hoped that these features will be implemented as well,
they are marked at-risk in recognition that they might not be at first.


<h2 id=interaction>
Module interaction</h2>

This document depends on the Infra Standard [[!infra]].

The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" are to be interpreted as described in RFC 2119. [[!RFC2119]]


<div class=verbose>
<h2 id=overview class=non-normative>
Overview</h2>

<em>This section is not normative.</em>

Using a UA-defined mechanism
(typically arrow keys, possibly in combination with modifier keys like <code class=key>Shift</code> or <code class=key>Control</code>),
the user may ask the User Agent to navigate in a particular direction.
This will either
move the focus from its current location to a new focusable item in the direction requested,
or scroll if there is no appropriate item.

More specifically,
the User Agent will first search for visible and focusable items
in the direction indicated
within the current <a>spatial navigation container</a>
(<span class=cssapi>by default, </span>the root element, scrollable elements, and iframes<span class=cssapi>,
but other elements can be made into <a>spatial navigation containers</a>
using the 'spatial-navigation-contain' property</span>).

If it finds any, it will pick the best one for that direction,
and move the focus there.

If it does not, it will scroll the <a>spatial navigation container</a> in the requested direction
instead of moving focus.
Doing so may uncover focusable elements
which would then be eligible targets to move the focus to
next time spatial navigation in the same direction is requested.

If the <a>spatial navigation container</a> cannot be scrolled,
either because it is not a scrollable element
or because it is already scrolled to the maximum in that direction,
the User Agent will select the next <a>spatial navigation container</a> up the ancestry chain,
and recursively repeat the above process
until it finds some element to focus or scroll,
or reaches the root element.

Note: As a consequence of this processing model,
the elements that are reachable by sequential navigation
and by spatial navigation are almost the same.
Elements that are currently outside of the viewport of a scrollable element
can only be reached by spatial navigation once they have been scrolled into view.
Therefore, elements that cannot be scrolled into view by default.

<div class=api>
At key points during this search for the appropriate response to the spatial navigation request,
the User Agent will fire events.
These enable the author to prevent the upcoming action
(by calling {{preventDefault()}}),
and if desired to provide an alternate action,
such as using the {{HTMLOrSVGElement/focus()}} method on a different
element of the author's choosing.

To help the author write such alternate actions,
and as part of exposing underlying platform primitives as per the <a href="https://github.com/extensibleweb/manifesto">Extensible Web</a> principles,
this specification also defines JavaScript APIs
that expose key constructs of the underlying model.


See [[#js-api]] for details about the JavaScript API,
[[#events-nav-type]] for details about the various events,
and [[#declarative]] for details about the CSS properties.
</div>

<div class='example'>
    This example shows how a series of focusable elements
    arranged in a scrollable element
    would be navigated when using spatial navigation.
    For the sake of keeping the description simple,
    this example assumes a User Agent where spatial navigation is triggered using arrow keys.

    <figure>
        <img alt="" src="images/spatnav-scroll-visible-1.png" style="width: 200px;"/>
        <img alt="" src="images/spatnav-scroll-visible-2.png" style="width: 200px;"/>
        <figcaption>Moving focus to the visible element in the <a>spatial navigation container</a>.</figcaption>
    </figure>

    On the left of figure 2, "Box 2" is focused.
    Pressing the <code class=key>ArrowDown</code> key moves the focus to
    "Box 3" without scrolling because "Box 3" is visible in the <a>scrollport</a> of the <a>spatial navigation container</a>.

    <figure>
        <img alt="" src="images/spatnav-scroll-invisible-1.png" style="width: 160px;"/>
        <img alt="" src="images/spatnav-scroll-invisible-2.png" style="width: 160px;"/>
        <img alt="" src="images/spatnav-scroll-invisible-3.png" style="width: 160px;"/>
        <img alt="" src="images/spatnav-scroll-invisible-4.png" style="width: 160px;"/>
        <figcaption>Moving focus to the hidden element in the <a>spatial navigation container</a>.</figcaption>
    </figure>

    On the first of figure 3, under "Box 3", there isn't any visible element in the <a>scrollport</a>.
    Therefore, the effect of pressing the <code class=key>ArrowDown</code> is to scroll down, as shown in the second.
    The next press of the <code class=key>ArrowDown</code> key makes "Box 4" come into the <a>scrollport</a>,
    and the focus will move to it when there is additional pressing the <code class=key>ArrowDown</code>, as the fourth.

    This example uses the markup as follows:
    <pre class="lang-css">
        #scroller {
            width: 700px;
            height: 700px;
            overflow-x: hidden;
            overflow-y: auto;
        }

        .box {
            width: 150px;
            height: 110px;
            background-color: blue;
        }

        .box:focus {
            background-color: red;
        }
    </pre>

    <pre class="lang-html">
        &lt;div id="scroller">
            &lt;div class="box" tabindex="0">Box 1&lt;/div>
            &lt;div class="box" tabindex="0">Box 2&lt;/div>
            &lt;div class="box" tabindex="0">Box 3&lt;/div>
            &lt;div class="box" tabindex="0">Box 4&lt;/div>
        &lt;/div>
    </pre>
</div>
</div>

<h2 id=triggering>
Triggering Spatial Navigation</h2>

When the user triggers spatial navigation in a given direction,
the User Agent must run the <a>spatial navigation steps</a> in that direction.

This specification does not define what UI mechanism User Agents should offer to users to trigger spatial navigation.
This intentionally left for User Agents to decide.

<div class=note>Note:
    It is expected that User Agents on devices with limited input capabilities,
    such as TVs operated with a remote control,
    feature phones,
    or devices operated with a game controller,
    will use spatial navigation as their primary or exclusive navigation mechanism.
</div>

Although User Agents can implement the processing model and APIs
defined by the specification,
this specification recommends that
User Agents should offer a means for users to trigger spatial navigation directly,
without having to use the APIs.

Note: Conversely, the author should assume that spatial navigation may be triggered
by the User Agent in response to user actions
even if the author has not invoked any of the APIs.

Regardless of the actual mechanism chosen to trigger spatial navigation,
the following requirements apply:
* If the mechanism the user must use to trigger spatial navigation
    would normally fire a {{UIEvent}},
    the event must be fired prior to running the <a>spatial navigation steps</a>
    and these steps must not be run if that event's <a>canceled flag</a>
    gets set.

    <div class=example>
        Gaming devices may trigger spatial navigation based on pressing the D-pad.
        This would result in firing a <a event>keydown</a> event
        with the key set to one of
        <code class=key>ArrowDown</code>,
        <code class=key>ArrowLeft</code>,
        <code class=key>ArrowRight</code>,
        or <code class=key>ArrowUp</code>,
        followed if not canceled by running the <a>spatial navigation steps</a><span class=api>,
        including firing the relevant {{NavigationEvent}}s</span>.

        A User Agent on a desktop computer that triggers spatial navigation
        using the arrow keys of the keyboard
        would follow the same sequence.
    </div>
* If the mechanism the user must use to trigger spatial navigation
    would also perform other actions in some contexts,
    the User Agents should in these contexts
    give priority to these other actions
    and execute them instead of spatial navigation.
    It must not trigger both.

    <div class=example>
        In a User Agent that triggers spatial navigation
        using the arrow keys without modifier keys,
        and uses these same arrow keys to move
        the text insertion caret when an editable element is focused,
        the arrow keys should by default to moving the caret.
        Spatial navigation would only be triggered by the arrow keys
        when the focused element is not editable
        or when it is editable, but the caret cannot move any further in the requested direction.
    </div>

    An exception is made for scrolling:
    since spatial navigation itself handles scrolling
    (in addition to moving the focus)
    User Agents should not offer the same mechanism to trigger both spatial navigation
    and the scrolling behavior separate from spatial navigation.
    However, User Agents may offer a way for the user to switch between different modes,
    or offer both based on different UI mechanisms.

    <div class=example>
        A User Agent may have a setting to let the user choose
        between using the arrow keys without modifier keys
        for spatial navigation or for scrolling.
        Another one may offer scrolling on arrow keys without modifiers,
        and spatial navigation on arrow keys when pressed together
        with the <code class=key>Shift</code> key,
        or on the <code class=key>W</code> <code class=key>A</code> <code class=key>S</code> <code class=key>D</code> keys.
        Offering only spatial navigation or only scrolling
        as responses to pressing arrow keys would also be possibilities.
    </div>

<div class=api>
<h2 id="js-api">
JavaScript API</h2>

<h3 id=high-level-api>
Triggering Navigation Programmatically</h3>

The {{Window/navigate()}} method enables the author to trigger spatial navigation programmatically,
as if the user had done so manually
(for instance, by pressing the arrow keys in a browser where that is the way to trigger spatial navigation).

Note: As this triggers the same processing model as manual navigation,
all the same results should be expected:
the same chain of events will be fired and
the same element will be scrolled or focused.

Note: The author can use this to trigger spatial navigation
based on a different UI mechanism than the one assigned by the User Agent,
such as mapping to different keys,
or triggering spatial navigation from a clickable on-screen directional pad,
or in reaction to other events than UI ones.
It could also be used when an author wants to interrupt navigation to do some asynchronous operation
(e.g. load more content in an infinite scroller) then resume the navigation where they canceled.

Note: This API is also useful for testing purposes,
as there it is difficult to trigger spatial navigation
that does not depend on vendor specific UI conventions.

<pre class="idl">
enum SpatialNavigationDirection {
    "up",
    "down",
    "left",
    "right",
};

partial interface Window {
    void navigate(SpatialNavigationDirection dir);
};
</pre>

<div algorithm="windowNavigate steps">
When the <dfn method for="Window" lt="navigate(dir)">navigate(dir)</dfn> method is called,
the User Agent must run the following step:

* If direction <var>dir</var> is <code>"up"</code>, <code>"down"</code>, <code>"left"</code>, or <code>"right"</code>,
    run the <a>spatial navigation steps</a> in <var>dir</var>.

Issue(3387): The name of this API is under discussion

</div>

<h3 id=low-level-api>
Low level APIs</h3>

These APIs are designed to be low level constructs following the processing model closely.
As such, they should be easy to use by the author who wants to extend or override the way spatial navigation works.

<pre class="idl">
enum FocusableAreaSearchMode {
    "visible",
    "all"
};

dictionary FocusableAreasOption {
    FocusableAreaSearchMode mode;
};

dictionary SpatialNavigationSearchOptions {
    sequence&lt;Node>? candidates;
    Node? container;
};

partial interface Element {
    Node getSpatialNavigationContainer();
    sequence&lt;Node> focusableAreas(optional FocusableAreasOption option);
    Node? spatialNavigationSearch(SpatialNavigationDirection dir, optional SpatialNavigationSearchOptions options);
};
</pre>

Note: The way the direction is expressed allows us to expand to more than 4-way navigation
later if this is found necessary.
More directional keywords or a numerical angle could be added.

Note: the {{focusableAreas()}} and {{getSpatialNavigationContainer()}} methods are <a>at-risk</a>.

When these methods are called,
the User Agent must run the steps described below:

<div algorithm="getSpatialNavigationContainer steps">
:   <dfn method for=Element lt="getSpatialNavigationContainer()">getSpatialNavigationContainer()</dfn>
::
    1. Return the nearest ancestor of the element that is a <a>spatial navigation container</a>,
        or the <a>document</a> if the nearest <a>spatial navigation container</a> is the viewport.

    Note: If the element is a <a>spatial navigation container</a>, {{getSpatialNavigationContainer()}} also returns
    the nearest <a>spatial navigation container</a>, not the element itself.

</div>

<div algorithm="focusableAreas steps">
:   <dfn method for=Element lt="focusableAreas(option)">focusableAreas(<var>option</var>)</dfn>
::
    1. Let <var>visibleOnly</var> be <code>false</code>
        if <var>option</var> is present and its value is equal to <code>'all'</code>,
        or <code>true</code> otherwise.
    2. Let <var>areas</var> be the result of <a>finding focusable areas</a> within the element with <var>visibleOnly</var> as argument.
    4. Return <var>areas</var>

</div>

<div class=example id=focusAreas-visible>
    The following code shows how to get all the visible focusable elements in the current page using {{Element/focusableAreas()}}.
    If the method finds a <a>spatial navigation container</a>, it recursively finds focusable areas inside it.
    Because the value of the {{FocusableAreasOption/mode}} attribute in this method is <code>visible</code>,
    the focusable elements which aren't inside the <a>scrollport</a> are excluded from the result.

    <pre><code highlight=markup>
    &lt;body>
        &lt;button>&lt;/button>
        &lt;div style="width:300px; height:200px; overflow-x: scroll;">
            &lt;button style="left:25px;">&lt;/button>
            &lt;button style="left:150px;">&lt;/button>
            &lt;button style="left:350px;">&lt;/button>
        &lt;/div>
    &lt;/body>
    </code></pre>
    <pre><code highlight=javascript>
        const focusableAreas = document.body.focusableAreas({mode: 'visible'});
        focusableAreas && focusableAreas.forEach(focusable => {
          focusable.style.outline = '5px solid red';
        });
    </code></pre>
    The figure below is the result of this code.
    <figure>
        <img alt="An image about focusableAreas()" src="images/focusableareas-visible-example.png" style="width: 450px;"/>
        <figcaption>Find all visible focusable areas inside the document.</figcaption>
    </figure>
</div>

<div algorithm="spatialNavigationSearch steps">
:   <dfn method for=Element lt="spatialNavigationSearch(options)">spatialNavigationSearch(<var>dir</var>, <var>options</var>)</dfn>
::
    1. Let <var>direction</var> be the value of <var>dir</var>.
    2. Let <var>container</var> be
        * if the value of {{SpatialNavigationSearchOptions/container}} attribute of <var>options</var> is not null,
            * itself, if it is <a>spatial navigation container</a>.
            * its nearest <a>spatial navigation container</a> ancestor, otherwise.
        * else the element's nearest <a>spatial navigation container</a> ancestor.
    3. Let <var>areas</var> be
        * the value of {{SpatialNavigationSearchOptions/candidates}} attribute of <var>options</var> if it is not <code>null</code>,
        * result of <a>finding focusable areas</a> within <var>container</var> otherwise.
    4. Return the result of <a>selecting the best candidate</a> among <var>areas</var> within <var>container</var> in <var>direction</var> from the element.

Note: When neither a container nor a list of candidates is provided,
this only searches through the visible focusable areas of the nearest
<a>spatial navigation container</a> ancestor.
<em>If there isn't any, this does not climb further up the ancestry chain,
and the result will be <code>null</code>.</em>
</div>
</div>

<div class=api>
<h2 id="events-navigationevent">
Navigation Events</h2>

<h3 id="interface-focusevent">
Interface NavigationEvent</h3>

The {{NavigationEvent}} interface provides specific contextual information associated with spatial navigation.

To create an instance of the {{NavigationEvent}} interface, use the {{NavigationEvent}} constructor,
passing an optional {{NavigationEventInit}} dictionary.

<pre class=idl>
[Exposed=Window]
interface NavigationEvent : UIEvent {
    constructor(DOMString type,
                optional NavigationEventInit eventInitDict);
    readonly attribute SpatialNavigationDirection dir;
    readonly attribute EventTarget? relatedTarget;
};

dictionary NavigationEventInit : UIEventInit {
    SpatialNavigationDirection dir;
    EventTarget? relatedTarget = null;
};
</pre>

<div class=verbose>
<h3 id="events-nav-type" class="non-normative">
Navigation Event Types</h3>

<em>This section and its subsections are not normative.</em>

The Navigation event types are summarized below.
For full normative details, see [[#processing-model]].

<h4 id="event-type-navbeforefocus" class="non-normative">
<dfn event for=NavigationEvent>navbeforefocus</dfn></h4>

This event occurs when there is a valid result of <a>selecting the best candidate</a>.

<table class="def">
    <tbody>
        <tr>
            <th>Type
            <td><strong><code>navbeforefocus</code></strong>
        <tr>
            <th>Interface
            <td>{{NavigationEvent}}
        <tr>
            <th>Bubbles
            <td>Yes
        <tr>
            <th>Cancelable
            <td>Yes
        <tr>
            <th>Attributes of the event
            <td><dl>
                <dt>{{Event}}.{{Event/target}}
                <dd>The focused element or if no element focused,
                then <a>the body element</a> if available, otherwise the root element

                <dt>{{NavigationEvent}}.{{NavigationEvent/relatedTarget}}
                <dd>The DOM anchor of the focusable area that will be focused

                <dt>{{NavigationEvent}}.{{NavigationEvent/dir}}
                <dd>The direction of the navigation as requested by the user
            </dl>
    </tbody>
</table>

The User Agent <dfn lt="dispatches navbeforefocus event | dispatching navbeforefocus event">dispatches <a event>navbeforefocus</a> event</dfn>
before spatial navigation moves the focus.
The <a>event target</a> is the element which has focus and
the {{NavigationEvent/relatedTarget}} is the element which is about to receive focus.

If <a>navigation-override</a> is disabled in the [=node document=] of <var>eventTarget</var> for
the <a spec=html for="/">origin</a> of the [=active document=] of the [=top-level browsing context=], this event won't be dispatched.

<div class='example'>
    This example shows the [[UI-EVENTS#event-order]] when pressing the <code class=key>ArrowRight</code>
    key.
    For the sake of keeping the description simple,
    this example assumes a User Agent where spatial navigation is triggered using arrow keys.

    <table class="complex data">
        <thead>
            <tr>
                <th>
                <th>Event type
                <th>{{KeyboardEvent}}.{{KeyboardEvent/key}}
                <th>Notes
        </thead>
        <tbody>
            <tr>
                <td>1
                <td>keydown
                <td><code class=key>ArrowRight</code>
                <td>MUST be a key which can activate spatial navigation,
                    such as the arrow keys, or spatial navigation is not activated.
            <tr>
                <td>2
                <td>navbeforefocus
                <td>
                <td>Sent if the candidates for spatial navigation is not <code>null</code>,
                    or this is not generated.
            <tr>
                <td>3
                <td>focusin
                <td>
                <td>Sent before the target element receives focus.
            <tr>
                <td>4
                <td>focus
                <td>
                <td>Sent after the target element receives focus.
        </tbody>
    </table>
</div>

<div class=example id=delegation>
    The following code changes the behavior of spatial navigation
    so that when a scroll container would get focused,
    if it has at least one visible focusable descendant,
    the focus is automatically transferred to it,
    recursively.

    <pre><code highlight=javascript>
    document.addEventListener('navbeforefocus', e => {
        e.preventDefault();

        let nextTarget = e.relatedTarget;
        if (isSpatialNavigationContainer(nextTarget)) {
            const areas = nextTarget.focusableAreas();

            if (areas.length > 0) {
                nextTarget = nextTarget.spatialNavigationSearch(e.dir, { candidates: areas });
            }
        }
        nextTarget.focus();
    });

    function isSpatialNavigationContainer(element) {
        return (!element.parentElement) ||
            (element.nodeName === 'IFRAME') ||
            (isScrollContainer(element)) ||
            (isCSSSpatNavContain(element));
    }
    </code></pre>
</div>

<h4 id="event-type-navnotarget" class="non-normative">
<dfn event for=NavigationEvent>navnotarget</dfn></h4>

This event occurs before going up the tree to search candidates in the
nearest ancestor <a>spatial navigation container</a> when spatial navigation has failed to find any candidate
within the current <a>spatial navigation container</a>,
and in cases where the <a>spatial navigation container</a> is scrollable,
when it cannot be scrolled further.

<table class="def">
    <tbody>
        <tr>
            <th>Type
            <td><strong><code>navnotarget</code></strong>
        <tr>
            <th>Interface
            <td>{{NavigationEvent}}
        <tr>
            <th>Bubbles
            <td>Yes
        <tr>
            <th>Cancelable
            <td>Yes
        <tr>
            <th>Attributes of the event
            <td><dl>
                <dt>{{Event}}.{{Event/target}}
                <dd>The focused element or if no element focused,
                then <a>the body element</a> if available, otherwise the root element

                <dt>{{NavigationEvent}}.{{NavigationEvent/relatedTarget}}
                <dd>The <a>spatial navigation container</a> that was searched in.

                <dt>{{NavigationEvent}}.{{NavigationEvent/dir}}
                <dd>The direction of the navigation as requested by the user
            </dl>
    </tbody>
</table>

The User Agent <dfn lt="dispatches navnotarget event | dispatching navnotarget event">dispatches <a event>navnotarget</a> event</dfn>
with initializing the <a>event target</a> as the element which has focus and
the {{NavigationEvent/relatedTarget}} as <a>spatial navigation container</a> of the <a>event target</a>.

If <a>navigation-override</a> is disabled in the [=node document=] of <var>eventTarget</var> for
the <a spec=html for="/">origin</a> of the [=active document=] of the [=top-level browsing context=], this event won't be dispatched.

<div class='example'>
    This example shows the [[UI-EVENTS#event-order]] when pressing the <code class=key>ArrowDown</code>
    key in the situation like the following figure.
    For the sake of keeping the description simple,
    this example assumes a User Agent where spatial navigation is triggered using arrow keys.

    <figure>
        <img alt="An image about navnotarget" src="images/navnotarget-example-1.png" style="width: 200px;"/>
        <figcaption>Moving focus when there isn't any candidate in the
            <a>scroll container</a>.</figcaption>
    </figure>

    <table class="complex data">
        <thead>
            <tr>
                <th>
                <th>Event type
                <th>Event target
                <th><code>relatedTarget</code>
                <th>Notes
        </thead>
        <tbody>
            <tr>
                <td>1
                <td>keydown
                <td><code>#box2</code>
                <td>N/A
                <td>MUST be a key which can activate spatial navigation,
                    such as the arrow keys,
                    otherwise spatial navigation is not triggered.
            <tr>
                <td>2
                <td>navnotarget
                <td><code>#box2</code>
                <td><code>#scrollContainer</code>
                <td>Sent if <code>#scrollContainer</code> doesn't contain any candidate and
                cannot be scrolled,
                otherwise this would not be generated.
            <tr>
                <td>3
                <td>navbeforefocus
                <td><code>#box2</code>
                <td><code>#box3</code>
                <td>Sent if the candidates in <code>#container</code> is not <code>null</code>,
                otherwise this would not be fired.
            <tr>
                <td>4
                <td>focusin
                <td><code>#box3</code>
                <td><code>#box2</code>
                <td>Sent before the target element receives focus.
            <tr>
                <td>5
                <td>focus
                <td><code>#box3</code>
                <td><code>#box2</code>
                <td>Sent after the target element receives focus.
        </tbody>
    </table>

    The result of this example is the figure as follows:

    <figure>
        <img alt="An image of the result about navnotarget" src="images/navnotarget-example-2.png" style="width: 200px;"/>
        <figcaption>The result of moving focus when there isn't any candidate in the <a>scrollport</a>
        and <a>scroll container</a> cannot be scrolled.</figcaption>
    </figure>

    This example uses the markup as follows:
    <pre class="lang-css">
        #container {
            width: 900px;
            height: 1400px;
        }

        #scrollContainer {
            width: 700px;
            height: 700px;
            overflow-x: hidden;
            overflow-y: auto;
        }

        .item {
            width: 150px;
            height: 110px;
            background-color: blue;
        }

        .item:focus {
            background-color: red;
        }
    </pre>

    <pre class="lang-html">
        &lt;div id="container">
            &lt;div id="scrollContainer">
                &lt;div id="box1" class="item" tabindex="0">Box 1&lt;/div>
                &lt;div id="box2" class="item" tabindex="0">Box 2&lt;/div>
            &lt;/div>
            &lt;div id="box3" class="item" tabindex="0">Box 3&lt;/div>
        &lt;/div>
   </pre>
</div>

<div class=example id=loop>
    The following code changes the behavior of spatial navigation
    to trap the focus within a <a>spatial navigation container</a> which is vertically scrollable.
    When no further focusable elements can be found in the requested direction
    and the <a>spatial navigation container</a> cannot be scrolled any further,
    the focus loops back to the other side instead of moving outside of it.

    However, the focus can still be moved outside by sequential navigation,
    mouse interaction,
    or programmatic calls to {{focus()}}.

    <pre><code highlight=javascript>
    scrollContainer.addEventListener('navnotarget', e => {
        let nextTarget = null;
        const verticalDir = ['up', 'down'];
        const candidates = e.relatedTarget.focusableAreas({'mode': 'all'});

        // Prevent default only when navigation direction is on y-axis
        if (verticalDir.includes(e.dir) && (candidates.length > 0)) {
            e.preventDefault();

            if (e.dir === 'down') {
                nextTarget = candidates[0];
            } else if (e.dir === 'up') {
                nextTarget = candidates[candidates.length-1];
            }
            nextTarget.focus();
        }
    });
    </code></pre>
</div>

</div>
</div>

<h2 id=policy-feature>
The <a>navigation-override</a> <a>policy-controlled feature</a></h2>

	The <dfn>navigation-override</dfn> <a>policy-controlled feature</a> controls
	the availability of mechanisms that enables the page author
	to take control over the behavior of spatial navigation,
	or to cancel it outright.

	* The feature name is "<code>navigation-override</code>"
	* The <a>default allowlist</a> for <a>navigation-override</a> is "<code>self</code>"

	As defined in further details in [[#nav]],
	if <a>navigation-override</a> is disabled in a document,
	the navigation events (see [[#events-navigationevent]]) will not be fired.

	Note: This is to prevent a hostile iframe from using these events
	in order to highjack the focus.
	We recognize that there exist other mechanisms predating spatial navigation
	that malicious the author could use
	to interfere with the user's ability to control where the focus goes.
	Despite that, it seems worthwhile to attempt not to increase this attack surface,
	although it is possible that such attacks are already sufficiently easy to perform
	that this is a lost cause.
	Further feedback on this topic,
	based on experience with implementation or with mitigating such attacks,
	is very welcome.


<h2 id=processing-model>
Processing Model</h2>

<div class=verbose>
The [[#overview]] section gives a high level idea of how spatial navigation works,
to help readers of this specification build a general mental model.
It uses intuitive but imprecise terminology,
and glosses over many details
for the sake of readability.

This section defines the corresponding normative behavior
and aims for as much detail as necessary
to fully define the behavior.
</div>

<h3 id=glossary>
Glossary</h3>

The following term definitions have been specified to explain the processing model for spatial navigation.
See the links within the definitions for more information.

The <dfn>boundary box</dfn> of an object is defined as follows:
* if the object is a point, the boundary box is that point
* if the object is a [=box=] or [=box fragment=], the boundary box is the <a>border box</a> of that box or fragment
* if the object is a <a>focusable area</a> which is not an element, the boundary box is the axis-aligned the bounding box of that <a>focusable area</a>

The <dfn>inside area</dfn> of an object is defined as follows:
* if the object is a <a>scroll container</a>, its <a>optimal viewing region</a>
* if the object is a <a>document</a>, the viewport of its <a>browsing context</a>
* if the object is a [=box=] or [=box fragment=], its <a>boundary box</a>
* otherwise, the <a>optimal viewing region</a> of its nearest ancestor <a>scroll container</a>

NOTE: If an object is offscreen, the <a>inside area</a> should be the nearest visible ancestor container.

Issue(w3c/csswg-drafts#2324): CSS should have a term for “border box taking into account corner shaping properties like border-radius”.

The <dfn>search origin</dfn> is the origin for searching next target.

The <dfn>spatial navigation starting point</dfn> is the origin for searching next target which is set by the User Agent. It is initially unset and it can be element or point.

Note: For example, the User Agent could set it to the position of the user's click if the user clicks on the document contents,
and unset when the focus is moved (by spatial navigation or any other means).

If the User Agent sets both a <a>spatial navigation starting point</a> and a <a>sequential focus navigation starting point</a>,
they must not be set differently.

<h3 id=grouping>
Groupings of elements</h3>

While the processing model for spatial navigation
is to work from the layout of the document
and the relative position of focusable elements,
the User Agent is required to prioritize finding elements
from a local logical grouping,
only looking for focusable elements outside of the grouping
if a suitable one cannot be found inside it (see [[#nav]] for details).

Such groupings are called <dfn>spatial navigation containers</dfn>.

<span class=cssapi>By default, </span><a>spatial navigation containers</a> are established by:
* The viewport of a <a for="/">browsing context</a>
    (not limited to the <a>top-level browsing context</a>)

* <a>scroll containers</a>

<div class=cssapi>
Additional <a>spatial navigation containers</a> can be created using the 'spatial-navigation-contain' property (see [[#container]]).
</div>

<h3 id=nav>
Navigation</h3>

The processing model for spatial navigation describes how spatial navigation works in general.

<figure class="verbose non-normative">
    <object type="image/svg+xml" data="images/spatnav_processing_model_diagram.svg"></object>
    <figcaption>
        Overview of the Spatial navigation processing model
        <br>
        This figure is not normative.
        It gives an overview of the processing model further defined in this section,
        assuming that the 'spatial-navigation-action' property has its initial value of ''spatial-navigation-action/auto''.
    </figcaption>
</figure>

<div algorithm="to run the spatial navigation steps">

To run the <dfn>spatial navigation steps</dfn> in <var>direction</var>, do the following:

1. Let <var>searchOrigin</var> be the result of <a>setting the search origin</a>.
2.
    * If <var>searchOrigin</var> is an <a>node</a>,
        let <var>eventTarget</var> be <var>searchOrigin</var>
    * else (<a>assert</a>: <var>searchOrigin</var> is a position)
        let <var>eventTarget</var> be the <a>node</a> which contains <var>searchOrigin</var>
3. If <var>eventTarget</var> is the <a>Document</a> or the <a>document element</a>,
        set <var>eventTarget</var> be <a>the body element</a> if it is not <code>null</code>
        or to the <a>document element</a> otherwise.
4.  <ul>
        <li class=cssapi>If <var>eventTarget</var> is <a>scroll container</a>
            and the computed value of the 'spatial-navigation-action' property on <var>eventTarget</var> is ''spatial-navigation-action/scroll''
            and <var>eventTarget</var> [=can be manually scrolled=],
            then [=directionally scroll the element=] <var>eventTarget</var> and return.</li>
        <li><span class=cssapi>Else,</span> if <var>eventTarget</var> is either a <a>scroll container</a> or the <a>document</a>
            1. Let <var>candidates</var> be the result of <a>finding focusable areas</a>
                within <var>eventTarget</var>
                with the argument <var>visibleOnly</var> set to <code>false</code>
                <span class=cssapi>if computed value of the 'spatial-navigation-action' property on <var>eventTarget</var>
                is ''spatial-navigation-action/focus'' or to <code>true</code> otherwise.
                </span>
            2.
                <ul>
                    <li class=cssapi>If
                        the computed value of the 'spatial-navigation-action' property on <var>eventTarget</var> is not ''spatial-navigation-action/focus''
                        and <var>eventTarget</var> <a>can be manually scrolled</a>,
                        then <a>directionally scroll the element</a> <var>eventTarget</var> in <var>direction</var> and return.</li>
                    <li><span class=cssapi>Else </span>if <var>candidates</var> contains at least 1 item:
                        1. Let <var>bestCandidate</var> be the result of <a>selecting the best candidate</a>
                            within <var>candidates</var> in <var>direction</var> starting from <var>searchOrigin</var>
                        2. <a>Dispatches navbeforefocus event</a> at <var>eventTarget</var> with <var>direction</var> and <var>bestCandidate</var>.
                        3. Run the <a>focusing steps</a> for <var>bestCandidate</var> and return
                    </li>
                    <li>Else, fall back to the next step.</li>
                </ul>
        </li>
        <li>Else, fall back to the next step.</li>
    </ul>
5. Let <var>container</var> be the nearest ancestor of <var>eventTarget</var> that is a <a>spatial navigation container</a>.
6. <i>Loop</i>: Let <var>candidates</var> be the result of <a>finding focusable areas</a>
    within <var>container</var>
    with the argument <var>visibleOnly</var> set to <code>false</code>
    <span class=cssapi>
    if computed value of the 'spatial-navigation-action' property on <var>container</var> is ''spatial-navigation-action/focus''
    or to <code>true</code> otherwise,
    excluding <var>eventTarget</var>
    </span>
7. If <var>candidates</var> is empty:
        <li class=cssapi>If the computed value of the 'spatial-navigation-action' property on <var>container</var> is not ''spatial-navigation-action/focus''
            and <var>container</var> is a <a>scroll container</a> that <a>can be manually scrolled</a>,
            <a>directionally scroll the element</a> <var>container</var> in <var>direction</var> and return.
        </li>
        <li class=cssapi>Else,</li>
            1. <a>Dispatches navnotarget event</a> at <var>eventTarget</var> with <var>direction</var> and <var>container</var>.
            2.
                * If <var>container</var> is the <a>document element</a> of the <a>top-level browsing context</a>,
                    then return.
                    The User Agent may transfer focus to its own controls (if any) honouring <var>direction</var>.
                * Else, if <var>container</var> is the <a>document element</a> of a <a>nested browsing context</a> then:
                    1. Set <var>searchOrigin</var> to <var>container</var>'s <a>browsing context container</a>
                    2. Set <var>eventTarget</var> be <var>searchOrigin</var>
                    3. Set <var>container</var> to the nearest ancestor of <var>eventTarget</var> that is a <a>spatial navigation container</a>.
                    4. Return to the step labeled <i>loop</i>.
                * Else, set <var>container</var> to its closest ancestor that is itself a <a>spatial navigation container</a>
                    and return to the step labeled <i>loop</i>.
    </ul>
8. Let <var>bestCandidate</var> be the result of <a>selecting the best candidate</a>
    within <var>candidates</var> in <var>direction</var> starting from <var>eventTarget</var>.
9. <a>Dispatches navbeforefocus event</a> at <var>eventTarget</var> with <var>direction</var> and <var>bestCandidate</var>.
10. Run the <a>focusing steps</a> for <var>bestCandidate</var> and return.

</div>

<h3 id=heuristics>
Focus Navigation Heuristics</h3>

Note: The following algorithms are inspired from Chrome's implementation
as well as from the <a href="https://www.w3.org/TR/WICD/#focus-handling">old WICD Spec</a>.
Implementors who find better approaches or refinements to these approaches are strongly
encouraged to provide feedback and help improve this specification
in order to maximize interoperability.
In particular, divergences in how User Agents <a>find focusable areas</a>
may cause some elements to be focusable in some User Agents but not in others,
which would be bad for users.

All geometrical operations in this section are defined to work on the result of CSS layout,
including all graphical transformations, such as <a>relative positioning</a> or [[CSS-TRANSFORMS-1]].

<div algorithm="to set the search origin">

To <dfn lt="set the search origin | setting the search origin">set the <a>search origin</a></dfn>,
run the following steps:

1. Let <var>searchOrigin</var> be the <a>DOM anchor</a> of the <a>currently focused area of a top-level browsing context</a>.
2. If the <a>spatial navigation starting point</a> is not <code>null</code>
    and it is inside <var>searchOrigin</var>,
    then return it.
3. Otherwise, return <var>searchOrigin</var>.

If the status of <var>focus target</var> changed not by moving the focus,
<dfn lt="update the search origin | updating the search origin">update the <a>search origin</a></dfn> as following:
1. If <var>focus target</var> becomes
    <a>actually disabled</a> or
    <a>expressly inert</a> or
    not <a>being rendered</a>,
    then let <var>searchOrigin</var> be the [=boundary box=] of <var>focus target</var>.
2. If <var>focus target</var> is <a>removed</a>,
    then let <var>searchOrigin</var> be the [=boundary box=] of <var>focus target</var> with the position of <var>focus target</var> when it existed.
3. If <var>focus target</var> is completely off-screen,
    then let <var>searchOrigin</var> be the viewport of <var>focus target</var>'s nearest visible <a>spatial navigation container</a>.

NOTE: The User Agent should <a>update the search origin</a>, for example,
when the focused element was scrolled out by mouse scrolling or vanished from the viewport.
</div>

<div algorithm="to find focusable areas">

To <dfn lt="find focusable areas | finding focusable areas">find focusable areas</dfn> within a containing element <var>C</var>,
with an optional <var>visibleOnly</var> argument that defaults to <code>true</code>,
run the following steps:

1. Let <var>focusables</var> be the <a spec=infra for="/">set</a> of all the <a>focusable areas</a> whose [=DOM anchor=] are descendants of <var>C</var>.
    In the case of [=boxes=] with several [=box fragments=], each [=box fragment=] is considered separately.
2. The User Agent should <a spec=infra for=set>remove</a> from <var>focusables</var> items that have a [=DOM anchor=] whose <a element-attr spec=html><code>tabindex</code></a> attribute is set to a negative value.

    Note: This is a "SHOULD" in order to mirror the exclusion of elements with negative tabindex
    from the <a>sequential focus navigation order</a> as defined in <a>tabindex</a>.
3. If <var>visibleOnly</var> is <code>false</code>,
    return <var>focusables</var>.

    Note: <var>focusables</var> may be empty
4. Let <var>visibles</var> be the subset of items in <var>focusables</var>
    whose <a>boundary box</a>
    is at least partly within the <a>inside area</a> of <var>C</var>.

    <div class="advisement non-normative">
    Except for elements that are in the currently non visible part of a scroller,
    spatial navigation does not automatically exclude
    elements which cannot be clicked on,
    for example, due to being obscured by some other element.
    To avoid breaking assumptions in
    the application logic if a user actually focuses and activates such an element,
    and to avoid confusing users by focusing invisible or apparently unreachable elements,
    the author should use make these elements unreachable to spatial navigation
    using the same best practices as for making elements unreachable to sequential navigation,
    such as using <code>tab-index="-1"</code>
    or the <a href="https://github.com/WICG/inert"><code>inert</code></a> attribute.
    </div>

5. Return <var>visibles</var>.

    Note: <var>visibles</var> may be empty

</div>

<div algorithm="to select the best candidate">

To <dfn lt="select the best candidate | selecting the best candidate">select the best candidate</dfn>
within a <a spec=infra for="/">set</a> of <var>candidates</var>
in a direction <var>dir</var>,
starting from <var>searchOrigin</var>,
run the following steps:

1. If <var>candidates</var> is <a spec=infra for=set>empty</a>, return <code>null</code>
2. If <var>candidates</var> contains a single item, return that item
3. Let <var>insiders</var> be the subset of <var>candidates</var>
    * whose boundary box fully overlaps with <a>inside area</a> of <var>searchOrigin</var>
    * whose boundary box partially overlaps with <a>inside area</a> of <var>searchOrigin</var> as
        * top edge is below the top edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/down}}
        * bottom edge is above the bottom edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/up}}
        * right edge is left of the right edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/left}}
        * left edge is right of the left edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/right}}

        NOTE: More detail condition about how the element is overlapped with the search origin affects the sequence of focus movement.
        The sequence of focus movement is related to UX, so it depends on the UA-defined mechanism.

    Note: this sub-setting is necessary to avoid going in the opposite direction than the one requested.
4.
    * If <var>insiders</var> is non empty,
        1. Let <var>closest subset</var> be the subset of <var>insiders</var> whose <a>boundary box</a>'s
            * top edge is closest to the top edge of <a>inside area</a> of <var>searchOrigin</var> if <var>dir</var> is {{SpatialNavigationDirection/down}}
            * bottom edge is closest to the bottom edge of <a>inside area</a> of <var>searchOrigin</var> if <var>dir</var> is {{SpatialNavigationDirection/up}}
            * right edge is closest to the right edge of <a>inside area</a> of <var>searchOrigin</var> if <var>dir</var> is {{SpatialNavigationDirection/left}}
            * left edge is closest to the left edge of <a>inside area</a> of <var>searchOrigin</var> if <var>dir</var> is {{SpatialNavigationDirection/right}}
        2. If <var>closest subset</var> contains a single item,
            return that item,
            else return the first item of <var>closest subset</var> in document order,
            unless its [=boundary box=] overlaps with the [=boundary box=] of another item
            and that item is higher in the CSS [=painting order=].
            In that case, return that item instead,
            unless it too is overlapped with another higher item, recursively.
    * Else
        1. Set <var>candidates</var> be the subset of its items which satisfies one of the following conditions:
            * the item doesn't overlap with <var>searchOrigin</var> and its <a>boundary box</a>'s
                * top edge is below the bottom edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/down}}
                * bottom edge is above the top edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/up}}
                * right edge is left of the left edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/left}}
                * left edge is right of the right edge of <var>searchOrigin</var>'s <a>boundary box</a> if <var>dir</var> is {{SpatialNavigationDirection/right}}

        2. For each <var ignore="">candidate</var> in <var>candidates</var>,
            [=find the shortest distance=] between <var>searchOrigin</var>.
        3. Return the item of the <var>candidates</var> set that has the smallest distance.
            If several have the same distance,
            return the first one in document order,
            unless its [=boundary box=] overlaps with the [=boundary box=] of another item at the same distance,
            and that item is higher in the CSS [=painting order=].
            In that case, return that item instead,
            unless it too is overlapped with another higher item at the same distance, recursively.

</div>

<div algorithm="to find the shortest the distance">
To <dfn lt="find the shortest distance | finding the shortest distance">find the shortest distance</dfn>
between a <var>reference</var> and a <var>candidate</var>
in direction <var>dir</var>,
find the points <var>P1</var> and <var>P2</var>,
respectively within the boundary boxes of the <var>reference</var> and of the <var>candidate</var>,
that minimize the <var>distance</var> as defined as below:

<pre class="prod">
    <var>distance</var> = <var>euclidean</var> + <var>displacement</var> - <var>alignment</var> - <var>sqrt(Overlap)</var>
</pre>

The meaning of each term is as follows:

<dl dfn-type="value" dfn-for="spatial-navigation-distance-function">
    <dt><var>euclidean</var>
    <dd>
        The euclidean distance between <var>P1</var> and <var>P2</var>

    <dt><var>displacement</var>
    <dd>
        The degree of displacement in <var>dir</var> between the <var>reference</var> and the <var>candidate</var>,
        defined as
        <pre><code>
            <var>displacement</var> = (absolute distance on the axis orthogonal to <var>dir</var> between <var>P1</var> and <var>P2</var> +
                            <var>orthogonalBias</var>) *
                           <var>orthogonalWeight</var>
        </code></pre>

    <dt><var>orthogonalBias</var>:
    <dd>
        * If the <var>dir</var> is {{SpatialNavigationDirection/left}} or {{SpatialNavigationDirection/right}},
            the height of the axis-aligned bounding box of <var>reference</var> / 2
        * Else if the <var>dir</var> is {{SpatialNavigationDirection/up}} or {{SpatialNavigationDirection/down}},
            the width of the axis-aligned bounding box of <var>reference</var> / 2

    <dt><var>orthogonalWeight</var>:
    <dd>
        * If the <var>dir</var> is {{SpatialNavigationDirection/left}} or {{SpatialNavigationDirection/right}}, 30
        * Else if the <var>dir</var> is {{SpatialNavigationDirection/up}} or {{SpatialNavigationDirection/down}}, 2

    <dt><var>alignment</var>
    <dd>
        The degree of alignment in <var>dir</var> between the <var>reference</var> and the <var>candidate</var>,
        defined as:
        <pre><code>
            <var>alignment</var> = <var>alignBias</var> * <var>alignWeight</var>
        </code></pre>

    <dt><var>alignBias</var>:
    <dd>
        * If the <var>dir</var> is {{SpatialNavigationDirection/left}} or {{SpatialNavigationDirection/right}},
            <var>projectedOverlap</var> / height of the axis-aligned bounding box of <var>reference</var>
        * Else if the <var>dir</var> is {{SpatialNavigationDirection/up}} or {{SpatialNavigationDirection/down}},
            <var>projectedOverlap</var> / width of the axis-aligned bounding box of <var>reference</var>

    <dt><var>projectedOverlap</var>:
    <dd>
        * If the <var>dir</var> is {{SpatialNavigationDirection/left}} or {{SpatialNavigationDirection/right}},
            the length of the overlap between the horizontal projections onto the vertical axis
            of the <var>reference</var> and the <var>candidate</var>
        * Else if the <var>dir</var> is {{SpatialNavigationDirection/up}} or {{SpatialNavigationDirection/down}},
            the length of the overlap between the vertical projections onto the horizontal axis
            of the <var>reference</var> and the <var>candidate</var>

	    <figure>
		    <img alt="" src="images/projected_overlap.png" style="width: 500px;"/>
		    <figcaption>projectedOverlap</figcaption>
	    </figure>

    <dt><var>alignWeight</var>:
    <dd>5

    <dt><var>sqrt(Overlap)</var>
    <dd>
        The square root of area of overlap between the <var>reference</var> and the <var>candidate</var>,
        or 0 if they do not overlap.
</dl>

Note: This general formula was picked from several plausible alternatives,
based on which one most often matches intuition
when used to select the best candidate
in a series of <a href="https://wicg.github.io/spatial-navigation/tests/ux/list.html">UX test cases</a>.
Similarly, the values of <var>alignWeight</var> and <var>orthogonalWeight</var>
were also determined experimentally based on the same test cases.
The resulting formula is somewhat complicated,
but seems to give good answers.
Suggestions for improvements or simplifications are welcome.

</div>

<div class=cssapi>
<h2 id=declarative>
Controlling spatial navigation through declarative means</h2>

<h3 id=container>
Creating additional spatial navigation containers: the 'spatial-navigation-contain' property</h3>

<pre class='propdef'>
Name: spatial-navigation-contain
Value: auto | contain
Initial: auto
Inherited: no
</pre>

<dl dfn-for=spatial-navigation-contain dfn-type=value>
    <dt><dfn>auto</dfn>
    <dd>If the element is a <a>scroll container</a>
        then it establishes a <a>spatial navigation container</a>,
        otherwise it does not.

    <dt><dfn>contain</dfn>
    <dd>The element establishes a <a>spatial navigation container</a>
</dl>

Note: In addition, as per [[#grouping]], the viewport of a <a for="/">browsing context</a>
        (not limited to the <a>top-level browsing context</a>)
        also establishes a <a>spatial navigation container</a>.

<div class=example>
    The following example shows a simplified TV program schedule or calendar.
    It has a grid of elements representing TV shows or calendar entries
    and some UI buttons around it.

    In this case, the grid is quite sparse,
    so if the user tries to move down from "Foo",
    focus would be moved to "Next Week",
    as it is objectively closer in the down direction.
    The same is true for going down from "Bar":
    the focus would move to "Previous Week".

    <div class=output>
        <div id=example-cal>
            <button>Previous Week</button>
            <table>
                <tr><td><th>M<th>T<th>W<th>T<th>F<th>S<th>S
                <tr><td>0-6<td><td><td><td><td><td><td><a href="#">Foo</a>
                <tr><td>6-9<td><a href="#">Bar</a><td><td><td><td><td><td>
                <tr><td>9-12<td><td><a href="#">Bat</a><td><td><td><td><td>
                <tr><td>12-18<td><td><td><td><td><td><td>
                <tr><td>18-21<td><td><td><td><td><td><td><a href="#">Woo</a>
                <tr><td>21-24<td><td><td><td><td><td><a href="#">Baz</a><td>
            </table>
            <button>Next Week</button>
        </div>
        <style>
        #example-cal table, #example-cal td, #example-cal th {
            border-collapse: collapse;
            border: solid 1px;
        }
        #example-cal th { text-align: center; }
        #example-cal td { width: 12.5%; }
        #example-cal {
            display: grid;
            grid-template-columns: auto 1fr auto;
        }
        #example-cal button { align-self: center; }

        /* For browsers that don't support grid */
        #example-cal table {
            display:inline-table;
            vertical-align: middle;
        }
        </style>
    </div>
    <pre><code highlight=markup>
        &lt;div>
            &lt;button>Previous Week&lt;/button>
            &lt;table>
                &lt;tr>&lt;td>&lt;th>M&lt;th>T&lt;th>W&lt;th>T&lt;th>F&lt;th>S&lt;th>S
                &lt;tr>&lt;td>0-6&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;a href="#">Foo&lt;/a>
                &lt;tr>&lt;td>6-9&lt;td>&lt;a href="#">Bar&lt;/a>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>
                &lt;tr>&lt;td>9-12&lt;td>&lt;td>&lt;a href="#">Bat&lt;/a>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>
                &lt;tr>&lt;td>12-18&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>
                &lt;tr>&lt;td>18-21&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;a href="#">Woo&lt;/a>
                &lt;tr>&lt;td>21-24&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;td>&lt;a href="#">Baz&lt;/a>&lt;td>
            &lt;/table>
            &lt;button>Next Week&lt;/button>
        &lt;/div>
    </code></pre>

    However, the author may want to provide a different navigation experience
    giving priority to movements inside the grid once you have focused one of its items
    because the elements in the table are semantically related to each other.

    Adding <code highlight=css>table { spatial-navigation-contain: contain; }</code> to the stylesheet
    would result this behavior.

    After that, the focus would move down from "Foo" to "Woo" instead of "Next Week",
    and from "Bar" to "Bat" instead of "Previous Week".

    It would still be possible to move the focus out of the table.
    For example, the focus would move to "Next week" by going right from "Foo"
    since there is nothing in the grid that is to the right.
</div>

Note: the 'spatial-navigation-contain' property is <a>at-risk</a>.

</div>

<h3 id=css-property-spatialnavigationaction>
Controlling the interaction with scrolling: the 'spatial-navigation-action' property</h3>

<pre class='propdef'>
Name: spatial-navigation-action
Value: auto | focus | scroll
Initial: auto
Applies to: <a>scroll containers</a>
Inherited: no
</pre>

When the focus is inside of a scroll container and the user triggers spatial navigation,
it is somewhat ambiguous whether they are requesting that the focus be moved in that direction,
or whether the document should be scrolled in that direction.
By default, this is automatically determined,
but this property allows the author to decide between focusing or scrolling.

The precise behavior is defined in [[#nav]],
but a high level description of the effect of each value is provided below.

When spatial navigation is triggered,
the behavior depends on the value of the 'spatial-navigation-action' on the currently focused element
if that element is a [=scroll container=],
or of its nearest [=scroll container=] ancestor if it isn't.

<dl dfn-for=spatial-navigation-action dfn-type=value>
    <dt><dfn>auto</dfn>
    <dd>
        If there are visible focusable elements within the
        [=scroll container=] in the direction requested,
        the closest one becomes focused.
        Otherwise, the [=scroll container=] is scrolled in the direction requested.

    <dt><dfn>focus</dfn>
    <dd>
        The focus is moved to the nearest focusable element within the [=scroll container=],
        regardless of whether it is visible.
        If there are none,
        the scroll container is <em>not</em> scrolled,
        and the search continues up the ancestry chain instead.

        Note: The [=scroll container=] may be scrolled as a side effect of focusing
        an element which was previously not in view,
        but it will not <a>be directionally scrolled</a>.

        Note: If the ''spatial-navigation-action/focus'' value is given to 'spatial-navigation-action',
        <a event>navnotarget</a> event occurs when there isn’t any visible candidate in the given direction within the viewport of
        the <a>spatial navigation container</a> even if the container can be scrolled more.

    <dt><dfn>scroll</dfn>
    <dd>
        If the currently focused element is not itself a [=scroll container=],
        this value on an ancestor [=scroll container=] has the same effect as ''spatial-navigation-action/auto''.

        If the currently focused element is a [=scroll container=],
        it is scrolled in the direction requested without changing which element is in focus,
        regardless of the presence of focusable descendants.

        Note: This means that spatial navigation can be used
        to move the focus to a [=scroll container=] and to scroll it,
        but not to move the focus to its descendants.
        However, if the focus is moved to a descendant by some other mean
        (such as pressing the <span class=key>Tab</span> key or using the <{{HTMLOrSVGElement/focus()}}> method)
        spatial navigation can be used to move the focus to other focusable descendants.

        Note: The ''spatial-navigation-ation/scroll'' value is <a>at-risk</a>.
</dl>

Note: Earlier version of this specification did not offer a declarative way
to opt into the behavior defined by ''spatial-navigation-action/focus'',
and instead offered a cancellable event that would be fired before scrolling,
so that the author could implement that behavior themselves.
However, cancellable events related to scrolling can cause performance problems,
so this event was removed and the 'spatial-navigation-action' property was introduced instead.

<div class=example>
In this example, a scrollable container is specified with <code highlight=css>spatial-navigation-action: focus</code>.
Inside the container, there is an element which is out of the view within a <a>scrollport</a>.
Pressing the down arrow key moves the focus directly to it without scrolling manually.

    <figure>
        <img alt="" src="images/spatnav-action.png" style="width: 500px;"/>
        <figcaption>Moving focus from "Box 2" to "Box 3" without manually scrolling</figcaption>
    </figure>

    <pre><code highlight=markup>
        &lt;div class='scroller'>
            &lt;button class='item'>Box 1&lt;/button>
            &lt;button class='item'>Box 2&lt;/button>
            &lt;button class='item'>Box 3&lt;/button>
        &lt;/div>
    </code></pre>
    <pre><code highlight=css>
        .scroller {
            display: grid;
            grid-template-columns: repeat(1, 1fr);
            height: 300px;
            width: 200px;
            overflow-y: scroll;
            spatial-navigation-action: focus;
        }
        .item {
            height: 100px;
            width: 100px;
            margin: 50px auto;
            background-color: blue;
        }
        :focus {
            background-color: red;
        }
    </code></pre>

</div>

<h3 id=css-property-spatialnavigationfunction>
Selecting the navigation algorithm: the 'spatial-navigation-function' property</h3>

<pre class='propdef'>
Name: spatial-navigation-function
Value: normal | grid
Initial: normal
Applies to: <a>spatial navigation containers</a>
Inherited: no
</pre>

The default algorithm of spatial navigation specified in the [[#processing-model]] may need the fine tune depending on the layout types.
This property allows the author to indicate which navigation algorithm is reasonable for spatial navigation behavior.

Its values are defined as follows:

<dl dfn-for=spatial-navigation-function dfn-type=value>
    <dt><dfn>normal</dfn>
    <dd>
        Moves the focus with the default focus navigation algorithm defined by UA.

        In general, the focus moves to the element with the closest distance calculated by <a>finding the shortest distance</a>.

    <dt><dfn>grid</dfn>
    <dd>
        Moves the focus to the element which is aligned most in the navigation direction.

        * If there are more than one aligned candidates in the navigation direction,
             select the element with the closest distance along the axis which corresponds to the navigation direction.
            In case of multiple elements with the same distance,
             select the element with the minimum amount of alignment.

        * Else if there isn't any aligned candidate in a given direction,
             select the element with the closest distance along the axis which corresponds to the navigation direction.
            In case of multiple elements with the same distance,
             select the element with the minimum distance along the axis which is orthogonal to the navigation direction.
</dl>

NOTE: These values are negotiated with the users' preferences which seems natural spatial navigation behavior for their pages.

<div class=example>
    This example shows how the focus moves differently by the value of <code highlight=css>spatial-navigation-function</code>.

    <figure>
        <img alt="" src="images/spatnav-function.png" style="width: 500px;"/>
        <figcaption>Moving focus from "A" to one of the candidate elements</figcaption>
    </figure>

    Let the element which contains "A", "B" and "C" is the <a>spatial navigation container</a>.

    When the user presses the down arrow key,
    if <code highlight=css>normal</code> value is given to <code highlight=css>spatial-navigation-function</code> of the element, the focus will move to "B".
    Otherwise, <code highlight=css>grid</code> value was specified to the element, the focus will move to "C".
</div>

<h2 class=no-num id=scrolling>Appendix A. Scroll extensions</h2>

This section proposes a few extensions to CSS
that should be integrated in upstream specifications,
but are hosted here until then.

<div algorithm>

Issue(w3c/csswg-drafts#2322): Terminology like this should be in [[CSSOM-VIEW-1]], [[CSS-OVERFLOW-3]], [[CSS-SCROLL-SNAP-1]].

An element <var>e</var> <dfn lt="can be manually scrolled | can be scrolled manually | cannot be scrolled manually | cannot be manually scrolled">can be manually scrolled</dfn> in a given direction <var>d</var> if:
* The <a>principal box</a> established by <var>e</var> is a <a>scroll container</a>, and
* if <var>d</var> is <code>up</code> or <code>down</code>, the computed value of the 'overflow-y' property is not ''overflow/hidden'', and
* if <var>d</var> is <code>left</code> or <code>right</code>, the computed value of the 'overflow-x' property is not ''overflow/hidden'', and
* <var>e</var> is not at the <a>scroll boundary</a> in the direction <var>d</var>
* <var>e</var> is not snapped to the last ''mandatory'' snap point in direction <var>d</var>

</div>

<div algorithm="to directionally scroll an element">

Issue(w3c/csswg-drafts#2323): [[CSSOM-VIEW-1]] should probably define
how to perform a scroll in a given direction without an explicit position.
Until then, we roll our own.

To <dfn lt="directionally scroll an element | directionally scroll the element | be directionally scrolled">directionally scroll an element</dfn> <var>e</var> in direction <var>dir</var>:

1. Let <var>d</var> be a User Agent defined distance.
2. Let <var>x</var> be <var>e</var>’s current scroll position on the x axis.
3. Let <var>y</var> be <var>e</var>’s current scroll position on the y axis.
4. Use the <a spec=CSSOM-VIEW-1>scroll an element</a> algorithm from [[!CSSOM-VIEW-1]] on <var>e</var> to
    * (<var>x</var>, <var>y</var> - <var>d</var>) if <var>dir</var> is <code>up</code>
    * (<var>x</var>, <var>y</var> + <var>d</var>) if <var>dir</var> is <code>down</code>
    * (<var>x</var> - <var>d</var>, <var>y</var>) if <var>dir</var> is <code>left</code>
    * (<var>x</var> + <var>d</var>, <var>y</var>) if <var>dir</var> is <code>right</code>

</div>

<h2 class=no-num id=privsec>
Appendix B. Privacy and Security Considerations</h2>

The specification contributors believe that
all known potential security risks associated with this specification
have been adequately addressed.
Further details are provided below.

The TAG has developed a self-review questionaire
to help editors and Working Groups evaluate the risks introduced by their specifications.
Answers are provided below.

<dl>
  <dt>Does this specification deal with personally-identifiable information?
  <dd>No.

  <dt>Does this specification deal with high-value data?
  <dd>No.

  <dt>Does this specification introduce new state for an origin that persists across browsing sessions?
  <dd>No.

  <dt>Does this specification expose persistent, cross-origin state to the web?
  <dd>No.

  <dt>Does this specification expose any other data to an origin that it doesn’t currently have access to?
  <dd>
    Mostly, no.

    The one exception identified would be in the following scenario:
    if the author uses `window.navigate` while the focus is in a cross origin iframe,
    if they don't get an event at all it means that either there was something scrollable or focusable within the iframe,
    as the only case where they'd get an event is when the search didn't find anything at all goes up the tree.

    This is so limited information that it does not seem it would introduces real a security risk,
    but it is as far as the editors can tell information that the author could not get could not get otherwise.

  <dt>Does this specification enable new script execution/loading mechanisms?
  <dd>No.

  <dt>Does this specification allow an origin access to a user’s location?
  <dd>No.

  <dt>Does this specification allow an origin access to sensors on a user’s device?
  <dd>No.

  <dt>Does this specification allow an origin access to aspects of a user’s local computing environment?
  <dd>No.

  <dt>Does this specification allow an origin access to other devices?
  <dd>No.

  <dt>Does this specification allow an origin some measure of control over a user agent’s native UI?
  <dd>
    No control is given over the appearance of the User Agent's UI.
    Some control is given over how the User Agent performs spatial navigation,
    which may be considered part of its user interface.
    This is intentional, to let the author tailor the behavior of spatial navigation to their pages.
    To prevent malicious the author to interefere with the users' desire to control focus and navigate the document,
    this overriding mechanism is disabled by default for cross-origin iframes.
    See [[#policy-feature]].

  <dt>Does this specification expose temporary identifiers to the web?
  <dd>No.

  <dt>Does this specification distinguish between behavior in first-party and third-party contexts?
  <dd>No.

  <dt>How should this specification work in the context of a user agent’s "incognito" mode?
  <dd>No Difference.

  <dt>Does this specification persist data to a user’s local device?
  <dd>No.

  <dt>Does this specification have a "Security Considerations" and "Privacy Considerations" section?
  <dd>Yes, this is the section you are reading now.

  <dt>Does this specification allow downgrading default security characteristics?
  <dd>
    It does not allow downgrading any unrelated security mechanism.

    It **does** allow the author to opt into allowing
    the events needed to override the default behavior of spatial navigation
    in cross origin iframes they trust
    using [[feature-policy]].
    See [[#policy-feature]].
</dl>

<h2 class=no-num id=ack>Acknowledgements</h2>

The editors of this specification would like to thank the following individuals for their feedback and contributions (in alphabetical order):
* Alice Boxhall
* Brian Kardell
* Elika Etemad
* Eric Seong
* Hugo Holgersson
* Hyojin Song
* Jeonghee Ahn
* Junho Seo
* Rob Dodson
* Seungcheon Baek

<h2 class="no-num" id="changes">Changes</h2>

<em>This section is non-normative.</em>

	The following changes were made since the <a href="https://www.w3.org/TR/2019/WD-css-nav-1-20190423/">23 April 2019 First Public Working Draft</a>.

    * Changed the result of {{getSpatialNavigationContainer()}} to return the nearest <a>spatial navigation container</a> ancestor
    * Added 'spatial-navigation-function'
    * Added <a>updating the search origin</a> step
    * Changed the IDL of {{spatialNavigationSearch()}} as separating the dir attribute from {{SpatialNavigationSearchOptions}}
    * Made the focusable element fully overlapped with search origin which is not the <a>spatial navigation container</a> as a candidate for fixing the unreachability
