من الصفر إلى الاحتراف · المختبرEnglishGitHub

الفصل 16

صفحات يصل إليها الجميع

4 مثالاً · 3 مشروعاً · 5 تمارين

ستتعلم في هذا الفصل أن

  • تشرح ما الوصول (accessibility) ومن يستفيد منه
  • تستخدم عنصر HTML المناسب، وهي أهم مهارة في الوصول
  • تصنع صفحات تعمل بلوحة المفاتيح، بتركيز ظاهر ورابط تخطٍّ
  • تكتب نماذج وصوراً وألواناً يصل إليها الجميع، وتقيس التباين بنفسك
  • تفحص الصفحة بأدوات المتصفح نفسه

الأمثلة

16.2 العنصر المناسب للمهمة

انظر إلى هذين الزرين:

buttons.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>أزرار يصل إليها الجميع</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; }
      .fake, button { display: inline-block; padding: 10px 20px; border: 0; border-radius: 999px;
        color: white; background: #4338ca; font: inherit; cursor: pointer; margin: 4px; }
    </style>
  </head>
  <body>
    <h1>زرّان</h1>
    <!-- سيئ: يبدو زراً لكنه صندوق فقط -->
    <div class="fake" onclick="alert('Hi')">أنا div</div>
    <!-- جيد: زر حقيقي -->
    <button type="button" onclick="alert('Hi')">أنا زر</button>
    <p>يبدوان متشابهين، لكن واحداً منهما فقط يعمل بلوحة المفاتيح وقارئ الشاشة.</p>
  </body>
</html>
buttons.html560px
الشكل 16.1: يبدوان متشابهين، وليسا كذلك.

16.3 اختبار لوحة المفاتيح

أبعد الفأرة وجرّب استخدام صفحتك بلوحة المفاتيح وحدها. Tab تتقدم بين الروابط والأزرار والحقول، وShift + Tab ترجع، وEnter تتبع الروابط وتضغط الأزرار، وSpace تضغط الأزرار وتعلّم المربعات. ويجب أن يصح أمران:

focus.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>أهلاً بك</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 0; }
      .skip { position: absolute; inset-inline-start: 8px; top: -60px; padding: 8px 14px;
        background: #1e1b2e; color: white; border-radius: 8px; }
      .skip:focus { top: 8px; }
      nav { display: flex; gap: 8px; padding: 56px 16px 16px; background: #eef2ff; }
      nav a { padding: 6px 14px; border-radius: 8px; color: #312e81; font-weight: 700; }
      a:focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      main { padding: 0 16px; }
      @media (prefers-reduced-motion: reduce) {
        * { animation: none !important; transition: none !important; }
      }
    </style>
  </head>
  <body>
    <a class="skip" href="#main">تخطَّ إلى المحتوى الرئيسي</a>
    <header>
      <nav aria-label="الرئيسية">
        <a href="#">الرئيسية</a>
        <a href="#">المشاريع</a>
        <a href="#">تواصل</a>
      </nav>
    </header>
    <main id="main">
      <h1>أهلاً بك</h1>
      <p>اضغط Tab للتنقل بين الروابط، والرابط المحدد عليه إطار واضح.</p>
    </main>
  </body>
</html>
focus.html560px
الشكل 16.2: بعد ضغط Tab مرة: يظهر رابط التخطي المخفي.
الشكل 16.3: بعد ضغطتين أخريين: على الرابط المحدد إطار سميك واضح.

16.5 نماذج يصل إليها الجميع

ولا تبدأ بـ «صورة لـ»؛ فقارئات الشاشة تقول أصلاً إنها صورة. صِف الغرض لا كل بكسل.

form.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>التسجيل</title>
    <style>
      body { font-family: system-ui, sans-serif; margin: 24px; max-width: 420px; }
      label { display: block; font-weight: 700; margin-top: 14px; }
      input { display: block; width: 100%; box-sizing: border-box; padding: 8px; font: inherit;
        border: 2px solid #5b5873; border-radius: 8px; }
      input[aria-invalid="true"] { border-color: #b91c1c; }
      .hint { color: #4a4760; margin: 4px 0 0; font-size: 0.9rem; }
      .error { color: #b91c1c; font-weight: 700; margin: 4px 0 0; }
      button { margin-top: 18px; padding: 10px 22px; border: 0; border-radius: 999px; color: white; background: #4338ca; font: inherit; }
    </style>
  </head>
  <body>
    <h1>أنشئ حساباً</h1>
    <form novalidate>
      <label for="email">البريد الإلكتروني</label>
      <input id="email" type="email" autocomplete="email"
             aria-describedby="email-hint email-error" aria-invalid="true" value="sara@">
      <p class="hint" id="email-hint">لن نشارك بريدك مع أحد أبداً.</p>
      <p class="error" id="email-error" role="alert">من فضلك اكتب بريداً إلكترونياً صحيحاً.</p>

      <label for="password">كلمة المرور</label>
      <input id="password" type="password" autocomplete="new-password">

      <button type="submit">أنشئ الحساب</button>
    </form>
  </body>
</html>
form.html560px
الشكل 16.4: حقل له تلميح ورسالة خطأ يدركهما الجميع.

16.6 اللون والتباين

تطلب WCAG نسبة تباين لا تقل عن 4.5 إلى 1 بين النص العادي وخلفيته، و3 إلى 1 للنص الكبير. والنسبة من 1 (اللون نفسه) إلى 21 (أسود على أبيض). ورأيت أدوات المطورين تعرضها في الفصل 6. والآن، تمريناً أخيراً على JavaScript، لنحسبها بأنفسنا بالمعادلة الرسمية:

contrast.js⤓ الملف
// نسبة التباين بين لونين بمعادلة WCAG
function luminance(hex) {
  const channels = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
  const linear = channels.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
  return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
}

function contrast(foreground, background) {
  const [a, b] = [luminance(foreground), luminance(background)].sort((x, y) => y - x);
  return (a + 0.05) / (b + 0.05);
}

const pairs = [
  ["#1e1b2e", "#ffffff"],
  ["#4338ca", "#ffffff"],
  ["#9ca3af", "#ffffff"],
  ["#ffffff", "#fbbf24"],
];

for (const [fg, bg] of pairs) {
  const ratio = contrast(fg, bg);
  const verdict = ratio >= 4.5 ? "ناجح" : "راسب";
  console.log(`${fg} / ${bg}: ${ratio.toFixed(2)} → ${verdict}`);
}
الناتج المسجَّل$ node contrast.js
#1e1b2e / #ffffff: 16.78 → ناجح
#4338ca / #ffffff: 7.90 → ناجح
#9ca3af / #ffffff: 2.54 → راسب
#ffffff / #fbbf24: 1.67 → راسب

المشاريع التطبيقية

مشروع 16.1 · سهل

أنقذ بطاقة الوصفة

تبدو هذه البطاقة جيدة، لكن مستخدم قارئ الشاشة، ومستخدم لوحة المفاتيح، ومن يقرأ تحت شمس قوية، سيعانون معها جميعاً. جِد خمس مشكلات وأصلحها.

ستتدرب على: الأزرار الحقيقية، والعناوين والمعالم، ونص alt، والتسميات، والتباين، وإطار التركيز الظاهر.

الخطوات
  1. العنوان div. اجعله h1 ليظهر في قائمة العناوين عند قارئ الشاشة.
  2. الصورة بلا alt. صِف ما يراه القارئ المبصر في جملة قصيرة.
  3. مربع البحث بنص إرشادي (placeholder) فقط، يختفي بمجرد الكتابة. أعطه <label> حقيقياً، وضعه في <form role="search">.
  4. «ابحث» و«احفظ الوصفة» عنصرا div: يتخطاهما Tab. حوّلهما إلى <button>.
  5. نص الوقت الرمادي (#c4c4c4 على الأبيض) تباينه نحو 1.7. اجعله أغمق، #4b5563، وتحقق من النسبة بسكربت القسم 16.6.
  6. غلّف الصفحة بـ header وmain وarticle، ثم اجرِ اختبار لوحة المفاتيح.

تلميح: معظم إصلاحات سهولة الوصول ليست عملاً إضافياً، بل هي العنصر الصحيح في HTML للمهمة، والذي كنت ستستخدمه أصلاً لو اعتنيت قليلاً.

الحل
recipe-before.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>وصفة</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      .card { max-width: 26em; background: white; border-radius: 16px; overflow: hidden; }
      .card img { width: 100%; display: block; }
      .body { padding: 16px; }
      .time { color: #c4c4c4; }
      .btn { display: inline-block; padding: 8px 18px; border-radius: 999px; color: white; background: #4338ca; }
    </style>
  </head>
  <body>
    <div class="title">شوربة العدس عند بِت</div>
    <input placeholder="ابحث في الوصفات"> <div class="btn">ابحث</div>
    <div class="card">
      <img src="soup.svg">
      <div class="body">
        <div class="time">جاهزة في 30 دقيقة · تكفي 4 أشخاص</div>
        <div class="btn" onclick="alert('Saved')">احفظ الوصفة</div>
      </div>
    </div>
  </body>
</html>
recipe-before.html640px
recipe.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>وصفة</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      .search { display: flex; gap: 8px; align-items: center; margin-bottom: 16px; flex-wrap: wrap; }
      .search input { font: inherit; padding: 7px 10px; border: 2px solid #6b7280; border-radius: 8px; }
      .card { max-width: 26em; background: white; border-radius: 16px; overflow: hidden; }
      .card img { width: 100%; display: block; }
      .body { padding: 16px; }
      .card h2 { margin: 0 0 4px; }
      .time { color: #4b5563; margin: 0 0 12px; }
      .secondary { background: #e0e7ff; color: #312e81; }
    </style>
  </head>
  <body>
    <header>
      <form class="search" role="search">
        <label for="q">ابحث في الوصفات</label>
        <input id="q" type="search">
        <button type="submit">ابحث</button>
      </form>
    </header>
    <main>
      <h1>شوربة العدس عند بِت</h1>
      <article class="card">
        <img src="soup.svg" alt="طبق شوربة عدس برتقالية وبجانبه ليمون">
        <div class="body">
          <p class="time">جاهزة في 30 دقيقة · تكفي 4 أشخاص</p>
          <button type="button">احفظ الوصفة</button>
          <button type="button" class="secondary">اطبع</button>
        </div>
      </article>
    </main>
  </body>
</html>
recipe.html560px
مشروع 16.1: البطاقة بعد الإصلاح، والتركيز على «احفظ الوصفة».

مشروع 16.2 · متوسط

نموذج يشرح أخطاءه

حين يخطئ الزائر، أخبره ما الخطأ، وأين هو، وكيف يصلحه، بطريقة تلاحظها العين وقارئ الشاشة معاً.

ستتدرب على: label وautocomplete وaria-describedby وaria-invalid وrole="alert"، ونقل التركيز بجافاسكربت.

الخطوات
  1. ابنِ النموذج بتسمية لكل حقل، وأضف novalidate ليعرض سكربتك الرسائل لا المتصفح. وحقل البريد يأخذ dir="ltr" فيُكتب العنوان بترتيبه الصحيح.
  2. تحت كل حقل أضف <p class="error"> فارغاً، واربطه بالحقل بـ aria-describedby، فيقرؤه قارئ الشاشة مع الحقل.
  3. احتفظ بالقواعد بيانات: مصفوفة من { id, message, ok }، وok دالة صغيرة تختبر القيمة.
  4. عند الإرسال افحص كل قاعدة. اكتب الرسالة، وضع aria-invalid="true" على كل حقل لا ينجح.
  5. املأ صندوق ملخص في الأعلى برابط لكل مشكلة، وأظهره، واستدعِ summary.focus(). ولأن فيه role="alert" يُعلَن فوراً.
  6. حين يصح كل شيء، أخفِ الملخص واعرض رسالة نجاح في عنصر role="status".

تلميح: لا تعتمد على اللون وحده في الأخطاء. فهنا للرسالة كلمات، ويتغير الإطار، ويكررها الملخص، فيعرف ما يفعل من لا يرى الأحمر.

الحل
join.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>انضم إلى النادي</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      form { max-width: 24em; display: flex; flex-direction: column; gap: 4px; }
      label { font-weight: 700; margin-top: 10px; }
      input { font: inherit; padding: 8px 10px; border: 2px solid #6b7280; border-radius: 8px; }
      input[aria-invalid="true"] { border-color: #b91c1c; }
      .hint { color: #4b5563; margin: 0; font-size: 0.9rem; }
      .error { color: #b91c1c; margin: 0; font-weight: 700; }
      .error:empty { display: none; }
      #summary { background: #fee2e2; border-inline-start: 5px solid #b91c1c; padding: 10px 14px; border-radius: 8px; max-width: 24em; }
      #summary[hidden] { display: none; }
      #summary ul { margin: 4px 0 0; }
      #summary a { color: #7f1d1d; }
      #done { color: #047857; font-weight: 700; }
      button { margin-top: 14px; align-self: flex-start; }
    </style>
  </head>
  <body>
    <h1>انضم إلى نادي البرمجة</h1>
    <div id="summary" role="alert" tabindex="-1" hidden></div>
    <form id="join" novalidate>
      <label for="name">الاسم الكامل</label>
      <input id="name" autocomplete="name" aria-describedby="name-error">
      <p class="error" id="name-error"></p>

      <label for="email">البريد الإلكتروني</label>
      <input id="email" type="email" autocomplete="email" dir="ltr" aria-describedby="email-hint email-error">
      <p class="hint" id="email-hint">سنستخدمه فقط لإرسال مواعيد اللقاءات.</p>
      <p class="error" id="email-error"></p>

      <button type="submit">انضم</button>
    </form>
    <p id="done" role="status"></p>
    <script src="join.js"></script>
  </body>
</html>
join.html560px
مشروع 16.2: بعد الإرسال باسم فارغ وبريد ناقص.
join.js⤓ الملف
const form = document.querySelector("#join");
const summary = document.querySelector("#summary");
const done = document.querySelector("#done");

const rules = [
  { id: "name", message: "اكتب اسمك الكامل.", ok: (value) => value.trim().length >= 2 },
  { id: "email", message: "اكتب بريداً صحيحاً مثل name@example.com", ok: (value) => /^\S+@\S+\.\S+$/.test(value) },
];

function showError(field, message) {
  const input = document.querySelector("#" + field);
  const error = document.querySelector("#" + field + "-error");
  error.textContent = message;
  input.setAttribute("aria-invalid", message ? "true" : "false");
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const problems = [];

  for (const rule of rules) {
    const value = document.querySelector("#" + rule.id).value;
    if (rule.ok(value)) {
      showError(rule.id, "");
    } else {
      showError(rule.id, rule.message);
      problems.push(rule);
    }
  }

  if (problems.length === 0) {
    summary.hidden = true;
    done.textContent = "أهلاً بك في النادي!";
    return;
  }

  const title = document.createElement("p");
  title.textContent = problems.length === 1 ? problems[0].message : "يُرجى تصحيح مشكلتين:";
  const list = document.createElement("ul");
  for (const problem of problems) {
    const link = document.createElement("a");
    link.href = "#" + problem.id;
    link.textContent = problem.message;
    const item = document.createElement("li");
    item.append(link);
    list.append(item);
  }
  summary.replaceChildren(title);
  if (problems.length > 1) summary.append(list);
  summary.hidden = false;
  summary.focus();
});

مشروع 16.3 · تحدٍّ

أسئلة شائعة سهلة الوصول

ابنِ أسئلة تفتح إجاباتها وتغلقها، وتخبر التقنيات المساعدة هل كل منها مفتوح.

ستتدرب على: الأزرار داخل العناوين، وaria-expanded وaria-controls، والخاصية hidden، وquerySelectorAll.

الخطوات
  1. لكل سؤال اكتب h2 فيه <button type="button" aria-expanded="false" aria-controls="answer-1">.
  2. تحته ضع الإجابة في <div id="answer-1" hidden>. وhidden تخفيها عن الجميع، بمن فيهم قارئ الشاشة.
  3. جِد كل الأزرار بـ querySelectorAll وأعطِ كلاً منها مستمعاً للضغط.
  4. عند الضغط اقرأ aria-expanded واقلبها، واجعل hidden للإجابة تتبعها.
  5. ارسم + و− بـ CSS من الخاصية نفسها: button[aria-expanded="true"]::after. فلا يمكن أن يخالف الشكل ما يقوله قارئ الشاشة.
  6. اختبره بلوحة المفاتيح وحدها: Tab إلى سؤال، ثم Enter أو المسافة، ثم Tab إلى داخل الإجابة المفتوحة.

تلميح: لأنك استخدمت أزراراً حقيقية، يعمل Enter والمسافة دون كود إضافي. ولو استخدمت div بمستمع ضغط لاحتجت عشرات الأسطر لتقلّد ما يعطيك <button> مجاناً.

الحل
faq.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>أسئلة شائعة</title>
    <style>
      *, *::before, *::after { box-sizing: border-box; }
      body { margin: 0; padding: 24px; font-family: system-ui, "Segoe UI", Tahoma, sans-serif; background: #f5f5fb; color: #1e1b2e; line-height: 1.5; }
      h1 { color: #4338ca; margin-top: 0; }
      button { font: inherit; padding: 8px 18px; border: 0; border-radius: 999px; color: white; background: #4338ca; cursor: pointer; }
      :focus-visible { outline: 3px solid #db2777; outline-offset: 3px; }
      .faq { max-width: 30em; }
      .faq h2 { margin: 0 0 8px; font-size: 1.05rem; }
      .faq h2 button { width: 100%; text-align: start; border-radius: 12px; padding: 12px 16px; display: flex; justify-content: space-between; gap: 12px; }
      .faq h2 button::after { content: "+"; font-weight: 700; }
      .faq h2 button[aria-expanded="true"]::after { content: "−"; }
      .answer { background: white; border-radius: 12px; padding: 4px 16px; margin: -4px 0 12px; }
    </style>
  </head>
  <body>
    <h1>أسئلة عن الدورة</h1>
    <div class="faq">
      <h2>
        <button type="button" aria-expanded="false" aria-controls="answer-1">هل أحتاج إلى تثبيت شيء؟</button>
      </h2>
      <div id="answer-1" class="answer" hidden>
        <p>متصفح وVS Code فقط، وكلاهما مجاني.</p>
      </div>
      <h2>
        <button type="button" aria-expanded="false" aria-controls="answer-2">كم يستغرق كل فصل؟</button>
      </h2>
      <div id="answer-2" class="answer" hidden>
        <p>ينهي معظم القراء الفصل في أمسيتين أو ثلاث، مع المشاريع.</p>
      </div>
      <h2>
        <button type="button" aria-expanded="false" aria-controls="answer-3">ماذا أفعل إن توقفت؟</button>
      </h2>
      <div id="answer-3" class="answer" hidden>
        <p>أعد قراءة التلميح، واتبع طريقة تصحيح الأخطاء من الفصل 14، ثم اسأل المجتمع.</p>
      </div>
    </div>
    <script src="faq.js"></script>
  </body>
</html>
faq.html560px
مشروع 16.3: الأسئلة والإجابة الثانية مفتوحة.
faq.js⤓ الملف
const buttons = document.querySelectorAll(".faq button");

for (const button of buttons) {
  button.addEventListener("click", () => {
    const open = button.getAttribute("aria-expanded") === "true";
    const answer = document.querySelector("#" + button.getAttribute("aria-controls"));

    button.setAttribute("aria-expanded", String(!open));
    answer.hidden = open;
  });
}
+ 1 ملفات
soup.svg⤓ الملف

التمارين

التمرين 16.1 · سهل

استخدم صفحتك التعريفية بلوحة المفاتيح وحدها. هل تصل إلى كل رابط؟ هل ترى دائماً مكان التركيز؟ أصلح ما تجده.
جواب الكتاب المختصر
إصلاحات معتادة: استبدال عناصر div القابلة للنقر بأزرار أو روابط، وإضافة تنسيق :focus-visible ظاهر.
اعرض الحل
profile.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../../ch07/examples/style.css">
    <link rel="stylesheet" href="keyboard.css">
    <title>عن سارة</title>
  </head>
  <body>
    <header>
      <img src="../../../ch07/examples/bit.svg" alt="صورة سارة الرمزية: روبوت بنفسجي مبتسم" width="90" height="105">
      <h1>سارة خان</h1>
      <p>مطورة ويب مبتدئة من الإسكندرية</p>
      <nav>
        <a href="#about">عني</a> |
        <a href="#skills">مهاراتي</a> |
        <a href="#contact">تواصل</a>
      </nav>
    </header>

    <main>
      <section id="about">
        <h2>عني</h2>
        <p>بدأت تعلم البرمجة هذا العام مع كتاب <em>البرمجة من الصفر</em>، وأحب بناء أدوات صغيرة تجعل الحياة أسهل.</p>
      </section>

      <section id="skills">
        <h2>مهارات أتعلمها</h2>
        <ul>
          <li>HTML</li>
          <li>CSS</li>
          <li>JavaScript</li>
        </ul>
      </section>

      <section id="contact">
        <h2>تواصل معي</h2>
        <p>راسلني على <a href="mailto:sara@example.com">sara@example.com</a>.</p>
      </section>
    </main>

    <footer>
      <p>بنتها سارة بـ HTML وCSS.</p>
    </footer>
  </body>
</html>
profile.html640px
keyboard.css⤓ الملف
/* ما وجده اختبار لوحة المفاتيح في صفحة الفصل 7:
   1. كل رابط يُوصل إليه بـ Tab: إنها روابط <a href> حقيقية، لا عناصر div قابلة للنقر. جيد.
   2. التركيز يصعب رؤيته على أزرار القائمة البيضاء فوق الرأس البنفسجي، وعلى الروابط الوردية في البطاقات.
   الإصلاح: إطار عريض يظهر فقط مع تركيز لوحة المفاتيح (:focus-visible)، بلون يبرز على الخلفيتين. */
a:focus-visible,
button:focus-visible {
  outline: 3px solid #f59e0b;
  outline-offset: 3px;
  border-radius: 4px;
}

nav a:focus-visible {
  border-radius: 999px;
}

التمرين 16.2 · سهل

أضف رابط تخطٍّ إلى صفحتك التعريفية.
جواب الكتاب المختصر
انسخ رابط التخطي وتنسيقه من focus.html، وأضف id="main" إلى <main>.
اعرض الحل
profile.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../../ch07/examples/style.css">
    <link rel="stylesheet" href="skip.css">
    <title>عن سارة</title>
  </head>
  <body>
    <!-- أول ما يصل إليه Tab: يقفز فوق الرأس والقائمة إلى المحتوى. -->
    <a class="skip" href="#main">تخطَّ إلى المحتوى الرئيسي</a>
    <header>
      <img src="../../../ch07/examples/bit.svg" alt="صورة سارة الرمزية: روبوت بنفسجي مبتسم" width="90" height="105">
      <h1>سارة خان</h1>
      <p>مطورة ويب مبتدئة من الإسكندرية</p>
      <nav>
        <a href="#about">عني</a> |
        <a href="#skills">مهاراتي</a> |
        <a href="#contact">تواصل</a>
      </nav>
    </header>

    <main id="main">
      <section id="about">
        <h2>عني</h2>
        <p>بدأت تعلم البرمجة هذا العام مع كتاب <em>البرمجة من الصفر</em>، وأحب بناء أدوات صغيرة تجعل الحياة أسهل.</p>
      </section>

      <section id="skills">
        <h2>مهارات أتعلمها</h2>
        <ul>
          <li>HTML</li>
          <li>CSS</li>
          <li>JavaScript</li>
        </ul>
      </section>

      <section id="contact">
        <h2>تواصل معي</h2>
        <p>راسلني على <a href="mailto:sara@example.com">sara@example.com</a>.</p>
      </section>
    </main>

    <footer>
      <p>بنتها سارة بـ HTML وCSS.</p>
    </footer>
  </body>
</html>
profile.html640px
skip.css⤓ الملف
/* من focus.html: مخفي فوق الصفحة حتى يحصل على التركيز. */
.skip {
  position: absolute;
  inset-inline-start: 8px;
  top: -60px;
  padding: 8px 14px;
  background: #1e1b2e;
  color: white;
  border-radius: 8px;
  z-index: 10;
}

.skip:focus {
  top: 8px;
}

التمرين 16.3 · متوسط

شغّل فحص الوصول في Lighthouse على صفحتك التعريفية وعلى متجر الفصل 13، وأصلح كل مشكلة يذكرها.
جواب الكتاب المختصر
تقارير معتادة: alt ناقص، أو تباين ضعيف، أو تسميات ناقصة، أو خاصية lang مفقودة.
اعرض الحل

Lighthouse موجود في أدوات المطور في Chrome: افتح الصفحة، واضغط F12، واختر لوحة Lighthouse، وعلّم Accessibility، وانقر Analyze page load.

ما أبلغ عنه، والإصلاحات:

الصفحة المشكلة الإصلاح
الصفحة الشخصية (ف 7) نص التذييل #5b5873 على #f5f5fb: ‏6.3:1، ناجح. لا مشكلات أخرى. —
المتجر (ف 13) أزرار «أضف إلى السلة» كثيرة بالاسم نفسه؛ والمجموع يتغير بصمت. aria-label باسم المنتج، وaria-live على المجموع (انظر التمرين 16.5).
recipe-before.html بلا alt، وحقل بلا تسمية، وعناصر div قابلة للنقر، وتباين ضعيف (#c4c4c4)، وبلا h1. أُصلحت كلها في مشروع الفصل recipe.html.

والملف a11y-check.js يجد الأنواع نفسها من المشكلات آلياً؛ شغّله بـ node a11y-check.js أو أعطه صفحاتك.

a11y-check.js⤓ الملف
يعمل بـ Node.js: node a11y-check.js
// مدقق آلي صغير للمشكلات التي يبلّغ عنها Lighthouse أكثر من غيرها في صفحات المبتدئين.
// يقرأ HTML نصاً، فلا يغني عن Lighthouse (الذي يفحص الصفحة الحقيقية، والألوان معها)، لكنه يجد المشتبهين المعتادين في ثانية.
// التشغيل: node a11y-check.js [file.html ...]
const fs = require("node:fs");
const path = require("node:path");

function check(file) {
  const page = fs.readFileSync(file, "utf8");
  const problems = [];

  if (!/<html[^>]*\slang="[^"]+"/.test(page)) problems.push("‏<html> بلا خاصية lang");
  if (!/<title>[^<]+<\/title>/.test(page)) problems.push("الصفحة بلا <title>");

  for (const img of page.match(/<img\b[^>]*>/g) || []) {
    if (!/\salt=/.test(img)) problems.push(`صورة بلا alt: ${img}`);
  }

  // كل حقل يحتاج <label for="معرّفه"> (أو aria-label).
  const labels = new Set([...page.matchAll(/<label[^>]*\sfor="([^"]+)"/g)].map((m) => m[1]));
  for (const input of page.match(/<(input|textarea|select)\b[^>]*>/g) || []) {
    if (/type="(hidden|submit|button)"/.test(input) || /aria-label=/.test(input)) continue;
    const id = (input.match(/\sid="([^"]+)"/) || [])[1];
    if (!id || !labels.has(id)) problems.push(`حقل بلا تسمية: ${input}`);
  }

  // عناصر div قابلة للنقر: تستطيعها الفأرة، ولا تستطيعها لوحة المفاتيح.
  for (const div of page.match(/<div\b[^>]*onclick[^>]*>/g) || []) {
    problems.push(`div قابل للنقر بدل زر: ${div}`);
  }

  if (!/<h1\b/.test(page)) problems.push("لا يوجد عنوان <h1>");
  if (!/<main\b/.test(page)) problems.push("لا يوجد معلم <main>");

  return problems;
}

const here = (p) => path.join(__dirname, p);
const files = process.argv.length > 2 ? process.argv.slice(2) : [
  here("../../projects/recipe-before.html"),
  here("../../projects/recipe.html"),
  here("../../../ch07/examples/profile.html"),
  here("../../../ch13/examples/shop.html"),
];

for (const file of files) {
  const problems = check(file);
  console.log(`${path.relative(here("../.."), file)}: ${problems.length === 0 ? "لا مشكلات" : problems.length + " مشكلة"}`);
  for (const p of problems) console.log(`  - ${p}`);
}
الناتج المسجَّل$ node a11y-check.js
projects/recipe-before.html: 5 مشكلة
  - صورة بلا alt: <img src="soup.svg">
  - حقل بلا تسمية: <input placeholder="ابحث في الوصفات">
  - div قابل للنقر بدل زر: <div class="btn" onclick="alert('Saved')">
  - لا يوجد عنوان <h1>
  - لا يوجد معلم <main>
projects/recipe.html: لا مشكلات
../ch07/examples/profile.html: لا مشكلات
../ch13/examples/shop.html: لا مشكلات

التمرين 16.4 · متوسط

استخدم contrast.js لفحص كل لون نص في ملف تنسيق صفحتك التعريفية، وغيّر كل لون يرسب.
جواب الكتاب المختصر
شغّل contrast(لون_النص, لون_الخلفية) لكل زوج، وكل نتيجة أقل من 4.5 تحتاج نصاً أغمق أو خلفية أفتح.
اعرض الحل
contrast-profile.js⤓ الملف
// الملف contrast.js من الفصل، يفحص كل لون نص في ملف تنسيق الصفحة الشخصية (الفصل 7).
function luminance(hex) {
  const channels = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
  const linear = channels.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
  return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
}

function contrast(foreground, background) {
  const [a, b] = [luminance(foreground), luminance(background)].sort((x, y) => y - x);
  return (a + 0.05) / (b + 0.05);
}

// [النص، الخلفية، المكان]
const pairs = [
  ["#1e1b2e", "#f5f5fb", "نص الصفحة"],
  ["#1e1b2e", "#ffffff", "النص في البطاقات"],
  ["#ffffff", "#4338ca", "نص الرأس"],
  ["#4338ca", "#ffffff", "روابط القائمة، عناوين الأقسام"],
  ["#ffffff", "#db2777", "وسوم المهارات"],
  ["#db2777", "#ffffff", "الروابط في البطاقات"],
  ["#5b5873", "#f5f5fb", "التذييل"],
];

let failures = 0;
for (const [fg, bg, where] of pairs) {
  const ratio = contrast(fg, bg);
  const verdict = ratio >= 4.5 ? "ناجح" : "راسب";
  if (ratio < 4.5) failures++;
  console.log(`${fg} / ${bg}: ${ratio.toFixed(2)} → ${verdict}  (${where})`);
}
console.log(failures === 0 ? "كل الأزواج تتجاوز 4.5:1. لا شيء يحتاج تغييراً." : `ألوان يجب تغييرها: ${failures}`);

// لون كان سيرسب، وآخر أدكن ينجح:
console.log(`#9ca3af / #ffffff: ${contrast("#9ca3af", "#ffffff").toFixed(2)}  →  #6b7280 / #ffffff: ${contrast("#6b7280", "#ffffff").toFixed(2)}`);
الناتج المسجَّل$ node contrast-profile.js
#1e1b2e / #f5f5fb: 15.45 → ناجح  (نص الصفحة)
#1e1b2e / #ffffff: 16.78 → ناجح  (النص في البطاقات)
#ffffff / #4338ca: 7.90 → ناجح  (نص الرأس)
#4338ca / #ffffff: 7.90 → ناجح  (روابط القائمة، عناوين الأقسام)
#ffffff / #db2777: 4.60 → ناجح  (وسوم المهارات)
#db2777 / #ffffff: 4.60 → ناجح  (الروابط في البطاقات)
#5b5873 / #f5f5fb: 6.26 → ناجح  (التذييل)
كل الأزواج تتجاوز 4.5:1. لا شيء يحتاج تغييراً.
#9ca3af / #ffffff: 2.54  →  #6b7280 / #ffffff: 4.83

التمرين 16.5 · تحدٍّ

شغّل قارئ الشاشة في حاسوبك أو هاتفك، وحاول أن تشتري ملصقاً من متجر بِت دون أن تنظر إلى الشاشة. اكتب كل لحظة تهت فيها، وأصلح الصفحة.
جواب الكتاب المختصر
لا يوجد جواب واحد؛ ومن المشكلات الشائعة أزرار بلا أسماء، وصور بلا alt، وتغييرات لا تُعلن.
اعرض الحل

قارئات الشاشة: NVDA (مجاني) أو الراوي (Ctrl + Win + Enter) على ويندوز، وVoiceOver ‏(Cmd + F5) على ماك وآيفون، وTalkBack على أندرويد.

أين تهت وأنا أحاول شراء ملصق بعينين مغمضتين، والإصلاح في هذه النسخة من المتجر:

  1. أربعة أزرار كلها اسمها «أضف إلى السلة». وأنا أتنقل بـ Tab لم أعرف أيها للملصق. الإصلاح: aria-label="أضف ملصق بِت إلى السلة" على كل زر.
  2. لم يحدث شيء في ما سمعت بعد الضغط على الزر: المجموع تغير بصمت. الإصلاح: aria-live="polite" على المجموع، فيُقرأ بصوت.
  3. البطاقات بلا أسماء، فلم أسمع إلا «مقالة». الإصلاح: كل بطاقة تُسمّى بعنوانها عبر aria-labelledby.
  4. رسالة التحميل كان فيها role="status" في نسخة الفصل، فأُعلنت «جارٍ تحميل المنتجات…». لا شيء يحتاج إصلاحاً.
shop.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="ar" dir="rtl">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>متجر بِت</title>
    <link rel="stylesheet" href="../../../ch13/examples/shop.css">
  </head>
  <body>
    <header><h1>متجر بِت</h1></header>
    <main>
      <section>
        <p id="status" role="status"></p>
        <div id="products"></div>
      </section>
      <aside id="cart">
        <h2>سلتك</h2>
        <ul id="cart-lines"></ul>
        <!-- aria-live: يعلن قارئ الشاشة المجموع الجديد كلما تغيّر. -->
        <p id="cart-total" aria-live="polite"></p>
      </aside>
    </main>
    <script src="shop.js"></script>
  </body>
</html>
shop.html640px
shop.js⤓ الملف
let catalog = [];

const cart = [];

// ارسم بطاقة لكل منتج
function renderProducts() {
  const container = document.querySelector("#products");
  for (const product of catalog) {
    const card = document.createElement("article");
    card.className = "card";

    // كل بطاقة تُسمّى بعنوانها، فيقول قارئ الشاشة أي منتج هو فيه.
    card.setAttribute("aria-labelledby", `product-${product.id}`);

    const name = document.createElement("h3");
    name.id = `product-${product.id}`;
    name.textContent = product.name;

    const price = document.createElement("p");
    price.textContent = `$${product.price}`;

    const button = document.createElement("button");
    button.textContent = "أضف إلى السلة";
    // أربعة أزرار باسم «أضف إلى السلة» تبدو متشابهة؛ والتسمية تقول أي منتج.
    button.setAttribute("aria-label", `أضف ${product.name} إلى السلة`);
    button.addEventListener("click", () => addToCart(product.id));

    card.append(name, price, button);
    container.append(card);
  }
}

function addToCart(productId) {
  const line = cart.find((item) => item.productId === productId);
  if (line) {
    line.quantity++;
  } else {
    cart.push({ productId, quantity: 1 });
  }
  renderCart();
}

// أعد رسم السلة من البيانات كلما تغيرت
function renderCart() {
  const list = document.querySelector("#cart-lines");
  list.replaceChildren();

  let total = 0;
  for (const item of cart) {
    const product = catalog.find((p) => p.id === item.productId);
    const lineTotal = product.price * item.quantity;
    total += lineTotal;

    const li = document.createElement("li");
    li.textContent = `${product.name} × ${item.quantity}`;
    const amount = document.createElement("span");
    amount.textContent = `$${lineTotal}`;
    li.append(amount);
    list.append(li);
  }

  document.querySelector("#cart-total").textContent =
    cart.length === 0 ? "سلتك فارغة." : `المجموع: $${total}`;
}

// حمّل المنتجات من الخادم، ثم ارسم الصفحة
async function start() {
  const status = document.querySelector("#status");
  status.textContent = "جارٍ تحميل المنتجات…";
  try {
    const response = await fetch("../../../ch13/examples/products.json");
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    catalog = await response.json();
    status.textContent = "";
    renderProducts();
    renderCart();
  } catch (error) {
    status.textContent = "عذراً، تعذّر تحميل المنتجات. حاول مرة أخرى.";
    console.error(error);
  }
}

start();