├── packages
├── trap
│ ├── .gitignore
│ ├── builds
│ │ ├── module.js
│ │ └── cdn.js
│ ├── package.json
│ └── src
│ │ └── index.js
├── csp
│ ├── builds
│ │ ├── module.js
│ │ └── cdn.js
│ ├── package.json
│ ├── src
│ │ └── index.js
│ └── dist
│ │ └── module.js
├── alpinejs
│ ├── builds
│ │ ├── module.js
│ │ └── cdn.js
│ ├── src
│ │ ├── magics
│ │ │ ├── $el.js
│ │ │ ├── $store.js
│ │ │ ├── $nextTick.js
│ │ │ ├── index.js
│ │ │ ├── $refs.js
│ │ │ ├── $dispatch.js
│ │ │ └── $watch.js
│ │ ├── plugin.js
│ │ ├── utils
│ │ │ ├── warn.js
│ │ │ ├── once.js
│ │ │ ├── dispatch.js
│ │ │ ├── styles.js
│ │ │ ├── walk.js
│ │ │ ├── classes.js
│ │ │ └── bind.js
│ │ ├── datas.js
│ │ ├── directives
│ │ │ ├── x-effect.js
│ │ │ ├── x-cloak.js
│ │ │ ├── index.js
│ │ │ ├── x-init.js
│ │ │ ├── x-ref.js
│ │ │ ├── x-text.js
│ │ │ ├── x-ignore.js
│ │ │ ├── x-on.js
│ │ │ ├── x-if.js
│ │ │ ├── x-data.js
│ │ │ ├── x-bind.js
│ │ │ ├── x-show.js
│ │ │ └── x-model.js
│ │ ├── nextTick.js
│ │ ├── magics.js
│ │ ├── store.js
│ │ ├── scheduler.js
│ │ ├── reactivity.js
│ │ ├── alpine.js
│ │ ├── clone.js
│ │ ├── scope.js
│ │ ├── lifecycle.js
│ │ ├── interceptor.js
│ │ ├── index.js
│ │ └── evaluator.js
│ ├── package.json
│ └── node_modules
│ │ └── .package-lock.json
├── docs
│ ├── src
│ │ └── en
│ │ │ ├── advanced.md
│ │ │ ├── essentials.md
│ │ │ ├── magics.md
│ │ │ ├── globals.md
│ │ │ ├── directives.md
│ │ │ ├── magics
│ │ │ ├── el.md
│ │ │ ├── nextTick.md
│ │ │ ├── refs.md
│ │ │ ├── watch.md
│ │ │ ├── store.md
│ │ │ └── dispatch.md
│ │ │ ├── directives
│ │ │ ├── ignore.md
│ │ │ ├── ref.md
│ │ │ ├── text.md
│ │ │ ├── if.md
│ │ │ ├── effect.md
│ │ │ ├── show.md
│ │ │ ├── cloak.md
│ │ │ ├── init.md
│ │ │ └── for.md
│ │ │ ├── advanced
│ │ │ ├── async.md
│ │ │ ├── csp.md
│ │ │ └── reactivity.md
│ │ │ ├── essentials
│ │ │ ├── installation.md
│ │ │ ├── lifecycle.md
│ │ │ └── events.md
│ │ │ └── globals
│ │ │ ├── alpine-store.md
│ │ │ └── alpine-data.md
│ └── package.json
├── history
│ ├── builds
│ │ ├── module.js
│ │ └── cdn.js
│ ├── package.json
│ ├── dist
│ │ ├── cdn.min.js
│ │ ├── module.esm.js
│ │ ├── cdn.js
│ │ └── module.cjs.js
│ └── src
│ │ ├── url.js
│ │ └── index.js
├── persist
│ ├── builds
│ │ ├── module.js
│ │ └── cdn.js
│ ├── dist
│ │ ├── cdn.min.js
│ │ ├── module.esm.js
│ │ ├── cdn.js
│ │ └── module.cjs.js
│ ├── package.json
│ └── src
│ │ └── index.js
├── intersect
│ ├── builds
│ │ ├── module.js
│ │ └── cdn.js
│ ├── package.json
│ ├── dist
│ │ ├── cdn.min.js
│ │ ├── module.esm.js
│ │ ├── cdn.js
│ │ └── module.cjs.js
│ ├── node_modules
│ │ └── .package-lock.json
│ └── src
│ │ └── index.js
└── morph
│ ├── builds
│ ├── module.js
│ └── cdn.js
│ ├── package.json
│ ├── src
│ └── index.js
│ └── dist
│ └── cdn.min.js
├── tests
├── cypress
│ ├── .gitignore
│ ├── fixtures
│ │ └── example.json
│ ├── integration
│ │ ├── directives
│ │ │ ├── x-cloak.spec.js
│ │ │ ├── x-if.spec.js
│ │ │ ├── x-ignore.spec.js
│ │ │ ├── x-bind:style.spec.js
│ │ │ ├── x-text.spec.js
│ │ │ ├── x-init.spec.js
│ │ │ ├── x-transition.spec.js
│ │ │ ├── x-bind:class.spec.js
│ │ │ ├── x-model.spec.js
│ │ │ └── x-data.spec.js
│ │ ├── magics
│ │ │ ├── $el.spec.js
│ │ │ ├── $dispatch.spec.js
│ │ │ ├── $refs.spec.js
│ │ │ ├── $nextTick.spec.js
│ │ │ └── $watch.spec.js
│ │ ├── custom-prefix.spec.js
│ │ ├── plugins
│ │ │ ├── persist.spec.js
│ │ │ ├── csp-compatibility.spec.js
│ │ │ ├── intersect.spec.js
│ │ │ ├── trap.spec.js
│ │ │ ├── morph.spec.js
│ │ │ └── history.spec.js
│ │ ├── custom-magics.spec.js
│ │ ├── custom-directives.spec.js
│ │ ├── mutation.spec.js
│ │ ├── store.spec.js
│ │ ├── custom-data.spec.js
│ │ └── clone.spec.js
│ ├── support
│ │ ├── index.js
│ │ └── commands.js
│ ├── plugins
│ │ └── index.js
│ ├── spec-csp.html
│ ├── spec.html
│ ├── utils.js
│ └── manual-transition-test.html
└── jest
│ └── morph
│ ├── createElement.js
│ ├── external.spec.js
│ ├── alpine-scope.spec.js
│ └── internal.spec.js
├── .gitignore
├── jest.config.js
├── README.md
├── editorconfig
├── cypress.json
├── benchmarks
├── memory.html
└── mutation_observer.html
├── package.json
├── LICENSE.md
└── scripts
└── build.js
/packages/trap/.gitignore:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/cypress/.gitignore:
--------------------------------------------------------------------------------
1 | /videos
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | scratch.md
3 | package-lock.json
4 |
--------------------------------------------------------------------------------
/packages/csp/builds/module.js:
--------------------------------------------------------------------------------
1 | import Alpine from './../src/index'
2 |
3 | export default Alpine
4 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | let config = {
2 | rootDir: './tests/jest',
3 | }
4 |
5 | module.exports = config
6 |
--------------------------------------------------------------------------------
/packages/alpinejs/builds/module.js:
--------------------------------------------------------------------------------
1 | import Alpine from './../src/index'
2 |
3 | export default Alpine
4 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics/$el.js:
--------------------------------------------------------------------------------
1 | import { magic } from "../magics";
2 |
3 | magic('el', el => el)
4 |
--------------------------------------------------------------------------------
/packages/docs/src/en/advanced.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 8
3 | title: Advanced
4 | type: sub-directory
5 | ---
6 |
--------------------------------------------------------------------------------
/packages/history/builds/module.js:
--------------------------------------------------------------------------------
1 | import history from '../src/index.js'
2 |
3 | export default history
4 |
--------------------------------------------------------------------------------
/packages/persist/builds/module.js:
--------------------------------------------------------------------------------
1 | import persist from '../src/index.js'
2 |
3 | export default persist
4 |
--------------------------------------------------------------------------------
/packages/docs/src/en/essentials.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 3
3 | title: Essentials
4 | type: sub-directory
5 | ---
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### IMPORTANT:
2 | This repo has moved to the main Alpine repo here: https://github.com/alpinejs/alpine
3 |
--------------------------------------------------------------------------------
/packages/intersect/builds/module.js:
--------------------------------------------------------------------------------
1 | import intersect from './../src/index.js'
2 |
3 | export default intersect
4 |
--------------------------------------------------------------------------------
/packages/trap/builds/module.js:
--------------------------------------------------------------------------------
1 | import registerTrapDirective from '../src/index.js'
2 |
3 | export default registerTrapDirective
4 |
--------------------------------------------------------------------------------
/packages/docs/src/en/magics.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 5
3 | title: Magics
4 | prefix: $
5 | font-type: mono
6 | type: sub-directory
7 | ---
8 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/plugin.js:
--------------------------------------------------------------------------------
1 | import Alpine from './alpine'
2 |
3 | export function plugin(callback) {
4 | callback(Alpine)
5 | }
6 |
--------------------------------------------------------------------------------
/packages/docs/src/en/globals.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 6
3 | title: Globals
4 | font-type: mono
5 | prefix: Alpine.
6 | type: sub-directory
7 | ---
8 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 4
3 | title: Directives
4 | prefix: x-
5 | font-type: mono
6 | type: sub-directory
7 | ---
8 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics/$store.js:
--------------------------------------------------------------------------------
1 | import { getStores } from '../store'
2 | import { magic } from '../magics'
3 |
4 | magic('store', getStores)
5 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/utils/warn.js:
--------------------------------------------------------------------------------
1 |
2 | export function warn(message, ...args) {
3 | console.warn(`Alpine Warning: ${message}`, ...args)
4 | }
5 |
--------------------------------------------------------------------------------
/packages/morph/builds/module.js:
--------------------------------------------------------------------------------
1 | import morphPlugin, { morph } from '../src/index.js'
2 |
3 | export default morphPlugin
4 |
5 | export { morph }
6 |
--------------------------------------------------------------------------------
/packages/csp/builds/cdn.js:
--------------------------------------------------------------------------------
1 | import Alpine from './../src/index'
2 |
3 | window.Alpine = Alpine
4 |
5 | queueMicrotask(() => {
6 | Alpine.start()
7 | })
8 |
--------------------------------------------------------------------------------
/packages/alpinejs/builds/cdn.js:
--------------------------------------------------------------------------------
1 | import Alpine from './../src/index'
2 |
3 | window.Alpine = Alpine
4 |
5 | queueMicrotask(() => {
6 | Alpine.start()
7 | })
8 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics/$nextTick.js:
--------------------------------------------------------------------------------
1 | import { nextTick } from '../nextTick'
2 | import { magic } from '../magics'
3 |
4 | magic('nextTick', () => nextTick)
5 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics/index.js:
--------------------------------------------------------------------------------
1 | import './$nextTick'
2 | import './$dispatch'
3 | import './$watch'
4 | import './$store'
5 | import './$refs'
6 | import './$el'
7 |
--------------------------------------------------------------------------------
/packages/morph/builds/cdn.js:
--------------------------------------------------------------------------------
1 | import morph from '../src/index.js'
2 |
3 | document.addEventListener('alpine:initializing', () => {
4 | window.Alpine.plugin(morph)
5 | })
6 |
--------------------------------------------------------------------------------
/packages/trap/builds/cdn.js:
--------------------------------------------------------------------------------
1 | import trap from '../src/index.js'
2 |
3 | document.addEventListener('alpine:initializing', () => {
4 | window.Alpine.plugin(trap)
5 | })
6 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics/$refs.js:
--------------------------------------------------------------------------------
1 | import { closestRoot } from '../lifecycle'
2 | import { magic } from '../magics'
3 |
4 | magic('refs', el => closestRoot(el)._x_refs || {})
5 |
--------------------------------------------------------------------------------
/packages/history/builds/cdn.js:
--------------------------------------------------------------------------------
1 | import history from '../src/index.js'
2 |
3 | document.addEventListener('alpine:initializing', () => {
4 | window.Alpine.plugin(history)
5 | })
6 |
--------------------------------------------------------------------------------
/packages/persist/builds/cdn.js:
--------------------------------------------------------------------------------
1 | import persist from '../src/index.js'
2 |
3 | document.addEventListener('alpine:initializing', () => {
4 | window.Alpine.plugin(persist)
5 | })
6 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics/$dispatch.js:
--------------------------------------------------------------------------------
1 | import { dispatch } from '../utils/dispatch'
2 | import { magic } from '../magics'
3 |
4 | magic('dispatch', el => dispatch.bind(dispatch, el))
5 |
--------------------------------------------------------------------------------
/packages/intersect/builds/cdn.js:
--------------------------------------------------------------------------------
1 | import intersect from '../src/index.js'
2 |
3 | document.addEventListener('alpine:initializing', () => {
4 | window.Alpine.plugin(intersect)
5 | })
6 |
--------------------------------------------------------------------------------
/tests/cypress/fixtures/example.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Using fixtures to represent data",
3 | "email": "hello@cypress.io",
4 | "body": "Fixtures are a great way to mock data for responses to routes"
5 | }
--------------------------------------------------------------------------------
/packages/docs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/docs",
3 | "version": "3.0.0-alpha.0",
4 | "description": "The documentation for Alpine",
5 | "author": "Caleb Porzio",
6 | "license": "MIT"
7 | }
8 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/datas.js:
--------------------------------------------------------------------------------
1 |
2 | let datas = {}
3 |
4 | export function data(name, callback) {
5 | datas[name] = callback
6 | }
7 |
8 | export function getNamedDataProvider(name) {
9 | return datas[name]
10 | }
11 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-effect.js:
--------------------------------------------------------------------------------
1 | import { directive } from '../directives'
2 | import { evaluateLater } from '../evaluator'
3 |
4 | directive('effect', (el, { expression }, { effect }) => effect(evaluateLater(el, expression)))
5 |
--------------------------------------------------------------------------------
/editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | insert_final_newline = true
7 | indent_style = space
8 | indent_size = 4
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-cloak.js:
--------------------------------------------------------------------------------
1 | import { directive, prefix } from '../directives'
2 | import { mutateDom } from '../mutation'
3 | import { nextTick } from '../nextTick'
4 |
5 | directive('cloak', el => nextTick(() => mutateDom(() => el.removeAttribute(prefix('cloak')))))
6 |
--------------------------------------------------------------------------------
/packages/persist/dist/cdn.min.js:
--------------------------------------------------------------------------------
1 | (()=>{function n(r){r.magic("persist",(o,{interceptor:l})=>l((s,t)=>({init(e,i){localStorage.getItem(t)?i(localStorage.getItem(t)):i(e)},set(e,i){localStorage.setItem(t,e),i(e)}})))}document.addEventListener("alpine:initializing",()=>{window.Alpine.plugin(n)});})();
2 |
--------------------------------------------------------------------------------
/packages/persist/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/persist",
3 | "version": "3.0.0-alpha.0",
4 | "description": "Persist Alpine data to localStorage or similar client-side stores",
5 | "author": "Caleb Porzio",
6 | "license": "MIT",
7 | "main": "dist/module.cjs.js",
8 | "module": "dist/module.esm.js"
9 | }
10 |
--------------------------------------------------------------------------------
/tests/cypress/integration/directives/x-cloak.spec.js:
--------------------------------------------------------------------------------
1 | import { html, notHaveAttribute, test } from '../../utils'
2 |
3 | test('x-cloak is removed',
4 | html`
5 |
6 |
7 |
8 | `,
9 | ({ get }) => get('span').should(notHaveAttribute('x-cloak'))
10 | )
11 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/index.js:
--------------------------------------------------------------------------------
1 | import './x-transition'
2 | import './x-ignore'
3 | import './x-effect'
4 | import './x-model'
5 | import './x-cloak'
6 | import './x-init'
7 | import './x-text'
8 | import './x-bind'
9 | import './x-data'
10 | import './x-show'
11 | import './x-for'
12 | import './x-ref'
13 | import './x-if'
14 | import './x-on'
15 |
--------------------------------------------------------------------------------
/tests/jest/morph/createElement.js:
--------------------------------------------------------------------------------
1 |
2 | function createElement(htmlOrTemplate) {
3 | if (typeof htmlOrTemplate === 'string') {
4 | return document.createRange().createContextualFragment(htmlOrTemplate).firstElementChild
5 | }
6 |
7 | return htmlOrTemplate.content.firstElementChild.cloneNode(true)
8 | }
9 |
10 | module.exports = createElement
11 |
--------------------------------------------------------------------------------
/packages/trap/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/trap",
3 | "version": "3.0.0-alpha.0",
4 | "description": "Declaratively trap focus",
5 | "author": "Caleb Porzio",
6 | "license": "MIT",
7 | "main": "dist/module.cjs.js",
8 | "module": "dist/module.esm.js",
9 | "dependencies": {
10 | "wicg-inert": "^3.1.1"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/utils/once.js:
--------------------------------------------------------------------------------
1 |
2 | export function once(callback, fallback = () => {}) {
3 | let called = false
4 |
5 | return function () {
6 | if (! called) {
7 | called = true
8 |
9 | callback.apply(this, arguments)
10 | } else {
11 | fallback.apply(this, arguments)
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/packages/intersect/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/intersect",
3 | "version": "3.0.0-alpha.0",
4 | "description": "Trigger JavaScript when an element enters or leaves the viewport",
5 | "author": "Caleb Porzio",
6 | "license": "MIT",
7 | "main": "dist/module.cjs.js",
8 | "module": "dist/module.esm.js",
9 | "dependencies": {}
10 | }
11 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/utils/dispatch.js:
--------------------------------------------------------------------------------
1 |
2 | export function dispatch(el, name, detail = {}) {
3 | el.dispatchEvent(
4 | new CustomEvent(name, {
5 | detail,
6 | bubbles: true,
7 | // Allows events to pass the shadow DOM barrier.
8 | composed: true,
9 | cancelable: true,
10 | })
11 | )
12 | }
13 |
--------------------------------------------------------------------------------
/packages/csp/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/csp",
3 | "version": "3.0.0-alpha.0",
4 | "description": "A CSP compatible build of Alpine",
5 | "author": "Caleb Porzio",
6 | "license": "MIT",
7 | "main": "dist/module.cjs.js",
8 | "module": "dist/module.esm.js",
9 | "dependencies": {
10 | "@vue/reactivity": "^3.0.2"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/packages/alpinejs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "alpinejs",
3 | "version": "3.0.0-alpha.0",
4 | "description": "The rugged, minimal JavaScript framework",
5 | "author": "Caleb Porzio",
6 | "license": "MIT",
7 | "main": "dist/module.cjs.js",
8 | "module": "dist/module.esm.js",
9 | "dependencies": {
10 | "@vue/reactivity": "^3.0.2"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-init.js:
--------------------------------------------------------------------------------
1 | import { directive, prefix } from "../directives";
2 | import { addRootSelector } from "../lifecycle";
3 | import { skipDuringClone } from "../clone";
4 | import { evaluate } from "../evaluator";
5 |
6 | addRootSelector(() => `[${prefix('init')}]`)
7 |
8 | directive('init', skipDuringClone((el, { expression }) => evaluate(el, expression, {}, false)))
9 |
--------------------------------------------------------------------------------
/packages/history/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/history",
3 | "version": "3.0.0-alpha.0",
4 | "description": "Sync Alpine data with the browser's query string",
5 | "author": "Caleb Porzio",
6 | "license": "MIT",
7 | "main": "dist/module.cjs.js",
8 | "module": "dist/module.esm.js",
9 | "dependencies": {
10 | "@vue/reactivity": "^3.0.2"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/packages/morph/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/morph",
3 | "version": "3.0.0-alpha.0",
4 | "description": "Diff and patch a block of HTML on a page with an HTML template",
5 | "author": "Caleb Porzio",
6 | "license": "MIT",
7 | "main": "dist/module.cjs.js",
8 | "module": "dist/module.esm.js",
9 | "dependencies": {
10 | "@vue/reactivity": "^3.0.2"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/cypress.json:
--------------------------------------------------------------------------------
1 | {
2 | "ignoreTestFiles": "*.html",
3 | "screenshotOnRunFailure": false,
4 | "video": false,
5 | "fixturesFolder": "tests/cypress/fixtures",
6 | "integrationFolder": "tests/cypress/integration",
7 | "pluginsFile": "tests/cypress/plugins/index.js",
8 | "screenshotsFolder": "tests/cypress/screenshots",
9 | "videosFolder": "tests/cypress/videos",
10 | "supportFile": "tests/cypress/support/index.js"
11 | }
12 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-ref.js:
--------------------------------------------------------------------------------
1 | import { closestRoot } from '../lifecycle'
2 | import { directive } from '../directives'
3 |
4 | function handler () {}
5 |
6 | handler.inline = (el, { expression }, { cleanup }) => {
7 | let root = closestRoot(el)
8 |
9 | if (! root._x_refs) root._x_refs = {}
10 |
11 | root._x_refs[expression] = el
12 |
13 | cleanup(() => delete root._x_refs[expression])
14 | }
15 |
16 | directive('ref', handler)
17 |
--------------------------------------------------------------------------------
/tests/cypress/integration/magics/$el.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../../utils'
2 |
3 | test('$el returns the current element',
4 | html`
5 |
6 | click me
7 |
8 | `,
9 | ({ get }) => {
10 | get('button').should(haveText('click me'))
11 | get('button').click()
12 | get('button').should(haveText('foo'))
13 | }
14 | )
15 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-text.js:
--------------------------------------------------------------------------------
1 | import { evaluateLater } from '../evaluator'
2 | import { directive } from '../directives'
3 | import { mutateDom } from '../mutation'
4 |
5 | directive('text', (el, { expression }, { effect, cleanup }) => {
6 | let evaluate = evaluateLater(el, expression)
7 |
8 | effect(() => {
9 | evaluate(value => {
10 | mutateDom(() => {
11 | el.textContent = value
12 | })
13 | })
14 | })
15 | })
16 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-ignore.js:
--------------------------------------------------------------------------------
1 | import { directive } from "../directives"
2 |
3 | let handler = () => {}
4 |
5 | handler.inline = (el, { modifiers }, { cleanup }) => {
6 | modifiers.includes('self')
7 | ? el._x_ignore_self = true
8 | : el._x_ignore = true
9 |
10 | cleanup(() => {
11 | modifiers.includes('self')
12 | ? delete el._x_ignore_self
13 | : delete el._x_ignore
14 | })
15 | }
16 |
17 | directive('ignore', handler)
18 |
--------------------------------------------------------------------------------
/packages/docs/src/en/magics/el.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 1
3 | prefix: $
4 | title: el
5 | ---
6 |
7 | # `$el`
8 |
9 | `$el` is a magic property that can be used to retrieve the current DOM node.
10 |
11 | ```html
12 | Replace me with "foo"
13 | ```
14 |
15 |
16 |
17 |
18 | Replace me with "Hello World!"
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/tests/cypress/integration/custom-prefix.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../utils'
2 |
3 | test('can set a custom x- prefix',
4 | html`
5 |
10 |
11 |
12 |
13 |
14 | `,
15 | ({ get }) => get('span').should(haveText('bar'))
16 | )
17 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/nextTick.js:
--------------------------------------------------------------------------------
1 |
2 | let tickStack = []
3 |
4 | let isHolding = false
5 |
6 | export function nextTick(callback) {
7 | tickStack.push(callback)
8 |
9 | queueMicrotask(() => {
10 | isHolding || setTimeout(() => {
11 | releaseNextTicks()
12 | })
13 | })
14 | }
15 |
16 | export function releaseNextTicks() {
17 | isHolding = false
18 |
19 | while (tickStack.length) tickStack.shift()()
20 | }
21 |
22 | export function holdNextTicks() {
23 | isHolding = true
24 | }
25 |
--------------------------------------------------------------------------------
/benchmarks/memory.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | hi
7 |
8 |
9 | delete
10 |
11 |
12 |
17 |
18 |
--------------------------------------------------------------------------------
/packages/morph/src/index.js:
--------------------------------------------------------------------------------
1 | import { morph } from './morph'
2 |
3 | export default function (Alpine) {
4 | Alpine.directive('morph', (el, { expression }, { effect, evaluateLater }) => {
5 | let evaluate = evaluateLater(expression)
6 |
7 | effect(() => {
8 | evaluate(value => {
9 | let child = el.firstElementChild || el.firstChild || el.appendChild(document.createTextNode(''))
10 |
11 | morph(child, value)
12 | })
13 | })
14 | })
15 | }
16 |
17 | export { morph }
18 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics.js:
--------------------------------------------------------------------------------
1 | import Alpine from './alpine'
2 | import { interceptor } from './interceptor'
3 |
4 | let magics = {}
5 |
6 | export function magic(name, callback) {
7 | magics[name] = callback
8 | }
9 |
10 | export function injectMagics(obj, el) {
11 | Object.entries(magics).forEach(([name, callback]) => {
12 | Object.defineProperty(obj, `$${name}`, {
13 | get() { return callback(el, { Alpine, interceptor }) },
14 |
15 | enumerable: true,
16 | })
17 | })
18 |
19 | return obj
20 | }
21 |
--------------------------------------------------------------------------------
/tests/cypress/integration/plugins/persist.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../../utils'
2 |
3 | test('can perist data',
4 | [html`
5 |
6 | Inc
7 |
8 |
9 | `],
10 | ({ get }, reload) => {
11 | get('span').should(haveText('1'))
12 | get('button').click()
13 | get('span').should(haveText('2'))
14 | reload()
15 | get('span').should(haveText('2'))
16 | },
17 | )
18 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/store.js:
--------------------------------------------------------------------------------
1 | import { reactive } from "./reactivity"
2 |
3 | let stores = {}
4 | let isReactive = false
5 |
6 | export function store(name, value) {
7 | if (! isReactive) { stores = reactive(stores); isReactive = true; }
8 |
9 | if (value === undefined) {
10 | return stores[name]
11 | }
12 |
13 | if (typeof value === 'object' && value !== null && value.hasOwnProperty('init') && typeof value.init === 'function') {
14 | value.init()
15 | }
16 |
17 | stores[name] = value
18 | }
19 |
20 | export function getStores() { return stores }
21 |
--------------------------------------------------------------------------------
/tests/cypress/integration/custom-magics.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../utils'
2 |
3 | test('can register custom magic properties',
4 | html`
5 |
12 |
13 |
14 |
15 |
16 | `,
17 | ({ get }) => get('span').should(haveText('baz'))
18 | )
19 |
--------------------------------------------------------------------------------
/tests/cypress/integration/magics/$dispatch.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../../utils'
2 |
3 | test('$dispatch dispatches events properly',
4 | html`
5 |
6 |
7 |
8 | click me
9 |
10 | `,
11 | ({ get }) => {
12 | get('span').should(haveText('bar'))
13 | get('button').click()
14 | get('span').should(haveText('baz'))
15 | }
16 | )
17 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "private": true,
3 | "workspaces": [
4 | "packages/*"
5 | ],
6 | "devDependencies": {
7 | "brotli-size": "^4.0.0",
8 | "cypress": "^5.5.0",
9 | "cypress-plugin-tab": "^1.0.5",
10 | "dot-json": "^1.2.2",
11 | "esbuild": "^0.8.39",
12 | "jest": "^26.6.3"
13 | },
14 | "scripts": {
15 | "build": "node ./scripts/build.js",
16 | "watch": "node ./scripts/build.js --watch",
17 | "test": "jest test && cypress run",
18 | "cypress": "cypress open",
19 | "jest": "jest test"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/tests/cypress/integration/directives/x-if.spec.js:
--------------------------------------------------------------------------------
1 | import { beVisible, html, notBeVisible, notHaveAttribute, test } from '../../utils'
2 |
3 | test('x-if',
4 | html`
5 |
6 | Toggle
7 |
8 |
9 | Toggle Me
10 |
11 |
12 | `,
13 | ({ get }) => {
14 | get('h1').should(notBeVisible())
15 | get('button').click()
16 | get('h1').should(beVisible())
17 | get('button').click()
18 | get('h1').should(notBeVisible())
19 | }
20 | )
21 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives/ignore.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 11
3 | title: ignore
4 | ---
5 |
6 | # `x-ignore`
7 |
8 | By default, Alpine will crawl and initialize the entire DOM tree of an element containing `x-init` or `x-data`.
9 |
10 | If for some reason, you don't want Alpine to touch a specific section of your HTML, you can prevent it from doing so using `x-ignore`.
11 |
12 | ```html
13 |
18 | ```
19 |
20 | In the above example, the `` tag will not contain "From Alpine" because we told Alpine to ignore the contents of the `div` completely.
21 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-on.js:
--------------------------------------------------------------------------------
1 | import { directive, into, mapAttributes, prefix, startingWith } from '../directives'
2 | import { evaluateLater } from '../evaluator'
3 | import { skipDuringClone } from '../clone'
4 | import on from '../utils/on'
5 |
6 | mapAttributes(startingWith('@', into(prefix('on:'))))
7 |
8 | directive('on', skipDuringClone((el, { value, modifiers, expression }, { cleanup }) => {
9 | let evaluate = expression ? evaluateLater(el, expression) : () => {}
10 |
11 | let removeListener = on(el, value, modifiers, e => {
12 | evaluate(() => {}, { scope: { '$event': e }, params: [e] })
13 | })
14 |
15 | cleanup(() => removeListener())
16 | }))
17 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives/ref.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 11
3 | title: ref
4 | ---
5 |
6 | # `x-ref`
7 |
8 | `x-ref` in combination with `$refs` is a useful utility for easily accessing DOM elements directly. It's most useful as a replacement for APIs like `getElementById` and `querySelector`.
9 |
10 | ```html
11 | Remove Text
12 |
13 | Hello 👋
14 | ```
15 |
16 |
17 |
18 |
19 |
Remove Text
20 |
21 |
Hello 👋
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/magics/$watch.js:
--------------------------------------------------------------------------------
1 | import { evaluateLater } from '../evaluator'
2 | import { effect } from '../reactivity'
3 | import { magic } from '../magics'
4 |
5 | magic('watch', el => (key, callback) => {
6 | let evaluate = evaluateLater(el, key)
7 |
8 | let firstTime = true
9 |
10 | let oldValue
11 |
12 | effect(() => evaluate(value => {
13 | // This is a hack to force deep reactivity for things like "items.push()".
14 | let div = document.createElement('div')
15 | div.dataset.throwAway = value
16 |
17 | if (! firstTime) callback(value, oldValue)
18 |
19 | oldValue = value
20 |
21 | firstTime = false
22 | }))
23 | })
24 |
--------------------------------------------------------------------------------
/tests/cypress/integration/plugins/csp-compatibility.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../../utils'
2 |
3 | test.csp('Can use components and basic expressions with CSP-compatible build',
4 | [html`
5 |
6 |
7 |
8 | Change Foo
9 |
10 | `,
11 | `
12 | Alpine.data('test', () => ({
13 | foo: 'bar',
14 | change() { this.foo = 'baz' },
15 | }))
16 | `],
17 | ({ get }) => {
18 | get('span').should(haveText('bar'))
19 | get('button').click()
20 | get('span').should(haveText('baz'))
21 | }
22 | )
23 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives/text.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 6
3 | title: text
4 | ---
5 |
6 | # `x-text`
7 |
8 | `x-text` sets the text content of an element to the result of a given expression.
9 |
10 | Here's a basic example of using `x-text` to display a user's username.
11 |
12 | ```html
13 |
14 | Username:
15 |
16 | ```
17 |
18 |
19 |
20 |
21 | Username:
22 |
23 |
24 |
25 |
26 | Now the `` tag's inner text content will be set to "calebporzio".
27 |
--------------------------------------------------------------------------------
/packages/persist/src/index.js:
--------------------------------------------------------------------------------
1 |
2 | export default function (Alpine) {
3 | Alpine.magic('persist', (el, { interceptor }) => {
4 | return interceptor((key, path) => {
5 | return {
6 | init(initialValue, setter) {
7 | if (localStorage.getItem(path)) {
8 | setter(localStorage.getItem(path))
9 | } else {
10 | setter(initialValue)
11 | }
12 | },
13 | set(value, setter) {
14 | localStorage.setItem(path, value)
15 |
16 | setter(value)
17 | },
18 | }
19 | })
20 | })
21 | }
22 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/scheduler.js:
--------------------------------------------------------------------------------
1 |
2 | let flushPending = false
3 | let flushing = false
4 | let queue = []
5 |
6 | export function scheduler (callback) { queueJob(callback) }
7 |
8 | function queueJob(job) {
9 | if (! queue.includes(job)) queue.push(job)
10 |
11 | queueFlush()
12 | }
13 |
14 | function queueFlush() {
15 | if (! flushing && ! flushPending) {
16 | flushPending = true
17 |
18 | queueMicrotask(flushJobs)
19 | }
20 | }
21 |
22 | export function flushJobs() {
23 | flushPending = false
24 | flushing = true
25 |
26 | for (let i = 0; i < queue.length; i++) {
27 | queue[i]()
28 | }
29 |
30 | queue.length = 0
31 |
32 | flushing = false
33 | }
34 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives/if.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 16
3 | title: if
4 | ---
5 |
6 | # `x-if`
7 |
8 | `x-if` is used for toggling elements on the page, similarly to `x-show`, however it completely adds and removes the elememt it's applied to rather than just changing its CSS display property to "hidden".
9 |
10 | Because of this difference in behavior, `x-if` should not be applied directly to the element, but instead to a `` tag that encloses the element. This way, Alpine can keep a record of the element once it's removed from the page.
11 |
12 | ```html
13 |
14 | Contents...
15 |
16 | ```
17 |
18 | > Unlike `x-show`, `x-if`, does NOT support tansitioning toggles with `x-transition`.
19 |
--------------------------------------------------------------------------------
/packages/persist/dist/module.esm.js:
--------------------------------------------------------------------------------
1 | // packages/persist/src/index.js
2 | function src_default(Alpine) {
3 | Alpine.magic("persist", (el, {interceptor}) => {
4 | return interceptor((key, path) => {
5 | return {
6 | init(initialValue, setter) {
7 | if (localStorage.getItem(path)) {
8 | setter(localStorage.getItem(path));
9 | } else {
10 | setter(initialValue);
11 | }
12 | },
13 | set(value, setter) {
14 | localStorage.setItem(path, value);
15 | setter(value);
16 | }
17 | };
18 | });
19 | });
20 | }
21 |
22 | // packages/persist/builds/module.js
23 | var module_default = src_default;
24 | export {
25 | module_default as default
26 | };
27 |
--------------------------------------------------------------------------------
/tests/cypress/integration/plugins/intersect.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, test, html } from '../../utils'
2 |
3 | test('can intersect',
4 | [html`
5 |
10 | `],
11 | ({ get }, reload) => {
12 | get('span').should(haveText('0'))
13 | get('span').should(haveText('1'))
14 | get('#1').scrollIntoView()
15 | get('span').should(haveText('1'))
16 | get('span').scrollIntoView()
17 | get('span').should(haveText('1'))
18 | get('#1').scrollIntoView()
19 | get('span').should(haveText('2'))
20 | },
21 | )
22 |
--------------------------------------------------------------------------------
/tests/cypress/integration/directives/x-ignore.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, notHaveClasses, notHaveText, test } from '../../utils'
2 |
3 | test('x-ignore',
4 | html`
5 |
10 | `,
11 | ({ get }) => get('span').should(notHaveText('bar'))
12 | )
13 |
14 | test('x-ignore.self',
15 | html`
16 |
17 |
18 |
19 |
20 |
21 | `,
22 | ({ get }) => {
23 | get('span').should(haveText('bar'))
24 | get('h1').should(notHaveClasses(['bar']))
25 | }
26 | )
27 |
--------------------------------------------------------------------------------
/tests/cypress/support/index.js:
--------------------------------------------------------------------------------
1 | // ***********************************************************
2 | // This example support/index.js is processed and
3 | // loaded automatically before your test files.
4 | //
5 | // This is a great place to put global configuration and
6 | // behavior that modifies Cypress.
7 | //
8 | // You can change the location of this file or turn off
9 | // automatically serving support files with the
10 | // 'supportFile' configuration option.
11 | //
12 | // You can read more here:
13 | // https://on.cypress.io/configuration
14 | // ***********************************************************
15 |
16 | // Import commands.js using ES2015 syntax:
17 | import './commands'
18 |
19 | // Alternatively you can use CommonJS syntax:
20 | // require('./commands')
21 | require('cypress-plugin-tab')
22 |
--------------------------------------------------------------------------------
/packages/intersect/dist/cdn.min.js:
--------------------------------------------------------------------------------
1 | (()=>{var r=!1;function o(n){n.directive("intersect",(e,{value:i,modifiers:t,expression:c},{evaluateLater:u})=>{let s=u(c);["out","leave"].includes(i)?e._x_intersectLeave(s,t):e._x_intersectEnter(s,t)})}window.Element.prototype._x_intersectEnter=function(n,e){this._x_intersect((i,t)=>{r||(r=!0,i.intersectionRatio>0&&(n(),e.includes("once")&&t.unobserve(this)),setTimeout(()=>{r=!1},100))})};window.Element.prototype._x_intersectLeave=function(n,e){this._x_intersect((i,t)=>{r||(r=!0,!i.intersectionRatio>0&&(n(),e.includes("once")&&t.unobserve(this)),setTimeout(()=>{r=!1},100))})};window.Element.prototype._x_intersect=function(n){let e=new IntersectionObserver(i=>{i.forEach(t=>n(t,e))},{});return e.observe(this),e};document.addEventListener("alpine:initializing",()=>{window.Alpine.plugin(o)});})();
2 |
--------------------------------------------------------------------------------
/tests/cypress/plugins/index.js:
--------------------------------------------------------------------------------
1 | ///
2 | // ***********************************************************
3 | // This example plugins/index.js can be used to load plugins
4 | //
5 | // You can change the location of this file or turn off loading
6 | // the plugins file with the 'pluginsFile' configuration option.
7 | //
8 | // You can read more here:
9 | // https://on.cypress.io/plugins-guide
10 | // ***********************************************************
11 |
12 | // This function is called when a project is opened or re-opened (e.g. due to
13 | // the project's config changing)
14 |
15 | /**
16 | * @type {Cypress.PluginConfig}
17 | */
18 | module.exports = (on, config) => {
19 | // `on` is used to hook into various events Cypress emits
20 | // `config` is the resolved Cypress config
21 | }
22 |
--------------------------------------------------------------------------------
/packages/docs/src/en/magics/nextTick.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 6
3 | prefix: $
4 | title: nextTick
5 | ---
6 |
7 | # `$nextTick`
8 |
9 | `$nextTick` is a magic property that allows you to only execute a given expression AFTER Alpine has made its reactive DOM updates. This is useful for times you want to interact with the DOM state AFTER it's reflected any data updates you've made.
10 |
11 | ```html
12 |
13 | { console.log($el.innerText) });
17 | "
18 | x-text="title"
19 | >
20 |
21 | ```
22 |
23 | In the above example, rather than logging "Hello" to the console, "Hello World!" will be logged because `$nextTick` was used to wait until Alpine was finished updating the DOM.
24 |
--------------------------------------------------------------------------------
/packages/alpinejs/node_modules/.package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "alpinejs",
3 | "version": "3.0.0",
4 | "lockfileVersion": 2,
5 | "requires": true,
6 | "packages": {
7 | "node_modules/@vue/reactivity": {
8 | "version": "3.0.11",
9 | "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.0.11.tgz",
10 | "integrity": "sha512-SKM3YKxtXHBPMf7yufXeBhCZ4XZDKP9/iXeQSC8bBO3ivBuzAi4aZi0bNoeE2IF2iGfP/AHEt1OU4ARj4ao/Xw==",
11 | "dependencies": {
12 | "@vue/shared": "3.0.11"
13 | }
14 | },
15 | "node_modules/@vue/shared": {
16 | "version": "3.0.11",
17 | "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.0.11.tgz",
18 | "integrity": "sha512-b+zB8A2so8eCE0JsxjL24J7vdGl8rzPQ09hZNhystm+KqSbKcAej1A+Hbva1rCMmTTqA+hFnUSDc5kouEo0JzA=="
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/packages/persist/dist/cdn.js:
--------------------------------------------------------------------------------
1 | (() => {
2 | // packages/persist/src/index.js
3 | function src_default(Alpine) {
4 | Alpine.magic("persist", (el, {interceptor}) => {
5 | return interceptor((key, path) => {
6 | return {
7 | init(initialValue, setter) {
8 | if (localStorage.getItem(path)) {
9 | setter(localStorage.getItem(path));
10 | } else {
11 | setter(initialValue);
12 | }
13 | },
14 | set(value, setter) {
15 | localStorage.setItem(path, value);
16 | setter(value);
17 | }
18 | };
19 | });
20 | });
21 | }
22 |
23 | // packages/persist/builds/cdn.js
24 | document.addEventListener("alpine:initializing", () => {
25 | window.Alpine.plugin(src_default);
26 | });
27 | })();
28 |
--------------------------------------------------------------------------------
/packages/docs/src/en/magics/refs.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 2
3 | prefix: $
4 | title: refs
5 | ---
6 |
7 | # `$refs`
8 |
9 | `$refs` is a magic property that can be used to retrieve DOM elements marked with `x-ref` inside the component. This is useful when you need to manually manipulate DOM elements. It's often used as a more succinct, scoped, alternative to `document.querySelector`.
10 |
11 | ```html
12 | Remove Text
13 |
14 | Hello 👋
15 | ```
16 |
17 |
18 |
19 |
20 |
Remove Text
21 |
22 |
Hello 👋
23 |
24 |
25 |
26 |
27 | Now, when the `` is pressed, the `` will be removed.
28 |
--------------------------------------------------------------------------------
/packages/intersect/node_modules/.package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@alpinejs/intersect",
3 | "version": "0.1.0",
4 | "lockfileVersion": 2,
5 | "requires": true,
6 | "packages": {
7 | "node_modules/@vue/reactivity": {
8 | "version": "3.0.10",
9 | "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.0.10.tgz",
10 | "integrity": "sha512-0GOSqlIv/a5wy4r6fAcdaglQ8v2sLYMRUpu49yK8Z2vHccK85Ym3R9C9K3vo6dfBRGbbCVvoKxYtQw49LvE8Ug==",
11 | "dependencies": {
12 | "@vue/shared": "3.0.10"
13 | }
14 | },
15 | "node_modules/@vue/shared": {
16 | "version": "3.0.10",
17 | "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.0.10.tgz",
18 | "integrity": "sha512-p8GJ+bGpEGiEHICwcCH/EtJnkZQllrOfm1J2J+Ep0ydMte25bPnArgrY/h2Tn1LKqqR3LXyQlOSYY6gJgiW2LQ=="
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/tests/cypress/integration/directives/x-bind:style.spec.js:
--------------------------------------------------------------------------------
1 | import { beHidden, beVisible, haveText, beChecked, haveAttribute, haveClasses, haveValue, notBeChecked, notHaveAttribute, notHaveClasses, test, html } from '../../utils'
2 |
3 | test('style attribute object binding',
4 | html`
5 |
6 | I should be red
7 |
8 | `,
9 | ({ get }) => {
10 | get('span').should(haveAttribute('style', 'color: red;'))
11 | }
12 | )
13 |
14 | test('style attribute object bindings are merged with existing styles',
15 | html`
16 |
17 | I should be red
18 |
19 | `,
20 | ({ get }) => {
21 | get('span').should(haveAttribute('style', 'display: block; color: red;'))
22 | }
23 | )
24 |
--------------------------------------------------------------------------------
/packages/history/dist/cdn.min.js:
--------------------------------------------------------------------------------
1 | (()=>{function h(t){t.magic("queryString",(l,{interceptor:i})=>{let e;return i((o,r)=>{let u=!1,n=e||r;return{init(a,c,w,p){let f=a,s=new URL(window.location.href);s.searchParams.has(n)&&(c(s.searchParams.get(n)),f=s.searchParams.get(n));let m={value:f};s.searchParams.set(n,f),P(s.toString(),r,m),window.addEventListener("popstate",d=>{!d.state||!d.state.alpine||Object.entries(d.state.alpine).forEach(([y,{value:g}])=>{y===o&&(u=!0,w(g),u=!1)})})},set(a,c){if(c(a),u)return;let w={value:a},p=new URL(window.location.href);p.searchParams.set(n,a),S(p.toString(),r,w)}}},o=>{o.as=r=>(e=r,o)})})}function P(t,l,i){let e=window.history.state||{};e.alpine||(e.alpine={}),e.alpine[l]=i,window.history.replaceState(e,"",t)}function S(t,l,i){let e={alpine:{...window.history.state.alpine,[l]:i}};window.history.pushState(e,"",t)}document.addEventListener("alpine:initializing",()=>{window.Alpine.plugin(h)});})();
2 |
--------------------------------------------------------------------------------
/tests/cypress/integration/plugins/trap.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, test, html, haveFocus } from '../../utils'
2 |
3 | test('can trap focus',
4 | [html`
5 |
13 | `],
14 | ({ get }, reload) => {
15 | get('#1').click()
16 | get('#1').should(haveFocus())
17 | get('#1').type('{shift}')
18 | get('#2').should(haveFocus())
19 | cy.focused().tab()
20 | get('#2').should(haveFocus())
21 | get('#2').type('{shift}')
22 | get('#1').should(haveFocus())
23 | cy.focused().tab()
24 | cy.focused().tab()
25 | get('#2').should(haveFocus())
26 | },
27 | )
28 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-if.js:
--------------------------------------------------------------------------------
1 | import { evaluateLater } from '../evaluator'
2 | import { setStyles } from '../utils/styles'
3 | import { directive } from '../directives'
4 | import { once } from '../utils/once'
5 |
6 | directive('if', (el, { modifiers, expression }, { effect, cleanup }) => {
7 | let evaluate = evaluateLater(el, expression)
8 |
9 | let show = () => {
10 | if (el._x_currentIfEl) return el._x_currentIfEl
11 |
12 | let clone = el.content.cloneNode(true).firstElementChild
13 |
14 | el.after(clone)
15 |
16 | el._x_currentIfEl = clone
17 |
18 | el._x_undoIf = () => { clone.remove(); delete el._x_currentIfEl }
19 |
20 | return clone
21 | }
22 |
23 | let hide = () => el._x_undoIf?.() || delete el._x_undoIf
24 |
25 | effect(() => evaluate(value => {
26 | value ? show() : hide()
27 | }))
28 |
29 | cleanup(() => el._x_undoIf && el._x_undoIf())
30 | })
31 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives/effect.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 11
3 | title: effect
4 | ---
5 |
6 | # `x-effect`
7 |
8 | `x-effect` is a useful directive for re-evaluating an expression when one of its dependancies change. You can think of it as a watcher where you don't have to specify what property to watch, it will watch all properties used within it.
9 |
10 | If this definition is confusing for you, that's ok. It's better explained through an example:
11 |
12 | ```html
13 |
14 | Change Message
15 |
16 | ```
17 |
18 | When this component is loaded, the `x-effect` expression will be run and "Hello" will be logged into the console.
19 |
20 | Because Alpine knows about any property references contained within `x-effect`, when the button is clicked and `label` is changed", the effect will be retriggered and "Hello World!" will be logged to the console.
21 |
--------------------------------------------------------------------------------
/tests/cypress/support/commands.js:
--------------------------------------------------------------------------------
1 | // ***********************************************
2 | // This example commands.js shows you how to
3 | // create various custom commands and overwrite
4 | // existing commands.
5 | //
6 | // For more comprehensive examples of custom
7 | // commands please read more here:
8 | // https://on.cypress.io/custom-commands
9 | // ***********************************************
10 | //
11 | //
12 | // -- This is a parent command --
13 | // Cypress.Commands.add("login", (email, password) => { ... })
14 | //
15 | //
16 | // -- This is a child command --
17 | // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
18 | //
19 | //
20 | // -- This is a dual command --
21 | // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
22 | //
23 | //
24 | // -- This will overwrite an existing command --
25 | // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
26 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/utils/styles.js:
--------------------------------------------------------------------------------
1 |
2 | export function setStyles(el, value) {
3 | if (typeof value === 'object' && value !== null) {
4 | return setStylesFromObject(el, value)
5 | }
6 |
7 | return setStylesFromString(el, value)
8 | }
9 |
10 | function setStylesFromObject(el, value) {
11 | let previousStyles = {}
12 |
13 | Object.entries(value).forEach(([key, value]) => {
14 | previousStyles[key] = el.style[key]
15 |
16 | el.style[key] = value
17 | })
18 |
19 | setTimeout(() => {
20 | if (el.style.length === 0) {
21 | el.removeAttribute('style')
22 | }
23 | })
24 |
25 | return () => {
26 | setStyles(el, previousStyles)
27 | }
28 | }
29 |
30 | function setStylesFromString(el, value) {
31 | let cache = el.getAttribute('style', value)
32 |
33 | el.setAttribute('style', value)
34 |
35 | return () => {
36 | el.setAttribute('style', cache)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/utils/walk.js:
--------------------------------------------------------------------------------
1 | export function walk(el, callback) {
2 | if (el instanceof ShadowRoot) {
3 | Array.from(el.children).forEach(el => walk(el, callback))
4 |
5 | return
6 | }
7 |
8 | let skip = false
9 |
10 | callback(el, () => skip = true)
11 |
12 | if (skip) return
13 |
14 | let node = el.firstElementChild
15 |
16 | while (node) {
17 | walk(node, callback, false)
18 |
19 | node = node.nextElementSibling
20 | }
21 | }
22 | // export function walk(el, callback) {
23 | // if (el instanceof ShadowRoot || el instanceof DocumentFragment) {
24 | // Array.from(el.children).forEach(el => walk(el, callback))
25 |
26 | // return
27 | // }
28 |
29 | // callback(el, () => {
30 | // let node = el.firstElementChild
31 |
32 | // while (node) {
33 | // walk(node, callback)
34 |
35 | // node = node.nextElementSibling
36 | // }
37 | // })
38 | // }
39 |
--------------------------------------------------------------------------------
/tests/cypress/integration/directives/x-text.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, notHaveText, test } from '../../utils'
2 |
3 | test('sets text on init',
4 | html`
5 |
6 |
7 |
8 | `,
9 | ({ get }) => { get('span').should(haveText('bar')) }
10 | )
11 |
12 | test('sets text on update',
13 | html`
14 |
15 | Show "bar"
16 |
17 |
18 |
19 | `,
20 | ({ get }) => {
21 | get('span').should(notHaveText('bar'))
22 | get('button').click()
23 | get('span').should(haveText('bar'))
24 | }
25 | )
26 |
27 | test('sets text on SVG elements',
28 | html`
29 |
30 |
31 |
32 |
33 |
34 | `,
35 | ({ get }) => get('svg text').should(haveText('bar'))
36 | )
37 |
--------------------------------------------------------------------------------
/tests/jest/morph/external.spec.js:
--------------------------------------------------------------------------------
1 | let { morph } = require('@alpinejs/morph')
2 | let createElement = require('./createElement.js')
3 |
4 | test('text content', () => assertPatch(
5 | `foo
`,
6 | `bar
`
7 | ))
8 |
9 | test('change tag', () => assertPatch(
10 | ``,
11 | `foo
`
12 | ))
13 |
14 | test('add child', () => assertPatch(
15 | `foo
`,
16 | `foo
baz `
17 | ))
18 |
19 | test('remove child', () => assertPatch(
20 | `foo
baz `,
21 | `foo
`
22 | ))
23 |
24 | test('add attribute', () => assertPatch(
25 | `foo
`,
26 | `foo
`
27 | ))
28 |
29 | test('remove attribute', () => assertPatch(
30 | `foo
`,
31 | `foo
`
32 | ))
33 |
34 | test('change attribute', () => assertPatch(
35 | `foo
`,
36 | `foo
`
37 | ))
38 |
39 | function assertPatch(before, after) {
40 | expect(morph(createElement(before), after).outerHTML).toEqual(after)
41 | }
42 |
--------------------------------------------------------------------------------
/packages/persist/dist/module.cjs.js:
--------------------------------------------------------------------------------
1 | var __defProp = Object.defineProperty;
2 | var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
3 | var __export = (target, all) => {
4 | for (var name in all)
5 | __defProp(target, name, {get: all[name], enumerable: true});
6 | };
7 |
8 | // packages/persist/builds/module.js
9 | __markAsModule(exports);
10 | __export(exports, {
11 | default: () => module_default
12 | });
13 |
14 | // packages/persist/src/index.js
15 | function src_default(Alpine) {
16 | Alpine.magic("persist", (el, {interceptor}) => {
17 | return interceptor((key, path) => {
18 | return {
19 | init(initialValue, setter) {
20 | if (localStorage.getItem(path)) {
21 | setter(localStorage.getItem(path));
22 | } else {
23 | setter(initialValue);
24 | }
25 | },
26 | set(value, setter) {
27 | localStorage.setItem(path, value);
28 | setter(value);
29 | }
30 | };
31 | });
32 | });
33 | }
34 |
35 | // packages/persist/builds/module.js
36 | var module_default = src_default;
37 |
--------------------------------------------------------------------------------
/packages/history/src/url.js:
--------------------------------------------------------------------------------
1 |
2 | export function hasQueryParam(param) {
3 | let queryParams = new URLSearchParams(window.location.search);
4 |
5 | return queryParams.has(param)
6 | }
7 |
8 | export function getQueryParam(param) {
9 | let queryParams = new URLSearchParams(window.location.search);
10 |
11 | return queryParams.get(param)
12 | }
13 |
14 | export function setQueryParam(param, value) {
15 | let queryParams = new URLSearchParams(window.location.search);
16 |
17 | queryParams.set(param, value)
18 |
19 | let url = urlFromQueryParams(queryParams)
20 |
21 | history.replaceState(history.state, '', url)
22 | }
23 |
24 | function urlFromParams(params = {}) {
25 | let queryParams = new URLSearchParams(window.location.search);
26 |
27 | Object.entries(params).forEach(([key, value]) => {
28 | queryParams.set(key, value)
29 | })
30 |
31 | let queryString = Array.from(queryParams.entries()).length > 0
32 | ? '?'+params.toString()
33 | : ''
34 |
35 | return window.location.origin + window.location.pathname + '?'+queryString + window.location.hash
36 | }
37 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/reactivity.js:
--------------------------------------------------------------------------------
1 |
2 | import { scheduler } from './scheduler'
3 |
4 | let reactive, effect, release, raw
5 |
6 | export function setReactivityEngine(engine) {
7 | reactive = engine.reactive
8 | release = engine.release
9 | effect = (callback) => engine.effect(callback, { scheduler })
10 | raw = engine.raw
11 | }
12 |
13 | export function overrideEffect(override) { effect = override }
14 |
15 | export function elementBoundEffect(el) {
16 | let cleanup = () => {}
17 |
18 | let wrappedEffect = (callback) => {
19 | let effectReference = effect(callback)
20 |
21 | if (! el._x_effects) {
22 | el._x_effects = new Set
23 |
24 | el._x_runEffects = () => { el._x_effects.forEach(i => i()) }
25 | }
26 |
27 | el._x_effects.add(effectReference)
28 |
29 | cleanup = () => {
30 | el._x_effects.delete(effectReference)
31 |
32 | release(effectReference)
33 | }
34 | }
35 |
36 | return [wrappedEffect, () => { cleanup() }]
37 | }
38 |
39 | export {
40 | release,
41 | reactive,
42 | effect,
43 | raw,
44 | }
45 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | # MIT License
2 |
3 | Copyright © 2019-2021 Caleb Porzio and contributors
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/tests/cypress/integration/magics/$refs.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../../utils'
2 |
3 | test('can reference elements from event listeners',
4 | html`
5 |
6 |
7 |
8 |
9 |
10 | `,
11 | ({ get }) => {
12 | get('button').click()
13 | get('span').should(haveText('lob'))
14 | }
15 | )
16 |
17 | test('can reference elements from data object methods',
18 | html`
19 |
20 |
21 |
22 |
23 |
24 | `,
25 | ({ get }) => {
26 | get('button').click()
27 | get('span').should(haveText('lob'))
28 | }
29 | )
30 |
31 | test('can reference elements from x-init',
32 | html`
33 |
34 | bob
35 |
36 | `,
37 | ({ get }) => {
38 | get('span').should(haveText('lob'))
39 | }
40 | )
41 |
--------------------------------------------------------------------------------
/tests/cypress/integration/directives/x-init.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../../utils'
2 |
3 | test('sets text on init',
4 | html`
5 |
6 |
7 |
8 | `,
9 | ({ get }) => get('span').should(haveText('baz'))
10 | )
11 |
12 |
13 | test('x-init can be used outside of x-data',
14 | html`
15 |
16 | `,
17 | ({ get }) => get('div').should(haveText('foo'))
18 | )
19 |
20 |
21 | test('changes made in x-init happen before the rest of the component',
22 | html`
23 |
24 | baz
25 |
26 | `,
27 | ({ get }) => get('span').should(haveText('bar'))
28 | )
29 |
30 | test('can make deferred changes with $nextTick',
31 | html`
32 |
33 | baz
34 |
35 | `,
36 | ({ get }) => get('span').should(haveText('yo'))
37 | )
38 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/alpine.js:
--------------------------------------------------------------------------------
1 | import { setReactivityEngine, reactive, effect, release, raw } from './reactivity'
2 | import { mapAttributes, directive, setPrefix as prefix } from './directives'
3 | import { setEvaluator, evaluate, evaluateLater } from './evaluator'
4 | import { start, addRootSelector, closestRoot } from './lifecycle'
5 | import { interceptor } from './interceptor'
6 | import { mutateDom } from './mutation'
7 | import { nextTick } from './nextTick'
8 | import { plugin } from './plugin'
9 | import { magic } from './magics'
10 | import { store } from './store'
11 | import { clone } from './clone'
12 | import { data } from './datas'
13 |
14 | let Alpine = {
15 | get reactive() { return reactive },
16 | get release() { return release },
17 | get effect() { return effect },
18 | get raw() { return raw },
19 | version: ALPINE_VERSION,
20 | setReactivityEngine,
21 | addRootSelector,
22 | mapAttributes,
23 | evaluateLater,
24 | setEvaluator,
25 | closestRoot,
26 | interceptor,
27 | mutateDom,
28 | directive,
29 | evaluate,
30 | nextTick,
31 | prefix,
32 | plugin,
33 | magic,
34 | store,
35 | start,
36 | clone,
37 | data,
38 | }
39 |
40 | export default Alpine
41 |
--------------------------------------------------------------------------------
/packages/docs/src/en/advanced/async.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 4
3 | title: Async
4 | ---
5 |
6 | # Async
7 |
8 | Alpine is built to support asynchronous functions in most places it supports standard ones.
9 |
10 | For example, let's say you have a simple function called `getLabel()` that you use as the input to an `x-text` directive:
11 |
12 | ```js
13 | function getLabel() {
14 | return 'Hello World!'
15 | }
16 | ```
17 | ```html
18 |
19 | ```
20 |
21 | Because `getLabel` is synchronous, everything works as expected.
22 |
23 | Now let's pretend that `getLabel` makes a network request to retrieve the label and can't return one instantaniously (asynchronous). By making `getLabel` an async function, you can call it from Alpine using JavaScript's `await` syntax.
24 |
25 | ```js
26 | async function getLabel() {
27 | let response = await fetch('/api/label')
28 |
29 | return await response.text()
30 | }
31 | ```
32 | ```html
33 |
34 | ```
35 |
36 | Additionally, if you prefer calling methods in Alpine without the trailing parenthesis, you can leave them out and Alpine will detect that the provided function is async and handle it accordingly. For example:
37 |
38 | ```html
39 |
40 | ```
41 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-data.js:
--------------------------------------------------------------------------------
1 | import { directive, prefix } from '../directives'
2 | import { initInterceptors } from '../interceptor'
3 | import { getNamedDataProvider } from '../datas'
4 | import { addRootSelector } from '../lifecycle'
5 | import { skipDuringClone } from '../clone'
6 | import { addScopeToNode } from '../scope'
7 | import { injectMagics } from '../magics'
8 | import { reactive } from '../reactivity'
9 | import { evaluate } from '../evaluator'
10 |
11 | addRootSelector(() => `[${prefix('data')}]`)
12 |
13 | directive('data', skipDuringClone((el, { expression }, { cleanup }) => {
14 | expression = expression === '' ? '{}' : expression
15 |
16 | let dataProvider = getNamedDataProvider(expression)
17 |
18 | let data = {}
19 |
20 | if (dataProvider) {
21 | let magics = injectMagics({}, el)
22 |
23 | data = dataProvider.bind(magics)()
24 | } else {
25 | data = evaluate(el, expression)
26 | }
27 |
28 | initInterceptors(data)
29 |
30 | injectMagics(data, el)
31 |
32 | let reactiveData = reactive(data)
33 |
34 | let undo = addScopeToNode(el, reactiveData)
35 |
36 | if (reactiveData['init']) reactiveData['init']()
37 |
38 | cleanup(() => {
39 | undo()
40 |
41 | reactiveData['destroy'] && reactiveData['destroy']()
42 | })
43 | }))
44 |
--------------------------------------------------------------------------------
/packages/docs/src/en/magics/watch.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 4
3 | title: watch
4 | ---
5 |
6 | # `$watch`
7 |
8 | You can "watch" a component property using the `$watch` magic method. For example:
9 |
10 | ```html
11 |
12 | Toggle Open
13 |
14 | ```
15 |
16 | In the above example, when the button is pressed and `open` is changed, the provided callback will fire and `console.log` the new value:
17 |
18 | You can watch deeply nested properties using "dot" notation
19 |
20 | ```html
21 |
22 | Toggle Open
23 |
24 | ```
25 |
26 | When the `` is pressed, `foo.bar` will be set to "bob", and "bob" will be logged to the console.
27 |
28 |
29 | ### Getting the "old" value
30 |
31 | `$watch` keeps track of the previous value of the property being watched, You can access it using the optional second argument to the callback like so:
32 |
33 | ```html
34 |
35 | Toggle Open
36 |
37 | ```
38 |
--------------------------------------------------------------------------------
/packages/csp/src/index.js:
--------------------------------------------------------------------------------
1 | import Alpine from 'alpinejs/src/alpine'
2 |
3 | Alpine.setEvaluator(cspCompliantEvaluator)
4 |
5 | import { reactive, effect, stop, toRaw } from '@vue/reactivity'
6 | Alpine.setReactivityEngine({ reactive, effect, release: stop, raw: toRaw })
7 |
8 | import 'alpinejs/src/magics/index'
9 | import 'alpinejs/src/directives/index'
10 |
11 | import { closestDataStack, mergeProxies } from 'alpinejs/src/scope'
12 | import { injectMagics } from 'alpinejs/src/magics'
13 | import { generateEvaluatorFromFunction, runIfTypeOfFunction, tryCatch } from 'alpinejs/src/evaluator'
14 |
15 | function cspCompliantEvaluator(el, expression) {
16 | let overriddenMagics = {}
17 |
18 | injectMagics(overriddenMagics, el)
19 |
20 | let dataStack = [overriddenMagics, ...closestDataStack(el)]
21 |
22 | if (typeof expression === 'function') {
23 | return generateEvaluatorFromFunction(dataStack, expression)
24 | }
25 |
26 | let evaluator = (receiver = () => {}, { scope = {}, params = [] } = {}) => {
27 | let completeScope = mergeProxies([scope, ...dataStack])
28 |
29 | if (completeScope[expression] !== undefined) {
30 | runIfTypeOfFunction(receiver, completeScope[expression], completeScope, params)
31 | }
32 | }
33 |
34 | return tryCatch.bind(null, el, expression, evaluator)
35 | }
36 |
37 | export default Alpine
38 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-bind.js:
--------------------------------------------------------------------------------
1 | import { directive, directives, into, mapAttributes, prefix, startingWith } from '../directives'
2 | import { evaluateLater } from '../evaluator'
3 | import { mutateDom } from '../mutation'
4 | import bind from '../utils/bind'
5 |
6 | mapAttributes(startingWith(':', into(prefix('bind:'))))
7 |
8 | directive('bind', (el, { value, modifiers, expression, original }, { effect }) => {
9 | if (! value) return applyBindingsObject(el, expression, original, effect)
10 |
11 | if (value === 'key') return storeKeyForXFor(el, expression)
12 |
13 | let evaluate = evaluateLater(el, expression)
14 |
15 | effect(() => evaluate(result => {
16 | mutateDom(() => bind(el, value, result, modifiers))
17 | }))
18 | })
19 |
20 | function applyBindingsObject(el, expression, original, effect) {
21 | let getBindings = evaluateLater(el, expression)
22 |
23 | let cleanupRunners = []
24 |
25 | effect(() => {
26 | while (cleanupRunners.length) cleanupRunners.pop()()
27 |
28 | getBindings(bindings => {
29 | let attributes = Object.entries(bindings).map(([name, value]) => ({ name, value }))
30 |
31 | directives(el, attributes, original).map(handle => {
32 | cleanupRunners.push(handle.runCleanups)
33 |
34 | handle()
35 | })
36 | })
37 |
38 | })
39 | }
40 |
41 | function storeKeyForXFor(el, expression) {
42 | el._x_key_expression = expression
43 | }
44 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives/show.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 3
3 | title: show
4 | ---
5 |
6 | # `x-show`
7 |
8 | `x-show` is one of the most useful and powerful directives in Alpine. It provides an expressive way to show and hide DOM elements.
9 |
10 | Here's an example of a simple dropdown component using `x-show`.
11 |
12 | ```html
13 |
14 |
Toggle Dropdown
15 |
16 |
17 | Dropdown Contents...
18 |
19 |
20 | ```
21 |
22 | When the "Toggle Dropdown" button is clicked, the dropdown will show and hide accordingly.
23 |
24 | > If the "default" state of an `x-show` on page load is "false", you may want to use `x-cloak` on the page to avoid "page flicker" (The effect that happens when the browser renders your content before Alpine is finished initializing and hiding it.) You can learn more about `x-cloak` in its documentation.
25 |
26 |
27 | ## With transitions
28 |
29 | If you want to apply smooth transitions to the `x-show` behavior, you can use it in conjunction with `x-transition`. You can learn more about that directive [here](), but here's a quick example of the same component as above, just with transitions applied.
30 |
31 | ```html
32 |
33 |
Toggle Dropdown
34 |
35 |
36 | Dropdown Contents...
37 |
38 |
39 | ```
40 |
--------------------------------------------------------------------------------
/packages/docs/src/en/directives/cloak.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 12
3 | title: cloak
4 | ---
5 |
6 | # `x-cloak`
7 |
8 | Sometimes, when you're using AlpineJS for a part of your template, there is a "blip" where you might see your uninitialized template after the page loads, but before Alpine loads.
9 |
10 | `x-cloak` addresses this scenerio by hiding the element it's attached to until Alpine is fully loaded on the page.
11 |
12 | For `x-cloak` to work however, you must add the following CSS to the page.
13 |
14 | ```css
15 | [x-cloak] { display: none !important; }
16 | ```
17 |
18 | Now, the following example will hide the `` tag until Alpine has set its text content to the `message` property.
19 |
20 | ```html
21 |
22 | ```
23 |
24 | When Alpine loads on the page, it removes all `x-cloak` property from the element, which also removes the `display: none;` applied by CSS, therefore showing the element.
25 |
26 | If you'd like to achieve this same behavior, but avoid having to include a global style, you can use the following cool, but admittadly odd trick:
27 |
28 | ```html
29 |
30 |
31 |
32 | ```
33 |
34 | This will achieve the same goal as `x-cloak` by just leveraging the way `x-if` works.
35 |
36 | Because `` elements are "hidden" in browsers by default, you won't see the `` until Alpine has had a chance to render the `x-if="true"` and show it.
37 |
38 | Again, this solution is not for everyone, but it's worth mentioning for special cases.
39 |
--------------------------------------------------------------------------------
/packages/docs/src/en/magics/store.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 3
3 | prefix: $
4 | title: store
5 | ---
6 |
7 | # `$store`
8 |
9 | You can use `$store` to conveniently access global Alpine stores registered using [`Alpine.store(...)`](#). For example:
10 |
11 | ```html
12 | Toggle Dark Mode
13 |
14 | ...
15 |
16 |
17 | ...
18 |
19 |
20 |
21 |
32 | ```
33 |
34 | Given that we've registered the `darkMode` store and set `on` to "false", when the `` is pressed, `on` will be "true" and the background color of the page will change to black.
35 |
36 |
37 | ## Single-value stores
38 |
39 | If you don't need an entire object for a store, you can set and use any kind of data as a store.
40 |
41 | Here's the example from above but using it more simply as a boolean value:
42 |
43 | ```html
44 | Toggle Dark Mode
45 |
46 | ...
47 |
48 |
49 | ...
50 |
51 |
52 |
53 |
58 | ```
59 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/directives/x-show.js:
--------------------------------------------------------------------------------
1 | import { evaluateLater } from '../evaluator'
2 | import { directive } from '../directives'
3 | import { mutateDom } from '../mutation'
4 | import { once } from '../utils/once'
5 |
6 | directive('show', (el, { modifiers, expression }, { effect }) => {
7 | let evaluate = evaluateLater(el, expression)
8 |
9 | let hide = () => mutateDom(() => {
10 | el.style.display = 'none'
11 |
12 | el._x_is_shown = false
13 | })
14 |
15 | let show = () => mutateDom(() => {
16 | if (el.style.length === 1 && el.style.display === 'none') {
17 | el.removeAttribute('style')
18 | } else {
19 | el.style.removeProperty('display')
20 | }
21 |
22 | el._x_is_shown = true
23 | })
24 |
25 | // We are wrapping this function in a setTimeout here to prevent
26 | // a race condition from happening where elements that have a
27 | // @click.away always view themselves as shown on the page.
28 | let clickAwayCompatibleShow = () => setTimeout(show)
29 |
30 | let toggle = once(
31 | value => value ? show() : hide(),
32 | value => {
33 | if (typeof el._x_toggleAndCascadeWithTransitions === 'function') {
34 | el._x_toggleAndCascadeWithTransitions(el, value, show, hide)
35 | } else {
36 | value ? clickAwayCompatibleShow() : hide()
37 | }
38 | }
39 | )
40 |
41 | effect(() => evaluate(value => {
42 | if (modifiers.includes('immediate')) value ? clickAwayCompatibleShow() : hide()
43 |
44 | toggle(value)
45 | }))
46 | })
47 |
--------------------------------------------------------------------------------
/packages/alpinejs/src/clone.js:
--------------------------------------------------------------------------------
1 | import { effect, release, overrideEffect } from "./reactivity"
2 | import { initTree, isRoot } from "./lifecycle"
3 | import { walk } from "./utils/walk"
4 |
5 | let isCloning = false
6 |
7 | export function skipDuringClone(callback) {
8 | return (...args) => isCloning || callback(...args)
9 | }
10 |
11 | export function onlyDuringClone(callback) {
12 | return (...args) => isCloning && callback(...args)
13 | }
14 |
15 | export function skipWalkingSubClone(callback) {
16 | return (...args) => isCloning || callback(...args)
17 | }
18 |
19 | export function interuptCrawl(callback) {
20 | return (...args) => isCloning || callback(...args)
21 | }
22 |
23 | export function clone(oldEl, newEl) {
24 | newEl._x_dataStack = oldEl._x_dataStack
25 |
26 | isCloning = true
27 |
28 | dontRegisterReactiveSideEffects(() => {
29 | cloneTree(newEl)
30 | })
31 |
32 | isCloning = false
33 | }
34 |
35 | export function cloneTree(el) {
36 | let hasRunThroughFirstEl = false
37 |
38 | let shallowWalker = (el, callback) => {
39 | walk(el, (el, skip) => {
40 | if (hasRunThroughFirstEl && isRoot(el)) return skip()
41 |
42 | hasRunThroughFirstEl = true
43 |
44 | callback(el, skip)
45 | })
46 | }
47 |
48 | initTree(el, shallowWalker)
49 | }
50 |
51 | function dontRegisterReactiveSideEffects(callback) {
52 | let cache = effect
53 |
54 | overrideEffect((callback, el) => {
55 | let storedEffect = cache(callback)
56 |
57 | release(storedEffect)
58 | })
59 |
60 | callback()
61 |
62 | overrideEffect(cache)
63 | }
64 |
--------------------------------------------------------------------------------
/tests/cypress/integration/custom-directives.spec.js:
--------------------------------------------------------------------------------
1 | import { haveText, html, test } from '../utils'
2 |
3 | test('can register custom directive',
4 | [html`
5 |
6 |
7 |
8 | `,
9 | `
10 | Alpine.directive('foo', (el, { value, modifiers, expression }) => {
11 | el.textContent = value+modifiers+expression
12 | })
13 | `],
14 | ({ get }) => get('span').should(haveText('barbazbob'))
15 | )
16 |
17 | test('directives are auto cleaned up',
18 | [html`
19 |
20 |
21 |
22 |
23 | change
24 | remove
25 |
26 | `,
27 | `
28 | Alpine.directive('foo', (el, {}, { effect, cleanup, evaluateLater }) => {
29 | let evaluate = evaluateLater('foo')
30 | let incCount = evaluateLater('count++')
31 |
32 | cleanup(() => {
33 | incCount()
34 | incCount()
35 | })
36 |
37 | effect(() => {
38 | incCount()
39 | evaluate(value => el.textContent = value)
40 | })
41 | })
42 | `],
43 | ({ get }) => {
44 | get('h1').should(haveText('1'))
45 | get('#change').click()
46 | get('h1').should(haveText('3'))
47 | get('#remove').click()
48 | get('#change').click()
49 | get('h1').should(haveText('6'))
50 | get('#change').click()
51 | get('h1').should(haveText('7'))
52 | }
53 | )
54 |
--------------------------------------------------------------------------------
/packages/intersect/dist/module.esm.js:
--------------------------------------------------------------------------------
1 | // packages/intersect/src/index.js
2 | var pauseReactions = false;
3 | function src_default(Alpine) {
4 | Alpine.directive("intersect", (el, {value, modifiers, expression}, {evaluateLater}) => {
5 | let evaluate = evaluateLater(expression);
6 | if (["out", "leave"].includes(value)) {
7 | el._x_intersectLeave(evaluate, modifiers);
8 | } else {
9 | el._x_intersectEnter(evaluate, modifiers);
10 | }
11 | });
12 | }
13 | window.Element.prototype._x_intersectEnter = function(callback, modifiers) {
14 | this._x_intersect((entry, observer) => {
15 | if (pauseReactions)
16 | return;
17 | pauseReactions = true;
18 | if (entry.intersectionRatio > 0) {
19 | callback();
20 | modifiers.includes("once") && observer.unobserve(this);
21 | }
22 | setTimeout(() => {
23 | pauseReactions = false;
24 | }, 100);
25 | });
26 | };
27 | window.Element.prototype._x_intersectLeave = function(callback, modifiers) {
28 | this._x_intersect((entry, observer) => {
29 | if (pauseReactions)
30 | return;
31 | pauseReactions = true;
32 | if (!entry.intersectionRatio > 0) {
33 | callback();
34 | modifiers.includes("once") && observer.unobserve(this);
35 | }
36 | setTimeout(() => {
37 | pauseReactions = false;
38 | }, 100);
39 | });
40 | };
41 | window.Element.prototype._x_intersect = function(callback) {
42 | let observer = new IntersectionObserver((entries) => {
43 | entries.forEach((entry) => callback(entry, observer));
44 | }, {});
45 | observer.observe(this);
46 | return observer;
47 | };
48 |
49 | // packages/intersect/builds/module.js
50 | var module_default = src_default;
51 | export {
52 | module_default as default
53 | };
54 |
--------------------------------------------------------------------------------
/packages/intersect/src/index.js:
--------------------------------------------------------------------------------
1 | let pauseReactions = false
2 |
3 | export default function (Alpine) {
4 | Alpine.directive('intersect', (el, { value, modifiers, expression }, { evaluateLater }) => {
5 | let evaluate = evaluateLater(expression)
6 |
7 | if (['out', 'leave'].includes(value)) {
8 | el._x_intersectLeave(evaluate, modifiers)
9 | } else {
10 | el._x_intersectEnter(evaluate, modifiers)
11 | }
12 | })
13 | }
14 |
15 | window.Element.prototype._x_intersectEnter = function (callback, modifiers) {
16 | this._x_intersect((entry, observer) => {
17 | if (pauseReactions) return
18 |
19 | pauseReactions = true
20 | if (entry.intersectionRatio > 0) {
21 |
22 | callback()
23 |
24 | modifiers.includes('once') && observer.unobserve(this)
25 |
26 |
27 | }
28 | setTimeout(() => {
29 | pauseReactions = false
30 | }, 100);
31 | })
32 | }
33 |
34 | window.Element.prototype._x_intersectLeave = function (callback, modifiers) {
35 | this._x_intersect((entry, observer) => {
36 | if (pauseReactions) return
37 |
38 | pauseReactions = true
39 | if (! entry.intersectionRatio > 0) {
40 |
41 | callback()
42 |
43 | modifiers.includes('once') && observer.unobserve(this)
44 |
45 |
46 | }
47 | setTimeout(() => {
48 | pauseReactions = false
49 | }, 100);
50 | })
51 | }
52 |
53 | window.Element.prototype._x_intersect = function (callback) {
54 | let observer = new IntersectionObserver(entries => {
55 | entries.forEach(entry => callback(entry, observer))
56 | }, {
57 | // threshold: 1,
58 | })
59 |
60 | observer.observe(this);
61 |
62 | return observer
63 | }
64 |
--------------------------------------------------------------------------------
/packages/docs/src/en/essentials/installation.md:
--------------------------------------------------------------------------------
1 | ---
2 | order: 1
3 | title: Installation
4 | ---
5 |
6 | # Installation
7 |
8 | There are 2 ways to include Alpine into your project:
9 |
10 | * Including it from a `
26 |
27 | ...
28 |