Files
tabler/shared/ui/Colorpicker.astro
T

52 lines
1.9 KiB
Plaintext

---
import site from '@data/site.json'
import CaptureScript from '../components/CaptureScript.astro'
interface Props {
value?: string
id?: string | number
format?: string | false
class?: string
/** Accessible name for the input; falls back to a generic label when the caller doesn't wrap this in a labelled FormGroup */
ariaLabel?: string
}
const { value, id = 'default', format = false, class: className, ariaLabel } = Astro.props
const alpha = false
const colors = site.colors as Record<string, { prop: string }>
const swatchProps = Object.values(colors).map((color) => color.prop)
const colorpickerId = `colorpicker-${id}`
const colorpickerSelector = `#colorpicker-${id}`
---
<input type="text" class={`form-control d-block${className ? ` ${className}` : ''}`} id={colorpickerId} value={value} aria-label={ariaLabel ?? 'Color value'} />
<CaptureScript>
<!-- BEGIN COLORPICKER -->
<script is:inline define:vars={{ colorpickerId, colorpickerSelector, alpha, format, swatchProps }}>
function initColorpicker() {
window.tabler_colorpicker ??= {}
const swatches = swatchProps.map((prop) => window.getComputedStyle(document.body).getPropertyValue(prop))
if (window.Coloris) {
// `el` can only be configured globally, but Coloris.setInstance() scopes the rest
// (alpha, format, swatches, ...) to this selector so multiple pickers with
// different options don't clobber each other's settings.
Coloris({ el: colorpickerSelector })
Coloris.setInstance(colorpickerSelector, {
selectInput: false,
alpha,
...(format ? { format } : {}),
swatches,
})
window.tabler_colorpicker[colorpickerId] = colorpickerSelector
}
}
document.readyState !== 'loading' ? initColorpicker() : document.addEventListener('DOMContentLoaded', initColorpicker, { once: true })
</script>
<!-- END COLORPICKER -->
</CaptureScript>