rebase from live enviornment

This commit is contained in:
Rachit Bhargava
2024-01-09 22:14:20 -05:00
parent ff0b49a046
commit 3a22fcaa4a
15968 changed files with 2344674 additions and 45234 deletions

View File

@@ -0,0 +1,113 @@
/**
* External dependencies
*/
import {
getSetting,
STORE_PAGES,
LocaleSpecificAddressField,
} from '@woocommerce/settings';
export type WordCountType =
| 'words'
| 'characters_excluding_spaces'
| 'characters_including_spaces';
interface WcBlocksConfig {
buildPhase: number;
pluginUrl: string;
productCount: number;
defaultAvatar: string;
restApiRoutes: Record< string, string[] >;
wordCountType: WordCountType;
}
export const blocksConfig = getSetting( 'wcBlocksConfig', {
buildPhase: 1,
pluginUrl: '',
productCount: 0,
defaultAvatar: '',
restApiRoutes: {},
wordCountType: 'words',
} ) as WcBlocksConfig;
export const WC_BLOCKS_IMAGE_URL = blocksConfig.pluginUrl + 'images/';
export const WC_BLOCKS_BUILD_URL = blocksConfig.pluginUrl + 'build/';
export const WC_BLOCKS_PHASE = blocksConfig.buildPhase;
export const SHOP_URL = STORE_PAGES.shop?.permalink;
export const CHECKOUT_PAGE_ID = STORE_PAGES.checkout?.id;
export const CHECKOUT_URL = STORE_PAGES.checkout?.permalink;
export const PRIVACY_URL = STORE_PAGES.privacy?.permalink;
export const PRIVACY_PAGE_NAME = STORE_PAGES.privacy?.title;
export const TERMS_URL = STORE_PAGES.terms?.permalink;
export const TERMS_PAGE_NAME = STORE_PAGES.terms?.title;
export const CART_PAGE_ID = STORE_PAGES.cart?.id;
export const CART_URL = STORE_PAGES.cart?.permalink;
export const LOGIN_URL = STORE_PAGES.myaccount?.permalink
? STORE_PAGES.myaccount.permalink
: getSetting( 'wpLoginUrl', '/wp-login.php' );
export const LOCAL_PICKUP_ENABLED = getSetting< boolean >(
'localPickupEnabled',
false
);
type CountryData = {
allowBilling: boolean;
allowShipping: boolean;
states: Record< string, string >;
locale: Record< string, LocaleSpecificAddressField >;
};
// Contains country names.
const countries = getSetting< Record< string, string > >( 'countries', {} );
// Contains country settings.
const countryData = getSetting< Record< string, CountryData > >(
'countryData',
{}
);
export const ALLOWED_COUNTRIES = Object.fromEntries(
Object.keys( countryData )
.filter( ( countryCode ) => {
return countryData[ countryCode ].allowBilling === true;
} )
.map( ( countryCode ) => {
return [ countryCode, countries[ countryCode ] || '' ];
} )
);
export const ALLOWED_STATES = Object.fromEntries(
Object.keys( countryData )
.filter( ( countryCode ) => {
return countryData[ countryCode ].allowBilling === true;
} )
.map( ( countryCode ) => {
return [ countryCode, countryData[ countryCode ].states || [] ];
} )
);
export const SHIPPING_COUNTRIES = Object.fromEntries(
Object.keys( countryData )
.filter( ( countryCode ) => {
return countryData[ countryCode ].allowShipping === true;
} )
.map( ( countryCode ) => {
return [ countryCode, countries[ countryCode ] || '' ];
} )
);
export const SHIPPING_STATES = Object.fromEntries(
Object.keys( countryData )
.filter( ( countryCode ) => {
return countryData[ countryCode ].allowShipping === true;
} )
.map( ( countryCode ) => {
return [ countryCode, countryData[ countryCode ].states || [] ];
} )
);
export const COUNTRY_LOCALE = Object.fromEntries(
Object.keys( countryData ).map( ( countryCode ) => {
return [ countryCode, countryData[ countryCode ].locale || [] ];
} )
);

