-
Notifications
You must be signed in to change notification settings - Fork 69
/
index.js
583 lines (534 loc) · 16.4 KB
/
index.js
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/**
* Internal dependencies
*/
import { upeRestrictedProperties } from './upe-styles';
import {
generateHoverRules,
generateOutlineStyle,
dashedToCamelCase,
isColorLight,
getBackgroundColor,
maybeConvertRGBAtoRGB,
handleAppearanceForFloatingLabel,
} from './utils.js';
export const appearanceSelectors = {
default: {
hiddenContainer: '#wcpay-hidden-div',
hiddenInput: '#wcpay-hidden-input',
hiddenInvalidInput: '#wcpay-hidden-invalid-input',
hiddenValidActiveLabel: '#wcpay-hidden-valid-active-label',
},
classicCheckout: {
appendTarget: '.woocommerce-billing-fields__field-wrapper',
upeThemeInputSelector: '#billing_first_name',
upeThemeLabelSelector: '.woocommerce-checkout .form-row label',
upeThemeTextSelector: '.woocommerce-checkout .form-row',
rowElement: 'p',
validClasses: [ 'form-row' ],
invalidClasses: [
'form-row',
'woocommerce-invalid',
'woocommerce-invalid-required-field',
],
backgroundSelectors: [
'li.wc_payment_method .wc-payment-form',
'li.wc_payment_method .payment_box',
'#payment',
'#order_review',
'form.checkout',
'body',
],
headingSelectors: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
buttonSelectors: [ '#place_order' ],
linkSelectors: [ 'a' ],
},
blocksCheckout: {
appendTarget: '#contact-fields',
upeThemeInputSelector: '.wc-block-components-text-input #email',
upeThemeLabelSelector: '.wc-block-components-text-input label',
upeThemeTextSelector: '.wc-block-components-text-input',
rowElement: 'div',
validClasses: [ 'wc-block-components-text-input', 'is-active' ],
invalidClasses: [ 'wc-block-components-text-input', 'has-error' ],
alternateSelectors: {
appendTarget: '#billing.wc-block-components-address-form',
upeThemeInputSelector: '#billing-first_name',
upeThemeLabelSelector:
'.wc-block-components-checkout-step__description',
},
backgroundSelectors: [
'#payment-method .wc-block-components-radio-control-accordion-option',
'#payment-method',
'form.wc-block-checkout__form',
'.wc-block-checkout',
'body',
],
headingSelectors: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
buttonSelectors: [ '.wc-block-components-checkout-place-order-button' ],
linkSelectors: [ 'a' ],
containerSelectors: [
'.wp-block-woocommerce-checkout-order-summary-block',
],
},
bnplProductPage: {
appendTarget: '.product .cart .quantity',
upeThemeInputSelector: '.product .cart .quantity .qty',
upeThemeLabelSelector: '.product .cart .quantity label',
upeThemeTextSelector: '.product .cart .quantity',
rowElement: 'div',
validClasses: [ 'input-text' ],
invalidClasses: [ 'input-text', 'has-error' ],
backgroundSelectors: [
'#payment-method-message',
'#main > .product > div.summary.entry-summary',
'#main > .product',
'#main',
'body',
],
headingSelectors: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
buttonSelectors: [ '.single_add_to_cart_button' ],
linkSelectors: [ 'a' ],
},
bnplClassicCart: {
appendTarget: '.cart .quantity',
upeThemeInputSelector: '.cart .quantity .qty',
upeThemeLabelSelector: '.cart .quantity label',
upeThemeTextSelector: '.cart .quantity',
rowElement: 'div',
validClasses: [ 'input-text' ],
invalidClasses: [ 'input-text', 'has-error' ],
backgroundSelectors: [
'#payment-method-message',
'#main .entry-content .cart_totals',
'#main .entry-content',
'#main',
'body',
],
headingSelectors: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
buttonSelectors: [ '.checkout-button' ],
linkSelectors: [ 'a' ],
containerSelectors: [ '.shop_table' ],
},
bnplCartBlock: {
appendTarget: '.wc-block-cart .wc-block-components-quantity-selector',
upeThemeInputSelector:
'.wc-block-cart .wc-block-components-quantity-selector .wc-block-components-quantity-selector__input',
upeThemeLabelSelector: '.wc-block-components-text-input',
upeThemeTextSelector: '.wc-block-components-text-input',
rowElement: 'div',
validClasses: [ 'wc-block-components-text-input' ],
invalidClasses: [ 'wc-block-components-text-input', 'has-error' ],
backgroundSelectors: [
'.wc-block-components-bnpl-wrapper',
'.wc-block-components-order-meta',
'.wc-block-components-totals-wrapper',
'.wp-block-woocommerce-cart-order-summary-block',
'.wp-block-woocommerce-cart-totals-block',
'.wp-block-woocommerce-cart .wc-block-cart',
'.wp-block-woocommerce-cart',
'body',
],
headingSelectors: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
buttonSelectors: [ '.wc-block-cart__submit-button' ],
linkSelectors: [ 'a' ],
containerSelectors: [ '.wp-block-woocommerce-cart-line-items-block' ],
},
wooPayClassicCheckout: {
appendTarget: '.woocommerce-billing-fields__field-wrapper',
upeThemeInputSelector: '#billing_first_name',
upeThemeLabelSelector: '.woocommerce-checkout .form-row label',
upeThemeTextSelector: '.woocommerce-checkout .form-row',
rowElement: 'p',
validClasses: [ 'form-row' ],
invalidClasses: [
'form-row',
'woocommerce-invalid',
'woocommerce-invalid-required-field',
],
backgroundSelectors: [
'#customer_details',
'#order_review',
'form.checkout',
'body',
],
headingSelectors: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ],
buttonSelectors: [ '#place_order' ],
linkSelectors: [ 'a' ],
containerSelectors: [ '.woocommerce-checkout-review-order-table' ],
headerSelectors: [ '.site-header' ],
footerSelectors: [ '.site-footer' ],
footerLink: [ '.site-footer a' ],
},
/**
* Update selectors to use alternate if not present on DOM.
*
* @param {Object} selectors Object of selectors for updation.
*
* @return {Object} Updated selectors.
*/
updateSelectors: function ( selectors ) {
if ( selectors.hasOwnProperty( 'alternateSelectors' ) ) {
Object.entries( selectors.alternateSelectors ).forEach(
( altSelector ) => {
const [ key, value ] = altSelector;
if ( ! document.querySelector( selectors[ key ] ) ) {
selectors[ key ] = value;
}
}
);
delete selectors.alternateSelectors;
}
return selectors;
},
/**
* Returns selectors based on checkout type.
*
* @param {boolean} elementsLocation The location of the elements.
*
* @return {Object} Selectors for checkout type specified.
*/
getSelectors: function ( elementsLocation ) {
let appearanceSelector = this.blocksCheckout;
switch ( elementsLocation ) {
case 'blocks_checkout':
appearanceSelector = this.blocksCheckout;
break;
case 'shortcode_checkout':
appearanceSelector = this.classicCheckout;
break;
case 'bnpl_product_page':
appearanceSelector = this.bnplProductPage;
break;
case 'bnpl_classic_cart':
appearanceSelector = this.bnplClassicCart;
break;
case 'bnpl_cart_block':
appearanceSelector = this.bnplCartBlock;
break;
case 'woopay_shortcode_checkout':
appearanceSelector = this.wooPayClassicCheckout;
break;
}
return {
...this.default,
...this.updateSelectors( appearanceSelector ),
};
},
};
const hiddenElementsForUPE = {
/**
* Create hidden container for generating UPE styles.
*
* @param {string} elementID ID of element to create.
*
* @return {Object} Object of the created hidden container element.
*/
getHiddenContainer: function ( elementID ) {
const hiddenDiv = document.createElement( 'div' );
hiddenDiv.setAttribute( 'id', this.getIDFromSelector( elementID ) );
hiddenDiv.style.border = 0;
hiddenDiv.style.clip = 'rect(0 0 0 0)';
hiddenDiv.style.height = '1px';
hiddenDiv.style.margin = '-1px';
hiddenDiv.style.overflow = 'hidden';
hiddenDiv.style.padding = '0';
hiddenDiv.style.position = 'absolute';
hiddenDiv.style.width = '1px';
return hiddenDiv;
},
/**
* Create invalid element row for generating UPE styles.
*
* @param {string} elementType Type of element to create.
* @param {Array} classes Array of classes to be added to the element. Default: empty array.
*
* @return {Object} Object of the created invalid row element.
*/
createRow: function ( elementType, classes = [] ) {
const newRow = document.createElement( elementType );
if ( classes.length ) {
newRow.classList.add( ...classes );
}
return newRow;
},
/**
* Append elements to target container.
*
* @param {Object} appendTarget Element object where clone should be appended.
* @param {string} elementToClone Selector of the element to be cloned.
* @param {string} newElementID Selector for the cloned element.
*/
appendClone: function ( appendTarget, elementToClone, newElementID ) {
const cloneTarget = document.querySelector( elementToClone );
if ( cloneTarget ) {
const clone = cloneTarget.cloneNode( true );
clone.id = this.getIDFromSelector( newElementID );
clone.value = '';
appendTarget.appendChild( clone );
}
},
/**
* Retrieve ID/Class from selector.
*
* @param {string} selector Element selector.
*
* @return {string} Extracted ID/Class from selector.
*/
getIDFromSelector: function ( selector ) {
if ( selector.startsWith( '#' ) || selector.startsWith( '.' ) ) {
return selector.slice( 1 );
}
return selector;
},
/**
* Initialize hidden fields to generate UPE styles.
*
* @param {boolean} elementsLocation The location of the elements.
*/
init: function ( elementsLocation ) {
const selectors = appearanceSelectors.getSelectors( elementsLocation ),
appendTarget = document.querySelector( selectors.appendTarget ),
elementToClone = document.querySelector(
selectors.upeThemeInputSelector
);
// Exit early if elements are not present.
if ( ! appendTarget || ! elementToClone ) {
return;
}
// Remove hidden container is already present on DOM.
if ( document.querySelector( selectors.hiddenContainer ) ) {
this.cleanup();
}
// Create hidden container & append to target.
const hiddenContainer = this.getHiddenContainer(
selectors.hiddenContainer
);
appendTarget.appendChild( hiddenContainer );
// Create hidden valid row & append to hidden container.
const hiddenValidRow = this.createRow(
selectors.rowElement,
selectors.validClasses
);
hiddenContainer.appendChild( hiddenValidRow );
// Create hidden invalid row & append to hidden container.
const hiddenInvalidRow = this.createRow(
selectors.rowElement,
selectors.invalidClasses
);
hiddenContainer.appendChild( hiddenInvalidRow );
// Clone & append target input to hidden valid row.
this.appendClone(
hiddenValidRow,
selectors.upeThemeInputSelector,
selectors.hiddenInput
);
// Clone & append target label to hidden valid row.
this.appendClone(
hiddenValidRow,
selectors.upeThemeLabelSelector,
selectors.hiddenValidActiveLabel
);
// Clone & append target input to hidden invalid row.
this.appendClone(
hiddenInvalidRow,
selectors.upeThemeInputSelector,
selectors.hiddenInvalidInput
);
// Clone & append target label to hidden invalid row.
this.appendClone(
hiddenInvalidRow,
selectors.upeThemeLabelSelector,
selectors.hiddenInvalidInput
);
// Remove transitions & focus on hidden element.
const wcpayHiddenInput = document.querySelector(
selectors.hiddenInput
);
wcpayHiddenInput.style.transition = 'none';
},
/**
* Remove hidden container from DROM.
*/
cleanup: function () {
const element = document.querySelector(
appearanceSelectors.default.hiddenContainer
);
if ( element ) {
element.remove();
}
},
};
export const getFieldStyles = (
selector,
upeElement,
backgroundColor = null
) => {
if ( ! document.querySelector( selector ) ) {
return {};
}
const validProperties = upeRestrictedProperties[ upeElement ];
const elem = document.querySelector( selector );
const styles = window.getComputedStyle( elem );
const filteredStyles = {};
for ( let i = 0; i < styles.length; i++ ) {
const camelCase = dashedToCamelCase( styles[ i ] );
if ( validProperties.includes( camelCase ) ) {
let propertyValue = styles.getPropertyValue( styles[ i ] );
if ( camelCase === 'color' ) {
propertyValue = maybeConvertRGBAtoRGB( propertyValue );
}
filteredStyles[ camelCase ] = propertyValue;
}
}
if ( upeElement === '.Input' || upeElement === '.Tab--selected' ) {
const outline = generateOutlineStyle(
filteredStyles.outlineWidth,
filteredStyles.outlineStyle,
filteredStyles.outlineColor
);
if ( outline !== '' ) {
filteredStyles.outline = outline;
}
delete filteredStyles.outlineWidth;
delete filteredStyles.outlineColor;
delete filteredStyles.outlineStyle;
}
// Workaround for rewriting text-indents to padding-left & padding-right
//since Stripe doesn't support text-indents.
const textIndent = styles.getPropertyValue( 'text-indent' );
if (
textIndent !== '0px' &&
filteredStyles.paddingLeft === '0px' &&
filteredStyles.paddingRight === '0px'
) {
filteredStyles.paddingLeft = textIndent;
filteredStyles.paddingRight = textIndent;
}
if ( upeElement === '.Block' ) {
filteredStyles.backgroundColor = backgroundColor;
}
return filteredStyles;
};
export const getFontRulesFromPage = () => {
const fontRules = [],
sheets = document.styleSheets,
fontDomains = [
'fonts.googleapis.com',
'fonts.gstatic.com',
'fast.fonts.com',
'use.typekit.net',
];
for ( let i = 0; i < sheets.length; i++ ) {
if ( ! sheets[ i ].href ) {
continue;
}
const url = new URL( sheets[ i ].href );
if ( fontDomains.indexOf( url.hostname ) !== -1 ) {
fontRules.push( {
cssSrc: sheets[ i ].href,
} );
}
}
return fontRules;
};
export const getAppearance = ( elementsLocation, forWooPay = false ) => {
const selectors = appearanceSelectors.getSelectors( elementsLocation );
// Add hidden fields to DOM for generating styles.
hiddenElementsForUPE.init( elementsLocation );
const inputRules = getFieldStyles( selectors.hiddenInput, '.Input' );
const inputInvalidRules = getFieldStyles(
selectors.hiddenInvalidInput,
'.Input'
);
const labelRules = getFieldStyles(
selectors.upeThemeLabelSelector,
'.Label'
);
const paragraphRules = getFieldStyles(
selectors.upeThemeTextSelector,
'.Text'
);
const tabRules = getFieldStyles( selectors.upeThemeInputSelector, '.Tab' );
const selectedTabRules = getFieldStyles(
selectors.hiddenInput,
'.Tab--selected'
);
const tabHoverRules = generateHoverRules( tabRules );
const tabIconHoverRules = {
color: tabHoverRules.color,
};
const selectedTabIconRules = {
color: selectedTabRules.color,
};
const backgroundColor = getBackgroundColor( selectors.backgroundSelectors );
const headingRules = getFieldStyles( selectors.headingSelectors, '.Label' );
const blockRules = getFieldStyles(
selectors.upeThemeLabelSelector,
'.Block',
backgroundColor
);
const buttonRules = getFieldStyles( selectors.buttonSelectors, '.Input' );
const linkRules = getFieldStyles( selectors.linkSelectors, '.Label' );
const containerRules = getFieldStyles(
selectors.containerSelectors,
'.Container'
);
const headerRules = getFieldStyles( selectors.headerSelectors, '.Header' );
const footerRules = getFieldStyles( selectors.footerSelectors, '.Footer' );
const footerLinkRules = getFieldStyles(
selectors.footerLink,
'.Footer--link'
);
const globalRules = {
colorBackground: backgroundColor,
colorText: paragraphRules.color,
fontFamily: paragraphRules.fontFamily,
fontSizeBase: paragraphRules.fontSize,
};
const isFloatingLabel = elementsLocation === 'blocks_checkout';
let appearance = {
variables: globalRules,
theme: isColorLight( backgroundColor ) ? 'stripe' : 'night',
labels: isFloatingLabel ? 'floating' : 'above',
// We need to clone the object to avoid modifying other rules when updating the appearance for floating labels.
rules: JSON.parse(
JSON.stringify( {
'.Input': inputRules,
'.Input--invalid': inputInvalidRules,
'.Label': labelRules,
'.Block': blockRules,
'.Tab': tabRules,
'.Tab:hover': tabHoverRules,
'.Tab--selected': selectedTabRules,
'.TabIcon:hover': tabIconHoverRules,
'.TabIcon--selected': selectedTabIconRules,
'.Text': paragraphRules,
'.Text--redirect': paragraphRules,
} )
),
};
if ( isFloatingLabel ) {
appearance = handleAppearanceForFloatingLabel(
appearance,
getFieldStyles(
selectors.hiddenValidActiveLabel,
'.Label--floating'
)
);
}
if ( forWooPay ) {
appearance.rules = {
...appearance.rules,
'.Heading': headingRules,
'.Header': headerRules,
'.Footer': footerRules,
'.Footer-link': footerLinkRules,
'.Button': buttonRules,
'.Link': linkRules,
'.Container': containerRules,
};
}
// Remove hidden fields from DOM.
hiddenElementsForUPE.cleanup();
return appearance;
};