Skip to content

Commit

Permalink
Make aside label canbe translate.
Browse files Browse the repository at this point in the history
  • Loading branch information
liruifengv committed Aug 9, 2023
1 parent 6a7692a commit 5132831
Show file tree
Hide file tree
Showing 17 changed files with 138 additions and 25 deletions.
2 changes: 1 addition & 1 deletion docs/src/content/docs/zh/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ description: This is a page in my Starlight-powered site

## 更新 Starlight

:::tip[提示]
:::tip
由于 Starlight 是 beta 软件,所以会经常更新和改进。请务必定期更新 Starlight!
:::

Expand Down
73 changes: 63 additions & 10 deletions packages/starlight/integrations/asides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,63 @@ import remarkDirective from 'remark-directive';
import type { Plugin, Transformer } from 'unified';
import { remove } from 'unist-util-remove';
import { visit } from 'unist-util-visit';
import builtinTranslations from '../translations';
import type { StarlightConfig } from '../types';


/** Build a dictionary by layering preferred translation sources. */
function buildDictionary(
base: (typeof builtinTranslations)[string],
...dictionaries: (CollectionEntry<'i18n'>['data'] | undefined)[]
) {
const dictionary = { ...base };
// Iterate over alternate dictionaries to avoid overwriting preceding values with `undefined`.
for (const dict of dictionaries) {
for (const key in dict) {
const value = dict[key as keyof typeof dict];
if (value) dictionary[key as keyof typeof dict] = value;
}
}
return dictionary;
}

// TODO get defaultLocale
const defaultLocale = 'root';

/** All translation data from the i18n collection, keyed by `id`, which matches locale. */
let userTranslations = {};
try {
// Load the user’s i18n collection and ignore the error if it doesn’t exist.
// TODO How to get user i18n collection
} catch {}

/** Default map of UI strings based on Starlight and user-configured defaults. */
const defaults = buildDictionary(
builtinTranslations.en!,
userTranslations.en,
builtinTranslations[defaultLocale],
userTranslations[defaultLocale]
);

function localeToLang(locale: string | undefined): string {
return 'zh';
}

/**
* Generate a utility function that returns UI strings for the given `locale`.
* @param {string | undefined} [locale]
* @example
* const t = useTranslations('en');
* const label = t('search.label'); // => 'Search'
*/
export function useTranslations(locale: string | undefined) {
const lang = localeToLang(locale);
const dictionary = buildDictionary(defaults, builtinTranslations[lang], userTranslations[lang]);
const t = <K extends keyof typeof dictionary>(key: K) => dictionary[key];
t.pick = (startOfKey: string) =>
Object.fromEntries(Object.entries(dictionary).filter(([k]) => k.startsWith(startOfKey)));
return t;
}

