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

الفصل 17

مشروع: ابنِ تطبيق ويب وانشره

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

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

  • تخطط للتطبيق قبل كتابة الكود: الميزات، والرسم، وشكل البيانات
  • تبني تطبيق مهام يومية كاملاً بـ HTML وCSS وJavaScript
  • تحفظ البيانات في المتصفح بـ localStorage فتبقى بعد إعادة التحميل
  • تختبره كالمحترفين: لوحة المفاتيح، وعرض الهاتف، والحالات غير المعتادة
  • تنشره على الإنترنت مجاناً بـ GitHub Pages

الأمثلة

17.2 HTML

أنشئ مجلداً اسمه my-tasks فيه ثلاثة ملفات. HTML تحمل البنية، وتكاد تكون فارغة حيث ستأتي المهام:

index.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="style.css">
  </head>
  <body>
    <main class="app">
      <h1>مهامي</h1>
      <p class="subtitle">خطوات صغيرة، كل يوم.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden">مهمة جديدة</label>
        <input id="task-text" type="text" placeholder="مثلاً: اقرأ الفصل 17" required>
        <button class="primary" type="submit">أضف</button>
      </form>

      <div class="filters" role="group" aria-label="اعرض">
        <button type="button" data-filter="all" aria-pressed="true">الكل</button>
        <button type="button" data-filter="active" aria-pressed="false">المتبقية</button>
        <button type="button" data-filter="done" aria-pressed="false">المنجزة</button>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty">لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear">احذف المنجزة</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html560px
الشكل 17.2: التطبيق مكتملاً بثلاث مهام، إحداها منجزة.

17.4 JavaScript

البرنامج يتبع نمط الفصل 12: البيانات، والتغييرات، والعرض، والأحداث. اقرأه قسماً قسماً:

app.js⤓ الملف
// ---------- البيانات ----------
const STORAGE_KEY = "my-tasks";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- التغييرات ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- العرض ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = "احذف";
  remove.setAttribute("aria-label", `احذف: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, remove);
  return li;
}

// العربية تغيّر صيغة الكلمة مع العدد
function leftText(count) {
  if (count === 0) return "أنجزت كل مهامك!";
  if (count === 1) return "بقيت مهمة واحدة";
  if (count === 2) return "بقيت مهمتان";
  if (count <= 10) return `بقيت ${count} مهام`;
  return `بقيت ${count} مهمة`;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = leftText(count);

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- الأحداث ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);

render();
+ 1 ملفات
style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

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

مشروع 17.1 · سهل

شريط التقدّم

اعرض كم أُنجز من القائمة، شريطاً وكلمات، وأبقِه متوافقاً مع كل تغيير.

ستتدرب على: العنصر <progress>، والإضافة إلى render()، وaccent-color.

الخطوات
  1. في HTML، فوق القائمة، أضف <progress id="progress" max="1" value="0"> و<span id="progress-text">، واربطهما بـ aria-labelledby ليكون للشريط اسم.
  2. في CSS اجعل الشريط يملأ السطر بـ flex: 1، ولوّنه بـ accent-color: var(--brand).
  3. في render() احسب done = tasks.length - count، ثم اضبط max وvalue للشريط.
  4. استخدم tasks.length || 1 لـ max، فلا تقسم القائمة الفارغة على صفر.
  5. اكتب «1 من 3 منجزة» في الـ span. علّم المهام وألغِ علامتها وأضف واحذف، وتحقق أن الشريط صحيح دائماً.

تلميح: لم تلمس addTask ولا toggleTask ولا deleteTask. فلأن كل تغيير ينتهي بـ render() تكفي كتلة واحدة جديدة هناك. وهذه مكافأة البنية التي بنيتها في هذا الفصل.

الحل
progress/index.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="style.css">
  </head>
  <body>
    <main class="app">
      <h1>مهامي</h1>
      <p class="subtitle">خطوات صغيرة، كل يوم.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden">مهمة جديدة</label>
        <input id="task-text" type="text" placeholder="مثلاً: اقرأ الفصل 17" required>
        <button class="primary" type="submit">أضف</button>
      </form>

      <div class="filters" role="group" aria-label="اعرض">
        <button type="button" data-filter="all" aria-pressed="true">الكل</button>
        <button type="button" data-filter="active" aria-pressed="false">المتبقية</button>
        <button type="button" data-filter="done" aria-pressed="false">المنجزة</button>
      </div>

      <div class="progress">
        <progress id="progress" max="1" value="0" aria-labelledby="progress-text"></progress>
        <span id="progress-text"></span>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty">لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear">احذف المنجزة</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html560px
مشروع 17.1: أُنجزت مهمة من ثلاث.
progress/app.js⤓ الملف
// ---------- البيانات ----------
const STORAGE_KEY = "my-tasks";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- التغييرات ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- العرض ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = "احذف";
  remove.setAttribute("aria-label", `احذف: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, remove);
  return li;
}

