@scalar/localization 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present Scalar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,60 @@
1
+ import type { PartialDeep } from 'type-fest';
2
+ import { type ComputedRef, type MaybeRefOrGetter } from 'vue';
3
+ /** A locale identifier, for example `en` or `zh-CN`. */
4
+ export type Locale = string;
5
+ /** Text direction used when rendering localized content. */
6
+ export type TextDirection = 'ltr' | 'rtl';
7
+ /** Text direction preference. `auto` derives the direction from the locale. */
8
+ export type TextDirectionPreference = TextDirection | 'auto';
9
+ /** Values interpolated into a translation template through `{name}` placeholders. */
10
+ export type TranslateParams = Record<string, number | string>;
11
+ /** Translates a dot-path key into a localized string. */
12
+ export type TranslateFn<Key extends string> = (key: Key, params?: TranslateParams) => string;
13
+ /** Reactive localization context shared through Vue's provide/inject. */
14
+ export type LocalizationContext<Translations, Key extends string> = {
15
+ locale: ComputedRef<Locale>;
16
+ direction: ComputedRef<TextDirection>;
17
+ translations: ComputedRef<Translations>;
18
+ translate: TranslateFn<Key>;
19
+ };
20
+ /** Fully resolved localization state for a single locale. */
21
+ export type ResolvedLocalization<Translations> = {
22
+ locale: Locale;
23
+ direction: TextDirection;
24
+ translations: Translations;
25
+ };
26
+ /** Localization input accepted by a localization instance. */
27
+ export type LocalizationInput<Translations> = {
28
+ /** Locale used to select built-in translations. */
29
+ locale?: Locale;
30
+ /** Text direction. `auto` derives the direction from the locale. */
31
+ direction?: TextDirectionPreference;
32
+ /** Custom translations merged on top of the built-in locale and the default fallback. */
33
+ translations?: PartialDeep<Translations>;
34
+ };
35
+ /** Content and defaults a localization instance is built from. */
36
+ export type LocalizationConfig<Translations extends Record<string, unknown>> = {
37
+ /** Built-in translations keyed by locale identifier. Must include {@link LocalizationConfig.defaultLocale}. */
38
+ localeTranslations: Record<string, Translations>;
39
+ /** Locale used as the base fallback when a key or locale is missing. */
40
+ defaultLocale: string;
41
+ /** Languages (primary subtag, for example `ar`) that render right-to-left. */
42
+ rtlLocales: Set<string>;
43
+ /** Prefix used for the missing-translation development warning. */
44
+ logPrefix?: string;
45
+ };
46
+ /**
47
+ * Creates a localization instance bound to a specific set of translations.
48
+ *
49
+ * The returned `provideLocalization`/`useLocalization` pair shares a single module-level injection
50
+ * key, so a component provided with one instance can be consumed from another package's instance.
51
+ * This is what lets translations flow across package boundaries.
52
+ *
53
+ * @param config - Built-in translations plus locale/direction defaults.
54
+ */
55
+ export declare const createLocalization: <Translations extends Record<string, unknown>, Key extends string>(config: LocalizationConfig<Translations>) => {
56
+ resolveLocalization: (localization?: LocalizationInput<Translations>) => ResolvedLocalization<Translations>;
57
+ provideLocalization: (localization: MaybeRefOrGetter<LocalizationInput<Translations> | undefined>) => LocalizationContext<Translations, Key>;
58
+ useLocalization: () => LocalizationContext<Translations, Key>;
59
+ };
60
+ //# sourceMappingURL=create-localization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-localization.d.ts","sourceRoot":"","sources":["../src/create-localization.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAC5C,OAAO,EAAE,KAAK,WAAW,EAAqB,KAAK,gBAAgB,EAAsC,MAAM,KAAK,CAAA;AAEpH,wDAAwD;AACxD,MAAM,MAAM,MAAM,GAAG,MAAM,CAAA;AAE3B,4DAA4D;AAC5D,MAAM,MAAM,aAAa,GAAG,KAAK,GAAG,KAAK,CAAA;AAEzC,+EAA+E;AAC/E,MAAM,MAAM,uBAAuB,GAAG,aAAa,GAAG,MAAM,CAAA;AAE5D,qFAAqF;AACrF,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAA;AAE7D,yDAAyD;AACzD,MAAM,MAAM,WAAW,CAAC,GAAG,SAAS,MAAM,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,eAAe,KAAK,MAAM,CAAA;AAE5F,yEAAyE;AACzE,MAAM,MAAM,mBAAmB,CAAC,YAAY,EAAE,GAAG,SAAS,MAAM,IAAI;IAClE,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;IAC3B,SAAS,EAAE,WAAW,CAAC,aAAa,CAAC,CAAA;IACrC,YAAY,EAAE,WAAW,CAAC,YAAY,CAAC,CAAA;IACvC,SAAS,EAAE,WAAW,CAAC,GAAG,CAAC,CAAA;CAC5B,CAAA;AAED,6DAA6D;AAC7D,MAAM,MAAM,oBAAoB,CAAC,YAAY,IAAI;IAC/C,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,aAAa,CAAA;IACxB,YAAY,EAAE,YAAY,CAAA;CAC3B,CAAA;AAED,8DAA8D;AAC9D,MAAM,MAAM,iBAAiB,CAAC,YAAY,IAAI;IAC5C,mDAAmD;IACnD,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,oEAAoE;IACpE,SAAS,CAAC,EAAE,uBAAuB,CAAA;IACnC,yFAAyF;IACzF,YAAY,CAAC,EAAE,WAAW,CAAC,YAAY,CAAC,CAAA;CACzC,CAAA;AAED,kEAAkE;AAClE,MAAM,MAAM,kBAAkB,CAAC,YAAY,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;IAC7E,+GAA+G;IAC/G,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAA;IAChD,wEAAwE;IACxE,aAAa,EAAE,MAAM,CAAA;IACrB,8EAA8E;IAC9E,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IACvB,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAA;AAYD;;;;;;;;GAQG;AACH,eAAO,MAAM,kBAAkB,GAAI,YAAY,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,SAAS,MAAM,EACjG,QAAQ,kBAAkB,CAAC,YAAY,CAAC;yCAoCI,iBAAiB,CAAC,YAAY,CAAC,KAAG,oBAAoB,CAAC,YAAY,CAAC;wCAoDrE,gBAAgB,CAAC,iBAAiB,CAAC,YAAY,CAAC,GAAG,SAAS,CAAC;2BAY5E,mBAAmB,CAAC,YAAY,EAAE,GAAG,CAAC;CAQnE,CAAA"}
@@ -0,0 +1,97 @@
1
+ import { getValueAtPath } from '@scalar/helpers/object/get-value-at-path';
2
+ import { mergeObjects } from '@scalar/helpers/object/merge-objects';
3
+ import { computed, inject, provide, toValue } from 'vue';
4
+ /**
5
+ * Shared injection key for the localization context.
6
+ *
7
+ * This lives at module scope so that every package consuming `@scalar/localization` injects the
8
+ * exact same symbol a provider used. Instances created through {@link createLocalization} may be
9
+ * typed differently, so the key is intentionally untyped here and narrowed inside each instance.
10
+ * This shared identity is what lets a component provided in one package be consumed from another.
11
+ */
12
+ const LOCALIZATION_SYMBOL = Symbol('scalar-localization');
13
+ /**
14
+ * Creates a localization instance bound to a specific set of translations.
15
+ *
16
+ * The returned `provideLocalization`/`useLocalization` pair shares a single module-level injection
17
+ * key, so a component provided with one instance can be consumed from another package's instance.
18
+ * This is what lets translations flow across package boundaries.
19
+ *
20
+ * @param config - Built-in translations plus locale/direction defaults.
21
+ */
22
+ export const createLocalization = (config) => {
23
+ const { localeTranslations, defaultLocale, rtlLocales, logPrefix = '[@scalar/localization]' } = config;
24
+ const resolveBuiltInLocale = (locale) => {
25
+ if (!locale) {
26
+ return defaultLocale;
27
+ }
28
+ if (locale in localeTranslations) {
29
+ return locale;
30
+ }
31
+ const normalized = locale.replace('_', '-').toLowerCase();
32
+ if (normalized.startsWith('zh') && 'zh-CN' in localeTranslations) {
33
+ return 'zh-CN';
34
+ }
35
+ const language = normalized.split('-')[0];
36
+ const match = Object.keys(localeTranslations).find((key) => key.toLowerCase() === language);
37
+ return match ?? defaultLocale;
38
+ };
39
+ const resolveDirection = (localization) => {
40
+ if (localization?.direction && localization.direction !== 'auto') {
41
+ return localization.direction;
42
+ }
43
+ const locale = localization?.locale ?? defaultLocale;
44
+ const language = locale.replace('_', '-').split('-')[0]?.toLowerCase();
45
+ return language && rtlLocales.has(language) ? 'rtl' : 'ltr';
46
+ };
47
+ const resolveLocalization = (localization) => {
48
+ const locale = localization?.locale ?? defaultLocale;
49
+ const builtInLocale = resolveBuiltInLocale(locale);
50
+ // The default locale is the base every other layer merges onto, so a missing key always
51
+ // falls back to it rather than to the raw key.
52
+ const base = localeTranslations[defaultLocale] ?? {};
53
+ const translations = mergeObjects(mergeObjects(base, localeTranslations[builtInLocale]), localization?.translations);
54
+ return {
55
+ locale,
56
+ direction: resolveDirection(localization),
57
+ translations,
58
+ };
59
+ };
60
+ const translate = (translations, key, params) => {
61
+ const value = getValueAtPath(translations, key.split('.'));
62
+ // Accessed defensively so the engine is safe outside a Vite/Vitest context, where
63
+ // `import.meta.env` is not defined.
64
+ const isDev = import.meta.env?.DEV;
65
+ if (typeof value !== 'string' && isDev) {
66
+ console.warn(`${logPrefix} Missing translation for key "${key}". Falling back to the key itself.`);
67
+ }
68
+ const template = typeof value === 'string' ? value : key;
69
+ if (!params) {
70
+ return template;
71
+ }
72
+ return Object.entries(params).reduce((result, [param, paramValue]) => result.replaceAll(`{${param}}`, String(paramValue)), template);
73
+ };
74
+ const createContext = (localization) => {
75
+ const resolved = computed(() => resolveLocalization(toValue(localization)));
76
+ return {
77
+ locale: computed(() => resolved.value.locale),
78
+ direction: computed(() => resolved.value.direction),
79
+ translations: computed(() => resolved.value.translations),
80
+ translate: (key, params) => translate(resolved.value.translations, key, params),
81
+ };
82
+ };
83
+ const provideLocalization = (localization) => {
84
+ const context = createContext(localization);
85
+ provide(LOCALIZATION_SYMBOL, context);
86
+ return context;
87
+ };
88
+ // Built once per instance and reused as the no-provider fallback, so `useLocalization` does not
89
+ // construct a fresh context (and its computed chain) on every call.
90
+ const fallbackContext = createContext(undefined);
91
+ const useLocalization = () => inject(LOCALIZATION_SYMBOL, fallbackContext);
92
+ return {
93
+ resolveLocalization,
94
+ provideLocalization,
95
+ useLocalization,
96
+ };
97
+ };
@@ -0,0 +1,3 @@
1
+ export type { Locale, LocalizationConfig, LocalizationContext, LocalizationInput, ResolvedLocalization, TextDirection, TextDirectionPreference, TranslateFn, TranslateParams, } from './create-localization.js';
2
+ export { createLocalization } from './create-localization.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,MAAM,EACN,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,oBAAoB,EACpB,aAAa,EACb,uBAAuB,EACvB,WAAW,EACX,eAAe,GAChB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createLocalization } from './create-localization.js';
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@scalar/localization",
3
+ "description": "Framework-agnostic localization engine for Scalar packages",
4
+ "license": "MIT",
5
+ "author": "Scalar (https://github.com/scalar)",
6
+ "homepage": "https://github.com/scalar/scalar",
7
+ "bugs": "https://github.com/scalar/scalar/issues/new/choose",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/scalar/scalar.git",
11
+ "directory": "packages/localization"
12
+ },
13
+ "keywords": [
14
+ "scalar",
15
+ "localization",
16
+ "i18n",
17
+ "translations"
18
+ ],
19
+ "version": "0.1.0",
20
+ "engines": {
21
+ "node": ">=22"
22
+ },
23
+ "type": "module",
24
+ "main": "dist/index.js",
25
+ "module": "dist/index.js",
26
+ "types": "dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "import": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "CHANGELOG.md"
37
+ ],
38
+ "sideEffects": false,
39
+ "dependencies": {
40
+ "type-fest": "^5.8.0",
41
+ "vue": "^3.5.40",
42
+ "@scalar/helpers": "0.11.3"
43
+ },
44
+ "devDependencies": {
45
+ "@vue/test-utils": "2.4.11",
46
+ "jsdom": "27.4.0",
47
+ "vitest": "4.1.10"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
51
+ "test": "vitest --run",
52
+ "test:watch": "vitest",
53
+ "types:check": "tsc --noEmit"
54
+ }
55
+ }