Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Alpine.js with JS hooks #818

Open
wants to merge 42 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
59f0b1c
implement hook basics and first hook for upload field
pehbehbeh Jan 30, 2025
4603593
adjust installation guide
pehbehbeh Jan 30, 2025
f767839
add upgrade guide
pehbehbeh Jan 30, 2025
7bb1e5f
prefix backpex hook to prevent conflicts
pehbehbeh Jan 30, 2025
b3dc828
fix typos
pehbehbeh Jan 30, 2025
71a768e
mix format
pehbehbeh Jan 30, 2025
a6f344b
dispatch form change on upload entry cancel
pehbehbeh Feb 2, 2025
388fd89
replace alpinejs with liveview JS in multi select filter dropdown
pehbehbeh Feb 2, 2025
2af6c2f
use daisyui drawer component for mobile menu
pehbehbeh Feb 2, 2025
bfa5670
split hooks
pehbehbeh Feb 2, 2025
52e6c3e
replace alpinejs with liveview JS for sidebar sections
pehbehbeh Feb 2, 2025
9ed7f13
remove obsolete class toggle
pehbehbeh Feb 2, 2025
0e4e888
replace row height with CSS solution
pehbehbeh Feb 5, 2025
3ab809c
remove global_prefixes for alpine
pehbehbeh Feb 5, 2025
2894320
remove alpinejs
pehbehbeh Feb 5, 2025
dc80267
remove autofocus hook (not used anymore?)
pehbehbeh Feb 5, 2025
3b3d205
move theme selector to backpex hooks
pehbehbeh Feb 5, 2025
02e663b
improve docs and upgrade guide
pehbehbeh Feb 5, 2025
43a161e
improve installation docs
pehbehbeh Feb 5, 2025
711531f
formatting
pehbehbeh Feb 5, 2025
f2d4ae9
add intersection observer to dynamically show border+shadow on item a…
pehbehbeh Feb 5, 2025
e7ddf60
remove item action tooltips (because of clipping issues)
pehbehbeh Feb 5, 2025
9dc1566
Merge branch 'develop' into feature/backpex-hooks
pehbehbeh Feb 5, 2025
a9149c4
fix stuck attribute on re-renders
pehbehbeh Feb 5, 2025
c4d04d8
copy backpex js package stuff before building the assets
pehbehbeh Feb 6, 2025
af74071
please credo
pehbehbeh Feb 6, 2025
c21e0d8
Update theme selector hook
Flo0807 Feb 7, 2025
6a0b25b
Remove event listener on destroy
Flo0807 Feb 7, 2025
dc75a48
Format js files
Flo0807 Feb 7, 2025
b759fde
Install javascript standard
Flo0807 Feb 7, 2025
e57155f
Update standard command in package.json
Flo0807 Feb 7, 2025
ccd84dc
Run standard in ci
Flo0807 Feb 7, 2025
993a8fd
Install node dependencies in ci
Flo0807 Feb 7, 2025
3c0eeb7
Fix standard issue
Flo0807 Feb 7, 2025
3da4b55
Add js files and package json to package files
Flo0807 Feb 7, 2025
6e8a17e
Update lib/backpex/html/layout.ex
Flo0807 Feb 7, 2025
e13379b
Update colors
Flo0807 Feb 7, 2025
5d4453c
Improve class assignments
Flo0807 Feb 7, 2025
bdf5b91
Remove some border classes
Flo0807 Feb 7, 2025
eb59792
Add init order to category live
Flo0807 Feb 7, 2025
e3d9808
Refactor sidebar sections
Flo0807 Feb 7, 2025
55c9853
Format
Flo0807 Feb 7, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ jobs:
otp-version: ${{ matrix.erlang }}
elixir-version: ${{ matrix.elixir }}

- name: Setup node
uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0
with:
node-version: 20
cache: 'yarn'
cache-dependency-path: yarn.lock

- name: Restore the deps and _build cache
uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0
id: restore-cache
Expand All @@ -58,14 +65,17 @@ jobs:
if: steps.restore-cache.outputs.cache-hit != 'true'
run: mix deps.compile

