:has()를 사용하여 상위 요소 스타일 지정

문제

오류 상태에서는 입력 자체 외부의 요소에 스타일을 지정해야 하는 경우가 많습니다. 예를 들어 상위 fieldset 테두리의 색상을 변경하거나, <label>를 강조 표시하거나, 카드 헤더에 전역 오류 아이콘을 표시해야 할 수 있습니다. 이전에는 상위 요소에서 클래스를 전환하기 위해 JavaScript가 필요했습니다.

해결 방법

:has()를 :user-invalid와 결합하면 특정 하위 요소의 유효성 상태를 기반으로 모든 상위 요소의 스타일을 선언적으로 지정할 수 있습니다. 이렇게 하면 모든 프레젠테이션 로직이 CSS에 유지됩니다.

구현 전략

  1. 선택기: .parent:has(:user-invalid)를 사용하여 컨테이너를 타겟팅합니다.
  2. 범위: 성능 문제를 방지하기 위해 구체적으로 지정합니다. body 대신 .field-group를 타겟팅합니다.
  3. 대체: :has()가 지원되지 않는 경우 상위 요소에서 클래스를 전환하려면 JS가 필요합니다.

구현 가이드

1. HTML 구조

<form>
  <div class="card-section">
    <div class="header">
      <h3>Profile Settings</h3>
      <span class="status-icon"></span>
    </div>

    <div class="field">
      <label for="username">Username</label>
      <input type="text" id="username" required>
    </div>
  </div>
</form>

2. CSS

/* Default State */
.card-section {
  border: 1px solid #ccc;
  border-left: 4px solid #ccc;
}

/*
  Parent Styling Logic:
  If the card contains ANY user-invalid input, turn the whole card's edge red.
*/
.card-section:has(:user-invalid) {
  border-left-color: #d93025;
  background-color: #fff8f8;
}

/* Change the icon too */
.card-section:has(:user-invalid) .status-icon::after {
  content: "⚠️";
}

대체 및 브라우저 지원

대체 CSS

상위 요소에 .has-error 클래스를 사용하여 :has() 동작을 모방합니다.

/* Native */
.card-section:has(:user-invalid) {
  border-left-color: #d93025;
}

/* Fallback */
.card-section.has-error-fallback {
  border-left-color: #d93025;
}

JavaScript 대체

WeakMap를 사용하여 상호작용 상태를 추적하는 재사용 가능한 유틸리티를 사용합니다. 이렇게 하면 '더러운' 클래스나 데이터 속성으로 DOM을 오염시키는 것을 방지할 수 있습니다.

const UserInvalidFallback = (() => {
  const dirtyState = new WeakMap();

  const updateState = (input) => {
    const isValid = input.checkValidity();

    // Update both visual and ARIA state
    input.classList.toggle('user-invalid-fallback', !isValid);
    input.classList.toggle('user-valid-fallback', isValid);

    if (!isValid) {
      input.setAttribute('aria-invalid', 'true');
    } else {
      input.removeAttribute('aria-invalid');
    }
  };

  const handleEvent = (event) => {
    const input = event.target;

    if (event.type === 'reset') {
      const controls = input.elements || [];
      for (const control of controls) {
        dirtyState.delete(control);
        control.classList.remove('user-invalid-fallback');
        control.classList.remove('user-valid-fallback');
        control.removeAttribute('aria-invalid');
      }
      return;
    }

    if (!input.checkValidity) return;

    if (event.type === 'input' || event.type === 'change') {
      const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
      state.hasInteracted = true;
      dirtyState.set(input, state);
      if (state.hasBlurred) {
        updateState(input);
      }
    } else if (event.type === 'blur') {
      const state = dirtyState.get(input) || { hasInteracted: false, hasBlurred: false };
      state.hasBlurred = true;
      dirtyState.set(input, state);
      if (state.hasInteracted) {
        updateState(input);
      }
    }
  };

  const init = (root = document) => {
    if (CSS.supports('selector(:user-invalid)')) return;

    root.addEventListener('blur', handleEvent, true); // Capture phase
    root.addEventListener('input', handleEvent);
    root.addEventListener('change', handleEvent);
    root.addEventListener('reset', handleEvent, true); // Capture resets
  };

  return { init };
})();

// Initialize for a specific form
const form = document.querySelector('#demo-form');
UserInvalidFallback.init(form);
// 1. Initialize the generic fallback
const form = document.querySelector('#demo-form');
UserInvalidFallback.init(form);

// 2. Add specialized "parent styling" logic (Separate from fallback)
// Listen for changes to form validity after interaction
form.addEventListener('blur', (e) => {
  if (!e.target.matches('input, select, textarea')) return;

  // Find the container we want to style (sync with CSS)
  const container = e.target.closest('.card-section');
  if (!container) return;

  // Check if ANY fallbacked input in this container is invalid
  const hasError = container.querySelector('.user-invalid-fallback');
  container.classList.toggle('has-error-fallback', !!hasError);
}, true); // Capture phase to ensure we run after the fallback's blur listener

// Also handle input events for immediate cleanup
form.addEventListener('input', (e) => {
  const container = e.target.closest('.card-section');
  if (container) {
    const hasError = container.querySelector('.user-invalid-fallback');
    container.classList.toggle('has-error-fallback', !!hasError);
  }
});

// Handle form resets
form.addEventListener('reset', () => {
  form.querySelectorAll('.has-error-fallback').forEach(el => {
    el.classList.remove('has-error-fallback');
  });
});

기타 고려사항

  1. 접근성: 네이티브 :user-invalid는 ARIA 속성과 자동으로 동기화되지 않습니다. 다음 JavaScript를 추가하여 aria-invalid를 시각적 상태와 동기화합니다.
// Sync aria-invalid with the CSS :user-invalid state
const syncAria = (el) => {
  el.setAttribute?.('aria-invalid', el.matches(':user-invalid') ? 'true' : 'false');
};

// Update on blur (to show error) and input (to clear it)
document.addEventListener('blur', (e) => syncAria(e.target), true);
document.addEventListener('input', (e) => {
  if (e.target.hasAttribute('aria-invalid')) syncAria(e.target);
});