// العربية تغيّر صيغة الكلمة مع العدد
function leftText(count) {
  if (count === 0) return "أنجزت كل مهامك!";
  if (count === 1) return "بقيت مهمة واحدة";
  if (count === 2) return "بقيت مهمتان";
  if (count <= 10) return `بقيت ${count} مهام`;
  return `بقيت ${count} مهمة`;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = leftText(count);

  const done = tasks.length - count;
  const bar = document.querySelector("#progress");
  bar.max = tasks.length || 1;
  bar.value = done;
  document.querySelector("#progress-text").textContent = `${done} من ${tasks.length} منجزة`;

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- الأحداث ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);

render();
progress/style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.progress {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 8px 0 4px;
  color: var(--muted);
  font-size: 0.9rem;
}

.progress progress {
  flex: 1;
  height: 10px;
  accent-color: var(--brand);
}

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

تعديل المهمة

الأخطاء الإملائية تحدث. دع المستخدم يصحح نص المهمة في مكانها: Enter يحفظ، وEscape يلغي.

ستتدرب على: دالة تغيير جديدة، وreplaceWith، وأحداث لوحة المفاتيح، وfocus() وselect().

الخطوات
  1. أضف renameTask(id, text) بجانب دوال التغيير الأخرى: جِد المهمة، وغيّر نصها، واستدعِ update().
  2. في taskItem أضف زر «عدّل» بـ aria-label يسمّي المهمة، مثل زر الحذف.
  3. اكتب startEditing(li, task): أنشئ حقلاً فيه النص الحالي، وضعه مكان التسمية بـ label.replaceWith(input)، ثم استدعِ focus() وselect().
  4. استمع إلى keydown على الحقل. عند "Enter" احفظ النص بعد تنظيفه إن لم يكن فارغاً، وعند "Escape" استدعِ render() فقط.
  5. حين يفقد الحقل التركيز (blur) استدعِ render() أيضاً، فلا تبقى مهمة نصف معدّلة على الشاشة.

تلميح: اقترح القسم 17.7 النقر المزدوج، والزر أفضل: فالنقر المزدوج لا تؤديه لوحة المفاتيح ولا يسهل على الجوال، وعرفت في الفصل 16 لماذا يهم هذا.

الحل
edit/index.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="style.css">
  </head>
  <body>
    <main class="app">
      <h1>مهامي</h1>
      <p class="subtitle">خطوات صغيرة، كل يوم.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden">مهمة جديدة</label>
        <input id="task-text" type="text" placeholder="مثلاً: اقرأ الفصل 17" required>
        <button class="primary" type="submit">أضف</button>
      </form>

      <div class="filters" role="group" aria-label="اعرض">
        <button type="button" data-filter="all" aria-pressed="true">الكل</button>
        <button type="button" data-filter="active" aria-pressed="false">المتبقية</button>
        <button type="button" data-filter="done" aria-pressed="false">المنجزة</button>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty">لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear">احذف المنجزة</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html560px
