Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 | 1x 28x 1x 7803x 1x 80x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 427x 34x 2297x 18x 2297x 430x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 466x 2297x 430x 2297x 433x 2297x 2297x 2297x 10479x 2297x 2297x 2297x 2297x 2297x 3x 2297x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2297x 101x 40x 2297x 2x 4x 2297x 7x 2x 2297x 4x 2x 2x 2x 2x 2x 1x 2x 2297x 1x 2297x 2297x 2297x 2297x 2297x 430x 430x 430x 2297x 435x 177x 2297x 2297x 2297x 2297x 2297x 2297x 2297x 571x 289x 2297x 2297x 2297x 2297x 431x 2x 2x 2297x 2297x 2297x 2297x 18x 173x 18x 13x 5x 2297x 4x 4x 4x 2297x 2x 2x 2x 2x 2x 2x 1x 2297x 2297x 547x 107x 547x 2297x 2297x 2297x 2297x 427x 92x 2297x 2297x 2297x 2297x 2297x 465x 19x 2297x 2297x 516x 2297x 2297x 8x 8x 5x 5x 3x 1x 3x 8x 2297x 6x 3x 3x 3x 2297x 2x 2x 2x 2x 2x 2297x 5x 5x 2297x 4x 2x 4x 2297x 434x 1863x 4x 1859x 368x 1491x 1491x 2x 1491x 1491x 1491x 1491x 1x 1491x 1491x 1491x 4x 1491x 1x 1491x 105x 7x 1491x 1x 2x 1x 2x 1x 1x 2x 1x 2x 1x 1x 422x 1x 3x 5x 3x 2x 5x 101x 101x 1x 4x 1x 2x 1x 2x 2x 3x 199x 2x 2x 2x 457x 4x 1x 1x 1x 2x 2x 2x 132x 1x 2x 4x 2x 1491x 1491x 162x 1329x 15x 1314x 655x 1491x 1x | /* eslint-disable react/jsx-no-bind */
/**
* PayPal Payment Buttons — API-managed block editor (V2).
*
* When PayPal is connected, merchants fill in product details and create
* buttons directly in the editor. Shown while the API-managed buttons flag is on.
*
* @package
* @since 0.8.0
*/
import { useAnalytics } from '@automattic/jetpack-shared-extension-utils';
import apiFetch from '@wordpress/api-fetch'; // eslint-disable-line import/no-unresolved
import {
BlockControls,
InspectorControls,
MediaUpload,
MediaUploadCheck,
URLInput,
useBlockProps,
} from '@wordpress/block-editor';
import {
BaseControl,
Button,
CheckboxControl,
CustomSelectControl,
Notice,
PanelBody,
SelectControl,
Spinner,
TextControl,
TextareaControl,
ToggleControl,
ToolbarButton,
ToolbarGroup,
} from '@wordpress/components';
import { useDispatch, useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import {
createInterpolateElement,
useState,
useCallback,
useEffect,
useMemo,
useRef,
useSyncExternalStore,
} from '@wordpress/element';
import { __, isRTL, sprintf } from '@wordpress/i18n';
import { chevronLeft, chevronRight } from '@wordpress/icons';
import { Link } from '@wordpress/ui';
import clsx from 'clsx';
import GridiconPlus from 'gridicons/dist/plus-small';
import PayPalAccountHeader from './components/account-header';
import AmountField from './components/amount-field';
import ConfirmDialogs, { UnsavedChangesDialog } from './components/confirm-dialogs';
import ConnectionWizard, { OnboardingFrame } from './components/connection-wizard';
import ExistingLinksStep from './components/existing-links-step';
import PayPalFormatControls from './components/format-controls';
import LegacyBlock from './components/legacy-block';
import LinkDetails from './components/link-details';
import PayPalButtonPreview from './components/paypal-button-preview';
import VariantBuilder, {
getComparisonPrice,
isVariantPricingOn,
validateCustomerNotes,
validateVariants,
} from './components/variant-builder';
import PayPalInspectorControls from './controls';
import { useExistingLinks } from './hooks/use-existing-links';
import { broadcastConnectionChange, usePayPalConnection } from './hooks/use-paypal-connection';
import { usePayPalResource } from './hooks/use-paypal-resource';
import { API_BASE } from './utils/api-base';
import { SUPPORTED_CURRENCIES } from './utils/currencies';
import { CURRENCY_SYMBOLS, getPricePlaceholder, getPriceStep } from './utils/currency-symbols';
import { markExistingLinksDirty, removeExistingLink } from './utils/existing-links';
import { withPartnerAttribution } from './utils/partner-attribution';
import { getPostSaveCount, subscribeToPostSaves } from './utils/register-save-sync';
import {
isSameValue,
PAYMENT_ATTRIBUTES,
PAYPAL_SET_ATTRIBUTES,
RESOURCE_ATTRIBUTES,
resetToDefaults,
turnGateOff,
} from './utils/resource-sync';
import { recordPaymentRead } from './utils/sync-on-save';
import { toast } from './utils/toast';
import {
getUserFriendlyError,
getValidationErrors,
hasBlockingError,
hasCheckoutOptionError,
isNotFound,
MAX_CUSTOMER_NOTES,
MAX_DESCRIPTION_LENGTH,
MAX_NAME_LENGTH,
MAX_PRODUCT_ID_LENGTH,
SHIPPING_MODES_WITH_FEE,
} from './utils/validation';
// Button type is always 'single' — the hosted payment page handles
// payment method selection (PayPal, cards, wallets, etc.).
// What the form edits: the payment's attributes the merchant sets, and the block's
// image, which is sent with them.
const FORM_FIELDS = [
...RESOURCE_ATTRIBUTES.filter( key => ! PAYPAL_SET_ATTRIBUTES.includes( key ) ),
'imageUrl',
'imageId',
];
const formFieldsOf = attributes =>
Object.fromEntries( FORM_FIELDS.map( key => [ key, attributes[ key ] ] ) );
// Touched marks key on the row index. A stable `_key` would make every mount report a
// change, since resource-sync.js strips `_key` from variants only.
const NOTE_KEY_PREFIX = 'customerNote:';
const noteFieldKey = noteIndex => `${ NOTE_KEY_PREFIX }${ noteIndex }`;
const helpQuantity = __( 'Fixed at 1 unit per purchase', 'jetpack-paypal-payments' );
// The minifier folds a ternary between two __() calls into one non-literal msgid and
// i18n-check-webpack-plugin then rejects the build, so each branch gets its own const.
const placeholderTaxRate = __( 'Enter tax rate', 'jetpack-paypal-payments' );
const placeholderTaxValue = __( 'Enter tax value', 'jetpack-paypal-payments' );
// FLAT and PERCENTAGE are PayPal's own values, so the select writes them straight to
// the attribute. CustomSelectControl renders each option's hint as a second line.
const DISCOUNT_TYPES = [
{
key: 'FLAT',
name: __( 'Amount off', 'jetpack-paypal-payments' ),
hint: __( 'Fixed amount off the price', 'jetpack-paypal-payments' ),
},
{
key: 'PERCENTAGE',
name: __( 'Percentage', 'jetpack-paypal-payments' ),
hint: __( 'Percentage based on price', 'jetpack-paypal-payments' ),
},
];
// Both selects write taxType.
const TAX_TYPE_PROFILE = {
key: 'profile',
name: __( 'Use tax from my PayPal settings', 'jetpack-paypal-payments' ),
};
const TAX_TYPE_SPECIFIC = {
key: 'specific',
name: __( 'Use a specific tax rate', 'jetpack-paypal-payments' ),
};
const TAX_TYPES = [ TAX_TYPE_PROFILE, TAX_TYPE_SPECIFIC ];
const TAX_RATE_TYPES = [
{ key: 'PERCENTAGE', name: __( 'Percentage', 'jetpack-paypal-payments' ) },
{ key: 'FLAT', name: __( 'Amount', 'jetpack-paypal-payments' ) },
];
// PayPal's tax settings page, per environment.
const TAX_PROFILE_URL = {
sandbox: 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_profile-sales-tax',
production: 'https://www.paypal.com/cgi-bin/webscr?cmd=_profile-sales-tax',
};
// PayPal's shipping settings page, per environment. Its own cgi-bin script,
// separate from the tax one.
const SHIPPING_PROFILE_URL = {
sandbox: 'https://www.sandbox.paypal.com/cgi-bin/customerprofileweb?cmd=_profile-shipping',
production: 'https://www.paypal.com/cgi-bin/customerprofileweb?cmd=_profile-shipping',
};
// Editor modes. buildShipping() maps them onto PayPal's two types: PROFILE and FREE
// send PREFERENCE, FLAT and QUANTITY send FLAT.
const SHIPPING_MODES = [
{
key: 'PROFILE',
name: __( 'Use shipping from my PayPal settings', 'jetpack-paypal-payments' ),
},
{ key: 'QUANTITY', name: __( 'Use quantity-based shipping fee', 'jetpack-paypal-payments' ) },
{ key: 'FLAT', name: __( 'Use specific shipping fee', 'jetpack-paypal-payments' ) },
{ key: 'FREE', name: __( 'Free shipping', 'jetpack-paypal-payments' ) },
];
// The address checkbox swaps its help when a profile tax makes it mandatory.
const helpAddress = __(
'Requires customer to add shipping address during checkout',
'jetpack-paypal-payments'
);
const helpAddressWithProfileTax = __(
'Required while the tax comes from your PayPal settings.',
'jetpack-paypal-payments'
);
// Own const per branch, same i18n reason as the tax placeholders above: the first
// amount field's label changes with the mode.
const labelShippingFirstItem = __( 'Shipping fee for first item', 'jetpack-paypal-payments' );
const labelShippingFee = __( 'Enter shipping fee', 'jetpack-paypal-payments' );
/**
* API-managed PayPal Payment Buttons edit component.
*
* @param {object} props - Block props.
* @param {object} props.attributes - Block attributes.
* @param {Function} props.setAttributes - Function to update block attributes.
* @param {string} props.clientId - The block's client id, renamed because
* usePayPalConnection() returns PayPal's own clientId.
* @param {boolean} props.isSelected - Whether this block is the selected one.
* @return {Element} Block editor UI.
*/
export default function ApiManagedEdit( {
attributes,
setAttributes,
clientId: blockClientId,
isSelected,
} ) {
const {
isApiManaged,
scriptSrc,
hostedButtonId,
buttonText,
linkText,
resourceId,
paymentLink,
productName,
price,
currencyCode,
productDescription,
productId,
imageUrl,
imageId,
returnUrl,
variantsEnabled,
variants,
adjustableQuantity,
maxQuantity,
customerNotes,
taxEnabled,
taxType,
taxValue,
handlingEnabled,
handlingValue,
discountEnabled,
discountType,
discountValue,
shippingEnabled,
shippingMode,
shippingValue,
shippingAdditionalValue,
collectShippingAddress,
format,
qrShowCaption,
qrCaption,
} = attributes;
// Normalize — old blocks without the attribute default to BUTTON.
const activeFormat = format || 'BUTTON';
// PayPal rejects any decimal in JPY, HUF and TWD, so the input must not offer one.
const priceStep = getPriceStep( currencyCode || 'USD' );
const pricePlaceholder = getPricePlaceholder( currencyCode || 'USD' );
const currencySymbol = CURRENCY_SYMBOLS[ currencyCode || 'USD' ] || currencyCode || 'USD';
const blockProps = useBlockProps();
// Identifies this bundle's Tracks events with the connected user.
useAnalytics();
const {
isConnected,
setIsConnected,
environment,
setEnvironment,
connectionLoading,
partnerAttributionId,
accountEmail,
showReconnect,
setShowReconnect,
signupUrl,
setOnboardingRequested,
isOverlayOpen,
isOpeningPayPal,
setFrameNode,
clientId,
clientSecret,
connectError,
setConnectError,
connectErrorDismissed,
setConnectErrorDismissed,
isConnecting,
isCompletingOnboarding,
wizardStep,
setWizardStep,
showSecretField,
setShowSecretField,
partnerReferralsAvailable,
handleClientIdChange,
handleClientSecretChange,
clientIdWarning,
handleConnect,
fetchSignupLink,
cancelOnboarding,
} = usePayPalConnection();
// One string with the link inside it so translators keep the sentence order.
const taxProfileHint = createInterpolateElement(
__(
'This will be applied when the customer enters their address. <TaxSettingsLink>Set up or manage tax settings</TaxSettingsLink>',
'jetpack-paypal-payments'
),
{
TaxSettingsLink: (
<Link openInNewTab href={ TAX_PROFILE_URL[ environment ] || TAX_PROFILE_URL.production } />
),
}
);
const shippingProfileHint = createInterpolateElement(
__(
'This will be applied when the customer enters their address. <ShippingSettingsLink>Set up or manage shipping settings</ShippingSettingsLink>',
'jetpack-paypal-payments'
),
{
ShippingSettingsLink: (
<Link
openInNewTab
href={ SHIPPING_PROFILE_URL[ environment ] || SHIPPING_PROFILE_URL.production }
/>
),
}
);
// Confirmation dialog state for destructive actions.
const [ showDeleteConfirm, setShowDeleteConfirm ] = useState( false );
const [ showDisconnectConfirm, setShowDisconnectConfirm ] = useState( false );
const [ showLogOutConfirm, setShowLogOutConfirm ] = useState( false );
// Inline validation state — track which fields have been touched.
//
// A note row that opens blank gets marked touched up front, so its error shows
// without a blur. A block saved that way has no resourceId, so hasButton misses it.
const [ touchedFields, setTouchedFields ] = useState( () =>
Object.fromEntries(
( attributes.customerNotes || [] )
.map( ( note, i ) => ( note.label?.trim() ? null : [ noteFieldKey( i ), true ] ) )
.filter( Boolean )
)
);
/**
* Mark a field as touched (user has interacted with it).
*
* @param {string} field - Field name.
*/
const markTouched = useCallback( field => {
setTouchedFields( prev => ( { ...prev, [ field ]: true } ) );
}, [] );
/**
* Whether per-variant pricing is turned on.
*
* The product price field goes as soon as the toggle is on, before any option price
* is typed. The request itself keys on the prices, in utils/sync-on-save.js.
*/
const variantPricingOn = useMemo(
() => isVariantPricingOn( variantsEnabled, variants ),
[ variantsEnabled, variants ]
);
const taxHasValue = ( taxType || 'PERCENTAGE' ) !== 'PREFERENCE';
const taxIsPercentage = ( taxType || 'PERCENTAGE' ) === 'PERCENTAGE';
// PayPal rejects a payment that takes its tax from the profile and collects no
// address, so the checkbox is locked on for as long as that tax type is picked.
const addressIsRequired = !! taxEnabled && ! taxHasValue;
const discountIsPercentage = ( discountType || 'FLAT' ) === 'PERCENTAGE';
const activeShippingMode = shippingMode || 'FLAT';
const shippingHasFee = SHIPPING_MODES_WITH_FEE.includes( activeShippingMode );
const comparisonPrice = getComparisonPrice( variantPricingOn, variants, price );
/**
* Compute validation errors for all form fields.
* Memoized to avoid re-computing on every render.
*/
const validationErrors = useMemo(
() => getValidationErrors( { ...attributes, variantPricingOn, comparisonPrice } ),
[ attributes, variantPricingOn, comparisonPrice ]
);
/**
* Variant validation errors (empty array if valid or disabled).
*/
const variantErrors = useMemo(
() => validateVariants( variantsEnabled, variants, currencyCode || 'USD' ),
[ variantsEnabled, variants, currencyCode ]
);
/**
* Customer note errors, one per row with a blank label (empty array if valid).
*/
const customerNoteErrors = useMemo(
() => validateCustomerNotes( customerNotes ),
[ customerNotes ]
);
/**
* Whether the block has a created button to preview.
*/
const hasButton = !! ( isApiManaged && resourceId && paymentLink );
// A paste-code block, drawn by LegacyBlock.
const isLegacy = ! isApiManaged && !! ( scriptSrc || hostedButtonId );
/**
* Show a field's error once the merchant leaves it, or right away on a saved
* button - the same rule as noteErrorFor() below and VariantBuilder's showAll.
*
* @param {string} field - Attribute name.
* @return {string|undefined} The message, or undefined while it is still hidden.
*/
const errorFor = field =>
hasButton || touchedFields[ field ] ? validationErrors[ field ] : undefined;
// The price field only hides while per-variant pricing is on, so seeing it with product
// options on means the merchant has been in the pricing UI - say what is wrong rather
// than wait for a blur on a field they never asked for.
const priceError = variantsEnabled ? validationErrors.price : errorFor( 'price' );
const returnUrlError = errorFor( 'returnUrl' );
// Valid once every field, option group and customer note is free of errors.
const isFormValid =
! hasBlockingError( validationErrors ) &&
variantErrors.length === 0 &&
customerNoteErrors.length === 0;
const {
resource,
isBusy,
linkDeleted,
paymentChanged,
dismissPaymentChanged,
handleDeleteButton,
executeDeleteButton,
} = usePayPalResource( {
attributes,
setAttributes,
isConnected,
clientId: blockClientId,
setShowDeleteConfirm,
} );
/**
* Handle PayPal disconnect with confirmation.
* Triggers a ConfirmDialog — actual disconnect runs in executeDisconnect().
*/
const handleDisconnect = useCallback( () => {
setShowDisconnectConfirm( true );
}, [] );
/**
* Execute the PayPal disconnect after the user confirms.
*/
const executeDisconnect = useCallback( () => {
setShowDisconnectConfirm( false );
const doDisconnect = () => {
setIsConnected( false );
setWizardStep( 'welcome' );
setShowReconnect( false );
broadcastConnectionChange( false );
// Clear block attributes so the block shows the connect wizard.
setAttributes( {
// Back to block.json defaults, so reconnecting starts the next payment clean.
...resetToDefaults( ...PAYMENT_ATTRIBUTES ),
// The image is block-owned and has no default to read.
imageUrl: undefined,
imageId: undefined,
} );
toast( 'success', __( 'PayPal account disconnected.', 'jetpack-paypal-payments' ) );
};
apiFetch( {
path: `${ API_BASE }/disconnect`,
method: 'POST',
} )
.then( doDisconnect )
.catch( doDisconnect ); // Still disconnect locally if API fails.
}, [ setAttributes, setIsConnected, setShowReconnect, setWizardStep ] );
/**
* Show a row's error once the merchant leaves the field, or right away on a saved
* button - the same rule as VariantBuilder's showAll.
*
* @param {number} noteIndex - Which row.
* @return {string|undefined} The message, or undefined while it is still hidden.
*/
const noteErrorFor = noteIndex =>
hasButton || touchedFields[ noteFieldKey( noteIndex ) ]
? customerNoteErrors.find( e => e.index === noteIndex )?.message
: undefined;
/**
* Patch one note row.
*
* @param {number} noteIndex - Which row.
* @param {object} patch - The fields to change.
*/
const updateNote = ( noteIndex, patch ) => {
setAttributes( {
customerNotes: customerNotes.map( ( note, i ) =>
i === noteIndex ? { ...note, ...patch } : note
),
} );
};
/**
* Every touched mark except the note ones.
*
* @param {object} marks - The current touchedFields.
* @return {object} The same marks with the note rows removed.
*/
const withoutNoteMarks = marks =>
Object.fromEntries(
Object.entries( marks ).filter( ( [ key ] ) => ! key.startsWith( NOTE_KEY_PREFIX ) )
);
/**
* Drop a note row and shift the touched marks down with it, so the next row keeps
* its own mark.
*
* @param {number} noteIndex - Which row.
*/
const removeNote = noteIndex => {
const remaining = customerNotes.filter( ( _, i ) => i !== noteIndex );
setAttributes( { customerNotes: remaining } );
setTouchedFields( prev => {
const next = withoutNoteMarks( prev );
remaining.forEach( ( _, i ) => {
if ( prev[ noteFieldKey( i < noteIndex ? i : i + 1 ) ] ) {
next[ noteFieldKey( i ) ] = true;
}
} );
return next;
} );
};
/**
* Add an empty note row.
*/
const addNote = () => {
setAttributes( {
customerNotes: [ ...customerNotes, { label: '', required: false } ],
} );
};
// A saved link opens on its details; the form is a menu click away. A link
// with something to fix opens on the form instead, or the error would be
// hidden behind a view that cannot show it. Decided once, as the block first
// sees the link - re-reading validity every render would pull the form away
// on the keystroke that fixes the error.
const formIsValid = useRef( isFormValid );
formIsValid.current = isFormValid;
const [ isEditing, setIsEditing ] = useState( ! isFormValid );
// A saved link can be switched for another of the account's links from its
// details menu. A new link, however it arrived, closes the picker.
const [ isSwitching, setIsSwitching ] = useState( false );
useEffect( () => {
setIsEditing( ! formIsValid.current );
setIsSwitching( false );
setShowUnsavedConfirm( false );
}, [ resourceId ] );
// An undo, or a read writing back a value that fails validation, can break the
// link later on, and the details have nowhere to show it. Opening only, so the
// form stays put while the merchant works through the error.
useEffect( () => {
if ( ! isFormValid ) {
setIsEditing( true );
}
}, [ isFormValid ] );
const showDetails = hasButton && ! isEditing;
const showSwitch = hasButton && isSwitching;
// The form's fields as last opened or saved, so leaving with them changed can ask
// first. Retaken when PayPal's own values come in while the form is open.
const formOpenedWith = useRef( null );
const latestAttributes = useRef( attributes );
latestAttributes.current = attributes;
const postSaves = useSyncExternalStore( subscribeToPostSaves, getPostSaveCount );
useEffect( () => {
if ( isEditing ) {
formOpenedWith.current = formFieldsOf( latestAttributes.current );
}
}, [ isEditing, paymentChanged, postSaves ] );
const [ showUnsavedConfirm, setShowUnsavedConfirm ] = useState( false );
// A post save while the dialog is open saves the changes it asks about, so leave.
const dialogOpen = useRef( showUnsavedConfirm );
dialogOpen.current = showUnsavedConfirm;
useEffect( () => {
if ( dialogOpen.current ) {
setShowUnsavedConfirm( false );
setIsEditing( false );
}
}, [ postSaves ] );
const [ isSavingFromModal, setIsSavingFromModal ] = useState( false );
// savePost() returns at once while another save runs, so the dialog's buttons stay
// disabled until it ends.
const isSavingPost = useSelect( select => select( editorStore ).isSavingPost(), [] );
const { savePost } = useDispatch( editorStore );
/**
* Back from the form to the details, asking first when there is something to lose.
* Compared on the click, since the snapshot is retaken in an effect after the render.
*/
const leaveForm = () => {
const hasUnsavedChanges = FORM_FIELDS.some(
key => ! isSameValue( key, attributes[ key ], formOpenedWith.current[ key ] )
);
if ( hasUnsavedChanges ) {
setShowUnsavedConfirm( true );
} else {
setIsEditing( false );
}
};
/**
* Put the form back as it was last opened, saved or read from PayPal, and leave.
*/
const discardChanges = () => {
setAttributes( formOpenedWith.current );
setShowUnsavedConfirm( false );
setIsEditing( false );
};
/**
* Save the post, which writes the payment to PayPal on the way, and leave once
* it is saved. The editor reports the save and anything that went wrong in it.
*/
const saveChanges = async () => {
const saves = getPostSaveCount();
setIsSavingFromModal( true );
await savePost();
setIsSavingFromModal( false );
setShowUnsavedConfirm( false );
// savePost() resolves on a failed save too, so leave only if the save count went up.
if ( getPostSaveCount() > saves ) {
setIsEditing( false );
}
};
// The changed-at-PayPal warning is done once the merchant leaves the details
// screen it was raised on. Keyed to that screen rather than to selection, which
// drops the sidebar on any click elsewhere in the post and would clear a warning
// still unread.
const detailsWasShown = useRef( showDetails );
useEffect( () => {
if ( detailsWasShown.current && ! showDetails ) {
dismissPaymentChanged();
}
detailsWasShown.current = showDetails;
}, [ showDetails, dismissPaymentChanged ] );
// A block with nothing in it yet opens on the links the account already has,
// and the step is skipped when there are none. Decided once, as the block mounts:
// the form leaves the picker by choice, and comes back to it the same way.
const startedEmpty = useRef( ! hasButton && ! productName && ! price ).current;
const [ showPicker, setShowPicker ] = useState( startedEmpty );
const [ isPicking, setIsPicking ] = useState( false );
// A new block reads the list again, for links made in wp-admin or another tab.
useEffect( () => {
if ( startedEmpty && ! isLegacy ) {
markExistingLinksDirty();
}
}, [ startedEmpty, isLegacy ] );
// The picker: the first step of a new link, or Change item on a saved one.
const pickerShown = isConnected && ! isLegacy && ( ( showPicker && ! hasButton ) || showSwitch );
// A shown picker reads the list even when deselected, for its hint on the canvas.
// Other blocks wait until selected, since every block on the canvas mounts this.
const {
links: existingLinks,
isLoading: linksLoading,
deleteLink,
isDeleting,
} = useExistingLinks( {
enabled: pickerShown || ( isConnected && ! isLegacy && isSelected ),
showing: pickerShown,
} );
const showLinkStep =
isConnected && ! hasButton && showPicker && ( linksLoading || existingLinks.length > 0 );
// With no link to offer, skip the step for good, as Create new does, so the form
// stays put when another block creates a link.
const skipsLinkStep = isConnected && ! hasButton && showPicker && ! showLinkStep;
useEffect( () => {
if ( skipsLinkStep ) {
setShowPicker( false );
}
}, [ skipsLinkStep ] );
// The form of a new link can go back to the picker, once there are links to pick from.
const canReturnToPicker = ! hasButton && ! showPicker && existingLinks.length > 0;
const otherLinks = useMemo(
() => existingLinks.filter( link => link.id !== resourceId ),
[ existingLinks, resourceId ]
);
const canChangeLink = isConnected && ! isBusy && ( linksLoading || otherLinks.length > 0 );
/**
* Read a link back from PayPal and hand its attributes on.
*
* @param {object} link - A payment resource from the list.
* @param {Function} apply - Receives the attributes PayPal holds for it.
*/
const readLink = useCallback( ( link, apply ) => {
setIsPicking( true );
apiFetch( { path: `${ API_BASE }/buttons/${ link.id }` } )
.then( response => {
Eif ( response?.attributes ) {
apply( response.attributes );
}
} )
.catch( err => {
// Gone from PayPal, so drop it from every block's picker.
if ( isNotFound( err ) ) {
removeExistingLink( link.id );
}
toast( 'error', getUserFriendlyError( err ) );
} )
.finally( () => setIsPicking( false ) );
}, [] );
/**
* Point the block at an existing link, with the attributes PayPal holds for it.
*
* @param {object} link - A payment resource from the list.
*/
const pickExistingLink = useCallback(
link =>
readLink( link, linkAttributes => {
// The block just read the payment, so the save can write it without a second fetch.
recordPaymentRead( blockClientId, link.id, linkAttributes );
// The read only carries what the payment has, so what the last link had
// goes back to its default first. The image stays: it belongs to the block.
setAttributes( {
...resetToDefaults( ...RESOURCE_ATTRIBUTES ),
isApiManaged: true,
resourceId: link.id,
...linkAttributes,
} );
toast( 'success', __( 'Payment link updated.', 'jetpack-paypal-payments' ) );
} ),
[ blockClientId, readLink, setAttributes ]
);
/**
* Open the form with a copy of an existing link. The copy has no payment of its
* own until the post is saved, which creates one.
*
* @param {object} link - A payment resource from the list.
*/
const duplicateLink = useCallback(
link =>
readLink( link, linkAttributes => {
const {
isApiManaged: _api,
resourceId: _id,
paymentLink: _link,
scriptSrc: _script,
integrationMode: _mode,
...copied
} = linkAttributes;
// Named as a copy, so it reads as one next to the original in the list and
// on PayPal. Cut to the limit rather than open the form on an error.
const copyName = copied.productName
? sprintf(
/* translators: %s: the product name of the link being copied */
__( 'Copy of %s', 'jetpack-paypal-payments' ),
copied.productName
).slice( 0, MAX_NAME_LENGTH )
: '';
// Let go of any payment the block points at, so the save creates a new one.
setAttributes( {
...resetToDefaults( ...PAYMENT_ATTRIBUTES ),
...copied,
productName: copyName,
} );
setShowPicker( false );
} ),
[ readLink, setAttributes ]
);
/**
* Leave the form for the picker. Whatever was typed or copied goes, along with any
* payment the block points at, so Create new opens empty again.
*/
const returnToPicker = useCallback( () => {
setAttributes( {
...resetToDefaults( ...PAYMENT_ATTRIBUTES ),
imageUrl: undefined,
imageId: undefined,
} );
setShowPicker( true );
}, [ setAttributes ] );
/**
* Leave the picker for an empty form. A pick read back with an empty link still
* sets resourceId, so clear the payment first.
*/
const createNew = useCallback( () => {
if ( resourceId ) {
setAttributes( resetToDefaults( ...PAYMENT_ATTRIBUTES ) );
}
setShowPicker( false );
}, [ resourceId, setAttributes ] );
// Loading state while checking connection.
if ( connectionLoading ) {
return (
<div { ...blockProps }>
<div className="jetpack-paypal-payment-buttons__loading">
<Spinner />
<p>{ __( 'Checking PayPal connection…', 'jetpack-paypal-payments' ) }</p>
</div>
</div>
);
}
// Legacy paste-code block — render as-is without the new UI.
if ( isLegacy ) {
return (
<LegacyBlock
setAttributes={ setAttributes }
buttonText={ buttonText }
blockProps={ blockProps }
/>
);
}
// Not connected — the canvas says what the block is for and the sidebar
// carries the connection wizard. A block that already holds a saved button
// keeps showing its preview instead (e.g. demo posts in Playground, or a
// button created before the site was disconnected), unless the merchant
// explicitly asked to reconnect.
if ( ! isConnected && ( ! hasButton || showReconnect ) ) {
return (
<div { ...blockProps }>
<div className="jetpack-paypal-payment-buttons__placeholder">
<h4>{ __( 'PayPal Payment Button', 'jetpack-paypal-payments' ) }</h4>
<p>
{ __(
'Log in to or create a PayPal business account to use payment buttons',
'jetpack-paypal-payments'
) }
</p>
</div>
<OnboardingFrame
signupUrl={ signupUrl }
isOverlayOpen={ isOverlayOpen }
setFrameNode={ setFrameNode }
cancelOnboarding={ cancelOnboarding }
/>
<InspectorControls>
<ConnectionWizard
setIsConnected={ setIsConnected }
environment={ environment }
setEnvironment={ setEnvironment }
showReconnect={ showReconnect }
setShowReconnect={ setShowReconnect }
signupUrl={ signupUrl }
setOnboardingRequested={ setOnboardingRequested }
isOpeningPayPal={ isOpeningPayPal }
clientId={ clientId }
clientSecret={ clientSecret }
connectError={ connectError }
setConnectError={ setConnectError }
connectErrorDismissed={ connectErrorDismissed }
setConnectErrorDismissed={ setConnectErrorDismissed }
isConnecting={ isConnecting }
isCompletingOnboarding={ isCompletingOnboarding }
wizardStep={ wizardStep }
setWizardStep={ setWizardStep }
showSecretField={ showSecretField }
setShowSecretField={ setShowSecretField }
partnerReferralsAvailable={ partnerReferralsAvailable }
handleClientIdChange={ handleClientIdChange }
handleClientSecretChange={ handleClientSecretChange }
clientIdWarning={ clientIdWarning }
handleConnect={ handleConnect }
fetchSignupLink={ fetchSignupLink }
/>
</InspectorControls>
</div>
);
}
// Toolbar control to delete the payment button.
const toolbarControls = hasButton ? (
<BlockControls>
<ToolbarGroup>
<ToolbarButton
icon="trash"
label={ __( 'Delete payment link', 'jetpack-paypal-payments' ) }
onClick={ handleDeleteButton }
disabled={ isBusy || ! isConnected }
isDestructive
/>
</ToolbarGroup>
</BlockControls>
) : null;
// The account header replaces core's block card. A block can still hold a button
// after a site-wide disconnect, and there the canvas offers Reconnect instead.
const accountHeader = isConnected ? (
<PayPalAccountHeader
isSelected={ isSelected }
environment={ environment }
accountEmail={ accountEmail }
onLogOut={ () => setShowLogOutConfirm( true ) }
/>
) : null;
// The connection panel sits last in the Settings tab, under whichever view is showing.
const connectionPanel = (
<PayPalInspectorControls
isConnected={ isConnected }
environment={ environment }
setShowReconnect={ setShowReconnect }
isBusy={ isBusy }
handleDeleteButton={ handleDeleteButton }
handleDisconnect={ handleDisconnect }
hasButton={ hasButton }
/>
);
// The Styles tab — Embed as and the format's own controls — is a fill of its own.
// Only once there is a link, so the editor hides the tab bar until then.
const formatControls = hasButton ? (
<PayPalFormatControls
format={ activeFormat }
attributes={ attributes }
setAttributes={ setAttributes }
paymentUrl={ linkDeleted ? '' : withPartnerAttribution( paymentLink, partnerAttributionId ) }
disabled={ isBusy }
environment={ environment }
/>
) : null;
// Shared confirmation dialogs — extracted so they render regardless of which return branch is active.
const confirmDialogs = (
<ConfirmDialogs
showDeleteConfirm={ showDeleteConfirm }
setShowDeleteConfirm={ setShowDeleteConfirm }
showDisconnectConfirm={ showDisconnectConfirm }
setShowDisconnectConfirm={ setShowDisconnectConfirm }
showLogOutConfirm={ showLogOutConfirm }
setShowLogOutConfirm={ setShowLogOutConfirm }
executeDeleteButton={ executeDeleteButton }
executeDisconnect={ executeDisconnect }
/>
);
// The PayPal connection is site-wide, so a block can still hold a working
// button after the account was disconnected — from this post, another post,
// or the admin. The button keeps paying out; only editing it needs the
// connection back, so say so instead of failing on save.
const disconnectedNotice = ! isConnected ? (
<Notice
status="warning"
isDismissible={ false }
actions={ [
{
label: __( 'Reconnect PayPal', 'jetpack-paypal-payments' ),
onClick: () => setShowReconnect( true ),
variant: 'primary',
},
] }
>
{ __(
'Your PayPal account is disconnected. This payment link still works for buyers, but you need to reconnect before you can edit or delete it.',
'jetpack-paypal-payments'
) }
</Notice>
) : null;
// A payment link can be shared by blocks on any post, so warn whenever there is one.
const sharedResourceNotice = hasButton ? (
<p className="jetpack-paypal-payment-buttons__shared-link-note">
{ __(
'Changes made will apply to all payment buttons with this link.',
'jetpack-paypal-payments'
) }
</p>
) : null;
// Both screens show this, at the top of the sidebar: the warning belongs to the
// link, and the read that raises it comes in while the details are showing.
const paymentChangedNotice = paymentChanged ? (
<Notice status="warning" isDismissible={ false }>
{ __(
'This payment link was updated elsewhere and this block has been updated to match. Save the post so this page shows the change.',
'jetpack-paypal-payments'
) }
</Notice>
) : null;
const linkStep = (
<ExistingLinksStep
links={ existingLinks }
isLoading={ linksLoading }
onCreateNew={ createNew }
onPick={ pickExistingLink }
onDuplicate={ duplicateLink }
onDelete={ link => deleteLink( link.id ) }
isBusy={ isPicking || isDeleting }
/>
);
// The same picker, minus Create new and the link the block already has.
const switchView = (
<>
<div className="jetpack-paypal-payment-buttons__form-actions">
<Button
icon={ isRTL() ? chevronRight : chevronLeft }
onClick={ () => setIsSwitching( false ) }
className="jetpack-paypal-payment-buttons__back-to-details"
>
{ __( 'Change item', 'jetpack-paypal-payments' ) }
</Button>
</div>
<ExistingLinksStep
links={ otherLinks }
isLoading={ linksLoading }
onPick={ pickExistingLink }
isBusy={ isPicking }
/>
</>
);
const detailsView = (
<LinkDetails
attributes={ attributes }
resource={ resource }
notices={ paymentChangedNotice }
onEdit={ () => setIsEditing( true ) }
onChangeLink={ () => setIsSwitching( true ) }
canChangeLink={ canChangeLink }
/>
);
const formPanels = (
<>
{ /* Form-wide notices go here. A field's own notice renders next to that field. */ }
{ ( hasButton || paymentChanged || canReturnToPicker ) && (
<div className="jetpack-paypal-payment-buttons__form-actions">
{ /* Plain, so the back link keeps the sidebar's own foreground -
`tertiary` would paint it the admin accent. */ }
{ hasButton && (
<Button
icon={ isRTL() ? chevronRight : chevronLeft }
onClick={ leaveForm }
className="jetpack-paypal-payment-buttons__back-to-details"
>
{ __( 'Edit Button', 'jetpack-paypal-payments' ) }
</Button>
) }
{ canReturnToPicker && (
<Button
icon={ isRTL() ? chevronRight : chevronLeft }
onClick={ returnToPicker }
className="jetpack-paypal-payment-buttons__back-to-details"
>
{ __( 'New payment link', 'jetpack-paypal-payments' ) }
</Button>
) }
{ sharedResourceNotice }
{ paymentChangedNotice }
</div>
) }
<PanelBody title={ __( 'Details', 'jetpack-paypal-payments' ) } initialOpen={ true }>
<TextControl
label={ __( 'Product Name', 'jetpack-paypal-payments' ) }
value={ productName || '' }
onChange={ value => setAttributes( { productName: value } ) }
onBlur={ () => markTouched( 'productName' ) }
disabled={ isBusy }
placeholder={ __( 'e.g., Premium Widget', 'jetpack-paypal-payments' ) }
help={
errorFor( 'productName' ) ||
sprintf(
/* translators: 1: current character count, 2: maximum allowed */
__( '%1$d / %2$d characters', 'jetpack-paypal-payments' ),
( productName || '' ).length,
MAX_NAME_LENGTH
)
}
className={
errorFor( 'productName' ) ? 'jetpack-paypal-payment-buttons__has-error' : undefined
}
/>
<div className="jetpack-paypal-payment-buttons__price-row">
{ ! variantPricingOn && (
<div>
<TextControl
label={ __( 'Price', 'jetpack-paypal-payments' ) }
value={ price || '' }
onChange={ value => setAttributes( { price: value } ) }
onBlur={ () => markTouched( 'price' ) }
disabled={ isBusy }
type="number"
min={ priceStep }
step={ priceStep }
placeholder={ pricePlaceholder }
help={ priceError || undefined }
className={ priceError ? 'jetpack-paypal-payment-buttons__has-error' : undefined }
/>
</div>
) }
{ /* No touched-gate, for the same reason the tax rate has none: the menu
only offers currencies PayPal takes, so a bad one arrived from a
paste or an older block and there is no visit coming to wait for. */ }
<SelectControl
label={ __( 'Currency', 'jetpack-paypal-payments' ) }
value={ currencyCode || 'USD' }
options={ SUPPORTED_CURRENCIES }
onChange={ value => setAttributes( { currencyCode: value } ) }
help={ validationErrors.currencyCode || undefined }
className={
validationErrors.currencyCode
? 'jetpack-paypal-payment-buttons__has-error'
: undefined
}
/>
</div>
<TextareaControl
label={ __( 'Description (optional)', 'jetpack-paypal-payments' ) }
value={ productDescription || '' }
onChange={ value => setAttributes( { productDescription: value } ) }
onBlur={ () => markTouched( 'productDescription' ) }
help={
errorFor( 'productDescription' ) || (
<>
{ __( 'Shown to customers at checkout.', 'jetpack-paypal-payments' ) }
<br />
{ sprintf(
/* translators: 1: current character count, 2: maximum allowed */
__( '%1$d / %2$d characters', 'jetpack-paypal-payments' ),
// Trim first: validateDescription() and the server both measure the trimmed length.
( productDescription || '' ).trim().length,
MAX_DESCRIPTION_LENGTH
) }
</>
)
}
className={
errorFor( 'productDescription' )
? 'jetpack-paypal-payment-buttons__has-error'
: undefined
}
/>
<div className="jetpack-paypal-payment-buttons__image-field">
<BaseControl.VisualLabel>
{ __( 'Product Image (optional)', 'jetpack-paypal-payments' ) }
</BaseControl.VisualLabel>
{ imageUrl ? (
<div className="jetpack-paypal-payment-buttons__image-preview">
<img src={ imageUrl } alt={ productName || '' } />
{ ! /^https:\/\//i.test( imageUrl ) && (
<Notice status="warning" isDismissible={ false }>
{ __(
'PayPal only shows images served from a public HTTPS address, so this one will not appear at checkout.',
'jetpack-paypal-payments'
) }
</Notice>
) }
<div className="jetpack-paypal-payment-buttons__image-actions">
<MediaUploadCheck>
<MediaUpload
onSelect={ media =>
setAttributes( { imageUrl: media.url, imageId: media.id } )
}
allowedTypes={ [ 'image' ] }
value={ imageId }
render={ ( { open } ) => (
<Button variant="secondary" onClick={ open } size="small">
{ __( 'Replace', 'jetpack-paypal-payments' ) }
</Button>
) }
/>
</MediaUploadCheck>
<Button
variant="link"
isDestructive
onClick={ () => setAttributes( { imageUrl: undefined, imageId: undefined } ) }
size="small"
>
{ __( 'Remove', 'jetpack-paypal-payments' ) }
</Button>
</div>
</div>
) : (
<MediaUploadCheck>
<MediaUpload
onSelect={ media => setAttributes( { imageUrl: media.url, imageId: media.id } ) }
allowedTypes={ [ 'image' ] }
value={ imageId }
render={ ( { open } ) => (
<Button
variant="secondary"
onClick={ open }
className="jetpack-paypal-payment-buttons__upload-button"
>
{ __( 'Upload Image', 'jetpack-paypal-payments' ) }
</Button>
) }
/>
</MediaUploadCheck>
) }
</div>
</PanelBody>
{ /* A closed panel renders no children, so open it when an option needs
fixing - otherwise the error is invisible on a saved button. */ }
<PanelBody
title={ __( 'Product Options', 'jetpack-paypal-payments' ) }
initialOpen={ ! hasButton || variantErrors.length > 0 }
>
<TextControl
label={ __( 'Product ID (optional)', 'jetpack-paypal-payments' ) }
value={ productId || '' }
onChange={ value => setAttributes( { productId: value } ) }
disabled={ isBusy }
maxLength={ MAX_PRODUCT_ID_LENGTH }
placeholder={ __( 'SKU number or other identifiers', 'jetpack-paypal-payments' ) }
/>
<VariantBuilder
enabled={ variantsEnabled }
variants={ variants }
currencyCode={ currencyCode || 'USD' }
onChange={ updates => setAttributes( updates ) }
disabled={ isBusy }
errors={ variantErrors }
touched={ touchedFields }
// A saved button's groups came out of storage already invalid, so
// there is no blur coming - the same reason the panel opens below.
showAll={ hasButton }
onTouch={ markTouched }
/>
</PanelBody>
{ /* `initialOpen`, so the panel opens itself on a checkout-field error and the
merchant can still close it. */ }
<PanelBody
title={ __( 'Checkout Options', 'jetpack-paypal-payments' ) }
initialOpen={ hasCheckoutOptionError( validationErrors ) || customerNoteErrors.length > 0 }
>
{ /* WOOPTP-171: Customer Notes */ }
<ToggleControl
label={ __( 'Add customer note', 'jetpack-paypal-payments' ) }
help={ __(
'Tell customers what you need, like personalization, gift messages, etc.',
'jetpack-paypal-payments'
) }
checked={ customerNotes?.length > 0 }
onChange={ value => {
if ( value ) {
setAttributes( {
customerNotes: [ { label: '', required: false } ],
} );
} else {
setAttributes( resetToDefaults( 'customerNotes' ) );
}
// A fresh row starts untouched, so the old marks go with the old rows.
setTouchedFields( withoutNoteMarks );
} }
disabled={ isBusy }
/>
{ customerNotes?.length > 0 && (
<div className="jetpack-paypal-payment-buttons__customer-notes">
{ customerNotes.map( ( note, noteIndex ) => {
const noteError = noteErrorFor( noteIndex );
return (
<div
key={ noteIndex }
className="jetpack-paypal-payment-buttons__customer-note"
role="group"
aria-label={ sprintf(
/* translators: %d: note number */
__( 'Customer note %d', 'jetpack-paypal-payments' ),
noteIndex + 1
) }
>
{ /* Rows share one label; the group's aria-label above tells them apart. */ }
<TextControl
__nextHasNoMarginBottom
label={ __( 'Customer note label', 'jetpack-paypal-payments' ) }
value={ note.label || '' }
onChange={ value => updateNote( noteIndex, { label: value } ) }
placeholder={ __( 'For example: Gift message', 'jetpack-paypal-payments' ) }
onBlur={ () => markTouched( noteFieldKey( noteIndex ) ) }
help={ noteError }
className={ clsx( 'jetpack-paypal-payment-buttons__field', {
'jetpack-paypal-payment-buttons__has-error': noteError,
} ) }
disabled={ isBusy }
/>
<CheckboxControl
__nextHasNoMarginBottom
label={ __( 'Required', 'jetpack-paypal-payments' ) }
checked={ !! note.required }
onChange={ value => updateNote( noteIndex, { required: value } ) }
disabled={ isBusy }
/>
{ customerNotes.length > 1 && (
<Button
size="small"
isDestructive
variant="tertiary"
onClick={ () => removeNote( noteIndex ) }
disabled={ isBusy }
label={ sprintf(
/* translators: %d: note number */
__( 'Remove customer note %d', 'jetpack-paypal-payments' ),
noteIndex + 1
) }
>
{ __( 'Remove', 'jetpack-paypal-payments' ) }
</Button>
) }
</div>
);
} ) }
{ customerNotes.length < MAX_CUSTOMER_NOTES && (
<Button
__next40pxDefaultSize
variant="tertiary"
icon={ GridiconPlus }
onClick={ addNote }
disabled={ isBusy }
>
{ __( 'Add another note', 'jetpack-paypal-payments' ) }
</Button>
) }
</div>
) }
{ /* Adjustable quantity */ }
<ToggleControl
label={ __( 'Let customers set quantity', 'jetpack-paypal-payments' ) }
help={ helpQuantity }
checked={ adjustableQuantity }
onChange={ value =>
setAttributes(
value ? { adjustableQuantity: true } : turnGateOff( 'adjustableQuantity' )
)
}
disabled={ isBusy }
/>
{ adjustableQuantity && (
<TextControl
className="jetpack-paypal-payment-buttons__field"
label={ __( 'Maximum quantity', 'jetpack-paypal-payments' ) }
value={ maxQuantity || '' }
onChange={ value =>
setAttributes( {
maxQuantity: parseInt( value, 10 ) || resetToDefaults( 'maxQuantity' ).maxQuantity,
} )
}
type="number"
min={ 2 }
max={ 999 }
disabled={ isBusy }
help={ __( 'Customers can buy up to this number', 'jetpack-paypal-payments' ) }
/>
) }
{ /* Tax */ }
<ToggleControl
label={ __( 'Add tax', 'jetpack-paypal-payments' ) }
help={ __( 'Set the tax rate for this item', 'jetpack-paypal-payments' ) }
checked={ taxEnabled }
onChange={ value =>
setAttributes( value ? { taxEnabled: true } : turnGateOff( 'taxEnabled' ) )
}
disabled={ isBusy }
/>
{ taxEnabled && (
<>
<CustomSelectControl
className={ clsx(
'jetpack-paypal-payment-buttons__field',
'jetpack-paypal-payment-buttons__select-menu',
{ 'jetpack-paypal-payment-buttons__has-hint': ! taxHasValue }
) }
label={ __( 'Tax type', 'jetpack-paypal-payments' ) }
value={ taxHasValue ? TAX_TYPE_SPECIFIC : TAX_TYPE_PROFILE }
options={ TAX_TYPES }
// PayPal reads a profile tax back with an empty value, so a leftover rate
// would show up as a change on the next mount.
onChange={ ( { selectedItem } ) =>
setAttributes(
'profile' === selectedItem.key
? {
taxType: 'PREFERENCE',
...resetToDefaults( 'taxValue' ),
collectShippingAddress: true,
}
: { taxType: 'PERCENTAGE' }
)
}
disabled={ isBusy }
/>
{ /* CustomSelectControl passes `help` to the trigger as a DOM attribute, so
the hint gets its own paragraph. */ }
{ ! taxHasValue && (
<p className="jetpack-paypal-payment-buttons__field-hint">{ taxProfileHint }</p>
) }
{ taxHasValue && (
<>
<CustomSelectControl
className="jetpack-paypal-payment-buttons__field jetpack-paypal-payment-buttons__select-menu"
label={ __( 'Rate type', 'jetpack-paypal-payments' ) }
value={
TAX_RATE_TYPES.find( option => option.key === taxType ) ?? TAX_RATE_TYPES[ 0 ]
}
options={ TAX_RATE_TYPES }
// 7.5% and $7.50 are different numbers, so the value clears with the type.
onChange={ ( { selectedItem } ) =>
setAttributes( {
taxType: selectedItem.key,
...resetToDefaults( 'taxValue' ),
} )
}
disabled={ isBusy }
/>
<AmountField
label={ __( 'Tax rate', 'jetpack-paypal-payments' ) }
value={ taxValue }
onChange={ value => setAttributes( { taxValue: value } ) }
suffix={ taxIsPercentage ? '%' : currencySymbol }
step={ taxIsPercentage ? '0.01' : priceStep }
min="0"
max={ taxIsPercentage ? '99.99' : undefined }
placeholder={ taxIsPercentage ? placeholderTaxRate : placeholderTaxValue }
error={ validationErrors.taxValue }
disabled={ isBusy }
/>
</>
) }
</>
) }
{ /* Shipping */ }
<ToggleControl
label={ __( 'Add shipping', 'jetpack-paypal-payments' ) }
help={ __( 'Set shipping fees and get address', 'jetpack-paypal-payments' ) }
checked={ shippingEnabled }
onChange={ value =>
setAttributes( value ? { shippingEnabled: true } : turnGateOff( 'shippingEnabled' ) )
}
disabled={ isBusy }
/>
{ shippingEnabled && (
<>
<CustomSelectControl
className={ clsx(
'jetpack-paypal-payment-buttons__field',
'jetpack-paypal-payment-buttons__select-menu',
{
'jetpack-paypal-payment-buttons__has-hint': 'PROFILE' === activeShippingMode,
}
) }
label={ __( 'Shipping fee', 'jetpack-paypal-payments' ) }
value={
SHIPPING_MODES.find( option => option.key === activeShippingMode ) ??
SHIPPING_MODES[ 0 ]
}
options={ SHIPPING_MODES }
// Clear the fees the new mode hides. A leftover fee comes back blank from the
// next read-back, which shows up as PayPal changing the button.
onChange={ ( { selectedItem } ) =>
setAttributes( {
shippingMode: selectedItem.key,
...( SHIPPING_MODES_WITH_FEE.includes( selectedItem.key )
? {}
: resetToDefaults( 'shippingValue' ) ),
...( 'QUANTITY' === selectedItem.key
? {}
: resetToDefaults( 'shippingAdditionalValue' ) ),
} )
}
disabled={ isBusy }
/>
{ 'PROFILE' === activeShippingMode && (
<p className="jetpack-paypal-payment-buttons__field-hint">{ shippingProfileHint }</p>
) }
{ shippingHasFee && (
<AmountField
label={
'QUANTITY' === activeShippingMode ? labelShippingFirstItem : labelShippingFee
}
value={ shippingValue }
onChange={ value => setAttributes( { shippingValue: value } ) }
suffix={ currencySymbol }
step={ priceStep }
min="0"
placeholder={ __( 'Amount', 'jetpack-paypal-payments' ) }
error={ validationErrors.shippingValue }
disabled={ isBusy }
/>
) }
{ 'QUANTITY' === activeShippingMode && (
<AmountField
label={ __( 'Additional items (optional)', 'jetpack-paypal-payments' ) }
value={ shippingAdditionalValue }
onChange={ value => setAttributes( { shippingAdditionalValue: value } ) }
suffix={ currencySymbol }
step={ priceStep }
min="0"
placeholder={ __( 'Amount', 'jetpack-paypal-payments' ) }
error={ validationErrors.shippingAdditionalValue }
disabled={ isBusy }
/>
) }
<CheckboxControl
label={ __( 'Collect shipping address', 'jetpack-paypal-payments' ) }
help={ addressIsRequired ? helpAddressWithProfileTax : helpAddress }
checked={ addressIsRequired || !! collectShippingAddress }
onChange={ value => setAttributes( { collectShippingAddress: value } ) }
disabled={ isBusy || addressIsRequired }
/>
</>
) }
{ /* Handling fee */ }
<ToggleControl
label={ __( 'Add handling fee', 'jetpack-paypal-payments' ) }
help={ __( 'One fee per purchase', 'jetpack-paypal-payments' ) }
checked={ handlingEnabled }
onChange={ value =>
setAttributes( value ? { handlingEnabled: true } : turnGateOff( 'handlingEnabled' ) )
}
disabled={ isBusy }
/>
{ handlingEnabled && (
<AmountField
label={ __( 'Handling fee', 'jetpack-paypal-payments' ) }
value={ handlingValue }
onChange={ value => setAttributes( { handlingValue: value } ) }
suffix={ currencySymbol }
step={ priceStep }
min="0"
placeholder={ __( 'Amount', 'jetpack-paypal-payments' ) }
error={ validationErrors.handlingValue }
disabled={ isBusy }
/>
) }
{ /* Discount */ }
<ToggleControl
label={ __( 'Add discount', 'jetpack-paypal-payments' ) }
help={ __( 'Applies to each item, no matter quantity', 'jetpack-paypal-payments' ) }
checked={ discountEnabled }
onChange={ value =>
setAttributes( value ? { discountEnabled: true } : turnGateOff( 'discountEnabled' ) )
}
disabled={ isBusy }
/>
{ discountEnabled && (
<>
{ /* CustomSelectControl, for the second hint line each option carries. */ }
<CustomSelectControl
className="jetpack-paypal-payment-buttons__field jetpack-paypal-payment-buttons__select-menu"
label={ __( 'Discount type', 'jetpack-paypal-payments' ) }
// Keeps the control controlled when the stored type has no option here.
value={
DISCOUNT_TYPES.find( option => option.key === discountType ) ?? DISCOUNT_TYPES[ 0 ]
}
options={ DISCOUNT_TYPES }
// Clear the value with the type: 2 kept across a switch turns $2 off
// into 2% off, and both are legal.
onChange={ ( { selectedItem } ) =>
setAttributes( {
discountType: selectedItem.key,
...resetToDefaults( 'discountValue' ),
} )
}
disabled={ isBusy }
/>
<AmountField
label={ __( 'Discount value', 'jetpack-paypal-payments' ) }
value={ discountValue }
onChange={ value => setAttributes( { discountValue: value } ) }
suffix={ discountIsPercentage ? '%' : currencySymbol }
// PayPal takes a whole-number percentage only, 1 to 99.
step={ discountIsPercentage ? '1' : priceStep }
min={ discountIsPercentage ? '1' : priceStep }
max={ discountIsPercentage ? '99' : undefined }
help={ __( 'Reduced from the product price', 'jetpack-paypal-payments' ) }
error={ validationErrors.discountValue }
disabled={ isBusy }
/>
</>
) }
</PanelBody>
{ /* Opens itself on a return URL error. */ }
<PanelBody
title={ __( 'URL Redirect', 'jetpack-paypal-payments' ) }
initialOpen={ !! validationErrors.returnUrl }
>
{ /* URLInput takes no onBlur, so the wrapper catches it as it bubbles, and
carries the error class too. URLInput gets exactly one class - it appends
`__suggestions` to whatever it is given, and a second one in there
would break the suggestion list's width. */ }
<div
className={ returnUrlError ? 'jetpack-paypal-payment-buttons__has-error' : undefined }
onBlur={ () => markTouched( 'returnUrl' ) }
>
<URLInput
label={ __( 'Return URL (optional)', 'jetpack-paypal-payments' ) }
className="jetpack-paypal-payment-buttons__return-url"
value={ returnUrl || '' }
// Pasted URLs often bring a stray space at either end.
onChange={ value => setAttributes( { returnUrl: value.trim() } ) }
required={ false }
disabled={ isBusy }
help={
returnUrlError ||
__( 'Redirect customers here after payment.', 'jetpack-paypal-payments' )
}
/>
</div>
</PanelBody>
</>
);
let sidebar = formPanels;
if ( showLinkStep ) {
sidebar = linkStep;
} else if ( showSwitch ) {
sidebar = switchView;
} else if ( showDetails ) {
sidebar = detailsView;
}
return (
<div { ...blockProps }>
{ toolbarControls }
{ /* One fill for the whole Settings tab. Separate fills portal into the same
container, so the sidebar orders them by which mounted last rather than
by source. */ }
<InspectorControls>
{ sidebar }
{ connectionPanel }
</InspectorControls>
{ accountHeader }
{ formatControls }
{ /* The inspector only mounts when the block is selected, so notices about a
broken block go on the canvas. */ }
{ disconnectedNotice }
{ linkDeleted && (
<Notice status="warning" isDismissible={ false }>
{ __(
'This payment link was deleted from PayPal, so the published button shows nothing. Updating the post creates a new link with a new URL and QR code. Remove the block instead if you no longer sell this.',
'jetpack-paypal-payments'
) }
</Notice>
) }
{ showLinkStep ? (
<p className="jetpack-paypal-payment-buttons__links-hint">
{ __(
'Choose a payment link you already have, or create a new one, in the block settings.',
'jetpack-paypal-payments'
) }
</p>
) : (
<PayPalButtonPreview
format={ activeFormat }
productName={ productName }
price={ price }
currencyCode={ currencyCode }
productDescription={ productDescription }
paymentLink={ paymentLink }
variantsEnabled={ variantsEnabled }
variants={ variants }
imageUrl={ imageUrl }
partnerAttributionId={ partnerAttributionId }
buttonText={ buttonText }
linkText={ linkText }
qrShowCaption={ qrShowCaption }
qrCaption={ qrCaption }
attributes={ attributes }
resource={ resource }
isSelected={ isSelected }
/>
) }
{ confirmDialogs }
{ showUnsavedConfirm && (
<UnsavedChangesDialog
canSave={ isFormValid }
isSaving={ isSavingFromModal || isSavingPost }
onSave={ saveChanges }
onDiscard={ discardChanges }
onCancel={ () => setShowUnsavedConfirm( false ) }
/>
) }
</div>
);
}
|