-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
197 lines (159 loc) · 5.86 KB
/
Copy pathindex.js
File metadata and controls
197 lines (159 loc) · 5.86 KB
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
/* ============================================================
SHORTLY — index.js
- Mobile nav toggle
- URL shortening via urlvanish.com API
- Results list rendering
- Copy to clipboard
============================================================ */
'use strict';
/* ── DOM refs ─────────────────────────────────────────────── */
const $navToggle = document.querySelector('.nav-toggle');
const $primaryNav = document.querySelector('#primary-nav');
const $form = document.querySelector('.shortener__form');
const $input = document.querySelector('#url-input');
const $errorMsg = document.querySelector('#url-error');
const $resultsList = document.querySelector('.results-list');
/* ── 1. MOBILE NAV TOGGLE ─────────────────────────────────── */
$navToggle.addEventListener('click', () => {
const isOpen = $primaryNav.classList.toggle('is-open');
$navToggle.setAttribute('aria-expanded', isOpen);
$navToggle.setAttribute(
'aria-label',
isOpen ? 'Close navigation menu' : 'Open navigation menu'
);
});
// Close nav when clicking outside
document.addEventListener('click', (e) => {
if (!$primaryNav.contains(e.target) && !$navToggle.contains(e.target)) {
$primaryNav.classList.remove('is-open');
$navToggle.setAttribute('aria-expanded', 'false');
$navToggle.setAttribute('aria-label', 'Open navigation menu');
}
});
// Close nav on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && $primaryNav.classList.contains('is-open')) {
$primaryNav.classList.remove('is-open');
$navToggle.setAttribute('aria-expanded', 'false');
$navToggle.setAttribute('aria-label', 'Open navigation menu');
$navToggle.focus();
}
});
/* ── 2. VALIDATION ────────────────────────────────────────── */
function showError(message) {
$errorMsg.textContent = message;
$errorMsg.hidden = false;
$input.setAttribute('aria-invalid', 'true');
}
function clearError() {
$errorMsg.hidden = true;
$input.removeAttribute('aria-invalid');
}
function isValidUrl(value) {
try {
const url = new URL(value);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
}
/* ── 3. API CALL ──────────────────────────────────────────── */
async function shortenUrl(longUrl) {
const response = await fetch('https://urlvanish.com/create_api.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ originalUrl: longUrl }),
});
const data = await response.json();
if (!response.ok || data.status === 'error') {
throw new Error(data.message || 'Something went wrong. Please try again.');
}
return data.alias;
}
/* ── 4. RESULTS RENDERING ─────────────────────────────────── */
function createResultItem(originalUrl, shortUrl) {
const li = document.createElement('li');
li.className = 'results-list__item';
li.innerHTML = `
<span class="results-list__original" title="${originalUrl}">${originalUrl}</span>
<div class="results-list__short-group">
<a
href="${shortUrl}"
class="results-list__short-link"
target="_blank"
rel="noopener noreferrer"
>${shortUrl}</a>
<button
class="btn results-list__copy-btn"
aria-label="Copy shortened link ${shortUrl}"
data-link="${shortUrl}"
>
Copy
</button>
</div>
`;
return li;
}
function prependResult(originalUrl, shortUrl) {
const item = createResultItem(originalUrl, shortUrl);
// Newest result at the top
$resultsList.prepend(item);
}
/* ── 5. COPY TO CLIPBOARD ─────────────────────────────────── */
// Event delegation — handles all copy buttons, including future ones
$resultsList.addEventListener('click', async (e) => {
const $btn = e.target.closest('.results-list__copy-btn');
if (!$btn) return;
const shortUrl = $btn.dataset.link;
try {
await navigator.clipboard.writeText(shortUrl);
// Visual + accessible feedback
$btn.textContent = 'Copied!';
$btn.classList.add('is-copied');
$btn.setAttribute('aria-label', `Copied ${shortUrl}`);
// Reset after 2s
setTimeout(() => {
$btn.textContent = 'Copy';
$btn.classList.remove('is-copied');
$btn.setAttribute('aria-label', `Copy shortened link ${shortUrl}`);
}, 2000);
} catch {
$btn.textContent = 'Failed';
setTimeout(() => {
$btn.textContent = 'Copy';
}, 2000);
}
});
/* ── 6. FORM SUBMIT ───────────────────────────────────────── */
$form.addEventListener('submit', async (e) => {
e.preventDefault();
const rawValue = $input.value.trim();
// Client-side validation
if (!rawValue) {
showError('Please add a link');
$input.focus();
return;
}
if (!isValidUrl(rawValue)) {
showError('Please enter a valid URL (include https://)');
$input.focus();
return;
}
clearError();
// Loading state
const submitBtn = $form.querySelector('.shortener__btn');
const originalBtnText = submitBtn.textContent;
submitBtn.textContent = 'Shortening…';
submitBtn.disabled = true;
try {
const shortUrl = await shortenUrl(rawValue);
prependResult(rawValue, shortUrl);
$input.value = '';
$input.focus();
} catch (err) {
showError(err.message);
} finally {
submitBtn.textContent = originalBtnText;
submitBtn.disabled = false;
}
});