Two languages
Write a label, a note or a summary in Chinese and English, and show the reader's half.
Sam writes in English, and Grandma reads Chinese. The card's labels, the notes beside its choices and the summaries a model writes all come in both languages. Each reader sees their own half.
You will learn
- What a text in two languages looks like
- How
saygives the reader's half - How
langOffinds the reader's language
A text in two languages
A text is either an object with both halves or one string that holds both, the way vocabularies label their possibilities:
import { say, isText, type Text } from '@reintent/lib/text';
const note: Text = { zh: '给奶奶的生日卡', en: 'a birthday card for Grandma' };
say(note, 'en'); // 'a birthday card for Grandma'
say('温暖 · warm', 'zh'); // '温暖'
say('Grandma', 'zh'); // 'Grandma'
isText(note); // trueA Text is { zh, en }. A Lang is 'zh' or 'en'. say(t, lang) gives the reader's half: of an object, the half in that language (the other when it is empty); of a string, the part before or after the middle dot ' · '. A string in one language is said as it is. isText(x) tells an object with both halves from anything else, for data a model wrote. both(s) makes a text with the same words in both halves.
The vocabulary's half(label, locale) is say for a label that may be missing: half(undefined, 'en', 'the tone') is 'the tone'.
The reader's language
import { langOf } from '@reintent/lib/text';
const lang = langOf(); // on Grandma's phone: 'zh'
langOf({ search: '?lang=en', navigator: 'zh-CN' }); // 'en'
langOf({ stored: 'zh', navigator: 'en-US' }); // 'zh'
langOf({}); // 'zh'langOf(sources) asks, in order, the page's query (?lang=en), what the reader chose before (localStorage.locale), and the browser's language. With no argument it reads them from the page. The sources are LangSources, so a server or a test passes its own. When none of them says, the language is Chinese.
Recap
- A
Textis{ zh, en }, or one string'中文 · English';say(t, lang)gives the reader's half. isTextrecognizes a text;halfsays a label with a fallback.langOf()reads the page's query, the stored choice, then the browser; Chinese when none says.
Last updated on
Edit on GitHub