File size: 1,787 Bytes
1e92f2d |
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 |
import apiFetch from '@wordpress/api-fetch';
import { addFilter } from '@wordpress/hooks';
import { map, unescape } from 'lodash';
import './editor.scss';
/*
* This is a workaround for the way Gutenberg autocomplete works. It only looks for
* beginnings of words and something like "teamabcp2" won't be found if you search "abc".
* Adding spaces around the word solves the problem.
*/
const COMMON_PREFIXES = /(team|a8c|woo|happiness)/i;
const stripCommonWords = ( str ) => str.replace( COMMON_PREFIXES, ' ' );
const p2s = apiFetch( {
path: '/internal/P2s?skip_description=true',
} ).then( ( result ) =>
map( result.list, ( p2, subdomain ) => {
const keywords = [ subdomain ];
const stripped = stripCommonWords( subdomain );
if ( subdomain !== stripped ) {
keywords.push( stripped );
}
return {
...p2,
subdomain,
keywords,
};
} )
);
const p2Completer = {
name: 'p2s',
triggerPrefix: '+',
options: p2s,
getOptionKeywords: ( site ) => site.keywords,
getOptionLabel: ( site ) => (
<div className="p2-autocomplete">
<span className="p2-autocomplete__subdomain">+{ site.subdomain }</span>
<span className="p2-autocomplete__title">{ unescape( site.title ) }</span>
{ site.blavatar ? (
<img
src={ `${ site.blavatar }?s=20` }
srcset={ `${ site.blavatar }?s=20 1x, ${ site.blavatar }?s=40 2x` }
width="20"
height="20"
className="p2-autocomplete__blavatar"
alt=""
/>
) : (
<span className="p2-autocomplete__blavatar-placeholder" />
) }
</div>
),
getOptionCompletion: ( site ) => `+${ site.subdomain }`,
isDebounced: true,
};
// Register autocompleter for all blocks
addFilter( 'editor.Autocomplete.completers', 'a8c/autocompleters/p2s', ( completers ) => [
...completers,
p2Completer,
] );
|