Skip to content

Commit

Permalink
Merge branch 'fix/cli-boolean-values' of github.com:10up/ElasticPress…
Browse files Browse the repository at this point in the history
… into fix/cli-boolean-values
  • Loading branch information
oscarssanchez committed Feb 19, 2023
2 parents 43a4aab + 3d3e054 commit a594d33
Show file tree
Hide file tree
Showing 44 changed files with 830 additions and 152 deletions.
12 changes: 11 additions & 1 deletion assets/js/api-search/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,21 @@ const Context = createContext();
* @param {string} props.apiHost API Host.
* @param {object} props.argsSchema Schema describing supported args.
* @param {string} props.authorization Authorization header.
* @param {string} props.requestIdBase Base of Requests IDs.
* @param {WPElement} props.children Component children.
* @param {string} props.paramPrefix Prefix used to set and parse URL parameters.
* @param {Function} props.onAuthError Function to run when request authentication fails.
* @returns {WPElement} Component.
*/
export const ApiSearchProvider = ({
apiEndpoint,
apiHost,
authorization,
requestIdBase,
argsSchema,
children,
paramPrefix,
onAuthError,
}) => {
/**
* Any default args from the URL.
Expand Down Expand Up @@ -82,7 +86,13 @@ export const ApiSearchProvider = ({
/**
* Set up fetch method.
*/
const fetchResults = useFetchResults(apiHost, apiEndpoint, authorization);
const fetchResults = useFetchResults(
apiHost,
apiEndpoint,
authorization,
onAuthError,
requestIdBase,
);

/**
* Set up the reducer.
Expand Down
37 changes: 31 additions & 6 deletions assets/js/api-search/src/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,31 @@
*/
import { useCallback, useRef } from '@wordpress/element';

/**
* Internal dependencies.
*/
import { generateRequestId } from '../../utils/helpers';

/**
* Get a callback function for retrieving search results.
*
* @param {string} apiHost API host.
* @param {string} apiEndpoint API endpoint.
* @param {string} Authorization Authorization header.
* @param {Function} onAuthError Function to run when request authentication fails.
* @param {string} requestIdBase Base of Request IDs.
* @returns {Function} Function for retrieving search results.
*/
export const useFetchResults = (apiHost, apiEndpoint, Authorization) => {
export const useFetchResults = (
apiHost,
apiEndpoint,
Authorization,
onAuthError,
requestIdBase = '',
) => {
const abort = useRef(new AbortController());
const request = useRef(null);
const onAuthErrorRef = useRef(onAuthError);

/**
* Get new search results from the API.
Expand All @@ -27,14 +41,25 @@ export const useFetchResults = (apiHost, apiEndpoint, Authorization) => {
abort.current.abort();
abort.current = new AbortController();

const headers = {
Accept: 'application/json',
Authorization,
};

const requestId = generateRequestId(requestIdBase);
if (requestId) {
headers['X-ElasticPress-Request-ID'] = requestId;
}

request.current = fetch(url, {
signal: abort.current.signal,
headers: {
Accept: 'application/json',
Authorization,
},
headers,
})
.then((response) => {
if (onAuthErrorRef.current && !response.ok) {
onAuthErrorRef.current();
}

return response.json();
})
.catch((error) => {
Expand All @@ -49,5 +74,5 @@ export const useFetchResults = (apiHost, apiEndpoint, Authorization) => {
return request.current;
};

return useCallback(fetchResults, [apiHost, apiEndpoint, Authorization]);
return useCallback(fetchResults, [apiHost, apiEndpoint, Authorization, requestIdBase]);
};
7 changes: 7 additions & 0 deletions assets/js/autosuggest/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
replaceGlobally,
debounce,
domReady,
generateRequestId,
} from '../utils/helpers';

const { epas } = window;
Expand Down Expand Up @@ -192,6 +193,12 @@ async function esSearch(query, searchTerm) {
fetchConfig.headers['EP-Search-Term'] = encodeURI(searchTerm);
}

// only add a request ID if using ep.io endpoint
const requestId = generateRequestId(epas?.requestIdBase || '');
if (requestId) {
fetchConfig.headers['X-ElasticPress-Request-ID'] = requestId;
}

try {
const response = await fetch(epas.endpointUrl, fetchConfig);

Expand Down
2 changes: 1 addition & 1 deletion assets/js/blocks/facets/meta-range/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@
"html": false
},
"editorScript": "ep-facets-meta-range-block-script",
"style": "file:/../../../../../dist/css/facets-styles.css"
"style": "elasticpress-facets"
}
6 changes: 5 additions & 1 deletion assets/js/blocks/facets/meta/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
"type": "string",
"default": ""
},
"displayCount": {
"type": "boolean",
"default": false
},
"orderby": {
"type" : "string",
"default": "count",
Expand All @@ -30,5 +34,5 @@
"html": false
},
"editorScript": "ep-facets-meta-block-script",
"style": "file:/../../../../../dist/css/facets-styles.css"
"style": "elasticpress-facets"
}
11 changes: 9 additions & 2 deletions assets/js/blocks/facets/meta/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
PanelBody,
RadioControl,
TextControl,
ToggleControl,
Spinner,
Placeholder,
SelectControl,
Expand All @@ -24,7 +25,7 @@ const FacetBlockEdit = (props) => {
const [metaKeys, setMetaKeys] = useState([]);
const [preview, setPreview] = useState('');
const [loading, setLoading] = useState(false);
const { searchPlaceholder, facet, orderby, order } = attributes;
const { searchPlaceholder, facet, displayCount, orderby, order } = attributes;

const blockProps = useBlockProps();

Expand All @@ -42,6 +43,7 @@ const FacetBlockEdit = (props) => {
const params = new URLSearchParams({
searchPlaceholder,
facet,
displayCount,
orderby,
order,
});
Expand All @@ -50,7 +52,7 @@ const FacetBlockEdit = (props) => {
})
.then((preview) => setPreview(preview))
.finally(() => setLoading(false));
}, [searchPlaceholder, facet, orderby, order]);
}, [searchPlaceholder, facet, displayCount, orderby, order]);

return (
<Fragment>
Expand Down Expand Up @@ -80,6 +82,11 @@ const FacetBlockEdit = (props) => {
]}
onChange={(value) => setAttributes({ facet: value })}
/>
<ToggleControl
checked={displayCount}
onChange={(value) => setAttributes({ displayCount: value })}
label={__('Display Term Count', 'elasticpress')}
/>
<RadioControl
label={__('Order By', 'elasticpress')}
help={__('The field used to order available options', 'elasticpress')}
Expand Down
6 changes: 5 additions & 1 deletion assets/js/blocks/facets/taxonomy/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
"type": "string",
"default": ""
},
"displayCount": {
"type": "boolean",
"default": false
},
"orderby": {
"type" : "string",
"default": "count",
Expand All @@ -26,5 +30,5 @@
"html": false
},
"editorScript": "ep-facets-block-script",
"style": "file:/../../../../../dist/css/facets-styles.css"
"style": "elasticpress-facets"
}
11 changes: 9 additions & 2 deletions assets/js/blocks/facets/taxonomy/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
RadioControl,
SelectControl,
Spinner,
ToggleControl,
Placeholder,
} from '@wordpress/components';
import { Fragment, useEffect, useState, useCallback } from '@wordpress/element';
Expand All @@ -15,7 +16,7 @@ const FacetBlockEdit = (props) => {
const [taxonomies, setTaxonomies] = useState({});
const [preview, setPreview] = useState('');
const [loading, setLoading] = useState(false);
const { facet, orderby, order } = attributes;
const { facet, displayCount, orderby, order } = attributes;

const blockProps = useBlockProps();

Expand All @@ -32,6 +33,7 @@ const FacetBlockEdit = (props) => {
setLoading(true);
const params = new URLSearchParams({
facet,
displayCount,
orderby,
order,
});
Expand All @@ -40,7 +42,7 @@ const FacetBlockEdit = (props) => {
})
.then((preview) => setPreview(preview))
.finally(() => setLoading(false));
}, [facet, orderby, order]);
}, [facet, displayCount, orderby, order]);

return (
<Fragment>
Expand All @@ -57,6 +59,11 @@ const FacetBlockEdit = (props) => {
]}
onChange={(value) => setAttributes({ facet: value })}
/>
<ToggleControl
checked={displayCount}
onChange={(value) => setAttributes({ displayCount: value })}
label={__('Display Term Count', 'elasticpress')}
/>
<RadioControl
label={__('Order By', 'elasticpress')}
help={__('The field used to order available options', 'elasticpress')}
Expand Down
2 changes: 2 additions & 0 deletions assets/js/instant-results/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const {
postTypeLabels,
taxonomyLabels,
termCount,
requestIdBase,
} = window.epInstantResults;

/**
Expand Down Expand Up @@ -74,4 +75,5 @@ export {
sortOptions,
taxonomyLabels,
termCount,
requestIdBase,
};
3 changes: 2 additions & 1 deletion assets/js/instant-results/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { render } from '@wordpress/element';
* Internal dependencies.
*/
import { ApiSearchProvider } from '../api-search';
import { apiEndpoint, apiHost, argsSchema, paramPrefix } from './config';
import { apiEndpoint, apiHost, argsSchema, paramPrefix, requestIdBase } from './config';
import Modal from './apps/modal';

/**
Expand All @@ -22,6 +22,7 @@ const init = () => {
apiHost={apiHost}
argsSchema={argsSchema}
paramPrefix={paramPrefix}
requestIdBase={requestIdBase}
>
<Modal />
</ApiSearchProvider>,
Expand Down
31 changes: 31 additions & 0 deletions assets/js/utils/helpers.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
/**
* WordPress dependencies.
*/
import { applyFilters } from '@wordpress/hooks';

/**
* External dependencies.
*/
import { v4 as uuidv4 } from 'uuid';

/**
* Simple throttling function for waiting a set amount of time after the last keypress
* So we don't overload the server with too many requests at once
Expand Down Expand Up @@ -155,3 +165,24 @@ export const domReady = (callback) => {
// DOMContentLoaded has not fired yet, delay callback until then.
document.addEventListener('DOMContentLoaded', callback);
};

/**
* Generate a Request ID for autosuggest
*
* @param {string} requestIdBase - base for request ID generation
* @returns {string} Request ID
*/
export const generateRequestId = (requestIdBase) => {
const uuid = uuidv4().replaceAll('-', '');

/**
* Filter the request ID used for an autosuggest request.
*
* @filter ep.Autosuggest.requestId
* @since 4.5.0
*
* @param {string} requestId The Request ID.
* @returns {string} New Request ID.
*/
return applyFilters('ep.requestId', requestIdBase + uuid);
};
8 changes: 5 additions & 3 deletions assets/js/woocommerce/admin/orders/app/components/listbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ export default ({ children, id, input, label, onSelect }) => {
}

event.preventDefault();
onSelect(selectedIndexRef.current);

onSelect(selectedIndexRef.current, event.metaKey);

break;
default:
Expand Down Expand Up @@ -153,6 +154,7 @@ export default ({ children, id, input, label, onSelect }) => {
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-haspopup', true);
input.setAttribute('aria-owns', id);
input.setAttribute('autocomplete', 'off');
input.setAttribute('role', 'combobox');
input.addEventListener('focus', onFocus);
input.addEventListener('keydown', onKeyDown);
Expand All @@ -162,6 +164,7 @@ export default ({ children, id, input, label, onSelect }) => {
input.removeAttribute('aria-autocomplete');
input.removeAttribute('aria-haspopup');
input.removeAttribute('aria-owns');
input.removeAttribute('autocomplete');
input.removeAttribute('role');
input.removeEventListener('focus', onFocus);
input.removeEventListener('keydown', onKeyDown);
Expand Down Expand Up @@ -191,13 +194,12 @@ export default ({ children, id, input, label, onSelect }) => {
aria-selected={selectedIndexRef.current === index}
className="ep-listbox__option"
key={child.props.id}
onClick={() => onSelect(index)}
onClick={(event) => onSelect(index, event.metaKey)}
onMouseEnter={() => {
setSelectedIndex(index);
selectedIndexRef.current = index;
}}
role="option"
tabIndex="-1"
>
{child}
</li>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* WordPress dependencies.
*/
import { date, dateI18n } from '@wordpress/date';
import { dateI18n } from '@wordpress/date';
import { WPElement } from '@wordpress/element';
import { _n, sprintf } from '@wordpress/i18n';

Expand Down Expand Up @@ -32,9 +32,9 @@ export default ({
orderNumber,
orderStatus,
}) => {
const formattedDate = dateI18n(dateFormat, orderDate, 'GMT');
const formattedDateTime = date('c', orderDate, 'GMT');
const formattedTime = dateI18n(timeFormat, orderDate, 'GMT');
const formattedDate = dateI18n(dateFormat, orderDate);
const formattedDateTime = dateI18n('c', orderDate);
const formattedTime = dateI18n(timeFormat, orderDate);
const statusClass = `status-${orderStatus.substring(3)}`;
const statusLabel = statusLabels[orderStatus];

Expand Down
Loading

0 comments on commit a594d33

Please sign in to comment.