Skip to content

Commit

Permalink
Update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
robisim74 committed May 4, 2023
1 parent d812d12 commit e602fa5
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 70 deletions.
26 changes: 17 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Live example on [Cloudflare pages](https://qwik-speak.pages.dev/) and playground

## Overview
### Getting the translation
```jsx
```tsx
import { $translate as t } from 'qwik-speak';

export default component$(() => {
Expand All @@ -32,7 +32,7 @@ export default component$(() => {
});
```
### Getting dates, relative time & numbers
```jsx
```tsx
import { formatDate as fd, relativeTime as rt, formatNumber as fn } from 'qwik-speak';

export default component$(() => {
Expand Down Expand Up @@ -84,7 +84,7 @@ stateDiagram-v2
of translation data
end note
```
`SpeakState` is immutable: it cannot be updated after it is created and is not reactive.
> `SpeakState` is immutable: it cannot be updated after it is created and is not reactive.
- `useSpeakContext()` Returns the Speak state
- `useSpeakConfig()` Returns the configuration in Speak context
Expand Down Expand Up @@ -130,22 +130,30 @@ and optionally contains:
- `langs` Optional additional languages to preload data for (multilingual)

### Functions
- `$translate(keys: string | string[], params?: any, ctx?: SpeakState, lang?: string)`
#### Translate
- `$translate(keys: string | string[], params?: any, lang?: string)`
Translates a key or an array of keys. The syntax of the string is `key@@[default value]`

- `$plural(value: number | string, key?: string, params?: any, options?: Intl.PluralRulesOptions, ctx?: SpeakState, lang?: string)`
- `$inlineTranslate(keys: string | string[], ctx: SpeakState, params?: any, lang?: string)`
Translates a key or an array of keys outside the component$. The syntax of the string is `key@@[default value]`

- `useTranslate$()`
Returns the translate functions as QRL

- `$plural(value: number | string, key?: string, params?: any, options?: Intl.PluralRulesOptions, lang?: string)`
Gets the plural by a number using [Intl.PluralRules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules) API

- `formatDate(value: Date | number | string, options?: Intl.DateTimeFormatOptions, locale?: SpeakLocale, lang?: string, timeZone?: string)`
#### Localize
- `formatDate(value: Date | number | string, options?: Intl.DateTimeFormatOptions, lang?: string, timeZone?: string)`
Formats a date using [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) API

- `relativeTime(value: number | string, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions, locale?: SpeakLocale, lang?: string)`
- `relativeTime(value: number | string, unit: Intl.RelativeTimeFormatUnit, options?: Intl.RelativeTimeFormatOptions, lang?: string)`
Formats a relative time using [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat) API

- `formatNumber(value: number | string, options?: Intl.NumberFormatOptions, locale?: SpeakLocale, lang?: string, currency?: string)`
- `formatNumber(value: number | string, options?: Intl.NumberFormatOptions, lang?: string, currency?: string)`
Formats a number using [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) API

- `displayName(code: string, options: Intl.DisplayNamesOptions, locale?: SpeakLocale, lang?: string)`
- `displayName(code: string, options: Intl.DisplayNamesOptions, lang?: string)`
Returns the translation of language, region, script or currency display names using [Intl.DisplayNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) API

## Development Builds
Expand Down
2 changes: 1 addition & 1 deletion docs/extract.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Optionally, you can use a default value for the keys. The syntax is `key@@[defau
```
When you use a default value, it will be used as initial value for the key in every translation.

> Note. A key will not be extracted when a function argument is a variable or a function (dynamic)
> Note. A key will not be extracted when it is an identifier or contains an indentifier (dynamic)
#### Naming conventions
If you use scoped translations, the first property will be used as filename:
Expand Down
4 changes: 2 additions & 2 deletions docs/inline.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Qwik Speak Inline Vite plugin

> Inline Qwik Speak `$translate` function at compile time
> Inline Qwik Speak `$translate`, `$inlineTranslate` and `$plural` functions at compile time
## How it works
In development mode, translation happens _at runtime_: translations are loaded during SSR or on client, and the lookup also happens at runtime.

Using _Qwik Speak Inline_ Vite plugin, translation happens _at compile-time_: translations are loaded and inlined in chunks sent to the browser during the build, and only _runtime assets_ are translated on the client.
Using _Qwik Speak Inline_ Vite plugin, translation happens _at compile-time_: translations are loaded and inlined in chunks sent to the browser during the build, and only `runtimeAssets` are translated on the client:

```mermaid
sequenceDiagram
Expand Down
8 changes: 4 additions & 4 deletions docs/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ We have added the Speak config and the implementation of the `loadTranslation$`
Just wrap Qwik City provider with `QwikSpeakProvider` component in `root.tsx` and pass it the configuration and the translation functions:

_src/root.tsx_
```jsx
```tsx
import { QwikSpeakProvider } from 'qwik-speak';

export default component$(() => {
Expand All @@ -76,7 +76,7 @@ export default component$(() => {
Finally we add an `index.tsx` with some translation:

_src/routes/index.tsx_
```jsx
```tsx
import {
$translate as t,
formatDate as fd,
Expand Down Expand Up @@ -150,7 +150,7 @@ Internally, Qwik Speak will try to take the Qwik `locale`, before falling back t
Now we want to change locale. Let's create a `ChangeLocale` component:

_src/components/change-locale.tsx_
```jsx
```tsx
import { $translate as t, useSpeakConfig, SpeakLocale } from 'qwik-speak';

export const ChangeLocale = component$(() => {
Expand All @@ -176,7 +176,7 @@ export const ChangeLocale = component$(() => {
});
```
and add the component in `header.tsx`:
```jsx
```tsx
export default component$(() => {
return (
<header>
Expand Down
6 changes: 3 additions & 3 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ To unit test a component which uses `qwik-speak`, you need to wrap it with `Qwik
Given the `config` object and a component to test like in [Quick Start](./quick-start.md):

_src/routes/index.tsx_
```jsx
```tsx
import {
$translate as t,
formatDate as fd,
Expand Down Expand Up @@ -41,7 +41,7 @@ export default component$(() => {
We'll have the following unit test (using _Vitest_):

_src/routes/index.spec.tsx_
```jsx
```tsx
import Home from './index';

test(`[Home Component]: Should render the component`, async () => {
Expand Down Expand Up @@ -73,7 +73,7 @@ const translationFnStub: TranslationFn = {
```
and pass it with the language you want to `QwikSpeakProvider`:

```jsx
```tsx
test(`[Home Component]: Should render translated texts in Italian`, async () => {
const { screen, render } = await createDOM();

Expand Down
101 changes: 60 additions & 41 deletions docs/translate.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# Translate

> The `$translate` function uses the Speak context internally and can therefore be considered a hook: it must be used within the Qwik components or else the context must be passed to it
> All translation functions, except `$inlineTranslate`, use the Speak context internally: they must be used within the Qwik components
## $translate
The `$translate` function is responsible for translating, extracting to external files, and inlining during the build, using key-value pairs:
```jsx
```tsx
$translate('home.title@@Qwik Speak')
```
- In dev mode, the function returns the default value (value after `@@`) if provided
Expand All @@ -20,13 +19,13 @@ $translate('home.title@@Qwik Speak')
```
- After extraction, it returns the value in files
- In prod mod, using _Qwik Speak Inline_ Vite plugin, `$translate` function is replaced by its translation in chunks sent to the browser:
```jsx
```tsx
`Qwik Speak`
```

### Params interpolation
`$translate` function accept params as well:
```jsx
```tsx
$translate('home.greeting@@Hi! I am {{name}}', { name: 'Qwik Speak' })
```
`name` param is replaced at runtime or during the inlining:
Expand All @@ -36,11 +35,11 @@ Hi! I am Qwik Speak

### Array of keys
`$translate` function accepts array of keys:
```jsx
```tsx
$translate(['value1@@Value 1', 'value2@@Value 2'])
```
and returns an array of translated values:
```jsx
```tsx
["Value 1", "Value 2"]
```

Expand All @@ -62,27 +61,46 @@ It can get arrays and objects directly from files:
}
```
just pass to the function the type parameter:
```jsx
```tsx
import type { Translation } from 'qwik-speak';

$translate<string[]>('home.array')
$translate<Translation>('home.obj')
```
Finally, it is possible to set arrays and objects passing a _valid stringified_ default value:
```jsx
```tsx
$translate<string[]>('home.array@@["one","two","three"]')
$translate<Translation>('home.obj@@{"one":"1","two":"2"}')
```
You can also access by array position:
```jsx
```tsx
$translate('home.array.2@@three')
```
> To reduce complexity (arrays and objects are _inlined_ during build) it is recommended to use objects with _a depth not greater than 1_. For the same reason, `params` interpolation is not supported when you return an array or an object
## $inlineTranslate
The `$inlineTranslate` function has the same behavior as `$translate`, but can be used outside the `component$`, for example in _Inline components_, passing the Speak context as second argument:
```tsx
import { $inlineTranslate, useSpeakContext } from 'qwik-speak';

export const MyComponent = (props: { ctx: SpeakState }) => {
return <h1>{$inlineTranslate('home.title@@Qwik Speak', props.ctx)}</h1>;
};

export const Home = component$(() => {
const ctx = useSpeakContext();

return (
<>
<MyComponent ctx={ctx} />
</>
);
});
```

## $plural
The `$plural` function uses the [Intl.PluralRules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules) API:
```jsx
```tsx
p(1, 'home.devs')
```
When you run the extraction tool, it creates a translation file with the Intl API plural rules for each language:
Expand Down Expand Up @@ -112,10 +130,30 @@ It is rendered as:
1 software developer
```

## useTranslate$
The `useTranslate$` closure returns the translate function as QRL. This means that it is serializable and it can be passed to other QRL functions characterized by lazy loading:
```tsx
import { useTranslate$ } from 'qwik-speak';

const MyComponent = component$(() => {
const t$ = useTranslate$();

const s = useSignal('');

return (
<button onClick$={async () => s.value = await t$('runtime.test')}></button>
);
});
```
> The translation keys passed into its must be provided in `runtimeAssets` and will not be inlined

# Localize
> All localization functions use the Speak context internally: they must be used within the Qwik components
## formatDate
The `formatDate` function uses the [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) API:
```jsx
```tsx
formatDate(Date.now(), { dateStyle: 'full', timeStyle: 'short' })
```
The second param in the signature is an Intl `DateTimeFormatOptions` object, which allows you to customize the format:
Expand All @@ -126,7 +164,7 @@ Optionally it uses the time zone set in `timeZone` property of the `SpeakLocale`

## relativeTime
The `relativeTime` function uses the [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat) API:
```jsx
```tsx
relativeTime(-1, 'second')
```
The second param in the signature is an Intl `RelativeTimeFormatUnit` string:
Expand All @@ -137,7 +175,7 @@ The second param in the signature is an Intl `RelativeTimeFormatUnit` string:

## formatNumber
The `formatNumber` function uses the [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) API:
```jsx
```tsx
formatNumber(1000000)
```
```text
Expand All @@ -146,7 +184,7 @@ formatNumber(1000000)

### Currency
To format as currency, you have to set the `style` property of the second param, an Intl `NumberFormatOptions` object:
```jsx
```tsx
formatNumber(1000000, { style: 'currency' })
```
```text
Expand All @@ -156,7 +194,7 @@ It uses the currency code set in `currency` property of the `SpeakLocale`.

### Unit
To format as unit, you have to set the `style` and `unit` properties of the second param:
```jsx
```tsx
const locale = useSpeakLocale();
const units = locale.units!;

Expand All @@ -172,7 +210,7 @@ units: { 'length': 'mile' }

## displayName
The `displayName` function uses the [Intl.DisplayNames](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) API:
```jsx
```tsx
displayName('en-US', { type: 'language' })
```
```text
Expand All @@ -182,33 +220,14 @@ American English
> The locale used by `formatDate`, `relativeTime`, `formatNumber` and `displayName` is primarily the `extension` property of the `SpeakLocale` if provided, otherwise the `lang` property. `extension` is the language with Intl extensions, in the format `language[-script][-region][-extensions]` like `en-US-u-ca-gregory-nu-latn`

## Multilingual
Each of the translation functions accepts a different language other than the current one as its last argument:
```jsx
$translate('home.title@@Qwik Speak', undefined, undefined, 'it-IT')
# Multilingual
Each of the translation and localization functions accepts a different language other than the current one as its last argument:
```tsx
$translate('home.title@@Qwik Speak', undefined, 'it-IT')
```
For the translation to occur in the language passed as an argument, you need to pass the additional language to `QwikSpeakProvider` or `Speak` components:
```jsx
```tsx
<Speak assets={['home'] langs=['it-IT']}>
<Home />
</Speak>
```


## Translation outside of Qwik components
The `SpeakContext` is not available outside of `component$`. You have to pass the context directly to the translation functions:
```jsx
export const MyComponent = (props: { ctx: SpeakState }) => {
return <h1>{t('home.title@@Qwik Speak', undefined, props.ctx)}</h1>;
};

export const Home = component$(() => {
const ctx = useSpeakContext();

return (
<>
<MyComponent ctx={ctx} />
</>
);
});
```
Loading

0 comments on commit e602fa5

Please sign in to comment.