Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web app: add RTL support #804

Merged
merged 2 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"lint": "eslint --report-unused-disable-directives --ext .js,.jsx ./src/"
},
"dependencies": {
"@emotion/cache": "^11.11.0",
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.4.2",
Expand All @@ -28,7 +29,9 @@
"react-infinite-scroll-component": "^6.1.0",
"react-router-dom": "^6.2.2",
"stacktrace-gps": "^3.0.4",
"stacktrace-js": "^2.0.2"
"stacktrace-js": "^2.0.2",
"stylis": "^4.3.0",
"stylis-plugin-rtl": "^2.1.1"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.0.0",
Expand Down
7 changes: 4 additions & 3 deletions web/src/app/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,14 @@ export const hashCode = (s) => {
return hash;
};

export const formatShortDateTime = (timestamp) =>
new Intl.DateTimeFormat("default", {
export const formatShortDateTime = (timestamp, language) =>
new Intl.DateTimeFormat(language, {
dateStyle: "short",
timeStyle: "short",
}).format(new Date(timestamp * 1000));

export const formatShortDate = (timestamp) => new Intl.DateTimeFormat("default", { dateStyle: "short" }).format(new Date(timestamp * 1000));
export const formatShortDate = (timestamp, language) =>
new Intl.DateTimeFormat(language, { dateStyle: "short" }).format(new Date(timestamp * 1000));

export const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return "0 bytes";
Expand Down
15 changes: 7 additions & 8 deletions web/src/components/Account.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
import { Trans, useTranslation } from "react-i18next";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import i18n from "i18next";
import humanizeDuration from "humanize-duration";
import CelebrationIcon from "@mui/icons-material/Celebration";
import CloseIcon from "@mui/icons-material/Close";
Expand All @@ -50,7 +49,7 @@
import accountApi, { LimitBasis, Role, SubscriptionInterval, SubscriptionStatus } from "../app/AccountApi";
import { Pref, PrefGroup } from "./Pref";
import db from "../app/db";
import UpgradeDialog from "./UpgradeDialog";

Check warning on line 52 in web/src/components/Account.jsx

View workflow job for this annotation

GitHub Actions / test

Dependency cycle via ./App:31
import { AccountContext } from "./App";
import DialogFooter from "./DialogFooter";
import { Paragraph } from "./styles";
Expand Down Expand Up @@ -224,7 +223,7 @@
};

const AccountType = () => {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const { account } = useContext(AccountContext);
const [upgradeDialogKey, setUpgradeDialogKey] = useState(0);
const [upgradeDialogOpen, setUpgradeDialogOpen] = useState(false);
Expand Down Expand Up @@ -283,7 +282,7 @@
{account.billing?.paid_until && !account.billing?.cancel_at && (
<Tooltip
title={t("account_basics_tier_paid_until", {
date: formatShortDate(account.billing?.paid_until),
date: formatShortDate(account.billing?.paid_until, i18n.language),
})}
>
<span>
Expand Down Expand Up @@ -328,7 +327,7 @@
{account.billing?.cancel_at > 0 && (
<Alert severity="warning" sx={{ mt: 1 }}>
{t("account_basics_tier_canceled_subscription", {
date: formatShortDate(account.billing.cancel_at),
date: formatShortDate(account.billing.cancel_at, i18n.language),
})}
</Alert>
)}
Expand Down Expand Up @@ -556,7 +555,7 @@
};

const Stats = () => {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const { account } = useContext(AccountContext);

if (!account) {
Expand Down Expand Up @@ -798,7 +797,7 @@
};

const TokensTable = (props) => {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const [snackOpen, setSnackOpen] = useState(false);
const [upsertDialogKey, setUpsertDialogKey] = useState(0);
const [upsertDialogOpen, setUpsertDialogOpen] = useState(false);
Expand Down Expand Up @@ -872,11 +871,11 @@
{token.token !== session.token() && (token.label || "-")}
</TableCell>
<TableCell sx={{ whiteSpace: "nowrap" }} aria-label={t("account_tokens_table_expires_header")}>
{token.expires ? formatShortDateTime(token.expires) : <em>{t("account_tokens_table_never_expires")}</em>}
{token.expires ? formatShortDateTime(token.expires, i18n.language) : <em>{t("account_tokens_table_never_expires")}</em>}
</TableCell>
<TableCell sx={{ whiteSpace: "nowrap" }} aria-label={t("account_tokens_table_last_access_header")}>
<div style={{ display: "flex", alignItems: "center" }}>
<span>{formatShortDateTime(token.last_access)}</span>
<span>{formatShortDateTime(token.last_access, i18n.language)}</span>
<Tooltip
title={t("account_tokens_table_last_origin_tooltip", {
ip: token.last_origin,
Expand Down
56 changes: 34 additions & 22 deletions web/src/components/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,26 @@
import { Box, Toolbar, CssBaseline, Backdrop, CircularProgress, useMediaQuery, ThemeProvider, createTheme } from "@mui/material";
import { useLiveQuery } from "dexie-react-hooks";
import { BrowserRouter, Outlet, Route, Routes, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { AllSubscriptions, SingleSubscription } from "./Notifications";
import { darkTheme, lightTheme } from "./theme";
import Navigation from "./Navigation";

Check warning on line 9 in web/src/components/App.jsx

View workflow job for this annotation

GitHub Actions / test

Dependency cycle detected
import ActionBar from "./ActionBar";

Check warning on line 10 in web/src/components/App.jsx

View workflow job for this annotation

GitHub Actions / test

Dependency cycle via ./SubscriptionPopup:21
import Preferences from "./Preferences";

Check warning on line 11 in web/src/components/App.jsx

View workflow job for this annotation

GitHub Actions / test

Dependency cycle detected
import subscriptionManager from "../app/SubscriptionManager";
import userManager from "../app/UserManager";
import { expandUrl } from "../app/utils";
import ErrorBoundary from "./ErrorBoundary";
import routes from "./routes";
import { useAccountListener, useBackgroundProcesses, useConnectionListeners, useWebPushTopics } from "./hooks";
import PublishDialog from "./PublishDialog";

Check warning on line 18 in web/src/components/App.jsx

View workflow job for this annotation

GitHub Actions / test

Dependency cycle detected
import Messaging from "./Messaging";
import Login from "./Login";
import Signup from "./Signup";
import Account from "./Account";

Check warning on line 22 in web/src/components/App.jsx

View workflow job for this annotation

GitHub Actions / test

Dependency cycle detected
import "../app/i18n"; // Translations!
import prefs, { THEME } from "../app/Prefs";
import RTLCacheProvider from "./RTLCacheProvider";

export const AccountContext = createContext(null);

Expand All @@ -39,37 +41,47 @@
};

const App = () => {
const { i18n } = useTranslation();
const languageDir = i18n.dir();

const [account, setAccount] = useState(null);
const accountMemo = useMemo(() => ({ account, setAccount }), [account, setAccount]);
const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
const themePreference = useLiveQuery(() => prefs.theme());
const theme = React.useMemo(
() => createTheme(darkModeEnabled(prefersDarkMode, themePreference) ? darkTheme : lightTheme),
[prefersDarkMode, themePreference]
() => createTheme({ ...(darkModeEnabled(prefersDarkMode, themePreference) ? darkTheme : lightTheme), direction: languageDir }),
[prefersDarkMode, themePreference, languageDir]
);

useEffect(() => {
document.documentElement.setAttribute("lang", i18n.language);
document.dir = languageDir;
}, [i18n.language, languageDir]);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dumb question:

  • Should this not be i18n.resolvedLanguage everywhere? I had to do that in the preferences to avoid issues.
  • Have you tested this with a cleared localStorage, i.e. without a language?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • resolvedLanguage is specifically for preferences - it references a value in your supported languages, so you can match it to an option with the user. language is fine for all other use cases: https://www.i18next.com/overview/api#language
  • works fine in incognito. it will use the fallback language if it can't detect one based on what the browser reports, or if it doesn't match a supported language.


return (
<Suspense fallback={<Loader />}>
<BrowserRouter>
<ThemeProvider theme={theme}>
<AccountContext.Provider value={accountMemo}>
<CssBaseline />
<ErrorBoundary>
<Routes>
<Route path={routes.login} element={<Login />} />
<Route path={routes.signup} element={<Signup />} />
<Route element={<Layout />}>
<Route path={routes.app} element={<AllSubscriptions />} />
<Route path={routes.account} element={<Account />} />
<Route path={routes.settings} element={<Preferences />} />
<Route path={routes.subscription} element={<SingleSubscription />} />
<Route path={routes.subscriptionExternal} element={<SingleSubscription />} />
</Route>
</Routes>
</ErrorBoundary>
</AccountContext.Provider>
</ThemeProvider>
</BrowserRouter>
<RTLCacheProvider>
<BrowserRouter>
<ThemeProvider theme={theme}>
<AccountContext.Provider value={accountMemo}>
<CssBaseline />
<ErrorBoundary>
<Routes>
<Route path={routes.login} element={<Login />} />
<Route path={routes.signup} element={<Signup />} />
<Route element={<Layout />}>
<Route path={routes.app} element={<AllSubscriptions />} />
<Route path={routes.account} element={<Account />} />
<Route path={routes.settings} element={<Preferences />} />
<Route path={routes.subscription} element={<SingleSubscription />} />
<Route path={routes.subscriptionExternal} element={<SingleSubscription />} />
</Route>
</Routes>
</ErrorBoundary>
</AccountContext.Provider>
</ThemeProvider>
</BrowserRouter>
</RTLCacheProvider>
</Suspense>
);
};
Expand Down
8 changes: 4 additions & 4 deletions web/src/components/Notifications.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,10 @@ const autolink = (s) => {
};

const NotificationItem = (props) => {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const { notification } = props;
const { attachment } = notification;
const date = formatShortDateTime(notification.time);
const date = formatShortDateTime(notification.time, i18n.language);
const otherTags = unmatchedTags(notification.tags);
const tags = otherTags.length > 0 ? otherTags.join(", ") : null;
const handleDelete = async () => {
Expand Down Expand Up @@ -277,7 +277,7 @@ const NotificationItem = (props) => {
};

const Attachment = (props) => {
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const { attachment } = props;
const expired = attachment.expires && attachment.expires < Date.now() / 1000;
const expires = attachment.expires && attachment.expires > Date.now() / 1000;
Expand All @@ -296,7 +296,7 @@ const Attachment = (props) => {
if (expires) {
infos.push(
t("notifications_attachment_link_expires", {
date: formatShortDateTime(attachment.expires),
date: formatShortDateTime(attachment.expires, i18n.language),
})
);
}
Expand Down
22 changes: 22 additions & 0 deletions web/src/components/RTLCacheProvider.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import React from "react";

import rtlPlugin from "stylis-plugin-rtl";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";
import { prefixer } from "stylis";
import { useTranslation } from "react-i18next";

// https://mui.com/material-ui/guides/right-to-left

const cacheRtl = createCache({
key: "muirtl",
stylisPlugins: [prefixer, rtlPlugin],
});

const RTLCacheProvider = ({ children }) => {
const { i18n } = useTranslation();

return i18n.dir() === "rtl" ? <CacheProvider value={cacheRtl}>{children}</CacheProvider> : children;
};

export default RTLCacheProvider;
binwiederhier marked this conversation as resolved.
Show resolved Hide resolved
10 changes: 8 additions & 2 deletions web/src/components/SubscriptionPopup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,16 @@ export const SubscriptionPopup = (props) => {
])[0];
const nowSeconds = Math.round(Date.now() / 1000);
const message = shuffle([
`Hello friend, this is a test notification from ntfy web. It's ${formatShortDateTime(nowSeconds)} right now. Is that early or late?`,
`Hello friend, this is a test notification from ntfy web. It's ${formatShortDateTime(
nowSeconds,
"en-US"
)} right now. Is that early or late?`,
`So I heard you like ntfy? If that's true, go to GitHub and star it, or to the Play store and rate it. Thanks! Oh yeah, this is a test notification.`,
`It's almost like you want to hear what I have to say. I'm not even a machine. I'm just a sentence that Phil typed on a random Thursday.`,
`Alright then, it's ${formatShortDateTime(nowSeconds)} already. Boy oh boy, where did the time go? I hope you're alright, friend.`,
`Alright then, it's ${formatShortDateTime(
nowSeconds,
"en-US"
)} already. Boy oh boy, where did the time go? I hope you're alright, friend.`,
`There are nine million bicycles in Beijing That's a fact; It's a thing we can't deny. I wonder if that's true ...`,
`I'm really excited that you're trying out ntfy. Did you know that there are a few public topics, such as ntfy.sh/stats and ntfy.sh/announcements.`,
`It's interesting to hear what people use ntfy for. I've heard people talk about using it for so many cool things. What do you use it for?`,
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/UpgradeDialog.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const Banner = {

const UpgradeDialog = (props) => {
const theme = useTheme();
const { t } = useTranslation();
const { t, i18n } = useTranslation();
const { account } = useContext(AccountContext); // May be undefined!
const [error, setError] = useState("");
const [tiers, setTiers] = useState(null);
Expand Down Expand Up @@ -233,7 +233,7 @@ const UpgradeDialog = (props) => {
<Trans
i18nKey="account_upgrade_dialog_cancel_warning"
values={{
date: formatShortDate(account?.billing?.paid_until || 0),
date: formatShortDate(account?.billing?.paid_until || 0, i18n.language),
}}
/>
</Alert>
Expand Down
Loading