mazey 5.3.1 → 5.4.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/lib/index.d.ts CHANGED
@@ -127,6 +127,18 @@ interface BrowserInfo {
127
127
  colorScheme: string;
128
128
  }
129
129
 
130
+ /**
131
+ * A resolved preference value and its human-readable label.
132
+ *
133
+ * @category Browser Information
134
+ */
135
+ interface PreferenceResult<T extends string = string> {
136
+ /** Machine-readable value used by application logic. */
137
+ value: T;
138
+ /** Human-readable label suitable for display. */
139
+ label: string;
140
+ }
141
+
130
142
  interface DefineListeners {
131
143
  [key: string]: any;
132
144
  }
@@ -3396,151 +3408,183 @@ type ThemePreference = "system" | "light" | "dark";
3396
3408
  */
3397
3409
  type ResolvedTheme = "light" | "dark";
3398
3410
  /**
3399
- * Human-readable names for supported theme preferences.
3411
+ * Resolve the current website theme.
3400
3412
  *
3401
- * @category Browser Information
3402
- */
3403
- type ThemePreferenceDisplayName = "System" | "Light" | "Dark";
3404
- /**
3405
- * The highest-priority source that selected a theme preference.
3413
+ * Resolution checks the fixed `theme` URL query, the supplied local-storage
3414
+ * key, the current `prefers-color-scheme` media query, and finally the fixed
3415
+ * `light` fallback. Query values accept only `light` and `dark`. Storage also
3416
+ * accepts `system`, which resolves to a concrete value while retaining the
3417
+ * `System` label.
3406
3418
  *
3407
- * @category Browser Information
3408
- */
3409
- type ThemePreferenceSource = "query" | "storage" | "system" | "fallback";
3410
- /**
3411
- * Options for {@link resolveThemePreference}.
3419
+ * Resolution matrix:
3412
3420
  *
3413
- * @category Browser Information
3414
- */
3415
- interface ResolveThemePreferenceOptions {
3416
- /** Project-specific local-storage key, such as `MAZEY_THEME`. */
3417
- storageKey: string;
3418
- /** URL query parameter name. Defaults to `theme`. */
3419
- queryParam?: string;
3420
- /** URL inspected for a query override. Defaults to `window.location.href` when available. */
3421
- url?: string | URL;
3422
- /** Storage used to read a persisted preference. Defaults to `window.localStorage` when available. */
3423
- storage?: Pick<Storage, "getItem"> | null;
3424
- /** Media-query implementation. Defaults to `window.matchMedia` when available. */
3425
- matchMedia?: (query: string) => Pick<MediaQueryList, "matches">;
3426
- /** Theme used when the system preference is unavailable. Defaults to `light`. */
3427
- fallback?: ResolvedTheme;
3428
- }
3429
- /**
3430
- * Options for {@link setThemePreference}.
3421
+ * | Query | Storage | System dark | Result |
3422
+ * | ------- | -------- | ----------: | ------------------------------------- |
3423
+ * | `dark` | `light` | false | `{ value: "dark", label: "Dark" }` |
3424
+ * | `light` | `dark` | true | `{ value: "light", label: "Light" }` |
3425
+ * | invalid | `dark` | false | `{ value: "dark", label: "Dark" }` |
3426
+ * | missing | `light` | true | `{ value: "light", label: "Light" }` |
3427
+ * | missing | `system` | true | `{ value: "dark", label: "System" }` |
3428
+ * | missing | `system` | false | `{ value: "light", label: "System" }` |
3429
+ * | missing | invalid | true | `{ value: "dark", label: "System" }` |
3430
+ * | missing | missing | false | `{ value: "light", label: "System" }` |
3431
+ * | missing | missing | unavailable | `{ value: "light", label: "Light" }` |
3432
+ *
3433
+ * Usage:
3431
3434
  *
3435
+ * ```ts
3436
+ * import {
3437
+ * resolveThemePreference,
3438
+ * setThemePreference,
3439
+ * } from "mazey";
3440
+ *
3441
+ * const theme = resolveThemePreference(
3442
+ * "MY_WEBSITE_THEME"
3443
+ * );
3444
+ *
3445
+ * console.log(theme);
3446
+ *
3447
+ * setThemePreference(
3448
+ * "MY_WEBSITE_THEME",
3449
+ * "system"
3450
+ * );
3451
+ * ```
3452
+ *
3453
+ * Possible output:
3454
+ *
3455
+ * ```text
3456
+ * {
3457
+ * value: "dark",
3458
+ * label: "System"
3459
+ * }
3460
+ * ```
3461
+ *
3462
+ * @param storageKey Project-specific local-storage key.
3463
+ * @returns The concrete `light` or `dark` value and the label of the preference that selected it.
3464
+ * @throws {TypeError} If `storageKey` is not a non-empty string.
3465
+ * @remarks Safe during SSR and resilient to unavailable or throwing browser APIs. This function reads preferences only and never writes storage, mutates the DOM, or adds listeners.
3432
3466
  * @category Browser Information
3433
3467
  */
