Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/alpine-collective/alpine-magic-helpers

A collection of magic properties and helper functions for use with Alpine.js
https://github.com/alpine-collective/alpine-magic-helpers

alpine alpine-collective alpinejs magic-helper

Last synced: about 2 months ago
JSON representation

A collection of magic properties and helper functions for use with Alpine.js

Awesome Lists containing this project

README

        

[![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/alpine-collective/alpine-magic-helpers?label=version&style=flat-square)](https://www.npmjs.com/package/alpine-magic-helpers)
[![](https://data.jsdelivr.com/v1/package/gh/alpine-collective/alpine-magic-helpers/badge)](https://www.jsdelivr.com/package/gh/alpine-collective/alpine-magic-helpers)
[![npm bundle size](https://img.shields.io/bundlephobia/minzip/alpine-magic-helpers?color=#0F0)](https://bundlephobia.com/result?p=alpine-magic-helpers)

# Magic Helpers

A collection of magic properties and helper functions for use with [Alpine.js](https://github.com/alpinejs/alpine) version 2

:warning: Notice: This collection of helpers will be tied to version 2 of Alpine and will only receive bug fixes and minor updates as needed.

→ New features and plugins for V3 that will be found in the [toolkit repo](https://github.com/alpine-collective/toolkit).

## About

Adds the following magic helpers to use with Alpine JS.
| Magic Helpers | Description |
| --- | --- |
| [`$component/$parent`](#component) | Natively access and update data from other components or the parent component. |
| [`$fetch/$get/$post`](#fetch) | Using Axios, fetch JSON from an external source. |
| [`$interval`](#interval) | Run a function every n milliseconds. Optionally start and stop the timer. |
| [`$range`](#range) | Iterate over a range of values. |
| [`$refresh`](#refresh) | Manually refresh a component. |
| [`$screen`](#screen) | Detect if the current browser width is equal or greater than a given breakpoint. |
| [`$scroll`](#scroll) | Scroll the page vertically to a specific position. |
| [`$truncate`](#truncate) | Limit a text string to a specific number of characters or words. |
| [`$undo`](#undo) | Track and undo state changes inside your component. |

Adds the following custom directives to use with Alpine JS.
| Custom Directives | Description |
| --- | --- |
| [`x-unsafe-html`](#x-unsafe-html) | like x-html but allowing new javascript scripts to run. |

***More to come!***

🚀 If you have ideas for more magic helpers or custom directives, please open a [discussion](https://github.com/alpine-collective/alpine-magic-helpers/discussions) or join us on the [AlpineJS Discord](https://discord.gg/snmCYk3)

**Known issues**
* [Using `$component`/`$parent` in `x-init`](#warning-using-componentparent-in-x-init)
* [Using Magic Helpers with Livewire](#warning-using-magic-helpers-with-livewire)

## Installation

Include the following `` tag in the `<head>` of your document before Alpine:

```html
<script src="https://cdn.jsdelivr.net/gh/alpine-collective/[email protected]/dist/index.min.js" defer>
```

Or you can use the specific magic helpers you need:

```html

```

---

### Manual

If you wish to create your own bundle:

```bash
npm install alpine-magic-helpers --save
```

Then add the following to your script:

```javascript
import 'alpine-magic-helpers'
import 'alpinejs'
```

Or you can import the specific magic helpers you need like so:

```javascript
import 'alpine-magic-helpers/dist/component'
import 'alpine-magic-helpers/dist/fetch'
import 'alpinejs'
```

---

### :warning: **Using Magic Helpers with Livewire**
When using magic helpers along with Laravel Livewire, you need to make sure that the library is registered after Livewire to prevent Livewire from overriding the magic helper startup callbacks. This can be done either using the defer attribute on the magic helper script or including the magic helper script at the bottom of your body after `@livewireScripts` **without** the `defer` attribute.

---

### `$component`
**Example:**

Arguably more useful, this also adds a `$parent` magic helper to access parent data
```html





```
[Demo](https://codepen.io/KevinBatdorf/pen/XWdjWrr)

You may watch other components, but you must give them each an id using the 'id' attribute or `x-id` if you need more flexibility:
```html






```

#### :warning: **Using `$component`/`$parent` in `x-init`**
```html


















```
When a component is initialised, the observed component may not be ready yet due to the way Alpine starts up. This is always true for `$parent` and it occurs for `$component` when the observer is placed before the observed component in the page structure.
Previous versions were using a hack to evaluate the missing x-data on the fly but that strategy wasn't allowing to use nested magic properties and it was not syncronising properly in some edge cases.
The magic helper since version 1.0 defers the resolution of those properties (resolving temporary to empty strings/noop functions) until the observed component is ready and then refreshes the component: this happens in a few milliseconds and it's not noticable by the final users but refreshing a component won't rerun `x-init` with the correct values.
**If developers need to use the magic property inside x-init, they'll need to manually postpone the execution of x-init for one tick either using the Alpine native `$nextTick` or a setTimeout with no duration (See examples above).**

---

### `$fetch`
**Example:**
```html




```
[Demo](https://codepen.io/KevinBatdorf/pen/poyyXKj)

> As a shortcut, you can optionally use `$get(url, params)` or `$post(url, data)` to conveniently send a GET or POST request with params or data as the second argument.

**Optionally pass in an Axios options object**

If you need more control, you may pass in an object to customize the request [See all options](https://github.com/axios/axios).

**Example:**

```html



```
> Note that this will return the entire response object, whereas by default `$fetch` will only return the data

---

### `$interval`
**Example:**
```html



```
[Demo](https://codepen.io/KevinBatdorf/pen/xxVVoaX?editors=1010)

**Optionally pass in options**

By default, `$interval ` will run your function every `nth` millisecond when browser provides an animation frame (via `requestAnimationFrame`). This means that the function will not run if the browser tab is not visible. Optionally, you may pass in the following options as the second parameter:
| Property | Description |
| --- | --- |
| `timer` | Timer in milliseconds. |
| `delay` | Delay the first run. N.B. The first run is also delayed by the timer time. |
| `forceInterval` | Ignore the browser animation request mechanism. Default is false |

> ⚠️ We also add a hidden property `autoIntervalTest` that will clear/stop the timer if set to false, and start the timer if then set to true.

**Example:**

```html




```
[Demo](https://codepen.io/KevinBatdorf/pen/poyyXQy?editors=1010)

---

### `$range`
**Example:**

The `$range` helper mostly mimics implementations found in other languages `$range(start, stop, step = 1)`
```html



...

```
[Demo](https://codepen.io/KevinBatdorf/pen/vYKbPBd)

> N.B: You may use `$range(10)` which will compute to `[1...10]`

---

### `$refresh`
**Example:**
```html


Refresh Date.now()


```
[Demo](https://codepen.io/KevinBatdorf/pen/PobZjrz?editors=1000)

---
### `$screen`
**Example:**

The `$screen` helper detects if the current browser width is equal or greater than a given breakpoint and returns `true` or `false` based on the result.

```html


This will be visible if the window width is equal or greater than 1024px.

```

*By default the `$screen` helper uses the following endpoint borrowed by **Tailwind CSS**:*
- `xs`: 0px
- `sm`: 640px
- `md`: 768px
- `lg`: 1024px
- `xl`: 1280px
- `2xl`: 1536px

> ⚠️ **NOTE**: A single breakpoint is only going to tell you if the browser width is equal or greater than the given breakpoint. If you want to restrict the check to a specific range, you will need to negate the next endpoint as:

```html


This will be visible if screen width is equal or greater than 768px but smaller then 1024px.

```

**Custom breakpoints**

You can pass a numeric value to use an ad-hoc breakpoint.
```html


This will be visible if screen width is equal or greater than 999px.

```

You can also override the default breakpoints including the following `` tag in the `<head>` of your document

```html
<!-- this example uses Bulma's breakpoints. -->
<script>
window.AlpineMagicHelpersConfig = {
breakpoints: {
mobile: 0,
tablet: 769,
desktop: 1024,
widescreen: 1216,
fullhd: 1408
}
}

```
And using those breakpoints in your page.
```html


This will be visible if screen width is equal or greater than 769px.

```

[Demo](https://codepen.io/KevinBatdorf/pen/OJXKRXE?editors=1000)

---

### `$scroll`
**Example:**
```html



...

Scroll to foo

```
[Demo](https://codepen.io/KevinBatdorf/pen/PozVLPy?editors=1000)

Alternatively, you can pass a css selector to scroll to an element at any position.
```html




Scroll to #foo

```

`$scroll` also supports integers to scroll to a specific point of the page.
```html
Scroll to top
```
[Demo](https://codepen.io/KevinBatdorf/pen/PozVLPy?editors=1000) (same as above)

`$scroll` optionally supports a second parameter where it's possible to define the behavior mode, `auto|smooth` (default smooth):
```html



...

Jump to foo

...



Jump to #foo

...
Jump to top
```
With offset:
```html


...

Scroll to 50px before foo

...



Scroll to 50px before #foo

...
Jump to 50px before top (a bit daft but supported)
```
With both:
```html


...

Jump to 50px before foo

...



Jump to 50px before #foo

...
Jump to 50px before top
```
[Demo](https://codepen.io/KevinBatdorf/pen/PozVLPy?editors=1000) (same as above)

---

### `$truncate`
**Example:**
```html




```
You may also pass a third argument to change the string that will be appended to the end:
```html



```
[Demo](https://codepen.io/KevinBatdorf/pen/BaKKgGg?editors=1000)

**Optionally pass in options**

By default, `$truncate` will return take characters as a parameter. Instead you can pass in an object and trim by words. You may also update the ellipsis.

**Example:**

```html




```
[Demo](https://codepen.io/KevinBatdorf/pen/BaKKgGg?editors=1000) (same as above)
> Behind the scenes, for words, this uses `sentence.split(" ").splice(0, words).join(" ")` which does not define a word in all languages.

---
### `$undo`
**Example:**
```html



undo

```
[Demo](https://codepen.io/KevinBatdorf/pen/jOrVzOg?editors=1000)

The `$undo` helper actually involves three helpers in one. First, add the `$track()` helper to the `x-init` directive to start tracking the component state. Next, add a button to `$undo()` changes as needed. And finally, you can access whether changes have occurred by using `$history.length`.

**Optionally pass in options**

By default, `$undo` will track all properties. Optionally you may limit the properties by passing in a string with the property name, or an array of property names.

**Example:**

```html




undo number only

```
> Use `$track(['prop1', 'prop2'])` to track multiple properties

[Demo](https://codepen.io/KevinBatdorf/pen/VwjmXLy?editors=1000)

---
### `x-unsafe-html`
**Example:**
```html



baralert(1)'">test

```

> :warning: **Only use on trusted content.** :warning:
>
> Dynamically rendering HTML from third parties can easily lead to [XSS](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting) vulnerabilities.

[Demo](https://codepen.io/KevinBatdorf/pen/poNYpZb)

---

## License

Copyright (c) 2020 Alpine Collective

Licensed under the MIT license, see [LICENSE.md](LICENSE.md) for details.