File size: 9,115 Bytes
96ba8a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Shared JavaScript across all pages
// HSK word database (simplified version)
const hskDatabase = {
    "你好": { level: 1, style: "Neutral", usage: "Common", meaning: "hello", pinyin: "nǐ hǎo" },
    "学习": { level: 1, style: "Neutral", usage: "Common", meaning: "study, learn", pinyin: "xué xí" },
    "谢谢": { level: 1, style: "Neutral", usage: "Common", meaning: "thank you", pinyin: "xiè xiè" },
    "再见": { level: 1, style: "Neutral", usage: "Common", meaning: "goodbye", pinyin: "zài jiàn" },
    "是": { level: 1, style: "Neutral", usage: "Common", meaning: "to be", pinyin: "shì" },
    "不": { level: 1, style: "Neutral", usage: "Common", meaning: "no, not", pinyin: "bù" },
    "我": { level: 1, style: "Neutral", usage: "Common", meaning: "I, me", pinyin: "wǒ" },
    "你": { level: 1, style: "Neutral", usage: "Common", meaning: "you", pinyin: "nǐ" },
    "好": { level: 1, style: "Neutral", usage: "Common", meaning: "good", pinyin: "hǎo" },
    "人": { level: 1, style: "Neutral", usage: "Common", meaning: "person", pinyin: "rén" },
    "冒险": { level: 4, style: "Neutral", usage: "Common", meaning: "adventure, take risks", pinyin: "mào xiǎn" },
    "尴尬": { level: 5, style: "Neutral", usage: "Common", meaning: "embarrassed, awkward", pinyin: "gān gà" },
    "牛逼": { level: "Not in HSK", style: "Informal", usage: "Common", meaning: "awesome, amazing", pinyin: "niú bī" },
    "囧": { level: "Not in HSK", style: "Informal", usage: "Rare", meaning: "embarrassed, awkward", pinyin: "jiǒng" },
    "饕餮": { level: "Not in HSK", style: "Formal", usage: "Rare", meaning: "gluttonous monster", pinyin: "tāo tiè" },
    "耄耋": { level: "Not in HSK", style: "Formal", usage: "Rare", meaning: "very old age", pinyin: "mào dié" }
};

// API endpoints configuration
const API_ENDPOINTS = {
    analyze: '/api/analyze',
    batchAnalyze: '/api/batch-analyze',
    hskLevel: '/api/hsk/'
};

// API utility functions
async function apiCall(endpoint, method = 'GET', data = null) {
    const options = {
        method: method,
        headers: {
            'Content-Type': 'application/json',
        },
    };
    
    if (data) {
        options.body = JSON.stringify(data);
    }
    
    try {
        const response = await fetch(endpoint, options);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        console.error('API call failed:', error);
        // Fallback to local database
        return fallbackAnalysis(data);
    }
}

// Fallback to local database when API is not available
function fallbackAnalysis(data) {
    if (data.word) {
        return {
            word: data.word,
            ...(hskDatabase[data.word] || {
                level: "Not in HSK",
                style: "Neutral",
                usage: "Rare",
                meaning: "unknown meaning",
                pinyin: "unknown"
            }
        };
    } else if (data.words) {
        return {
            results: data.words.map(word => ({
                word: word,
                ...(hskDatabase[word] || {
                    level: "Not in HSK",
                    style: "Neutral",
                    usage: "Rare",
                meaning: "unknown meaning",
                pinyin: "unknown"
            }))
        };
    }
    return null;
}

// Enhanced analyzeWord function with API support
async function analyzeWord(word) {
    // Check if input is Chinese characters
    if (!isChinese(word)) {
        showError("Please enter a valid Chinese word.");
        return;
    }
    
    // Try API first, then fallback to local database
    try {
        const response = await apiCall(API_ENDPOINTS.analyze, 'POST', { word: word });
        displayResults(word, response);
        saveResults(word, response);
    } catch (error) {
        // Fallback to local database
        const wordData = hskDatabase[word] || {
            level: "Not in HSK",
            style: "Neutral",
            usage: "Rare",
            meaning: "unknown meaning",
            pinyin: "unknown"
        };
        
        displayResults(word, wordData);
        saveResults(word, wordData);
    }
}
// DOM Elements
const wordForm = document.getElementById('wordForm');
const chineseWordInput = document.getElementById('chineseWord');
const resultsSection = document.getElementById('resultsSection');
const resultsDiv = document.getElementById('results');
const clearResultsBtn = document.getElementById('clearResults');

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    console.log('Hanzi Hunter initialized');
    
    // Form submission handler
    wordForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const word = chineseWordInput.value.trim();
        
        if (word) {
            analyzeWord(word);
        }
    });
    
    // Clear results handler
    clearResultsBtn.addEventListener('click', function() {
        clearResults();
    });
    
    // Load any saved results from localStorage
    loadSavedResults();
});

