-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgwp-admin.js
More file actions
382 lines (344 loc) · 11.2 KB
/
Copy pathgwp-admin.js
File metadata and controls
382 lines (344 loc) · 11.2 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
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/**
* GravityWP Admin JavaScript
*
* Handles tab switching, license key validation feedback, and other
* interactive elements on the GravityWP Settings and Hub pages.
*
* @package gravitywp-license-handler
* @since 2.1.0
*/
( function () {
'use strict';
document.addEventListener( 'DOMContentLoaded', function () {
initTabs();
initTabLinks();
initKeyValidation();
initRefreshButton();
initHubActions();
} );
/**
* Initialize cross-tab navigation links.
*
* Buttons with data-gwp-tab-link="<tab-key>" inside any tab panel
* will switch to that tab when clicked.
*/
function initTabLinks() {
var links = document.querySelectorAll( '[data-gwp-tab-link]' );
links.forEach( function ( link ) {
link.addEventListener( 'click', function ( e ) {
e.preventDefault();
var targetKey = link.getAttribute( 'data-gwp-tab-link' );
var tab = document.querySelector(
'.gwp-tab[data-gwp-tab="' + targetKey + '"]'
);
if ( tab ) {
tab.click();
}
} );
} );
}
/**
* Initialize the tabbed interface.
*
* Looks for .gwp-tab elements with data-gwp-tab attributes and
* toggles corresponding .gwp-tab-panel elements with matching data-gwp-panel.
* Remembers the active tab in sessionStorage.
*/
function initTabs() {
var tabs = document.querySelectorAll( '.gwp-tab' );
var panels = document.querySelectorAll( '.gwp-tab-panel' );
if ( ! tabs.length ) {
return;
}
// Restore active tab from session storage or URL hash.
var activeTab = sessionStorage.getItem( 'gwpActiveTab' );
if ( window.location.hash ) {
activeTab = window.location.hash.substring( 1 );
}
if ( activeTab ) {
var targetTab = document.querySelector(
'.gwp-tab[data-gwp-tab="' + activeTab + '"]'
);
if ( targetTab ) {
setActiveTab( targetTab, tabs, panels );
}
} else {
// No restored tab — sync Save visibility to the default active tab.
var defaultActive = document.querySelector( '.gwp-tab.is-active' );
if ( defaultActive ) {
syncSaveVisibility( defaultActive.getAttribute( 'data-gwp-tab' ) );
}
}
tabs.forEach( function ( tab ) {
// The Save button shares the .gwp-tab class for styling but has no
// data-gwp-tab attribute — it must perform its native form submit,
// not be intercepted as a tab.
if ( ! tab.hasAttribute( 'data-gwp-tab' ) ) {
return;
}
tab.addEventListener( 'click', function ( e ) {
e.preventDefault();
setActiveTab( tab, tabs, panels );
var tabKey = tab.getAttribute( 'data-gwp-tab' );
if ( tabKey ) {
sessionStorage.setItem( 'gwpActiveTab', tabKey );
// Update URL hash without scrolling.
if ( history.replaceState ) {
history.replaceState( null, '', '#' + tabKey );
}
}
} );
} );
initStickyTabs();
}
/**
* Toggle the .gwp-tabs--showing-save class on the nav so the Save CTA
* is only visible when the License Keys tab is active.
*
* @param {string} tabKey The data-gwp-tab key of the now-active tab.
*/
function syncSaveVisibility( tabKey ) {
var nav = document.querySelector( '.gwp-tabs' );
if ( nav ) {
nav.classList.toggle( 'gwp-tabs--showing-save', tabKey === 'license-keys' );
}
}
/**
* Add a .gwp-tabs--stuck class when the sticky tabs bar is pinned to
* the top of the viewport, so we can deepen the shadow for elevation.
*
* Uses a 1px sentinel placed just above the bar; when that sentinel
* scrolls out of view, the bar is stuck. Graceful no-op on browsers
* without IntersectionObserver.
*/
function initStickyTabs() {
var nav = document.querySelector( '.gwp-tabs' );
if ( ! nav || ! ( 'IntersectionObserver' in window ) ) {
return;
}
var sentinel = document.createElement( 'div' );
sentinel.className = 'gwp-tabs__sentinel';
sentinel.style.cssText = 'height:1px;margin-bottom:-1px;';
nav.parentNode.insertBefore( sentinel, nav );
new IntersectionObserver( function ( entries ) {
nav.classList.toggle( 'gwp-tabs--stuck', ! entries[ 0 ].isIntersecting );
}, { rootMargin: '-32px 0px 0px 0px', threshold: [ 1 ] } ).observe( sentinel );
}
/**
* Set a tab as active and show its panel.
*
* @param {Element} tab The tab element to activate.
* @param {NodeList} tabs All tab elements.
* @param {NodeList} panels All panel elements.
*/
function setActiveTab( tab, tabs, panels ) {
var tabKey = tab.getAttribute( 'data-gwp-tab' );
if ( ! tabKey ) {
return;
}
tabs.forEach( function ( t ) {
t.classList.remove( 'is-active' );
} );
panels.forEach( function ( p ) {
p.classList.remove( 'is-active' );
} );
tab.classList.add( 'is-active' );
var panel = document.querySelector(
'.gwp-tab-panel[data-gwp-panel="' + tabKey + '"]'
);
if ( panel ) {
panel.classList.add( 'is-active' );
}
syncSaveVisibility( tabKey );
}
/**
* Initialize license key validation visual feedback.
*
* Adds is-valid/is-invalid classes based on basic format checks
* (UUID format). This is purely a visual hint — actual validation
* happens server-side.
*/
function initKeyValidation() {
var inputs = document.querySelectorAll( '.gwp-input[data-gwp-validate="license-key"]' );
if ( ! inputs.length ) {
return;
}
// Basic UUID pattern (loose — accepts any string 20+ chars with dashes/alphanum).
var pattern = /^[a-f0-9-]{20,}$/i;
inputs.forEach( function ( input ) {
// Initial check — honors any server-stamped force-state.
updateValidity( input, pattern );
// Remember the value the server marked as invalid. As long as
// the user is still looking at THAT exact value, we stay locked
// to invalid. The moment they type anything different, they're
// trying to fix it, so we release the lock and let the shape
// check take over.
var serverInvalidValue = 'invalid' === input.dataset.gwpForceState ? input.value : null;
input.addEventListener( 'input', function () {
if ( null !== serverInvalidValue && input.value !== serverInvalidValue ) {
delete input.dataset.gwpForceState;
serverInvalidValue = null;
}
updateValidity( input, pattern );
} );
input.addEventListener( 'blur', function () {
updateValidity( input, pattern );
} );
} );
}
/**
* Update the validity class on an input.
*
* @param {HTMLInputElement} input The input element.
* @param {RegExp} pattern The validation pattern.
*/
function updateValidity( input, pattern ) {
// Server-side override: when PHP knows this row is invalid (wrong-
// plugin key, expired, etc.) it stamps data-gwp-force-state="invalid"
// on the input. The shape-only UUID check below would otherwise
// re-apply .is-valid on every keystroke, flashing the input green
// over a server-validated bad value. Lock it to invalid instead.
if ( 'invalid' === input.dataset.gwpForceState ) {
input.classList.remove( 'is-valid' );
input.classList.add( 'is-invalid' );
return;
}
var value = input.value.trim();
input.classList.remove( 'is-valid', 'is-invalid' );
if ( ! value ) {
return; // Empty — no state.
}
if ( pattern.test( value ) ) {
input.classList.add( 'is-valid' );
} else {
input.classList.add( 'is-invalid' );
}
}
/**
* Initialize Hub action buttons (Install / Activate / Deactivate).
*
* Uses event delegation so dynamically replaced footers keep working
* after an AJAX swap.
*/
function initHubActions() {
document.addEventListener( 'click', function ( e ) {
var btn = e.target.closest( '.gwp-hub-action' );
if ( ! btn || btn.disabled ) {
return;
}
e.preventDefault();
runHubAction( btn );
} );
}
/**
* Execute one Hub action (Install / Activate / Deactivate) via admin-ajax.
*
* @param {HTMLButtonElement} btn The clicked action button.
*/
function runHubAction( btn ) {
if ( ! window.gwpHub || ! window.gwpHub.ajaxUrl ) {
return;
}
var action = btn.dataset.action; // install | activate | deactivate | delete
var labels = ( window.gwpHub && gwpHub.i18n ) || {};
// Destructive action — confirm before sending.
if ( action === 'delete' ) {
var confirmMsg = labels.confirmDelete || 'Delete this plugin? This cannot be undone.';
if ( ! window.confirm( confirmMsg ) ) {
return;
}
}
var busyText;
if ( action === 'install' ) {
busyText = labels.installing;
} else if ( action === 'update' ) {
busyText = labels.updating;
} else if ( action === 'activate' ) {
busyText = labels.activating;
} else if ( action === 'delete' ) {
busyText = labels.deleting;
} else {
busyText = labels.deactivating;
}
var footer = btn.closest( '.gwp-plugin-card__footer' );
var status = footer ? footer.querySelector( '.gwp-hub-action-status' ) : null;
btn.disabled = true;
btn.classList.add( 'is-loading' );
if ( status ) {
status.textContent = busyText || '';
status.className = 'gwp-hub-action-status is-busy';
}
var body = new URLSearchParams();
body.append( 'action', 'gwp_hub_' + action );
body.append( 'nonce', btn.dataset.nonce || gwpHub.nonce || '' );
body.append( 'slug', btn.dataset.slug || '' );
if ( btn.dataset.pluginFile ) {
body.append( 'plugin_file', btn.dataset.pluginFile );
}
if ( btn.dataset.package ) {
body.append( 'package', btn.dataset.package );
}
fetch( gwpHub.ajaxUrl, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Accept': 'application/json' },
body: body
} )
.then( function ( res ) {
return res.json().catch( function () {
throw new Error( labels.genericError || 'Error' );
} );
} )
.then( function ( payload ) {
if ( ! payload || ! payload.success ) {
var msg = ( payload && payload.data && payload.data.message ) || labels.genericError || 'Error';
throw new Error( msg );
}
if ( footer && payload.data && payload.data.footer_html ) {
footer.innerHTML = payload.data.footer_html;
}
// Update succeeded — drop the now-stale "Update available" notice
// from the card header (the AJAX response only re-renders the
// footer, not the header).
if ( action === 'update' && footer ) {
var card = footer.closest( '.gwp-plugin-card' );
var notice = card && card.querySelector( '.gwp-plugin-card__update-notice' );
if ( notice ) {
notice.remove();
}
}
} )
.catch( function ( err ) {
btn.disabled = false;
btn.classList.remove( 'is-loading' );
if ( status ) {
status.textContent = err && err.message ? err.message : ( labels.genericError || 'Error' );
status.className = 'gwp-hub-action-status is-error';
}
} );
}
/**
* Initialize the refresh button (prevents double-clicks).
*/
function initRefreshButton() {
var refreshButtons = document.querySelectorAll( '.gwp-refresh-link, [data-gwp-refresh]' );
if ( ! refreshButtons.length ) {
return;
}
refreshButtons.forEach( function ( btn ) {
btn.addEventListener( 'click', function () {
// Add loading state.
btn.classList.add( 'is-loading' );
btn.style.pointerEvents = 'none';
btn.style.opacity = '0.6';
// Reset after page reload would normally happen anyway,
// but in case of anchor navigation:
setTimeout( function () {
btn.style.pointerEvents = '';
btn.style.opacity = '';
btn.classList.remove( 'is-loading' );
}, 5000 );
} );
} );
}
} )();