Skip to content

Commit

Permalink
Working template translations with MicroI18n
Browse files Browse the repository at this point in the history
  • Loading branch information
medihack committed Oct 15, 2023
1 parent aa1ac27 commit 5d17359
Show file tree
Hide file tree
Showing 29 changed files with 60 additions and 233 deletions.
3 changes: 2 additions & 1 deletion locales/de/common.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
formError:
alreadyUsed: Bereits vergeben.
invalidChars: "Enthält ungültige Zeichen. Erlaubt: {{chars}}"
reservedKeyword: "Reserviertes Schlüsselwort."
invalidLocale: Ungültiges Sprachschema.
reservedKeyword: Reserviertes Schlüsselwort.
tooLong: Zu lang. Maximal {{max}} Zeichen.
tooShort: Zu kurz. Mindestens {{min}} Zeichen.
unexpected: "Ein unerwarteter Fehler ist aufgetreten: "
Expand Down
10 changes: 0 additions & 10 deletions locales/de/drafts.yml

This file was deleted.

File renamed without changes.
3 changes: 2 additions & 1 deletion locales/en/common.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
formError:
alreadyUsed: Already in use.
invalidChars: "Contains invalid characters. Allowed: {{chars}}"
reservedKeyword: "Reserved keyword."
invalidLocale: Invalid locale name.
reservedKeyword: Reserved keyword.
tooLong: Too long. Maximum {{max}} characters.
tooShort: Too short. Minimum {{min}} characters.
unexpected: "An unexpected error occurred: "
Expand Down
10 changes: 0 additions & 10 deletions locales/en/drafts.yml

This file was deleted.

