Skip to content

i18n support for sicp #3133

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

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 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
13 changes: 13 additions & 0 deletions src/features/sicp/utils/SicpUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,16 @@ export const readSicpSectionLocalStorage = () => {
const data = readLocalStorage(SICP_CACHE_KEY, SICP_INDEX);
return data;
};

export const SICP_DEF_TB_LANG = 'en';
export const SICP_TB_LANG_KEY = 'sicp-textbook-lang';

export const setSicpLangLocalStorage = (value: string) => {
setLocalStorage(SICP_TB_LANG_KEY, value);
window.dispatchEvent(new Event('sicp-tb-lang-change'));
};

export const readSicpLangLocalStorage = () => {
const data = readLocalStorage(SICP_TB_LANG_KEY, SICP_DEF_TB_LANG);
return data;
};
59 changes: 55 additions & 4 deletions src/pages/sicp/Sicp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'katex/dist/katex.min.css';

import { Button, Classes, NonIdealState, Spinner } from '@blueprintjs/core';
import classNames from 'classnames';
import path from 'path';
import React, { useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation, useNavigate, useParams } from 'react-router';
Expand All @@ -14,9 +15,12 @@ import { SicpSection } from 'src/features/sicp/chatCompletion/chatCompletion';
import { parseArr, ParseJsonError } from 'src/features/sicp/parser/ParseJson';
import { getNext, getPrev } from 'src/features/sicp/TableOfContentsHelper';
import {
readSicpLangLocalStorage,
readSicpSectionLocalStorage,
setSicpLangLocalStorage,
setSicpSectionLocalStorage,
SICP_CACHE_KEY,
SICP_DEF_TB_LANG,
SICP_INDEX
} from 'src/features/sicp/utils/SicpUtils';

