Skip to content
This repository has been archived by the owner on Dec 27, 2022. It is now read-only.

Ensure frontend links and Ajax requests include UUID query param; add previewing of Ajax requests and form submissions #70

Merged
merged 32 commits into from
Aug 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
fe54c3c
Ensure customize_snapshot_uuid gets added to frontend links
westonruter Aug 7, 2016
c1ce097
Ignore customize_snapshot_uuid param if in the admin
westonruter Aug 7, 2016
8bf8be2
Add test for enqueue_frontend_scripts
westonruter Aug 7, 2016
1c93cfb
Remember snapshot in session and prompt to restore
westonruter Aug 7, 2016
0d74731
Confirm when leaving snapshot state
westonruter Aug 7, 2016
ae9593d
Improve logic for replacing customize admin bar link; move inspect it…
westonruter Aug 7, 2016
1100a2e
Add link to exit snapshot frontend preview; remove all other external…
westonruter Aug 8, 2016
5742fb5
Bump priority on removal of admin bar links; allow links with snapshots
westonruter Aug 8, 2016
b3707da
Remove confirm to resume snapshot in favor of admin bar link if avail…
westonruter Aug 8, 2016
e08b899
Remove nag when clicking on links without snapshot param
westonruter Aug 8, 2016
dd8e944
Use mutation observers to inject query params into links if available
westonruter Aug 8, 2016
74718b4
Inject customize_snapshot_uuid into frontend requests
westonruter Aug 8, 2016
c6b5bdd
Restore snapshot importing on customize.php
westonruter Aug 8, 2016
32c9c71
Remove obsolete leaveSessionPrompt
westonruter Aug 8, 2016
d57ecac
Add stub for customize-snapshots-preview
westonruter Aug 8, 2016
97f3663
Introduce Customize_Snapshot_Manager::is_previewing_settings()
westonruter Aug 8, 2016
e08290a
Fix readme
westonruter Aug 8, 2016
50b04d3
Add support for previewing Ajax requests inside of the Customizer pre…
westonruter Aug 8, 2016
1527e86
Ensure that GET requests in Customizer Preview get recognized as GET …
westonruter Aug 9, 2016
f2e5a17
Break up init method into smaller methods; add tests
westonruter Aug 9, 2016
557aa06
Add test for Post_Type::display_post_states()
westonruter Aug 9, 2016
751a80f
Add test for Customize_Snapshot_Manager::doing_customize_save_ajax()
westonruter Aug 9, 2016
672c202
Add test for Customize_Snapshot_Manager::ensure_customize_manager()
westonruter Aug 9, 2016
19a224e
Add test for Customize_Snapshot_Manager::is_theme_active()
westonruter Aug 9, 2016
be2a9cd
Add test for Customize_Snapshot_Manager::should_import_and_preview_sn…
westonruter Aug 9, 2016
6745570
Add support for previewing GET form submissions in Customizer preview
westonruter Aug 10, 2016
005aed4
Add not-allowed cursor to submit buttons for forms with post method
westonruter Aug 10, 2016
e2eb16e
Persist current snapshot in form submissions on frontend
westonruter Aug 10, 2016
307c5af
Re-use the previewUrl value's setter to determine if form action is p…
westonruter Aug 10, 2016
51c0439
Use jQuery instead of straight querySelector
westonruter Aug 10, 2016
ae6a176
Clarify jsdoc
westonruter Aug 10, 2016
9d1ad7a
Merge pull request #72 from xwp/feature/previewing-form-submissions
westonruter Aug 10, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions css/customize-snapshots-preview.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
form[method="post"] button[type="submit"],
form[method="post"] button[type=""],
form[method="post"] input[type="submit"] {
cursor: not-allowed;
}
form[method="post"] button:not([type]) {
cursor: not-allowed;
}
2 changes: 1 addition & 1 deletion customize-snapshots.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
* Admin notice for incompatible versions of PHP.
*/
function customize_snapshots_php_version_error() {
printf( '<div class="error"><p>%s</p></div>', customize_snapshots_php_version_text() );
printf( '<div class="error"><p>%s</p></div>', customize_snapshots_php_version_text() ); // WPCS: XSS OK.
}

/**
Expand Down
28 changes: 28 additions & 0 deletions instance.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,31 @@ function get_plugin_instance() {
global $customize_snapshots_plugin;
return $customize_snapshots_plugin;
}

/**
* Convenience function for whether settings are being previewed.
*
* @see Customize_Snapshot_Manager::is_previewing_settings()
* @see Customize_Snapshot_Manager::preview_snapshot_settings()
*
* @return bool Whether previewing settings.
*/
function is_previewing_settings() {
return get_plugin_instance()->customize_snapshot_manager->is_previewing_settings();
}