View File

@@ -0,0 +1,52 @@
/**
* External dependencies
*/
import { registerBlockType } from '@wordpress/blocks';
import type { Block, BlockConfiguration } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { WC_BLOCKS_PHASE } from './constants';
/**
* Registers a new experimental block provided a unique name and an object defining its
* behavior. Once registered, the block is made available as an option to any
* editor interface where blocks are implemented.
*/
export const registerExperimentalBlockType = (
blockNameOrMetadata: string | BlockConfiguration,
settings: Record< string, unknown >
): Block | undefined => {
if ( WC_BLOCKS_PHASE > 2 ) {
return registerBlockType( blockNameOrMetadata, settings );
}
};
/**
* Registers a new feature plugin block provided a unique name and an object
* defining its behavior. Once registered, the block is made available as an
* option to any editor interface where blocks are implemented.
*/
export const registerFeaturePluginBlockType = (
blockNameOrMetadata: string | BlockConfiguration,
settings: Record< string, unknown >
): Block | undefined => {
if ( WC_BLOCKS_PHASE > 1 ) {
return registerBlockType( blockNameOrMetadata, settings );
}
};
/**
* Checks if we're executing the code in an experimental build mode.
*
* @return {boolean} True if this is an experimental build, false otherwise.
*/
export const isExperimentalBuild = (): boolean => WC_BLOCKS_PHASE > 2;
/**
* Checks if we're executing the code in an feature plugin or experimental build mode.
*
* @return {boolean} True if this is an experimental or feature plugin build, false otherwise.
*/
export const isFeaturePluginBuild = (): boolean => WC_BLOCKS_PHASE > 1;

View File

@@ -0,0 +1,5 @@
/**
* Internal dependencies
*/
export * from './constants';
export * from './feature-flags';

View File