Expand All @@ -40,7 +44,8 @@ const Sicp: React.FC = () => {
const [data, setData] = useState(<></>);
const [loading, setLoading] = useState(false);
const [active, setActive] = useState('0');
const { section } = useParams<{ section: string }>();
const { param_lang, section } = useParams<{ param_lang: string; section: string }>();
const [lang, setLang] = useState(readSicpLangLocalStorage());
const parentRef = useRef<HTMLDivElement>(null);
const refs = useRef<Record<string, HTMLElement | null>>({});
const navigate = useNavigate();
Expand Down Expand Up @@ -89,13 +94,31 @@ const Sicp: React.FC = () => {

// Handle loading of latest viewed section and fetch json data
React.useEffect(() => {
const valid_langs = ['en', 'zh_CN'];

if ((section && valid_langs.includes(section)) || param_lang) {
const plang = param_lang ? param_lang : section ? section : SICP_DEF_TB_LANG;
if (!valid_langs.includes(plang)) {
setLang(SICP_DEF_TB_LANG);
setSicpLangLocalStorage(SICP_DEF_TB_LANG);
} else {
setLang(plang);
setSicpLangLocalStorage(plang);
}
if (section && valid_langs.includes(section)) {
navigate(`/sicpjs/${SICP_INDEX}`, { replace: true });
} else {
navigate(`/sicpjs/${section}`, { replace: true });
}
return;
}
if (!section) {
/**
* Handles rerouting to the latest viewed section when clicking from
* the main application navbar. Navigate replace logic is used to allow the
* user to still use the browser back button to navigate the app.
*/
navigate(`/sicpjs/${readSicpSectionLocalStorage()}`, { replace: true });
navigate(path.join('sicpjs', readSicpSectionLocalStorage()), { replace: true });
return;
}

Expand All @@ -106,7 +129,11 @@ const Sicp: React.FC = () => {

setLoading(true);

fetch(baseUrl + section + extension)
if (!valid_langs.includes(lang)) {
setLang(SICP_DEF_TB_LANG);
setSicpLangLocalStorage(SICP_DEF_TB_LANG);
}
fetch(baseUrl + lang + '/' + section + extension)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
Expand Down Expand Up @@ -139,7 +166,7 @@ const Sicp: React.FC = () => {
.finally(() => {
setLoading(false);
});
}, [section, navigate]);
}, [param_lang, section, lang, navigate]);

// Scroll to correct position
React.useEffect(() => {
Expand All @@ -164,10 +191,33 @@ const Sicp: React.FC = () => {
dispatch(WorkspaceActions.resetWorkspace('sicp'));
dispatch(WorkspaceActions.toggleUsingSubst(false, 'sicp'));
};

const handleLanguageToggle = () => {
const newLang = lang === 'en' ? 'zh_CN' : 'en';
setLang(newLang);
setSicpLangLocalStorage(newLang);
};

const handleNavigation = (sect: string) => {
navigate('/sicpjs/' + sect);
};

// Language toggle button with fixed position
const languageToggle = (
<div
style={{
position: 'sticky',
top: '20px',
left: '20px',
zIndex: 0
}}
>
<Button onClick={handleLanguageToggle} intent="primary" small>
{lang === 'en' ? '切换到中文' : 'Switch to English'}
</Button>
</div>
);

// `section` is defined due to the navigate logic in the useEffect above
const navigationButtons = (
<div className="sicp-navigation-buttons">
Expand All @@ -187,6 +237,7 @@ const Sicp: React.FC = () => {
>
<SicpErrorBoundary>
<CodeSnippetContext.Provider value={{ active: active, setActive: handleSnippetEditorOpen }}>
{languageToggle}
{loading ? (
<div className="sicp-content">{loadingComponent}</div>
) : section === 'index' ? (
Expand Down
73 changes: 63 additions & 10 deletions src/pages/sicp/subcomponents/SicpToc.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { Tree, TreeNodeInfo } from '@blueprintjs/core';
import { NonIdealState, Spinner } from '@blueprintjs/core';
import { cloneDeep } from 'lodash';
Copy link
Preview

Copilot AI Jul 5, 2025

Choose a reason for hiding this comment

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

The cloneDeep import is no longer used in this file. Removing it will reduce unused dependencies and improve readability.

Suggested change
import { cloneDeep } from 'lodash';

Copilot uses AI. Check for mistakes.

import React, { useState } from 'react';
import { useNavigate } from 'react-router';
import Constants from 'src/commons/utils/Constants';
import { readSicpLangLocalStorage } from 'src/features/sicp/utils/SicpUtils';

import toc from '../../../features/sicp/data/toc.json';
import fallbackToc from '../../../features/sicp/data/toc.json';

const baseUrl = Constants.sicpBackendUrl + 'json/';
const loadingComponent = <NonIdealState title="Loading Content" icon={<Spinner />} />;

type TocProps = OwnProps;

Expand All @@ -14,8 +20,9 @@ type OwnProps = {
/**
* Table of contents of SICP.
*/
const SicpToc: React.FC<TocProps> = props => {
const [sidebarContent, setSidebarContent] = useState(toc as TreeNodeInfo[]);

const Toc: React.FC<{ toc: TreeNodeInfo[]; props: TocProps }> = ({ toc, props }) => {
const [sidebarContent, setSidebarContent] = useState(toc);
const navigate = useNavigate();

const handleNodeExpand = (_node: TreeNodeInfo, path: integer[]) => {
Expand All @@ -40,15 +47,61 @@ const SicpToc: React.FC<TocProps> = props => {
[navigate, props]
);

return (
<Tree
className="sicp-toc-tree"
contents={sidebarContent}
onNodeClick={handleNodeClicked}
onNodeCollapse={handleNodeCollapse}
onNodeExpand={handleNodeExpand}
/>
);
};

const SicpToc: React.FC<TocProps> = props => {
const [lang, setLang] = useState(readSicpLangLocalStorage());
const [toc, setToc] = useState([] as TreeNodeInfo[]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);

React.useEffect(() => {
const handleLangChange = () => {
setLang(readSicpLangLocalStorage());
};
window.addEventListener('sicp-tb-lang-change', handleLangChange);
return () => window.removeEventListener('sicp-tb-lang-change', handleLangChange);
}, []);

React.useEffect(() => {
setLoading(true);
fetch(baseUrl + lang + '/toc.json')
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json();
})
.then(json => {
setToc(json as TreeNodeInfo[]);
})
.catch(error => {
console.log(error);
setError(true);
})
.finally(() => {
setLoading(false);
});
}, [lang]);

return (
<div className="sicp-toc">
<Tree
className="sicp-toc-tree"
contents={sidebarContent}
onNodeClick={handleNodeClicked}
onNodeCollapse={handleNodeCollapse}
onNodeExpand={handleNodeExpand}
/>
{loading ? (
<div className="sicp-content">{loadingComponent}</div>
) : error ? (
<Toc toc={fallbackToc as TreeNodeInfo[]} props={props} />
) : (
<Toc toc={toc} props={props} />
Comment on lines +101 to +103
Copy link
Preview

Copilot AI Jul 5, 2025

Choose a reason for hiding this comment

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

[nitpick] Rather than passing a single props object into Toc, either spread its contents (<Toc toc={fallbackToc} {...props} />) or rename the prop for clarity to avoid confusion.

Suggested change
<Toc toc={fallbackToc as TreeNodeInfo[]} props={props} />
) : (
<Toc toc={toc} props={props} />
<Toc toc={fallbackToc as TreeNodeInfo[]} {...props} />
) : (
<Toc toc={toc} {...props} />

Copilot uses AI. Check for mistakes.

)}
</div>
);
};
Expand Down
1 change: 1 addition & 0 deletions src/routes/routerConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const commonChildrenRoutes: RouteObject[] = [
{ path: 'contributors', lazy: Contributors },
{ path: 'callback/github', lazy: GitHubCallback },
{ path: 'sicpjs/:section?', lazy: Sicp },
{ path: 'sicpjs/:param_lang/:section?', lazy: Sicp },
Copy link
Preview

Copilot AI Jul 5, 2025

Choose a reason for hiding this comment

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

The route parameter is defined as :param_lang, but in useParams you destructure paramLang. These names must match exactly. Either rename the route to :paramLang or destructure param_lang in the component.

Suggested change
{ path: 'sicpjs/:param_lang/:section?', lazy: Sicp },
{ path: 'sicpjs/:paramLang/:section?', lazy: Sicp },

Copilot uses AI. Check for mistakes.

Comment on lines 52 to +53
Copy link
Preview

Copilot AI Jul 5, 2025

Choose a reason for hiding this comment

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

This generic :section? route is listed before the more specific :param_lang/:section? route, so it will match first and prevent the language-aware route from ever firing. Consider moving the two-segment route above the one-segment route.

Suggested change
{ path: 'sicpjs/:section?', lazy: Sicp },
{ path: 'sicpjs/:param_lang/:section?', lazy: Sicp },
{ path: 'sicpjs/:param_lang/:section?', lazy: Sicp },
{ path: 'sicpjs/:section?', lazy: Sicp },

Copilot uses AI. Check for mistakes.

{ path: 'features', lazy: Features }
];

Expand Down
Loading