💬پیام‌های پایه

توابع مرورگر مثل alert() اجرای کد را متوقف می‌کنند. SweetAlert2 با Promise‌محور بودن این مشکل را حل کرده و ظاهری زیبا و قابل شخصی‌سازی ارائه می‌دهد.

// ساده‌ترین حالت
Swal.fire('سلام! من یک پیام ساده هستم.');

// فرم سه‌پارامتری — عنوان | متن | آیکون
Swal.fire('موفقیت', 'اطلاعات ذخیره شد.', 'success');

// فرم آبجکت (پیشنهادی — کنترل بیشتر)
Swal.fire({
  title:           '<strong>پشتیبانی از HTML</strong>',
  html:            '<b>متن بولد</b> یا <a href="#">لینک</a>',
  footer:          '<a href="#">راهنمایی بیشتر</a>',
  showCloseButton: true,
  confirmButtonText: 'متوجه شدم!'
});
▶ دمو: پیام‌های پایه
ویژگیتوضیحمثال
titleعنوان اصلی'خوش آمدید!'
textمتن ساده'اطلاعات ذخیره شد'
htmlمحتوای HTML (جایگزین text)'<b>مهم</b>'
iconآیکون پیام'success' / 'error'
footerمتن پایین پنجره'<a>راهنما</a>'
widthعرض پنجره'400px'
showCloseButtonدکمه × بستنtrue
allowOutsideClickبستن با کلیک بیرونfalse

🎨آیکون‌ها و انواع هشدار

SweetAlert2 دارای ۵ آیکون متحرک از پیش ساخته است که با ویژگی icon فراخوانی می‌شوند.

Swal.fire({ icon: 'success', title: 'عملیات موفق!' });
Swal.fire({ icon: 'error',   title: 'خطا!', text: 'ارتباط برقرار نشد.', footer: '<a href="#">چرا؟</a>' });
Swal.fire({ icon: 'warning', title: 'هشدار!' });
Swal.fire({ icon: 'info',    title: 'اطلاعات' });
Swal.fire({ icon: 'question',title: 'سوال' });

// سفارشی‌سازی رنگ آیکون
Swal.fire({ icon: 'success', iconColor: '#88ce02', confirmButtonColor: '#88ce02' });
▶ دمو: ۵ نوع آیکون

🔺دکمه‌ها و تاییدیه

با showCancelButton دکمه انصراف نمایش داده می‌شود. نتیجه از طریق .then(result) دریافت می‌شود.

Swal.fire({
  title:              'حذف فایل؟',
  text:               'این عملیات برگشت‌پذیر نیست!',
  icon:               'warning',
  showCancelButton:   true,
  confirmButtonColor: '#d33',
  cancelButtonColor:  '#3085d6',
  confirmButtonText:  'بله، حذف کن!',
  cancelButtonText:   'انصراف'
}).then(result => {
  if (result.isConfirmed)
    Swal.fire('حذف شد!', 'فایل حذف گردید.', 'success');
  else if (result.isDismissed)
    console.log('لغو شد — reason:', result.dismiss);
});

// سه دکمه با showDenyButton
Swal.fire({
  title:            'تغییرات ذخیره شود؟',
  showDenyButton:   true,
  showCancelButton: true,
  confirmButtonText: 'ذخیره',
  denyButtonText:    'ذخیره نکن',
  cancelButtonText:  'انصراف'
}).then(r => {
  if (r.isConfirmed)  Swal.fire('ذخیره شد!', '', 'success');
  else if (r.isDenied) Swal.fire('ذخیره نشد', '', 'info');
});
▶ دمو: تاییدیه و دکمه‌ها
ویژگیتوضیح
showCancelButtonنمایش دکمه انصراف
showDenyButtonنمایش دکمه سوم (انکار)
confirmButtonText/Colorمتن و رنگ دکمه تایید
cancelButtonText/Colorمتن و رنگ دکمه انصراف
reverseButtonsجابجایی ترتیب دکمه‌ها
result.isConfirmedکاربر تایید کرد
result.isDeniedکاربر انکار کرد
result.isDismissedپنجره بدون تایید بسته شد

دریافت ورودی از کاربر

با تنظیم input، یک فیلد ورودی درون پنجره نمایش داده می‌شود. مقدار در result.value است.