- name: Run tests
run: mix test
- name: Compile with warnings as errors
run: mix compile --warnings-as-errors --force

- name: Install node dependencies
run: yarn install --pure-lockfile

- name: Check formatting
run: mix format --check-formatted

- name: Compile with warnings as errors
run: mix compile --warnings-as-errors --force
- name: JavaScript Standard
run: yarn run lint:standard

- name: Build docs with warnings as errors
run: mix docs --warnings-as-errors
Expand All @@ -79,6 +89,9 @@ jobs:
- name: Deps Unused
run: mix deps.unlock --check-unused

- name: Run tests
run: mix test

- name: Deps Audit
continue-on-error: true
run: mix deps.audit
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ backpex-*.tar
/priv/static/assets/
/priv/static/cache_manifest.json
npm-debug.log
/assets/node_modules/
/node_modules

2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ COPY demo/package.json demo/yarn.lock demo/.stylelintrc.json ./
RUN yarn install --pure-lockfile
COPY demo/assets assets/
COPY demo/lib lib/
COPY assets ../assets/
COPY package.json ../
RUN mix assets.deploy

# Copy the rest of the application files
Expand Down
3 changes: 3 additions & 0 deletions assets/js/backpex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as Hooks from './hooks'

export { Hooks }
18 changes: 18 additions & 0 deletions assets/js/hooks/_cancel_entry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* This hook dispatches a form change/input event on the hidden upload field when cancelling an entry.
* This makes errors validation on upload fields work.
*/
export default {
mounted () {
this.form = this.el.closest('form')

const uploadKey = this.el.dataset.uploadKey
this.handleEvent(`cancel-entry:${uploadKey}`, (e) => { this.dispatchChangeEvent() })
this.handleEvent(`cancel-existing-entry:${uploadKey}`, (e) => { this.dispatchChangeEvent() })
},
dispatchChangeEvent () {
if (this.form) {
this.el.dispatchEvent(new Event('input', { bubbles: true }))
}
}
}
25 changes: 25 additions & 0 deletions assets/js/hooks/_drag_hover.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* This hook adds hover styles on the upload dropzone when dragging a file over it.
*/
export default {
mounted () {
this.dragging = 0

this.dragenterHandler = () => this.dragChange(this.dragging + 1)
this.dragleaveHandler = () => this.dragChange(this.dragging - 1)
this.dropHandler = () => this.dragChange(0)

this.el.addEventListener('dragenter', this.dragenterHandler)
this.el.addEventListener('dragleave', this.dragleaveHandler)
this.el.addEventListener('drop', this.dropHandler)
},
Flo0807 marked this conversation as resolved.
Show resolved Hide resolved
dragChange (value) {
this.dragging = value
this.el.firstElementChild.classList.toggle('border-primary', this.dragging > 0)
},
destroyed () {
this.el.removeEventListener('dragenter', this.dragenterHandler)
this.el.removeEventListener('dragleave', this.dragleaveHandler)
this.el.removeEventListener('drop', this.dropHandler)
}
}
50 changes: 50 additions & 0 deletions assets/js/hooks/_sidebar_sections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Handles the initial state of all sidebar sections and saves the state to localstorage on toggle.
*/
export default {
mounted () {
this.initializeSections()
},
updated () {
this.initializeSections()
},
destroyed () {
const sections = this.el.querySelectorAll('[data-section-id]')

sections.forEach(section => {
const toggle = section.querySelector('[data-menu-dropdown-toggle]')
toggle.removeEventListener('click', this.handleToggle.bind(this))
})
},
initializeSections () {
const sections = this.el.querySelectorAll('[data-section-id]')

sections.forEach(section => {
const sectionId = section.dataset.sectionId
const toggle = section.querySelector('[data-menu-dropdown-toggle]')
const content = section.querySelector('[data-menu-dropdown-content]')

const isOpen = localStorage.getItem(`sidebar-section-${sectionId}`) === 'true'
if (!isOpen) {
toggle.classList.remove('menu-dropdown-show')
content.style.display = 'none'
}

section.classList.remove('hidden')

toggle.addEventListener('click', this.handleToggle.bind(this))
})
},
handleToggle (event) {
const section = event.currentTarget.closest('[data-section-id]')
const sectionId = section.dataset.sectionId
const toggle = section.querySelector('[data-menu-dropdown-toggle]')
const content = section.querySelector('[data-menu-dropdown-content]')

toggle.classList.toggle('menu-dropdown-show')
content.style.display = content.style.display === 'none' ? 'block' : 'none'

const isNowOpen = toggle.classList.contains('menu-dropdown-show')
localStorage.setItem(`sidebar-section-${sectionId}`, isNowOpen)
}
}
29 changes: 29 additions & 0 deletions assets/js/hooks/_sticky_actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Hook to determine if a table row is horizontally scrollable (=> actions are sticky).
*
* Adds a 'stuck' attribute to the sticky element which can then be used for styling.
*/
export default {
mounted () {
this.sticky = this.el.querySelector('.sticky')

this.observer = new IntersectionObserver(
([entry]) => {
this.stuck = entry.intersectionRatio < 1
this.toggleStuckAttribute()
},
{ threshold: [1], root: this.el.closest('.overflow-x-auto') }
)

this.observer.observe(this.el)
},
updated () {
this.toggleStuckAttribute()
},
destroyed () {
this.observer.disconnect()
},
toggleStuckAttribute () {
this.sticky.toggleAttribute('stuck', this.stuck)
}
}
Flo0807 marked this conversation as resolved.
Show resolved Hide resolved
56 changes: 56 additions & 0 deletions assets/js/hooks/_theme_selector.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Hook for selecting a theme.
*/
export default {
mounted () {
const form = document.querySelector('#backpex-theme-selector-form')
const storedTheme = window.localStorage.getItem('backpexTheme')

// Marking current theme as active
if (storedTheme != null) {
const activeThemeRadio = form.querySelector(
`input[name='theme-selector'][value='${storedTheme}']`
)
activeThemeRadio.checked = true
}

window.addEventListener('backpex:theme-change', this.handleThemeChange.bind(this))
},
// Event listener that handles the theme changes and store
// the selected theme in the session and also in localStorage
async handleThemeChange () {
const form = document.querySelector('#backpex-theme-selector-form')
const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute('content')
const cookiePath = form.dataset.cookiePath
const selectedTheme = form.querySelector(
'input[name="theme-selector"]:checked'
)

if (selectedTheme) {
window.localStorage.setItem('backpexTheme', selectedTheme.value)
document.documentElement.setAttribute(
'data-theme',
selectedTheme.value
)
await fetch(cookiePath, {
body: `select_theme=${selectedTheme.value}`,
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
'x-csrf-token': csrfToken
}
})
}
},
// Call this from your app.js as soon as possible to minimize flashes with the old theme in some situations.
setStoredTheme () {
const storedTheme = window.localStorage.getItem('backpexTheme')

if (storedTheme != null) {
document.documentElement.setAttribute('data-theme', storedTheme)
}
},
destroyed () {
window.removeEventListener('backpex:theme-change', this.handleThemeChange.bind(this))
}
}
5 changes: 5 additions & 0 deletions assets/js/hooks/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export { default as BackpexCancelEntry } from './_cancel_entry'
export { default as BackpexDragHover } from './_drag_hover'
export { default as BackpexSidebarSections } from './_sidebar_sections'
export { default as BackpexStickyActions } from './_sticky_actions'
export { default as BackpexThemeSelector } from './_theme_selector'
82 changes: 5 additions & 77 deletions demo/assets/js/app.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import Alpine from 'alpinejs'
import 'phoenix_html'
import * as Sentry from '@sentry/browser'
import topbar from 'topbar'
import { Socket } from 'phoenix'
import { LiveSocket } from 'phoenix_live_view'