3434
- interface SetThemePreferenceOptions {
3435
- /** Project-specific local-storage key, such as `MAZEY_THEME`. */
3436
- storageKey: string;
3437
- /** Supported preference to persist. */
3438
- preference: ThemePreference;
3439
- /** Storage used to persist the preference. Defaults to `window.localStorage` when available. */
3440
- storage?: Pick<Storage, "setItem"> | null;
3441
- }
3468
+ declare function resolveThemePreference(storageKey: string): PreferenceResult<ResolvedTheme>;
3442
3469
  /**
3443
- * Result returned by {@link resolveThemePreference}.
3470
+ * Persist a website theme preference.
3471
+ *
3472
+ * The exact lowercase value `system`, `light`, or `dark` is written under the
3473
+ * project-specific key. The function does not resolve or apply the theme.
3474
+ *
3475
+ * Usage:
3476
+ *
3477
+ * ```ts
3478
+ * import { setThemePreference } from "mazey";
3479
+ *
3480
+ * const stored = setThemePreference(
3481
+ * "MY_WEBSITE_THEME",
3482
+ * "dark"
3483
+ * );
3484
+ *
3485
+ * console.log(stored);
3486
+ * ```
3487
+ *
3488
+ * Output when browser storage is available:
3489
+ *
3490
+ * ```text
3491
+ * true
3492
+ * ```
3444
3493
  *
3494
+ * @param storageKey Project-specific local-storage key.
3495
+ * @param value Theme preference to persist.
3496
+ * @returns `true` when storage succeeds, or `false` when storage is unavailable or rejects the write.
3497
+ * @throws {TypeError} If `storageKey` is empty or `value` is not `system`, `light`, or `dark`.
3498
+ * @remarks Safe during SSR. This function writes only the preference and never mutates the DOM, applies a theme, or adds listeners.
3445
3499
  * @category Browser Information
3446
3500
  */
