|
| 1 | +import type { Attachment } from 'svelte/attachments'; |
| 2 | + |
| 3 | +import type { ActiveOptions } from '~/models/action.model.js'; |
| 4 | +import type { RouteName } from '~/models/route.model.js'; |
| 5 | + |
| 6 | +import { activeStyles, doNameMatch, doPathMatch, ensurePathName, ensureRouter, getOriginalStyle, restoreStyles } from '~/models/action.model.js'; |
| 7 | +import { Matcher } from '~/models/index.js'; |
| 8 | +import { getRouter } from '~/router/context.svelte.js'; |
| 9 | + |
| 10 | +export function useActive(options: ActiveOptions): Attachment { |
| 11 | + const router = getRouter(); |
| 12 | + |
| 13 | + return (element) => { |
| 14 | + if (!ensureRouter(element, router)) return; |
| 15 | + |
| 16 | + const _options = $derived(options); |
| 17 | + const _path: string | null = $derived(options?.path || element.getAttribute('data-path') || element.getAttribute('href')); |
| 18 | + const _name: RouteName | null = $derived(options?.name || element.getAttribute('data-name')); |
| 19 | + |
| 20 | + const caseSensitive = $derived(_options?.caseSensitive ?? router.options?.caseSensitive); |
| 21 | + const matchName = $derived(doNameMatch(router.route, _name, { caseSensitive, exact: _options?.exact })); |
| 22 | + |
| 23 | + const location = $derived(router.location?.path); |
| 24 | + const matcher = $derived(_path ? new Matcher(_path) : undefined); |
| 25 | + const matchPath = $derived(doPathMatch(matcher, _name, location, _options?.exact)); |
| 26 | + |
| 27 | + const match = $derived(matchName || matchPath); |
| 28 | + |
| 29 | + const originalStyle = $derived(getOriginalStyle(element, _options?.style)); |
| 30 | + |
| 31 | + $effect(() => { |
| 32 | + if (match) activeStyles(element, _options); |
| 33 | + else restoreStyles(element, originalStyle, _options); |
| 34 | + }); |
| 35 | + |
| 36 | + $effect(() => { |
| 37 | + ensurePathName(element, { path: _path, name: _name }); |
| 38 | + }); |
| 39 | + }; |
| 40 | +} |
0 commit comments