/**
* Alpine
*/
window.Alpine = Alpine
Alpine.start()
import { Hooks as BackpexHooks } from 'backpex'

/**
* Sentry
Expand All @@ -27,84 +21,18 @@ window.addEventListener('phx:page-loading-start', _info => topbar.show(250))
window.addEventListener('phx:page-loading-stop', _info => topbar.hide())

/**
* theme selector
* Theme Selector
*/

const Hooks = {}

// We want this to run as soon as possible to minimize
// flashes with the old theme in some situations
const storedTheme = window.localStorage.getItem('backpexTheme')
if (storedTheme != null) {
document.documentElement.setAttribute('data-theme', storedTheme)
}
Hooks.BackpexThemeSelector = {
mounted () {
const form = document.querySelector('#backpex-theme-selector-form')
const storedTheme = window.localStorage.getItem('backpexTheme')

// Marking current theme as active
if (storedTheme != null) {
const activeThemeRadio = form.querySelector(
`input[name='theme-selector'][value='${storedTheme}']`
)
activeThemeRadio.checked = true
}

// Event listener that handles the theme changes and store
// the selected theme in the session and also in localStorage
window.addEventListener('backpex:theme-change', async (event) => {
const cookiePath = form.dataset.cookiePath
const selectedTheme = form.querySelector(
'input[name="theme-selector"]:checked'
)
if (selectedTheme) {
window.localStorage.setItem('backpexTheme', selectedTheme.value)
document.documentElement.setAttribute(
'data-theme',
selectedTheme.value
)
await fetch(cookiePath, {
body: `select_theme=${selectedTheme.value}`,
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
'x-csrf-token': csrfToken
}
})
}
})
}
}
BackpexHooks.BackpexThemeSelector.setStoredTheme()