/** Hacky function that generates an mdast HTML tree ready for conversion to HTML by rehype. */
function h(el: string, attrs: Properties = {}, children: any[] = []): P {
Expand Down Expand Up @@ -54,14 +111,9 @@ function remarkAsides(): Plugin<[], Root> {
type Variant = 'note' | 'tip' | 'caution' | 'danger';
const variants = new Set(['note', 'tip', 'caution', 'danger']);
const isAsideVariant = (s: string): s is Variant => variants.has(s);

// TODO: hook these up for i18n once the design for translating strings is ready
const defaultTitles = {
note: 'Note',
tip: 'Tip',
caution: 'Caution',
danger: 'Danger',
};
// TODO how to get current locale
const locale = 'en';
const t = useTranslations(locale);

const iconPaths = {
// Information icon
Expand Down Expand Up @@ -96,18 +148,19 @@ function remarkAsides(): Plugin<[], Root> {
};

const transformer: Transformer<Root> = (tree) => {

// console.log('Astro.props', Astro.props);
visit(tree, (node, index, parent) => {
if (!parent || index === null || node.type !== 'containerDirective') {
return;
}
const variant = node.name;
if (!isAsideVariant(variant)) return;

// remark-directive converts a container’s “label” to a paragraph in
// its children, but we want to pass it as the title prop to <Aside>, so
// we iterate over the children, find a directive label, store it for the
// title prop, and remove the paragraph from children.
let title = defaultTitles[variant];
let title = t(`aside.${variant}`) || 'error';
remove(node, (child): boolean | void => {
if (child.data?.directiveLabel) {
if (
Expand Down
4 changes: 4 additions & 0 deletions packages/starlight/schemas/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ function starlightI18nSchema() {
.describe('Label shown on the “next page” pagination arrow in the page footer.'),

'404.text': z.string().describe('Text shown on Starlight’s default 404 page'),
'aside.tip': z.string().describe('Text shown on the aside tip'),
'aside.note': z.string().describe('Text shown on the aside note'),
'aside.caution': z.string().describe('Text shown on the aside warning'),
'aside.danger': z.string().describe('Text shown on the aside danger'),
})
.partial();
}
Expand Down
6 changes: 5 additions & 1 deletion packages/starlight/translations/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "اخر تحديث:",
"page.previousLink": "السابق",
"page.nextLink": "التالي",
"404.text": "الصفحة غير موجودة. تأكد من الرابط أو ابحث بإستعمال شريط البحث."
"404.text": "الصفحة غير موجودة. تأكد من الرابط أو ابحث بإستعمال شريط البحث.",
"aside.note": "ملحوظة",
"aside.tip": "نصيحة",
"aside.caution": "تنبيه",
"aside.danger": "تحذير"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Poslední aktualizace:",
"page.previousLink": "Předchozí",
"page.nextLink": "Další",
"404.text": "Stránka nenalezena. Zkontrolujte adresu URL nebo zkuste použít vyhledávací pole."
"404.text": "Stránka nenalezena. Zkontrolujte adresu URL nebo zkuste použít vyhledávací pole.",
"aside.note": "Note",
"aside.tip": "Tip",
"aside.caution": "Caution",
"aside.danger": "Danger"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/da.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Sidst opdateret:",
"page.previousLink": "Forrige",
"page.nextLink": "Næste",
"404.text": "Siden er ikke fundet. Tjek din URL eller prøv søgelinjen."
"404.text": "Siden er ikke fundet. Tjek din URL eller prøv søgelinjen.",
"aside.note": "Note",
"aside.tip": "Tip",
"aside.caution": "Caution",
"aside.danger": "Danger"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Zuletzt bearbeitet:",
"page.previousLink": "Vorherige Seite",
"page.nextLink": "Nächste Seite",
"404.text": "Seite nicht gefunden. Überprüfe die URL oder nutze die Suchleiste."
"404.text": "Seite nicht gefunden. Überprüfe die URL oder nutze die Suchleiste.",
"aside.note": "Hinweis",
"aside.tip": "Tipp",
"aside.caution": "Achtung",
"aside.danger": "Gefahr"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Last updated:",
"page.previousLink": "Previous",
"page.nextLink": "Next",
"404.text": "Page not found. Check the URL or try using the search bar."
"404.text": "Page not found. Check the URL or try using the search bar.",
"aside.note": "Note",
"aside.tip": "Tip",
"aside.caution": "Caution",
"aside.danger": "Danger"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Última actualización:",
"page.previousLink": "Página anterior",
"page.nextLink": "Siguiente página",
"404.text": "Página no encontrada. Verifica la URL o intenta usar la barra de búsqueda."
"404.text": "Página no encontrada. Verifica la URL o intenta usar la barra de búsqueda.",
"aside.note": "Nota",
"aside.tip": "Consejo",
"aside.caution": "Precaución",
"aside.danger": "Peligro"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Dernière mise à jour :",
"page.previousLink": "Précédent",
"page.nextLink": "Suivant",
"404.text": "Page non trouvée. Vérifiez l’URL ou essayez d’utiliser la barre de recherche."
"404.text": "Page non trouvée. Vérifiez l’URL ou essayez d’utiliser la barre de recherche.",
"aside.note": "Note",
"aside.tip": "Astuce",
"aside.caution": "Attention",
"aside.danger": "Danger"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Ultimo aggiornamento:",
"page.previousLink": "Indietro",
"page.nextLink": "Avanti",
"404.text": "Pagina non trovata. Verifica l'URL o prova a utilizzare la barra di ricerca."
"404.text": "Pagina non trovata. Verifica l'URL o prova a utilizzare la barra di ricerca.",
"aside.note": "Nota",
"aside.tip": "Consiglio",
"aside.caution": "Attenzione",
"aside.danger": "Pericolo"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "最終更新日:",
"page.previousLink": "前へ",
"page.nextLink": "次へ",
"404.text": "ページが見つかりません。 URL を確認するか、検索バーを使用してみてください。"
"404.text": "ページが見つかりません。 URL を確認するか、検索バーを使用してみてください。",
"aside.note": "ノート",
"aside.tip": "ヒント",
"aside.caution": "注意",
"aside.danger": "危険"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/nb.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Sist oppdatert:",
"page.previousLink": "Forrige",
"page.nextLink": "Neste",
"404.text": "Siden ble ikke funnet. Sjekk URL-en eller prøv å bruke søkefeltet."
"404.text": "Siden ble ikke funnet. Sjekk URL-en eller prøv å bruke søkefeltet.",
"aside.note": "Note",
"aside.tip": "Tip",
"aside.caution": "Caution",
"aside.danger": "Danger"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Laatst bewerkt:",
"page.previousLink": "Laatste",
"page.nextLink": "Volgende",
"404.text": "Pagina niet gevonden. Controleer de URL of probeer de zoekbalk."
"404.text": "Pagina niet gevonden. Controleer de URL of probeer de zoekbalk.",
"aside.note": "Note",
"aside.tip": "Tip",
"aside.caution": "Caution",
"aside.danger": "Danger"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Última atualização:",
"page.previousLink": "Anterior",
"page.nextLink": "Próximo",
"404.text": "Página não encontrada. Verifique o URL ou tente usar a barra de pesquisa."
"404.text": "Página não encontrada. Verifique o URL ou tente usar a barra de pesquisa.",
"aside.note": "Nota",
"aside.tip": "Dica",
"aside.caution": "Cuidado",
"aside.danger": "Perigo"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "Son güncelleme:",
"page.previousLink": "Önceki",
"page.nextLink": "Sonraki",
"404.text": "Sayfa bulunamadı. URL'i kontrol edin ya da arama çubuğunu kullanmayı deneyin."
"404.text": "Sayfa bulunamadı. URL'i kontrol edin ya da arama çubuğunu kullanmayı deneyin.",
"aside.note": "Note",
"aside.tip": "Tip",
"aside.caution": "Caution",
"aside.danger": "Danger"
}
6 changes: 5 additions & 1 deletion packages/starlight/translations/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@
"page.lastUpdated": "最近更新:",
"page.previousLink": "上一页",
"page.nextLink": "下一页",
"404.text": "页面未找到。检查 URL 或尝试使用搜索栏。"
"404.text": "页面未找到。检查 URL 或尝试使用搜索栏。",
"aside.note": "注意",
"aside.tip": "提示",
"aside.caution": "警告",
"aside.danger": "危险"
}

0 comments on commit 5132831

Please sign in to comment.