// Analyze the Chinese word
function analyzeWord(word) {
    // Check if input is Chinese characters
    if (!isChinese(word)) {
        showError("Please enter a valid Chinese word.");
        return;
    }
    
    // Find word in database or create default response
    const wordData = hskDatabase[word] || {
        level: "Not in HSK",
        style: "Neutral",
        usage: "Rare",
        meaning: "unknown meaning"
    };
    
    // Display results
    displayResults(word, wordData);
    
    // Save to localStorage
    saveResults(word, wordData);
}

// Check if string contains Chinese characters
function isChinese(str) {
    return /[\u4e00-\u9fff]/.test(str);
}

// Display analysis results
function displayResults(word, data) {
    resultsSection.classList.remove('hidden');
    resultsSection.classList.add('fade-in-up');
    
    let warningText = '';
    if (data.style === "Informal") {
        warningText = '<p class="text-yellow-400 text-sm mt-2"><i data-feather="alert-triangle" class="w-4 h-4 inline mr-1"></i>This is casual spoken Chinese.</p>';
    } else if (data.style === "Formal" || data.usage === "Rare") {
        warningText = '<p class="text-orange-400 text-sm mt-2"><i data-feather="info" class="w-4 h-4 inline mr-1"></i>This word is mostly used in formal writing.</p>';
    }
    
    resultsDiv.innerHTML = `
        <div class="bg-gray-800 rounded-lg p-4 border-l-4 border-red-500">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <p class="text-gray-400 text-sm">Word</p>
                    <p class="text-2xl font-bold">${word}</p>
                </div>
                <div>
                    <p class="text-gray-400 text-sm">HSK Level</p>
                    <p class="text-xl font-semibold">${data.level}</p>
                </div>
                <div>
                    <p class="text-gray-400 text-sm">Style</p>
                    <p class="text-xl font-semibold">${data.style}</p>
                </div>
                <div>
                    <p class="text-gray-400 text-sm">Usage</p>
                    <p class="text-xl font-semibold">${data.usage}</p>
                </div>
                <div>
                    <p class="text-gray-400 text-sm">Meaning</p>
                    <p class="text-xl font-semibold">${data.meaning}</p>
                </div>
            </div>
            ${warningText}
        </div>
    `;
    
    // Update feather icons in the new content
    feather.replace();
    
    // Scroll to results
    resultsSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// Show error message
function showError(message) {
    resultsSection.classList.remove('hidden');
    resultsDiv.innerHTML = `
        <div class="bg-red-900 rounded-lg p-4 border-l-4 border-red-500">
            <div class="flex items-center">
                <i data-feather="alert-circle" class="w-6 h-6 text-red-300 mr-3"></i>
                <p class="text-red-300">${message}</p>
            </div>
        </div>
    `;
    feather.replace();
}

// Clear results
function clearResults() {
    resultsSection.classList.add('hidden');
    chineseWordInput.value = '';
    chineseWordInput.focus();
    localStorage.removeItem('lastWordAnalysis');
}

// Save results to localStorage
function saveResults(word, data) {
    const analysis = {
        word: word,
        data: data,
        timestamp: new Date().toISOString()
    };
    localStorage.setItem('lastWordAnalysis', JSON.stringify(analysis));
}

// Load saved results from localStorage
function loadSavedResults() {
    const saved = localStorage.getItem('lastWordAnalysis');
    if (saved) {
        const analysis = JSON.parse(saved);
        displayResults(analysis.word, analysis.data);
    }
}

// Theme management (for future use)
function toggleTheme() {
    document.documentElement.classList.toggle('dark');
}