44 lines
1.4 KiB
JavaScript
44 lines
1.4 KiB
JavaScript
import { Controller } from '@hotwired/stimulus'
|
|
|
|
export default class extends Controller {
|
|
// the default of one row keeps every existing textarea exactly as it was, fields that
|
|
// are written into at length can ask for a taller floor to grow from
|
|
static values = { minRows: { type: Number, default: 1 } }
|
|
|
|
connect() {
|
|
this.element.rows = this.minRowsValue
|
|
this.minHeight = null
|
|
|
|
// A textarea inside a hidden block (a questionnaire follow-up, a modal tab) has no layout
|
|
// yet: measured now, its floor would be 0 and it would collapse to nothing. It is measured
|
|
// once it is rendered instead - ResizeObserver reports the switch from display: none.
|
|
this.observer = new ResizeObserver(() => this.measure())
|
|
this.observer.observe(this.element)
|
|
this.measure()
|
|
}
|
|
|
|
disconnect() {
|
|
this.observer.disconnect()
|
|
}
|
|
|
|
measure() {
|
|
if (null !== this.minHeight || 0 === this.element.getClientRects().length) {
|
|
return
|
|
}
|
|
|
|
this.minHeight = this.element.scrollHeight
|
|
this.observer.disconnect()
|
|
this.resize()
|
|
}
|
|
|
|
resize() {
|
|
// until it has been rendered there is nothing to size; its rows keep it at the floor
|
|
if (null === this.minHeight) {
|
|
return
|
|
}
|
|
|
|
this.element.style.height = 'auto'
|
|
this.element.style.height = `${Math.max(this.element.scrollHeight, this.minHeight)}px`
|
|
}
|
|
}
|