/**
* Convenience function to get the current snapshot UUID.
*
* @see Customize_Snapshot_Manager::$current_snapshot_uuid
*
* @return string|null The current snapshot UUID or null if no snapshot.
*/
function current_snapshot_uuid() {
$customize_snapshot_uuid = get_plugin_instance()->customize_snapshot_manager->current_snapshot_uuid;
if ( empty( $customize_snapshot_uuid ) ) {
return null;
} else {
return $customize_snapshot_uuid;
}
}
335 changes: 335 additions & 0 deletions js/customize-snapshots-frontend.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,335 @@
/* global jQuery, confirm */
/* exported CustomizeSnapshotsFrontend */
/* eslint consistent-this: [ "error", "section" ], no-magic-numbers: [ "error", { "ignore": [-1,0,1] } ] */
/* eslint-disable no-alert */

/*
* The code here is derived from the initial Transactions pull request: https://github.com/xwp/wordpress-develop/pull/61
* See https://github.com/xwp/wordpress-develop/blob/97fd5019c488a0713d34b517bdbff67c62c48a5d/src/wp-includes/js/customize-preview.js#L98-L111
*/

var CustomizeSnapshotsFrontend = ( function( $ ) {
'use strict';

var component = {
data: {
uuid: '',
home_url: {
scheme: '',
host: '',
path: ''
},
l10n: {
restoreSessionPrompt: ''
}
}
};

/**
* Init.
*
* @param {object} args Args.
* @param {string} args.uuid UUID.
* @returns {void}
*/
component.init = function init( args ) {
_.extend( component.data, args );

component.hasSessionStorage = 'undefined' !== typeof sessionStorage;

component.keepSessionAlive();
component.rememberSessionSnapshot();
component.injectSnapshotIntoLinks();
component.handleExitSnapshotSessionLink();
component.injectSnapshotIntoAjaxRequests();
component.injectSnapshotIntoForms();
};

/**
* Prompt to restore session.
*
* @returns {void}
*/
component.keepSessionAlive = function keepSessionAlive() {
var currentSnapshotUuid, urlParser, adminBarItem;
if ( ! component.hasSessionStorage ) {
return;
}
currentSnapshotUuid = sessionStorage.getItem( 'customize_snapshot_uuid' );
if ( ! currentSnapshotUuid || component.data.uuid ) {
return;
}

urlParser = document.createElement( 'a' );
urlParser.href = location.href;
if ( urlParser.search.length > 1 ) {
urlParser.search += '&';
}
urlParser.search += 'customize_snapshot_uuid=' + encodeURIComponent( sessionStorage.getItem( 'customize_snapshot_uuid' ) );

$( function() {
adminBarItem = $( '#wp-admin-bar-resume-customize-snapshot' );
if ( adminBarItem.length ) {
adminBarItem.find( '> a' ).prop( 'href', urlParser.href );
adminBarItem.show();
} else if ( confirm( component.data.l10n.restoreSessionPrompt ) ) {
location.replace( urlParser.href );
} else {
sessionStorage.removeItem( 'customize_snapshot_uuid' );
}
} );
};

/**
* Remember the session's snapshot.
*
* Persist the snapshot UUID in session storage so that we can prompt to restore the snapshot query param if inadvertently dropped.
*
* @returns {void}
*/
component.rememberSessionSnapshot = function rememberSessionSnapshot() {
if ( ! component.hasSessionStorage || ! component.data.uuid ) {
return;
}
sessionStorage.setItem( 'customize_snapshot_uuid', component.data.uuid );
};

/**
* Inject the snapshot UUID into links in the document.
*
* @returns {void}
*/
component.injectSnapshotIntoLinks = function injectSnapshotIntoLinks() {
var linkSelectors = 'a, area';

if ( ! component.data.uuid ) {
return;
}
$( function() {

// Inject links into initial document.
$( document.body ).find( linkSelectors ).each( function() {
component.injectSnapshotLinkParam( this );
} );

// Inject links for new elements added to the page
if ( 'undefined' !== typeof MutationObserver ) {
component.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( linkSelectors ).each( function() {
component.injectSnapshotLinkParam( this );
} );
} );
} );
component.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
} else {

// If mutation observers aren't available, fallback to just-in-time injection.
$( document.documentElement ).on( 'click focus mouseover', linkSelectors, function() {
component.injectSnapshotLinkParam( this );
} );
}
} );
};

/**
* Is matching base URL (host and path)?
*
* @param {HTMLAnchorElement} parsedUrl Parsed URL.
* @param {string} parsedUrl.hostname Host.
* @param {string} parsedUrl.pathname Path.
* @returns {boolean} Whether matched.
*/
component.isMatchingBaseUrl = function isMatchingBaseUrl( parsedUrl ) {
return parsedUrl.hostname === component.data.home_url.host && 0 === parsedUrl.pathname.indexOf( component.data.home_url.path );
};