3447
- interface ThemePreferenceResult {
3448
- /** Selected user-facing preference. */
3449
- preference: ThemePreference;
3450
- /** Effective light or dark theme. */
3451
- resolvedTheme: ResolvedTheme;
3452
- /** Human-readable name of the selected preference. */
3453
- displayName: ThemePreferenceDisplayName;
3454
- /** Highest-priority source that supplied the selected preference. */
3455
- source: ThemePreferenceSource;
3456
- }
3501
+ declare function setThemePreference(storageKey: string, value: ThemePreference): boolean;
3502
+
3457
3503
  /**
3458
- * Resolve a website theme preference without mutating the DOM or storage.
3504
+ * Resolve the current website language.
3459
3505
  *
3460
- * Resolution uses four priority levels: a `light` or `dark` URL query
3461
- * override, a stored `system`/`light`/`dark` preference, the current system
3462
- * color scheme, and finally a configured `light` or `dark` fallback. The
3463
- * default query parameter is `theme`, and the storage key must be supplied by
3464
- * the consuming project. Query `system` and all unsupported values are ignored.
3506
+ * Resolution checks the fixed `lang` URL query, the supplied local-storage
3507
+ * key, `navigator.language`, and finally the fixed `en` fallback. Each value
3508
+ * is trimmed, treats `_` as `-`, and is canonicalized as a language tag.
3509
+ * `navigator.languages` is intentionally ignored.
3465
3510
  *
3466
- * The result separates the selected preference from the effective theme and
3467
- * includes its display name (`System`, `Light`, or `Dark`) and source. A stored
3468
- * `system` preference retains `source: "storage"` while its effective theme is
3469
- * resolved from the current media query or fallback.
3511
+ * The label is generated at runtime with `Intl.DisplayNames` in the resolved
3512
+ * language when available. Runtime wording may vary; the canonical language
3513
+ * value is used as the label when display-name generation is unavailable.
3470
3514
  *
3471
3515
  * Usage:
3472
3516
  *
3473
- * ```javascript
3474
- * import { resolveThemePreference } from "mazey";
3517
+ * ```ts
3518
+ * import {
3519
+ * resolveLanguagePreference,
3520
+ * setLanguagePreference,
3521
+ * } from "mazey";
3475
3522
  *
3476
- * const theme = resolveThemePreference({
3477
- * storageKey: "MY_WEBSITE_THEME",
3478
- * });
3479
- * console.log(theme.preference);
3480
- * console.log(theme.resolvedTheme);
3481
- * console.log(theme.displayName);
3482
- * console.log(theme.source);
3483
- * ```
3523
+ * const language =
3524
+ * resolveLanguagePreference(
3525
+ * "MY_WEBSITE_LANGUAGE"
3526
+ * );
3484
3527
  *
3485
- * Possible output:
3528
+ * console.log(language);
3486
3529
  *
3487
- * ```text
3488
- * system
3489
- * dark
3490
- * System
3491
- * system
3530
+ * setLanguagePreference(
3531
+ * "MY_WEBSITE_LANGUAGE",
3532
+ * "ja-JP"
3533
+ * );
3492
3534
  * ```
3493
3535
  *
3494
- * URL override:
3536
+ * Possible output:
3495
3537
  *
3496
- * ```javascript
3497
- * const theme = resolveThemePreference({
3498
- * storageKey: "MY_WEBSITE_THEME",
3499
- * url: "https://example.com/?theme=light",
3500
- * });
3538
+ * ```text
3539
+ * {
3540
+ * value: "ja-JP",
3541
+ * label: "日本語(日本)"
3542
+ * }
3501
3543
  * ```
3502
3544
  *
3503
- * @param options Project storage key and optional URL, storage, media-query, and fallback inputs.
3504
- * @returns The selected preference, effective theme, display name, and preference source.
3505
- * @throws {TypeError} If required options or explicitly supplied option values are invalid.
3506
- * @remarks Safe during SSR and resilient to unavailable or throwing browser APIs. This function does not write storage, mutate the DOM, or add listeners. System resolution reads the current media-query result rather than cached browser information.
3545
+ * @param storageKey Project-specific local-storage key.
3546
+ * @returns The canonical current language and a runtime-generated display label.
3547
+ * @throws {TypeError} If `storageKey` is not a non-empty string.
3548
+ * @remarks Safe during SSR and resilient to unavailable or throwing browser and `Intl` APIs. This function reads preferences only and never writes storage, mutates the DOM, loads translations, redirects, or adds listeners.
3507
3549
  * @category Browser Information
3508
3550
  */
