تعديل الكود الأصلي لإرسال البيانات إلى Custom Element:
سنقوم بتعديل دالة handleCalculate بحيث بدلاً من تحديث العنصر #answer1، تقوم بإرسال البيانات إلى العنصر المخصص #ageDisplay باستخدام postMessage.
// Import necessary Wix modules
import wixData from 'wix-data';
import wixWindow from 'wix-window';
// When the page is ready
$w.onReady(function () {
// Initially hide #section7
$w("#section7").collapse();
// Populate Year Dropdown
populateYearDropdown();
// Populate Month Dropdown
populateMonthDropdown();
// Set up event listeners for the dropdowns
$w("#dropdown1year, #dropdown2mounth").onChange(updateDays);
// Handle the "Calculate" button click
$w("#calcnow").onClick(handleCalculate);
// Initial update of days dropdown
updateDays();
});
/**
* Populates the Year Dropdown with options from current year down to 1900.
*/
function populateYearDropdown() {
const currentYear = new Date().getFullYear();
const yearOptions = [];
for (let year = currentYear; year >= 1900; year--) {
yearOptions.push({ label: year.toString(), value: year.toString() });
}
$w("#dropdown1year").options = yearOptions;
}
/**
* Populates the Month Dropdown with month names and corresponding values.
*/
function populateMonthDropdown() {
const monthOptions = [
{ label: "January - 1", value: "1" },
{ label: "February - 2", value: "2" },
{ label: "March - 3", value: "3" },
{ label: "April - 4", value: "4" },
{ label: "May - 5", value: "5" },
{ label: "June - 6", value: "6" },
{ label: "July - 7", value: "7" },
{ label: "August - 8", value: "8" },
{ label: "September - 9", value: "9" },
{ label: "October - 10", value: "10" },
{ label: "November - 11", value: "11" },
{ label: "December - 12", value: "12" }
];
$w("#dropdown2mounth").options = monthOptions;
}
/**
* Updates the Days Dropdown based on selected Year and Month.
*/
function updateDays() {
const birthYear = parseInt($w("#dropdown1year").value);
const birthMonth = parseInt($w("#dropdown2mounth").value);
if (!birthYear || !birthMonth) {
$w("#dropdown3day").options = [];
return;
}
const lastDay = new Date(birthYear, birthMonth, 0).getDate();
const daysOptions = [];
for (let day = 1; day <= lastDay; day++) {
daysOptions.push({ label: day.toString(), value: day.toString() });
}
$w("#dropdown3day").options = daysOptions;
}
/**
* Handles the Calculate button click event.
*/
function handleCalculate() {
const birthYear = parseInt($w("#dropdown1year").value);
const birthMonth = parseInt($w("#dropdown2mounth").value) - 1; // JavaScript months are 0-based
const birthDay = parseInt($w("#dropdown3day").value);
if (!birthYear || isNaN(birthMonth) || !birthDay) {
console.error("Please select all date fields");
return;
}
const today = new Date();
const birthDate = new Date(birthYear, birthMonth, birthDay);
let years = today.getFullYear() - birthDate.getFullYear();
let months = today.getMonth() - birthDate.getMonth();
let days = today.getDate() - birthDate.getDate();
if (days < 0) {
const lastMonthDate = new Date(today.getFullYear(), today.getMonth(), 0);
days = lastMonthDate.getDate() + days;
months--;
}
if (months < 0) {
months += 12;
years--;
}
const totalMonths = years * 12 + months;
const totalDays = Math.floor((today - birthDate) / (1000 * 60 * 60 * 24));
const totalWeeks = Math.floor(totalDays / 7);
const daysToNextBirthday = calculateDaysToNextBirthday(birthDate, today);
const nextBirthdayDate = new Date(today.getFullYear(), birthMonth, birthDay);
const nextBirthdayDay = nextBirthdayDate.toLocaleDateString('en-US', { weekday: 'long' });
const zodiacSign = getZodiacSign(birthDay, birthMonth + 1);
const birthDayOfWeek = birthDate.toLocaleDateString('en-US', { weekday: 'long' });
const birthSeason = getSeason(birthMonth + 1);
const birthSeasonEmoji = getSeasonEmoji(birthSeason);
const data = {
years,
months,
days,
totalMonths,
totalWeeks,
totalDays,
hours: totalDays * 24,
daysToNextBirthday,
nextBirthdayDay,
zodiacSign,
birthDayOfWeek,
birthSeason,
birthSeasonEmoji
};
// إرسال البيانات إلى الـ Custom Element
$w("#ageDisplay").postMessage(data);
// إظهار القسم 7 إذا كان مخفيًا
$w("#section7").expand();
}
/**
* Helper functions
*/
function calculateDaysToNextBirthday(birthDate, today) {
let nextBirthday = new Date(today.getFullYear(), birthDate.getMonth(), birthDate.getDate());
if (nextBirthday < today) {
nextBirthday.setFullYear(today.getFullYear() + 1);
}
nextBirthday.setHours(0,0,0,0);
today.setHours(0,0,0,0);
const diffTime = nextBirthday - today;
return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}
function getZodiacSign(day, month) {
const zodiacSigns = [
{ name: "Capricorn", symbol: "♑️", endDay: 19 },
{ name: "Aquarius", symbol: "♒️", endDay: 18 },
{ name: "Pisces", symbol: "♓️", endDay: 20 },
{ name: "Aries", symbol: "♈️", endDay: 19 },
{ name: "Taurus", symbol: "♉️", endDay: 20 },
{ name: "Gemini", symbol: "♊️", endDay: 20 },
{ name: "Cancer", symbol: "♋️", endDay: 22 },
{ name: "Leo", symbol: "♌️", endDay: 22 },
{ name: "Virgo", symbol: "♍️", endDay: 22 },
{ name: "Libra", symbol: "♎️", endDay: 21 },
{ name: "Scorpio", symbol: "♏️", endDay: 21 },
{ name: "Sagittarius", symbol: "♐️", endDay: 21 },
{ name: "Capricorn", symbol: "♑️", endDay: 31 }
];
const index = month - 1;
if (day > zodiacSigns[index].endDay) {
return zodiacSigns[(index + 1) % 12].name + " " + zodiacSigns[(index + 1) % 12].symbol;
} else {
return zodiacSigns[index].name + " " + zodiacSigns[index].symbol;
}
}
function getEmojiFromZodiac(zodiacWithSymbol) {
const parts = zodiacWithSymbol.split(' ');
return parts.length >= 2 ? parts[1] : "";
}
function getSeason(month) {
if (month >= 3 && month <= 5) return "Spring";
if (month >= 6 && month <= 8) return "Summer";
if (month >= 9 && month <= 11) return "Autumn";
return "Winter";
}
function getSeasonEmoji(season) {
const seasonEmojis = {
"Spring": "🌸",
"Summer": "☀️",
"Autumn": "🍁",
"Winter": "❄️"
};
return seasonEmojis[season] || "❓";
}
تعديل كود الـ Custom Element لاستقبال البيانات وعرضها:
سنقوم بتعديل كود الـ Custom Element لاستقبال البيانات عبر حدث message وتحديث الـ DOM بناءً عليها باستخدام نفس التصميم الذي كنت تستخدمه في دالة generateHTMLContent.
// wixDefaultCustomElement.js
class AgeDisplayElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.renderDefault();
}
connectedCallback() {
window.addEventListener('message', this.handleMessage.bind(this));
}
disconnectedCallback() {
window.removeEventListener('message', this.handleMessage.bind(this));
}
handleMessage(event) {
// تأكد من مصدر الرسالة إذا لزم الأمر
const data = event.data;
if (data && typeof data === 'object' && data.years !== undefined) {
this.renderContent(data);
}
}
renderDefault() {
const style = document.createElement('style');
style.textContent = `
.default-container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
color: #7f8c8d;
}
`;
const container = document.createElement('div');
container.className = 'default-container';
container.textContent = 'الرجاء إدخال بياناتك لحساب العمر.';
this.shadowRoot.appendChild(style);
this.shadowRoot.appendChild(container);
}
renderContent(data) {
// مسح المحتوى السابق
this.shadowRoot.innerHTML = '';
// إضافة الأنماط
const style = document.createElement('style');
style.textContent = `
.age-calculator {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.section {
background: white;
border-radius: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 25px;
padding: 25px;
text-align: center;
transition: transform 0.3s ease;
}
.section:hover {
transform: translateY(-5px);
}
h1, h2 {
color: #2c3e50;
margin-bottom: 20px;
}
.main-age {
display: flex;
justify-content: center;
gap: 30px;
margin-bottom: 20px;
}
.age-unit {
flex: 1;
max-width: 150px;
}
.age-number {
font-size: 48px;
font-weight: bold;
color: #3498db;
}
.age-label {
font-size: 18px;
color: #7f8c8d;
}
.timeline {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 20px;
}
.timeline-item {
padding: 15px;
border-radius: 10px;
background: #f7f9fc;
}
.timeline-number {
font-size: 24px;
font-weight: bold;
color: #e74c3c;
}
.birthday-countdown {
font-size: 36px;
color: #e67e22;
}
.next-birthday-day {
font-size: 20px;
color: #7f8c8d;
margin-top: 10px;
}
.birth-story {
display: flex;
justify-content: center;
gap: 30px;
flex-wrap: wrap;
}
.story-item {
flex: 1;
min-width: 120px;
max-width: 200px;
}
.story-emoji {
font-size: 36px;
margin-bottom: 10px;
}
.story-title {
font-weight: bold;
color: #2c3e50;
}
.story-value {
color: #7f8c8d;
}
@media (max-width: 600px) {
.main-age {
flex-direction: column;
align-items: center;
}
.age-unit {
margin-bottom: 15px;
}
.birth-story {
flex-direction: column;
align-items: center;
}
.story-item {
margin-bottom: 20px;
}
}
`;
this.shadowRoot.appendChild(style);
// إنشاء الهيكلية الأساسية
const container = document.createElement('div');
container.className = 'age-calculator';
// القسم الأول: عمر المستخدم بالسنوات، الأشهر، والأيام
const section1 = document.createElement('div');
section1.className = 'section';
section1.innerHTML = `
<h1>Your Life Journey</h1>
<div class="main-age">
<div class="age-unit">
<div class="age-number">${data.years}</div>
<div class="age-label">Years</div>
</div>
<div class="age-unit">
<div class="age-number">${data.months}</div>
<div class="age-label">Months</div>
</div>
<div class="age-unit">
<div class="age-number">${data.days}</div>
<div class="age-label">Days</div>
</div>
</div>
`;
container.appendChild(section1);
// القسم الثاني: خط الزمن
const section2 = document.createElement('div');
section2.className = 'section';
section2.innerHTML = `
<h2>Your Timeline</h2>
<div class="timeline">
<div class="timeline-item">
<div class="timeline-number">${data.totalMonths}</div>
<div class="age-label">Total Months</div>
</div>
<div class="timeline-item">
<div class="timeline-number">${data.totalWeeks}</div>
<div class="age-label">Total Weeks</div>
</div>
<div class="timeline-item">
<div class="timeline-number">${data.totalDays}</div>
<div class="age-label">Total Days</div>
</div>
<div class="timeline-item">
<div class="timeline-number">${data.hours}</div>
<div class="age-label">Total Hours</div>
</div>
</div>
`;
container.appendChild(section2);
// القسم الثالث: عيد الميلاد القادم
const section3 = document.createElement('div');
section3.className = 'section';
section3.innerHTML = `
<h2>Next Birthday</h2>
<div class="birthday-countdown">${data.daysToNextBirthday} Days</div>
<div class="next-birthday-day">It will be on a ${data.nextBirthdayDay}</div>
`;
container.appendChild(section3);
// القسم الرابع: قصة الميلاد
const section4 = document.createElement('div');
section4.className = 'section';
section4.innerHTML = `
<h2>Your Birth Story</h2>
<div class="birth-story">
<div class="story-item">
<div class="story-emoji">${getEmojiFromZodiac(data.zodiacSign)}</div>
<div class="story-title">Zodiac Sign</div>
<div class="story-value">${data.zodiacSign.split(' ')[0]}</div>
</div>
<div class="story-item">
<div class="story-emoji">📅</div>
<div class="story-title">Born On</div>
<div class="story-value">${data.birthDayOfWeek}</div>
</div>
<div class="story-item">
<div class="story-emoji">${data.birthSeasonEmoji}</div>
<div class="story-title">Season</div>
<div class="story-value">${data.birthSeason}</div>
</div>
</div>
`;
container.appendChild(section4);
this.shadowRoot.appendChild(container);
}
}
// مساعدة للحصول على الـ Emoji من برج الفلكي
function getEmojiFromZodiac(zodiacWithSymbol) {
const parts = zodiacWithSymbol.split(' ');
return parts.length >= 2 ? parts[1] : "";
}
// تعريف الـ Custom Element
customElements.define('age-display-element', AgeDisplayElement);