Skip to content

Instantly share code, notes, and snippets.

@bencroker
Last active October 30, 2024 19:27
Show Gist options
  • Save bencroker/ea2b8c80cbc1ef58bdd5d4bf03b8ad74 to your computer and use it in GitHub Desktop.
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.
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'));
},
}
<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