|
| 1 | +--- |
| 2 | +export type CheckBoxOption = { |
| 3 | + /** Unique id used for input id + label for */ |
| 4 | + id: string; |
| 5 | + /** Text shown next to the checkbox */ |
| 6 | + label: string; |
| 7 | + /** Optional default checked state */ |
| 8 | + checked?: boolean; |
| 9 | + /** Optional disabled state */ |
| 10 | + disabled?: boolean; |
| 11 | + /** Optional hint text shown under the label */ |
| 12 | + description?: string; |
| 13 | +}; |
| 14 | +
|
| 15 | +export interface Props { |
| 16 | + /** Fieldset legend (group label) */ |
| 17 | + legend: string; |
| 18 | + /** Name attribute for the checkbox inputs */ |
| 19 | + name: string; |
| 20 | + /** Checkbox options */ |
| 21 | + options: CheckBoxOption[]; |
| 22 | + /** Optional help text for the whole group */ |
| 23 | + helpText?: string; |
| 24 | + /** Optional error text for the whole group */ |
| 25 | + errorText?: string; |
| 26 | + /** Optional additional classes */ |
| 27 | + className?: string; |
| 28 | +} |
| 29 | +
|
| 30 | +const { legend, name, options, helpText, errorText, className } = Astro.props; |
| 31 | +
|
| 32 | +const helpId = helpText ? `${name}-help` : undefined; |
| 33 | +const errorId = errorText ? `${name}-error` : undefined; |
| 34 | +const describedBy = [errorId, helpId].filter(Boolean).join(" ") || undefined; |
| 35 | +--- |
| 36 | + |
| 37 | +<fieldset class={className} aria-describedby={describedBy}> |
| 38 | + <legend>{legend}</legend> |
| 39 | + |
| 40 | + {errorText && ( |
| 41 | + <p id={errorId} role="alert"> |
| 42 | + {errorText} |
| 43 | + </p> |
| 44 | + )} |
| 45 | + |
| 46 | + {helpText && <p id={helpId}>{helpText}</p>} |
| 47 | + |
| 48 | + {options.map((opt) => { |
| 49 | + const descId = opt.description ? `${opt.id}-desc` : undefined; |
| 50 | + const inputDescribedBy = [descId].filter(Boolean).join(" ") || undefined; |
| 51 | + |
| 52 | + return ( |
| 53 | + <div> |
| 54 | + <input |
| 55 | + type="checkbox" |
| 56 | + id={opt.id} |
| 57 | + name={name} |
| 58 | + checked={opt.checked} |
| 59 | + disabled={opt.disabled} |
| 60 | + aria-describedby={inputDescribedBy} |
| 61 | + /> |
| 62 | + <label for={opt.id}>{opt.label}</label> |
| 63 | + {opt.description && <div id={descId}>{opt.description}</div>} |
| 64 | + </div> |
| 65 | + ); |
| 66 | + })} |
| 67 | +</fieldset> |
0 commit comments