مشروع 17.2: تعديل المهمة الثانية.
edit/app.js⤓ الملف
// ---------- البيانات ----------
const STORAGE_KEY = "my-tasks";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- التغييرات ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function renameTask(id, text) {
  const task = tasks.find((t) => t.id === id);
  task.text = text;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- العرض ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = "احذف";
  remove.setAttribute("aria-label", `احذف: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  const edit = document.createElement("button");
  edit.type = "button";
  edit.className = "edit";
  edit.textContent = "عدّل";
  edit.setAttribute("aria-label", `عدّل: ${task.text}`);
  edit.addEventListener("click", () => startEditing(li, task));

  li.append(box, label, edit, remove);
  return li;
}

// العربية تغيّر صيغة الكلمة مع العدد
function startEditing(li, task) {
  const input = document.createElement("input");
  input.className = "edit-text";
  input.value = task.text;
  input.setAttribute("aria-label", "عدّل المهمة");

  input.addEventListener("keydown", (event) => {
    if (event.key === "Enter") {
      const text = input.value.trim();
      if (text) renameTask(task.id, text);
      else render();
    }
    if (event.key === "Escape") render();
  });
  input.addEventListener("blur", () => render());

  li.querySelector("label").replaceWith(input);
  input.focus();
  input.select();
}

function leftText(count) {
  if (count === 0) return "أنجزت كل مهامك!";
  if (count === 1) return "بقيت مهمة واحدة";
  if (count === 2) return "بقيت مهمتان";
  if (count <= 10) return `بقيت ${count} مهام`;
  return `بقيت ${count} مهمة`;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = leftText(count);

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- الأحداث ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);

render();
edit/style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.edit {
  padding: 4px 12px;
  color: var(--brand);
  background: var(--soft);
}

li input.edit-text {
  flex: 1;
  width: auto;
  height: auto;
  padding: 6px 10px;
  font: inherit;
  border: 2px solid var(--brand);
  border-radius: 10px;
}

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

العربية والإنجليزية في تطبيق واحد

أضف زراً يبدّل كل نصوص التطبيق بين العربية والإنجليزية، ويقلب الاتجاه بين اليمين واليسار، ويتذكر الاختيار.

ستتدرب على: حفظ النصوص بيانات، وخصائص data-*، والدوال المحفوظة في الكائنات، وlang وdir، ومفتاح ثانٍ في localStorage.

الخطوات
  1. أنشئ كائن TEXTS بجزأين en وar، فيهما كل كلمة يعرضها التطبيق. وleft دالة، لأن الجمع العربي يتغير مع العدد.
  2. اكتب دالة مساعدة صغيرة t(key) تُرجع النص باللغة الحالية language.
  3. في HTML علّم كل نص بمفتاحه: <h1 data-text="title">، وأضف زر اللغة في الترويسة.
  4. اكتب applyLanguage(): اضبط lang وdir على document.documentElement، واملأ كل عنصر [data-text]، واضبط النص الإرشادي والتسميات، ثم render().
  5. استبدل كل كلمة ثابتة في app.js بـ t(…)، ثم احذف leftText القديمة.
  6. الزر يبدّل language، ويحفظها بمفتاحها الخاص، ويستدعي applyLanguage(). أعد تحميل الصفحة: يجب أن تفتح باللغة التي اخترتها آخر مرة.

تلميح: لأن CSS تستخدم flex وgap ولا «يسار» أو «يمين» ثابتاً، ينعكس التخطيط كله وحده حين يتغير dir. والتطبيقات الحقيقية تحفظ نصوصها هكذا، وبهذا تُترجم إلى لغات كثيرة دون أن يُلمس الكود.

الحل
languages/index.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Tasks</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <main class="app">
      <header class="top">
        <h1 data-text="title">My Tasks</h1>
        <button type="button" id="language" lang="ar">العربية</button>
      </header>
      <p class="subtitle" data-text="subtitle">Small steps, every day.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden" data-text="newTask">New task</label>
        <input id="task-text" type="text" placeholder="e.g. Read chapter 17" required>
        <button class="primary" type="submit" data-text="add">Add</button>
      </form>

      <div class="filters" role="group" aria-label="Show">
        <button type="button" data-filter="all" aria-pressed="true" data-text="all">All</button>
        <button type="button" data-filter="active" aria-pressed="false" data-text="active">To do</button>
        <button type="button" data-filter="done" aria-pressed="false" data-text="done">Done</button>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty" data-text="empty">Nothing here yet. Add your first task above!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear" data-text="clear">Clear done</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html560px
مشروع 17.3: التطبيق بالعربية من اليمين إلى اليسار، وزر «English» يقلبه كله بضغطة.
languages/app.js⤓ الملف
// ---------- Texts ----------
const TEXTS = {
  en: {
    title: "My Tasks",
    subtitle: "Small steps, every day.",
    newTask: "New task",
    placeholder: "e.g. Read chapter 17",
    add: "Add",
    show: "Show",
    all: "All",
    active: "To do",
    done: "Done",
    empty: "Nothing here yet. Add your first task above!",
    clear: "Clear done",
    delete: "Delete",
    switchTo: "العربية",
    left: (count) => {
      if (count === 0) return "All done!";
      if (count === 1) return "1 task left";
      return `${count} tasks left`;
    },
  },
  ar: {
    title: "مهامي",
    subtitle: "خطوات صغيرة، كل يوم.",
    newTask: "مهمة جديدة",
    placeholder: "مثلاً: اقرأ الفصل 17",
    add: "أضف",
    show: "اعرض",
    all: "الكل",
    active: "المتبقية",
    done: "المنجزة",
    empty: "لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!",
    clear: "احذف المنجزة",
    delete: "احذف",
    switchTo: "English",
    left: (count) => {
      if (count === 0) return "أنجزت كل مهامك!";
      if (count === 1) return "بقيت مهمة واحدة";
      if (count === 2) return "بقيت مهمتان";
      if (count <= 10) return `بقيت ${count} مهام`;
      return `بقيت ${count} مهمة`;
    },
  },
};

const LANG_KEY = "my-tasks-language";
let language = localStorage.getItem(LANG_KEY) || "ar";

function t(key) {
  return TEXTS[language][key];
}

function applyLanguage() {
  document.documentElement.lang = language;
  document.documentElement.dir = language === "ar" ? "rtl" : "ltr";
  document.title = t("title");

  for (const element of document.querySelectorAll("[data-text]")) {
    element.textContent = t(element.dataset.text);
  }
  document.querySelector("#task-text").placeholder = t("placeholder");
  document.querySelector(".filters").setAttribute("aria-label", t("show"));
  const button = document.querySelector("#language");
  button.textContent = t("switchTo");
  button.lang = language === "en" ? "ar" : "en";
  render();
}

function switchLanguage() {
  language = language === "en" ? "ar" : "en";
  localStorage.setItem(LANG_KEY, language);
  applyLanguage();
}

// ---------- Data ----------
const STORAGE_KEY = "my-tasks";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- Changes ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- Display ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = t("delete");
  remove.setAttribute("aria-label", `${t("delete")}: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, remove);
  return li;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = t("left")(count);

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- Events ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);
document.querySelector("#language").addEventListener("click", switchLanguage);

