form-control.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { html } from 'lit';
  2. import { classMap } from 'lit-html/directives/class-map';
  3. import { ifDefined } from 'lit-html/directives/if-defined';
  4. export const renderFormControl = (props, input) => {
  5. const hasLabel = props.label ? true : !!props.hasLabelSlot;
  6. const hasHelpText = props.helpText ? true : !!props.hasHelpTextSlot;
  7. return html `
  8. <div
  9. part="form-control"
  10. class=${classMap({
  11. 'form-control': true,
  12. 'form-control--small': props.size === 'small',
  13. 'form-control--medium': props.size === 'medium',
  14. 'form-control--large': props.size === 'large',
  15. 'form-control--has-label': hasLabel,
  16. 'form-control--has-help-text': hasHelpText
  17. })}
  18. >
  19. <label
  20. part="label"
  21. id=${ifDefined(props.labelId)}
  22. class="form-control__label"
  23. for=${props.inputId}
  24. aria-hidden=${hasLabel ? 'false' : 'true'}
  25. @click=${(event) => (props.onLabelClick ? props.onLabelClick(event) : null)}
  26. >
  27. <slot name="label">${props.label}</slot>
  28. </label>
  29. <div class="form-control__input">${html `${input}`}</div>
  30. <div
  31. part="help-text"
  32. id=${ifDefined(props.helpTextId)}
  33. class="form-control__help-text"
  34. aria-hidden=${hasHelpText ? 'false' : 'true'}
  35. >
  36. <slot name="help-text">${props.helpText}</slot>
  37. </div>
  38. </div>
  39. `;
  40. };
  41. export function getLabelledBy(props) {
  42. const labelledBy = [
  43. props.label || props.hasLabelSlot ? props.labelId : '',
  44. props.helpText || props.hasHelpTextSlot ? props.helpTextId : ''
  45. ].filter(val => val);
  46. return labelledBy.join(' ') || undefined;
  47. }