@sv-use/core
Version:
A collection of Svelte 5 utilities.
45 lines (44 loc) • 1.6 kB
JavaScript
import { onDestroy, untrack } from 'svelte';
import { observeMutation } from '../observe-mutation/index.svelte.js';
import { defaultDocument } from '../__internal__/configurable.js';
import { noop, normalizeValue } from '../__internal__/utils.svelte.js';
/**
* Indicates the text writing directionality of the content of an element.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/get-text-direction
*/
export function getTextDirection(options = {}) {
const { element = undefined, observe = false, initial = 'ltr', autoCleanup = true, document = defaultDocument } = options;
let cleanup = noop;
const _element = $derived(element ? normalizeValue(element) : document?.documentElement);
let current = $state(getValue());
// Instead of onMount so we can test the utility
$effect(() => {
untrack(() => {
current = getValue();
});
});
if (observe && document) {
cleanup = observeMutation(() => _element, () => (current = getValue()), { attributes: true, autoCleanup }).cleanup;
}
if (autoCleanup) {
onDestroy(() => cleanup());
}
function getValue() {
return (_element?.getAttribute('dir') ?? initial);
}
function removeAttribute() {
_element?.removeAttribute('dir');
}
return {
get current() {
return current;
},
set current(v) {
current = v;
_element?.setAttribute('dir', current);
},
removeAttribute,
cleanup
};
}