File renamed without changes.
3 changes: 3 additions & 0 deletions src/components/common/FlagIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,8 @@ interface FlagImageProps {

export const FlagIcon = ({ language, size = 18 }: FlagImageProps) => {
const Img = flagIcons[language]
if (!Img) {
throw new Error(`Missing flag for language: ${language}`)
}
return <Img width={size} height={size} />
}
9 changes: 5 additions & 4 deletions src/components/common/SiteTranslationProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { i18n } from "i18next"
import { useRouter } from "next/router"
import { Locale } from "nextjs-routes"
import { ReactNode, useCallback, useRef, useState } from "react"
import { I18nSiteContextProvider } from "~/contexts/I18nSiteContext"
import { useOnRouteChange } from "~/hooks/useOnRouteChange"
import { I18nSite, SiteLanguageOption } from "~/types/general"
import { I18nSite } from "~/types/general"
import { createClient } from "~/utils/i18nBrowserClient"
import { registerInstance } from "~/utils/i18nextReloader"

Expand All @@ -16,7 +17,7 @@ export const SiteTranslationProvider = ({
i18nSiteProps,
children,
}: SiteTranslationProviderProps) => {
const [currentSiteLanguage, _setCurrentSiteLanguage] = useState<SiteLanguageOption>(
const [currentSiteLanguage, _setCurrentSiteLanguage] = useState(
i18nSiteProps.initialSiteLanguage!
)

Expand Down Expand Up @@ -44,7 +45,7 @@ export const SiteTranslationProvider = ({
})

const setCurrentSiteLanguage = useCallback(
(language: SiteLanguageOption) => {
(language: string) => {
i18nInstance.current!.i18nSite.changeLanguage(language, () => {
if (language !== "cimode") {
router.push(
Expand All @@ -55,7 +56,7 @@ export const SiteTranslationProvider = ({
},
},
undefined,
{ shallow: true, locale: language }
{ shallow: true, locale: language as Locale }
)
}
_setCurrentSiteLanguage(language)
Expand Down
15 changes: 6 additions & 9 deletions src/components/inputs/MeasurementsInput.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { ComponentProps, useState } from "react"
import { calcStats, createEmptyMeasurements, createStatsText } from "~/utils/measurementsUtils"
import { MeasurementsData } from "../../types/measurements"
import { SiteTranslations } from "../storybook/SiteTranslations"
import { StructuredReportTranslations } from "../storybook/StructuredReportTranslations"
import { MeasurementsInput } from "./MeasurementsInput"

const meta: Meta<typeof MeasurementsInput> = {
Expand All @@ -25,14 +24,12 @@ const MeasurementsInputWithState = ({

return (
<SiteTranslations>
<StructuredReportTranslations>
<MeasurementsInput
value={value}
onChange={setValue}
footer={footer}
{...{ label, extras, disabled }}
/>
</StructuredReportTranslations>
<MeasurementsInput
value={value}
onChange={setValue}
footer={footer}
{...{ label, extras, disabled }}
/>
</SiteTranslations>
)
}
Expand Down
5 changes: 3 additions & 2 deletions src/components/inputs/MeasurementsInput/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Box, Stack } from "@mantine/core"
import { ReactNode, useCallback, useRef } from "react"
import { useStructureTranslation } from "~/hooks/useStructureTranslation"
import { useSiteTranslation } from "~/hooks/useSiteTranslation"
import { MeasurementsAction, MeasurementsData } from "~/types/measurements"
import { getMeasurementsDataParams, measurementsReducer } from "~/utils/measurementsUtils"
import { InputLabel } from "../InputLabel"
Expand Down Expand Up @@ -38,7 +38,8 @@ export const MeasurementsInput = ({
[onChange]
)

const { t } = useStructureTranslation()
const { t } = useSiteTranslation()
// TODO: make label configurable props
const labels = {
clearAll: t("MeasurementsInput.toolClearAll"),
clearReferences: t("MeasurementsInput.toolClearReferences"),
Expand Down
4 changes: 2 additions & 2 deletions src/components/outputs/MeasurementsOutput.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ReactNode } from "react"
import { useReportTranslation } from "~/hooks/useReportTranslation"
import { useSiteTranslation } from "~/hooks/useSiteTranslation"
import { useStructureLink } from "~/hooks/useStructureLink"
import { selectOutputFormat } from "~/state/displaySlice"
import { useAppSelector } from "~/state/store"
Expand Down Expand Up @@ -31,7 +31,7 @@ export const MeasurementsOutput = ({
}: MeasurementsOutputProps) => {
const { activateLink } = useStructureLink({ fieldId })
const outputFormat = useAppSelector(selectOutputFormat)
const { t } = useReportTranslation()
const { t } = useSiteTranslation()

const labels = {
previous: previousLabel || t("MeasurementsOutput.columnPrevious"),
Expand Down
3 changes: 1 addition & 2 deletions src/components/storybook/SiteTranslations.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { ReactNode, Suspense, useMemo } from "react"
import { I18nSiteContextProvider } from "~/contexts/I18nSiteContext"
import { SiteLanguageOption } from "~/types/general"
import { createClient } from "~/utils/i18nStorybookClient"

const DEFAULT_ADDITIONAL_NAMESPACES: string[] = []

interface SiteTranslationsProps {
language?: SiteLanguageOption
language?: string
additionalNamespaces?: string[]
children: ReactNode
}
Expand Down
12 changes: 8 additions & 4 deletions src/components/template/TemplateTranslationProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export const TemplateTranslationProvider = ({
const setStructureLanguage = useCallback(
(language: TemplateLanguage) => {
i18nStructure.options = { debugKeys: language === "cimode" }
i18nStructure.changeLanguage(language === "asSite" ? currentSiteLanguage : language)
if (language !== "cimode") {
i18nStructure.changeLanguage(language === "asSite" ? currentSiteLanguage : language)
}
_setStructureLanguage(language)
},
[i18nStructure, currentSiteLanguage]
Expand All @@ -34,17 +36,19 @@ export const TemplateTranslationProvider = ({
const setReportLanguage = useCallback(
(language: TemplateLanguage) => {
i18nReport.options = { debugKeys: language === "cimode" }
i18nReport.changeLanguage(language === "asSite" ? currentSiteLanguage : language)
if (language !== "cimode") {
i18nReport.changeLanguage(language === "asSite" ? currentSiteLanguage : language)
}
_setReportLanguage(language)
},
[i18nReport, currentSiteLanguage]
)

useSiteLanguageListener((language) => {
if (structureLanguage === "asSite") {
if (structureLanguage === "asSite" && language !== "cimode") {
i18nStructure.changeLanguage(language)
}
if (reportLanguage === "asSite") {
if (reportLanguage === "asSite" && language !== "cimode") {
i18nReport.changeLanguage(language)
}
})
Expand Down
7 changes: 3 additions & 4 deletions src/contexts/I18nSiteContext.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { i18n } from "i18next"
import { SiteLanguageOption } from "~/types/general"
import { createRequiredContext } from "~/utils/createRequiredContext"

export interface I18nSiteContext {
i18nSite: i18n
supportedSiteLanguages: SiteLanguageOption[]
currentSiteLanguage: SiteLanguageOption
setCurrentSiteLanguage: (language: SiteLanguageOption) => void
supportedSiteLanguages: string[]
currentSiteLanguage: string
setCurrentSiteLanguage: (language: string) => void
}

export const [useI18nSite, I18nSiteContextProvider] =
Expand Down
30 changes: 6 additions & 24 deletions src/hocs/withTranslations.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import hoistNonReactStatics from "hoist-non-react-statics"
import { ComponentType } from "react"
import { SiteTranslationProvider } from "~/components/common/SiteTranslationProvider"
import { StructuredReportTranslationProvider } from "~/components/common/StructuredReportTranslationProvider"
import { ServerSideProps } from "~/types/general"

interface AppProps {
Expand All @@ -13,33 +12,16 @@ export const withTranslations = <T extends AppProps>(
): ComponentType<T> => {
const WithTranslations = (props: AppProps) => {
const i18nSiteProps = props.pageProps?.i18nSite
const i18nStructuredReportProps = props.pageProps?.i18nStructuredReport

if (!i18nSiteProps && !i18nStructuredReportProps) {
if (!i18nSiteProps) {
return <WrappedComponent {...(props as T)} />
}

if (i18nSiteProps && !i18nStructuredReportProps) {
return (
<SiteTranslationProvider i18nSiteProps={i18nSiteProps}>
<WrappedComponent {...(props as T)} />
</SiteTranslationProvider>
)
}

if (i18nSiteProps && i18nStructuredReportProps) {
return (
<SiteTranslationProvider i18nSiteProps={i18nSiteProps}>
<StructuredReportTranslationProvider
i18nStructuredReportProps={i18nStructuredReportProps}
>
<WrappedComponent {...(props as T)} />
</StructuredReportTranslationProvider>
</SiteTranslationProvider>
)
}

throw new Error("Invalid translations setup.")
return (
<SiteTranslationProvider i18nSiteProps={i18nSiteProps}>
<WrappedComponent {...(props as T)} />
</SiteTranslationProvider>
)
}

return hoistNonReactStatics(WithTranslations, WrappedComponent)
Expand Down
3 changes: 1 addition & 2 deletions src/hooks/useSiteLanguageListener.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { useEffect } from "react"
import { SiteLanguageOption } from "../types/general"
import { useSiteTranslation } from "./useSiteTranslation"

type Callback = (language: SiteLanguageOption) => void
type Callback = (language: string) => void

export const useSiteLanguageListener = (callback: Callback) => {
const { i18n } = useSiteTranslation()
Expand Down
2 changes: 1 addition & 1 deletion src/pages/tools/adrenal-mri.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async ({
}) => ({
props: {
session: await getServerSideSession(req, res),
i18nSite: await getServerSideSiteTranslations(locale, locales),
i18nSite: await getServerSideSiteTranslations(locale, locales, ["template"]),
preloadedReduxState: {},
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/tools/adrenal-washout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async ({
}) => ({
props: {
session: await getServerSideSession(req, res),
i18nSite: await getServerSideSiteTranslations(locale, locales),
i18nSite: await getServerSideSiteTranslations(locale, locales, ["template"]),
preloadedReduxState: {},
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/tools/fleischner2017.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async ({
}) => ({
props: {
session: await getServerSideSession(req, res),
i18nSite: await getServerSideSiteTranslations(locale, locales),
i18nSite: await getServerSideSiteTranslations(locale, locales, ["template"]),
preloadedReduxState: {},
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/tools/gfr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async ({
}) => ({
props: {
session: await getServerSideSession(req, res),
i18nSite: await getServerSideSiteTranslations(locale, locales),
i18nSite: await getServerSideSiteTranslations(locale, locales, ["template"]),
preloadedReduxState: {},
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/tools/kidney-volume.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async ({
}) => ({
props: {
session: await getServerSideSession(req, res),
i18nSite: await getServerSideSiteTranslations(locale, locales),
i18nSite: await getServerSideSiteTranslations(locale, locales, ["template"]),
preloadedReduxState: {},
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/tools/measurements-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async ({
}) => ({
props: {
session: await getServerSideSession(req, res),
i18nSite: await getServerSideSiteTranslations(locale, locales),
i18nSite: await getServerSideSiteTranslations(locale, locales, ["template"]),
preloadedReduxState: {},
},
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/tools/sandbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const getServerSideProps: GetServerSideProps<ServerSideProps> = async ({
}) => ({
props: {
session: await getServerSideSession(req, res),
i18nSite: await getServerSideSiteTranslations(locale, locales),
i18nSite: await getServerSideSiteTranslations(locale, locales, ["template"]),
preloadedReduxState: {},
},
})
Expand Down
15 changes: 1 addition & 14 deletions src/server/utils/figureUtils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { JSDOM } from "jsdom"
import { optimize } from "svgo"
import { FigureDocument } from "~/types/resources"
import { extractMetadata } from "~/utils/figureUtils"

function optimizeSvg(source: string) {
export function optimizeSvg(source: string) {
const { data } = optimize(source, {
plugins: [
{
Expand All @@ -20,13 +17,3 @@ function optimizeSvg(source: string) {

return data
}

export function createFigureDocument(source: string): FigureDocument {
const dom = new JSDOM(source, { contentType: "image/svg+xml" })
const meta = extractMetadata(dom.window.document, "med")

return {
svg: optimizeSvg(source),
meta,
}
}
6 changes: 3 additions & 3 deletions src/server/utils/siteTranslations.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { Resource } from "i18next"
import { GetServerSidePropsContext } from "next"
import { I18nSite, SiteLanguageOption } from "~/types/general"
import { I18nSite } from "~/types/general"
import { createClient } from "./i18nServerClient"

export const getServerSideSiteTranslations = async (
locale: GetServerSidePropsContext["locale"],
locales: GetServerSidePropsContext["locales"],
additionalSiteNamespaces: string[] = []
): Promise<I18nSite> => {
const initialSiteLanguage = locale! as SiteLanguageOption
const supportedSiteLanguages = locales! as SiteLanguageOption[]
const initialSiteLanguage = locale!
const supportedSiteLanguages = locales!
const siteNamespaces = [...additionalSiteNamespaces, "common"]

const { i18n, initPromise } = createClient({
Expand Down
Loading

0 comments on commit 5d17359

Please sign in to comment.