npm package diff

Package: @forge/react

Versions: 10.5.3-next.0-experimental-c7a7d36 - 10.6.0-next.1

File: package/out/hooks/useTranslation.js

Index: package/out/hooks/useTranslation.js
===================================================================
--- package/out/hooks/useTranslation.js
+++ package/out/hooks/useTranslation.js
@@ -0,0 +1,58 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.I18nProvider = exports.useTranslation = void 0;
+const jsx_runtime_1 = require("react/jsx-runtime");
+const react_1 = require("react");
+const bridge_1 = require("@forge/bridge");
+const EMPTY_I18N_CONTEXT_VALUE = {
+    ready: false,
+    t: (key, defaultValue) => defaultValue ?? key
+};
+const I18nContext = (0, react_1.createContext)(EMPTY_I18N_CONTEXT_VALUE);
+/**
+ * Custom hook to access the i18n translation context.
+ *
+ * This hook provides the current i18n context value, which includes the translation function (`t`)
+ * and the readiness state of the i18n context. If the context is not ready, the translation function
+ * will return the key itself.
+ *
+ * @returns The current i18n context value, including the translation function, current locale, and readiness state.
+ */
+const useTranslation = () => {
+    return (0, react_1.useContext)(I18nContext);
+};
+exports.useTranslation = useTranslation;
+/**
+ * Provider component for the i18n context.
+ *
+ * This component initializes the i18n context with the appropriate locale and translation function.
+ * It fetches the locale from the provided props or the current view context if no locale is provided.
+ * The i18n context value is then made available to all child components.
+ *
+ * @param children The child components that will have access to the i18n context.
+ * @param locale The optional locale to initialize the i18n context with,
+ *    if not provided, the current locale from the view context is used.
+ *
+ * @returns The provider component that wraps the children with the i18n context.
+ */
+const I18nProvider = ({ children, locale }) => {
+    const [i18nContextValue, setI18nContextValue] = (0, react_1.useState)(EMPTY_I18N_CONTEXT_VALUE);
+    (0, react_1.useEffect)(() => {
+        const loadI18nContext = async () => {
+            let targetLocale = locale;
+            if (!targetLocale) {
+                const context = await bridge_1.view.getContext();
+                targetLocale = context.locale;
+            }
+            const t = await bridge_1.i18n.createTranslationFunction(targetLocale);
+            setI18nContextValue({
+                ready: true,
+                t,
+                locale: targetLocale
+            });
+        };
+        void loadI18nContext();
+    }, [setI18nContextValue, locale]);
+    return (0, jsx_runtime_1.jsx)(I18nContext.Provider, { value: i18nContextValue, children: children });
+};
+exports.I18nProvider = I18nProvider;