עיצוב של רכיב הורה באמצעות ‎ :has()‎

תכונות אינטרנט: ‎:user-valid ו-‎ :user-invalid

הבעיה

במקרים רבים, מצב שגיאה דורש עיצוב של רכיבים מחוץ לשדה הקלט עצמו. לדוגמה, שינוי הצבע של הגבול של רכיב ההורה fieldset, הדגשת ה-<label> או הצגת סמל שגיאה גלובלי בכותרת הכרטיס. בעבר, כדי להחליף בין מחלקות ברכיבי הורה היה צריך להשתמש ב-JavaScript.

הפתרון

כשמשלבים את :has() עם :user-invalid, אפשר להגדיר באופן הצהרתי את הסגנון של כל רכיב אב על סמך מצב התקינות של רכיב צאצא ספציפי. כך כל הלוגיקה של התצוגה נשמרת ב-CSS.

אסטרטגיית הטמעה

  1. בורר: משתמשים ב-.parent:has(:user-invalid) כדי לטרגט את מאגר התגים.
  2. היקף: חשוב להיות ספציפיים כדי למנוע בעיות בביצועים. מטרגטים את .field-group במקום את body.
  3. חלופה: נדרש JS כדי להחליף מחלקות בהורה אם אין תמיכה ב-:has().

מדריך הטמעה

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. כדי לסנכרן את aria-invalid עם המצב החזותי, מוסיפים את קוד ה-JavaScript הבא:
// 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);
});