diff --git a/packages/params/README.md b/packages/params/README.md new file mode 100644 index 0000000..d862968 --- /dev/null +++ b/packages/params/README.md @@ -0,0 +1,225 @@ +# Alpine History: Param Persistance for AlpineJS + +[](https://www.npmjs.com/package/@ekwoka/alpine-history) + + +[](https://bundlephobia.com/package/@ekwoka/alpine-history) + +> This exposes a simple magic `$query` to allow syncing and persisting values in an Alpine Component to the URL query string. This is useful for things like search forms, where you want to be able to share a link to the search results. + +## Install + +```sh +npm i @ekwoka/alpine-history +``` + +Import to Build (Simple Version): + +```js +import Alpine from 'alpinejs'; +import Params from '@ekwoka/alpine-history'; + +Alpine.plugin(Params); // key used for your Cloudinary with Fetch API + +window.Alpine = Alpine; +Alpine.start(); +``` + +## Usage: + +When you want to sync a value to the URL query string, simply use the `$query` magic property when defining your Alpine component: + +```html +
+ + +
+``` + +Now you will see as you type in the input, the URL will update to include the query string `?search=your+input+here`. Refresh the page and your value will be restored! It's so easy! + +You can even go back and forward in the navigation! It's like magic! + +> This adds `Alpine.query` to allow this to be used in contexts that don't have Magics available, like when using `Alpine.data`. + +## Options + +The Query Interceptor exposes a few handy helpers to customize the behavior. These are available as methods to call after defining your initial value. + +### `.as(name: string)` + +By default, the query key will be the path in your component from the root until where the query is used. `as` can be used to customize the name of the query key. + +```html +
+``` + +This will now use `q` as the query key instead of `search`. + +When the `$query` is nested in an object or array, the key in the query param will be visible as `key[key][key]` in the query string. This can be customized by using `as` on the parent object or array. For example: + +```js +{ + search: { + query: $query('hello'), + }, +} +``` + +would be `?search[query]=hello` by default. + +### `.alwaysShow()` + +By default, if the current value of the query is the same as the defined initial value, the query will not be shown in the URL. This can be overridden by calling `.alwaysShow()`. + +```js +{ + search: $query('hello').as('q').alwaysShow(), // ?q=hello +} +``` + +### `.usePush()` + +By default, the query will be updated using `history.replaceState` to avoid adding a new entry to the browser history. This can be overridden by calling `.usePush()`. This should be used when the query is used to handle major state changes for the user, but will likely be less useful for quickly updating minor steps. + +```js +{ + episodeId: $query('').as('eid').usePush(); +} +``` + +Whenever `episodeId` the URL will be updated with `?eid=123` and a new entry will be added to the browser history. + +This plugin also implements a `popstate` listener to note when the user navigates back or forward in the browser history. This will update the value of the query to match the URL. Two way binding! + +### `.into(fn: Transformer)` + +Naturally, query params are always strings. If you want to handle numbers or booleans, or other types, you can use the `.into` method to transform the value before it is used in your component. + +```js +{ + episodeId: $query('').as('eid').into(Number); +} +``` + +Now, `episodeId` will be a number instead of a string when loaded from the query string. + +This only handles how the value is converted from the query string. It will not affect how the value is converted to a string when updating the query string. Due to this, object types that aren't simple objects or arrays will not work as expected. Speaking of... + +#### `Transformer` + +For TypeScript people, here's the type signature for the transformer: + +```ts +type Transformer = (val: T | PrimitivesToStrings) => T; + +type PrimitivesToStrings = T extends string | number | boolean | null + ? `${T}` + : T extends Array + ? Array> + : T extends object + ? { + [K in keyof T]: PrimitivesToStrings; + } + : T; +``` + +Note, the transformer will need to be able to handle being called with the type of the value or a simply parsed structure that equates to all primitives being strings. This is because the transformer will be called with the value when initializing, which can be the provided value, or the one determined from the query string. + +When writing your transformer as a literal or typed function, TypeScript should help guide you to a properly formatted transformer. + +Additionally, if you have an initial value that contains non-string primitives, the value of the key on the data context will resolve to `never` which should indicate, if you attempt to use it, that you need to add a transformer. + +```ts +{ + episodeId: $query(123), // never + seasonNumber: $query(1).into(Number), // number +} +``` + +## Arrays and Objects + +This plugin supports arrays and objects as well! It will automatically treat objects and arrays as if they are made up of `$query` interceptors. For example: + +```js +{ + search: $query({ + query: 'hello', + results: ['1', '2', '3'], + }), +} +``` + +will be `?search[query]=hello&search[results][0]=1&search[results][1]=2&search[results][2]=3` by default. + +If you have nested primitives like booleans and numbers, you can use `.into` to transform them, but your transformer will need to handle the nested values. + +```js +{ + search: $query({ + query: 'hello', + results: [1, 2, 3], + }).into((obj) => { + obj.results = obj.results.map(Number); + }), +} +``` + +You may choose to use separate `$query` interceptors to make this simpler. + +## Reactivity + +All normal reactive behaviors apply to the `$query` interceptor. You can hook up effects to them, and just have a grand old time. + +## What This Doesn't Do + +This plugin does not do anything to manage params not associated with an `$query` interceptor. This means that if you have a query string like `?search=hello&sort=asc` and you only have a `$query` interceptor for `search`, the `sort` param will be perpetuated during query string updates. + +This does not directly expose anything for triggering events or handlers on query string changes. As the query interceptors are reactive, you can hook directly into the ones you care about and use Alpine Effects to trigger events or other behaviors. + +## Use outside of Alpine + +This Alpine plugin can actually be used outside of Alpine, though it's obviously not ideal for many reason. It's a bit of a hack, but it works! + +```ts +import { QueryInterceptor } from '@ekwoka/alpine-history'; + +const params: Record = {}; // internal object structure to store the params + +const myData = { + search: '', +}; + +new QueryInterceptor( + '', + { + raw: (v: T): T => { + v; + }, + }, + params, +) + .as('q') + .initialize(myData, 'search'); +``` + +Not example pretty, but it works! + +This can allow you to use other reactive objects, like Solid Stores. But mostly, this is a hack, but fun! + +## Author + +👤 **Eric Kwoka** + +- Website: http://thekwoka.net +- Github: [@ekwoka](https://github.com/ekwoka) + +## Show your support + +Give a ⭐️ if this project helped you! diff --git a/packages/params/src/index.ts b/packages/params/src/index.ts index e2f0dba..ef4717f 100644 --- a/packages/params/src/index.ts +++ b/packages/params/src/index.ts @@ -7,18 +7,43 @@ import { insertDotNotatedValueIntoData, } from './pathresolve'; -class QueryInterceptor implements InterceptorObject { +type InnerType = T extends PrimitivesToStrings + ? T + : S extends Transformer + ? T + : T | PrimitivesToStrings; + +/** + * This is the InterceptorObject that is returned from the `query` function. + * When inside an Alpine Component or Store, these interceptors are initialized. + * This hooks up setter/getter methods to to replace the object itself + * and sync the query string params + */ +export class QueryInterceptor< + T, + S extends Transformer | undefined = undefined, +> implements InterceptorObject> +{ _x_interceptor = true as const; private alias: string | undefined = undefined; - private transformer: Transformer | null = null; + private transformer?: S; private method: 'replaceState' | 'pushState' = 'replaceState'; private show: boolean = false; + public initialValue: InnerType; constructor( - public initialValue: T, - private Alpine: Alpine, + initialValue: T, + private Alpine: Pick, private reactiveParams: Record, - ) {} - initialize(data: Record, path: string) { + ) { + this.initialValue = initialValue as InnerType; + } + /** + * Self Initializing interceptor called by Alpine during component initialization + * @param {object} data The Alpine Data Object (component or store) + * @param {string} path dot notated path from the data root to the interceptor + * @returns {T} The value of the interceptor after initialization + */ + initialize(data: Record, path: string): InnerType { const { alias = path, initialValue, @@ -26,9 +51,8 @@ class QueryInterceptor implements InterceptorObject { transformer, show, } = this; - const initial = - (retrieveDotNotatedValueFromData(alias, reactiveParams) as T) ?? - initialValue; + const initial = (retrieveDotNotatedValueFromData(alias, reactiveParams) ?? + initialValue) as InnerType; const keys = path.split('.'); const final = keys.pop()!; @@ -49,8 +73,11 @@ class QueryInterceptor implements InterceptorObject { enumerable: true, }); - return transformer?.(initial) ?? initial; + return (transformer?.(initial) ?? initial) as InnerType; } + /** + * Sets the query string params to the current reactive params + */ private setParams() { const { reactiveParams, method, Alpine } = this; history[method]( @@ -59,18 +86,34 @@ class QueryInterceptor implements InterceptorObject { `?${toQueryString(Alpine.raw(reactiveParams))}`, ); } + /** + * Changes the keyname for using in the query string + * Keyname defaults to path to data + * @param {string} name Key alias + */ as(name: string) { this.alias = name; return this; } - into(fn: Transformer) { - this.transformer = fn; - return this; + /** + * Transforms the value of the query param before it is set on the data + * @param {function} fn Transformer function + */ + into(fn: Transformer): QueryInterceptor> { + const self = this as QueryInterceptor>; + self.transformer = fn; + return self; } + /** + * Always show the initial value in the query string + */ alwaysShow() { this.show = true; return this; } + /** + * Use pushState instead of replaceState + */ usePush() { this.method = 'pushState'; return this; @@ -96,17 +139,29 @@ export const query: PluginCallback = (Alpine) => { Alpine.magic('query', () => bindQuery); }; -type Transformer = (val: string | T) => T; +export type Transformer = (val: T | PrimitivesToStrings) => T; export default query; declare module 'alpinejs' { interface Alpine { - query: (val: T) => QueryInterceptor; + /** + * Sync a search param in the query string with the value in the Alpine Context + * @param initialValue Value when the query param is not present + * @returns {QueryInterceptor} Self initializing interceptor + */ + query: (initialValue: T) => QueryInterceptor; } } -const intoState = (data: Record) => +/** + * Creates a new object containing the old history state and new query data + * @param {object} data Query Data to inject into the current history state + * @returns {object} New object for the new history state + */ +const intoState = >( + data: Record, +): Record & { query: T } => Object.assign({}, history.state ?? {}, { query: JSON.parse(JSON.stringify(data)), }); @@ -117,10 +172,7 @@ if (import.meta.vitest) { raw(val: T): T { return val; }, - reactive(val: T): T { - return val; - }, - } as unknown as Alpine; + }; afterEach(() => { vi.restoreAllMocks(); }); @@ -271,3 +323,13 @@ if (import.meta.vitest) { }); }); } + +type PrimitivesToStrings = T extends string | number | boolean | null + ? `${T}` + : T extends Array + ? Array> + : T extends object + ? { + [K in keyof T]: PrimitivesToStrings; + } + : T; diff --git a/size.json b/size.json index 84cfc95..a8b17a9 100644 --- a/size.json +++ b/size.json @@ -1,12 +1,12 @@ { "params": { "minified": { - "pretty": "1.84 kB", - "raw": 1842 + "pretty": "1.88 kB", + "raw": 1877 }, "brotli": { - "pretty": "875 B", - "raw": 875 + "pretty": "897 B", + "raw": 897 } }, "xajax": {