alpine-collective / alpine-magic-helpers Goto Github PK
View Code? Open in Web Editor NEWA collection of magic properties and helper functions for use with Alpine.js
Home Page: https://npmjs.com/alpine-magic-helpers
License: MIT License
A collection of magic properties and helper functions for use with Alpine.js
Home Page: https://npmjs.com/alpine-magic-helpers
License: MIT License
Flagged on discord. Due to the component using the mutation observer, if nothing changes when updating a property, a child component won't pick it up.
for example
<div x-data="{foo: 'bar'}">
<button x-on:click="foo = 'bob'">test</button>
<div x-data>
<p x-text="$parent.foo"></p>
</div>
</div>
Someone shared this library on work chat, so I'm sharing it here in case you are interested.
https://github.com/developit/redaxios
The Axios API, as an 800 byte Fetch wrapper.
Extract from the README
Axios has a great API that developers love. Redaxios provides that API in 800 bytes, using native fetch()
.
For those searching for ways to shave a few kilobytes off of their bundles, that's less than 1/5th of the size.
For use with $fetch :)
This is really a very helpful package and I am trying to use it inside laravel app.
I have imported both import 'alpine-magic-helpers'; import 'alpinejs';
I am trying to use the $scroll helper and I have tried both $refs and using #id but when I click on the button to scroll to that specific section, It is not working and it shows the following error in the console.
Uncaught (in promise) Error: Unsupported $scroll target: at Proxy.eval (index.js?d52a:2334) at eval (eval at saferEvalNoReturn (alpine.js?df24:1900), <anonymous>:3:21) at saferEvalNoReturn (alpine.js?df24:143) at Component.evaluateCommandExpression (alpine.js?df24:1720) at runListenerHandler (alpine.js?df24:895) at HTMLButtonElement.handler (alpine.js?df24:871) eval @ index.js?d52a:2334 eval @ VM1370:3 saferEvalNoReturn @ alpine.js?df24:143 evaluateCommandExpression @ alpine.js?df24:1720 runListenerHandler @ alpine.js?df24:895 handler @ alpine.js?df24:871 Promise.then (async) handler @ alpine.js?df24:872
Just as a remider the $scroll(0) is working fine.
Thanks in advance
Hi, simple string of code not working:
x-on:submit.prevent="$post($el.dataset.action, new FormData($el))"
and i have exception like:
Alpine Error: "ReferenceError: $post is not defined"
Expression: "$post($el.dataset.action, new FormData($el))"
If we run npm update and we pull the latest version of Alpine, $undo > component can keep track after component is replaced with a clone
starts failing. Not sure if it's a red herring but I think a bug fix/BC went into the latest version around how alpine behaves in regards to a cloned element and it might affect $undo. cc @KevinBatdorf
Hello,
I am new to livewire/alpine and trying to use alpine-magic-helpers Scroll
i want use apline.js lasted version
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
not working and show me this error in console
VM8167:3 Uncaught (in promise) ReferenceError: $scroll is not defined at eval (eval at qr (cdn.min.js:1), <anonymous>:3:16) at cdn.min.js:1 at Br (cdn.min.js:1) at cdn.min.js:5 at o (cdn.min.js:5) at cdn.min.js:5 at HTMLButtonElement.<anonymous> (cdn.min.js:5)
Howdy, somewhat new to the Alpine js world, don't know if this is a bug or just a situation of operator error.
The goal is to query some data, get back an array of json items then:
x-for="item in items"
which works, but when i try to insert your demo using my for loop data:
<div x-data="{ baz: null }" x-init="$nextTick(() => baz = $parent.item.minutes)">
<span x-text='baz'></span>
</div>
I get nothing :/ All the demos work when not using for loop data. And the for loop data works when not nesting it.
I think this is main issue, not understanding how to properly access this parent data, or maybe it's a bug? Appreciate it. If it matters, the goal with this data is to use it with the iterator demo you have created:
<div x-data="{
timer: 1000,
count: parseInt($nextTick($parent.item.minutes)),
addOne: function() {
this.count++
}
}"
x-init="$nextTick($interval(addOne, timer))"
x-text="count.toString()">
</div>
$parent doesn't seem to work with x-for. See #126
Hi Support AlpineJS V3 alpine-collective ..?
The demonstrated Install instructions on the AlpineJS repository use the defer
attribute on the script
tag. Perhaps the README and the Installation script
tag demonstrations here should be updated accordingly as well?
NB: I have not read the source code for these helpers, so I don't know if there's a reason for the helpers to block the parsing of the page while loading and then executing. My assumption is that since these helpers are dependent upon the base Alpine framework, their utility comes following the load and execution of the base framework.
Both the current tag and the refactored version (using Alpine the legacy build from master) return errors and broken components when loading the example page for component.
How would you go about finding unused translations? I'm thinking of the possibility of wrapping the $t
method with a proxy so its possible to memorize which translations keys have been used. Then there could be a helper function that allows you to see unused translations at that point in time. The only alternative I can think of is a regex based approach on the code. Advise appreciated.
edit: Sorry, this was meant for https://github.com/rehhouari/alpinejs-i18n @rehhouari
@KevinBatdorf interval test failing for some reason. Also sometimes it happens on my local. Probably there is something related with timeouts
Originally posted by @MuzafferDede in #42 (comment)
When running the suggested install command I get errors:
npm install @alpine-collective/toolkit --save
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@alpine-collective%2ftoolkit - Not found
When searching npm I see the following:
npm search alpine-collective
NAME | DESCRIPTION | AUTHOR | DATE | VERSION | KEYWORDS
@alpine-collective/toolki | A $scroll helper… | =simotod | 2021-07-25 | 1.0.0 |
t-scroll | | | | |
@alpine-collective/toolki | Alpine magic helper… | =simotod | 2021-07-25 | 1.0.0 |
t-screen | | | | |
@alpine-collective/toolki | Truncate a string… | =simotod | 2021-07-25 | 1.0.0 |
t-truncate | | | | |
@alpine-collective/toolki | A magic function to… | =simotod | 2021-07-25 | 1.0.0 |
t-dbg | | | | |
@alpine-collective/toolki | Generate an array… | =simotod | 2021-07-25 | 1.0.0 |
t-range | | | | |
Hi
npm install @alpine-collective/toolkit --save
Fail with this error:
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@alpine-collective%2ftoolkit - Not found
npm ERR! 404
npm ERR! 404 '@alpine-collective/toolkit@*' is not in this registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.
While using the following setup:
<div wire:click="setBankType({{ $bankType }})"
x-data x-on:click="$scroll('#scrolltopaymentbutton')">Bank 1</div>
<div wire:click="setBankType({{ $bankType }})"
x-data x-on:click="$scroll('#scrolltopaymentbutton')">Bank 2</div>
<div id="scrolltopaymentbutton">Pay now</div>
I got the following error: Uncaught (in promise) TypeError: Cannot convert undefined or null to object
Currently if a translation is missing the fallback is an empty string. Would it be possible to define a fallback language or at least have the key-name as a fallback value?
edit: Sorry, this was meant for https://github.com/rehhouari/alpinejs-i18n @rehhouari
It just snaps to the top of the page if I use this code:
$scroll(0, {behavior: 'smooth'})
Or this:
$scroll(0)
And that is on a very long page with a fixed back-to-top button, after clicking on it you snap back to top in an instant.
Hey everyone,
I'm upgrading a project from a colleague to make use of compiling a single JS file with npm
modules instead of using several script tags.
I noticed that we're using the $screen
helper (and perhaps more :) ), so I updated our app.js
file to the following:
import Alpine from 'alpinejs'
import Toolkit from '@alpine-collective/toolkit'
Alpine.plugin(Toolkit)
window.Alpine = Alpine
window.Alpine.start()
Unfortunately every time I try I to use this in the browser, I get the following error in the console:
I tried different Alpine versions, but I'm not sure what could be causing this. Am I importing this wrong?
Thanks!
PS: I also tried opening an issue in the v3 repo, but was redirected here. Don't know if that's on purpose or if you forgot to update the link.
Ideally a $component should behave the same as the Alpine function and have access to magic properties such as $refs and $el.
Here is a simple example that shows this in action:
https://codepen.io/atomgiant/pen/abBOdap
A simple workaround that I am using instead of $component for now is:
document.getElementById(e).__x.$data
This seems to support all the standard Alpine behavior.
Regarding toolkit/README.md:
Do I really need to paste the following script
-tag without a source-destination into my code?
<script src="#" defer></script>
Is it possible to use $refresh to force a component to update?
I have this function in one component:
selected: function(item) {
return this.$store.stats.includes(item.value)
}
which is used by:
<template x-for="(item, index) in items" :key="index">
<div :class="{ 'font-medium bg-primary': selected(item) }">...</div>
</template>
It basically checks if that item
's value
is in the Spruce store array of stats
.
The value of this.$store.stats
gets changed after this is called (I can't change the loading order either) but this function doesn't then seem to reflect this change.
I appreciate that I'm probably pushing Alpine to/past the limit, it's on a project that started off quite simple and keeps evolving, and a rewrite into something like Vue isn't feasible.
Any help would be really appreciated!
When running the suggested install command I get these errors:
npm install @alpine-collective/toolkit --save
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@alpine-collective%2ftoolkit - Not found
When searching npm I see the following:
npm search alpine-collective
NAME | DESCRIPTION | AUTHOR | DATE | VERSION | KEYWORDS
@alpine-collective/toolki | A $scroll helper… | =simotod | 2021-07-25 | 1.0.0 |
t-scroll | | | | |
@alpine-collective/toolki | Alpine magic helper… | =simotod | 2021-07-25 | 1.0.0 |
t-screen | | | | |
@alpine-collective/toolki | Truncate a string… | =simotod | 2021-07-25 | 1.0.0 |
t-truncate | | | | |
@alpine-collective/toolki | A magic function to… | =simotod | 2021-07-25 | 1.0.0 |
t-dbg | | | | |
@alpine-collective/toolki | Generate an array… | =simotod | 2021-07-25 | 1.0.0 |
t-range | | | | |
This is really a very helpful package and I am trying to use it inside laravel app.
I have imported both import 'alpine-magic-helpers'; import 'alpinejs';
I am trying to use the $scroll helper and I have tried both $refs and using #id but when I click on the button to scroll to that specific section, It is not working and it shows the following error in the console.
Uncaught (in promise) Error: Unsupported $scroll target: at Proxy.eval (index.js?d52a:2334) at eval (eval at saferEvalNoReturn (alpine.js?df24:1900), <anonymous>:3:21) at saferEvalNoReturn (alpine.js?df24:143) at Component.evaluateCommandExpression (alpine.js?df24:1720) at runListenerHandler (alpine.js?df24:895) at HTMLButtonElement.handler (alpine.js?df24:871) eval @ index.js?d52a:2334 eval @ VM1370:3 saferEvalNoReturn @ alpine.js?df24:143 evaluateCommandExpression @ alpine.js?df24:1720 runListenerHandler @ alpine.js?df24:895 handler @ alpine.js?df24:871 Promise.then (async) handler @ alpine.js?df24:872
Thanks in advance
Add a check to checkForAlpine
that "Alpine version > version that added addMagicProperty"
Although not achieving behaviour expected the following is loading without error
<div x-data="chat()" x-init="() => { listen(); $watch('messages', () => $scroll($refs.anchor) ); }">
However, when I try and add additional parameters such as
<div x-data="chat()" x-init="() => { listen(); $watch('messages', () => $scroll($refs.anchor, {behavior: auto}) ); }">
Then I'm getting the following error
Uncaught (in promise) ReferenceError: auto is not defined
I have a fairly complex setup and I first thought that it was the reason that it did not work anymore.
However see the simple code below that currently does not work with $screen('sm')
, and gives this error: Uncaught ReferenceError: $screen is not defined
<script src="https://cdn.jsdelivr.net/gh/alpine-collective/[email protected]/dist/index.min.js"></script>
<script type="module" src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>
<div x-data="">
<div x-show="$screen('sm')">
SHOW ON > SM ONLY (DOES NOT WORK)
</div>
</div>
{{-- remove this line and it works... --}}
@livewireScripts
You can toy around here where I also added my usecase with an x-data
function:
https://laravelplayground.com/#/snippets/81b039fe-6a65-479b-aa40-d17bc37d7b75 (go to livewire.blade.php)
Note:
I think there is something wrong with the registration of the $screen helper
Alpine.addMagicProperty('truncate', function () {
return (...parameters) => {
the ...parameters
isn't necessary at this point, could be converted to (string, options)
to clean up that function.
Accessing properties and functions from $parent
in the child init()
function works in version 0.6.0. It no longer works in 1.0.0 so this might be a regression.
0.6.0 (works) : https://codepen.io/pomartel/pen/jOVaZKX
1.0.0 (broken): https://codepen.io/pomartel/pen/bGBYLmx
https://codepen.io/storegear/pen/KKaJwmR
So...day 4 on this on why iterator kills everything and now the variable seems to be it doesn't work when in a loop when in a TABLE. Take out the table mark up and it works.
Scroll offset calculation sometimes gives us a value with a fraction ex: 8245.125
target = target.getBoundingClientRect().top + window.pageYOffset
then, it fails this check:
if (Number.isInteger(target)) {
continues to:
if (typeof target !== 'object')
and throws Unsupported $scroll target error
When you try to mutate parent data from a child element on an event, you need to fire it 2 times. I have also tried to pre-bind data-last-refresh
but it does not give me any luck.
<div x-data="{num: 16}">
<!-- Outside -->
<p x-text='num'></p>
<button @click="num = Math.random()">Random a Number (Outside)</button>
<div x-data>
<!-- Inside -->
<button @click="$parent.num = Math.random()">Random a Number (Inside)</button>
</div>
</div>
Hello 👋
First of all, thank you for the good work with these helpers.
I'm trying to build an image slider using $interval.
I want it to start automatically on init and pause/resume on @mouseenter and @mouseleave.
Here is my code:
<div x-data="{
timer: 7000,
autoIntervalTest: true,
autoplaySlider: function() {
document.getElementById('next_btn').click();
}}"
x-init="$interval(autoplaySlider, { timer, forceInterval: true})"
@mouseenter="autoIntervalTest = false"
@mouseleave="autoIntervalTest = true">
When I enter the picture, the timer is correctly stopped and starts again when leaving.
The problem is that when you quickly enter and leave the slider, the function will run multiple times in a row without respecting the initial timer. It's like leaving the picture fires the function every time and stacks these functions instead of resetting the initial one.
Another example with this
If you increase the timer value a little bit (2000 for example) and try clicking the counter multiple times in a row, the counter is now increasing much faster than the initial 2 seconds set by the timer.
Is there a way to resume/restart the same function instead of launching a new one with autoIntervalTest?
Hope my explanation is clear enough and thanks in advance for your help!
Regards,
Joachim
Try this:
<div x-id='main' x-data="{ x: 1 }">
<span x-text="$component('main').x">
</span>
</div>
A variant of this structure in my actual program produces undefined for the text instead of becoming non-responsive.
Hello.
Thanks for your awesome helpers
Just a quick question. Is it possible to use $parent.$parent.property
?
I have data property at the body but a two-level component. I want to update the body data property from 2nd child.
What's the solution to this?
Thank you.
Hello,
I am new to livewire/alpine and trying to debug an error in the console.
I have a livewire component, that renders a form step by step. When a radio input option is selected, the next radio input is loaded and available for selection. On click, the next radio input group is loaded and it scrolls to it. It works well until I load another livewire component inside current livewire component.
Inside first livewire component, I apply the scroll code x-data x-on:click="$nextTick(() => { $scroll('#calendarScroll', {behavior: 'smooth'}) })"
It looks for the id="calendarScroll" inside second livewire component. Here I have another list of radio inputs, and after selecting one, the script turns back to the first livewire component to render remaining data.
When I click on a radio input from the second component, I get following error
scroll.js:526 Uncaught TypeError: Cannot convert undefined or null to object at Function.assign (<anonymous>) at Proxy.<anonymous> (scroll.js:526) at eval (eval at tryCatch.el.el (app.js:182), <anonymous>:3:39) at app.js:1658
If I click twice on the same radio input, it scrolls to given id, that is inside first livewire component, as intended.
What may be the problem? Why it throws the error on first click?
Currently the [Unreleased] header isn't updated when making a release.
If someone wants to take this on please do or I can look into it on Sunday
Hi,
I have an unexpected behaviour of $component/$parent, when I have multiple nested components.
I've created some simple tests. The examples are not quite realistic, but I hope they show the problem.
Or in a x-for loop, the $parent ist not defined after the component mount phase ?
I'm not sure if I don't understand the helper correctly or if this is a bug.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.jsdelivr.net/gh/kevinbatdorf/[email protected]/dist/component.js"></script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>
</head>
<body>
<h1 style="color:green">Works as expected</h1>
<div x-data="{ colors: ['blue','red','green','yellow'] }">
<div :data-color-index="0">
<div x-data x-text="$parent.colors[$el.parentNode.dataset.colorIndex]" x-on:click="alert($parent.colors)"></div>
</div>
</div>
<hr />
<h1 style="color:red">Click handler does not show expected result</h1>
<p>
<b>expected result for click on a color:</b> 'blue,red,green,yellow'<br />
<b>current result:</b> undefined
</p>
<div x-data="{ colors: ['blue','red','green','yellow'] }">
<div :data-color-index="0">
<div x-data x-text="$parent.colors[$el.parentNode.dataset.colorIndex]" x-on:click="alert($parent.colors)"></div>
</div>
<div :data-color-index="1">
<div x-data x-text="$parent.colors[$el.parentNode.dataset.colorIndex]" x-on:click="alert($parent.colors)"></div>
</div>
<div :data-color-index="2">
<div x-data x-text="$parent.colors[$el.parentNode.dataset.colorIndex]" x-on:click="alert($parent.colors)"></div>
</div>
<div :data-color-index="3">
<div x-data x-text="$parent.colors[$el.parentNode.dataset.colorIndex]" x-on:click="alert($parent.colors)"></div>
</div>
</div>
<hr />
<h1 style="color:red">Click handler does not show expected result and $parent.colors error in the console log</h1>
<p>
<b>expected result for click on a color:</b> 'blue,red,green,yellow'<br />
<b>current result:</b> undefined<br /><br />
</p>
<div x-data="{ colors: ['blue','red','green','yellow'] }">
<template x-for="(color, index) in colors">
<div :data-color-index="index">
<div x-data x-text="$parent.colors[$el.parentNode.dataset.colorIndex]" x-on:click="alert($parent.colors)"></div>
</div>
</template>
</div>
<script>
</script>
</body>
</html>
Would adding a DOM select magic helper add value? Make the Alpine developers happier and more productive?
I'm my case, YES!
Quite often I use a vanilla JS DOM selectors in my code (sometimes one, sometimes more):
getElementsByTagName()
getElementsByClassName()
getElementById()
querySelector()
querySelectorAll()
I'm thinking of porting [select-dom](https://www.npmjs.com/package/select-dom)
as a magic helper $select
or even implement it!
The idea is to have a unified method to query DOM elements no matter what we're looking for (id, tag, class, data attribute):
This:
element = select('.foo');
element = select('#foo');
element = select('.foo a[href=bar]');
element = select('[data-foo]');
Instead of:
element = document.getElementById('foo')
element = document.getElementsByClassName('foo')
element = document.querySelector('.foo a[href=bar]');
element = document.querySelector('[data-foo]');
Comments?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.