UNPKG

@revenuecat/purchases-ui-js

Version:

Web components for Paywalls. Powered by RevenueCat

72 lines (71 loc) 2.93 kB
export const VARIABLE_NAMES = [ "product_name", "price", "price_per_period", "price_per_period_full", "total_price_and_per_month", "total_price_and_per_month_full", "sub_price_per_month", "sub_price_per_week", "sub_duration", "sub_duration_in_months", "sub_period", "sub_period_length", "sub_period_abbreviated", "sub_offer_duration", "sub_offer_duration_2", "sub_offer_price", "sub_offer_price_2", "sub_relative_discount", ]; /** * Returns a string with the variables replaced by values from the dictionary * @param value A string like "Try {{ product_name }} for only {{ total_price_and_per_month }}" * @param dictionary Dictionary containing the values for the variables * @returns The string with values: "Try CatGPT Annual for only $59.99/yr ($4.99/mo)" */ export const replaceVariables = ({ value = "", variableDictionary: dictionary, }) => { if (!dictionary) return value; return VARIABLE_NAMES.reduce((result, variableName) => { const currentVariableReplaced = result.replaceAll(`{{ ${variableName} }}`, dictionary[variableName]?.toString() || "N/A"); return currentVariableReplaced; }, value); }; /** * Given a ComponentLocalizations object and a locale returns the label with label_id in the chosen locale, if any. Falls * back to the label with the same label_id in the fallbackLocale, if any. Finally returns undefined if no label can be * found for the requested label_id. * @param label_id - The id of the label to be returned * @param locale - The preferred locale to return the label * @param fallbackLocale - The locale to fall back to in case no label is found in the preferred one * @param labels - A ComponentLocalizations instance * @returns The label in the preferred or fallback locale, or undefined. */ export function getLabelById(label_id, locale, fallbackLocale, labels) { if (!label_id) return ""; const fallback = labels[fallbackLocale]?.[label_id]; if (!(labels[locale] || {})[label_id]) { return fallback; } return labels[locale][label_id]; } /** * Gets a label by ID and replaces any variables in it with values from the dictionary * @param text_lid - The ID of the text label to retrieve * @param purchaseState - Object containing locale and defaultLocale * @param labels - ComponentLocalizations containing the labels * @param variableDictionary - Dictionary of variables to replace in the label text * @returns The label with variables replaced, or undefined if label not found */ export function getLabelAndReplaceVariables({ text_lid, locale, defaultLocale, labels, variableDictionary, }) { if (!text_lid) return ""; const label = getLabelById(text_lid, locale, defaultLocale, labels); const parsedLabel = replaceVariables({ value: label, variableDictionary, }); return parsedLabel; }