// text / email / password / number / textarea / select / radio / checkbox / color / file / range
Swal.fire({
  title:       'ایمیل خود را وارد کنید',
  input:       'email',
  inputPlaceholder: 'user@example.com',
  showCancelButton: true,
  inputValidator: value => {
    if (!value) return 'ایمیل الزامی است!';
  }
}).then(r => {
  if (r.isConfirmed) Swal.fire(`ایمیل ثبت شد: ${r.value}`);
});
▶ دمو: انواع ورودی

'+r.value+'

'})})">رنگ (color)

🍔Toast نوتیفیکیشن

Toast‌ها هشدارهای کوچک غیرمزاحم هستند که در گوشه‌های صفحه نمایش می‌یابند و اجرای کد را متوقف نمی‌کنند.

// بهترین روش: یک mixin تعریف کنید و همه جا استفاده کنید
const Toast = Swal.mixin({
  toast:              true,
  position:           'top-end',
  showConfirmButton:  false,
  timer:              3000,
  timerProgressBar:   true,
  didOpen: toast => {
    toast.addEventListener('mouseenter', Swal.stopTimer);
    toast.addEventListener('mouseleave', Swal.resumeTimer);
  }
});

Toast.fire({ icon: 'success', title: 'تنظیمات ذخیره شد' });
Toast.fire({ icon: 'error',   title: 'خطا در اتصال!' });
Toast.fire({ icon: 'warning', title: 'حجم دیسک کم است' });
▶ دمو: Toast در موقعیت‌های مختلف
positionموقعیت
top-endبالا راست (پیشنهاد)
topبالا مرکز
top-startبالا چپ
bottom-endپایین راست
bottomپایین مرکز
centerوسط صفحه

تایمر و Progress Bar

// بسته شدن خودکار بعد از 3 ثانیه
Swal.fire({
  title:           'ذخیره شد!',
  icon:            'success',
  timer:           3000,           // ms
  timerProgressBar: true,          // نوار پیشرفت زیر پنجره
  showConfirmButton: false         // بدون دکمه تایید
});

// تایمر با شمارنده زنده در متن
let timerInterval;
Swal.fire({
  title: 'در حال بسته شدن...',
  html:  ' ثانیه دیگر',
  timer: 5000,
  timerProgressBar: true,
  didOpen: () => {
    Swal.showLoading();
    timerInterval = setInterval(() => {
      const b = Swal.getHtmlContainer().querySelector('b');
      if (b) b.textContent = Math.ceil(Swal.getTimerLeft() / 1000);
    }, 100);
  },
  willClose: () => clearInterval(timerInterval)
});

// کنترل تایمر از بیرون
Swal.stopTimer();    // توقف
Swal.resumeTimer(); // ادامه
Swal.getTimerLeft(); // ms باقی‌مانده
▶ دمو: تایمر

🌐AJAX و Loader

با showLoaderOnConfirm و preConfirm می‌توانید درخواست شبکه را مستقیم داخل SweetAlert2 مدیریت کنید.

Swal.fire({
  title:              'جستجوی کاربر گیت‌هاب',
  input:              'text',
  inputPlaceholder:   'نام کاربری...',
  showCancelButton:   true,
  confirmButtonText:  'جستجو',
  showLoaderOnConfirm: true,           // Loader روی دکمه
  allowOutsideClick:  () => !Swal.isLoading(),
  preConfirm: login => {
    return fetch(`https://api.github.com/users/${login}`)
      .then(res => {
        if (!res.ok) throw new Error('کاربر یافت نشد!');
        return res.json();
      })
      .catch(err => Swal.showValidationMessage(`خطا: ${err.message}`));
  }
}).then(r => {
  if (r.isConfirmed && r.value) {
    Swal.fire({
      title: r.value.name || r.value.login,
      text: `مخازن: ${r.value.public_repos}`,
      imageUrl: r.value.avatar_url,
      imageWidth: 130
    });
  }
});
▶ دمو: AJAX

📈Wizard چند مرحله‌ای

با زنجیر کردن Swal.fire() یا استفاده از Swal.mixin() می‌توان یک فرآیند چند مرحله‌ای (Wizard) ساخت:

// روش ۱: زنجیر async/await
async function multiStep() {
  const step1 = await Swal.fire({
    title: 'مرحله ۱ از ۳', input: 'text', inputPlaceholder: 'نام',
    showCancelButton: true, confirmButtonText: 'بعدی ←'
  });
  if (!step1.isConfirmed) return;

  const step2 = await Swal.fire({
    title: 'مرحله ۲ از ۳', input: 'email', inputPlaceholder: 'ایمیل',
    confirmButtonText: 'بعدی ←', showCancelButton: true
  });
  if (!step2.isConfirmed) return;

  Swal.fire({
    icon: 'success', title: 'تکمیل شد!',
    html: `نام: <b>${step1.value}</b><br>ایمیل: <b>${step2.value}</b>`
  });
}

