Code Monkey home page Code Monkey logo

focus-svelte's Introduction

๐Ÿชค focus-svelte

Focus trap for svelte with zero dependencies.

Installation

npm install -D focus-svelte
# yarn add -D focus-svelte
# pnpm add -D focus-svelte

Example

https://svelte.dev/repl/4b31b2f4a45c4ee08230f6d47d31db48

Description

focus-svelte works a bit differently than other focus traps I've encounted. Rather than using an event listener to track user activity and override the default behavior of the browser, the DOM is manipulated instead. All elements outside of an active focus trap's descendants or ancestory have their tabindex set to -1 if it was 0 or greater previously.

To keep track of changes after the trap is enabled, a MutationObserver monitors the DOM for updates. Once all focus traps are disabled or removed, the observer is stopped and the elements' properties are reset. If a focus trap later becomes active, the observer is restarted and nodes are decorated accordingly.

When a trap becomes active for the first time, the HTMLElement that is assigned focus is determined by the configuration options passed to the component or action.

  • If element is assigned and is tabbable, it will be focused upon.
  • If element is undefined or not tabbable and focusable is true, the HTMLElement with use:focus is granted focus.
  • If neither of the previous conditions are met, focus will be placed on the first tabbable element.

Usage

There is both an action and a component that can be utilized.

Options

option description type default
element If element is assigned and is tabbable, it will be focused upon when the trap is enabled. string values will be considered a query selector. Element | string undefined
focusable The HTMLElement the action is assigned to gets a tabindex of 0 when the trap becomes active boolean false
focusDelay can either be a number of ms to wait or an async function that resolves (void) when the focus of an element should be set. number | () => Promise<void> tick
delay Determines how long to wait before batching updates to tabIndex and ariaHidden. number | () => Promise<void> tick
assignAriaHidden When a focus trap becomes enabled and is true, all elements outside of an active trap or their ancestory have their aria-hidden attribute set to "true". boolean false
preventScroll sets preventScroll when focusing. boolean false
enabled If true, the focus trap becomes active. boolean false

action

<script>
	import { focus } from "focus-svelte";
	let enabled = true;
	function toggleFocus() {
		enabled = !enabled;
	}
</script>

<button on:click="{toggleFocus}">{enabled ? "disable" : "enable"} focus</button>

<div use:focus="{enabled}">
	<input value={enabled ? "focus is trapped here" : "regular tabbable input"} />
</div>

<input value={enabled ? "can't tab here" : "can be tabbed into!"} />

With assignAriaHidden

<script>
	import { focus } from "focus-svelte";
	let enabled = true;
	function toggleFocus() {
		enabled = !enabled;
	}
</script>

<button on:click="{toggleFocus}">{enabled ? "disable" : "enable"} focus</button>

<div use:focus="{{enabled, assignAriaHidden: true}}">
	<input value={enabled ? "focus is trapped here" : "regular tabbable input"} />
</div>

<input value={enabled ? "can't tab here" : "can be tabbed into!"} />

component

<script>
	import { Focus } from "focus-svelte";
	let enabled = true;
	function toggleFocus() {
		enabled = !enabled;
	}
</script>

<button on:click="{toggleFocus}">{enabled ? "disable" : "enable"} focus</button>

<Focus {enabled} assignAriaHidden="{true}">
	<input value={enabled ? "focus is trapped here" : "regular tabbable input"} />
</Focus>

<input value={enabled ? "can't tab here" : "can be tabbed into!"} />

Note: As the action needs an HTMLElement, the component version wraps your content with a div.

override

If you wish to override the behavior of an element, you can set data-focus-override="true" and it will retain its original tabindex.

Contributing

Pull requests are always welcome.

License

MIT

focus-svelte's People

Contributors

ayndqy avatar chanced avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

ivoilic

focus-svelte's Issues

consider migrating to WeakMaps instead of data attributes

When there are multiple thousands of nodes, the performance can get a bit janky. Experiment with WeakMap<HTMLElement, {hidden: string[], shown: string[], tabIndex: number | null, ariaHidden: string | null }>

The solution would still need to acquire all elements in the dom and assign them to the map. the MutationObserver would need to stay.

This solution would reduce a lot of reads and writes to the DOM.

Package isn't working anywhere I've tried it

I've tried this package, both in the REPL and on a local project, on Chromium/Firefox on Linux, and in Chrome on macOS. None of them are trapping focus anywhere.

Am I missing something?

preventScroll option

Hi!
I like your library, it's really useful!

In some cases i need to focus on element without scrolling to it (if element behind screen view).
In native JS it looks like this:

element.focus({
  preventScroll: true
});

Can you add this feature to your library?
I think it might look like this:
use:focus={{ enabled: true, preventScroll: true }}

Thanks in advance!

preventScroll option does not work at initial focus

Hi, thank you for your library!

I noticed a bug: when only an element with use:focus={{ enabled: true, preventScroll: true }} is created preventScroll option does not work.

The bug may be in lines 498 and 513 in action/focus.ts file (the value of preventScroll option is not used there).

Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.