forked from fixin.me/fixin.me
Migrate all inline JS to Stimulus controllers
Add stimulus-rails gem and wire up 7 controllers: - measurements_view_controller: view toggle (compact/wide) via localStorage - measurements_controller: grouped rows MutationObserver - charts_controller: Plotly chart rendering - form_controller: keyboard shortcuts (Escape/Enter) and submit validation - details_controller: quantity picker state, focusout close, MutationObserver - readout_unit_controller: default unit button enable/disable + PATCH submission - drag_controller: drag-and-drop for quantity reparenting and unit rebasing Remove all inline onclick/onkeydown/ondrag*/onsubmit handlers from templates. Remove all window.* global exports from application.js. Remove bare <script> block from measurements/_form.html.erb. Remove turbo:load listeners for behavior now in controller connect(). application.js now only contains: Turbo Stream custom action definitions and the showPage visibility listener. Document Stimulus conventions in CLAUDE.md. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
7
app/javascript/controllers/application.js
Normal file
7
app/javascript/controllers/application.js
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Application } from "@hotwired/stimulus"
|
||||
|
||||
const application = Application.start()
|
||||
application.debug = false
|
||||
window.Stimulus = application
|
||||
|
||||
export { application }
|
||||
45
app/javascript/controllers/charts_controller.js
Normal file
45
app/javascript/controllers/charts_controller.js
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ["container", "data"]
|
||||
|
||||
connect() {
|
||||
const readouts = JSON.parse(this.dataTarget.textContent)
|
||||
if (readouts.length === 0) return
|
||||
|
||||
const quantities = new Map()
|
||||
readouts.forEach(r => {
|
||||
if (!r.takenAt) return
|
||||
if (!quantities.has(r.quantityId)) {
|
||||
quantities.set(r.quantityId, { name: r.quantityName, unit: r.unit, x: [], y: [] })
|
||||
}
|
||||
const q = quantities.get(r.quantityId)
|
||||
q.x.push(r.takenAt)
|
||||
q.y.push(r.value)
|
||||
})
|
||||
|
||||
const traces = []
|
||||
quantities.forEach(q => {
|
||||
traces.push({
|
||||
x: q.x, y: q.y,
|
||||
mode: 'lines+markers', type: 'scatter',
|
||||
name: q.name + ' (' + q.unit + ')',
|
||||
marker: { size: 5 }
|
||||
})
|
||||
})
|
||||
|
||||
const div = document.createElement('div')
|
||||
div.className = 'chart-panel'
|
||||
this.containerTarget.appendChild(div)
|
||||
|
||||
Plotly.newPlot(div, traces, {
|
||||
xaxis: { type: 'date', tickformat: '%Y-%m-%d %H:%M' },
|
||||
yaxis: {},
|
||||
margin: { t: 20, r: 20, b: 80, l: 60 },
|
||||
paper_bgcolor: 'transparent',
|
||||
plot_bgcolor: 'transparent',
|
||||
font: { family: 'system-ui' },
|
||||
legend: { orientation: 'h', y: -0.25 }
|
||||
}, { responsive: true, displayModeBar: false })
|
||||
}
|
||||
}
|
||||
55
app/javascript/controllers/details_controller.js
Normal file
55
app/javascript/controllers/details_controller.js
Normal file
@@ -0,0 +1,55 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ["countLabel", "submitButton", "list"]
|
||||
|
||||
connect() {
|
||||
this._observer = new MutationObserver(() => {
|
||||
this.element.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
})
|
||||
this._observer.observe(this.listTarget, { subtree: true, attributeFilter: ['disabled'] })
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this._observer?.disconnect()
|
||||
}
|
||||
|
||||
change() {
|
||||
const count = this.element.querySelectorAll('input:checked:not([disabled])').length
|
||||
if (count > 0) {
|
||||
this.countLabelTarget.textContent = count + ' selected'
|
||||
Turbo.StreamElement.prototype.enableElement(this.submitButtonTarget)
|
||||
} else {
|
||||
this.countLabelTarget.textContent = this.countLabelTarget.dataset.prompt
|
||||
Turbo.StreamElement.prototype.disableElement(this.submitButtonTarget)
|
||||
}
|
||||
}
|
||||
|
||||
close(event) {
|
||||
if (!event.relatedTarget ||
|
||||
event.relatedTarget.closest("details") != this.element) {
|
||||
this.element.removeAttribute("open")
|
||||
}
|
||||
}
|
||||
|
||||
processKey(event) {
|
||||
switch (event.key) {
|
||||
case "Escape":
|
||||
if (this.element.hasAttribute("open")) {
|
||||
this.element.removeAttribute("open")
|
||||
event.stopPropagation()
|
||||
}
|
||||
break
|
||||
case "Enter": {
|
||||
const button = this.element.querySelector("button:not([disabled])")
|
||||
if (button) {
|
||||
button.click()
|
||||
event.target.blur()
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
62
app/javascript/controllers/drag_controller.js
Normal file
62
app/javascript/controllers/drag_controller.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
// Shared across all instances — drag spans multiple elements
|
||||
let lastEnterTime
|
||||
|
||||
export default class extends Controller {
|
||||
static values = {
|
||||
dragPath: String,
|
||||
dropId: String,
|
||||
dropIdParam: String
|
||||
}
|
||||
|
||||
start(event) {
|
||||
lastEnterTime = event.timeStamp
|
||||
this.element.closest("table").querySelectorAll("thead tr").forEach(tr => {
|
||||
tr.toggleAttribute("hidden")
|
||||
})
|
||||
event.dataTransfer.setData("text/plain", this.dragPathValue)
|
||||
const rect = this.element.getBoundingClientRect()
|
||||
event.dataTransfer.setDragImage(this.element, event.x - rect.left, event.y - rect.top)
|
||||
event.dataTransfer.dropEffect = "move"
|
||||
}
|
||||
|
||||
end(event) {
|
||||
this.leave(event)
|
||||
this.element.closest("table").querySelectorAll("thead tr").forEach(tr => {
|
||||
tr.toggleAttribute("hidden")
|
||||
})
|
||||
}
|
||||
|
||||
enter(event) {
|
||||
this.leave(event)
|
||||
lastEnterTime = event.timeStamp
|
||||
document.getElementById(this.dropIdValue)?.classList.add("dropzone")
|
||||
}
|
||||
|
||||
over(event) {
|
||||
event.preventDefault()
|
||||
}
|
||||
|
||||
leave(event) {
|
||||
if (event.timeStamp <= lastEnterTime) return
|
||||
this.element.closest("table").querySelectorAll(".dropzone").forEach(tr => {
|
||||
tr.classList.remove("dropzone")
|
||||
})
|
||||
}
|
||||
|
||||
drop(event) {
|
||||
event.preventDefault()
|
||||
const id = this.dropIdValue.split("_").pop()
|
||||
const form = document.createElement('form')
|
||||
form.action = event.dataTransfer.getData("text/plain")
|
||||
form.method = 'post'
|
||||
form.dataset.turboStream = 'true'
|
||||
const input = document.createElement('input')
|
||||
input.type = 'hidden'; input.name = this.dropIdParamValue; input.value = id
|
||||
form.appendChild(input)
|
||||
form.addEventListener('turbo:submit-end', () => form.remove())
|
||||
document.body.appendChild(form)
|
||||
form.requestSubmit()
|
||||
}
|
||||
}
|
||||
25
app/javascript/controllers/form_controller.js
Normal file
25
app/javascript/controllers/form_controller.js
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
export default class extends Controller {
|
||||
processKey(event) {
|
||||
switch (event.key) {
|
||||
case "Escape":
|
||||
this.element.querySelector("a[name=cancel]").click()
|
||||
break
|
||||
case "Enter":
|
||||
this.element.querySelector("button[name=button]").click()
|
||||
event.preventDefault()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
validate(event) {
|
||||
const id = event.submitter?.getAttribute("data-validate")
|
||||
if (!id) return
|
||||
const input = document.getElementById(id)
|
||||
if (!input.checkValidity()) {
|
||||
input.reportValidity()
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
}
|
||||
3
app/javascript/controllers/index.js
Normal file
3
app/javascript/controllers/index.js
Normal file
@@ -0,0 +1,3 @@
|
||||
import { application } from "controllers/application"
|
||||
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
|
||||
eagerLoadControllersFrom("controllers", application)
|
||||
29
app/javascript/controllers/measurements_controller.js
Normal file
29
app/javascript/controllers/measurements_controller.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ["tbody"]
|
||||
|
||||
connect() {
|
||||
this.#group()
|
||||
this._observer = new MutationObserver(() => this.#group())
|
||||
this._observer.observe(this.tbodyTarget, {
|
||||
childList: true, subtree: true,
|
||||
attributes: true, attributeFilter: ['style']
|
||||
})
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this._observer?.disconnect()
|
||||
}
|
||||
|
||||
#group() {
|
||||
let prevTakenAt = null
|
||||
Array.from(this.tbodyTarget.querySelectorAll('tr[data-taken-at]'))
|
||||
.filter(row => row.style.display !== 'none')
|
||||
.forEach(row => {
|
||||
const takenAt = row.dataset.takenAt
|
||||
row.classList.toggle('grouped', takenAt !== null && takenAt === prevTakenAt)
|
||||
prevTakenAt = takenAt
|
||||
})
|
||||
}
|
||||
}
|
||||
17
app/javascript/controllers/measurements_view_controller.js
Normal file
17
app/javascript/controllers/measurements_view_controller.js
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
export default class extends Controller {
|
||||
connect() {
|
||||
document.body.dataset.measurementsView = this.#get()
|
||||
}
|
||||
|
||||
set(event) {
|
||||
const view = event.params.name
|
||||
localStorage.setItem('measurements-view', view)
|
||||
document.body.dataset.measurementsView = view
|
||||
}
|
||||
|
||||
#get() {
|
||||
return localStorage.getItem('measurements-view') || 'compact'
|
||||
}
|
||||
}
|
||||
36
app/javascript/controllers/readout_unit_controller.js
Normal file
36
app/javascript/controllers/readout_unit_controller.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ["select", "button"]
|
||||
|
||||
unitChanged() {
|
||||
if (this.selectTarget.value && this.selectTarget.value !== this.selectTarget.dataset.defaultUnitId) {
|
||||
Turbo.StreamElement.prototype.enableElement(this.buttonTarget)
|
||||
} else {
|
||||
Turbo.StreamElement.prototype.disableElement(this.buttonTarget)
|
||||
}
|
||||
}
|
||||
|
||||
setDefault() {
|
||||
const select = this.selectTarget
|
||||
const form = document.createElement('form')
|
||||
form.action = this.buttonTarget.dataset.path
|
||||
form.method = 'post'
|
||||
form.dataset.turboStream = 'true'
|
||||
const methodInput = document.createElement('input')
|
||||
methodInput.type = 'hidden'; methodInput.name = '_method'; methodInput.value = 'patch'
|
||||
const unitInput = document.createElement('input')
|
||||
unitInput.type = 'hidden'; unitInput.name = 'quantity[default_unit_id]'; unitInput.value = select.value
|
||||
form.appendChild(methodInput)
|
||||
form.appendChild(unitInput)
|
||||
form.addEventListener('turbo:submit-end', event => {
|
||||
if (event.detail.success) {
|
||||
select.dataset.defaultUnitId = select.value
|
||||
this.unitChanged()
|
||||
}
|
||||
form.remove()
|
||||
})
|
||||
document.body.appendChild(form)
|
||||
form.requestSubmit()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user