Last active
October 30, 2024 19:27
-
-
Save bencroker/ea2b8c80cbc1ef58bdd5d4bf03b8ad74 to your computer and use it in GitHub Desktop.
History plugin for Datastar – sets store values in `data-history` to the URL param values.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AttributeContext, AttributePlugin } from '../types' | |
export const HistoryPlugin: AttributePlugin = { | |
prefix: 'history', | |
mustHaveEmptyKey: true, | |
mustNotEmptyExpression: true, | |
onLoad: (ctx: AttributeContext) => { | |
const { el, expressionFn, store } = ctx | |
const storeNames: string[] = expressionFn(ctx) | |
const params: URLSearchParams = new URLSearchParams(location.search); | |
for (const storeName of storeNames) { | |
const param = params.get(storeName); | |
if (param !== null) { | |
store()[storeName].value = param.split(','); | |
} | |
} | |
el.dispatchEvent(new CustomEvent('history-restore')); | |
}, | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div data-store="{page: 1}" data-history="['page']"> | |
Page: <span data-text="$page"> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment