Skip to content

Commit

Permalink
Fix: params type & parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
robisim74 committed May 11, 2023
1 parent 8d1a626 commit 4a4507e
Show file tree
Hide file tree
Showing 9 changed files with 150 additions and 60 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,16 @@ and optionally contains:

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

- `$inlineTranslate(keys: string | string[], ctx: SpeakState, params?: any, lang?: string)`
- `$inlineTranslate(keys: string | string[], ctx: SpeakState, params?: Record<string, 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
Returns the translate function as QRL

- `$plural(value: number | string, key?: string, params?: any, options?: Intl.PluralRulesOptions, lang?: string)`
- `$plural(value: number | string, key?: string, params?: Record<string, 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

#### Localize
Expand Down
4 changes: 2 additions & 2 deletions packages/qwik-speak/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const loadTranslations = async (
export const translate = (
key: string | string[],
data: Translation,
params?: any,
params?: Record<string, any>,
keySeparator = '.',
keyValueSeparator = '@@',
): any => {
Expand Down Expand Up @@ -126,7 +126,7 @@ export const separateKeyValue = (key: string, keyValueSeparator: string): [strin
/**
* Replace params in the value
*/
export const transpileParams = (value: string, params: any): string => {
export const transpileParams = (value: string, params: Record<string, any>): string => {
const replacedValue = value.replace(/{{\s?([^{}\s]*)\s?}}/g, (substring: string, parsedKey: string) => {
const replacer = params[parsedKey];
return replacer !== undefined ? replacer : substring;
Expand Down
10 changes: 5 additions & 5 deletions packages/qwik-speak/src/inline-translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ export type InlineTranslateFn = {
* @param lang Optional language if different from the current one
* @returns The translation or the key if not found
*/
(key: string, ctx: SpeakState, params?: any, lang?: string): string;
<T>(key: string, ctx: SpeakState, params?: any, lang?: string): T;
(key: string, ctx: SpeakState, params?: Record<string, any>, lang?: string): string;
<T>(key: string, ctx: SpeakState, params?: Record<string, any>, lang?: string): T;
/**
* Translate an array of keys outside the component$.
* The syntax of the strings is 'key@@[default value]'
Expand All @@ -22,14 +22,14 @@ export type InlineTranslateFn = {
* @param lang Optional language if different from the current one
* @returns The translations or the keys if not found
*/
(keys: string[], ctx: SpeakState, params?: any, lang?: string): string[];
<T>(keys: string[], ctx: SpeakState, params?: any, lang?: string): T[];
(keys: string[], ctx: SpeakState, params?: Record<string, any>, lang?: string): string[];
<T>(keys: string[], ctx: SpeakState, params?: Record<string, any>, lang?: string): T[];
};

export const $inlineTranslate: InlineTranslateFn = (
keys: string | string[],
ctx: SpeakState,
params?: any,
params?: Record<string, any>,
lang?: string
) => {
const { locale, translation, config } = ctx;
Expand Down
2 changes: 1 addition & 1 deletion packages/qwik-speak/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export interface SpeakLocale {
/**
* Key value pairs of unit identifiers
*/
units?: { [key: string]: string };
units?: Record<string, string>;
}

/**
Expand Down
8 changes: 6 additions & 2 deletions packages/qwik-speak/src/use-plural.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ export type PluralFn = {
* @param lang Optional language if different from the current one
* @returns The translation for the plural
*/
(value: number | string, key?: string, params?: any, options?: Intl.PluralRulesOptions, lang?: string): string;
(value: number | string,
key?: string,
params?: Record<string, any>,
options?: Intl.PluralRulesOptions,
lang?: string): string;
};

export const usePlural: PluralFn = (
value: number | string,
key?: string,
params?: any,
params?: Record<string, any>,
options?: Intl.PluralRulesOptions,
lang?: string
) => {
Expand Down
20 changes: 10 additions & 10 deletions packages/qwik-speak/src/use-translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export type TranslateFn = {
* @param lang Optional language if different from the current one
* @returns The translation or the key if not found
*/
(key: string, params?: any, lang?: string): string;
<T>(key: string, params?: any, lang?: string): T;
(key: string, params?: Record<string, any>, lang?: string): string;
<T>(key: string, params?: Record<string, any>, lang?: string): T;
/**
* Translate an array of keys.
* The syntax of the strings is 'key@@[default value]'
Expand All @@ -23,11 +23,11 @@ export type TranslateFn = {
* @param lang Optional language if different from the current one
* @returns The translations or the keys if not found
*/
(keys: string[], params?: any, lang?: string): string[];
<T>(keys: string[], params?: any, lang?: string): T[];
(keys: string[], params?: Record<string, any>, lang?: string): string[];
<T>(keys: string[], params?: Record<string, any>, lang?: string): T[];
};

export const useTranslate: TranslateFn = (keys: string | string[], params?: any, lang?: string) => {
export const useTranslate: TranslateFn = (keys: string | string[], params?: Record<string, any>, lang?: string) => {
const ctx = useSpeakContext();
const { locale, translation, config } = ctx;

Expand All @@ -45,8 +45,8 @@ export interface TranslateQrl extends QRL<() => any> {
* @param lang Optional language if different from the current one
* @returns The translation or the key if not found
*/
(key: string, params?: any, lang?: string): Promise<string>;
<T>(key: string, params?: any, lang?: string): Promise<T>;
(key: string, params?: Record<string, any>, lang?: string): Promise<string>;
<T>(key: string, params?: Record<string, any>, lang?: string): Promise<T>;
/**
* Translate an array of keys.
* The syntax of the strings is 'key@@[default value]'
Expand All @@ -55,15 +55,15 @@ export interface TranslateQrl extends QRL<() => any> {
* @param lang Optional language if different from the current one
* @returns The translations or the keys if not found
*/
(keys: string[], params?: any, lang?: string): Promise<string[]>;
<T>(keys: string[], params?: any, lang?: string): Promise<T[]>;
(keys: string[], params?: Record<string, any>, lang?: string): Promise<string[]>;
<T>(keys: string[], params?: Record<string, any>, lang?: string): Promise<T[]>;
}

export const useTranslateQrl = (): TranslateQrl => {
const ctx = useSpeakContext();
const { locale, translation, config } = ctx;

const translate$ = $((keys: string | string[], params?: any, lang?: string) => {
const translate$ = $((keys: string | string[], params?: Record<string, any>, lang?: string) => {
lang ??= locale.lang;

return translate(keys, translation[lang], params, config.keySeparator, config.keyValueSeparator);
Expand Down
57 changes: 44 additions & 13 deletions packages/qwik-speak/tools/core/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ export function tokenize(code: string, start = 0): Token[] {

const next = () => code[++index];

const lookAhead = () => code[index + 1];
const lookBehind = () => code[index - 1];

const getRawValue = () => code.substring(start, index + 1);

const startLiteral = (ch: string) => /["'`0-9+-]/.test(ch);
Expand All @@ -100,6 +103,8 @@ export function tokenize(code: string, start = 0): Token[] {

const startPunctuator = (ch: string) => /[(){},:;.[\]?!]/.test(ch);

const startComment = (ch: string) => /\//.test(ch) && /\*/.test(lookAhead());

const scanLiteral = (ch: string, token?: Token): Token[] => {
if (!token) {
token = createToken('Literal');
Expand Down Expand Up @@ -164,6 +169,14 @@ export function tokenize(code: string, start = 0): Token[] {
return scan(next());
};

const scanComment = (ch: string): Token[] => {
if (/\//.test(ch) && /\*/.test(lookBehind())) {
return scan(ch);
}

return scanComment(next());
};

const endOfScan = () => (tokens[tokens.length - 1]?.type === 'Punctuator' && parenthesisStack.length === 0) ||
index === code.length;

Expand All @@ -179,6 +192,8 @@ export function tokenize(code: string, start = 0): Token[] {

if (startPunctuator(ch)) return scanPunctuator(ch);

if (startComment(ch)) return scanComment(ch);

return scan(next());
};

Expand Down Expand Up @@ -231,11 +246,17 @@ export function parse(tokens: Token[], code: string, alias: string): CallExpress
if (!property) {
property = {
type: 'Property',
key: { type: 'Identifier', value: token.value }, value: { type: 'Literal', value: '' }
key: { type: 'Identifier', value: token.value },
value: { type: 'Literal', value: '' }
};
properties.push(property);
}

if (!/\)/.test(token.value) && property.value.type == 'CallExpression') {
property.value.value += token.value;
return parseProperty(next(), properties, property);
}

if (!/:/.test(token.value) && !/:/.test(lookAhead().value)) {
if (token.type === 'Literal') {
property.value.value = trimQuotes(token.value);
Expand Down Expand Up @@ -296,21 +317,31 @@ export function parse(tokens: Token[], code: string, alias: string): CallExpress
return parseArgs(next());
};

const parseCallExpr = (token = tokens[c]): CallExpression => {
if (new RegExp(alias).test(token.value)) {
node = {
type: 'CallExpression',
value: code.substring(token.position.start, last().position.end + 1),
arguments: []
};
return parseArgs(next());
} else {
node.arguments.push({ type: 'CallExpression', value: token.value });
return parseArgs(next());
const parseCallExpr = (token: Token, arg?: Argument): CallExpression => {
if (!arg) {
if (new RegExp(alias).test(token.value)) {
node = {
type: 'CallExpression',
value: code.substring(token.position.start, last().position.end + 1),
arguments: []
};
return parseArgs(next());
} else {
arg = { type: 'CallExpression', value: token.value };
node.arguments.push(arg);
return parseCallExpr(next(), arg)
}
}

arg.value += token.value;

// End of call
if (/\)/.test(token.value)) return parseArgs(next());

return parseCallExpr(next(), arg)
}

return parseCallExpr();
return parseCallExpr(tokens[c]);
}

/**
Expand Down
27 changes: 7 additions & 20 deletions packages/qwik-speak/tools/inline/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,6 @@ export function qwikSpeakInline(options: QwikSpeakInlineOptions): Plugin {
if (target === 'client') {
// Filter id
if (/\/src\//.test(id) && /\.(js|cjs|mjs|jsx|ts|tsx)$/.test(id)) {
// TEST
/* if (code.includes('$translate')) {
console.log(code);
} */
// Filter code: $plural
if (/\$plural/.test(code)) {
code = transformPlural(code);
Expand All @@ -118,10 +114,6 @@ export function qwikSpeakInline(options: QwikSpeakInlineOptions): Plugin {
if (/\$inlineTranslate/.test(code)) {
code = transformInline(code);
}
// TEST
/* if (code.includes('$translate')) {
console.log(code);
} */
return code;
}
}
Expand Down Expand Up @@ -176,20 +168,15 @@ export async function writeChunks(
if (chunk.type === 'chunk' && 'code' in chunk && /build\//.test(chunk.fileName)) {
const filename = normalize(`${targetDir}/${chunk.fileName.split('/')[1]}`);

// TEST
/* if (chunk.code.includes(inlinePlaceholder)) {
console.log(filename);
console.log(chunk.code);
} */
// Inline
let code = inlinePlural(chunk.code, inlinePluralPlaceholder, inlinePlaceholder, lang, opts);
code = inline(code, translation, inlinePlaceholder, lang, opts);
let code = chunk.code;
if (code.includes(inlinePluralPlaceholder)) {
code = inlinePlural(chunk.code, inlinePluralPlaceholder, inlinePlaceholder, lang, opts);
}
if (code.includes(inlinePlaceholder)) {
code = inline(code, translation, inlinePlaceholder, lang, opts);
}
tasks.push(writeFile(filename, code));
// TEST
/* if (chunk.code.includes(inlinePlaceholder)) {
console.log(filename);
console.log(code);
} */

// Original chunks to default lang
if (lang === opts.defaultLang) {
Expand Down
Loading

0 comments on commit 4a4507e

Please sign in to comment.