Refactor i18n (#1405)

Merging note: the typing changes were fixed in a separate PR.

* Put rootDirs into subprojects

- typings do not work for any ts or svelte files
- if we set the 'rootDirs' in ts/tsconfig.json to '../bazel-bin/ts' and then inherit
  them from e.g. editor, the root will be changed to '../../bazel-bin/ts',
  however editor needs look in '../../bazel-bin/ts/editor' instead.

* Rename i18n and i18n_helpers to i18n-generated and i18n

- This way, we can restrict the awkwardness of importing files outside
  the ts directory within lib

* Fix missing typing of i18n and backend_proto by adding back symlinks

* Split up i18n-generated into i18n-{translate,modules}

* Change i18n from singleton to functions

* Revert "Put rootDirs into subprojects"

This partially reverts commit e1d4292ce3979e7b7ee21bf3951b8a462d45c29c.

It seems like this might not be necessary after all.
However some other change made on this branch seems to have fixed
the .svelte.d.ts imports

* Introduce i18n-bundles to remove circular import

There was a circular import i18n.ts <-> i18n-translate.ts

* Create own directory for i18n

* Move lib/i18n/translate to lib/translate

* This restores tree shaking

* Update tsconfig libs and module

* es2018-2020 have wide support on all modern browsers including

* Switch bundles and langs inside i18n to variables again

* Add missing copyright header

* Rename translate.ts to ftl.ts

* Remove the symlinks again

I added them to fix to have completion for tr, however this would have
also have meant to abandon the tree shaking.
As we want to have tree shaking, it's also not necessary to have the
symlinks anymore

* Revert "Update tsconfig libs and module"

This reverts commit 0a96776a475e9901c1f9f3407c726d1d002fb9ef.

* move withCollapsedWhitespace back to i18n/utils

* Add back /ts as in rootDirs
This commit is contained in:
Henrik Giesel 2021-10-07 15:31:49 +02:00 committed by GitHub
parent 26e2941950
commit dec0fbe845
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
66 changed files with 265 additions and 233 deletions

View File

@ -1,4 +1,5 @@
licenses.json
vendor
*.svelte.d.ts
lib/translate.ts
lib/i18n/modules.ts
backend_proto.d.ts

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import NotetypeSelector from "./NotetypeSelector.svelte";
import Mapper from "./Mapper.svelte";
import { ChangeNotetypeState, MapContext } from "./lib";

View File

@ -3,8 +3,8 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import MapperRow from "./MapperRow.svelte";
import * as tr from "../lib/ftl";
import { ChangeNotetypeState, MapContext } from "./lib";
import { slide } from "svelte/transition";

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import type { ChangeNotetypeState } from "./lib";
import { withButton } from "../components/helpers";

View File

@ -6,9 +6,9 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { Scheduler } from "../lib/proto";
import { buildNextLearnMsg } from "./lib";
import { bridgeLink } from "../lib/bridgecommand";
import * as tr from "../lib/ftl";
export let info: Scheduler.CongratsInfoResponse;
import * as tr from "../lib/i18n";
const congrats = tr.schedulingCongratulationsFinished();
let nextLearnMsg: string;

View File

@ -4,8 +4,7 @@
import { Scheduler } from "../lib/proto";
import { postRequest } from "../lib/postrequest";
import { naturalUnit, unitAmount, unitName } from "../lib/time";
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
export async function getCongratsInfo(): Promise<Scheduler.CongratsInfoResponse> {
return Scheduler.CongratsInfoResponse.decode(

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import SpinBoxRow from "./SpinBoxRow.svelte";

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import SwitchRow from "./SwitchRow.svelte";

View File

@ -3,10 +3,10 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import SwitchRow from "./SwitchRow.svelte";
import * as tr from "../lib/ftl";
import type { DeckOptionsState } from "./lib";
export let state: DeckOptionsState;

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import TooltipLabel from "./TooltipLabel.svelte";
import RevertButton from "./RevertButton.svelte";
import Row from "./Row.svelte";

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import { getContext } from "svelte";
import { modalsKey } from "../components/context-keys";
import type { DeckOptionsState, ConfigListEntry } from "./lib";

View File

@ -3,7 +3,7 @@
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import SpinBoxRow from "./SpinBoxRow.svelte";

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import EnumSelectorRow from "./EnumSelectorRow.svelte";

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import StepsInputRow from "./StepsInputRow.svelte";

View File

@ -3,14 +3,15 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import StepsInputRow from "./StepsInputRow.svelte";
import SpinBoxRow from "./SpinBoxRow.svelte";
import EnumSelectorRow from "./EnumSelectorRow.svelte";
import Warning from "./Warning.svelte";
import type { DeckOptionsState } from "./lib";
import * as tr from "../lib/ftl";
export let state: DeckOptionsState;
export let api = {};

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import type Dropdown from "bootstrap/js/dist/dropdown";
import WithDropdown from "../components/WithDropdown.svelte";
import DropdownMenu from "../components/DropdownMenu.svelte";

View File

@ -3,11 +3,12 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import { createEventDispatcher } from "svelte";
import type { DeckOptionsState } from "./lib";
import type Dropdown from "bootstrap/js/dist/dropdown";
import { withButton } from "../components/helpers";
import { withCollapsedWhitespace } from "../lib/i18n";
import ButtonGroup from "../components/ButtonGroup.svelte";
import ButtonGroupItem from "../components/ButtonGroupItem.svelte";
@ -41,7 +42,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
? tr.deckConfigWillRequireFullSync() + " "
: "") +
tr.deckConfigConfirmRemoveName({ name: state.getCurrentName() });
if (confirm(tr.i18n.withCollapsedWhitespace(msg))) {
if (confirm(withCollapsedWhitespace(msg))) {
try {
state.removeCurrentConfig();
} catch (err) {

View File

@ -3,11 +3,11 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import * as tr from "../lib/i18n";
import TitledContainer from "./TitledContainer.svelte";
import Item from "../components/Item.svelte";
import SpinBoxRow from "./SpinBoxRow.svelte";
import SwitchRow from "./SwitchRow.svelte";
import * as tr from "../lib/ftl";
import type { DeckOptionsState } from "./lib";
export let state: DeckOptionsState;

View File

@ -9,7 +9,7 @@ import { DeckConfig } from "../lib/proto";
import { postRequest } from "../lib/postrequest";
import { Writable, writable, get, Readable, readable } from "svelte/store";
import { isEqual, cloneDeep } from "lodash-es";
import * as tr from "../lib/i18n";
import { localeCompare } from "../lib/i18n";
import type { DynamicSvelteComponent } from "../sveltelib/dynamicComponent";
export async function getDeckOptionsInfo(
@ -278,9 +278,7 @@ export class DeckOptionsState {
useCount,
};
});
list.sort((a, b) =>
a.name.localeCompare(b.name, tr.i18n.langs, { sensitivity: "base" })
);
list.sort((a, b) => localeCompare(a.name, b.name, { sensitivity: "base" }));
return list;
}

View File

@ -1,7 +1,7 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
export const reviewMixChoices = (): string[] => [
tr.deckConfigReviewMixMixWithReviews(),

View File

@ -3,12 +3,11 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import IconButton from "../components/IconButton.svelte";
import WithShortcut from "../components/WithShortcut.svelte";
import OnlyEditable from "./OnlyEditable.svelte";
import * as tr from "../lib/ftl";
import { withButton } from "../components/helpers";
import { ellipseIcon } from "./icons";
import { forEditorField } from ".";

View File

@ -3,8 +3,6 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import ButtonGroup from "../components/ButtonGroup.svelte";
import ButtonGroupItem from "../components/ButtonGroupItem.svelte";
import IconButton from "../components/IconButton.svelte";
@ -13,6 +11,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import WithColorHelper from "./WithColorHelper.svelte";
import OnlyEditable from "./OnlyEditable.svelte";
import * as tr from "../lib/ftl";
import { bridgeCommand } from "../lib/bridgecommand";
import { withButton } from "../components/helpers";
import { textColorIcon, highlightColorIcon, arrowIcon } from "./icons";

View File

@ -3,8 +3,6 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import ButtonGroup from "../components/ButtonGroup.svelte";
import ButtonGroupItem from "../components/ButtonGroupItem.svelte";
import IconButton from "../components/IconButton.svelte";
@ -14,6 +12,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import OnlyEditable from "./OnlyEditable.svelte";
import CommandIconButton from "./CommandIconButton.svelte";
import * as tr from "../lib/ftl";
import { getListItem } from "../lib/dom";
import { getCurrentField, execCommand } from "./helpers";
import {

View File

@ -3,12 +3,11 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import ButtonGroup from "../components/ButtonGroup.svelte";
import ButtonGroupItem from "../components/ButtonGroupItem.svelte";
import CommandIconButton from "./CommandIconButton.svelte";
import * as tr from "../lib/ftl";
import {
boldIcon,
italicIcon,

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import ButtonGroup from "../components/ButtonGroup.svelte";
import ButtonGroupItem from "../components/ButtonGroupItem.svelte";

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import ButtonGroup from "../components/ButtonGroup.svelte";
import ButtonGroupItem from "../components/ButtonGroupItem.svelte";

View File

@ -3,12 +3,11 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import ButtonGroup from "../components/ButtonGroup.svelte";
import ButtonGroupItem from "../components/ButtonGroupItem.svelte";
import IconButton from "../components/IconButton.svelte";
import * as tr from "../lib/ftl";
import { inlineIcon, blockIcon } from "./icons";
export let activeImage: HTMLImageElement;

View File

@ -4,7 +4,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import { bridgeCommand } from "../lib/bridgecommand";
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import { withButton } from "../components/helpers";
import ButtonGroup from "../components/ButtonGroup.svelte";

View File

@ -4,7 +4,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import { bridgeCommand } from "../lib/bridgecommand";
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import { withButton } from "../components/helpers";
import WithShortcut from "../components/WithShortcut.svelte";

View File

@ -3,7 +3,7 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import { bridgeCommand } from "../lib/bridgecommand";
import { fieldFocusedKey, inCodableKey } from "./context-keys";

View File

@ -2,8 +2,7 @@
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { EditorField } from "./editor-field";
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
import { registerShortcut } from "../lib/shortcuts";
import { bridgeCommand } from "./lib";
import { appendInParentheses } from "./helpers";

View File

@ -13,6 +13,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import GraphRangeRadios from "./GraphRangeRadios.svelte";
import TableData from "./TableData.svelte";
import * as tr from "../lib/ftl";
import { RevlogRange, GraphRange } from "./graph-helpers";
import type { TableDatum, SearchEventMap } from "./graph-helpers";
import type { HistogramData } from "./histogram-graph";
@ -20,7 +21,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { GraphData } from "./added";
export let sourceData: Stats.GraphsResponse | null = null;
import * as tr from "../lib/i18n";
export let preferences: PreferenceStore<Stats.GraphPreferences>;
let histogramData = null as HistogramData | null;

View File

@ -4,6 +4,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { Stats } from "../lib/proto";
import * as tr from "../lib/ftl";
import Graph from "./Graph.svelte";
import InputBox from "./InputBox.svelte";
@ -15,7 +16,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { defaultGraphBounds, GraphRange, RevlogRange } from "./graph-helpers";
export let sourceData: Stats.GraphsResponse | null = null;
import * as tr from "../lib/i18n";
export let revlogRange: RevlogRange;
let graphRange: GraphRange = GraphRange.Year;

View File

@ -3,10 +3,10 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import { createEventDispatcher } from "svelte";
import type { Stats } from "../lib/proto";
import type { PreferenceStore } from "../sveltelib/preferences";
import { createEventDispatcher } from "svelte";
import * as tr from "../lib/ftl";
import Graph from "./Graph.svelte";
import InputBox from "./InputBox.svelte";
@ -21,7 +21,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
export let sourceData: Stats.GraphsResponse;
export let preferences: PreferenceStore<Stats.GraphPreferences>;
export let revlogRange: RevlogRange;
import * as tr from "../lib/i18n";
export let nightMode: boolean;
let { calendarFirstDayOfWeek } = preferences;

View File

@ -3,20 +3,19 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import { createEventDispatcher } from "svelte";
import type { Stats } from "../lib/proto";
import type { PreferenceStore } from "../sveltelib/preferences";
import Graph from "./Graph.svelte";
import InputBox from "./InputBox.svelte";
import { createEventDispatcher } from "svelte";
import type { Stats } from "../lib/proto";
import type { PreferenceStore } from "../sveltelib/preferences";
import * as translate from "../lib/ftl";
import { defaultGraphBounds } from "./graph-helpers";
import type { SearchEventMap } from "./graph-helpers";
import { gatherData, renderCards } from "./card-counts";
import type { GraphData, TableDatum } from "./card-counts";
export let sourceData: Stats.GraphsResponse;
import * as tr2 from "../lib/i18n";
export let preferences: PreferenceStore<Stats.GraphPreferences>;
let { cardCountsSeparateInactive, browserLinksSupported } = preferences;
@ -36,8 +35,8 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
tableData = renderCards(svg as any, bounds, graphData);
}
const label = tr2.statisticsCountsSeparateSuspendedBuriedCards();
const total = tr2.statisticsCountsTotalCards();
const label = translate.statisticsCountsSeparateSuspendedBuriedCards();
const total = translate.statisticsCountsTotalCards();
</script>
<Graph title={graphData.title}>

View File

@ -4,10 +4,10 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { Stats } from "../lib/proto";
import * as tr from "../lib/i18n";
import type { PreferenceStore } from "../sveltelib/preferences";
import { createEventDispatcher } from "svelte";
import * as tr from "../lib/ftl";
import HistogramGraph from "./HistogramGraph.svelte";
import Graph from "./Graph.svelte";

View File

@ -14,6 +14,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import TableData from "./TableData.svelte";
import type { PreferenceStore } from "../sveltelib/preferences";
import * as tr from "../lib/ftl";
import type { HistogramData } from "./histogram-graph";
import { GraphRange, RevlogRange } from "./graph-helpers";
import type { TableDatum, SearchEventMap } from "./graph-helpers";
@ -21,7 +22,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { GraphData } from "./future-due";
export let sourceData: Stats.GraphsResponse | null = null;
import * as tr from "../lib/i18n";
export let preferences: PreferenceStore<Stats.GraphPreferences>;
const dispatch = createEventDispatcher<SearchEventMap>();

View File

@ -3,10 +3,10 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import * as tr from "../lib/ftl";
import { RevlogRange, GraphRange } from "./graph-helpers";
import { timeSpan, MONTH, YEAR } from "../lib/time";
import * as tr from "../lib/i18n";
export let revlogRange: RevlogRange;
export let graphRange: GraphRange;
export let followRevlog: boolean = false;

View File

@ -3,8 +3,6 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { Stats } from "../lib/proto";
import Graph from "./Graph.svelte";
import InputBox from "./InputBox.svelte";
import AxisTicks from "./AxisTicks.svelte";
@ -12,11 +10,13 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import GraphRangeRadios from "./GraphRangeRadios.svelte";
import CumulativeOverlay from "./CumulativeOverlay.svelte";
import HoverColumns from "./HoverColumns.svelte";
import type { Stats } from "../lib/proto";
import * as tr from "../lib/ftl";
import { defaultGraphBounds, RevlogRange, GraphRange } from "./graph-helpers";
import { renderHours } from "./hours";
export let sourceData: Stats.GraphsResponse | null = null;
import * as tr from "../lib/i18n";
export let revlogRange: RevlogRange;
let graphRange: GraphRange = GraphRange.Year;

View File

@ -3,17 +3,16 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import { timeSpan, MONTH } from "../lib/time";
import type { Stats } from "../lib/proto";
import type { PreferenceStore } from "../sveltelib/preferences";
import { createEventDispatcher } from "svelte";
import Graph from "./Graph.svelte";
import InputBox from "./InputBox.svelte";
import HistogramGraph from "./HistogramGraph.svelte";
import TableData from "./TableData.svelte";
import { timeSpan, MONTH } from "../lib/time";
import * as tr from "../lib/ftl";
import type { Stats } from "../lib/proto";
import type { PreferenceStore } from "../sveltelib/preferences";
import { createEventDispatcher } from "svelte";
import type { HistogramData } from "./histogram-graph";
import {
gatherIntervalData,
@ -24,7 +23,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { TableDatum, SearchEventMap } from "./graph-helpers";
export let sourceData: Stats.GraphsResponse | null = null;
import * as tr from "../lib/i18n";
export let preferences: PreferenceStore<Stats.GraphPreferences>;
const dispatch = createEventDispatcher<SearchEventMap>();

View File

@ -4,8 +4,10 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { GraphBounds } from "./graph-helpers";
import * as tr from "../lib/ftl";
export let bounds: GraphBounds;
import * as tr from "../lib/i18n";
const noData = tr.statisticsNoData();
</script>

View File

@ -3,11 +3,10 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { Writable } from "svelte/store";
import InputBox from "./InputBox.svelte";
import * as tr from "../lib/i18n";
import type { Writable } from "svelte/store";
import * as tr from "../lib/ftl";
import { RevlogRange, daysToRevlogRange } from "./graph-helpers";
enum SearchRange {

View File

@ -3,8 +3,6 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { Stats } from "../lib/proto";
import Graph from "./Graph.svelte";
import InputBox from "./InputBox.svelte";
import NoDataOverlay from "./NoDataOverlay.svelte";
@ -14,6 +12,8 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import AxisTicks from "./AxisTicks.svelte";
import HoverColumns from "./HoverColumns.svelte";
import type { Stats } from "../lib/proto";
import * as tr from "../lib/ftl";
import { defaultGraphBounds, RevlogRange, GraphRange } from "./graph-helpers";
import type { TableDatum } from "./graph-helpers";
import { gatherData, renderReviews } from "./reviews";
@ -21,7 +21,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
export let sourceData: Stats.GraphsResponse | null = null;
export let revlogRange: RevlogRange;
import * as tr from "../lib/i18n";
let graphData: GraphData | null = null;

View File

@ -4,12 +4,12 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="typescript">
import type { TableDatum } from "./graph-helpers";
import { i18n } from "../lib/i18n";
import { direction } from "../lib/i18n";
export let tableData: TableDatum[];
</script>
<div>
<table dir={i18n.direction()}>
<table dir={direction()}>
{#each tableData as { label, value }}
<tr>
<td class="align-end">{label}:</td>

View File

@ -19,10 +19,10 @@ import {
import type { Bin } from "d3";
import type { HistogramData } from "./histogram-graph";
import * as tr from "../lib/ftl";
import { dayLabel } from "../lib/time";
import { GraphRange } from "./graph-helpers";
import type { TableDatum, SearchDispatch } from "./graph-helpers";
import * as tr from "../lib/i18n";
export interface GraphData {
daysAdded: number[];

View File

@ -6,8 +6,6 @@
@typescript-eslint/no-explicit-any: "off",
*/
import { Stats } from "../lib/proto";
import {
interpolateRdYlGn,
select,
@ -19,6 +17,8 @@ import {
axisLeft,
sum,
} from "d3";
import { Stats } from "../lib/proto";
import * as tr from "../lib/ftl";
import { showTooltip, hideTooltip } from "./tooltip";
import {
GraphBounds,
@ -26,7 +26,6 @@ import {
GraphRange,
millisecondCutoffForRange,
} from "./graph-helpers";
import * as tr from "../lib/i18n";
type ButtonCounts = [number, number, number, number];

View File

@ -29,8 +29,8 @@ import {
SearchDispatch,
} from "./graph-helpers";
import { clickableClass } from "./graph-styles";
import { i18n } from "../lib/i18n";
import * as tr from "../lib/i18n";
import { weekdayLabel, toLocaleString } from "../lib/i18n";
import * as tr from "../lib/ftl";
export interface GraphData {
// indexed by day, where day is relative to today
@ -155,7 +155,7 @@ export function renderCalendar(
.interpolator((n) => interpolateBlues(cappedRange(n)!));
function tooltipText(d: DayDatum): string {
const date = d.date.toLocaleString(i18n.langs, {
const date = toLocaleString(d.date, {
weekday: "long",
year: "numeric",
month: "long",
@ -172,7 +172,7 @@ export function renderCalendar(
.selectAll("text")
.data(sourceData.weekdayLabels)
.join("text")
.text((d: number) => i18n.weekdayLabel(d))
.text((d: number) => weekdayLabel(d))
.attr("width", x(-1)! - 2)
.attr("height", height - 2)
.attr("x", x(1)! - 3)

View File

@ -6,6 +6,7 @@
@typescript-eslint/no-explicit-any: "off",
*/
import * as tr from "../lib/ftl";
import { CardQueue, CardType } from "../lib/cards";
import type { Stats, Cards } from "../lib/proto";
import {
@ -22,8 +23,6 @@ import {
} from "d3";
import type { GraphBounds } from "./graph-helpers";
import * as tr from "../lib/i18n";
type Count = [string, number, boolean, string];
export interface GraphData {
title: string;

View File

@ -16,11 +16,10 @@ import {
interpolateRdYlGn,
} from "d3";
import type { Bin, ScaleLinear } from "d3";
import * as tr from "../lib/ftl";
import { CardType } from "../lib/cards";
import type { HistogramData } from "./histogram-graph";
import type { TableDatum, SearchDispatch } from "./graph-helpers";
import * as tr from "../lib/i18n";
export interface GraphData {
eases: number[];

View File

@ -17,13 +17,13 @@ import {
interpolateGreens,
} from "d3";
import type { Bin } from "d3";
import * as tr from "../lib/ftl";
import { CardQueue } from "../lib/cards";
import type { HistogramData } from "./histogram-graph";
import { dayLabel } from "../lib/time";
import { GraphRange } from "./graph-helpers";
import type { TableDatum, SearchDispatch } from "./graph-helpers";
import * as tr from "../lib/i18n";
export interface GraphData {
dueCounts: Map<number, number>;

View File

@ -21,6 +21,7 @@ import {
curveBasis,
} from "d3";
import * as tr from "../lib/ftl";
import { showTooltip, hideTooltip } from "./tooltip";
import {
GraphBounds,
@ -29,7 +30,6 @@ import {
millisecondCutoffForRange,
} from "./graph-helpers";
import { oddTickClass } from "./graph-styles";
import * as tr from "../lib/i18n";
interface Hour {
hour: number;

View File

@ -18,12 +18,12 @@ import {
interpolateBlues,
} from "d3";
import type { Bin } from "d3";
import * as tr from "../lib/ftl";
import { timeSpan } from "../lib/time";
import { CardType } from "../lib/cards";
import type { HistogramData } from "./histogram-graph";
import type { TableDatum, SearchDispatch } from "./graph-helpers";
import { timeSpan } from "../lib/time";
import * as tr from "../lib/i18n";
export interface IntervalGraphData {
intervals: number[];

View File

@ -32,10 +32,10 @@ import {
} from "d3";
import type { Bin } from "d3";
import * as tr from "../lib/ftl";
import type { TableDatum } from "./graph-helpers";
import { GraphBounds, setDataAvailable, GraphRange } from "./graph-helpers";
import { showTooltip, hideTooltip } from "./tooltip";
import * as tr from "../lib/i18n";
interface Reviews {
learn: number;

View File

@ -3,8 +3,7 @@
import { Stats } from "../lib/proto";
import { studiedToday } from "../lib/time";
import * as tr from "../lib/i18n";
import * as tr from "../lib/ftl";
export interface TodayData {
title: string;

View File

@ -1,17 +1,11 @@
load("@rules_python//python:defs.bzl", "py_binary")
load("//ts:prettier.bzl", "prettier_test")
load("//ts:eslint.bzl", "eslint_test")
load("//ts:protobuf.bzl", "protobufjs_library")
load("//ts:typescript.bzl", "typescript")
load("@rules_python//python:defs.bzl", "py_binary")
load("@py_deps//:requirements.bzl", "requirement")
load("//ts:jest.bzl", "jest_test")
protobufjs_library(
name = "backend_proto",
proto = "//proto:backend_proto_lib",
visibility = ["//visibility:public"],
)
py_binary(
name = "genfluent",
srcs = [
@ -22,21 +16,33 @@ py_binary(
requirement("stringcase"),
],
)
_i18n_generated = [
"ftl.ts",
"i18n/modules.ts",
]
genrule(
name = "fluent_gen",
outs = ["i18n.ts"],
cmd = "$(location genfluent) $(location //rslib/i18n:strings.json) $@",
outs = _i18n_generated,
cmd = "$(location genfluent) $(location //rslib/i18n:strings.json) $(OUTS)",
tools = [
"genfluent",
"//rslib/i18n:strings.json",
],
)
protobufjs_library(
name = "backend_proto",
proto = "//proto:backend_proto_lib",
visibility = ["//visibility:public"],
)
typescript(
name = "lib",
generated = [
":i18n.ts",
":backend_proto.d.ts",
":ftl.ts",
":i18n/modules.ts",
],
deps = [
":backend_proto",

View File

@ -7,7 +7,7 @@ from typing import List, Literal, TypedDict
import stringcase
strings_json, outfile = sys.argv[1:]
strings_json, translate_out, modules_out = sys.argv[1:]
modules = json.load(open(strings_json, encoding="utf8"))
@ -17,10 +17,12 @@ class Variable(TypedDict):
def methods() -> str:
out = [
'import { i18n } from "./i18n_helpers";',
'export { i18n, setupI18n } from "./i18n_helpers";',
]
out = [ """import type { FluentVariable } from "@fluent/bundle";
import { getMessage } from "./i18n";
function translate(key: string, args: Record<string, FluentVariable> = {}): string {
return getMessage(key, args) ?? `missing key: ${key}`;
}""" ]
for module in modules:
for translation in module["translations"]:
key = stringcase.camelcase(translation["key"].replace("-", "_"))
@ -31,7 +33,7 @@ def methods() -> str:
f"""
/** {doc} */
export function {key}({arg_types}): string {{
return i18n.translate("{translation["key"]}"{args})
return translate("{translation["key"]}"{args})
}}
"""
)
@ -102,17 +104,17 @@ def module_names() -> str:
return buf
out = ""
out += methods()
out += module_names()
open(outfile, "wb").write(
(
"""// Copyright: Ankitects Pty Ltd and contributors
def write(outfile, out) -> None:
open(outfile, "wb").write(
(
f"""// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
"""
+ out
).encode("utf8")
)
+ out
).encode("utf8")
)
write(translate_out, str(methods()))
write(modules_out, str(module_names()))

46
ts/lib/i18n/bundles.ts Normal file
View File

@ -0,0 +1,46 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { FluentNumber } from "@fluent/bundle";
import type { FluentBundle, FluentVariable } from "@fluent/bundle";
let bundles: FluentBundle[] = [];
export function setBundles(newBundles: FluentBundle[]): void {
bundles = newBundles;
}
export function firstLanguage(): string {
return bundles[0].locales[0];
}
function toFluentNumber(num: number): FluentNumber {
return new FluentNumber(num, {
maximumFractionDigits: 2,
});
}
function formatArgs(
args: Record<string, FluentVariable>
): Record<string, FluentVariable> {
return Object.fromEntries(
Object.entries(args).map(([key, value]) => [
key,
typeof value === "number" ? toFluentNumber(value) : value,
])
);
}
export function getMessage(
key: string,
args: Record<string, FluentVariable> = {}
): string | null {
for (const bundle of bundles) {
const msg = bundle.getMessage(key);
if (msg && msg.value) {
return bundle.formatPattern(msg.value, formatArgs(args));
}
}
return null;
}

6
ts/lib/i18n/index.ts Normal file
View File

@ -0,0 +1,6 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
export * from "./bundles";
export * from "./modules";
export * from "./utils";

87
ts/lib/i18n/utils.ts Normal file
View File

@ -0,0 +1,87 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import "intl-pluralrules";
import { FluentBundle, FluentResource } from "@fluent/bundle";
import { firstLanguage, setBundles } from "./bundles";
import type { ModuleName } from "./modules";
export function supportsVerticalText(): boolean {
const firstLang = firstLanguage();
return (
firstLang.startsWith("ja") ||
firstLang.startsWith("zh") ||
firstLang.startsWith("ko")
);
}
export function direction(): string {
const firstLang = firstLanguage();
if (
firstLang.startsWith("ar") ||
firstLang.startsWith("he") ||
firstLang.startsWith("fa")
) {
return "rtl";
} else {
return "ltr";
}
}
export function weekdayLabel(n: number): string {
const firstLang = firstLanguage();
const now = new Date();
const daysFromToday = -now.getDay() + n;
const desiredDay = new Date(now.getTime() + daysFromToday * 86_400_000);
return desiredDay.toLocaleDateString(firstLang, {
weekday: "narrow",
});
}
let langs: string[] = [];
export function toLocaleString(
date: Date,
options?: Intl.DateTimeFormatOptions
): string {
return date.toLocaleDateString(langs, options);
}
export function localeCompare(
first: string,
second: string,
options?: Intl.CollatorOptions
): number {
return first.localeCompare(second, langs, options);
}
/// Treat text like HTML, merging multiple spaces and converting
/// newlines to spaces.
export function withCollapsedWhitespace(s: string): string {
return s.replace(/\s+/g, " ");
}
export async function setupI18n(args: { modules: ModuleName[] }): Promise<void> {
const resp = await fetch("/_anki/i18nResources", {
method: "POST",
body: JSON.stringify(args),
});
if (!resp.ok) {
throw Error(`unexpected reply: ${resp.statusText}`);
}
const json = await resp.json();
const newBundles: FluentBundle[] = [];
for (const i in json.resources) {
const text = json.resources[i];
const lang = json.langs[i];
const bundle = new FluentBundle([lang, "en-US"]);
const resource = new FluentResource(text);
bundle.addResource(resource);
newBundles.push(bundle);
}
setBundles(newBundles);
langs = json.langs;
}

View File

@ -1,104 +0,0 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
// An i18n singleton and setupI18n is re-exported via the generated i18n.ts file,
// so you should not need to access this file directly.
import "intl-pluralrules";
import { FluentBundle, FluentResource, FluentNumber } from "@fluent/bundle";
type RecordVal = number | string | FluentNumber;
function formatNumbers(args?: Record<string, RecordVal>): void {
if (!args) {
return;
}
for (const key of Object.keys(args)) {
if (typeof args[key] === "number") {
args[key] = new FluentNumber(args[key] as number, {
maximumFractionDigits: 2,
});
}
}
}
export class I18n {
bundles: FluentBundle[] = [];
langs: string[] = [];
translate(key: string, args?: Record<string, RecordVal>): string {
formatNumbers(args);
for (const bundle of this.bundles) {
const msg = bundle.getMessage(key);
if (msg && msg.value) {
return bundle.formatPattern(msg.value, args);
}
}
return `missing key: ${key}`;
}
supportsVerticalText(): boolean {
const firstLang = this.bundles[0].locales[0];
return (
firstLang.startsWith("ja") ||
firstLang.startsWith("zh") ||
firstLang.startsWith("ko")
);
}
direction(): string {
const firstLang = this.bundles[0].locales[0];
if (
firstLang.startsWith("ar") ||
firstLang.startsWith("he") ||
firstLang.startsWith("fa")
) {
return "rtl";
} else {
return "ltr";
}
}
weekdayLabel(n: number): string {
const firstLang = this.bundles[0].locales[0];
const now = new Date();
const daysFromToday = -now.getDay() + n;
const desiredDay = new Date(now.getTime() + daysFromToday * 86_400_000);
return desiredDay.toLocaleDateString(firstLang, {
weekday: "narrow",
});
}
/// Treat text like HTML, merging multiple spaces and converting
/// newlines to spaces.
withCollapsedWhitespace(s: string): string {
return s.replace(/\s+/g, " ");
}
}
// global singleton
export const i18n = new I18n();
import type { ModuleName } from "./i18n";
export async function setupI18n(args: { modules: ModuleName[] }): Promise<void> {
const resp = await fetch("/_anki/i18nResources", {
method: "POST",
body: JSON.stringify(args),
});
if (!resp.ok) {
throw Error(`unexpected reply: ${resp.statusText}`);
}
const json = await resp.json();
i18n.bundles = [];
for (const i in json.resources) {
const text = json.resources[i];
const lang = json.langs[i];
const bundle = new FluentBundle([lang, "en-US"]);
const resource = new FluentResource(text);
bundle.addResource(resource);
i18n.bundles.push(bundle);
}
i18n.langs = json.langs;
}

View File

@ -1,7 +1,7 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import * as tr from "./i18n";
import * as tr from "./ftl";
import { isApplePlatform } from "./platform";
// those are the modifiers that Anki works with

View File

@ -2,6 +2,7 @@
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { anki } from "./backend_proto";
import Cards = anki.cards;
import DeckConfig = anki.deckconfig;
import Notetypes = anki.notetypes;

View File

@ -1,7 +1,7 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import * as tr from "./i18n";
import * as tr from "./ftl";
export const SECOND = 1.0;
export const MINUTE = 60.0 * SECOND;

View File

@ -1,6 +1,6 @@
{
"extends": "../tsconfig.json",
"include": ["*", "../../bazel-bin/ts/lib/*"],
"include": ["*", "i18n/*"],
"references": [],
"compilerOptions": {
"types": ["jest"]

View File

@ -17,14 +17,15 @@
"declaration": true,
"composite": true,
"target": "es6",
"module": "es6",
"module": "es2020",
"lib": [
"es2017",
"es2018.intl",
"es2019.array",
"es2018.promise",
"es2020.promise",
"es2019.array",
"es2019.object",
"es2019.string",
"es2020.promise",
"dom",
"dom.iterable"
],

View File

@ -4,12 +4,13 @@ load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin", "js_library")
def typescript(
name,
srcs = None,
exclude = [],
generated = [],
tsconfig = "tsconfig.json",
visibility = ["//visibility:public"],
**kwargs):
if not srcs:
srcs = native.glob(["**/*.ts"])
srcs = native.glob(["**/*.ts"], exclude = exclude)
# all tsconfig files must be in the bazel-out folder
copy_to_bin(