Skip to content

Commit

Permalink
refactor: some minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
kaisermann committed Aug 24, 2021
1 parent 8235f1e commit a7ce70f
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 42 deletions.
5 changes: 3 additions & 2 deletions src/cli/extract.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type {
Node,
ObjectExpression,
Expand Down Expand Up @@ -145,7 +146,7 @@ export function collectMessages(markup: string): Message[] {
...definitions.map((definition) => getObjFromExpression(definition)),
...calls.map((call) => {
const [pathNode, options] = call.arguments;
let messageObj: Partial<Message>;
let messageObj: Message;

if (pathNode.type === 'ObjectExpression') {
// _({ ...opts })
Expand All @@ -168,7 +169,7 @@ export function collectMessages(markup: string): Message[] {

return messageObj;
}),
].filter((Boolean as unknown) as (x: Message | null) => x is Message);
].filter(Boolean) as Message[];
}

export function extractMessages(
Expand Down
8 changes: 3 additions & 5 deletions src/cli/includes/getObjFromExpression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import type { ObjectExpression, Property, Identifier } from 'estree';

import type { Message } from '../types';

export function getObjFromExpression(
exprNode: ObjectExpression,
): Partial<Message> {
return exprNode.properties.reduce<Partial<Message>>((acc, prop: Property) => {
export function getObjFromExpression(exprNode: ObjectExpression): Message {
return exprNode.properties.reduce((acc, prop: Property) => {
// we only want primitives
if (
prop.value.type === 'Literal' &&
Expand All @@ -17,5 +15,5 @@ export function getObjFromExpression(
}

return acc;
}, {});
}, {} as Message);
}
2 changes: 1 addition & 1 deletion src/cli/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export interface Message {
id: string;
default: string;
default?: string;
[key: string]: any;
}
9 changes: 2 additions & 7 deletions src/runtime/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,8 @@ export const defaultFormats: Formats = {
},
};

export const defaultOptions: Omit<
ConfigureOptions,
'fallbackLocale' | 'initialLocale'
> &
Record<'fallbackLocale' | 'initialLocale', null> = {
fallbackLocale: null,
initialLocale: null,
export const defaultOptions: ConfigureOptions = {
fallbackLocale: null as any,
loadingDelay: 200,
formats: defaultFormats,
warnOnMissingMessages: true,
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/includes/formatters.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { Formats } from 'intl-messageformat';
import IntlMessageFormat from 'intl-messageformat';

import type {
Expand Down Expand Up @@ -35,8 +34,8 @@ const getIntlFormatterOptions = (
): any => {
const { formats } = getOptions();

if (type in formats && name in (formats as Formats)[type]) {
return (formats as Formats)[type][name];
if (type in formats && name in formats[type]) {
return formats[type][name];
}

throw new Error(`[svelte-i18n] Unknown "${name}" ${type} format.`);
Expand Down Expand Up @@ -106,6 +105,7 @@ export const getTimeFormatter: MemoizedDateTimeFormatterFactoryOptional = ({
} = {}) => createTimeFormatter({ locale, ...args });

export const getMessageFormatter = monadicMemoize(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
(message: string, locale: string = getCurrentLocale()!) =>
new IntlMessageFormat(message, locale, getOptions().formats, {
ignoreTag: getOptions().ignoreTag,
Expand Down
4 changes: 3 additions & 1 deletion src/runtime/includes/loaderQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ function getLocalesQueues(locale: string) {
.filter(([, localeQueue]) => localeQueue.length > 0);
}

export function hasLocaleQueue(locale: string) {
export function hasLocaleQueue(locale?: string | null) {
if (locale == null) return false;

return getPossibleLocales(locale).some(
(localeQueue) => getLocaleQueue(localeQueue)?.size,
);
Expand Down
1 change: 0 additions & 1 deletion src/runtime/stores/dictionary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type { LocaleDictionary, LocalesDictionary } from '../types/index';
import { getPossibleLocales } from './locale';
import { delve } from '../../shared/delve';
import { lookupCache } from '../includes/lookup';
import { locales } from '..';

let dictionary: LocalesDictionary;
const $dictionary = writable<LocalesDictionary>({});
Expand Down
17 changes: 11 additions & 6 deletions src/runtime/stores/formatters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,18 @@ import { $dictionary } from './dictionary';
import { getCurrentLocale, getPossibleLocales, $locale } from './locale';

const formatMessage: MessageFormatter = (id, options = {}) => {
let messageObj = options as MessageObject;

if (typeof id === 'object') {
options = id as MessageObject;
id = options.id!;
messageObj = id as MessageObject;
id = messageObj.id;
}

const {
values,
locale = getCurrentLocale(),
default: defaultValue,
} = options;
} = messageObj;

if (locale == null) {
throw new Error(
Expand All @@ -47,7 +49,7 @@ const formatMessage: MessageFormatter = (id, options = {}) => {
`[svelte-i18n] The message "${id}" was not found in "${getPossibleLocales(
locale,
).join('", "')}".${
hasLocaleQueue(getCurrentLocale()!)
hasLocaleQueue(getCurrentLocale())
? `\n\nNote: there are at least one loader still registered to this locale that wasn't executed.`
: ''
}`,
Expand Down Expand Up @@ -90,8 +92,11 @@ const formatNumber: NumberFormatter = (n, options) => {
return getNumberFormatter(options).format(n);
};

const getJSON: JSONGetter = (id: string, locale = getCurrentLocale()): any => {
return lookup(id, locale);
const getJSON: JSONGetter = <T = any>(
id: string,
locale = getCurrentLocale(),
) => {
return lookup(id, locale) as T;
};

export const $format = derived([$locale, $dictionary], () => formatMessage);
Expand Down
11 changes: 5 additions & 6 deletions src/runtime/stores/locale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ export function getPossibleLocales(
}

export function getCurrentLocale() {
return current;
return current ?? undefined;
}

internalLocale.subscribe((newLocale: string | null | undefined) => {
current = newLocale;
current = newLocale ?? undefined;

if (typeof window !== 'undefined' && newLocale != null) {
document.documentElement.setAttribute('lang', newLocale);
Expand All @@ -42,9 +42,8 @@ internalLocale.subscribe((newLocale: string | null | undefined) => {

const set = (newLocale: string | null | undefined): void | Promise<void> => {
if (
((getClosestAvailableLocale as unknown) as (
refLocale: string | null | undefined,
) => refLocale is string)(newLocale) &&
newLocale &&
getClosestAvailableLocale(newLocale) &&
hasLocaleQueue(newLocale)
) {
const { loadingDelay } = getOptions();
Expand All @@ -66,7 +65,7 @@ const set = (newLocale: string | null | undefined): void | Promise<void> => {
$isLoading.set(true);
}

return flush(newLocale)
return flush(newLocale as string)
.then(() => {
internalLocale.set(newLocale);
})
Expand Down
14 changes: 7 additions & 7 deletions src/runtime/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ export type InterpolationValues =
| undefined;

export interface MessageObject {
id?: string;
locale?: string | null;
id: string;
locale?: string;
format?: string;
default?: string;
values?: InterpolationValues;
}

export type MessageFormatter = (
id: string | MessageObject,
options?: MessageObject,
options?: Omit<MessageObject, 'id'>,
) => string;

export type TimeFormatter = (
Expand All @@ -53,11 +53,11 @@ export type NumberFormatter = (
options?: IntlFormatterOptions<Intl.NumberFormatOptions>,
) => string;

export type JSONGetter = (id: string, locale?: string | null) => any;
export type JSONGetter = <T>(id: string, locale?: string | null) => T;

type IntlFormatterOptions<T> = T & {
format?: string;
locale?: string | null;
locale?: string;
};

export interface MemoizedIntlFormatter<T, U> {
Expand All @@ -74,8 +74,8 @@ export interface MessagesLoader {

export interface ConfigureOptions {
fallbackLocale: string;
formats: Partial<Formats>;
initialLocale: string;
initialLocale?: string | null;
formats: Formats;
loadingDelay: number;
warnOnMissingMessages: boolean;
ignoreTag: boolean;
Expand Down
7 changes: 5 additions & 2 deletions test/runtime/includes/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ import {

describe('getting client locale', () => {
beforeEach(() => {
delete (window as any).location;
// @ts-expect-error - TS doesn't know this is a fake window object
delete window.location;

// @ts-expect-error - TS doesn't know this is a fake window object
window.location = {
pathname: '/',
hostname: 'example.com',
hash: '',
search: '',
} as any;
};
});

it('gets the locale based on the passed hash parameter', () => {
Expand Down
1 change: 0 additions & 1 deletion test/runtime/stores/locale.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ test('if no initial locale is set, set the locale to the fallback', () => {
test('if no initial locale was found, set to the fallback locale', () => {
init({
fallbackLocale: 'en',
initialLocale: null as any,
});
expect(get($locale)).toBe('en');
expect(getOptions().fallbackLocale).toBe('en');
Expand Down

0 comments on commit a7ce70f

Please sign in to comment.