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

Support translating default aside titles #517

Merged
merged 39 commits into from
Nov 17, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
5132831
Make aside label canbe translate.
liruifengv Aug 9, 2023
1cc3f2c
Merge branch 'main' into asides-i18n
liruifengv Aug 15, 2023
917e02b
Merge branch 'main' into asides-i18n
liruifengv Aug 21, 2023
ac80fc4
Merge branch 'main' into asides-i18n
liruifengv Aug 22, 2023
969c275
Update translate
liruifengv Aug 22, 2023
fedf41b
get current lang from file path
liruifengv Aug 22, 2023
d8a0b92
get default locale
liruifengv Aug 22, 2023
f12fdfb
format
liruifengv Aug 22, 2023
ed0c715
read userTranslations
liruifengv Aug 22, 2023
6325faa
update translate
liruifengv Aug 22, 2023
2f70609
format
liruifengv Aug 22, 2023
f7404df
Create thick-boxes-fail.md
liruifengv Aug 22, 2023
2f19456
Update thick-boxes-fail.md
liruifengv Aug 22, 2023
c8498c1
Merge branch 'main' into asides-i18n
liruifengv Sep 7, 2023
e82ad53
Merge branch 'main' into pr/517
delucis Nov 2, 2023
6b450a4
Merge branch 'main' into asides-i18n
liruifengv Nov 3, 2023
cca8a66
feat: pass useTranslations
liruifengv Nov 3, 2023
e66a1b0
Merge branch 'asides-i18n' of https://github.com/liruifengv/starlight…
liruifengv Nov 3, 2023
60b3b25
format
liruifengv Nov 3, 2023
6acd712
format path to unix style path
liruifengv Nov 3, 2023
e604e4b
Update .changeset/thick-boxes-fail.md
liruifengv Nov 3, 2023
d446792
Update packages/starlight/integrations/asides.ts
liruifengv Nov 3, 2023
b474053
Update packages/starlight/integrations/asides.ts
liruifengv Nov 3, 2023
83af8da
Fix type & getLocaleFromPath function
liruifengv Nov 3, 2023
c408ea6
format
liruifengv Nov 3, 2023
fc29e10
fix return type
liruifengv Nov 3, 2023
69e7925
delete unuse
liruifengv Nov 4, 2023
15b0438
Merge branch 'main' into asides-i18n
delucis Nov 16, 2023
3a56b9e
refactor: Use destructured objects instead of multiple arguments in a…
delucis Nov 16, 2023
25686a4
Handle missing file path in vFile history
delucis Nov 16, 2023
0d9415c
Fix existing tests
delucis Nov 16, 2023
a6ac57f
Fix test for default labels
delucis Nov 16, 2023
ed6006d
Fix asides test set up
delucis Nov 16, 2023
ab2e914
Add test for translated default labels
delucis Nov 16, 2023
e0cf7a8
Merge branch 'main' into asides-i18n
delucis Nov 16, 2023
a738926
Add test for no locales scenario
delucis Nov 16, 2023
a33185c
nit: Tweak schema field descriptions
delucis Nov 16, 2023
73fd8a9
Merge branch 'main' into asides-i18n
delucis Nov 17, 2023
27141e2
reset getting-started & components
liruifengv Nov 17, 2023
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
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) => {
liruifengv marked this conversation as resolved.
Show resolved Hide resolved

// 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": "危险"
}