mazey 5.3.0 → 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,104 +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:
3420
+ *
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:
3434
+ *
3435
+ * ```ts
3436
+ * import {
3437
+ * resolveThemePreference,
3438
+ * setThemePreference,
3439
+ * } from "mazey";
3440
+ *
3441
+ * const theme = resolveThemePreference(
3442
+ * "MY_WEBSITE_THEME"
3443
+ * );
3412
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.
3413
3466
  * @category Browser Information
3414
3467
  */
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
- }
3468
+ declare function resolveThemePreference(storageKey: string): PreferenceResult<ResolvedTheme>;
3429
3469
  /**
3430
- * 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
+ * );
3431
3484
  *
3485
+ * console.log(stored);
3486
+ * ```
3487
+ *
3488
+ * Output when browser storage is available:
3489
+ *
3490
+ * ```text
3491
+ * true
3492
+ * ```
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.
3432
3499
  * @category Browser Information
3433
3500
  */
3434
- interface ThemePreferenceResult {
3435
- /** Selected user-facing preference. */
3436
- preference: ThemePreference;
3437
- /** Effective light or dark theme. */
3438
- resolvedTheme: ResolvedTheme;
3439
- /** Human-readable name of the selected preference. */
3440
- displayName: ThemePreferenceDisplayName;
3441
- /** Highest-priority source that supplied the selected preference. */
3442
- source: ThemePreferenceSource;
3443
- }
3501
+ declare function setThemePreference(storageKey: string, value: ThemePreference): boolean;
3502
+
3444
3503
  /**
3445
- * Resolve a website theme preference without mutating the DOM or storage.
3504
+ * Resolve the current website language.
3446
3505
  *
3447
- * Resolution uses four priority levels: a `light` or `dark` URL query
3448
- * override, a stored `system`/`light`/`dark` preference, the current system
3449
- * color scheme, and finally a configured `light` or `dark` fallback. The
3450
- * default query parameter is `theme`, and the storage key must be supplied by
3451
- * 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.
3452
3510
  *
3453
- * The result separates the selected preference from the effective theme and
3454
- * includes its display name (`System`, `Light`, or `Dark`) and source. A stored
3455
- * `system` preference retains `source: "storage"` while its effective theme is
3456
- * 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.
3457
3514
  *
3458
3515
  * Usage:
3459
3516
  *
3460
- * ```javascript
3461
- * import { resolveThemePreference } from "mazey";
3517
+ * ```ts
3518
+ * import {
3519
+ * resolveLanguagePreference,
3520
+ * setLanguagePreference,
3521
+ * } from "mazey";
3462
3522
  *
3463
- * const theme = resolveThemePreference({
3464
- * storageKey: "MY_WEBSITE_THEME",
3465
- * });
3466
- * console.log(theme.preference);
3467
- * console.log(theme.resolvedTheme);
3468
- * console.log(theme.displayName);
3469
- * console.log(theme.source);
3523
+ * const language =
3524
+ * resolveLanguagePreference(
3525
+ * "MY_WEBSITE_LANGUAGE"
3526
+ * );
3527
+ *
3528
+ * console.log(language);
3529
+ *
3530
+ * setLanguagePreference(
3531
+ * "MY_WEBSITE_LANGUAGE",
3532
+ * "ja-JP"
3533
+ * );
3470
3534
  * ```
3471
3535
  *
3472
3536
  * Possible output:
3473
3537
  *
3474
3538
  * ```text
3475
- * system
3476
- * dark
3477
- * System
3478
- * system
3539
+ * {
3540
+ * value: "ja-JP",
3541
+ * label: "日本語(日本)"
3542
+ * }
3479
3543
  * ```
3480
3544
  *
3481
- * URL override:
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.
3549
+ * @category Browser Information
3550
+ */
3551
+ declare function resolveLanguagePreference(storageKey: string): PreferenceResult<string>;
3552
+ /**
3553
+ * Canonicalize and persist a website language.
3482
3554
  *
3483
- * ```javascript
3484
- * const theme = resolveThemePreference({
3485
- * storageKey: "MY_WEBSITE_THEME",
3486
- * url: "https://example.com/?theme=light",
3487
- * });
3555
+ * Usage:
3556
+ *
3557
+ * ```ts
3558
+ * import { setLanguagePreference } from "mazey";
3559
+ *
3560
+ * const stored = setLanguagePreference(
3561
+ * "MY_WEBSITE_LANGUAGE",
3562
+ * "ZH_cn"
3563
+ * );
3564
+ *
3565
+ * console.log(stored);
3566
+ * ```
3567
+ *
3568
+ * Output when browser storage is available:
3569
+ *
3570
+ * ```text
3571
+ * true
3572
+ * ```
3573
+ *
3574
+ * The stored value is canonicalized to:
3575
+ *
3576
+ * ```text
3577
+ * zh-CN
3488
3578
  * ```
3489
3579
  *
3490
- * @param options Project storage key and optional URL, storage, media-query, and fallback inputs.
3491
- * @returns The selected preference, effective theme, display name, and preference source.
3492
- * @throws {TypeError} If required options or explicitly supplied option values are invalid.
3493
- * @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.
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.
3494
3585
  * @category Browser Information
3495
3586
  */
3496
- declare function resolveThemePreference(options: ResolveThemePreferenceOptions): ThemePreferenceResult;
3587
+ declare function setLanguagePreference(storageKey: string, language: string): boolean;
3497
3588
 
3498
3589
  /**
3499
3590
  * Create a configurable wrapper around the global `console`.
@@ -3565,5 +3656,5 @@ declare const mazeyCon: Console;
3565
3656
  */
3566
3657
  declare const timeCon: Console;
3567
3658
 
3568
- 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, sha256Hex, sleep, throttle, timeCon, toJavaScriptGlobalName, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };
3569
- export type { GitHubRepositoryDetails, IsSafePWAEnvOptions, ResolveThemePreferenceOptions, ResolvedTheme, 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 };