Members
-
<constant> ACCEPT_LOCK :string
-
User accepts to lock his state to load the legacy data
Type:
- string
-
accessToken
-
The JWT access token (if the user is logged in) This will be removed in the initial state sent to the client, because the client will get its own access token using the implicit auth flow
-
<constant> accountStateTypeStrings
-
GROUP & ONLINE do not map exactly to accounStates recieved from the BE They are used by groupOnlineSelector and accountStateProvider HoC
- Source:
-
<constant> addError
-
- Source:
-
<constant> AgeRanges
-
Registration age requirements For group within the 'warning' range (11 and 15) we display an additional message but don't block registration
- Source:
-
<constant> AgeType
-
Age map
- Source:
-
<constant> allFilterKeys :Array.<string>
-
Array of all filter keys. Used to build collection parameters
Type:
- Array.<string>
- Source:
-
<constant> allMonths
-
This util includes a set of functions which populate the date select filters on the weigh history page
- Source:
-
<constant> apiDayDateFormat
-
When using moment to format days which get sent off as parameters to an API it expects them to be in the format
- Source:
-
<constant> availableFlags
-
return availble flags from a list of flags, availbe in a data set
- Source:
Example
availableFlags([1,4], flags)
-
<constant> AWARD_CEREMONY :string
-
Type:
- string
- Source:
-
<constant> awardCollection
-
These collections are used to drive which awards are grouped together on the members profile screen
- Source:
-
<constant> awardDataMap
-
Award data mapping
if AwardType.NORMAL, a locale reference (plus locale entry in the award component) is needed if AwardType.WEIGHT a locale is optional, otherwise will display default message
- Source:
-
<constant> AwardDisplayType :Object
-
Award display type determines which info to render in award component
Type:
- Object
- Source:
-
<constant> AwardMap
-
Constant name is mapped to backend enum value
- Source:
-
<constant> AwardType :Object
-
Type of awards, also used for collections
Type:
- Object
- Source:
-
<constant> BASE_64_REGEX :RegExp
-
Regex for base64 value
Type:
- RegExp
- Source:
-
<constant> canStartBodyMagicAward
-
Returns if a member has has a past body magic award and not got one in progress in order to display the next award CTA
-
<constant> CHECK_COMPLETE
-
TODO: this should not be here! SWO-6268
this should be a backend task - whenever passing something into the api - we should have a response for the current status of the award! Current we send activity data to the api, then ask the api what the status is after that data.
-
<constant> clearNonSerializable
-
Clears a non serializable value stored with
registerNonSerializable -
<constant> clearScrollTo
-
Clears all the positions that should be scrolled to. Used by ScrollManager
- Source:
-
<constant> CompetitionEntryTypes
-
Informs what type of competition the user has won to change the display of the banner
-
<constant> CONFIRM_NEWSLETTER_SIGNUP
-
SevenDayMenu - newsletter signup email confirmation confirm the members email address, using the passed email address and token this endpooint adds them onto the subscriber mailing list
-
<constant> confirmEntryDetails
-
Confirms the entry details of the user
-
<constant> consultantShape :Object
-
Reusable objects to use in
propTypesfor the group search componentsType:
- Object
-
<constant> convertArrayToBitwise
-
return a single bitwise value based of an array of flags
- Source:
Example
convertArrayToBitwise([1, 5, 18, 4])
-
<constant> convertBitwiseToArray
-
return a array of values that match within a bitwise
- Source:
Example
convertBitwiseToArray(2284)
-
<constant> convertDurationToMinutes
-
This util takes time durations stored in the ISO 8601 format and returns a number of total minutes
- Source:
Example
'PT1H10M' would return 70
-
<constant> convertWeighInDay
-
Convert the users weigh in date to take into account there timezone
Example
convertWeighInDay({ weighInDate: '2019-08-21T15:17:36.2445068Z', timeZoneId: 'America/Chicago' }) -
<constant> CookingType
-
CookingType map
- Source:
-
<constant> createCommunityPost
-
Creates a new post in the community
-
<constant> createPackagePurchase
-
Create a purchase for the given package id. A package contains multiple products.
-
<constant> createPurchaseSubscription
-
TODO: rename function to createProductPurchase TODO: rename second argument from selectedPackage to product, this should then represent a single item. This will make this funciton reusable for any product
-
<constant> createSuccessStory
-
Creates a success story entry in the database, this is needed for the success story overview page
-
<constant> Cuisine
-
Cuisine map
- Source:
-
<constant> currentRoute
-
Returns the current route (url) as string
- Source:
Example
currentRoute(state)
-
<constant> currentWeightSelector
-
Selector that gets the current weight of the user. It first checks the most recent weighIn, and will fall back to the startWeight when there are no weighIns yet.
-
<constant> DataTestidOverides
-
These data attributes overides are used in certain contexts when creating cypress tests. Please see https://slimmingworlddigital.atlassian.net/wiki/spaces/DT/pages/1024458768/End-to-end+testing for more info
-
<constant> defaultViewReducers :object
-
Contains default reducers for all state that is visible to the end user. Some examples of state that belongs in this reducer:
- which recipe is currently visible on a recipe detail page
- which articles are part of the search results for the current search of the user
- if the modal window is currently open, and what content is currently being shown inside
- current value of a toggle that determines the sorting of posts on the community overview page
Some examples of state that does not belong in this reducer:
- the current state of a form. While this is technically 'view' state, this state is put into our 'form' and 'enhancedForm' reducers because it is handled by other libraries.
- the status of the users payment. This state is not (directly) visible to the user so it does not belong in 'view'
- the data representing a recipe. While a 'view' reducer might contain state about which recipe is currently visible, the data itself should be in the 'entities' reducer
Type:
- object
-
<constant> detectGroupSearchType
-
Check if a value matches a search type (e.g. a postcode or place) Return the relevant enum
-
<constant> DeviceState
-
This enum is used by the DeviceStateTracker class to determine which of the media queries in the mediaQueries object above are considered 'device states'. Names of this enum have to correspond with one of the keys in the mediaQueries object. When using the DeviceStateTracker, make sure you have enough device states so that there will always be one with a matching media query.
At any time only one "device state" will be active. This will be the last name below that has a matching breakpoint. This is usually convenient for mobile-first designs. If you want to reverse this order (for desktop-first designs, for example), set the reverseDeviceState boolean below to 'true'.
- Source:
-
<constant> DURATION_HOURS
-
Convert hours within a ISO 8601 duration string
- Source:
Example
PT1H10M would return 1
-
<constant> DURATION_MINUTES
-
Convert minutes within a ISO 8601 duration string
- Source:
Example
PT1H10M would return 10
-
<constant> END :string
-
Type:
- string
- Source:
-
<constant> entityReducer
-
A reducer that manages a single entity. The state for this reducer is an object containing the entity data.
-
<constant> environmentConfig
-
Mock store, requied when we have connected components that consume state e.g device state
- Source:
-
<constant> EXTRACT_BOTH_PARTS_OF_UK_POSTCODE_REGEX :RegExp
-
Regex pattern to extract both post card parts from a string
Type:
- RegExp
- Source:
Example
NG20OQQ
-
<constant> extractPropsFromObject
-
Retrieves properties from the given object.
- Source:
-
<constant> factSheetShape :Object
-
Reusable object to use in
propTypesfor afactSheetprop.Type:
- Object
-
<constant> FeaturesType
-
features map
- Source:
-
<constant> filterGenerator
-
You are now able to pass an optional formatter
example:
{ 0: 'value 1', 1: 'value 2', 2: 'value 3', 3: 'value 4', 4: 'value 5', formatter: object, }
note: when using the formatter it will not use the objectKeys as values anymore
- Source:
-
<constant> filterMonths
-
Returns all 12 month options in assending order but disables the ones the user cannot choose based on available months.
- Source:
-
<constant> findWeekNumberInMonth
-
Returns number of week number in month
- Source:
Example
3
-
<constant> FIRSTNAME_EMAIL_SIGNUP_REGEX :RegExp
-
Regex pattern matching a valid first name of somebody signing up to the newsletter
Type:
- RegExp
- Source:
Examples
"Chloé" would match
"www.slimmingworld.co.uk" would NOT match
-
<constant> FontWeight
-
Prefered usage
- Source:
-
<constant> FoodOptimising
-
FoodOptimising map
- Source:
-
<constant> formIsSubmitted
-
Check if a form is submitted
- Source:
-
<constant> GET_ACCOUNT_ORIGIN
-
Get user origin for tracking purposes
-
<constant> GET_AUTHENTICATOR_DETAILS
-
Get authenticator key for manual QR code register
-
<constant> GET_CURRENT_SECTION
-
Get the users current active section of the recommended reading plan
-
<constant> GET_GROUP_DETAIL_CALL
-
Public Group
-
<constant> GET_IS_BETA_MEMBER :string
-
Returns boolean whether the user has a beta account or not
Type:
- string
-
<constant> GET_IS_GROUP_MEMBER :string
-
Returns boolean whether the user is a group account or not
Type:
- string
-
<constant> GET_LEGACY_SITE_URL :string
-
Returns legacy data url
Type:
- string
-
<constant> GET_MIGRATIONS :string
-
Returns the migration id/state and userId for the migrating account
Type:
- string
-
<constant> GET_MIGRATIONS_STATE :string
-
returns the current migration state
Type:
- string
-
<constant> GET_MIGRATIONS_SUMMARY :string
-
Retrieves the summary for the weight/ goals/ awards page
Type:
- string
-
<constant> GET_SECTION_CONTENT
-
Returns the content(articles / actions) for a given section depending on section number that is passed in
-
<constant> GET_VERIFIABLE_RESOURCE :string
-
Returns the data for a specific resource (personalDetails || addresses)
Type:
- string
-
<constant> getAllMonths
-
Returns all 12 month options, populating the select component. Allowing the user to select any month to filter by
- Source:
Example
{title: May, value: "5"} -
<constant> getAntiForgeryToken
-
AFT for group account api calls
-
<constant> getAntiForgeryToken
-
AFT for group account api calls
-
<constant> getAwardsByType
-
Returns achieved awards by passed type
-
<constant> getCheckBoxValues
-
- Source:
-
<constant> getComponent
-
Gets a single component
-
<constant> getConsultantDetail
-
Action to return consultant details including bio & image
-
<constant> getConsultantGroups
-
Action to return all of the groups a consultant runs
-
<constant> getCoverPhotoById
-
Get the cover photo by id
-
<constant> getCurrentSectionContent
-
Get the users active section and then fetch the content for that section
-
<constant> getCurrentWeighIn
-
weight: 234, // If weight is present, it means first step is done emotion: 1, // If emotion and bucket are present, it means mood step is done bucket: 123, commitment: 2, // If commitment is not null, it means commitment step is done isFinished: false, // If isFinished is true, it means the weigh-in is completed and has been shared
-
<constant> getDayName
-
Format weekday as the name of the day of the week e.g. 2 becomes Tuesday
- Source:
-
<constant> getEntity
-
This is a simple helper function to get a specific entity from the entities reducer. Because memoization is not really needed here, we use this simple util instead of creating a reselect selector
-
<constant> getEnvironmentConfig
-
<constant> getFullTowns
-
Get all towns from the DB (this is not xpressweigh's list of towns)
-
<constant> getKeyByValue
-
Fetch corresponding key of a value in a object
- Source:
-
<constant> getLinkPropsFromUrl
-
Returns an object to be used as props for a link tag, that based on the url returns a different attribute name. If the url is absolute, it will use the
hrefprop to not link internally. Otherwise it will use thetoattribute to have it picked up by React Router.- Source:
-
<constant> getMembersCompetitionEntriesOverview
-
Gets a list of all the competition entries submitted by the authenticated user
-
<constant> getMembersEntryDetails
-
Gets the users personal details for a given entry
-
<constant> getMembersSuccessStoriesOverview
-
Gets a list of all the success stories submitted by the authenticated user
-
<constant> getNotifications
-
Retrieves notifications
-
<constant> getNumWeeksInMonth
-
Returns number of weeks in a given month
- Source:
Example
5
-
<constant> getOrdinalDate
-
Show the Ordinal date for example: 12th Mar, 3rd Jun etc etc
- Source:
-
<constant> getPackages
-
<constant> getPostDetail
-
Gets a single post entity from the API
-
<constant> getPublicityEntryOverview
-
Gets the current success story or competition entry for the authenticated user
-
<constant> getPublicityEntryPhotos
-
Gets the photos for the given competition or success story entry
-
<constant> getPublicityEntryQuestions
-
Gets the questionnaire for the currently active success story or competition entry
-
<constant> getTimeZoneIsoString
-
Fix the timezone issue between offices when using tests
-
<constant> getUrlParameter
-
Get specific url parameter
- Source:
-
<constant> getUserFullWeighInHistory
-
Get the users entire weigh-in history, this is designed to be temporary until we can provide weight loss calculations on the back-end (MEMEX-36). Until then we need to fetch the users entire history otherwise there are circumstances where weight-loss messaging will be incorrect.
-
<constant> getUserPermissionStateData
-
For now all micro services has the subscription type 'online'
-
<constant> GridItemType
-
GridItem represents an amount of columns from 1 through 12. classNames are passed via the enum file in the format of:
- Source:
-
<constant> hasActiveBodyMagicAward
-
Check to see if a the user has a active body magic award
-
<constant> hasCommitment
-
Check if user has a commitment/goal
- Source:
-
<constant> hasConfirmedWeighInWeight
-
Has the user started a weigh-in?
- Source:
-
<constant> hasErrorCode
-
Returns a filter that checks if an action has the given validation error code on its payload
- Source:
-
<constant> hasValidBackRoute
-
Selector that has the current routeHistory state as input and returns
trueif there is a route in the current session's history that the user can go back to. -
<constant> hasWeighInEmotion
-
Does the user selected a emotion?
- Source:
-
idToken
-
The JWT identity token (if the user is logged in) This will be removed in the initial state sent to the client, because the client will get its own access token using the implicit auth flow
-
<constant> IMAGE_REGEX :RegExp
-
Regex pattern that matches paths/urls with an image extension at it's end
Type:
- RegExp
- Source:
Example
awesome.gif
-
<constant> IMAGE_THERAPY :string
-
Type:
- string
- Source:
-
<constant> IMPLICIT_ROUTE_SILENT_RENEW_TOKEN
-
TODO: GR-397 we need to implement a proper solution to renewing access tokens after we makes changes to accountState. This is a temporary solution to get transfers working.
- Source:
-
<constant> INDEX_KEY :string
-
Key for the cookie that will contain an index of all keys in redux-persist. Will be prefixed with
KEY_PREFIXType:
- string
- Source:
-
<constant> INTERNAL_LINK :RegExp
-
The full link regex is needed, because we don't want to match uploaded image
Regex pattern that matches internal category articles
Type:
- RegExp
- Source:
-
<constant> isAtTargetSelector
-
Selector that determines if a member is at target using their currentWeight and targetWeight out of their current journey, returns false by default if member doesn't have a target weight.
-
<constant> isBfpoPostcode
-
Helper function to determine if the postcode is BFPO valid
-
<constant> isFirstWeighInSelector
-
This selector finds if a user has completed a first weigh in yet
-
<constant> isFree2GoRegisteringMember
-
Gets the free2Go value from state
- Source:
-
<constant> isFulfilled
-
Returns true if the given action has an
isAsyncandisFulfilledflag onmeta- Source:
-
<constant> isInteraction
-
Type of interaction
- Source:
-
<constant> isNotPregnant
-
Wizard step disable the pregnant weigh in final screen
- Source:
-
<constant> isNowDate
-
Check for showing NOW or the fromDate
- Source:
-
<constant> isoDaysOfWeek
-
Array with an Object string-formated isoweekdays and numeric values
- Source:
Example
isoDaysOfWeek(1) = [ {value: 1, title: 'Monday'}, {value: 2, title: 'Tuesday'}, {value: 3, title: 'Wednesday'}, {value: 4, title: 'Thursday'}, {value: 5, title: 'Friday'}, {value: 6, title: 'Saturday'}, {value: 0, title: 'Sunday'}, ]; -
<constant> isOnJourney
-
Wizard step disable the start journey if member already has once
- Source:
-
<constant> isSignalRType
-
Returns a filter that returns true when the given
signalname is on the action'spayload.- Source:
-
<constant> isValidUkPostcode
-
Helper function to determine if a UK postcode is valid, skips checks if postcode is a BFPO postcode
-
<constant> JWT_CLAUSE_MAP
-
Object that maps JWT clauses to their corresponding property names in an account entity from the API. This is used to have a consistent API to get account information from the userAccountSelector
-
keepaliveAgent
-
SWO-6317 - add keepAlive agent to reuse sockets for all outbound http requests
- Source:
-
<constant> KEY_PREFIX :string
-
Prefix for all redux-persist related cookies
Type:
- string
- Source:
-
<constant> LAST_SLASH_OCCURRENCE_REGEX :RegExp
-
A pattern to detect the last slash of an occurrence
Type:
- RegExp
- Source:
-
<constant> lastWeighInSelector
-
This combined selector is used for showing the correct current week number and mood on the progress tile
-
<constant> LINE_BREAKS_REGEX :RegExp
-
A pattern that matches linebreaks from textarea elements
Type:
- RegExp
- Source:
Example
\r\, \n
-
<constant> LIVE :string
-
Type:
- string
- Source:
-
<constant> loadYearsOptions
-
Returns available years that can be selected, ordering them most recent first
- Source:
Example
{title: May 2018, value: "2018-05-05T00:00:00+01:00"} -
<constant> LOBBY :string
-
Type:
- string
- Source:
-
<constant> makeNonSerializableSelector
-
Returns a new selector that returns looks up a piece of non serializable state
Example
const promiseSelector = makeNonSerializableSelector('promises'); const myPromise = promiseSelector(state.nonSerializable, { key: 'getHeaderContent' }); -
<constant> makeOffsetPackageSelector
-
Return the next possible package to upgrade.
-
<constant> makePackagesWithDiscountSelector
-
Uses SubscriptionPackages and voucher entities. Looks-up the voucher and checks if the package is eligible for a discount. Merges the package entity with the discount/voucher.
-
<constant> makeSelectedPackageSelector
-
Return the selected package.
-
<constant> makeWeighInsSelector
-
TEMP helper function, remove this once we implement correct profile > weighins normalisation
-
<constant> markNotificationsRead
-
Mark notifcation(s) as read
-
<constant> MATCH_EXCLUDE_ALTERNATE_LINK :RegExp
-
Matches routes that do not need a alternate link see ExcludeAlternateLinks for full list of routes excluded
Type:
- RegExp
- Source:
Example
would match 'group' from 'https://www.slimmingworld.co.uk/group/354501'
-
<constant> MATCH_FIRST :RegExp
-
Regex that pull the environment preifx from the url
Type:
- RegExp
- Source:
Example
would match 'dev' from 'http://dev-www.swlabs.digital'
-
<constant> MATCH_HYPHENS :RegExp
-
Regex matches hyphens in counties
Type:
- RegExp
- Source:
Example
would match '-' from 'https://www.slimmingworld.co.uk/counties/south-yorkshire'
-
<constant> MATCH_WHITESPACE :RegExp
-
Regex pattern matching any whitespace within the string
Type:
- RegExp
- Source:
-
<constant> matchRouteThunk
-
Match route
- Source:
Example
dispatch(matchRouteThunk(Page.AwesomePage))
-
<constant> MAX_LENGTH :number
-
Maximal character length in the input
Type:
- number
-
<constant> MealType
-
Meal type map
- Source:
-
<constant> mediaQueries
-
Define your media queries here.
- Source:
-
<constant> memberFlagCheck
-
Check against possible accountState flags and add them to an array if present
Example
memberFlagCheck(account.accountState);
-
<constant> memberIsAccountType
-
Check a user has one specific account state
Example
checking if a profile is complete memberIsAccountType(accountStateTypeStrings.GROUP_PROFILE_COMPLETE);
-
<constant> membershipCardValid
-
Check if a member is entering a valid card number
Example
groupCard: Yup.string().test(membershipCardValid),
-
<constant> metaHasField
-
Returns a filter that returns true when the given
fieldname is on the action'smeta.- Source:
-
<constant> metaHasForm
-
Returns a filter that returns true when the given
formname is on the action'smeta.- Source:
-
<constant> MFA_REGISTER_OR_VERIFY :string
-
Action to either register or verify the 6 digit code
Type:
- string
-
<constant> MIN_LENGTH :number
-
Minimal character length in the input
Type:
- number
-
Action to be executed when the BackLink component is clicked. Will look up the most recent route in the browser history for this session that does not start with the current pathname.
- if this is the previous route, a history back will be executed
- if this is an older history entry, we will do a history push to that entry
- if no such history was found (probably due to the user landing on a deeplink) we will check
the referrer url.
- if the url appears to be from a SlimmingWorld related site, perform a history back
- otherwise, redirect to the root route ('/')
-
Navigation view options for the UK public nav
- Source:
-
<constant> NO_WHITESPACE_START_AND_END_REGEX :RegExp
-
Regex pattern matching any amount of whitespace at the start of the string
Type:
- RegExp
- Source:
Example
" Name "
-
<constant> NO_WHITESPACE_START_REGEX :RegExp
-
Regex pattern matching any amount of whitespace at the start of the string
Type:
- RegExp
- Source:
Example
" Name"
-
<constant> noCurrentWeekWeighIn
-
Check if the user has a saved weigh in for the current week
Example
noCurrentWeekWeighIn({ savedWeighIn }) -
<constant> nonSerializableMap :object
-
Map of non-serializable state. Only accessed in this file and by nonSerializableActions.js. Should not be used directly.
Type:
- object
-
<constant> NOT_WHITESPACE_END_REGEX :RegExp
-
Regex pattern matching last part of string not ending with a whitespace
Type:
- RegExp
- Source:
Example
"Name "
-
<constant> ONLY_ALPHANUMERIC :RegExp
-
Match non alphanumeric charachters (excluding whitespace)
Type:
- RegExp
- Source:
Example
"Hello! it's a me, mario" would match "!',"
-
<constant> ONLY_NUMERIC :RegExp
-
Match numeric only characters (excluding whitespace)
Type:
- RegExp
- Source:
Example
"2423424234234" would match "!',"
-
<constant> ONLY_SINGLE_DIGITS :RegExp
-
Only single digit value
Type:
- RegExp
- Source:
-
<constant> ONLY_SIX_NUMERIC :RegExp
-
Only 6 digits allowed
Type:
- RegExp
- Source:
-
<constant> onOrAfterWeighInDay
-
Check if the users weighInDay is before today's day of the week
-
<constant> ORIGIN_DETECTION
-
Checks if origin is part of url
Following urls match with this pattern: acc-origin-account.slimmingworld.co.uk origin-account.slimmingworld.co.uk http://acc-origin-account.slimmingworld.co.uk https://acc-origin-account.slimmingworld.co.uk
- Source:
-
<constant> packagesSelector
-
Select all of the packages available for the user
-
<constant> pageLoadComplete
-
Action dispatched on the client side by pageLoadedMiddleware to indicate that all client side initActions have completed for a specific page.
- Source:
-
<constant> pageRenderComplete
-
Action dispatched on to indicate that rendering of components is completed
- Source:
-
<constant> PARAM_WAIT_FOR_MIGRATION_CREATION
-
We often link to pages from other microservices or from pattern-lib component. Currently they would need to import the Pages file from member or account, which is not what we want; account or member files should only import files from their own folder So instead this file lives in Common, so it can be properly imported from everywhere.
- Source:
-
<constant> passLegacyDataLoaded :RouteRequirement
-
Legacy data loaded
Type:
-
<constant> passLegacyUserLockAccepted :RouteRequirement
-
User confirmed & approved to get the legacy data
Type:
-
<constant> passSecurityAnswerNotSet :RouteRequirement
-
Bare bones user created, let's see if the user passed the security question state
Type:
-
<constant> PASSWORD_REGEX :RegExp
-
password strength - Must be 8-64 characters & have at least one number
Type:
- RegExp
- Source:
Example
daverock123 A pattern to detect the password at least 1 letter at least 1 digit between 6 to 64 characters
-
<constant> PHONE_NUMBER_REGEX :RegExp
-
Phone number regex object
Type:
- RegExp
- Source:
Examples
GB - 01234 567 890,
US - 012 345 6789,
IE - 012 3456789
CY - 01 234567,
-
<constant> pollApi
-
- Source:
Example
pollApi( () => Promise.resolve(true), // pollFunction response => !!response, // predicate ).then(console.log); // `true`
-
<constant> pollingCurrentMigrationState
-
Poll the current migration state and redirect the user to the correct page according to the state
arrayValuesToCheck = optional array that you wanted to check until the polling stops gotoRedirectPage = When you wanted to redirect to a page according to a state
-
<constant> POSTAL_CODES :RegExp
-
postal codes regex values
Type:
- RegExp
- Source:
Examples
GB: SW1 1EA
US: 12345
IE: IE1 1SW
CY: 1234
-
<constant> postcodeValid
-
Check if a member is entering a valid postcode
Example
postcode: Yup.string().test(postcodeValid)
-
<constant> postPublicityEntryAnswer
-
Saves a questionnaire answer to the database
-
<constant> postPublicityPhoto
-
Uploads a photo for a competition entry or success story
-
<constant> previousWeightSelector
-
Selector that gets the previous weight of the after having done a new weighin. It first checks the second most recent weighIn, and will fall back to the initialWeight when there are no weighIns yet.
-
<constant> priceShape :Object
-
Reusable object to use in
propTypesfor apriceprop.Type:
- Object
-
<constant> processMatches
-
Processes the result of regex match on a segment
- Source:
-
<constant> productSnapshotShape :Object
-
Reusable object to use in
propTypesfor aproductSnapshotShapeprop.Type:
- Object
-
<constant> propNameValuesToObject
-
Converts an array of property names with an array of corresponding values to an object.
- Source:
-
<constant> PUBLIC_RECIPE_DETAIL
-
Public recipe
-
<constant> PUBLIC_SUCCESS_STORIES_LANDING
-
Public Success stories landing page
-
<constant> purchaseItemShape :Object
-
Reusable object to use in
propTypesfor apurchaseItemprop.Type:
- Object
-
<constant> purchaseShape :Object
-
Reusable object to use in
propTypesfor apurchaseItemprop.Type:
- Object
-
<constant> PUT_VERIFIABLE_RESOURCE :string
-
Update the verified redux data into the database
Type:
- string
-
<constant> quickLinkShape :Object
-
Reusable object to use in
propTypesfor aquicklinkprop.Type:
- Object
-
<constant> REACT_STATICS :Array.<string>
-
An array of properties that will be transferred from the wrapped functional component to the wrapper returned by createFunctionalComponentWrapper()
Type:
- Array.<string>
-
<constant> RecipeAdditionalTimSuffix
-
Recipe additional time suffix
-
<constant> RecipeTime
-
RecipeTime map
- Source:
-
<constant> registerFixedHeaderElement
-
Register an element that is fixed on the top of the page. This is to offset scrolling to elements to make sure the fixed element does not overlap the scrolled to element.
When the element unmounts, it should dispatch unregisterFixedHeaderElement
- Source:
-
<constant> registerNonSerializable
-
Registers a non-serializable object in the redux state. The state will contain a reference to the given value, and the value itself will be stored in a static object.
Use this to store global non-serializable state that should not be shared between different users on a Node.JS node. If the state can be shared between users (like an instance of a utility class) use the
injector.jslogic instead.This value will not be shared between server and client. When the state is serialized to send to the client, this value will be stripped. If you store an instance here that is also needed on the client, you will need to create a separate instance on the client.
-
<constant> removeKey
-
Delete a key from an object Returns a new object
- Source:
-
<constant> REQUEST_PATH_REGEX :RegExp
-
Regex request path
Type:
- RegExp
- Source:
Examples
would match 'recipes/spiced-rice-pudding'
would not match 'recipes/spiced-rice-pudding-sql(test)'
-
<constant> reverseDeviceStateOrder
-
The DeviceStateTracker will set the current deviceState to the last DeviceState with a breakpoint that matches. This is usually desired in mobile-first designs. Set this value to true if the tracker should choose the first matching DeviceState instead.
- Source:
-
<constant> SAVE_ACCOUNTS_EMAIL
-
Action to check if account matched users details
-
<constant> savePurchaseInfo
-
When the payment is cancelled or failed we're storing the data like package, voucherCode and checkout details (shop) in sessionStorage to recover it after hard refresh and bring the form pre-filled with the last changes.
-
<constant> scrollTo
-
Action to cause the ScrollManager to scroll to the given Y position. If this action is called multiple times within a debounce period (defined in ScrollManager), the ScrollManager will scroll to the top most position
- Source:
-
<constant> scrollToElement
-
Wrapper for the scrollTo action that will pass the top position of the given DOM element
- Source:
-
<constant> Seasonal
-
Seasonal map
- Source:
-
<constant> SeasonalType
-
seasonal enum map for filter flags
- Source:
-
<constant> selectedFoodRangeCategories
-
Returns selected categories
-
<constant> selectedFoodRangeProducts
-
Returns selected categories products or the full products
-
<constant> SelectedRecipe
-
Featured recipes on typical day section (in the long term these will be moved in umbraco!)
- Source:
-
<constant> SET_CURRENT_SECTION
-
Update the users current active section and fetch data for that week
-
<constant> SET_LOGOUT_RESPONSE
-
NOTE: We do not import this constant from logoutResponseActions because we are not allowed to import this action file in the web build.
- Source:
-
<constant> SET_PAYMENT_RESPONSE
-
NOTE: We do not import this constant from paymentResponseActions because we are not allowed to import this action file in the web build.
- Source:
-
<constant> SET_VERIFIABLE_RESOURCE :string
-
Update the data in the redux state for a specific resource
Type:
- string
-
<constant> setCheckboxValues
-
- Source:
-
<constant> setJourneyConfirmed
-
We want to catch only validation errors as this takes the user down a seperate modal flow. All other errors we want to handle as normal - block the form and display an error message on screen
-
<constant> setPublicityEntryComplete
-
Sets a competition or success stories status to complete
-
<constant> SEVEN_DAY_MENU_SIGNUP
-
SevenDayMenu - newsletter signup form submission
-
<constant> SLIMMER_OF_THE_MONTH :string
-
Type:
- string
- Source:
-
<constant> SLIMMER_OF_THE_WEEK :string
-
Type:
- string
- Source:
-
<constant> startPayment
-
Start a payment using Adyen
-
<constant> StoriesType
-
stories map
- Source:
-
<constant> STRENGTHENING
-
strengthening - The activity is classified as being muscle strengthening
- Source:
-
<constant> strictIdCheck
-
The entities reducer will perform an additional validation on the following entity types. This is to make sure that the id key the entity is stored under matches the id property in the entity itself.
- Source:
-
<constant> stringToUrl
-
Takes a string and converts to a URL-friendly string Truncates length at 64 charachters
- Source:
-
<constant> SUBMISSION_COUNT
-
Action to check if membership card, pin and email address are already registered
-
<constant> subscriptionPackageShape :Object
-
Reusable object to use in
propTypesfor asubscriptionPackageShapeprop.Type:
- Object
-
<constant> subscriptionTypeSelector
-
DEPRECIATED: this was called groupOrOnlineSelector It uses account state bitwises to determine member type, only used for new(?) authentication under userPermissionState
-
<constant> syncValuesToRoute
-
Updates the current route query string with the provided values. If the values in the query string are already equal to the given values, no update will be dispatched.
-
<constant> TableRowColumnAmount
-
Table row column enum map to determine how many columns to render in a table row
-
<constant> TAG_REGEX :RegExp
-
Regex pattern matching fragment starting with an @ followed by zero or more alphanumeric characters
Type:
- RegExp
- Source:
Example
@person
-
<constant> TextTypes
-
Market differences for text styles
- Source:
-
thunkIdCount :number
-
Incrementing counter to assign thunk ids to async actions
Type:
- number
- Source:
-
<constant> THUNKS_NAMESPACE :string
-
Namespace to use in the nonSerializable reducer
Type:
- string
- Source:
-
<constant> transformUbbToHTML
-
Replaces UBB codes to HTML tags
-
<constant> unregisterFixedHeaderElement
-
Unregisters an element that was registered with registerFixedHeaderElement
- Source:
-
<constant> updatePublicityEntryAnswer
-
Updates the answer to a question
-
<constant> URL_AFTER_LAST_SLASH_REGEX :RegExp
-
Regex pattern matching the section of url after the last slash
Type:
- RegExp
- Source:
Example
"recipe/breakfast/fry-up" would match "fry"
-
<constant> useForWmfcPollingStatesArray
-
This method is only used after the signUp call when the requireNewPassword = false
location = location object
-
<constant> userAccountByIdSelector
-
Retrieve a user account by id
-
<constant> userAccountSelector
-
Selector that receives the root redux state and returns an object with user information. If the user is not logged in, this selector returns null. If the user is logged in but the account entity is not loaded from the API, this object will contain a limited amount of properties which are available on the access token.
-
<constant> userGroupIdsSelector
-
Selector that extracts the user groupIds from the userAccountSelector. Returns empty array if no account data is available
-
<constant> userGroupSelector
-
Selects the members first group
- A member should only ever be able to join one group however the api returns an array of groups
- Source:
-
<constant> userGroupsSelector
-
Selects member groups
- Source:
-
<constant> userIdSelector
-
Selector that extracts the user id from the userAccountSelector. Returns null if no account data is available
-
userInfo
-
An object containing the decoded clauses in the JWT access token (if the user is logged in). This information will be available as initial state to the client. This is to make sure the clauses in the token are immediately available on the client, without having to wait for the implicit auth flow to complete. For that reason, some technical clauses that are specifically meant for the server token are not included in this object (like nbf, issuer, exp)
__PLEASE NOTE: __ As we want a single source of truth for account information, it is best not to use this state directly. Instead, use the userAccountSelector available in the
reducersfolder. -
<constant> userProfileSelector
-
Selector that receives the root redux state and returns an object with user profile. If the user is not logged in, or if the user is logged in but the profile entity is not loaded from the API, this selector returns null.
-
<constant> userWeighInsSelector
-
Instance of weighInSelector that does not pass props, and thus will always get the weighins for the current user.
-
<constant> validateBasket
-
Validates that the products in the basket are up to date.
-
<constant> VERIFIED_IDENTITY_TOKEN
-
Save new email
-
<constant> VERIFY_SECURITY_ANSWER
-
Verify security answer
-
<constant> voucherSelector
-
Selects the voucher based on the given VoucherCode
-
<constant> webHosts :Array
-
Array of webHost values
Type:
- Array
- Source:
-
<constant> weeklyGoalSet
-
Check if the user has set a weekly commitment for the current weigh in
Example
weeklyGoalSet({isCurrentWeighInFinished: true, savedWeighIn }) -
<constant> weighInByIdSelector
-
Selector for selected weigh-in by id
-
<constant> weighInHistorySelector
-
Select weigh-in history
-
<constant> weighInToAddSelector
-
Selector for weigh-in to add
-
<constant> WeightLossType
-
Camelcased by filterGenerator to match a locale key
- Source:
-
<constant> weightLowerRange
-
Checks weight value against the defined lower range for weight Called from inside a validation rule
-
<constant> weightUpperRange
-
Checks weight value against the defined upper range for weight Called from inside a validation rule
-
<constant> WELCOME :string
-
Type:
- string
- Source:
-
<constant> XmlSchemaNamespace
-
Based on: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/security/claims/ClaimValueTypes.cs
-
<constant> YOUTUBE_REGEX :RegExp
-
Regex pattern that matches youtube video urls
Type:
- RegExp
- Source:
Methods
-
address(addressType)
-
Parameters:
Name Type Description addressTypestring | current validations address type Returns an object with validation fields filled for address type and region
-
asyncActionTypes()
-
Reducer that keeps track of each actionType for which an async action is currently pending. The state has the following shape:
{ [actionType]: <numberOfPendingCalls> } -
awardComparer(a, b)
-
Sort awards by datetime
Parameters:
Name Type Description abReturns:
- Type
- number
-
batchLoadFoodPlannerDays(Date)
-
Returns a promise to batch load a set of food planner days Used when switch to a new day in the planner or on first load of the page
Parameters:
Name Type Description Datestring The at which you want the days to be fetched from
Returns:
an array of promise which needs to be wrapped in a Promise.All
- Type
- array
Example
2018-07-20 would return food planner days for [2018-07-18, 2018-07-19, 2018-07-20, 2018-07-21, 2018-07-22]
-
cancellableCallback(callback)
-
Returns a new function that has a
cancel()method on it. When the cancel method is called, the passed callback will be unreferenced so it is available for garbage collection. After that, any future calls to the returned function will be ignored.This util is meant to be used when having callbacks inside a React component. Once the component is unmounted, the callback can be cancelled so the react component itself is unreferenced and no further calls to
setState()are made from the callback. See isMounted is an AntipatternParameters:
Name Type Description callbackfunction The callback to wrap
- Source:
Returns:
- Type
- function
-
centimetersToInches(centimeters)
-
Converts centimeters to inches
Parameters:
Name Type Description centimeters- Source:
Returns:
in inches
- Type
- number
-
centimetersToMeters(centimeters)
-
Converts Centimeters to meters
Parameters:
Name Type Description centimeters- Source:
Returns:
[meters, centimeters]
- Type
- Array
-
chopMemberNames()
-
Creates parsering chop table for mention related content
Parameters:
Type Description -
cleanseId(name)
-
Create an id from a given string
Parameters:
Name Type Description name- Source:
Returns:
- Type
- string
-
closeModal()
-
Closes the active modal window. If a 'modal' query parameter is defined, remove that query parameter instead of dispatching the CLOSE_MODAL action. This will close any modals that are opened through query routing.
-
clubTenViewSettings()
-
Work out value and when to show the line that shows 90% of your initial weight
Parameters:
Type Description -
combineReducersNamed(reducerMap)
-
Wrapper function to combinedReducer that will add a name to the reducer. The name will be passed on to child named reducers, such that each reducer will automatically have a name that matches the nesting of the reducer. For example, a reducer nested as:
{ view: { pages: { homePage: { myReducer } } } }will have the name
view.pages.homePage.myReducer.This name is used by the
targetedReducer()utility. It makes sure that the passed reducer will only respond to actions with atargetproperty in the actionmetathat matches the reducer name.Parameters:
Name Type Description reducerMapA map containing child reducers. This uses the same syntax as the redux
combineReducersparameter. See combineReducersReturns:
A named reducer. This reducer should only be included in another named reducer.
- Type
- function
-
commonTrackEvent(category, action, label)
-
Dispatches a GENERIC_TRACK_EVENT action. This will not update any reducer but instead be picked up by redux-listeners-middleware, where actual dataLayer tracking can be performed.
Parameters:
Name Type Description categorystring Tracking category
actionstring Tracking action
labelstring Tracking string
- Source:
-
composeCheckboxesToArray(values)
-
Converts a list of checkboxes with names '0', '1', '2', etc... to an array containing all the keys that are checked.
example:
3 checked, 2 checked, 1 unchecked, 0 uncheckedwill be converted to[3, 2]Parameters:
Name Type Description valuesobject The values of all the checkboxes
Returns:
- Type
- array
-
composeCheckboxesToBitwise(values)
-
Converts a list of checkboxes with names '0', '1', '2', etc... to a number value representing the bitwise combination of all checkbox states.
example:
3 checked, 2 checked, 1 unchecked, 0 uncheckedwill be converted to1101, so the number output of the formatter will be13Parameters:
Name Type Description valuesobject The values of all the checkboxes
Returns:
- Type
- number
-
composeCheckboxesToCommaDelimitedString(values)
-
Converts a list of checkboxes with names 'value-1', 'value-2', 'value-3', etc... to an comma delimited string
Parameters:
Name Type Description valuesobject The values of all the checkboxes
- Source:
Returns:
- Type
- array
-
composeDate(values)
-
Composes the values of the DateFieldGroup inputs into a single date string
Parameters:
Name Type Description valuesobject Properties
Name Type Description daystring A string containing an integer value representing the day number
monthstring A string containing an integer value representing the month number
yearstring A string containing an integer value representing the year number
Returns:
A date string formatted as YYYY-MM-DD postfixed with T00:00:00Z (because backend expects a timezone indication)
- Type
- string
-
composeDuration(values)
-
Composes the values of the Duration inputs into a single string
Parameters:
Name Type Description valuesobject Properties
Name Type Description hoursstring A string containing an integer value representing the hours number
minutesstring A string containing an integer value representing the minutes number
Returns:
a duration string formatted in ISO8601 format see https://en.wikipedia.org/wiki/ISO_8601 for more info
- Type
- string
Example
values {hours: 3, minutes: 5} would return string 'PT3H5M' -
composeHeightImperialToMetric(formValues)
-
Converts values from the HeightImperialFieldGroup input into a number value in meters
Parameters:
Name Type Description formValuesobject Properties
Name Type Description feetstring A string that contains an integer representing the amount of feet
inchesstring A string that contains an integer representing the amount of inches
Returns:
The resulting number value in centimeters
- Type
- number
-
composeWeightImperialToMetric(formValues)
-
Converts values from the WeightImperialFieldGroup input into a number value in kilograms
Parameters:
Name Type Description formValuesobject Properties
Name Type Description fullPoundsstring A string that contains an integer representing the amount of pounds
remainingPoundsstring A string that contains an integer representing the any non-whole pounds, rounded to the nearest half
Returns:
The resulting number value in metric (kilos)
- Type
- number
-
composeWeightImperialWithStonesToMetric()
-
Converts values from the WeightMetricFieldGroup with stones input into a number value in pounds and then in kilograms.
- Source:
Returns:
The resulting number value in kilograms
- Type
- number
-
composeWeightMetric()
-
Converts values from the WeightMetricFieldGroup input into a number value in kg.
Returns:
The resulting number value in kg
- Type
- number
-
contactSupportParam()
-
Put commonly used locale params in ths file
-
convertToWebP()
-
replace known images formats for webp if availble
- Source:
-
convertWeightValue(asCompleteString,)
-
Takes a kilogram weight and returns as constituent units, with labels.
Parameters:
Name Type Description asCompleteString,return as JSX (default) or a string
Example
{weight: 115, weightUnit: MeasureUnit.IMPERIAL, imperialWeightUseStones: true} returns 18st 1lb ½ -
createDataArraySelector()
-
Custom memoization function for makeMemoizedGetEntities(). It runs through both arrays of objects and checks if the data property inside them is the same (strict equality)
-
createFunctionalComponentWrapper(wrapper)
-
note this does not create a true higher-order component. The inner component will not have it's own lifecyle methods, it is just a function call. This is slightly cheaper than wrapping the component with another component.
Enhanced the given component wrapper function to make it also transfer all the react-related statics on a component onto the wrapper. This is needed because unlike a normal HoC the inner functional component is not rendered by React. It is simply a function call. This means that all the static (propTypes, contextTypes, defaultProps) are lost if not copied over explicitly to the wrapped function.
Parameters:
Name Type Description wrapperfunction A function that takes a functional component and returns a new functional component.
Returns:
A function that will use the original wrapper function to create a new functional component and also transfers the react-related statics onto the new component.
- Type
- function
-
createQueryHistory(mainHistory, queryParam)
-
Creates a memoryHistory instance for a query parameter with query routing. Listens for changes in the main history and syncs the query parameter to the created query history.
This is only called in a web build. On the server side we don't do any further navigation after first render, so we aren't interested in the history.
Parameters:
Name Type Description mainHistoryObject The main history object
queryParamstring A query parameter to create a history for
Returns:
A history object for the query parameter
- Type
- Object
-
<async> createStoreInstance(reducer, cookies, history, authentication)
-
Creates store instance on the server
Parameters:
Name Type Description reducerThe main reducer for the store
cookiesobject Cookies object, used for redux-persist
Properties
Name Type Description jarobject The req.cookies object from express
setfunction The response.setCookie function from express
clearfunction The response.clearCookie function from express
historyThe history instance that will be synced with react-router-redux
authenticationobject This object contains id_token and access_token set up by BE.
Returns:
A redux Store instance
- Type
- Store
-
daysSince(date)
-
Takes a date and returns how many days have past
Parameters:
Name Type Description date- Source:
Returns:
- Type
- number
-
daysToYearsAndDays(days)
-
Converts days to years and days
Parameters:
Name Type Description days- Source:
Returns:
- Type
- string
-
dec2hex()
-
Copyright (C) 2007 Richard Ishida ishida@w3.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version as long as you point to http://rishida.net/ in your code.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. http://www.gnu.org/licenses/gpl.html
Source: https://r12a.github.io/apps/conversion/conversionfunctions.js
- Source:
-
decomposeCheckboxesToArray(values, currentValues)
-
Decomposes the value composed by composeCheckboxesToArray().
Parameters:
Name Type Description valuesArray.<string> The combined bitwise value
currentValuesobject The current values of the checkboxes
- Source:
- See:
Returns:
An object containing individual values for checkboxes
- Type
- object
-
decomposeCheckboxesToBitwise(bitwise, currentValues)
-
Decomposes the value composed by composeCheckboxesToBitwise().
Parameters:
Name Type Default Description bitwisenumber | string 0 The combined bitwise value
currentValuesobject The current values of the checkboxes
- Source:
- See:
Returns:
An object containing individual values for checkboxes
- Type
- object
-
decomposeDate(dateString)
-
Convert a combined date string back into separate day, month and year input values
Parameters:
Name Type Description dateStringstring A date string formatted as 'YYYY-MM-DD', optionally postfixed with T00:00:00Z
Returns:
The input values
- Type
- Object
-
decomposeDuration(durationString)
-
Convert a combined duration string back into separate hours and minutes input values
Parameters:
Name Type Description durationStringstring A duration string formatted as 'PT0H0M'
Returns:
The input values
- Type
- Object
-
decomposeHeightImperialToMetric(centimeters)
-
Converts values from cm to feet/inches
Parameters:
Name Type Description centimetersstring A string that contains an integer representing
Returns:
The resulting object should be { feet, inches }
- Type
- object
-
decomposeHeightMetric(centimeters)
-
Converts values from centimeters to { meters: 0, centimeters: 0 }
Parameters:
Name Type Description centimetersstring A string that contains an integer representing the amount of centimeters
Returns:
The resulting number value in { meters: 0, centimeters: 0 }
- Type
- object
-
decomposeWeightImperialToMetric(kilos)
-
Converts values from kilos to pounds
Parameters:
Name Type Description kilosstring A string that contains an integer representing the amount of kilograms
Returns:
The resulting object with { fullPounds, remainingPounds }
- Type
- object
-
decomposeWeightImperialWithStonesToMetric()
-
Converts values from kilos to pounds with stones
- Source:
Returns:
The resulting object value in { stones, fullPounds, remainingPounds }
- Type
- object
-
decomposeWeightMetric(kg)
-
Converts from kilograms to object { kilos, grams }
Parameters:
Name Type Description kgnumber A number that contains an integer representing the amount of kilograms
Returns:
The resulting object value in { kilos, grams }
- Type
- object
-
dedupeAsyncThunk(thunk [, withArgs])
-
Wraps a given thunk action to prevent it from executing multiple times simultaneously within a single request. If an execution is already pending when calling the action creator, it will return the promise for that execution. NodeJS may execute the given thunk multiple times in parallel, as long as it is not tied to the same request. Once the Promise returned by the given thunk action creator has resolved, it may be executed again.
Parameters:
Name Type Argument Default Description thunkfunc A thunk action creator that returns a promise
withArgsboolean <optional>
false If true, will only prevent duplicate calls with the same arguments. important: the supplied arguments should be serializable
- Source:
Returns:
A wrapped thunk action creator
- Type
- function
-
deriveKeysSP800_108_CTR_HMAC512(masterKeyBuffer, labelBuffer, contextBuffer)
-
Executes the SP800-108 algorithm in counter mode with HMAC-SHA512 as PRF
Parameters:
Name Type Description masterKeyBufferBuffer labelBufferBuffer contextBufferBuffer Returns:
A Buffer containing the result of the SP800-108 key derivation algorithm
- Type
- Buffer
-
detectEmoji(input)
-
Detects an user tagging in each SEGMENT_RAW message segment provided to
input. If an emoticon is detected, will convert it to a SEGMENT_EMOJI and attach a emoji object.Parameters:
Name Type Description inputArray.<Object> An array of message segments
Returns:
The processed array of message segments
- Type
- Array.<Object>
-
detectImageUrl(input)
-
Detects External image urls in each SEGMENT_URL message segment provided to
input. If a image url is detected, will convert it to a SEGMENT_EXTERNAL_IMAGE and attach a image object.Parameters:
Name Type Description inputArray.<Object> An array of message segments
Returns:
The processed array of message segments
- Type
- Array.<Object>
-
detectInternalUrl(input)
-
Detects an user tagging in each SEGMENT_URL message segment provided to
input. If a user tag is detected, will convert it to a SEGMENT_INTERNAL_LINK and attach a internal url object.Parameters:
Name Type Description inputArray.<Object> An array of message segments
Returns:
The processed array of message segments
- Type
- Array.<Object>
-
detectLineBreak(input)
-
Detects urls in all SEGMENT_RAW message segments using the
linkify-itmodule and converts them into a SEGMENT_URL.Parameters:
Name Type Description inputArray.<Object> An array of message segments
Returns:
The processed array of message segments
- Type
- Array.<Object>
-
detectSubsampling()
-
Detect subsampling in loaded image. In iOS, larger images than 2M pixels may be subsampled in rendering.
- Source:
-
detectTag(input)
-
Detects an user tagging in each SEGMENT_URL message segment provided to
input. If a user tag is detected, will convert it to a SEGMENT_TAG and attach a user tagging object.Parameters:
Name Type Description inputArray.<Object> An array of message segments
Returns:
The processed array of message segments
- Type
- Array.<Object>
-
detectUrl(input)
-
Detects urls in all SEGMENT_RAW message segments using the
linkify-itmodule and converts them into a SEGMENT_URL.Parameters:
Name Type Description inputArray.<Object> An array of message segments
Returns:
The processed array of message segments
- Type
- Array.<Object>
-
detectVerticalSquash()
-
Detecting vertical squash in loaded image. Fixes a bug which squash image vertically while drawing into canvas for some images.
- Source:
-
detectYoutubeVideo(input)
-
Detects YouTube video urls in each SEGMENT_URL message segment provided to
input. If a youtube url is detected, will convert it to a SEGMENT_YOUTUBE_VIDEO and attach a video object.Parameters:
Name Type Description inputArray.<Object> An array of message segments
Returns:
The processed array of message segments
- Type
- Array.<Object>
-
encodeBase64(itemsDictionary)
-
Encodes basket content object to Base64 string
Parameters:
Name Type Description itemsDictionary -
ensureTagsClosed(text)
-
Closes any open tags
Parameters:
Name Type Description textReturns:
Parsed text
- Type
- string
-
entitiesReducer()
-
The root reducer for all entities. It contains a entityTypeReducer for each entity type. These reducers are called automatically when an action of the relevant type is dispatched.
state structure: { [entity type]: entityTypeReducer(), ... }
-
entityTypeReducer()
-
Reducer for a list of entities of a single entity type. The state is structured as a map with ids as key and calls the entityReducer for the value.
{ [entity id]: entityReducer(), ... }
-
extractPayloadSignature(data)
-
Extracts the payload and the signature from raw data returned by the RsaSignatureCookieTransform util. See: https://msdn.microsoft.com/en-us/library/microsoft.identitymodel.web.rsasignaturecookietransform.aspx
Parameters:
Name Type Description dataBuffer The raw data to extract from
- Source:
Returns:
An object containing the following properties:
- {Buffer} payloadRaw The raw payload data
- {string} payload The payload decoded using utf8 encoding
- {Buffer} signature The signature
- Type
- Object
-
formatAddressType(addressField, addressType)
-
Returns amended fieldnames
Parameters:
Name Type Description addressFieldstring | address fieldname
addressTypestring | billing, shipping or null
-
formatKeyId(keyIdBuffer)
-
Formats a key id from the given Buffer.
Parameters:
Name Type Description keyIdBufferBuffer The buffer to read the key from
Returns:
A key id formatted as the output of the Guid.toString() method: https://msdn.microsoft.com/en-us/library/560tzess(v=vs.110).aspx The format looks like so: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
- Type
- string
-
formatTimeDuration(duration)
-
This util takes time durations stored in the ISO 8601 format and returns a hours and minutes object
Parameters:
Name Type Description durationString The duration stored in ISO 8601 format see https://en.wikipedia.org/wiki/ISO_8601 for more info
- Source:
Returns:
- Returns an object of hours and mintues
- Type
- object
Example
'PT1H10M' would return {minutues: 10, hours: 1} -
FormRouteSync()
-
Utility component that syncs the form values of the form it is placed in to the route query string. When the fields given to the
fieldsprop change value, the component calls thesyncValuesToRouteaction, which will update the route to match the values.Note: this util works one-way. It will not sync updates in the query back to the form values.
-
fractionalNumberToLocale(value)
-
Converts fractional number in decimal (only support mantissa of 5).
Parameters:
Name Type Default Description valuenumber 0 fractional number in integer and decimal (1.5)
Locale files cannot handle decimal correctly, this function will split the decimal and pass to the Locale files as an object with {NUMBER, HALF} example: getMessage('general.number.shortLabel', fractionalNumberToLocale(number))
-
generateAad(keyIdBuffer, purposeStrings)
-
Generates the additionalAuthenticatedData (AAD) that is used as label in the key derivation algorithm. The format is undocumented but derived from the ASP.NET source code: https://github.com/aspnet/DataProtection/blob/dev/src/Microsoft.AspNetCore.DataProtection/KeyManagement/KeyRingBasedDataProtector.cs#L314
Parameters:
Name Type Description keyIdBufferBuffer A buffer containing the 128bit key id.
purposeStringsArray.<string> An array of purpose strings passed to the IDataProtector instance that performed the cookie encryption. These purposes are used to create the AAD which is used as input to the key derivation function. See: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/purpose-strings?view=aspnetcore-2.1
Returns:
- Type
- Buffer
-
getAllowCacheHeaders()
-
Returns object with parsed max-age value and public form response
- Source:
-
<async> getAppConfigSettings(environmentVariables, labelFilter, keyFilter)
-
Create connection to retrieves the settings from a label or key
Parameters:
Name Type Description environmentVariableslabelFilterkeyFilterReturns:
-
getAssetData(awardId)
-
Retrieves asset data
Parameters:
Name Type Description awardId- Source:
-
getAvailableMonths(startDate, endDate)
-
Returns the months between two dates
Parameters:
Name Type Description startDateobject Moment date
endDateobject Moment date
- Source:
Returns:
An array of objects which include year, month year and month combined and utc date
- Type
- array.object
-
getContextHeader()
-
Generates a context header according to the following specification: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/context-headers?view=aspnetcore-2.1
Returns:
the generated context header
- Type
- Buffer
-
getCountry(current, addressType)
-
Returns users region
Parameters:
Name Type Description currentobject form values
addressTypeobject form prefix
- Source:
-
getCountryFieldRules(region, fieldName, rule)
-
Returns rules for region specific field
Parameters:
Name Type Description regionstring fieldNamestring rulestring -
getCurrentAge()
-
can take a complete ISO-8601 date like '2011-02-02T00:00:00Z' @returns number
- Source:
-
getDaysBetween(startDate, endDate)
-
Returns number of days from now until date passed through
Parameters:
Name Type Description startDatethe startDate value
endDatethe date value that we are comparing to the startDate
- Source:
-
getDefaultApiEntityTransform(path, actionType)
-
Returns default transform used to modify entities from the api before they are saved in the redux state. Adds a timestamp, the api path and the action type to the function.
Parameters:
Name Type Description pathstring The path of the api request
actionTypestring The action type that was used to make the request
Returns:
A function that transform the
- Type
- function
-
getEnvironmentFromHost(host)
-
Parse the host string and try to extract the environment being referenced
Parameters:
Name Type Description hostThe host path (e.g. www.contoso.com)
- Source:
-
getFraction(value, fractionClamp)
-
Parameters:
Name Type Default Description valueNumber 0 The value which should be converted
fractionClampNumber 2 Clamps the restFraction value to given exponent, 1 = whole number, 2 = halves, 4 = quaters etc
- Source:
-
<async> getGroupId(groupId, getState)
-
Retrieve the groupId
Parameters:
Name Type Description groupIdgetState- Source:
Returns:
- Type
- Promise.<*>
-
getHoursBetween(startDate, endDate)
-
Returns number of hours from now until date passed through
Parameters:
Name Type Description startDatethe startDate value
endDatethe date value that we are comparing to the startDate
- Source:
-
<async> getKeyVaultValue(appSettingValue)
-
Retrieves the value from the Azure keyVault secret
for example: '{"uri":"https://uk-shared-slimmingworld.vault.azure.net/secrets/uk-shared-instagram-accesstoken"}'
- parse string into an object
- check for the vaultName and secretName
- fetch the keyVaultSecret object
Parameters:
Name Type Description appSettingValueReturns:
- Type
- Promise.<(string|*)>
-
getMinutesBetween(startDate, endDate)
-
Returns number of minutes from now until date passed through
Parameters:
Name Type Description startDatethe startDate value
endDatethe date value that we are comparing to the startDate
- Source:
-
getMonthsBetween(startDate, endDate)
-
Returns number of days from now until date passed through
Parameters:
Name Type Description startDatethe startDate value
endDatethe date value that we are comparing to the startDate
- Source:
-
getOrdinalNum()
-
Add ordinal to the day digit
- Source:
-
getOrientation(image)
-
Get rotation of a image Resolving with -1: not defined Resolving with -2: not jpeg
Parameters:
Name Type Description image- Source:
-
getPublicPrices(category, item)
-
Returns a market-specific price with currency symbol if defined, else return UK price in pounds
Parameters:
Name Type Description categorye.g. "group"
iteme.g. "magazine"
- Source:
-
<async> getTransformedSettingsArray(environmentVariables, settingsIterator)
-
Iterate through the Symbol.asyncIterator and returns an new array with only the data we want
Parameters:
Name Type Description environmentVariablessettingsIteratorReturns:
-
getValueWithTwoDecimals()
-
Round a value to max. two decimals
-
getWeekName()
-
Takes day as a number and returns text string
- Source:
Example
given 4, will return "Thursday"
-
getYearsSince(startDate, endDate)
-
Returns the years that two date span over
Parameters:
Name Type Description startDateobject Moment date
endDateobject Moment date
- Source:
Returns:
An array of years
- Type
- array.number
Example
Passing in start date of 2017 and end date of 2019 would return [2017, 2018, 2019]
-
groupByFirstChar()
-
Takes an Array and returns and object of grouped values
Parameters:
Type Description Array - Source:
Returns:
Example
given ["zebras","cats","bats"]
-
groupOrOnlineSelector()
-
Given a MemberType (1 || 0) will return 'group' 'online' 'public'
-
groupSubscriptionHelper(xpressWeighState)
-
Convert Group Membership information to determine which locales, buttons or subsections to display on "membership status" account settings page and homepage Note this function will not make any assumptions about a member type (Group or Online)
Parameters:
Name Type Description xpressWeighStateObject an object from /account/api/v1/accounts/me/group-membership-details
Returns:
-
locale
- Type
- String
-
actions, optional, used to display CTAs or not
- Type
- Object
-
timeUnits, optional, weeks inactive
- Type
- Number
-
displayOnHomepage, optional
- Type
- Bool
-
-
imageInputRestFormatter(images)
-
Formats it to backend API specification
Parameters:
Name Type Description imagesReturns:
- Type
- *
-
inchesToCentimeters(inches)
-
Converts inches to centimeters
Parameters:
Name Type Description inches- Source:
Returns:
in centimeters
- Type
- number
-
inchesToFeet(inches)
-
Converts inches to feet
Parameters:
Name Type Description inches- Source:
Returns:
[feet, inches]
- Type
- array
-
isBeforeOrAfter(startDate, moment)
-
Returns true if a date or time is in the future Will default to market config if no format is passed in todo: SWO-4930 update Configuration.dateFormat to return a ISO or RFC2822 value
Parameters:
Name Type Description startDatestring Moment date
momentstring format e.g 'YYYY-MM-DD'
- Source:
Returns:
- Type
- boolean
-
isLocalOrDevelopment()
-
Returns
truein each of the following cases:- we are running a development build
- we are running a distribution build locally (identified by the
NODE_ENVenvironment variable being"development"or"localhost") - we are running a distribution build on the
developmentenvironment (e.g. https://dev-account.slimmingworld.com)
Returns
falseotherwiseReturns:
- Type
- boolean
-
isPastOrCurrentDate(date)
-
Returns true if date is the same or before the current date
Parameters:
Name Type Description datestring Date you want to compare againist the current date
- Source:
Returns:
- Type
- boolean
-
isWithinDateRange(date, dateRange)
-
Returns true if the date passed in is on the start or end date or inbetween it
Parameters:
Name Type Description datestring Date you want to check is within the date range
dateRangeobject The range in which you want to check the date is within this must have a end & start date within
- Source:
Returns:
- Type
- boolean
-
kilogramsToPounds(kgs)
-
Converts kilograms to pounds
Parameters:
Name Type Description kgs- Source:
Returns:
in pounds
- Type
- number
-
kilogramsToStones(kilograms)
-
Converts kilograms to stones
Parameters:
Name Type Description kilograms- Source:
Returns:
in stones
- Type
- number
-
kmToMiles(km)
-
Converts KM to miles
Parameters:
Name Type Description km- Source:
Returns:
- Type
- number
-
loadImage(url)
-
Set image src
Parameters:
Name Type Description url- Source:
Returns:
- Type
- *
-
makeIsLoadingSelector(actionTypes)
-
Creates a selector that returns
trueif an async action is currently pending for any of the given action types.Parameters:
Name Type Argument Description actionTypesstring <repeatable>
One or multiple action types to check for an isLoading state
Example
export default connect( () => { const isLoadingPostsSelector = makeIsLoadingSelector(GET_POSTS); return state => ({ isLoadingPosts: isLoadingPostsSelector(state), }); } )(MyComponent); -
MarkAsRead()
-
Stub component
- Source:
-
matchRoute(routeToMatch, state)
-
Match route
Parameters:
Name Type Description routeToMatchstring the route to match
stateobject the state object
- Source:
Example
matchRoute(Pages.AwesomePage, state)
-
MegaPixImage()
-
MegaPixImage class
- Source:
-
msUrlTokenDecode(data)
-
Util to base64 decode a string that has been encoded using the HttpServerUtility.UrlTokenEncode method. See: https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.urltokenencode(v=vs.110).aspx
Note: do not include this util in the web build. This will cause webpack to include large polyfills for the NodeJS Buffer Class.
Parameters:
Name Type Description datastring The data to decode
- Source:
Returns:
A NodeJS buffer with the decoded data
- Type
- Buffer
-
noBodyMagicAwards(isPrivate, awards, activeBodyMagicAwardLength, awardType)
-
Returns if we should display the start body magic award call to action
Parameters:
Name Type Description isPrivateawardsactiveBodyMagicAwardLengthawardType -
nonSerializableReducer()
-
Reducer to store global non-serializable per-user state.
Use this to store global non-serializable state that should not be shared between different users on a Node.JS node. If the state can be shared between users (like an instance of a utility class) use the
injector.jslogic instead.This state will not be shared between server and client. When the state is serialized to send to the client, this state will be stripped. If you want an instance to be available on the server and the client, you will need to register a separate instance with this reducer on both sides.
-
noWeightLossAwards(isPrivate, isOnJourney, awards, upcomingAwardLength, awardType)
-
Returns if we should display the start weight loss award call to action
Parameters:
Name Type Description isPrivateisOnJourneyawardsupcomingAwardLengthawardType -
openModal(component, props [, showCloseButton] [, enableCloseOnBackdrop] [, isFullBleed])
-
Opens a modal window
Parameters:
Name Type Argument Default Description componentstring The name of the modal component to display. Should be one of the components in /atoms/modals/ use Modal type enum
propsobject The props to pass to the modal component. Should be serializable as these are stored in redux state
showCloseButtonboolean <optional>
true Shows a close button in the modal window
enableCloseOnBackdropboolean <optional>
true Allows the user to close
isFullBleedboolean <optional>
true Shows the modal full bleed the modal window by clicking on the backdrop behind the modal
-
parseRoutesRequirements(routes)
-
Looks up the route requirements by looking at the
requirementsprop on the given routes array. Therequirementprop on child routes overrides those on parent routes, so this function will only use the lastrequirementsprop it can find.Returns an array of which route requirements must be met, based on the requirements in the
requirementsprop and its child requirements.If none of the routes have a
requirementsprop defined, this will return an empty array.Parameters:
Name Type Description routesArray An array of react-router
instances. Returns:
An array of RouteRequirement instances.
- Type
- Array.<RouteRequirement>
-
patchLocalStorageDebug()
-
Patches the debug variable on localStorage to ensure that SlimmingWorld debug statements are shown during development.
-
poundsToKilograms(pounds)
-
Converts pounds to kilograms
Parameters:
Name Type Description pounds- Source:
Returns:
in kilograms
- Type
- number
-
poundsToStones(pounds)
-
Converts pounds to stones
Parameters:
Name Type Description pounds- Source:
Returns:
[stones, pounds]
- Type
- Array
-
prependWebHost(environmentConfig, path [, webHost])
-
Will prepend the given webHost from the environment config to the given path, except when the given webHost is the same as the current webHost. This will make sure that we don't create a full url (with host) when a root-relative path will suffice.
Parameters:
Name Type Argument Default Description environmentConfigobject The full environment config object
pathstring The path. Should be one of the paths defined in Pages.js
webHoststring <optional>
null The webHost to redirect to. Should be one of the strings from the WebHost.js enum. If omitted, will never prepend a host
- Source:
-
processQueryRouting(route, mainHistory)
-
Processes the
configuration nested inside the routing config. Will create history instances for each defined . Parameters:
Name Type Description routeThe current route. This function will be called recursively
mainHistoryThe history instance of the main routing
-
readChunkedCookie(cookieStore, cookieName)
-
Reads a cookie stored by ASP.NET core ChunkingCookieManager
Parameters:
Name Type Description cookieStoreObject an object containing all cookies
cookieNamestring the name of the cookie to read
Returns:
A buffer containing the cookie payload if set, null otherwise
- Type
- Buffer | null
-
redirectToMigrationErrorPage()
-
Redirect the user to the specific error content page
Returns:
- Type
- function
-
reducePublicGroupSessions()
-
Reduce function to create group session information
-
renderImageToCanvas()
-
Rendering image element (with resizing) into the canvas element
- Source:
-
renderImageToDataURL()
-
Rendering image element (with resizing) and get its data URL
- Source:
-
returnOnlyPresentValues()
-
Check an object (valuesToCheck) against another object of keys only returning those values that have a key in the keys object, and that have a value
In order to transform larger objects of data with extra information we don't need e.g. the whole of a users account object only getting addressfields to set as initial values
Returns:
Example
keys: { addressLine1: 'addressLine1', addressLine2: 'addressLine2', postcode: 'postcode', } values: { postcode: 's7 80h', addressLine1: null, name: 'joe', } -
rotateImage(image, exifOrientation)
-
Rotate the image based on the value got from getOrientation
Parameters:
Name Type Description imageexifOrientation- Source:
Returns:
- Type
- *
-
scaleImage(image)
-
Scales the image using maxDimensions
Parameters:
Name Type Description image- Source:
Returns:
- Type
- *
-
scrollBarWidth Creates a div of screen, forces an overflow and checks the new size, returning the difference between the two.()
-
Returns scrollbar width for current OS/Browser
- Source:
-
securityQuestionReducer()
-
setCentimeters(formValues)
-
Converts values from the HeightMetricFieldGroup input into a number value in centimeters
Parameters:
Name Type Description formValuesobject Properties
Name Type Description metersstring A string (that contains an integer) or an integer representing the amount of meters
centimetersstring A string (that contains an integer) or an integer representing the amount entered into the centimeters box
Returns:
The resulting number value in centimeters
- Type
- number
Examples
User entry: 1.3, value: 130cm
User entry: 1.33, value: 133cm
-
setTrackingPageData(pageData [, merge])
-
Sets page tracking data that could be attached to every future tracking event
Parameters:
Name Type Argument Default Description pageDataobject The new persistentData properties to set
mergeboolean <optional>
false If true, the new properties will be merged into the current meta (by a shallow object assign). Otherwise, will replace the entire current pageData properties.
- Source:
-
setTrackingPersistentData(persistentData [, merge])
-
Sets event tracking data that will be attached to every future tracking event
Parameters:
Name Type Argument Default Description persistentDataobject The new persistentData properties to set
mergeboolean <optional>
true If true, the new properties will be merged into the current meta (by a shallow object assign). Otherwise, will replace the entire current persistentData properties.
- Source:
-
setupInjects(config, dispatch, clientCredentialsManagerInstance)
-
Sets up the injects for use in the project. This is done in a specific time in the startup flow where the required information is available, but before any of the values are used.
Parameters:
Name Type Description configany Config object with API information
dispatchfunction The redux store dispatch function
clientCredentialsManagerInstanceany The instance of the ClientCredentialsManager
- Source:
-
setUseCache()
-
Disable SSR cache for public
- Source:
Returns:
- Type
- boolean
-
shouldUpdateScroll(prevRouterProps, routerProps)
-
Function that determines if the scroll position should be updated. Called when navigating to a new route. See: https://github.com/taion/react-router-scroll#custom-scroll-behavior
Parameters:
Name Type Description prevRouterPropsobject routerPropsobject - Source:
Returns:
Currently always returns 'true', which will emulate the browser behavior
- Type
- any
-
stonesToPounds(stones)
-
Converts stones to pounds
Parameters:
Name Type Description stones- Source:
Returns:
- Type
- number
-
stripPrivateEnvironmentConfig(config [, parentKeys] [, path])
-
Strips private fields out of the environmentConfig using the top-level strip array of paths A new object will be returned without the keys on it. The strip array is defined in default.json.
Parameters:
Name Type Argument Description configobject The config object, also containing the strip list.
parentKeysArray.<string> <optional>
A list of keys (from the parent) to strip
pathArray.<string> <optional>
The current path in the nested object
Returns:
The object without the stripped keys
- Type
- *
-
targetedReducer(innerReducer)
-
Enhances the given reducer so it will only respond to actions that have a
targetproperty onmetathat exactly matches the name of this reducer. The name is provided by thecombineReducersNamed()utility on the parent reducer, so this util can only be used when the resulting reducer is included usingcombineReducersNamed().Parameters:
Name Type Description innerReducerThe reducer to enhance
- Source:
- See:
Returns:
The enhanced reducer that will only respond to actions with the correct
targetprop onmeta.- Type
- function
-
trackDomEvent(meta, eventType, tagName, className, cid)
-
Dispatches a TRACK_DOM_EVENT action. This will not update any reducer but instead be picked up by redux-listeners-middleware, where actual dataLayer tracking can be performed.
Parameters:
Name Type Description metaobject The meta properties that were attached to the DomEventTracker component
eventTypestring The type of event that was tracked. (for example: onClick)
tagNamestring The name of the DOM element that was clicked (for example: div, span)
classNamestring The full className of the clicked DOM element
cidstring The component id in the className of the clicked DOM element, if available. Otherwise, this will be null
- Source:
-
trackLink(meta, href)
-
Dispatches a TRACK_LINK action. This will not update any reducer but instead be picked up by redux-listeners-middleware, where actual dataLayer tracking can be performed.
Parameters:
Name Type Description metaobject The meta properties that were attached to the LinkTracker component
hrefstring The href for the link that was clicked
- Source:
-
trackVideoEvent(meta, eventType, playerType, videoId)
-
Dispatches a TRACK_VIDEO_EVENT action. This will not update any reducer but instead be picked up by redux-listeners-middleware, where actual dataLayer tracking can be performed.
Parameters:
Name Type Description metaobject The meta properties (additional properties)
eventTypestring Kind of event fired from the video player examples: play, pause
playerTypestring Kind of player YouTube, Vimeo, Brightcove etc.
videoIdstring Id of the video displayed
- Source:
-
transformCoordinate()
-
Transform canvas coordination according to specified frame size and orientation Orientation value is from EXIF tag
- Source:
-
trendLine(points)
-
Calculate a prediction based on the average difference in data points http://classroom.synonym.com/calculate-trendline-2709.html
Parameters:
Name Type Description pointsArray.<{x:number, y:number}> Returns:
- Type
- number
-
unprotectAspNetData(protectedPayload, purposeStrings, getMasterKeyById, azureBlobConnectionString, containerName)
-
Unprotects a cookie encrypted using ASP.NET Core Identity with the default settings.
More specifically, the default settings entail the following:
- The protected payload is base64 url encoded: https://tools.ietf.org/html/rfc4648#section-5
- The protected payload is formatted according to: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/authenticated-encryption-details?view=aspnetcore-2.1
- AES-256-CBC is used for encryption, HMAC-SHA5256 is used for validation. The encryptor used is an instance of CbcAuthenticatedEncryptor. This cipher text format can be found in the source code: https://github.com/aspnet/DataProtection/blob/dev/src/Microsoft.AspNetCore.DataProtection/Cng/CbcAuthenticatedEncryptor.cs#L152
- The AES-256-CBC and HMAC-SHA5256 keys are derived from a master key using SP800-108: https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-108.pdf
- SP800-108 key derivation runs in counter mode with HMAC-SHA512 as PRF
- The label input to SP800-108 derivation is an additionalAuthenticatedData (AAD) buffer. The format is undocumented but derived from the ASP.NET source code: https://github.com/aspnet/DataProtection/blob/dev/src/Microsoft.AspNetCore.DataProtection/KeyManagement/KeyRingBasedDataProtector.cs#L314
- Context headers are generated according to the following: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/context-headers?view=aspnetcore-2.1
Parameters:
Name Type Description protectedPayloadBuffer The payload from the identity cookie
purposeStringsArray.<string> An array of purpose strings passed to the IDataProtector instance that performed the cookie encryption. These purposes are used to create the AAD which is used as input to the key derivation function. See: https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/purpose-strings?view=aspnetcore-2.1
getMasterKeyByIdazureBlobConnectionStringA configuration string from the environmentConfig
containerNameThe name of the container to get the id from keys.xml
Returns:
A Promise that resolves with the unencrypted cookie
- Type
- Promise.<(string|null)>
-
updateTrackingDataCategory(trackingData, getState)
-
Retrieves the right category and name for a POST entity. We have two categories for this:
- Community
- Slimming Group
Parameters:
Name Type Description trackingDatagetStateReturns:
- Type
- Object
-
validateConfigs(configArr, envFromUrl)
-
Validate the properties for each configuration object to see if they match the expected environment in the url
Parameters:
Name Type Description configArrThe array containing the config objects
envFromUrlThe expected environment value
- Source:
-
verifyMagicHeader(protectedPayload)
-
Verifies that the protected payload starts with the magic header as specified in https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/authenticated-encryption-details?view=aspnetcore-2.1
Parameters:
Name Type Description protectedPayloadBuffer The decoded protected payload
-
verifySignature(payload, signature, pem)
-
Verifies a signature as generated by the RsaSignatureCookieTransform util. See: https://msdn.microsoft.com/en-us/library/microsoft.identitymodel.web.rsasignaturecookietransform.aspx
Parameters:
Name Type Description payloadBuffer The payload to verify
signatureBuffer The signature to compare
pemBuffer The public RSA key to use when verifying the signature
- Source:
Returns:
A Boolean indicating if the signature is valid
- Type
- boolean
-
withDeviceState A HoC for passing the deviceState to your component via the props. Makes use of react-redux connect() HoC()
-
Returns:
A function to compose or pass your component to
- Type
- function
Example
import React from 'react'; import PropTypes from 'prop-types'; import withDeviceState, { DeviceState, QueryHelpers } from './withDeviceState'; const CreatePost = ({ otherPropFromComponent, deviceState, deviceStateName, queryHelper, }, { getMessage }) => ( <div> { deviceState > DeviceState.LG ? <span>{foo}</span> : null } {queryHelper === QueryHelpers.MOBILE && <div>Only On Mobile!</div>} {queryHelper === QueryHelpers.TABLET && <div>Only On Tablet!</div>} {queryHelper === QueryHelpers.DESKTOP && <div>Only On Desktop!</div>} </div> ); CreatePost.propTypes = { otherPropFromComponent: PropTypes.number, deviceState: PropTypes.number, deviceStateName: PropTypes.string, queryHelper: PropTypes.string, }; export default withDeviceState()(CreatePost); -
WrapGetMessage()
-
Passes down getMessage
- Source:
Type Definitions
-
GetCollectionCachingCallback(paginationOptions [, currentCollectionState], requestData, getState)
-
A callback that manages caching for
apiGetCollection. Retrieves the pagination options for the current request. Can return one of the following:- The pagination options unmodified if no cache is available and the full request should be executed
- The pagination options modified to request a smaller amount of entities if a subset of the data is available in cache
falseif the data is fully available in cache and the request should be aborted
Parameters:
Name Type Argument Description paginationOptionsobject The pagination options passed to
apiGetCollectioncurrentCollectionStateobject <optional>
The state of the
collectionReducer. If no state is currently present, this will beundefinedrequestDataobject The data that will be sent with the request
getStatefunction The Redux
getStatefunctionReturns:
The
paginationOptionsparameter modified for caching orfalseif the request should be aborted- Type
- object | boolean
-
GetCollectionPaginationOptions
-
Type:
- object
- Source:
Properties:
Name Type Argument Description offsetnumber <optional>
The offset index to get entities from. Should only be used when requesting for offset-based pagination
limitnumber <optional>
The amount of entities to request
untilobject <optional>
An object with options to request entities before a specific cursor
Properties
Name Type Argument Description paramstring <optional>
The request parameter to set for requesting cursor-based pagination. Example:
"untilId"valueany <optional>
The value for the pagination parameter. If not set, will automatically detect the value of the first item that is currently in the collection.
keystring Required. The key which acts as a cursor in the target collection.
fromobject <optional>
An object with options to request entities after a specific cursor
Properties
Name Type Argument Description paramstring <optional>
The request parameter to set for requesting cursor-based pagination. Example:
"sinceId"valueany <optional>
The value for the pagination parameter. If not set, will automatically detect the value of the last item that is currently in the collection
keystring Required. The key which acts as a cursor in the target collection.
Events
-
authtoken
-
Will be emitted whenever new auth tokens are set.
Type: object
- Source:
Properties:
Name Type Description idTokenobject The new id token
accessTokenobject The new access token