applyLanguage();
languages/style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

#language {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

التمارين

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

غيّر ألوان التطبيق وعنوانه ليصير خاصاً بك، وانشر النسخة الجديدة بـ git push واحدة.
جواب الكتاب المختصر
غيّر الخصائص المخصصة و<h1>، واحفظ commit، وgit push؛ فيتحدث GitHub Pages خلال دقيقة.
اعرض الحل
index.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="style.css">
  </head>
  <body>
    <main class="app">
      <h1>خطوات سارة</h1>
      <p class="subtitle">علامة خضراء بعد علامة.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden">مهمة جديدة</label>
        <input id="task-text" type="text" placeholder="مثلاً: اقرأ الفصل 17" required>
        <button class="primary" type="submit">أضف</button>
      </form>

      <div class="filters" role="group" aria-label="اعرض">
        <button type="button" data-filter="all" aria-pressed="true">الكل</button>
        <button type="button" data-filter="active" aria-pressed="false">المتبقية</button>
        <button type="button" data-filter="done" aria-pressed="false">المنجزة</button>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty">لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear">احذف المنجزة</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html640px
app.js⤓ الملف
// ---------- البيانات ----------
const STORAGE_KEY = "my-tasks-ex1";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- التغييرات ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- العرض ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = "احذف";
  remove.setAttribute("aria-label", `احذف: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, remove);
  return li;
}

// العربية تغيّر صيغة الكلمة مع العدد
function leftText(count) {
  if (count === 0) return "أنجزت كل مهامك!";
  if (count === 1) return "بقيت مهمة واحدة";
  if (count === 2) return "بقيت مهمتان";
  if (count <= 10) return `بقيت ${count} مهام`;
  return `بقيت ${count} مهمة`;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = leftText(count);

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- الأحداث ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);

render();
publish.sh⤓ الملف
يعمل في الطرفية: bash publish.sh
#!/usr/bin/env bash
# نشر النسخة الجديدة إيداع واحد ودفع واحد؛ وGitHub Pages تتحدّث خلال دقيقة.
# شغّله داخل مستودع تطبيقك (الذي نشرته في الفصل 17).
# lab: do not run (إنه يدفع إلى مستودعك أنت، فالمختبر يعرضه فقط)
set -e
git add index.html style.css
git commit -m "Make the app my own: new title and colours"
git push
style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

/* الهوية كلها من هذه الخصائص المخصّصة: تغيير أربعة أسطر يغيّر التطبيق. */
:root {
  --brand: #0f766e;
  --accent: #c2410c;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #ecfdf5;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

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

أضف عدّاداً للمهام المنجزة بجانب عدّاد المتبقية.
جواب الكتاب المختصر
احسب tasks.filter((t) => t.done).length في render واعرضه في عنصر جديد.
اعرض الحل
index.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="style.css">
  </head>
  <body>
    <main class="app">
      <h1>مهامي</h1>
      <p class="subtitle">خطوات صغيرة، كل يوم.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden">مهمة جديدة</label>
        <input id="task-text" type="text" placeholder="مثلاً: اقرأ الفصل 17" required>
        <button class="primary" type="submit">أضف</button>
      </form>

      <div class="filters" role="group" aria-label="اعرض">
        <button type="button" data-filter="all" aria-pressed="true">الكل</button>
        <button type="button" data-filter="active" aria-pressed="false">المتبقية</button>
        <button type="button" data-filter="done" aria-pressed="false">المنجزة</button>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty">لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <span id="finished"></span>
        <button type="button" id="clear">احذف المنجزة</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html640px
app.js⤓ الملف
// ---------- البيانات ----------
const STORAGE_KEY = "my-tasks-ex2";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- التغييرات ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- العرض ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = "احذف";
  remove.setAttribute("aria-label", `احذف: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, remove);
  return li;
}

