Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Turbo Streams: Manage element focus #686

Merged
merged 1 commit into from
Sep 13, 2023

Commits on Sep 13, 2023

  1. Turbo Streams: Manage element focus

    When a `<turbo-stream>` modifies the document, it has the potential to
    affect which element has focus.
    
    For example, consider an element with an `[id]` that has focus:
    
    ```html
    <label for="an-input">
    <input id="an-input" value="an invalid value"> <!-- this element has focus -->
    ```
    
    Next, consider a `<turbo-stream>` element to replace it:
    
    ```html
    <turbo-stream action="replace" target="an-input">
      <template>
        <input id="an-input" value="an invalid value" class="invalid-input">
      </template>
    </turbo-stream>
    ```
    
    Prior to this commit, rendering that `<turbo-stream>` would remove the
    element with focus, and never restore it.
    
    After this commit, the `Session` will capture the `[id]` value of the
    element with focus (if there is any), then "restore" focus to an element
    in the document with a matching `[id]` attribute _after_ the render.
    
    Similarly, consider a `<turbo-stream>` that appends an element with
    `[autofocus]`:
    
    ```html
    <turbo-stream action="append" targets="body">
      <template>
        <input autofocus>
      </template>
    </turbo-stream>
    ```
    
    Prior to this commit, inserting an `[autofocus]` into the document with
    a `<turbo-stream>` had no effect.
    
    After this commit, the `Session` will scan any `<turbo-stream>` elements
    its about to render, extracting the first focusable element that
    declares an `[autofocus]` attribute.
    
    Once the rendering is complete, it will attempt to autofocus that
    element. Several scenarios will prevent that, including:
    
    * there aren't any `[autofocus]` elements in the collection of
      `<turbo-stream>` elements
    * the `[autofocus]` element does not exist in the document after the
      rendering is complete
    * the document already has an element with focus
    seanpdoyle committed Sep 13, 2023
    Configuration menu
    Copy the full SHA
    675f636 View commit details
    Browse the repository at this point in the history