File size: 9,708 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 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 |
import { recordTracksEvent } from '@automattic/calypso-analytics';
import styled from '@emotion/styled';
import { useI18n } from '@wordpress/react-i18n';
import { useCommandState } from 'cmdk';
import { useCallback } from 'react';
import { SiteType } from './commands';
import { useCommandPaletteContext } from './context';
import { isCustomDomain } from './utils';
import type { Command, CommandCallBackParams } from './commands';
import type { SiteExcerptData } from '@automattic/sites';
const FillDefaultIconWhite = styled.div( {
flexShrink: 0,
'.commands-command-menu__container [cmdk-item] & svg': {
fill: '#fff',
},
} );
const SiteIcon = styled.img( {
width: '32px',
verticalAlign: 'middle',
} );
const EmptySiteIcon = styled.div( {
width: '32px',
height: '32px',
background: 'var(--color-neutral-10)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
} );
interface SiteToCommandParameters {
selectedCommand: Command;
filteredSitesLength: number;
listVisibleCount: number;
search: string;
}
const useSiteToCommand = () => {
const { currentRoute } = useCommandPaletteContext();
return useCallback(
( {
selectedCommand,
filteredSitesLength,
listVisibleCount,
search,
}: SiteToCommandParameters ) =>
( site: SiteExcerptData ): Command => {
const siteName = site.name || site.URL; // Use site.name if present, otherwise default to site.URL
return {
name: `${ site.ID }`,
label: `${ siteName }`,
subLabel: `${ site.URL }`,
searchLabel: `${ site.ID } ${ siteName } ${ site.URL }`,
callback: ( params ) => {
recordTracksEvent( 'calypso_hosting_command_palette_site_select', {
command: selectedCommand.name,
list_count: filteredSitesLength,
list_visible_count: listVisibleCount,
current_route: currentRoute,
search_text: search,
command_site_id: site.ID,
command_site_has_custom_domain: isCustomDomain( site.slug ),
command_site_plan_id: site.plan?.product_id,
} );
selectedCommand.callback( { ...params, site, command: selectedCommand } );
},
image: (
<FillDefaultIconWhite>
{ site.icon?.img ? (
<SiteIcon src={ site.icon.img } alt="" />
) : (
<EmptySiteIcon>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width="24"
height="24"
>
<rect x="0" fill="none" width="24" height="24" />
<g>
<path d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 18l2-2 1-1v-2h-2v-1l-1-1H9v3l2 2v1.931C7.06 19.436 4 16.072 4 12l1 1h2v-2h2l3-3V6h-2L9 5v-.411a7.945 7.945 0 016 0V6l-1 1v2l1 1 3.13-3.13A7.983 7.983 0 0119.736 10H18l-2 2v2l1 1h2l.286.286C18.029 18.061 15.239 20 12 20z" />
</g>
</svg>
</EmptySiteIcon>
) }
</FillDefaultIconWhite>
),
};
},
[ currentRoute ]
);
};
const isCommandAvailableOnSite = (
command: Command,
site: SiteExcerptData,
userCapabilities: { [ key: number ]: { [ key: string ]: boolean } }
): boolean => {
const isAtomic = !! site.is_wpcom_atomic;
const isJetpack = !! site.jetpack;
const isSelfHosted = isJetpack && ! isAtomic;
if ( command?.capability && ! userCapabilities[ site.ID ]?.[ command.capability ] ) {
return false;
}
if ( command.siteType === SiteType.ATOMIC && ! isAtomic ) {
return false;
}
if ( command.siteType === SiteType.JETPACK && ! isJetpack ) {
return false;
}
if ( command?.isCustomDomain && ! isCustomDomain( site.slug ) ) {
return false;
}
if ( command?.publicOnly && ( site.is_coming_soon || site.is_private ) ) {
return false;
}
if ( command?.filterP2 && site.options?.is_wpforteams_site ) {
return false;
}
if ( command?.filterStaging && site.is_wpcom_staging_site ) {
return false;
}
if ( command?.filterSelfHosted && isSelfHosted ) {
return false;
}
if (
command?.adminInterface &&
! isSelfHosted &&
site.options?.wpcom_admin_interface !== command.adminInterface
) {
return false;
}
return true;
};
export const useCommandPalette = (): {
commands: Command[];
filterNotice: string | undefined;
emptyListNotice: string | undefined;
inSiteContext: boolean | undefined;
} => {
const {
currentSiteId,
useCommands,
currentRoute,
useSites,
userCapabilities,
search,
selectedCommandName,
setSelectedCommandName,
} = useCommandPaletteContext();
const siteToCommand = useSiteToCommand();
const listVisibleCount = useCommandState( ( state ) => state.filtered.count );
const sites = useSites();
const commands = useCommands();
const { __ } = useI18n();
const trackSelectedCommand = ( command: Command ) => {
recordTracksEvent( 'calypso_hosting_command_palette_command_select', {
command: command.name,
has_nested_commands: !! command.siteSelector,
list_count: commands.length,
list_visible_count: listVisibleCount,
current_route: currentRoute,
search_text: search,
} );
};
const currentSite = sites.find( ( site ) => site.ID === currentSiteId );
const inSiteContext =
currentSite && ( currentRoute.includes( ':site' ) || currentRoute.startsWith( '/wp-admin' ) );
// Logic for selected command (sites)
if ( selectedCommandName ) {
const selectedCommand = commands.find( ( c ) => c.name === selectedCommandName );
let sitesToPick = null;
let filterNotice = undefined;
let emptyListNotice = undefined;
if ( selectedCommand?.siteSelector ) {
let filteredSites = sites.filter( ( site ) =>
isCommandAvailableOnSite( selectedCommand, site, userCapabilities )
);
if ( sites.length === 0 ) {
emptyListNotice = __( "You don't have any sites yet.", __i18n_text_domain__ );
} else if ( filteredSites.length === 0 ) {
emptyListNotice = selectedCommand.emptyListNotice;
}
// Only show the filterNotice if there are some sites in the first place.
if ( filteredSites.length > 0 ) {
filterNotice = selectedCommand.filterNotice;
}
if ( currentSiteId ) {
const currentSite = filteredSites.find( ( site ) => site.ID === currentSiteId );
if ( currentSite ) {
if ( selectedCommand.name === 'switchSite' ) {
// Exclude the current site from the "Switch site" command;
filteredSites = filteredSites.filter( ( site ) => site.ID !== currentSiteId );
if ( filteredSites.length === 0 ) {
emptyListNotice = selectedCommand.emptyListNotice;
}
} else {
// Move current site to the top of the list
filteredSites = [
currentSite,
...filteredSites.filter( ( site ) => site.ID !== currentSiteId ),
];
}
}
}
// Map filtered sites to commands using the callback of the selected command.
sitesToPick = filteredSites.map(
siteToCommand( {
selectedCommand,
filteredSitesLength: filteredSites.length,
listVisibleCount,
search,
} )
);
}
return { commands: sitesToPick ?? [], filterNotice, emptyListNotice, inSiteContext };
}
// Logic for root commands
// Filter out commands that have context
const commandHasContext = (
paths: ( string | { path: string; match: string } )[] = []
): boolean => {
return paths.some( ( pathItem ) => {
if ( typeof pathItem === 'string' ) {
return currentRoute.includes( pathItem ) ?? false;
}
return pathItem.match === 'exact'
? currentRoute === pathItem.path
: currentRoute.includes( pathItem.path ) ?? false;
} );
};
// Sort commands with contextual commands ranking higher than general in a given context
let sortedCommands = commands.sort( ( a, b ) => {
const hasContextCommand = commandHasContext( a.context );
const hasNoContext = commandHasContext( b.context );
if ( hasContextCommand && ! hasNoContext ) {
return -1; // commands with context come first if there is a context match
} else if ( ! hasContextCommand && hasNoContext ) {
return 1; // commands without context set
}
return 0; // no change in order
} );
// If we are on a current site context, filter and map the commands for single site use.
if ( inSiteContext ) {
sortedCommands = sortedCommands.filter( ( command ) =>
isCommandAvailableOnSite( command, currentSite, userCapabilities )
);
sortedCommands = sortedCommands.map( ( command: Command ) => {
if ( command?.alwaysUseSiteSelector ) {
return command;
}
return {
...command,
siteSelector: false,
callback: ( params ) => {
command.callback( {
...params,
site: currentSite,
} );
},
};
} );
}
const finalSortedCommands = sortedCommands.map( ( command ) => {
return {
...command,
callback: ( params: CommandCallBackParams ) => {
// Inject a tracks event on the callback of each command.
trackSelectedCommand( command );
// Change the label when the site selector shows up and bail (the actual
// callback should be executed only after a site has been selected).
if ( command.siteSelector ) {
params.setSearch( '' );
setSelectedCommandName( command.name );
params.setPlaceholderOverride( command.siteSelectorLabel || '' );
return;
}
command.callback( params );
},
};
} ) as Command[];
// Add the "viewMySites" command to the beginning in all contexts except "/sites"
if ( currentRoute !== '/sites' ) {
const index = finalSortedCommands.findIndex( ( command ) => command.name === 'viewMySites' );
if ( index > 0 ) {
const [ element ] = finalSortedCommands.splice( index, 1 );
finalSortedCommands.unshift( element );
}
}
return {
commands: finalSortedCommands,
filterNotice: undefined,
emptyListNotice: undefined,
inSiteContext,
};
};
|