-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass-enqueue.php
More file actions
454 lines (410 loc) · 16.3 KB
/
class-enqueue.php
File metadata and controls
454 lines (410 loc) · 16.3 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?php
/**
* Assets class.
*
* @package Progress_Planner
*/
namespace Progress_Planner\Admin;
use Progress_Planner\Badges\Monthly;
/**
* Enqueue class.
*/
class Enqueue {
/**
* Have the scripts been registered?
*
* @var boolean
*/
protected static $scripts_registered = false;
/**
* Vendor scripts.
*
* @var array
*/
const VENDOR_SCRIPTS = [
'vendor/tsparticles.confetti.bundle.min' => [
'handle' => 'particles-confetti',
'version' => '2.11.0',
],
'vendor/driver.js.iife' => [
'handle' => 'driver',
'version' => '1.3.1',
],
];
/**
* Enqueued assets.
*
* @var array
*/
protected $enqueued_assets = [
'js' => [],
'css' => [],
];
/**
* Init.
*
* @return void
*/
public function init() {
\add_action( 'admin_head', [ $this, 'maybe_empty_session_storage' ], 1 );
}
/**
* Enqueue script.
*
* @param string $handle The handle of the script to enqueue.
* @param array $localize_data The data to localize.
* [
* 'name' => 'varName',
* 'data' => [
* 'foo' => 'bar',
* ],
* ].
* @return void
*/
public function enqueue_script( $handle, $localize_data = [] ) {
$file_details = $this->get_file_details( 'js', $handle );
if ( empty( $file_details ) ) {
return;
}
$this->enqueued_assets['js'][] = $file_details['handle'];
$final_dependencies = [];
// Enqueue the script dependencies.
foreach ( $file_details['dependencies'] as $dependency ) {
if ( ! \in_array( $dependency, $this->enqueued_assets['js'], true ) ) {
$this->enqueue_script( $dependency );
$final_dependencies[] = $dependency;
}
}
// Enqueue the stylesheet.
\wp_enqueue_script( $file_details['handle'], $file_details['file_url'], $final_dependencies, $file_details['version'], true );
// Localize the script.
$this->localize_script( $file_details['handle'], $localize_data );
}
/**
* Enqueue a style.
*
* @param string $handle The handle of the style to enqueue.
*
* @return void
*/
public function enqueue_style( $handle ) {
$file_details = $this->get_file_details( 'css', $handle );
if ( empty( $file_details ) ) {
return;
}
$this->enqueued_assets['css'][] = $file_details['handle'];
$final_dependencies = [];
// Enqueue the script dependencies.
foreach ( $file_details['dependencies'] as $dependency ) {
if ( ! \in_array( $dependency, $this->enqueued_assets['css'], true ) ) {
$this->enqueue_style( $dependency );
}
}
// Enqueue the stylesheet.
\wp_enqueue_style( $file_details['handle'], $file_details['file_url'], $final_dependencies, $file_details['version'] );
}
/**
* Get file details.
*
* @param string $context The context of the file ( `css` or `js` ).
* @param string $handle The handle of the file.
*
* @return array
*/
public function get_file_details( $context, $handle ) {
if ( \str_starts_with( $handle, 'progress-planner/' ) ) {
$handle = \str_replace( 'progress-planner/', '', $handle );
}
if ( 'js' === $context ) {
foreach ( self::VENDOR_SCRIPTS as $vendor_script_handle => $vendor_script ) {
if ( $vendor_script['handle'] === $handle ) {
$handle = $vendor_script_handle;
break;
}
}
}
// The file path.
$file_path = \constant( 'PROGRESS_PLANNER_DIR' ) . "/assets/{$context}/{$handle}.{$context}";
// If the file does not exist, bail early.
if ( ! \file_exists( $file_path ) ) {
return [];
}
// The file URL.
$file_url = \constant( 'PROGRESS_PLANNER_URL' ) . "/assets/{$context}/{$handle}.{$context}";
// The handle.
$handle = 'js' === $context && isset( self::VENDOR_SCRIPTS[ $handle ] )
? self::VENDOR_SCRIPTS[ $handle ]['handle']
: 'progress-planner/' . $handle;
// The version.
$version = 'js' === $context && isset( self::VENDOR_SCRIPTS[ $handle ] )
? self::VENDOR_SCRIPTS[ $handle ]['version']
: \progress_planner()->get_file_version( $file_path );
// The dependencies.
$headers = \get_file_data( $file_path, [ 'dependencies' => 'Dependencies' ] );
$dependencies = isset( $headers['dependencies'] )
? \array_filter( \array_map( 'trim', \explode( ',', $headers['dependencies'] ) ) )
: [];
return [
'file_path' => $file_path,
'file_url' => $file_url,
'handle' => $handle,
'version' => $version,
'dependencies' => $dependencies,
];
}
/**
* Localize a script.
*
* @param string $handle The script handle.
* @param array $localize_data The data to localize.
* @return void
*/
public function localize_script( $handle, $localize_data = [] ) {
$localize_data = [
'name' => $localize_data['name'] ?? false,
'data' => $localize_data['data'] ?? [],
];
switch ( $handle ) {
case 'progress-planner/l10n':
$localize_data = [
'name' => 'prplL10nStrings',
'data' => $this->get_localized_strings(),
];
break;
case 'progress-planner/web-components/prpl-badge':
$localize_data = [
'name' => 'progressPlannerBadge',
'data' => [
'remoteServerRootUrl' => \progress_planner()->get_remote_server_root_url(),
'placeholderImageUrl' => \progress_planner()->get_placeholder_svg(),
],
];
break;
case 'progress-planner/suggested-task':
// Celebrate only on the Progress Planner Dashboard page.
$delay_celebration = true;
if ( \progress_planner()->is_on_progress_planner_dashboard_page() ) {
// should_show_upgrade_popover() also checks if we're on the Progress Planner Dashboard page - but let's be explicit since that method might change in the future.
$delay_celebration = \progress_planner()->get_plugin_upgrade_tasks()->should_show_upgrade_popover();
}
// Get the providers available for the user.
$include_providers = [];
$providers_available_for_user = \progress_planner()->get_suggested_tasks()->get_tasks_manager()->get_task_providers_available_for_user();
foreach ( $providers_available_for_user as $provider ) {
// Skip user provider.
if ( 'user' === $provider->get_provider_id() ) {
continue;
}
$include_providers[] = $provider->get_provider_id();
}
// Check if user wants to see all recommendations.
$show_all_recommendations = isset( $_GET['prpl_show_all_recommendations'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$tasks_per_page = $show_all_recommendations ? -1 : \Progress_Planner\Admin\Widgets\Suggested_Tasks::get_per_page();
// Get tasks from task providers (limited to 5 by default, or unlimited if showing all).
$tasks = \progress_planner()->get_suggested_tasks()->get_tasks_in_rest_format(
[
'post_status' => 'publish',
'posts_per_page' => $tasks_per_page,
'include_provider' => $include_providers, // User provider is already excluded.
]
);
// Get pending celebration tasks.
$pending_celebration_tasks = \progress_planner()->get_suggested_tasks()->get_tasks_in_rest_format(
[
'post_status' => 'pending',
'posts_per_page' => 100,
'include_provider' => $include_providers, // User provider is already excluded.
]
);
// Get user tasks.
$user_tasks = \progress_planner()->get_suggested_tasks()->get_tasks_in_rest_format(
[
'post_status' => [ 'publish', 'trash' ],
'include_provider' => [ 'user' ],
]
);
$localize_data = [
'name' => 'prplSuggestedTask',
'data' => [
'nonce' => \wp_create_nonce( 'progress_planner' ),
'assets' => [
'infoIcon' => \constant( 'PROGRESS_PLANNER_URL' ) . '/assets/images/icon_info.svg',
'snoozeIcon' => \constant( 'PROGRESS_PLANNER_URL' ) . '/assets/images/icon_snooze.svg',
],
'tasks' => [
'pendingTasks' => $tasks,
'pendingCelebrationTasks' => $pending_celebration_tasks,
'userTasks' => $user_tasks,
],
'delayCelebration' => $delay_celebration,
'tasksPerPage' => $tasks_per_page,
'perPageDefault' => \Progress_Planner\Admin\Widgets\Suggested_Tasks::get_per_page(),
],
];
break;
case 'progress-planner/celebrate':
// Check if current date is between Feb 12-16 to use hearts confetti.
$confetti_options = [];
// February 12 will be (string) '0212', and when converted to int it will be 212.
// February 16 will be (string) '0216', and when converted to int it will be 216.
// The integer conversion makes it easier and faster to compare the dates.
$date_md = (int) \gmdate( 'md' );
if ( 212 <= $date_md && $date_md <= 216 ) {
$confetti_options = [
[
'particleCount' => 50,
'scalar' => 2.2,
'shapes' => [ 'heart' ],
'colors' => [ 'FFC0CB', 'FF69B4', 'FF1493', 'C71585' ],
],
[
'particleCount' => 20,
'scalar' => 3.2,
'shapes' => [ 'heart' ],
'colors' => [ 'FFC0CB', 'FF69B4', 'FF1493', 'C71585' ],
],
];
}
$localize_data = [
'name' => 'prplCelebrate',
'data' => [
'raviIconUrl' => \progress_planner()->get_ui__branding()->get_admin_menu_icon(),
'confettiOptions' => $confetti_options,
],
];
foreach ( $this->get_badge_urls() as $context => $url ) {
$localize_data['data'][ $context . 'IconUrl' ] = $url;
}
break;
}
if ( ! $localize_data['name'] ) {
return;
}
\wp_localize_script( $handle, $localize_data['name'], $localize_data['data'] );
}
/**
* Get the badge URLs.
*
* @return string[] The badge URLs.
*/
private function get_badge_urls() {
// Get the monthly badge URL.
$monthly_badge = \progress_planner()->get_badges()->get_badge( Monthly::get_badge_id_from_date( new \DateTime() ) );
if ( $monthly_badge ) {
$badge_urls['month'] = \progress_planner()->get_remote_server_root_url() . '/wp-json/progress-planner-saas/v1/badge-svg/?badge_id=' . $monthly_badge->get_id() . '&branding_id=' . (int) \progress_planner()->get_ui__branding()->get_branding_id();
}
// Get the content and maintenance badge URLs.
foreach ( [ 'content', 'maintenance' ] as $context ) {
$set_badges = \progress_planner()->get_badges()->get_badges( $context );
foreach ( $set_badges as $badge ) {
$progress = $badge->get_progress();
if ( $progress['progress'] > 100 ) {
$badge_urls[ $context ] = \progress_planner()->get_remote_server_root_url() . '/wp-json/progress-planner-saas/v1/badge-svg/?badge_id=' . $badge->get_id() . '&branding_id=' . (int) \progress_planner()->get_ui__branding()->get_branding_id();
}
}
if ( ! isset( $badge_urls[ $context ] ) ) {
// Fallback to the first badge in the set if no badge is completed.
$badge_urls[ $context ] = \progress_planner()->get_remote_server_root_url() . '/wp-json/progress-planner-saas/v1/badge-svg/?badge_id=' . $set_badges[0]->get_id() . '&branding_id=' . (int) \progress_planner()->get_ui__branding()->get_branding_id();
}
}
return $badge_urls;
}
/**
* Get an array of localized strings.
*
* @return array<string, string>
*/
public function get_localized_strings() {
// Strings alphabetically ordered.
return [
'badge' => \esc_html__( 'Badge', 'progress-planner' ),
'checklistProgressDescription' => \sprintf(
/* translators: %s: the checkmark icon. */
\esc_html__( 'Check off all required elements %s in the element checks below', 'progress-planner' ),
'<span style="background-color:#14b8a6;padding:0.35em;margin:0 0.25em;border-radius:50%;display:inline-block;"></span>'
),
'close' => \esc_html__( 'Close', 'progress-planner' ),
'doneBtnText' => \esc_html__( 'Finish', 'progress-planner' ),
'info' => \esc_html__( 'Info', 'progress-planner' ),
'markAsComplete' => \esc_html__( 'Mark as completed', 'progress-planner' ),
'nextBtnText' => \esc_html__( 'Next →', 'progress-planner' ),
'prevBtnText' => \esc_html__( '← Previous', 'progress-planner' ),
'pageType' => \esc_html__( 'Page type', 'progress-planner' ),
'progressPlannerSidebar' => \sprintf(
/* translators: %s: The plugin name. */
\esc_html__( '%s Sidebar', 'progress-planner' ),
\progress_planner()->get_ui__branding()->get_admin_menu_name()
),
'progressText' => \sprintf(
/* translators: %1$s: The current step number. %2$s: The total number of steps. */
\esc_html__( 'Step %1$s of %2$s', 'progress-planner' ),
'{{current}}',
'{{total}}'
),
'saving' => \esc_html__( 'Saving...', 'progress-planner' ),
'snooze' => \esc_html__( 'Snooze', 'progress-planner' ),
'subscribed' => \esc_html__( 'Subscribed...', 'progress-planner' ),
'subscribing' => \esc_html__( 'Subscribing...', 'progress-planner' ),
/* translators: %s: The task content. */
'taskDelete' => \esc_html__( "Delete task '%s'", 'progress-planner' ),
'delete' => \esc_html__( 'Delete', 'progress-planner' ),
'video' => \esc_html__( 'Video', 'progress-planner' ),
'watchVideo' => \esc_html__( 'Watch video', 'progress-planner' ),
'disabledRRCheckboxTooltip' => \esc_html__( 'Don\'t worry! This task will be checked off automatically when you\'ve completed it.', 'progress-planner' ),
'opensInNewWindow' => \esc_html__( 'Opens in new window', 'progress-planner' ),
'whyIsThisImportant' => \esc_html__( 'Why is this important?', 'progress-planner' ),
/* translators: %s: The plugin name. */
'installPlugin' => \esc_html__( 'Install and activate the "%s" plugin', 'progress-planner' ),
/* translators: %s: The plugin name. */
'activatePlugin' => \esc_html__( 'Activate plugin "%s"', 'progress-planner' ),
'installing' => \esc_html__( 'Installing...', 'progress-planner' ),
'installed' => \esc_html__( 'Installed', 'progress-planner' ),
'activating' => \esc_html__( 'Activating...', 'progress-planner' ),
'activated' => \esc_html__( 'Activated', 'progress-planner' ),
'somethingWentWrong' => \esc_html__( 'Something went wrong.', 'progress-planner' ),
'showAllRecommendations' => \esc_html__( 'Show all recommendations', 'progress-planner' ),
'showFewerRecommendations' => \esc_html__( 'Show fewer recommendations', 'progress-planner' ),
'loadingTasks' => \esc_html__( 'Loading tasks...', 'progress-planner' ),
'taskAddedSuccessfully' => \esc_html__( 'Task added successfully', 'progress-planner' ),
'tasksDeleted' => \esc_html__( 'Completed tasks deleted', 'progress-planner' ),
'taskDeleted' => \esc_html__( 'Completed task deleted', 'progress-planner' ),
'moveUp' => \esc_html__( 'Move up', 'progress-planner' ),
'moveDown' => \esc_html__( 'Move down', 'progress-planner' ),
/* translators: %d: The number of points. */
'fixThisIssue' => \esc_html__( 'Fix this issue for %d points', 'progress-planner' ),
];
}
/**
* Maybe empty the session storage for the prpl_recommendations post type.
* We need to do it early, before the WP API script reads the cached data from the browser.
*
* @return void
*/
public function maybe_empty_session_storage() {
$screen = \get_current_screen();
if ( ! $screen ) {
return;
}
// Inject the script only on the Progress Planner Dashboard and the WordPress dashboard pages.
if ( 'toplevel_page_progress-planner' !== $screen->id && 'dashboard' !== $screen->id ) {
return;
}
?>
<script type="text/javascript">
if ( 'sessionStorage' in window ) {
try {
for ( const key in sessionStorage ) {
if (
-1 < key.indexOf( 'wp-api-schema-model' ) &&
-1 === sessionStorage.getItem( key ).indexOf( '/wp/v2/prpl_recommendations' )
) {
sessionStorage.removeItem( key );
break;
}
}
} catch ( er ) {}
}
</script>
<?php
}
}