/**
* phoenix_live_view
*/
const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute('content')

const liveSocket = new LiveSocket('/live', Socket, {
dom: {
onBeforeElUpdated (from, to) {
if (from._x_dataStack) {
window.Alpine.clone(from, to)
}
},
onNodeAdded (node) {
// Mimic autofocus for dynamically inserted elements
if (node.nodeType === window.Node.ELEMENT_NODE && node.hasAttribute('autofocus')) {
node.focus()

if (node.setSelectionRange && node.value) {
const lastIndex = node.value.length
node.setSelectionRange(lastIndex, lastIndex)
}
}
Comment on lines -92 to -101
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't remember why we added this, but I wanted to add a comment in case this wasn't Alpine's reason (I don't see any Alpine specific code like in onBeforeElUpdated).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are not using autofocus in the codebase... so I removed it. Looked like a project-specific thing? But I was wondering about that one, too.

}
},
params: {
_csrf_token: csrfToken
},
hooks: Hooks
params: { _csrf_token: csrfToken },
hooks: { ...BackpexHooks }
})

liveSocket.connect()
Expand Down
3 changes: 2 additions & 1 deletion demo/assets/tailwind.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ module.exports = {
'assets/js/**/*.js',
'lib/*_web.ex',
'lib/*_web/**/*.{ex,heex}',
'../lib/**/*.*ex'
'../lib/**/*.*ex',
'../assets/js/**/*.js'
],
safelist: [
'input'
Expand Down
2 changes: 1 addition & 1 deletion demo/config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ config :esbuild,
version: "0.24.2",
default: [
args:
~w(assets/js/app.js --bundle --target=es2017 --outdir=priv/static/assets --external:/fonts/* --external:/images/*),
~w(assets/js/app.js --bundle --target=es2017 --outdir=priv/static/assets --external:/fonts/* --external:/images/* --alias:backpex=/opt/app),
cd: Path.expand("..", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
Expand Down
3 changes: 2 additions & 1 deletion demo/lib/demo_web/live/category_live.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ defmodule DemoWeb.CategoryLive do
name: Demo.PubSub,
topic: "categories",
event_prefix: "category_"
]
],
init_order: %{by: :name, direction: :asc}

@impl Backpex.LiveResource
def singular_name, do: "Category"
Expand Down
1 change: 0 additions & 1 deletion demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
},
"devDependencies": {
"@sentry/browser": "8.54.0",
"alpinejs": "3.14.8",
"npm-run-all2": "7.0.2",
"postcss": "8.5.1",
"standard": "17.1.2",
Expand Down
Loading