// العربية تغيّر صيغة الكلمة مع العدد
function leftText(count) {
  if (count === 0) return "أنجزت كل مهامك!";
  if (count === 1) return "بقيت مهمة واحدة";
  if (count === 2) return "بقيت مهمتان";
  if (count <= 10) return `بقيت ${count} مهام`;
  return `بقيت ${count} مهمة`;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = leftText(count);

  // الوجه الآخر للبيانات نفسها: المهام المنجزة.
  const finished = tasks.filter((t) => t.done).length;
  document.querySelector("#finished").textContent = `المنجزة: ${finished}`;

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- الأحداث ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);

render();
style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

#finished {
  margin-inline-start: auto;
  margin-inline-end: 12px;
  color: #15803d;
  font-weight: 700;
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

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

اسمح للمستخدم بتعديل نص المهمة بالنقر المزدوج عليه، واحفظ التعديل بـ Enter وألغه بـ Escape.
جواب الكتاب المختصر
مع dblclick استبدل التسمية بـ <input>، ومع keydown احفظ عند Enter (حدّث text المهمة واستدعِ update())، وألغِ عند Escape (استدعِ render()).
اعرض الحل
index.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="style.css">
  </head>
  <body>
    <main class="app">
      <h1>مهامي</h1>
      <p class="subtitle">خطوات صغيرة، كل يوم.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden">مهمة جديدة</label>
        <input id="task-text" type="text" placeholder="مثلاً: اقرأ الفصل 17" required>
        <button class="primary" type="submit">أضف</button>
      </form>

      <div class="filters" role="group" aria-label="اعرض">
        <button type="button" data-filter="all" aria-pressed="true">الكل</button>
        <button type="button" data-filter="active" aria-pressed="false">المتبقية</button>
        <button type="button" data-filter="done" aria-pressed="false">المنجزة</button>
      </div>

      <p class="hint">انقر مهمة نقراً مزدوجاً لتعدّلها. Enter يحفظ، وEscape يلغي.</p>
      <ul id="tasks"></ul>
      <p class="empty" id="empty">لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear">احذف المنجزة</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html640px
