Download index.html from mgkw/r: direct link, hf CLI and curl.
- Browser
- Download file 50.9 kB
-
https://huggingface.co/spaces/mgkw/r/resolve/main/index.html
- Command line
-
hf download hf://spaces/mgkw/r/index.html
-
curl -L -o index.html https://huggingface.co/spaces/mgkw/r/resolve/main/index.html
50.9 kB
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ماسح باركود ذكي</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap');
body {
font-family: 'Tajawal', sans-serif;
}
#reader {
position: relative;
overflow: hidden;
border-radius: 1rem;
background-color: #000;
aspect-ratio: 1/1;
}
#video {
width: 100%;
height: 100%;
object-fit: cover;
}
#canvas {
display: none;
}
#barcodeHighlight {
position: absolute;
border: 3px solid #10B981;
border-radius: 0.5rem;
display: none;
pointer-events: none;
z-index: 5;
transition: all 0.3s ease;
}
#scanBox {
position: absolute;
width: 70%;
height: 70%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid #3B82F6;
border-radius: 0.75rem;
box-shadow: 0 0 0 100vmax rgba(0, 0, 0, 0.5);
z-index: 2;
pointer-events: none;
}
.corner {
position: absolute;
width: 1.5rem;
height: 1.5rem;
border-color: #3B82F6;
border-width: 4px;
}
.corner-top-left {
top: -2px;
left: -2px;
border-top-style: solid;
border-left-style: solid;
border-top-left-radius: 0.5rem;
}
.corner-top-right {
top: -2px;
right: -2px;
border-top-style: solid;
border-right-style: solid;
border-top-right-radius: 0.5rem;
}
.corner-bottom-left {
bottom: -2px;
left: -2px;
border-bottom-style: solid;
border-left-style: solid;
border-bottom-left-radius: 0.5rem;
}
.corner-bottom-right {
bottom: -2px;
right: -2px;
border-bottom-style: solid;
border-right-style: solid;
border-bottom-right-radius: 0.5rem;
}
.zoom-btn {
width: 2.5rem;
height: 2.5rem;
border-radius: 50%;
background: rgba(0, 0, 0, 0.7);
color: white;
border: none;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s ease;
}
.zoom-btn:hover {
background: rgba(0, 0, 0, 0.9);
transform: scale(1.05);
}
.auto-zoom-active {
background: #3B82F6 !important;
}
.flash-on {
background-color: #F59E0B;
color: #1F2937;
}
.barcode-animation {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { opacity: 0.7; }
50% { opacity: 1; }
100% { opacity: 0.7; }
}
.loader {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.7);
z-index: 9999;
justify-content: center;
align-items: center;
}
.spinner {
width: 3rem;
height: 3rem;
border: 4px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: #3B82F6;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.result-card {
transition: all 0.3s ease;
}
.result-card:hover {
transform: translateY(-2px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.barcode-type-badge {
position: absolute;
top: 0.5rem;
left: 0.5rem;
background-color: #3B82F6;
color: white;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
font-size: 0.75rem;
font-weight: 500;
}
/* Statistics Page Styles */
#statisticsPage {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: white;
z-index: 1000;
padding: 1rem;
overflow-y: auto;
}
.stat-card {
background-color: #f8fafc;
border-radius: 0.5rem;
padding: 1rem;
margin-bottom: 1rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.stat-value {
font-size: 1.5rem;
font-weight: bold;
color: #3B82F6;
}
.chart-container {
height: 300px;
margin-top: 1rem;
}
.barcode-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 1rem;
border-bottom: 1px solid #e2e8f0;
}
.barcode-item:last-child {
border-bottom: none;
}
.barcode-count {
background-color: #3B82F6;
color: white;
border-radius: 9999px;
padding: 0.25rem 0.75rem;
font-size: 0.875rem;
}
</style>
</head>
<body class="bg-gray-100">
<div class="loader">
<div class="spinner"></div>
</div>
<!-- Main Page -->
<div id="mainPage" class="container mx-auto px-4 py-8 max-w-2xl">
<div class="text-center mb-8">
<h1 class="text-3xl font-bold text-blue-600 mb-2">ماسح باركود ذكي</h1>
<p class="text-gray-600">قم بمسح الباركود أو الكود الشريطي لقراءة محتواه</p>
</div>
<!-- iOS Instructions -->
<div id="iosMessage" class="bg-white p-4 rounded-lg shadow-md mb-6 hidden">
<h3 class="font-bold text-lg text-blue-600 mb-2">تعليمات لأجهزة iPhone</h3>
<ol class="list-decimal pr-5 space-y-1 text-gray-700">
<li>السماح باستخدام الكاميرا عند الطلب</li>
<li>توجيه الكاميرا نحو الباركود داخل المربع</li>
<li>الاقتراب من الباركود إذا لم يتم التعرف عليه</li>
</ol>
</div>
<!-- Scanner Card -->
<div class="bg-white rounded-xl shadow-md overflow-hidden mb-6">
<div class="bg-blue-600 px-4 py-3">
<h2 class="text-white font-bold text-lg flex items-center justify-between">
<span>مسح الباركود</span>
<i class="fas fa-barcode text-white"></i>
</h2>
</div>
<div class="p-4">
<div id="reader" class="relative">
<video id="video" playsinline></video>
<canvas id="canvas"></canvas>
<div id="scanBox"></div>
<div id="scanBoxCorners">
<div class="corner corner-top-left"></div>
<div class="corner corner-top-right"></div>
<div class="corner corner-bottom-left"></div>
<div class="corner corner-bottom-right"></div>
</div>
<div id="barcodeHighlight"></div>
<!-- Zoom Controls -->
<div id="zoomControls" class="absolute bottom-4 left-4 hidden flex-col gap-2">
<button id="zoomInBtn" class="zoom-btn" title="تكبير">
<i class="fas fa-search-plus"></i>
</button>
<button id="zoomOutBtn" class="zoom-btn" title="تصغير">
<i class="fas fa-search-minus"></i>
</button>
<button id="autoZoomBtn" class="zoom-btn auto-zoom-active" title="تكبير تلقائي">
<i class="fas fa-robot"></i>
</button>
</div>
</div>
<div class="mt-4 grid grid-cols-1 gap-3">
<button id="startButton" class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg flex items-center justify-center gap-2 transition-colors">
<i class="fas fa-camera"></i>
فتح الكاميرا
</button>
<div id="controlButtons" class="hidden grid grid-cols-2 gap-3">
<button id="stopButton" class="bg-red-600 hover:bg-red-700 text-white font-medium py-3 px-4 rounded-lg flex items-center justify-center gap-2 transition-colors">
<i class="fas fa-stop"></i>
إيقاف الكاميرا
</button>
<button id="flashButton" class="bg-yellow-500 hover:bg-yellow-600 text-gray-800 font-medium py-3 px-4 rounded-lg flex items-center justify-center gap-2 transition-colors">
<i class="fas fa-bolt"></i>
تشغيل الفلاش
</button>
</div>
</div>
</div>
</div>
<!-- Result Card -->
<div id="resultCard" class="bg-white rounded-xl shadow-md overflow-hidden result-card">
<div class="bg-blue-600 px-4 py-3">
<h2 class="text-white font-bold text-lg flex items-center justify-between">
<span>النتيجة</span>
<i class="fas fa-qrcode text-white"></i>
</h2>
</div>
<div class="p-4">
<div id="result" class="bg-gray-100 p-4 rounded-lg text-center text-gray-700 min-h-[6rem] flex items-center justify-center">
<div>
<i class="fas fa-barcode text-3xl text-gray-400 mb-2"></i>
<p>لم يتم مسح أي باركود بعد...</p>
</div>
</div>
<div class="mt-4 grid grid-cols-2 gap-3">
<button id="copyButton" class="bg-blue-100 hover:bg-blue-200 text-blue-700 font-medium py-3 px-4 rounded-lg flex items-center justify-center gap-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
<i class="fas fa-copy"></i>
نسخ النتيجة
</button>
<button id="printButton" class="bg-green-100 hover:bg-green-200 text-green-700 font-medium py-3 px-4 rounded-lg flex items-center justify-center gap-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
<i class="fas fa-print"></i>
طباعة النتيجة
</button>
</div>
</div>
</div>
<!-- History Section -->
<div id="historySection" class="mt-6 hidden">
<div class="flex justify-between items-center mb-3">
<h3 class="font-bold text-lg text-gray-800 flex items-center gap-2">
<i class="fas fa-history text-blue-600"></i>
سجل المسح
</h3>
<button id="showStatsBtn" class="text-blue-600 hover:text-blue-800 flex items-center gap-1">
<i class="fas fa-chart-bar"></i>
الإحصائيات
</button>
</div>
<div id="historyList" class="space-y-3">
<!-- History items will be added here dynamically -->
</div>
</div>
</div>
<!-- Statistics Page -->
<div id="statisticsPage">
<div class="container mx-auto px-4 py-8 max-w-2xl">
<div class="flex justify-between items-center mb-6">
<h1 class="text-2xl font-bold text-blue-600 flex items-center gap-2">
<i class="fas fa-chart-pie"></i>
إحصائيات المسح
</h1>
<button id="backToMainBtn" class="text-blue-600 hover:text-blue-800 flex items-center gap-1">
<i class="fas fa-arrow-right"></i>
العودة
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
<div class="stat-card">
<h3 class="text-gray-700 mb-2">إجمالي عمليات المسح</h3>
<div class="stat-value" id="totalScans">0</div>
</div>
<div class="stat-card">
<h3 class="text-gray-700 mb-2">عدد الباركودات الفريدة</h3>
<div class="stat-value" id="uniqueBarcodes">0</div>
</div>
<div class="stat-card">
<h3 class="text-gray-700 mb-2">أكثر باركود تكرراً</h3>
<div class="text-lg font-medium" id="mostScannedBarcode">-</div>
<div class="text-gray-500 text-sm" id="mostScannedCount">0 مرة</div>
</div>
<div class="stat-card">
<h3 class="text-gray-700 mb-2">آخر عملية مسح</h3>
<div class="text-lg font-medium" id="lastScanTime">-</div>
<div class="text-gray-500 text-sm" id="lastScanBarcode">-</div>
</div>
</div>
<div class="bg-white rounded-xl shadow-md overflow-hidden mb-6">
<div class="bg-blue-600 px-4 py-3">
<h2 class="text-white font-bold text-lg flex items-center justify-between">
<span>توزيع الباركودات</span>
<i class="fas fa-chart-bar text-white"></i>
</h2>
</div>
<div class="p-4">
<div class="chart-container" id="barcodeChart">
<!-- Chart will be rendered here -->
</div>
</div>
</div>
<div class="bg-white rounded-xl shadow-md overflow-hidden">
<div class="bg-blue-600 px-4 py-3">
<h2 class="text-white font-bold text-lg flex items-center justify-between">
<span>جميع الباركودات</span>
<i class="fas fa-list text-white"></i>
</h2>
</div>
<div class="p-4">
<div id="allBarcodesList">
<!-- Barcode list will be rendered here -->
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Elements
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
const flashButton = document.getElementById('flashButton');
const printButton = document.getElementById('printButton');
const copyButton = document.getElementById('copyButton');
const resultContainer = document.getElementById('result');
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const barcodeHighlight = document.getElementById('barcodeHighlight');
const zoomControls = document.getElementById('zoomControls');
const zoomInBtn = document.getElementById('zoomInBtn');
const zoomOutBtn = document.getElementById('zoomOutBtn');
const autoZoomBtn = document.getElementById('autoZoomBtn');
const controlButtons = document.getElementById('controlButtons');
const iosMessage = document.getElementById('iosMessage');
const historySection = document.getElementById('historySection');
const historyList = document.getElementById('historyList');
const resultCard = document.getElementById('resultCard');
const showStatsBtn = document.getElementById('showStatsBtn');
const backToMainBtn = document.getElementById('backToMainBtn');
const mainPage = document.getElementById('mainPage');
const statisticsPage = document.getElementById('statisticsPage');
const context = canvas.getContext('2d');
// Statistics elements
const totalScansEl = document.getElementById('totalScans');
const uniqueBarcodesEl = document.getElementById('uniqueBarcodes');
const mostScannedBarcodeEl = document.getElementById('mostScannedBarcode');
const mostScannedCountEl = document.getElementById('mostScannedCount');
const lastScanTimeEl = document.getElementById('lastScanTime');
const lastScanBarcodeEl = document.getElementById('lastScanBarcode');
const barcodeChartEl = document.getElementById('barcodeChart');
const allBarcodesListEl = document.getElementById('allBarcodesList');
// State variables
let isScanning = false;
let flashOn = false;
let stream = null;
let animationId = null;
let scanCount = 0;
let lastResult = null;
let lastResultTime = 0;
let processingAjax = false;
let currentZoom = 1;
let maxZoom = 3;
let autoZoomEnabled = true;
let lastBarcodeLocation = null;
// Data storage - Load from localStorage if available
let scanHistory = JSON.parse(localStorage.getItem('scanHistory')) || [];
let barcodeStats = JSON.parse(localStorage.getItem('barcodeStats')) || {};
let barcodeChart = null;
// Initialize history UI if there's data
if (scanHistory.length > 0) {
historySection.classList.remove('hidden');
updateHistoryUI();
}
// Check if iOS
function isIOS() {
return /iPhone|iPad|iPod/i.test(navigator.userAgent);
}
// Show iOS instructions if needed
if (isIOS()) {
iosMessage.classList.remove('hidden');
}
// Save data to localStorage
function saveData() {
localStorage.setItem('scanHistory', JSON.stringify(scanHistory));
localStorage.setItem('barcodeStats', JSON.stringify(barcodeStats));
}
// Clear all data
function clearAllData() {
if (confirm('هل أنت متأكد أنك تريد حذف جميع بيانات المسح؟ لا يمكن التراجع عن هذا الإجراء.')) {
scanHistory = [];
barcodeStats = {};
saveData();
// Update UI
historySection.classList.add('hidden');
historyList.innerHTML = '';
// Reset result display
resultContainer.innerHTML = `
<div>
<i class="fas fa-barcode text-3xl text-gray-400 mb-2"></i>
<p>لم يتم مسح أي باركود بعد...</p>
</div>
`;
printButton.disabled = true;
copyButton.disabled = true;
showToast('تم حذف جميع بيانات المسح', 'success');
}
}
// Check flash support
async function checkFlashSupport() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const cameras = devices.filter(device => device.kind === 'videoinput');
let cameraId = null;
for (const camera of cameras) {
if (camera.label.toLowerCase().includes('back') ||
camera.label.toLowerCase().includes('rear')) {
cameraId = camera.deviceId;
break;
}
}
return {
cameraId: cameraId || (cameras.length > 0 ? cameras[0].deviceId : null)
};
} catch (error) {
console.error("Error checking flash support:", error);
return { cameraId: null };
}
}
// Toggle flash
async function toggleFlash() {
if (!stream) return;
try {
const track = stream.getVideoTracks()[0];
const capabilities = track.getCapabilities();
if (capabilities.torch) {
flashOn = !flashOn;
await track.applyConstraints({
advanced: [{ torch: flashOn }]
});
flashButton.innerHTML = flashOn ?
'<i class="fas fa-bolt"></i> إيقاف الفلاش' :
'<i class="fas fa-bolt"></i> تشغيل الفلاش';
flashButton.classList.toggle("flash-on", flashOn);
// Show feedback
if (flashOn) {
showToast('تم تشغيل الفلاش', 'success');
} else {
showToast('تم إيقاف الفلاش', 'info');
}
} else {
showErrorMessage("الفلاش غير مدعوم على هذا الجهاز");
}
} catch (error) {
console.error("Error toggling flash:", error);
showErrorMessage("حدث خطأ أثناء تشغيل الفلاش");
}
}
// Highlight detected barcode
function highlightBarcode(location) {
const canvasRect = canvas.getBoundingClientRect();
const scale = canvasRect.width / canvas.width;
barcodeHighlight.style.left = `${location.topLeftCorner.x * scale}px`;
barcodeHighlight.style.top = `${location.topLeftCorner.y * scale}px`;
barcodeHighlight.style.width = `${(location.bottomRightCorner.x - location.topLeftCorner.x) * scale}px`;
barcodeHighlight.style.height = `${(location.bottomRightCorner.y - location.topLeftCorner.y) * scale}px`;
barcodeHighlight.style.display = 'block';
setTimeout(() => {
barcodeHighlight.style.display = 'none';
}, 1000);
}
// Apply current zoom level
function applyZoom() {
if (!stream) return;
const track = stream.getVideoTracks()[0];
const capabilities = track.getCapabilities();
if (capabilities.zoom) {
try {
track.applyConstraints({
advanced: [{ zoom: Math.min(maxZoom, Math.max(1, currentZoom)) }]
});
} catch (error) {
console.error("Error applying zoom:", error);
}
}
}
// Auto zoom based on barcode size
function applyAutoZoom(location) {
if (!autoZoomEnabled || !location) return;
const barcodeWidth = location.bottomRightCorner.x - location.topLeftCorner.x;
const barcodeHeight = location.bottomRightCorner.y - location.topLeftCorner.y;
const barcodeArea = barcodeWidth * barcodeHeight;
const frameArea = canvas.width * canvas.height;
const coverageRatio = barcodeArea / frameArea;
// Calculate desired zoom level
let targetZoom = 1;
if (coverageRatio < 0.2) {
targetZoom = Math.min(maxZoom, 1 / Math.sqrt(coverageRatio));
}
// Apply gradual zoom
if (Math.abs(targetZoom - currentZoom) > 0.1) {
currentZoom = currentZoom * 0.8 + targetZoom * 0.2;
applyZoom();
}
lastBarcodeLocation = location;
}
// Check if barcode is duplicate
function isDuplicateBarcode(barcode) {
return scanHistory.some(item => item.data === barcode);
}
// Update barcode statistics
function updateBarcodeStats(barcode) {
if (!barcodeStats[barcode]) {
barcodeStats[barcode] = 0;
}
barcodeStats[barcode]++;
saveData(); // Save after update
}
// Get most scanned barcode
function getMostScannedBarcode() {
let mostScanned = { barcode: null, count: 0 };
for (const [barcode, count] of Object.entries(barcodeStats)) {
if (count > mostScanned.count) {
mostScanned = { barcode, count };
}
}
return mostScanned;
}
// Render statistics
function renderStatistics() {
// Update basic stats
totalScansEl.textContent = scanHistory.length;
uniqueBarcodesEl.textContent = Object.keys(barcodeStats).length;
const mostScanned = getMostScannedBarcode();
mostScannedBarcodeEl.textContent = mostScanned.barcode || '-';
mostScannedCountEl.textContent = mostScanned.count ? `${mostScanned.count} مرة` : '0 مرة';
if (scanHistory.length > 0) {
const lastScan = scanHistory[0];
lastScanTimeEl.textContent = lastScan.timestamp;
lastScanBarcodeEl.textContent = lastScan.data;
} else {
lastScanTimeEl.textContent = '-';
lastScanBarcodeEl.textContent = '-';
}
// Render chart
renderBarcodeChart();
// Render barcode list
renderBarcodeList();
}
// Render barcode chart
function renderBarcodeChart() {
// Destroy previous chart if exists
if (barcodeChart) {
barcodeChart.destroy();
}
const barcodes = Object.keys(barcodeStats);
const counts = Object.values(barcodeStats);
// Limit to top 10 for better visualization
const topBarcodes = barcodes.slice(0, 10);
const topCounts = counts.slice(0, 10);
const ctx = barcodeChartEl.getContext('2d');
barcodeChart = new Chart(ctx, {
type: 'bar',
data: {
labels: topBarcodes,
datasets: [{
label: 'عدد عمليات المسح',
data: topCounts,
backgroundColor: '#3B82F6',
borderColor: '#2563EB',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1
}
}
},
plugins: {
legend: {
display: false
}
}
}
});
}
// Render barcode list
function renderBarcodeList() {
allBarcodesListEl.innerHTML = '';
// Sort by count descending
const sortedBarcodes = Object.entries(barcodeStats)
.sort((a, b) => b[1] - a[1]);
if (sortedBarcodes.length === 0) {
allBarcodesListEl.innerHTML = `
<div class="text-center py-4">
<p class="text-gray-500">لا توجد بيانات</p>
<button id="clearDataBtn" class="mt-4 text-red-600 hover:text-red-800 text-sm">
<i class="fas fa-trash-alt mr-1"></i> حذف جميع البيانات
</button>
</div>
`;
document.getElementById('clearDataBtn')?.addEventListener('click', clearAllData);
return;
}
sortedBarcodes.forEach(([barcode, count]) => {
const barcodeItem = document.createElement('div');
barcodeItem.className = 'barcode-item';
barcodeItem.innerHTML = `
<div class="flex-1 truncate" title="${barcode}">${barcode}</div>
<div class="barcode-count">${count}</div>
`;
allBarcodesListEl.appendChild(barcodeItem);
});
// Add clear data button at the bottom
const clearDiv = document.createElement('div');
clearDiv.className = 'text-center mt-4';
clearDiv.innerHTML = `
<button id="clearDataBtn" class="text-red-600 hover:text-red-800 text-sm">
<i class="fas fa-trash-alt mr-1"></i> حذف جميع البيانات
</button>
`;
allBarcodesListEl.appendChild(clearDiv);
document.getElementById('clearDataBtn').addEventListener('click', clearAllData);
}
// Scan frame for barcode
function scanBarcode() {
if (!isScanning) return;
// Reduce scan rate on iOS for better performance
if (isIOS() && scanCount % 2 !== 0) {
animationId = requestAnimationFrame(scanBarcode);
return;
}
if (video.readyState === video.HAVE_ENOUGH_DATA) {
canvas.height = video.videoHeight;
canvas.width = video.videoWidth;
context.drawImage(video, 0, 0, canvas.width, canvas.height);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "dontInvert",
});
// Only process if QR code has content and is not empty
if (code && code.data && code.data.trim() !== "" && !processingAjax) {
const currentTime = new Date().getTime();
if (lastResult !== code.data || currentTime - lastResultTime > 2000) {
lastResult = code.data;
lastResultTime = currentTime;
// Check if this is a duplicate barcode
const isDuplicate = isDuplicateBarcode(code.data);
// Update result display
resultContainer.innerHTML = `
<div class="relative">
<span class="barcode-type-badge">${code.channel ? 'QR Code' : 'Barcode'}</span>
<div class="mt-6">
<p class="font-medium text-gray-600 mb-2">محتوى الباركود:</p>
<p class="bg-white p-3 rounded-lg border border-gray-200 font-mono break-all">${code.data}</p>
${isDuplicate ? '<p class="text-yellow-600 text-sm mt-2">تم مسح هذا الباركود مسبقاً</p>' : ''}
</div>
</div>
`;
printButton.disabled = false;
copyButton.disabled = false;
// Only add to history if not duplicate
if (!isDuplicate) {
// Add to history
addToHistory(code.data, code.channel ? 'QR Code' : 'Barcode');
// Update statistics
updateBarcodeStats(code.data);
// Show success message
showToast('تم مسح الباركود بنجاح', 'success');
} else {
// Update statistics (count) even for duplicates
updateBarcodeStats(code.data);
// Show info message for duplicate
showToast('تم اكتشاف باركود مكرر', 'info');
}
highlightBarcode(code.location);
// Apply auto zoom
applyAutoZoom(code.location);
// Show success animation
resultCard.classList.add('barcode-animation');
setTimeout(() => {
resultCard.classList.remove('barcode-animation');
}, 2000);
if (scanCount == 0) {
processingAjax = true;
// Simulate API call (replace with actual API call)
setTimeout(() => {
document.querySelector('.loader').style.display = 'none';
processingAjax = false;
scanCount = 0;
}, 1500);
document.querySelector('.loader').style.display = 'flex';
}
scanCount++;
}
} else if (autoZoomEnabled && currentZoom > 1) {
// If no barcode found and zoom is active, gradually return to normal zoom
currentZoom = Math.max(1, currentZoom * 0.95);
applyZoom();
}
}
animationId = requestAnimationFrame(scanBarcode);
}
// Start scanner
async function startScanner() {
try {
const { cameraId } = await checkFlashSupport();
const constraints = {
video: {
facingMode: "environment",
width: { ideal: 1280 },
height: { ideal: 1280 },
frameRate: { ideal: 30 }
},
audio: false
};
// iOS specific settings
if (isIOS()) {
constraints.video = {
facingMode: "environment",
aspectRatio: { ideal: 1 },
frameRate: { ideal: 30 }
};
if (cameraId) {
constraints.video.deviceId = { exact: cameraId };
}
}
stream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = stream;
video.onloadedmetadata = () => {
video.play().catch(e => {
console.error("Error playing video:", e);
showErrorMessage("تعذر تشغيل الكاميرا");
});
isScanning = true;
currentZoom = 1;
applyZoom();
scanBarcode();
startButton.classList.add('hidden');
controlButtons.classList.remove('hidden');
zoomControls.classList.remove('hidden');
// Check flash support
const videoTrack = stream.getVideoTracks()[0];
const capabilities = videoTrack.getCapabilities();
if (capabilities.torch) {
flashButton.classList.remove('hidden');
}
showToast('تم تشغيل الكاميرا بنجاح', 'success');
};
} catch (error) {
console.error("Error starting camera:", error);
showErrorMessage("يجب السماح باستخدام الكاميرا في إعدادات المتصفح");
if (isIOS()) {
showIOSInstructions();
}
}
}
// Stop scanner
function stopScanner() {
isScanning = false;
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
if (stream) {
stream.getTracks().forEach(track => track.stop());
stream = null;
}
video.srcObject = null;
barcodeHighlight.style.display = 'none';
zoomControls.classList.add('hidden');
startButton.classList.remove('hidden');
controlButtons.classList.add('hidden');
flashButton.classList.add('hidden');
if (flashOn) {
flashOn = false;
flashButton.innerHTML = '<i class="fas fa-bolt"></i> تشغيل الفلاش';
flashButton.classList.remove("flash-on");
}
showToast('تم إيقاف الكاميرا', 'info');
}
// Copy result
function copyResult() {
if (!lastResult) return;
navigator.clipboard.writeText(lastResult)
.then(() => {
showToast("تم نسخ الباركود بنجاح", 'success');
})
.catch(err => {
showErrorMessage("فشل في نسخ الباركود");
console.error("Error copying:", err);
});
}
// Print result
function printResult() {
window.print();
}
// Add to scan history
function addToHistory(data, type) {
const timestamp = new Date().toLocaleString();
scanHistory.unshift({ data, type, timestamp });
saveData(); // Save after adding
// Show history section if not already shown
historySection.classList.remove('hidden');
updateHistoryUI();
}
// Update history UI
function updateHistoryUI() {
historyList.innerHTML = '';
scanHistory.forEach((item, index) => {
const historyItem = document.createElement('div');
historyItem.className = 'bg-white p-3 rounded-lg shadow-sm border border-gray-200';
historyItem.innerHTML = `
<div class="flex justify-between items-start">
<div class="flex-1">
<p class="text-sm text-gray-500 mb-1">${item.timestamp}</p>
<p class="font-medium text-gray-800 break-all">${item.data}</p>
</div>
<span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">${item.type}</span>
</div>
`;
historyItem.addEventListener('click', () => {
lastResult = item.data;
resultContainer.innerHTML = `
<div class="relative">
<span class="barcode-type-badge">${item.type}</span>
<div class="mt-6">
<p class="font-medium text-gray-600 mb-2">محتوى الباركود:</p>
<p class="bg-white p-3 rounded-lg border border-gray-200 font-mono break-all">${item.data}</p>
</div>
</div>
`;
printButton.disabled = false;
copyButton.disabled = false;
// Scroll to result
resultCard.scrollIntoView({ behavior: 'smooth' });
});
historyList.appendChild(historyItem);
});
}
// Show statistics page
function showStatisticsPage() {
mainPage.style.display = 'none';
statisticsPage.style.display = 'block';
renderStatistics();
}
// Show main page
function showMainPage() {
statisticsPage.style.display = 'none';
mainPage.style.display = 'block';
}
// Show iOS instructions
function showIOSInstructions() {
Swal.fire({
title: 'تعليمات iPhone',
html: `
<div style="text-align: right; direction: rtl;">
<p>لأفضل تجربة مسح:</p>
<ol class="list-decimal pr-5 space-y-1">
<li>اضغط على "فتح الكاميرا"</li>
<li>اسمح بالوصول إلى الكاميرا عند الطلب</li>
<li>وجه الكاميرا نحو الباركود بحيث يكون داخل المربع</li>
<li>سيقوم النظام تلقائياً بالتكبير على الباركود</li>
</ol>
<p class="mt-2 text-sm text-gray-500">ملاحظة: قد تحتاج إلى إضاءة جيدة</p>
</div>
`,
icon: 'info',
confirmButtonText: 'فهمت',
confirmButtonColor: '#3B82F6'
});
}
// Show toast message
function showToast(message, type) {
const Toast = Swal.mixin({
toast: true,
position: 'top-start',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: type,
title: message
});
}
// Show success message
function showSuccessMessage(message) {
Swal.fire({
title: 'تم بنجاح!',
text: message,
icon: 'success',
confirmButtonText: 'موافق',
confirmButtonColor: '#3B82F6',
timer: 3000,
timerProgressBar: true,
});
}
// Show error message
function showErrorMessage(message) {
Swal.fire({
title: 'خطأ!',
text: message,
icon: 'error',
confirmButtonText: 'موافق',
confirmButtonColor: '#EF4444',
timer: 3000,
timerProgressBar: true,
});
}
// Event listeners
startButton.addEventListener('click', startScanner);
stopButton.addEventListener('click', stopScanner);
flashButton.addEventListener('click', toggleFlash);
printButton.addEventListener('click', printResult);
copyButton.addEventListener('click', copyResult);
showStatsBtn.addEventListener('click', showStatisticsPage);
backToMainBtn.addEventListener('click', showMainPage);
// Zoom controls
zoomInBtn.addEventListener('click', () => {
autoZoomEnabled = false;
autoZoomBtn.classList.remove('auto-zoom-active');
currentZoom = Math.min(maxZoom, currentZoom + 0.5);
applyZoom();
showToast(`تم التكبير إلى ${currentZoom.toFixed(1)}x`, 'info');
});
zoomOutBtn.addEventListener('click', () => {
autoZoomEnabled = false;
autoZoomBtn.classList.remove('auto-zoom-active');
currentZoom = Math.max(1, currentZoom - 0.5);
applyZoom();
showToast(`تم التصغير إلى ${currentZoom.toFixed(1)}x`, 'info');
});
autoZoomBtn.addEventListener('click', () => {
autoZoomEnabled = !autoZoomEnabled;
autoZoomBtn.classList.toggle('auto-zoom-active', autoZoomEnabled);
if (autoZoomEnabled) {
currentZoom = 1;
applyZoom();
showToast('تم تفعيل التكبير التلقائي', 'success');
} else {
showToast('تم إيقاف التكبير التلقائي', 'info');
}
});
// Show iOS instructions if needed
if (isIOS()) {
setTimeout(showIOSInstructions, 1000);
}
});
</script>
</body>
</html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ماسح باركود ذكي</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap');
body {
font-family: 'Tajawal', sans-serif;
}
#reader {
position: relative;
overflow: hidden;
border-radius: 1rem;
background-color: #000;
aspect-ratio: 1/1;
}
#video {
width: 100%;
height: 100%;
object-fit: cover;
}
#canvas {
display: none;
}
#barcodeHighlight {
position: absolute;
border: 3px solid #10B981;
border-radius: 0.5rem;
display: none;
pointer-events: none;
z-index: 5;
transition: all 0.3s ease;
}
#scanBox {
position: absolute;
width: 70%;
height: 70%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 2px solid #3B82F6;
border-radius: 0.75rem;
box-shadow: 0 0 0 100vmax rgba(0, 0, 0, 0.5);
z-index: 2;
pointer-events: none;
}
.corner {
position: absolute;
width: 1.5rem;
height: 1.5rem;
border-color: #3B82F6;
border-width: 4px;
}
.corner-top-left {
top: -2px;
left: -2px;
border-top-style: solid;
border-left-style: solid;
border-top-left-radius: 0.5rem;
}
.corner-top-right {
top: -2px;
right: -2px;
border-top-style: solid;
border-right-style: solid;
border-top-right-radius: 0.5rem;
}
.corner-bottom-left {
bottom: -2px;
left: -2px;
border-bottom-style: solid;
border-left-style: solid;
border-bottom-left-radius: 0.5rem;
}
.corner-bottom-right {
bottom: -2px;
right: -2px;
border-bottom-style: solid;
border-right-style: solid;
border-bottom-right-radius: 0.5rem;
}
.zoom-btn {
width: 2.5rem;
height: 2.5rem;