// روش ۲: Swal.mixin برای style یکنواخت
const Wizard = Swal.mixin({
  progressSteps: ['۱', '۲', '۳'],
  confirmButtonText: 'بعدی ←',
  showCancelButton: true
});
▶ دمو: Wizard ثبت‌نام

🎨تم و استایل سفارشی

// تغییر رنگ دکمه‌ها
Swal.fire({
  title: 'پیام برند',
  confirmButtonColor: '#88ce02',
  cancelButtonColor:  '#e74c3c',
  showCancelButton:   true
});

// تصویر اختصاصی
Swal.fire({
  title:       'عکس سفارشی',
  imageUrl:    'https://placekitten.com/200/200',
  imageWidth:  200,
  imageAlt:    'گربه ناز'
});

// customClass — تغییر کلاس CSS
Swal.fire({
  title: 'با CSS سفارشی',
  customClass: {
    popup:         'my-popup',
    title:         'my-title',
    confirmButton: 'my-confirm-btn',
    cancelButton:  'my-cancel-btn'
  }
});

// پس‌زمینه سفارشی
Swal.fire({
  title:      'تم تاریک',
  background: '#1a1a2e',
  color:      '#e0e0e0',
  confirmButtonColor: '#88ce02'
});
▶ دمو: استایل‌های سفارشی

🔥mixin و چیت‌شیت

تنظیمات سراسری با mixin

// یک بار در ابتدای پروژه تعریف کنید
const MySwal = Swal.mixin({
  confirmButtonColor: '#88ce02',
  cancelButtonColor:  '#e74c3c',
  customClass: {
    confirmButton: 'my-confirm-btn',
    popup:         'my-popup'
  }
});

const Toast = Swal.mixin({
  toast: true, position: 'top-end',
  showConfirmButton: false, timer: 3000,
  timerProgressBar: true,
  didOpen: t => {
    t.addEventListener('mouseenter', Swal.stopTimer);
    t.addEventListener('mouseleave', Swal.resumeTimer);
  }
});

// بعداً استفاده کنید
MySwal.fire('موفقیت!', 'محصول اضافه شد.', 'success');
Toast.fire({ icon: 'success', title: 'ذخیره شد' });

// async/await
const result = await Swal.fire({ title: '...', showCancelButton: true });
if (result.isConfirmed) { /* ... */ }

// متدهای ایستا
Swal.isVisible();      // آیا پنجره‌ای باز است؟
Swal.close();           // بستن پنجره فعلی
Swal.showLoading();    // نمایش Loader روی دکمه
Swal.hideLoading();    // مخفی کردن Loader
Swal.getTimerLeft();   // ms باقی‌مانده تایمر
Swal.showValidationMessage('خطا!'); // نمایش خطا در input
▶ دمو: mixin سراسری

📄 چیت‌شیت سریع

عملیاتکد سریع
پیام سادهSwal.fire('متن')
موفقیتSwal.fire('','متن','success')
خطاSwal.fire({icon:'error',title:'خطا!'})
تاییدیه حذفSwal.fire({showCancelButton:true}).then(r=>r.isConfirmed&&...)
ToastSwal.mixin({toast:true,position:'top-end',...}).fire(...)
ورودیSwal.fire({input:'text',...}).then(r=>r.value)
AJAXSwal.fire({showLoaderOnConfirm:true,preConfirm:()=>fetch(...)})
تایمر خودکارSwal.fire({timer:3000,timerProgressBar:true,showConfirmButton:false})
LoaderSwal.fire({didOpen:()=>Swal.showLoading()})
بستنSwal.close()
💡 بهترین روش: در پروژه‌های واقعی همیشه یک Toast mixin و یک MySwal mixin در فایل اصلی JS تعریف کنید. این کار ظاهر هشدارها را کاملاً یکدست نگه می‌دارد و کد تکراری را حذف می‌کند.
⚠ async/await: SweetAlert2 از async/await پشتیبانی می‌کند: const result = await Swal.fire({...})

🚀زمین بازی کد (Playground)

انواع پیام‌های SweetAlert2 را امتحان کن: پایه، آیکون، تاییدیه، ورودی کاربر و Toast. دکمه‌ها را بزن و نتیجه را در پنل کنسول ببین. نسخهٔ ۱۱.۱۰.۷ آفلاین بارگذاری می‌شود.