app.js⤓ الملف
// ---------- البيانات ----------
const STORAGE_KEY = "my-tasks-ex3";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- التغييرات ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function editTask(id, text) {
  const task = tasks.find((t) => t.id === id);
  task.text = text;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- العرض ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  // لم يعد النص <label for> للمربع: فالتسمية تعلّم المربع مع كل نقرة من نقرتي النقر المزدوج.
  // و aria-labelledby ما زالت تعطي المربع اسمه.
  label.id = `text-${task.id}`;
  box.setAttribute("aria-labelledby", label.id);
  label.textContent = task.text;
  // نقر مزدوج: استبدل حقلاً نصياً بالتسمية، فيه النص نفسه.
  label.addEventListener("dblclick", (event) => {
    startEditing(task, label);
  });

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = "احذف";
  remove.setAttribute("aria-label", `احذف: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, remove);
  return li;
}

function startEditing(task, label) {
  const field = document.createElement("input");
  field.type = "text";
  field.className = "edit-text";
  field.value = task.text;
  field.setAttribute("aria-label", `عدّل: ${task.text}`);
  label.replaceWith(field);
  field.focus();
  field.select();

  field.addEventListener("keydown", (event) => {
    if (event.key === "Enter") {
      const text = field.value.trim();
      // النص الفارغ يترك مهمة غير مرئية: أبقِ القديم بدلاً منه.
      if (text) editTask(task.id, text);
      else render();
    } else if (event.key === "Escape") {
      render(); // الرسم من البيانات من جديد يتخلص من التعديل
    }
  });
  field.addEventListener("blur", () => render());
}

// العربية تغيّر صيغة الكلمة مع العدد
function leftText(count) {
  if (count === 0) return "أنجزت كل مهامك!";
  if (count === 1) return "بقيت مهمة واحدة";
  if (count === 2) return "بقيت مهمتان";
  if (count <= 10) return `بقيت ${count} مهام`;
  return `بقيت ${count} مهمة`;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = leftText(count);

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- الأحداث ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);

render();
style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.edit-text {
  flex: 1;
  padding: 4px 8px;
  font: inherit;
  border: 2px solid var(--brand);
  border-radius: 8px;
}

.hint {
  margin: 0 0 4px;
  color: var(--muted);
  font-size: 0.9rem;
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

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

أضف «أولوية» لكل مهمة (منخفضة، وعادية، وعالية) تُختار بـ <select> عند الإضافة، واعرض المهام العالية أولاً.
جواب الكتاب المختصر
أضف <select> إلى النموذج، واحفظ priority في كل مهمة، ورتّب المهام الظاهرة بـ sort((a, b) => rank[b.priority] - rank[a.priority]).
اعرض الحل
index.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="style.css">
  </head>
  <body>
    <main class="app">
      <h1>مهامي</h1>
      <p class="subtitle">خطوات صغيرة، كل يوم.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden">مهمة جديدة</label>
        <input id="task-text" type="text" placeholder="مثلاً: اقرأ الفصل 17" required>
        <label for="priority" class="visually-hidden">الأولوية</label>
        <select id="priority">
          <option value="low">منخفضة</option>
          <option value="normal" selected>عادية</option>
          <option value="high">عالية</option>
        </select>
        <button class="primary" type="submit">أضف</button>
      </form>

      <div class="filters" role="group" aria-label="اعرض">
        <button type="button" data-filter="all" aria-pressed="true">الكل</button>
        <button type="button" data-filter="active" aria-pressed="false">المتبقية</button>
        <button type="button" data-filter="done" aria-pressed="false">المنجزة</button>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty">لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear">احذف المنجزة</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html640px
app.js⤓ الملف
// ---------- البيانات ----------
const STORAGE_KEY = "my-tasks-ex4";

// رقم لكل أولوية، لنرتّب المهام حسبه.
const rank = { high: 3, normal: 2, low: 1 };
const priorityNames = { high: "عالية", normal: "عادية", low: "منخفضة" };
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- التغييرات ----------
function addTask(text, priority) {
  tasks.push({ id: Date.now(), text, done: false, priority });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- العرض ----------
function visibleTasks() {
  let list = tasks;
  if (filter === "active") list = tasks.filter((t) => !t.done);
  if (filter === "done") list = tasks.filter((t) => t.done);
  // العالية أولاً. ‏sort تغيّر المصفوفة التي تُعطاها، فنرتّب نسخة ([...list]) ونُبقي الترتيب المحفوظ.
  // المهام المحفوظة قبل هذا التغيير بلا أولوية: ‏?? تعاملها كعادية.
  return [...list].sort((a, b) => rank[b.priority ?? "normal"] - rank[a.priority ?? "normal"]);
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const priority = task.priority ?? "normal";
  const badge = document.createElement("span");
  badge.className = `badge ${priority}`;
  badge.textContent = priorityNames[priority];

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = "احذف";
  remove.setAttribute("aria-label", `احذف: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, badge, remove);
  return li;
}

// العربية تغيّر صيغة الكلمة مع العدد
function leftText(count) {
  if (count === 0) return "أنجزت كل مهامك!";
  if (count === 1) return "بقيت مهمة واحدة";
  if (count === 2) return "بقيت مهمتان";
  if (count <= 10) return `بقيت ${count} مهام`;
  return `بقيت ${count} مهمة`;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = leftText(count);

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- الأحداث ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text, document.querySelector("#priority").value);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);

render();
style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

form select {
  padding: 8px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
  background: white;
}

.badge {
  padding: 2px 10px;
  border-radius: 999px;
  font-size: 0.8rem;
  font-weight: 700;
}