@@ -0,0 +1,184 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
export interface AddressField {
// The label for the field.
label: string;
// The label for the field if made optional.
optionalLabel: string;
// The HTML autocomplete attribute value. See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete
autocomplete: string;
// How this field value is capitalized.
autocapitalize?: string;
// Set to true if the field is required.
required: boolean;
// Set to true if the field should not be rendered.
hidden: boolean;
// Fields will be sorted and render in this order, lowest to highest.
index: number;
// The type of input to render. Defaults to text.
type?: string;
}
export interface LocaleSpecificAddressField extends Partial< AddressField > {
priority?: number | undefined;
}
export interface AddressFields {
first_name: AddressField;
last_name: AddressField;
company: AddressField;
address_1: AddressField;
address_2: AddressField;
country: AddressField;
city: AddressField;
state: AddressField;
postcode: AddressField;
phone: AddressField;
}
export type AddressType = 'billing' | 'shipping';
export interface ShippingAddress {
first_name: string;
last_name: string;
company: string;
address_1: string;
address_2: string;
country: string;
city: string;
state: string;
postcode: string;
phone: string;
}
export type KeyedAddressField = AddressField & {
key: keyof AddressFields;
errorMessage?: string;
};
export interface BillingAddress extends ShippingAddress {
email: string;
}
export type CountryAddressFields = Record< string, AddressFields >;
/**
* Default address field properties.
*/
export const defaultAddressFields: AddressFields = {
first_name: {
label: __( 'First name', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'First name (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'given-name',
autocapitalize: 'sentences',
required: true,
hidden: false,
index: 10,
},
last_name: {
label: __( 'Last name', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'Last name (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'family-name',
autocapitalize: 'sentences',
required: true,
hidden: false,
index: 20,
},
company: {
label: __( 'Company', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'Company (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'organization',
autocapitalize: 'sentences',
required: false,
hidden: false,
index: 30,
},
address_1: {
label: __( 'Address', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'Address (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'address-line1',
autocapitalize: 'sentences',
required: true,
hidden: false,
index: 40,
},
address_2: {
label: __( 'Apartment, suite, etc.', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'Apartment, suite, etc. (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'address-line2',
autocapitalize: 'sentences',
required: false,
hidden: false,
index: 50,
},
country: {
label: __( 'Country/Region', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'Country/Region (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'country',
required: true,
hidden: false,
index: 60,
},
city: {
label: __( 'City', 'woo-gutenberg-products-block' ),
optionalLabel: __( 'City (optional)', 'woo-gutenberg-products-block' ),
autocomplete: 'address-level2',
autocapitalize: 'sentences',
required: true,
hidden: false,
index: 70,
},
state: {
label: __( 'State/County', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'State/County (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'address-level1',
autocapitalize: 'sentences',
required: true,
hidden: false,
index: 80,
},
postcode: {
label: __( 'Postal code', 'woo-gutenberg-products-block' ),
optionalLabel: __(
'Postal code (optional)',
'woo-gutenberg-products-block'
),
autocomplete: 'postal-code',
autocapitalize: 'characters',
required: true,
hidden: false,
index: 90,
},
phone: {
label: __( 'Phone', 'woo-gutenberg-products-block' ),
optionalLabel: __( 'Phone (optional)', 'woo-gutenberg-products-block' ),
autocomplete: 'tel',
type: 'tel',
required: true,
hidden: false,
index: 100,
},
};
export default defaultAddressFields;

View File

@@ -0,0 +1,29 @@
/**
* Internal dependencies
*/
import { allSettings } from './settings-init';
/**
* This exports all default core settings as constants.
*/
export const ADMIN_URL = allSettings.adminUrl;
export const COUNTRIES = allSettings.countries;
export const CURRENCY = allSettings.currency;
export const CURRENT_USER_IS_ADMIN = allSettings.currentUserIsAdmin as boolean;
export const HOME_URL = allSettings.homeUrl as string | undefined;
export const LOCALE = allSettings.locale;
export const ORDER_STATUSES = allSettings.orderStatuses;
export const PLACEHOLDER_IMG_SRC = allSettings.placeholderImgSrc as string;
export const SITE_TITLE = allSettings.siteTitle;
export const STORE_PAGES = allSettings.storePages as Record<
string,
{
id: 0;
title: '';
permalink: '';
}
>;
export const WC_ASSET_URL = allSettings.wcAssetUrl;
export const WC_VERSION = allSettings.wcVersion;
export const WP_LOGIN_URL = allSettings.wpLoginUrl;
export const WP_VERSION = allSettings.wpVersion;

View File

@@ -0,0 +1,9 @@
/**
* Internal dependencies
*/
import '../../filters/exclude-draft-status-from-analytics';
export * from './default-constants';
export * from './default-address-fields';
export * from './utils';
export { allSettings } from './settings-init';

View File

@@ -0,0 +1,109 @@
/**
* External dependencies
*/
import { SymbolPosition, CurrencyCode } from '@woocommerce/types';
declare global {
interface Window {
wcSettings: Record< string, unknown >;
}
}
export interface WooCommerceSiteCurrency {
// The ISO code for the currency.
code: CurrencyCode;
// The precision (decimal places).
precision: number;
// The symbol for the currency (eg '$')
symbol: string;
// The position for the symbol ('left', or 'right')
symbolPosition: SymbolPosition;
// The string used for the decimal separator.
decimalSeparator: string;
// The string used for the thousands separator.
thousandSeparator: string;
// The format string use for displaying an amount in this currency.
priceFormat: string;
}
export interface WooCommerceSiteLocale {
// The locale string for the current site.
siteLocale: string;
// The locale string for the current user.
userLocale: string;
// An array of short weekday strings in the current user's locale.
weekdaysShort: string[];
}
export interface WooCommerceSharedSettings {
adminUrl: string;
countries: Record< string, string > | never[];
currency: WooCommerceSiteCurrency;
currentUserId: number;
currentUserIsAdmin: boolean;
homeUrl: string;
locale: WooCommerceSiteLocale;
orderStatuses: Record< string, string > | never[];
placeholderImgSrc: string;
siteTitle: string;
storePages: Record< string, string > | never[];
wcAssetUrl: string;
wcVersion: string;
wpLoginUrl: string;
wpVersion: string;
}
const defaults: WooCommerceSharedSettings = {
adminUrl: '',
countries: [],
currency: {
code: 'USD',
precision: 2,
symbol: '$',
symbolPosition: 'left',
decimalSeparator: '.',
priceFormat: '%1$s%2$s',
thousandSeparator: ',',
},
currentUserId: 0,
currentUserIsAdmin: false,
homeUrl: '',
locale: {
siteLocale: 'en_US',
userLocale: 'en_US',
weekdaysShort: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
},
orderStatuses: [],
placeholderImgSrc: '',
siteTitle: '',
storePages: [],
wcAssetUrl: '',
wcVersion: '',
wpLoginUrl: '',
wpVersion: '',
};
const globalSharedSettings =
typeof window.wcSettings === 'object' ? window.wcSettings : {};
interface AllSettings extends Record< string, unknown > {
currency: WooCommerceSiteCurrency;
}
// Use defaults or global settings, depending on what is set.
const allSettings: AllSettings = {
...defaults,
...globalSharedSettings,
};
allSettings.currency = {
...defaults.currency,
...( allSettings.currency as WooCommerceSiteCurrency ),
};
allSettings.locale = {
...defaults.locale,
...( allSettings.locale as Record< string, unknown > ),
};
export { allSettings };

View File

@@ -0,0 +1,26 @@
/**
* Internal dependencies
*/
import { isWpVersion } from '..';
import { allSettings } from '../settings-init';
describe( 'isWpVersion', () => {
it.each`
version | operator | result
${ '5.3-beta1' } | ${ '<' } | ${ true }
${ '5.3' } | ${ '=' } | ${ true }
${ '5.3-beta12-235' } | ${ '<' } | ${ true }
${ '5.3-rc1' } | ${ '>' } | ${ false }
${ '5.3-rc12-235' } | ${ '<' } | ${ true }
${ '5.3.1' } | ${ '>' } | ${ true }
${ '5.4-beta1' } | ${ '>' } | ${ true }
`(
'should return $result when $version is the current wpVersion ' +
'and `5.3` is the version compared using `$operator`',
( { version, operator, result } ) => {
// eslint-disable-next-line
allSettings[ 'wpVersion' ] = version;
expect( isWpVersion( '5.3', operator ) ).toBe( result );
}
);
} );

View File

@@ -0,0 +1,33 @@
/**
* External dependencies
*/
import { isBoolean, isString } from '@woocommerce/types';
/**
* Internal dependencies
*/
import { ADMIN_URL } from '../default-constants';
import { getSettingWithCoercion } from '..';
describe( 'getSettingWithCoercion', () => {
it( 'returns provided default for non available setting', () => {
expect(
getSettingWithCoercion( 'nada', 'really nada', isString )
).toBe( 'really nada' );
} );
it( 'returns provided default value when the typeguard returns false', () => {
expect(
getSettingWithCoercion( 'currentUserIsAdmin', '', isString )
).toBe( '' );
} );
it( 'returns expected value for existing setting', () => {
expect(
getSettingWithCoercion( 'adminUrl', 'not this', isString )
).toEqual( ADMIN_URL );
} );
it( "returns expected value for existing setting even if it's a falsy value", () => {
expect(
getSettingWithCoercion( 'currentUserIsAdmin', true, isBoolean )
).toBe( false );
} );
} );

View File

@@ -0,0 +1,20 @@
/**
* Internal dependencies
*/
import { getSetting } from '../utils';
import { ADMIN_URL } from '../default-constants';
describe( 'getSetting', () => {
it( 'returns provided default for non available setting', () => {
expect( getSetting( 'nada', 'really nada' ) ).toBe( 'really nada' );
} );
it( 'returns expected value for existing setting', () => {
expect( getSetting( 'adminUrl', 'not this' ) ).toEqual( ADMIN_URL );
} );
it( "returns expected value for existing setting even if it's a falsy value", () => {
expect( getSetting( 'currentUserIsAdmin', true ) ).toBe( false );
} );
it( 'filters value via provided filter callback', () => {
expect( getSetting( 'some value', 'default', () => 42 ) ).toBe( 42 );
} );
} );

View File

@@ -0,0 +1,140 @@
/**
* External dependencies
*/
import compareVersions from 'compare-versions';
/**
* Internal dependencies
*/
import { allSettings } from './settings-init';
/**
* Retrieves a setting value from the setting state.
*
* If a setting with key `name` does not exist or is undefined,
* the `fallback` will be returned instead. An optional `filter`
* callback can be passed to format the returned value.
*/
export const getSetting = < T >(
name: string,
fallback: unknown = false,
filter = ( val: unknown, fb: unknown ) =>
typeof val !== 'undefined' ? val : fb
): T => {
let value = fallback;
if ( name in allSettings ) {
value = allSettings[ name ];
} else if ( name.includes( '_data' ) ) {
// This handles back compat with payment data _data properties after the move to camelCase and the dedicated
// paymentMethodData setting.
const nameWithoutData = name.replace( '_data', '' );
const paymentMethodData = getSetting(
'paymentMethodData',
{}
) as Record< string, unknown >;
value =
nameWithoutData in paymentMethodData
? paymentMethodData[ nameWithoutData ]
: fallback;
}
return filter( value, fallback ) as T;
};
export const getSettingWithCoercion = < T >(
name: string,
fallback: T,
typeguard: ( val: unknown, fb: unknown ) => val is T
): T => {
const value = name in allSettings ? allSettings[ name ] : fallback;
return typeguard( value, fallback ) ? value : fallback;
};
/**
* Note: this attempts to coerce the wpVersion to a semver for comparison
* This will result in dropping any beta/rc values.
*
* `5.3-beta1-4252` would get converted to `5.3.0-rc.4252`
* `5.3-beta1` would get converted to `5.3.0-rc`.
* `5.3` would not be touched.
*
* For the purpose of these comparisons all pre-release versions are normalized
* to `rc`.
*
* @param {string} setting Setting name (e.g. wpVersion or wcVersion).
* @param {string} version Version to compare.
* @param {compareVersions.CompareOperator} operator Comparison operator.
*/
const compareVersionSettingIgnorePrerelease = (
setting: string,
version: string,
operator: compareVersions.CompareOperator
): boolean => {
const settingValue = getSetting( setting, '' ) as string;
let replacement = settingValue.replace( /-[a-zA-Z0-9]*[\-]*/, '.0-rc.' );
replacement = replacement.endsWith( '.' )
? replacement.substring( 0, replacement.length - 1 )
: replacement;
return compareVersions.compare( replacement, version, operator );
};
/**
* Compare the current WP version with the provided `version` param using the
* `operator`.
*
* For example `isWpVersion( '5.6', '<=' )` returns true if the site WP version
* is smaller or equal than `5.6` .
*/
export const isWpVersion = (
version: string,
operator: compareVersions.CompareOperator = '='
): boolean => {
return compareVersionSettingIgnorePrerelease(
'wpVersion',
version,
operator
);
};
/**
* Compare the current WC version with the provided `version` param using the
* `operator`.
*
* For example `isWcVersion( '4.9.0', '<=' )` returns true if the site WC version
* is smaller or equal than `4.9`.
*/
export const isWcVersion = (
version: string,
operator: compareVersions.CompareOperator = '='
): boolean => {
return compareVersionSettingIgnorePrerelease(
'wcVersion',
version,
operator
);
};
/**
* Returns a string with the site's wp-admin URL appended. JS version of `admin_url`.
*
* @param {string} path Relative path.
* @return {string} Full admin URL.
*/
export const getAdminLink = ( path: string ): string =>
getSetting( 'adminUrl' ) + path;
/**
* Get payment method data from the paymentMethodData setting.
*/
export const getPaymentMethodData = (
paymentMethodId: string,
defaultValue: null | unknown = null
) => {
const paymentMethodData = getSetting( 'paymentMethodData', {} ) as Record<
string,
unknown
>;
return paymentMethodData[ paymentMethodId ] ?? defaultValue;
};