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 | 2x 2x 547x 547x 489x 489x 4912x 507x 30x 30x 32x 32x 2x 2x 39x 3x 3x 2x 2x 10x 10x 10x 7x 3x 10x 3x 7x 4x 4x 10x 36x 36x 36x 33x 3x 30x 30x 1x 29x 29x 29x 29x 29x 23x 29x 7x 7x 22x 11x 11x 29x 22x 7x 7x 7x 36x 47x 33x 14x 14x 3x 14x 14x 36x 47x 7x 40x | /**
* Hook the payment sync into the post save, save one block's payment on demand, and count
* the post saves for blocks to read.
*
* @package
*/
import jetpackAnalytics from '@automattic/jetpack-analytics';
import apiFetch from '@wordpress/api-fetch'; // eslint-disable-line import/no-unresolved
import { store as blockEditorStore } from '@wordpress/block-editor';
import { dispatch, select } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import { addAction, addFilter } from '@wordpress/hooks';
import { __, sprintf } from '@wordpress/i18n';
import metadata from '../block.json';
import { API_BASE } from './api-base';
import { isReadyForPayPal, notSavedMessage, syncBlocksBeforeSave } from './sync-on-save';
import { toast } from './toast';
import { isForbidden } from './validation';
// Successful post saves other than autosaves.
let postSaves = 0;
const listeners = new Set();
/**
* Set the count and call the listeners.
*
* @param {number} next - The new count.
*/
function update( next ) {
postSaves = next;
listeners.forEach( listener => listener() );
}
/**
* Call a function whenever the count changes.
*
* @param {Function} listener - Called with no arguments.
* @return {Function} Unsubscribes the listener.
*/
export function subscribeToPostSaves( listener ) {
listeners.add( listener );
return () => listeners.delete( listener );
}
/**
* How many post saves have succeeded.
*
* @return {number} The count, starting at 0.
*/
export function getPostSaveCount() {
return postSaves;
}
/**
* Forget the post saves counted. Tests start clean with this.
*/
export function forgetPostSaves() {
update( 0 );
}
/**
* Every PayPal block in the post, inner blocks included.
*
* @return {Array} Blocks with clientId and attributes.
*/
function payPalBlocks() {
const store = select( blockEditorStore );
return store
.getClientIdsWithDescendants()
.map( clientId => store.getBlock( clientId ) )
.filter( block => block?.name === metadata.name );
}
const CREATED_MESSAGE = __( 'Payment button successfully created.', 'jetpack-paypal-payments' );
const CHANGED_MESSAGE = __( 'Payment button changes saved.', 'jetpack-paypal-payments' );
/**
* What syncBlocksBeforeSave() needs from the editor, with the messages it shows.
*
* @param {Function} reportSaved - Called with true for a payment created, false for one changed.
* @param {Function} [onNotSaved] - Called for a block whose settings did not reach PayPal.
* @return {object} The collaborators.
*/
function syncDeps( reportSaved, onNotSaved ) {
return {
request: apiFetch,
updateBlockAttributes: dispatch( blockEditorStore ).updateBlockAttributes,
reportError: ( { clientId }, message ) => {
toast( 'error', message, `jetpack-paypal-sync-${ clientId }` );
onNotSaved?.();
},
// A block the merchant left incomplete is skipped, and the only other
// sign is a line in the block sidebar. Say so where the save is watched.
reportHeldBack: ( { clientId, attributes }, reason ) => {
toast(
'warning',
sprintf(
/* translators: 1: product name, 2: what to fix */
__( 'The PayPal button "%1$s" was not sent to PayPal: %2$s', 'jetpack-paypal-payments' ),
attributes.productName || __( 'Untitled', 'jetpack-paypal-payments' ),
reason
),
`jetpack-paypal-held-back-${ clientId }`
);
onNotSaved?.();
},
reportSaved,
};
}
/**
* Create or update the payment behind one block now, without saving the post.
*
* The messages a post save shows once it is done show right away instead.
*
* @param {object} block - The block, with clientId and attributes.
* @param {string} environment - The connection's environment, for the Tracks event.
* @return {Promise<boolean>} True once PayPal has the block's settings, changed or not.
*/
export async function savePaymentButton( block, environment ) {
const saved = [];
let notSaved = false;
await syncBlocksBeforeSave(
[ block ],
syncDeps(
created => saved.push( created ),
() => {
notSaved = true;
}
)
);
if ( saved.includes( true ) ) {
toast( 'success', CREATED_MESSAGE, 'jetpack-paypal-saved' );
} else if ( saved.length ) {
toast( 'success', CHANGED_MESSAGE, 'jetpack-paypal-saved' );
jetpackAnalytics.tracks.recordEvent( 'jetpack_paypal_button_updated', { environment } );
}
// A stacked block's account warning can follow a write that went through.
return saved.length > 0 || ! notSaved;
}
/**
* Sync the PayPal payments before the post is saved.
*
* Runs on `editor.preSavePost`, which awaits it and saves the content it returns.
* The post is saved whether or not PayPal cooperated: an error is reported, and the
* merchant can save again. The success snackbar waits for `editor.savePost`, which runs
* after the post saves.
*
* @param {Function} isEnabled - Whether API-managed buttons are on for this site.
*/
export function registerSaveSync( isEnabled ) {
// The success message, shown after the next post save that succeeds. It stays set through
// a failed post save, since PayPal already has the change.
let savedMessage = null;
// The environment for the button_updated event, set with the update message.
let updatedEnvironment = null;
addFilter(
'editor.preSavePost',
'jetpack/paypal-payment-buttons/sync-payments',
async ( edits, options ) => {
if ( options?.isAutosave || ! isEnabled() ) {
return edits;
}
const blocks = payPalBlocks();
if ( ! blocks.length ) {
return edits;
}
let connection;
try {
connection = await apiFetch( { path: `${ API_BASE }/connection` } );
} catch ( err ) {
// Only PayPal managers sync. Anyone else gets a 403 and saves without it.
if ( isForbidden( err ) ) {
return edits;
}
// The check failed, so nothing was sent to PayPal.
const { reportError } = syncDeps();
blocks
.filter( block => isReadyForPayPal( block.attributes ) )
.forEach( block => reportError( block, notSavedMessage( block.attributes, err ) ) );
return edits;
}
Iif ( ! connection?.connected ) {
return edits;
}
// One entry per payment this save created (true) or changed (false).
const saved = [];
const changed = await syncBlocksBeforeSave(
blocks,
syncDeps( created => saved.push( created ) )
);
// Set before the `changed` check: a PUT can change the payment and leave the block as
// it is. The create message replaces a pending update message, and stays until shown.
if ( saved.includes( true ) ) {
savedMessage = CREATED_MESSAGE;
updatedEnvironment = null;
} else if ( saved.length && ! savedMessage ) {
savedMessage = CHANGED_MESSAGE;
updatedEnvironment = connection.environment;
}
if ( ! changed ) {
return edits;
}
// The blocks now carry their payment ids; save that content, not the
// snapshot taken before this ran.
const content = select( editorStore ).getEditedPostContent();
dispatch( editorStore ).editPost( { content }, { undoIgnore: true } );
return { ...edits, content };
}
);
// Runs after the post saves. An autosave skips the PayPal sync, so the message waits
// for the next save.
addAction(
'editor.savePost',
'jetpack/paypal-payment-buttons/saved-snackbar',
( post, options ) => {
if ( options?.isAutosave || ! savedMessage ) {
return;
}
toast( 'success', savedMessage, 'jetpack-paypal-saved' );
if ( updatedEnvironment ) {
jetpackAnalytics.tracks.recordEvent( 'jetpack_paypal_button_updated', {
environment: updatedEnvironment,
} );
}
savedMessage = null;
updatedEnvironment = null;
}
);
// Runs after the post saves, and counts every save except autosaves.
addAction( 'editor.savePost', 'jetpack/paypal-payment-buttons/post-saves', ( post, options ) => {
if ( options?.isAutosave ) {
return;
}
update( postSaves + 1 );
} );
}
|