.badge.high { color: #b91c1c; background: #fee2e2; }
.badge.normal { color: #4338ca; background: #e0e7ff; }
.badge.low { color: #4b5563; background: #f3f4f6; }

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

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

أضف إلى التطبيق مفتاح لغة. احفظ كل النصوص في كائن مثل { en: {…}, ar: {…} }، وتذكّر الاختيار في localStorage، وحدّث lang وdir في عنصر <html>.
جواب الكتاب المختصر
احفظ النصوص في كائن واحد، واكتب دالة تملأ كل عنصر من اللغة المختارة، واحفظ الاختيار في localStorage، واضبط document.documentElement.lang و.dir.
اعرض الحل

هذا التمرين هو عمل مشروع الفصل التطبيقي «مبدّل اللغة» نفسه، فالحل يبدأ من ذلك المشروع. وهكذا يحقق كل جزء من التمرين:

  • كل النصوص في كائن واحد: TEXTS = { en: {…}, ar: {…} } في أعلى app.js. ونص «المهام المتبقية» العربي دالة، لأن العربية تغيّر الكلمة مع العدد (واحدة، اثنتان، من 3 إلى 10، 11 فأكثر).
  • دالة واحدة تملأ الصفحة: applyLanguage() تكتب نص كل عنصر فيه خاصية data-text، والنص المؤقت، وعنوان الصفحة.
  • الاختيار محفوظ: localStorage.setItem("my-tasks-language", language).
  • ‏lang وdir: يتغير document.documentElement.lang و.dir، فينقلب التخطيط كله من اليمين إلى اليسار دون CSS إضافي (ملف التنسيق يستخدم inline-start/inline-end اللتين تتبعان الاتجاه).
index.html↗ افتح الصفحة⤓ الملف
<!doctype html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Tasks</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <main class="app">
      <header class="top">
        <h1 data-text="title">My Tasks</h1>
        <button type="button" id="language" lang="ar">العربية</button>
      </header>
      <p class="subtitle" data-text="subtitle">Small steps, every day.</p>

      <form id="new-task">
        <label for="task-text" class="visually-hidden" data-text="newTask">New task</label>
        <input id="task-text" type="text" placeholder="e.g. Read chapter 17" required>
        <button class="primary" type="submit" data-text="add">Add</button>
      </form>

      <div class="filters" role="group" aria-label="Show">
        <button type="button" data-filter="all" aria-pressed="true" data-text="all">All</button>
        <button type="button" data-filter="active" aria-pressed="false" data-text="active">To do</button>
        <button type="button" data-filter="done" aria-pressed="false" data-text="done">Done</button>
      </div>

      <ul id="tasks"></ul>
      <p class="empty" id="empty" data-text="empty">Nothing here yet. Add your first task above!</p>

      <footer>
        <span id="count" aria-live="polite"></span>
        <button type="button" id="clear" data-text="clear">Clear done</button>
      </footer>
    </main>
    <script src="app.js"></script>
  </body>
</html>
index.html640px
app.js⤓ الملف
// ---------- Texts ----------
const TEXTS = {
  en: {
    title: "My Tasks",
    subtitle: "Small steps, every day.",
    newTask: "New task",
    placeholder: "e.g. Read chapter 17",
    add: "Add",
    show: "Show",
    all: "All",
    active: "To do",
    done: "Done",
    empty: "Nothing here yet. Add your first task above!",
    clear: "Clear done",
    delete: "Delete",
    switchTo: "العربية",
    left: (count) => {
      if (count === 0) return "All done!";
      if (count === 1) return "1 task left";
      return `${count} tasks left`;
    },
  },
  ar: {
    title: "مهامي",
    subtitle: "خطوات صغيرة، كل يوم.",
    newTask: "مهمة جديدة",
    placeholder: "مثلاً: اقرأ الفصل 17",
    add: "أضف",
    show: "اعرض",
    all: "الكل",
    active: "المتبقية",
    done: "المنجزة",
    empty: "لا شيء هنا بعد. أضف أول مهمة لك في الأعلى!",
    clear: "احذف المنجزة",
    delete: "احذف",
    switchTo: "English",
    left: (count) => {
      if (count === 0) return "أنجزت كل مهامك!";
      if (count === 1) return "بقيت مهمة واحدة";
      if (count === 2) return "بقيت مهمتان";
      if (count <= 10) return `بقيت ${count} مهام`;
      return `بقيت ${count} مهمة`;
    },
  },
};

const LANG_KEY = "my-tasks-language";
let language = localStorage.getItem(LANG_KEY) || "ar";

function t(key) {
  return TEXTS[language][key];
}

function applyLanguage() {
  document.documentElement.lang = language;
  document.documentElement.dir = language === "ar" ? "rtl" : "ltr";
  document.title = t("title");

  for (const element of document.querySelectorAll("[data-text]")) {
    element.textContent = t(element.dataset.text);
  }
  document.querySelector("#task-text").placeholder = t("placeholder");
  document.querySelector(".filters").setAttribute("aria-label", t("show"));
  const button = document.querySelector("#language");
  button.textContent = t("switchTo");
  button.lang = language === "en" ? "ar" : "en";
  render();
}

function switchLanguage() {
  language = language === "en" ? "ar" : "en";
  localStorage.setItem(LANG_KEY, language);
  applyLanguage();
}

// ---------- Data ----------
const STORAGE_KEY = "my-tasks-ex5";
let tasks = load();
let filter = "all";

function load() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}

// ---------- Changes ----------
function addTask(text) {
  tasks.push({ id: Date.now(), text, done: false });
  update();
}

function toggleTask(id) {
  const task = tasks.find((t) => t.id === id);
  task.done = !task.done;
  update();
}

function deleteTask(id) {
  tasks = tasks.filter((t) => t.id !== id);
  update();
}

function clearDone() {
  tasks = tasks.filter((t) => !t.done);
  update();
}

function update() {
  save();
  render();
}

// ---------- Display ----------
function visibleTasks() {
  if (filter === "active") return tasks.filter((t) => !t.done);
  if (filter === "done") return tasks.filter((t) => t.done);
  return tasks;
}

function taskItem(task) {
  const li = document.createElement("li");
  li.classList.toggle("done", task.done);

  const box = document.createElement("input");
  box.type = "checkbox";
  box.id = `task-${task.id}`;
  box.checked = task.done;
  box.addEventListener("change", () => toggleTask(task.id));

  const label = document.createElement("label");
  label.htmlFor = box.id;
  label.textContent = task.text;

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "delete";
  remove.textContent = t("delete");
  remove.setAttribute("aria-label", `${t("delete")}: ${task.text}`);
  remove.addEventListener("click", () => deleteTask(task.id));

  li.append(box, label, remove);
  return li;
}

function render() {
  const list = document.querySelector("#tasks");
  list.replaceChildren(...visibleTasks().map(taskItem));

  document.querySelector("#empty").hidden = tasks.length > 0;

  const count = tasks.filter((t) => !t.done).length;
  document.querySelector("#count").textContent = t("left")(count);

  for (const button of document.querySelectorAll("[data-filter]")) {
    button.setAttribute("aria-pressed", String(button.dataset.filter === filter));
  }
}

// ---------- Events ----------
document.querySelector("#new-task").addEventListener("submit", (event) => {
  event.preventDefault();
  const input = document.querySelector("#task-text");
  const text = input.value.trim();
  if (text) {
    addTask(text);
    input.value = "";
  }
  input.focus();
});

for (const button of document.querySelectorAll("[data-filter]")) {
  button.addEventListener("click", () => {
    filter = button.dataset.filter;
    render();
  });
}

document.querySelector("#clear").addEventListener("click", clearDone);
document.querySelector("#language").addEventListener("click", switchLanguage);

applyLanguage();
style.css⤓ الملف
*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
  --brand: #4338ca;
  --accent: #db2777;
  --ink: #1e1b2e;
  --muted: #5b5873;
  --soft: #eef2ff;
}

body {
  margin: 0;
  font-family: system-ui, "Segoe UI", Tahoma, sans-serif;
  color: var(--ink);
  background: var(--soft);
}

.app {
  max-width: 560px;
  margin: 32px auto;
  padding: 24px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(30, 27, 46, 0.1);
}

h1 {
  margin: 0;
  color: var(--brand);
}

.subtitle {
  margin: 4px 0 20px;
  color: var(--muted);
}

form {
  display: flex;
  gap: 8px;
}

form input {
  flex: 1;
  padding: 10px 14px;
  font: inherit;
  border: 2px solid #c7c5dd;
  border-radius: 12px;
}

button {
  font: inherit;
  cursor: pointer;
  border: 0;
  border-radius: 999px;
}

.primary {
  padding: 10px 20px;
  color: white;
  background: var(--brand);
}

.filters {
  display: flex;
  gap: 6px;
  margin: 18px 0 8px;
}

.filters button {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}

.filters button[aria-pressed="true"] {
  color: white;
  background: var(--brand);
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 4px;
  border-bottom: 1px solid var(--soft);
}

li label {
  flex: 1;
}

li.done label {
  color: var(--muted);
  text-decoration: line-through;
}

li input {
  width: 20px;
  height: 20px;
  accent-color: var(--brand);
}

.delete {
  padding: 4px 12px;
  color: var(--accent);
  background: #fdf0f6;
}

.empty {
  color: var(--muted);
  text-align: center;
  padding: 24px 0;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 14px;
  color: var(--muted);
}

footer button {
  padding: 4px 10px;
  color: var(--muted);
  background: none;
  text-decoration: underline;
}

:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

#language {
  padding: 6px 14px;
  color: var(--brand);
  background: var(--soft);
}