/**
* Should the supplied link have a snapshot UUID added (or does it have one already)?
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {string} element.search Query string.
* @param {string} element.pathname Path.
* @param {string} element.hostname Hostname.
* @returns {boolean} Is appropriate for snapshot link.
*/
component.shouldLinkHaveSnapshotParam = function shouldLinkHaveSnapshotParam( element ) {
if ( ! component.isMatchingBaseUrl( element ) ) {
return false;
}

// Skip wp login and signup pages.
if ( /\/wp-(login|signup)\.php$/.test( element.pathname ) ) {
return false;
}

// Allow links to admin ajax as faux frontend URLs.
if ( /\/wp-admin\/admin-ajax\.php$/.test( element.pathname ) ) {
return true;
}

// Disallow links to admin.
if ( /\/wp-admin(\/|$)/.test( element.pathname ) ) {
return false;
}

// Skip links in admin bar.
if ( $( element ).closest( '#wpadminbar' ).length ) {
return false;
}

return true;
};

/**
* Return whether the supplied link element has the snapshot query param.
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {object} element.search Query string.
* @returns {boolean} Whether query param is present.
*/
component.doesLinkHaveSnapshotQueryParam = function( element ) {
return /(^|&)customize_snapshot_uuid=/.test( element.search.substr( 1 ) );
};

/**
* Inject the customize_snapshot_uuid query param into links on the frontend.
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {object} element.search Query string.
* @returns {void}
*/
component.injectSnapshotLinkParam = function injectSnapshotLinkParam( element ) {
if ( component.doesLinkHaveSnapshotQueryParam( element ) || ! component.shouldLinkHaveSnapshotParam( element ) ) {
return;
}

if ( element.search.length > 1 ) {
element.search += '&';
}
element.search += 'customize_snapshot_uuid=' + encodeURIComponent( component.data.uuid );
};

/**
* Handle electing to exit from the snapshot session.
*
* @returns {void}
*/
component.handleExitSnapshotSessionLink = function handleExitSnapshotSessionLink() {
$( function() {
if ( ! component.hasSessionStorage ) {
return;
}
$( '#wpadminbar' ).on( 'click', '#wp-admin-bar-exit-customize-snapshot', function() {
sessionStorage.removeItem( 'customize_snapshot_uuid' );
} );
} );
};

/**
* Inject the snapshot UUID into Ajax requests.
*
* @return {void}
*/
component.injectSnapshotIntoAjaxRequests = function injectSnapshotIntoAjaxRequests() {
$.ajaxPrefilter( component.prefilterAjax );
};

/**
* Rewrite Ajax requests to inject Customizer state.
*
* @param {object} options Options.
* @param {string} options.type Type.
* @param {string} options.url URL.
* @returns {void}
*/
component.prefilterAjax = function prefilterAjax( options ) {
var urlParser;
if ( ! component.data.uuid ) {
return;
}

urlParser = document.createElement( 'a' );
urlParser.href = options.url;

// Abort if the request is not for this site.
if ( ! component.isMatchingBaseUrl( urlParser ) ) {
return;
}

// Skip if snapshot UUID already in URL.
if ( -1 !== urlParser.search.indexOf( 'customize_snapshot_uuid=' + component.data.uuid ) ) {
return;
}

if ( urlParser.search.substr( 1 ).length > 0 ) {
urlParser.search += '&';
}
urlParser.search += 'customize_snapshot_uuid=' + component.data.uuid;

options.url = urlParser.href;
};

/**
* Inject snapshot into forms, allowing preview to persist through submissions.
*
* @returns {void}
*/
component.injectSnapshotIntoForms = function injectSnapshotIntoForms() {
if ( ! component.data.uuid ) {
return;
}
$( function() {

// Inject inputs for forms in initial document.
$( document.body ).find( 'form' ).each( function() {
component.injectSnapshotFormInput( this );
} );

// Inject inputs for new forms added to the page.
if ( 'undefined' !== typeof MutationObserver ) {
component.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( 'form' ).each( function() {
component.injectSnapshotFormInput( this );
} );
} );
} );
component.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
}
} );
};

/**
* Inject snapshot into form inputs.
*
* @param {HTMLFormElement} form Form.
* @returns {void}
*/
component.injectSnapshotFormInput = function injectSnapshotFormInput( form ) {
var urlParser;
if ( $( form ).find( 'input[name=customize_snapshot_uuid]' ).length > 0 ) {
return;
}
urlParser = document.createElement( 'a' );
urlParser.href = form.action;
if ( ! component.isMatchingBaseUrl( urlParser ) ) {
return;
}

$( form ).prepend( $( '<input>', {
type: 'hidden',
name: 'customize_snapshot_uuid',
value: component.data.uuid
} ) );
};

return component;
} )( jQuery );

Loading