|
| 1 | +import { isUndefined } from '@guardian/libs'; |
| 2 | +import type { ProductCta } from '../../types/content'; |
| 3 | + |
| 4 | +const strikeThroughRegex = /~([^~]+)~(.*)/; |
| 5 | + |
| 6 | +type ParsedProductLabel = { |
| 7 | + struckThrough: string; |
| 8 | + restOfLabel: string; |
| 9 | +}; |
| 10 | + |
| 11 | +const parseProductLabel = (label: string): ParsedProductLabel | undefined => { |
| 12 | + const match = label.match(strikeThroughRegex); |
| 13 | + const struckThrough = match?.[1]; |
| 14 | + const restOfLabel = match?.[2]; |
| 15 | + |
| 16 | + if (isUndefined(struckThrough) || isUndefined(restOfLabel)) { |
| 17 | + return undefined; |
| 18 | + } |
| 19 | + |
| 20 | + return { struckThrough, restOfLabel }; |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * Create a struck through React component from a label |
| 25 | + * for a product link button or product CTA |
| 26 | + * that may contain a strikethroughed price |
| 27 | + * @param label the label text that may contain strikethrough eg '~£10~ £5 at Shop' |
| 28 | + */ |
| 29 | +export const createStrikeThroughProductLabel = (label: string) => { |
| 30 | + const parsedLabel = parseProductLabel(label); |
| 31 | + |
| 32 | + if (isUndefined(parsedLabel)) { |
| 33 | + return label; |
| 34 | + } else { |
| 35 | + return ( |
| 36 | + <> |
| 37 | + <s>{parsedLabel.struckThrough}</s> |
| 38 | + {parsedLabel.restOfLabel} |
| 39 | + </> |
| 40 | + ); |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +/** |
| 45 | + * Create accessible label text |
| 46 | + * for a product link button or product CTA |
| 47 | + * that may contain a struck through price |
| 48 | + * @param label the label text that may contain strikethrough eg '~£10~ £5 at Shop' |
| 49 | + */ |
| 50 | +export const createAccessibleProductLabel = (label: string): string => { |
| 51 | + const parsedLabel = parseProductLabel(label); |
| 52 | + if (isUndefined(parsedLabel)) { |
| 53 | + return label; |
| 54 | + } else { |
| 55 | + return `Was ${parsedLabel.struckThrough}, now ${parsedLabel.restOfLabel.trimStart()}`; |
| 56 | + } |
| 57 | +}; |
| 58 | + |
| 59 | +export const getProductLinkLabelWithoutPrice = ( |
| 60 | + cardCta: ProductCta, |
| 61 | +): string => { |
| 62 | + return cardCta.text !== '' ? cardCta.text : `Buy at ${cardCta.retailer}`; |
| 63 | +}; |
| 64 | + |
| 65 | +export const getProductLinkLabelWithPrice = (cta: ProductCta): string => { |
| 66 | + const overrideLabel = cta.text.trim().length > 0; |
| 67 | + return overrideLabel ? cta.text : `${cta.price} at ${cta.retailer}`; |
| 68 | +}; |
0 commit comments