3509
- declare function resolveThemePreference(options: ResolveThemePreferenceOptions): ThemePreferenceResult;
3551
+ declare function resolveLanguagePreference(storageKey: string): PreferenceResult<string>;
3510
3552
  /**
3511
- * Persist a supported website theme preference.
3512
- *
3513
- * The preference is written as the exact lowercase value `system`, `light`,
3514
- * or `dark` under a project-specific storage key. The function returns
3515
- * `false` instead of throwing when storage is unavailable, including during
3516
- * SSR and in privacy-restricted browser environments. It does not resolve or
3517
- * apply the theme and does not mutate the DOM.
3553
+ * Canonicalize and persist a website language.
3518
3554
  *
3519
3555
  * Usage:
3520
3556
  *
3521
- * ```javascript
3522
- * import { setThemePreference } from "mazey";
3557
+ * ```ts
3558
+ * import { setLanguagePreference } from "mazey";
3559
+ *
3560
+ * const stored = setLanguagePreference(
3561
+ * "MY_WEBSITE_LANGUAGE",
3562
+ * "ZH_cn"
3563
+ * );
3523
3564
  *
3524
- * const stored = setThemePreference({
3525
- * storageKey: "MY_WEBSITE_THEME",
3526
- * preference: "dark",
3527
- * });
3528
3565
  * console.log(stored);
3529
3566
  * ```
3530
3567
  *
3531
- * Output:
3568
+ * Output when browser storage is available:
3532
3569
  *
3533
3570
  * ```text
3534
3571
  * true
3535
3572
  * ```
3536
3573
  *
3537
- * @param options Project storage key, supported preference, and optional storage implementation.
3538
- * @returns `true` when the preference was written, or `false` when storage is unavailable or rejects the write.
3539
- * @throws {TypeError} If the options, storage key, preference, or explicitly supplied storage implementation is invalid.
3540
- * @remarks This function writes only the selected preference. Applying a resolved theme and updating controls remain the consuming project's responsibility.
3574
+ * The stored value is canonicalized to:
3575
+ *
3576
+ * ```text
3577
+ * zh-CN
3578
+ * ```
3579
+ *
3580
+ * @param storageKey Project-specific local-storage key.
3581
+ * @param language Language tag to canonicalize and persist.
3582
+ * @returns `true` when storage succeeds, or `false` when storage is unavailable or rejects the write.
3583
+ * @throws {TypeError} If `storageKey` is empty or `language` is empty or malformed.
3584
+ * @remarks Safe during SSR. This function writes only the canonical language and never mutates the DOM, applies translations, redirects, or adds listeners.
3541
3585
  * @category Browser Information
3542
3586
  */
3543
- declare function setThemePreference(options: SetThemePreferenceOptions): boolean;
3587
+ declare function setLanguagePreference(storageKey: string, language: string): boolean;
3544
3588
 
3545
3589
  /**
3546
3590
  * Create a configurable wrapper around the global `console`.
@@ -3612,5 +3656,5 @@ declare const mazeyCon: Console;
3612
3656
  */
3613
3657
  declare const timeCon: Console;
3614
3658
 
3615
- export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, deepFreeze, delCookie, doFn, extractElementText, fireEvent, floatFixed, floatToPercent, formatDate, formatDistanceToNow, formatDurationFromMs, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDateDifference, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isStandalonePWA, isString, isSupportWebp, isSupportedEntryType, isThisHour, isThisMonth, isThisWeek, isThisYear, isToday, isUdfOrNul, isValidCssSelector, isValidData, isValidDate, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, parseGitHubRepository, parseJsonSafe, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, resolveThemePreference, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLocalStorage, setSessionStorage, setThemePreference, sha256Hex, sleep, throttle, timeCon, toJavaScriptGlobalName, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };
3616
- export type { GitHubRepositoryDetails, IsSafePWAEnvOptions, ResolveThemePreferenceOptions, ResolvedTheme, SetThemePreferenceOptions, ThemePreference, ThemePreferenceDisplayName, ThemePreferenceResult, ThemePreferenceSource };
3659
+ export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, deepFreeze, delCookie, doFn, extractElementText, fireEvent, floatFixed, floatToPercent, formatDate, formatDistanceToNow, formatDurationFromMs, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDateDifference, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isStandalonePWA, isString, isSupportWebp, isSupportedEntryType, isThisHour, isThisMonth, isThisWeek, isThisYear, isToday, isUdfOrNul, isValidCssSelector, isValidData, isValidDate, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, parseGitHubRepository, parseJsonSafe, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, resolveLanguagePreference, resolveThemePreference, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLanguagePreference, setLocalStorage, setSessionStorage, setThemePreference, sha256Hex, sleep, throttle, timeCon, toJavaScriptGlobalName, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };
3660
+ export type { GitHubRepositoryDetails, IsSafePWAEnvOptions, PreferenceResult, ResolvedTheme, ThemePreference };