feat:移除了弹窗,服务器添加sls

This commit is contained in:
2026-09-08 22:39:45 +08:00
commit 6a295f9a7a
4082 changed files with 1322534 additions and 0 deletions

View File

@ -0,0 +1,8 @@
import type { AbstractModrinthClient } from '@modrinth/api-client'
import { createContext } from './create-context'
export const [injectModrinthClient, provideModrinthClient] = createContext<AbstractModrinthClient>(
'root',
'modrinthClient',
)

View File

@ -0,0 +1,10 @@
import { createContext } from './create-context'
export interface AppBackupContext {
createBackup: () => Promise<void>
}
export const [injectAppBackup, provideAppBackup] = createContext<AppBackupContext>(
'AppBackupContext',
'appBackupContext',
)

View File

@ -0,0 +1,16 @@
import type { Labrinth } from '@modrinth/api-client'
import type { Ref } from 'vue'
import { createContext } from './create-context'
export type AuthUser = Labrinth.Users.v2.User | Labrinth.Users.v3.User
export interface AuthProvider {
session_token: Ref<string | null>
user: Ref<AuthUser | null>
/** True once the initial auth check has completed (regardless of result). */
isReady?: Ref<boolean>
requestSignIn: (redirectPath: string) => void | Promise<void>
}
export const [injectAuth, provideAuth] = createContext<AuthProvider>('root', 'auth')

View File

@ -0,0 +1,7 @@
export {
type ContentManagerContext,
type ContentModpackData,
injectContentManager,
provideContentManager,
type UploadState,
} from '../layouts/shared/content-tab/providers/content-manager'

View File

@ -0,0 +1,81 @@
/**
* MIT License
*
* Copyright (c) 2023 UnoVue
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @source https://github.com/unovue/reka-ui/blob/53b4734734f8ebef9a344b1e62db291177c59bfe/packages/core/src/shared/createContext.ts
*/
import type { InjectionKey } from 'vue'
import { inject, provide } from 'vue'
/**
* @param providerComponentName - The name(s) of the component(s) providing the context.
*
* There are situations where context can come from multiple components. In such cases, you might need to give an array of component names to provide your context, instead of just a single string.
*
* @param contextName The description for injection key symbol.
*/
export function createContext<ContextValue>(
providerComponentName: string | string[],
contextName?: string,
) {
const symbolDescription =
typeof providerComponentName === 'string' && !contextName
? `${providerComponentName}Context`
: contextName
const injectionKey: InjectionKey<ContextValue | null> = Symbol.for(
`modrinth:${symbolDescription}`,
)
/**
* @param fallback The context value to return if the injection fails.
*
* @throws When context injection failed and no fallback is specified.
* This happens when the component injecting the context is not a child of the root component providing the context.
*/
const injectContext = <T extends ContextValue | null | undefined = ContextValue>(
fallback?: T,
): T extends null ? ContextValue | null : ContextValue => {
const context = inject(injectionKey, fallback)
if (context) return context
if (context === null)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return context as any
throw new Error(
`Injection \`${injectionKey.toString()}\` not found. Component must be used within ${
Array.isArray(providerComponentName)
? `one of the following components: ${providerComponentName.join(', ')}`
: `\`${providerComponentName}\``
}`,
)
}
const provideContext = (contextValue: ContextValue) => {
provide(injectionKey, contextValue)
return contextValue
}
return [injectContext, provideContext] as const
}

View File

@ -0,0 +1,18 @@
import { createContext } from '.'
export type NativeFileDropEvent = {
type: 'enter' | 'over' | 'drop' | 'leave'
paths: string[]
position: {
x: number
y: number
}
}
export interface FileDropProvider {
listenNativeFileDrop: (
handler: (event: NativeFileDropEvent) => void | Promise<void>,
) => Promise<() => void>
}
export const [injectFileDrop, provideFileDrop] = createContext<FileDropProvider>('FileDrop')

View File

@ -0,0 +1,37 @@
import { createContext } from '.'
export interface PickedFile {
/** Browser File object */
file: File
/** Native file system path (available on Tauri, undefined on web) */
path?: string
/** URL suitable for display (blob URL on web, convertFileSrc URL on Tauri) */
previewUrl: string
/** Whether the image should be displayed without the standard avatar frame */
frameless?: boolean
}
export interface PickedModpackFile extends Omit<PickedFile, 'file'> {
/** Only present for upload flows; native imports avoid copying huge packs into the browser heap. */
file?: File
}
export interface PickModpackFileOptions {
/** Set to false when a native path can be streamed directly by the backend. */
readFile?: boolean
}
export interface FilePickerProvider {
/** Pick an image file (for icons) */
pickImage: () => Promise<PickedFile | null>
/** Pick an uploaded or bundled instance icon when the platform provides a dedicated picker */
pickInstanceIcon?: () => Promise<PickedFile | null>
/** Resolve the default built-in instance icon URL for a loader */
getLoaderInstanceIconUrl?: (loader: string) => string | null
/** Pick a folder (directory) — returns path only, no file content */
pickFolder?: () => Promise<{ path: string } | null>
/** Pick a .mrpack modpack file */
pickModpackFile: (options?: PickModpackFileOptions) => Promise<PickedModpackFile | null>
}
export const [injectFilePicker, provideFilePicker] = createContext<FilePickerProvider>('FilePicker')

View File

@ -0,0 +1,24 @@
import type { InjectionKey, Ref } from 'vue'
import { inject, provide } from 'vue'
// This doesn't use the architecture outlined in index.ts as it needs some custom checks + use the symbol
export interface I18nContext {
locale: Ref<string>
t: (key: string, values?: Record<string, unknown>) => string
setLocale: (locale: string) => Promise<void> | void
}
export const I18N_INJECTION_KEY: InjectionKey<I18nContext> = Symbol('i18n')
export function injectI18n(): I18nContext {
const context = inject(I18N_INJECTION_KEY)
if (!context) {
throw new Error('Injection `Symbol(i18n)` not found. Ensure the i18n plugin is installed.')
}
return context
}
export function provideI18n(context: I18nContext): I18nContext {
provide(I18N_INJECTION_KEY, context)
return context
}

View File

@ -0,0 +1,16 @@
export * from './api-client'
export * from './app-backup'
export * from './auth'
export * from './content-manager'
export { createContext } from './create-context'
export * from './file-drop'
export * from './file-picker'
export * from './i18n'
export * from './instance-import'
export * from './loading-state'
export * from './modal-behavior'
export * from './page-context'
export * from './popup-notifications'
export * from './server-context'
export * from './tags'
export * from './web-notifications'

View File

@ -0,0 +1,184 @@
import { createContext } from './create-context.ts'
export interface ImportableLauncher {
name: string
path: string
instances: { name: string; path: string }[]
launcherType?: string
}
export type ImportPlanStage = 'resolving' | 'scanning' | 'done' | 'error'
export interface ImportPlanCounts {
files: number
bytes: number
}
export interface ImportPlanSnapshot {
requestId: string
stage: ImportPlanStage
gameVersion: string | null
loader: string | null
loaderVersion: string | null
importPath: string
minecraftRoot: string
modCount: number
cache: ImportPlanCounts
local: ImportPlanCounts
network: ImportPlanCounts
migrate: ImportPlanCounts
error?: string | null
}
export interface ImportPlanRequest {
requestId: string
launcherType: string
basePath: string
instanceFolder: string
instancePath?: string | null
gameVersion?: string | null
loader?: string | null
loaderVersion?: string | null
}
export const KNOWN_IMPORT_PLAN_LOADERS = ['fabric', 'forge', 'neoforge', 'quilt'] as const
export function importPlanDefaultGameVersion(detected: string | null | undefined) {
return detected ?? ''
}
export function importPlanDefaultLoader(detected: string | null | undefined) {
if (detected && (KNOWN_IMPORT_PLAN_LOADERS as readonly string[]).includes(detected)) {
return detected
}
return 'vanilla'
}
export function importPlanDefaultLoaderVersion(detected: string | null | undefined) {
return detected?.trim() ? detected : 'latest'
}
export function isImportPlanLoaderRecognized(loader: string | null | undefined) {
return !!loader && (KNOWN_IMPORT_PLAN_LOADERS as readonly string[]).includes(loader)
}
export interface ImportPlanWarningsInput {
gameVersion?: string | null
loader?: string | null
loaderVersion?: string | null
detectedGameVersion?: string | null
detectedLoader?: string | null
detectedLoaderVersion?: string | null
detectedModCount?: number
gameVersionTouched?: boolean
loaderTouched?: boolean
loaderVersionTouched?: boolean
}
export function importPlanWarnings(
snapshot: ImportPlanSnapshot | null,
selected: ImportPlanWarningsInput,
) {
const loader = selected.loader || 'vanilla'
const loaderVersion = selected.loaderVersion || ''
const gameVersion = selected.gameVersion || ''
const detectedGameVersion = importPlanDefaultGameVersion(
selected.detectedGameVersion ?? snapshot?.gameVersion,
)
const detectedLoader = importPlanDefaultLoader(selected.detectedLoader ?? snapshot?.loader)
const detectedLoaderVersion = importPlanDefaultLoaderVersion(
selected.detectedLoaderVersion ?? snapshot?.loaderVersion,
)
const gameVersionCustom = gameVersion !== detectedGameVersion
const loaderTypeCustom = loader !== detectedLoader
const loaderVersionCustom = loader !== 'vanilla' && loaderVersion !== detectedLoaderVersion
const loaderVersionMissing =
loader !== 'vanilla' && (!loaderVersion || loaderVersion === 'latest')
const loaderTypeUnrecognized =
(loader === 'vanilla' || !isImportPlanLoaderRecognized(loader)) &&
((selected.detectedModCount ?? 0) > 0 || (snapshot?.modCount ?? 0) > 0)
return {
gameVersionCustom,
loaderTypeCustom,
loaderVersionCustom,
loaderVersionMissing,
loaderTypeUnrecognized,
hasWarnings:
gameVersionCustom ||
loaderTypeCustom ||
loaderVersionCustom ||
loaderVersionMissing ||
loaderTypeUnrecognized,
}
}
export function reduceImportPlanSnapshot(
previous: ImportPlanSnapshot | null,
incoming: ImportPlanSnapshot | null,
activeRequestId: string,
) {
if (!incoming || incoming.requestId !== activeRequestId) return previous
return incoming
}
export interface SymlinkMethodInstance {
name: string
path?: string
launcherType?: string
basePath?: string
versionPath?: string
compatibleMode?: boolean
}
export interface SymlinkMethodChoice {
instanceName: string
instancePath?: string
symlink: boolean
gameVersion?: string | null
loader?: string | null
loaderVersion?: string | null
gameDirOverride?: string | null
}
export interface InstanceImportProvider {
/** Returns launchers with instances already populated (one round trip on mount) */
getDetectedLaunchers: () => Promise<ImportableLauncher[]>
/** Only needed for manually-added launcher paths */
getImportableInstances: (
launcherName: string,
path: string,
) => Promise<{ name: string; path: string }[]>
/** Resolve available loader version ids for a loader and game version */
getLoaderVersions: (loader: string, gameVersion: string) => Promise<string[]>
/** Open a filesystem path in the platform file manager */
openPath: (path: string) => Promise<void>
/** Start a non-blocking import statistics scan and return its request id */
startImportPlan: (request: ImportPlanRequest) => Promise<string>
/** Cancel a previously started import statistics scan */
cancelImportPlan: (requestId: string) => Promise<void>
/** Subscribe to import_plan events; resolves to an unsubscribe function */
listenImportPlan: (callback: (snapshot: ImportPlanSnapshot) => void) => Promise<() => void>
/** Perform the actual import */
importInstances: (
selections: {
launcher: string
path: string
instanceNames: string[]
instancePaths: string[]
launcherType?: string
symlink?: boolean
gameVersion?: string | null
loader?: string | null
loaderVersion?: string | null
gameDirOverride?: string | null
}[],
) => Promise<void>
/** Open a directory picker (platform-specific) */
selectDirectory: () => Promise<string | null>
/** Open a multi-directory picker */
selectDirectories: () => Promise<string[] | null>
}
export const [injectInstanceImport, provideInstanceImport] =
createContext<InstanceImportProvider>('InstanceImport')

View File

@ -0,0 +1,27 @@
import type { Ref } from 'vue'
import { createContext } from './create-context'
/**
* Cross-platform loading-state contract injected by the host app.
* Consumed by the shared `LoadingBar` and `ReadyTransition` components.
*/
export interface LoadingStateProvider {
/** True iff at least one active load token is registered. */
readonly pending: Readonly<Ref<boolean>>
/** Host-level kill switch (e.g. disable the bar during a splash screen). */
readonly barEnabled: Readonly<Ref<boolean>>
/** Begin a tracked load. Returns a unique token; pair with `end(token)`. */
begin(): symbol
/** End a previously-begun load. Idempotent — unknown or repeat tokens are silently ignored. */
end(token: symbol): void
/** Fire a synthetic load that auto-releases after `durationMs` (default 500ms). For manual-refresh buttons. */
beginManual(durationMs?: number): void
/** Toggle the bar at the host level. */
setEnabled(enabled: boolean): void
}
export const [injectLoadingState, provideLoadingState] = createContext<LoadingStateProvider>(
'root',
'loadingState',
)

View File

@ -0,0 +1,14 @@
import type { Ref } from 'vue'
import { createContext } from './create-context'
export interface ModalBehavior {
noblur: Ref<boolean>
onShow?: () => void
onHide?: () => void
}
export const [injectModalBehavior, provideModalBehavior] = createContext<ModalBehavior>(
'root',
'modalBehavior',
)

View File

@ -0,0 +1,28 @@
import type { ComputedRef, Ref } from 'vue'
import { createContext } from '.'
export interface PageContext {
// pages may render sidebar content in #sidebar-teleport-target instead of in the main layout when true
hierarchicalSidebarAvailable: Ref<boolean>
showAds: Ref<boolean>
floatingActionBarOffsets?: {
left: Ref<string> | ComputedRef<string>
right: Ref<string> | ComputedRef<string>
}
intercomBubble?: {
width: Ref<number> | ComputedRef<number>
horizontalPadding: Ref<number> | ComputedRef<number>
requestHorizontalPadding?: (id: symbol, padding: number | null) => void
requestVerticalClearance: (id: symbol, clearance: number | null) => void
}
featureFlags?: {
serverRamAsBytesAlwaysOn?: Ref<boolean>
}
openExternalUrl: (url: string) => void
}
export const [injectPageContext, providePageContext] = createContext<PageContext>(
'root',
'pageContext',
)

View File

@ -0,0 +1,158 @@
import type { Component } from 'vue'
import { createContext } from '.'
export interface PopupNotificationButton {
label: string
action: () => void | Promise<void>
icon?: Component
color?: 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'standard'
keepOpen?: boolean
}
export type PopupNotificationProgressType = 'percentage' | 'bytes' | 'count'
export interface PopupNotificationProgressItem {
id: string
title: string
text?: string
iconUrl?: string | null
progress: number
waiting: boolean
showProgress?: boolean
wrapText?: boolean
progressType?: PopupNotificationProgressType
progressCurrent?: number
progressTotal?: number
onDismiss?: () => void | Promise<void>
buttons?: PopupNotificationButton[]
}
export type PopupNotificationToastType =
| 'friend-request'
| 'server-invite'
| 'instance-invite'
| 'instance-download'
| 'instance-ready'
export interface PopupNotificationToast {
type: PopupNotificationToastType
actorName?: string | null
actorAvatarUrl?: string | null
entityName?: string
entityIconUrl?: string | null
statusText?: string
progress?: number
waiting?: boolean
showProgress?: boolean
progressType?: PopupNotificationProgressType
progressCurrent?: number
progressTotal?: number
onAccept?: () => void | Promise<void>
onDecline?: () => void | Promise<void>
onDismiss?: () => void | Promise<void>
onLaunch?: () => void | Promise<void>
onOpenActor?: () => void | Promise<void>
onOpenInstance?: () => void | Promise<void>
}
export interface PopupNotification {
id: string | number
createdAt?: number
title: string
titleLogo?: Component
bodyComponent?: Component
bodyProps?: Record<string, unknown>
text?: string
iconUrl?: string | null
type?: 'error' | 'warning' | 'success' | 'info' | 'download'
progress?: number
waiting?: boolean
progressItems?: PopupNotificationProgressItem[]
buttons?: PopupNotificationButton[]
toast?: PopupNotificationToast
onClick?: () => void | Promise<void>
autoCloseMs?: number | null
timer?: NodeJS.Timeout
/** Hidden from the toast stack but retained in notification history. */
collapsed?: boolean
}
export abstract class AbstractPopupNotificationManager {
protected readonly DEFAULT_AUTO_CLOSE_MS = 30 * 1000
abstract getNotifications(): PopupNotification[]
protected abstract addNotificationToStorage(notification: PopupNotification): void
protected abstract removeNotificationFromStorage(id: string | number): void
protected abstract clearAllNotificationsFromStorage(): void
addPopupNotification = (
notification: Omit<PopupNotification, 'id' | 'timer'>,
): PopupNotification => {
const newNotification: PopupNotification = {
...notification,
id: Date.now() + Math.random(),
createdAt: Date.now(),
}
this.setNotificationTimer(newNotification)
this.addNotificationToStorage(newNotification)
return newNotification
}
removeNotification = (id: string | number): void => {
const notifications = this.getNotifications()
const notification = notifications.find((n) => n.id === id)
if (notification) {
this.clearNotificationTimer(notification)
this.removeNotificationFromStorage(id)
}
}
clearAllNotifications = (): void => {
this.getNotifications().forEach((n) => this.clearNotificationTimer(n))
this.clearAllNotificationsFromStorage()
}
setNotificationTimer = (notification: PopupNotification): void => {
if (!notification) return
this.clearNotificationTimer(notification)
if (notification.autoCloseMs === null) return
const delay = notification.autoCloseMs ?? this.DEFAULT_AUTO_CLOSE_MS
notification.timer = setTimeout(() => {
this.collapseNotification(notification.id)
}, delay)
}
collapseNotification = (id: string | number): void => {
const notification = this.getNotifications().find((n) => n.id === id)
if (notification) {
this.clearNotificationTimer(notification)
notification.collapsed = true
}
}
expandNotification = (id: string | number): void => {
const notification = this.getNotifications().find((n) => n.id === id)
if (notification) {
notification.collapsed = false
this.setNotificationTimer(notification)
}
}
stopNotificationTimer = (notification: PopupNotification): void => {
this.clearNotificationTimer(notification)
}
private clearNotificationTimer(notification: PopupNotification): void {
if (notification.timer) {
clearTimeout(notification.timer)
notification.timer = undefined
}
}
}
export const [injectPopupNotificationManager, providePopupNotificationManager] =
createContext<AbstractPopupNotificationManager>('root', 'popupNotificationManager')

View File

@ -0,0 +1,75 @@
import type { Archon, UploadState } from '@modrinth/api-client'
import type { ComputedRef, Ref } from 'vue'
import type { MessageDescriptor } from '#ui/composables/i18n'
import type { FileOperation } from '#ui/layouts/shared/files-tab/types'
import { createContext } from '.'
export interface BusyReason {
reason: MessageDescriptor
}
export interface FilesystemAuth {
url: string
token: string
}
export type CancelUploadHandler = () => void | Promise<void>
export interface ServerStatsSample {
cpu_percent: number
ram_usage_bytes: number
ram_total_bytes: number
storage_usage_bytes: number
storage_total_bytes: number
}
export interface ServerStats {
current: ServerStatsSample
past: ServerStatsSample
graph: {
cpu: number[]
ram: number[]
}
}
export interface ModrinthServerContext {
readonly serverId: string
readonly worldId: Ref<string | null>
readonly server: Ref<Archon.Servers.v0.Server>
readonly serverFull: ComputedRef<Archon.Servers.v1.ServerFull | null>
readonly currentUserPermissions: ComputedRef<Archon.Servers.v0.UserScope>
// Websocket state
readonly isConnected: Ref<boolean>
readonly isWsAuthIncorrect: Ref<boolean>
readonly powerState: Ref<Archon.Websocket.v0.PowerState>
readonly powerStateDetails: Ref<{ oom_killed?: boolean; exit_code?: number } | undefined>
readonly isServerRunning: ComputedRef<boolean>
readonly stats: Ref<ServerStats>
readonly uptimeSeconds: Ref<number>
// Content sync state
readonly isSyncingContent: Ref<boolean>
// Busy state — when non-empty, all write operations should be disabled
readonly busyReasons: ComputedRef<BusyReason[]>
// Filesystem state
readonly fsAuth: Ref<FilesystemAuth | null>
readonly fsOps: Ref<Archon.Websocket.v0.FilesystemOperation[]>
readonly fsQueuedOps: Ref<Archon.Websocket.v0.QueuedFilesystemOp[]>
refreshFsAuth: () => Promise<void>
// File upload state
readonly uploadState: Ref<UploadState>
readonly cancelUpload: Ref<CancelUploadHandler | null>
// File operations (extract, move, etc.)
readonly activeOperations: ComputedRef<FileOperation[]>
dismissOperation: (opId: string, action: 'dismiss' | 'cancel') => Promise<void>
}
export const [injectModrinthServerContext, provideModrinthServerContext] =
createContext<ModrinthServerContext>('[id].vue', 'modrinthServerContext')

View File

@ -0,0 +1,11 @@
import type { Labrinth } from '@modrinth/api-client'
import type { Ref } from 'vue'
import { createContext } from './create-context'
export interface TagsContext {
gameVersions: Ref<Labrinth.Tags.v2.GameVersion[]>
loaders: Ref<Labrinth.Tags.v2.Loader[]>
}
export const [injectTags, provideTags] = createContext<TagsContext>('root', 'tags')

View File

@ -0,0 +1,173 @@
import { createContext } from '.'
export interface WebNotification {
id: string | number
createdAt?: number
title?: string
text?: string
type?: 'error' | 'warning' | 'success' | 'info'
errorCode?: string
count?: number
autoCloseMs?: number | null // null means do not dismiss automatically
timer?: NodeJS.Timeout
/** Hidden from the toast stack but retained in notification history. */
collapsed?: boolean
supportData?: Record<string, unknown>
}
export type NotificationPanelLocation = 'left' | 'right'
export abstract class AbstractWebNotificationManager {
protected readonly DEFAULT_AUTO_DISMISS_DELAY_MS = 30 * 1000
private lastGeneratedNotificationId = 0
abstract getNotifications(): WebNotification[]
abstract getNotificationLocation(): NotificationPanelLocation
abstract setNotificationLocation(location: NotificationPanelLocation): void
protected abstract addNotificationToStorage(notification: WebNotification): void
protected abstract removeNotificationFromStorage(id: string | number): void
protected abstract removeNotificationFromStorageByIndex(index: number): void
protected abstract clearAllNotificationsFromStorage(): void
addNotification = (notification: Partial<WebNotification>): WebNotification => {
const existingNotif = this.findExistingNotification(notification)
if (existingNotif) {
existingNotif.createdAt = Date.now()
existingNotif.collapsed = false
this.refreshNotificationTimer(existingNotif)
existingNotif.count = (existingNotif.count || 0) + 1
return existingNotif
}
const newNotification = this.createNotification(notification)
this.setNotificationTimer(newNotification)
this.addNotificationToStorage(newNotification)
return newNotification
}
/**
* @deprecated You should use `addNotification` instead to provide a more human-readable error message to the user.
*/
handleError = (error: unknown): void => {
this.addNotification({
title: '发生错误',
text:
error instanceof Error
? error.message
: typeof error === 'string'
? error
: JSON.stringify(error),
type: 'error',
})
}
removeNotification = (id: string | number): WebNotification | undefined => {
const notifications = this.getNotifications()
const notification = notifications.find((n) => n.id === id)
if (notification) {
this.clearNotificationTimer(notification)
this.removeNotificationFromStorage(id)
}
return notification
}
removeNotificationByIndex = (index: number): WebNotification | null => {
const notifications = this.getNotifications()
if (index >= 0 && index < notifications.length) {
const notification = notifications[index]
this.clearNotificationTimer(notification)
this.removeNotificationFromStorageByIndex(index)
return notification
}
return null
}
clearAllNotifications = (): void => {
const notifications = this.getNotifications()
notifications.forEach((notification) => {
this.clearNotificationTimer(notification)
})
this.clearAllNotificationsFromStorage()
}
setNotificationTimer = (notification: WebNotification): void => {
if (!notification) return
this.clearNotificationTimer(notification)
if (notification.autoCloseMs === null) return
const delay = notification.autoCloseMs ?? this.DEFAULT_AUTO_DISMISS_DELAY_MS
notification.timer = setTimeout(() => {
this.collapseNotification(notification.id)
}, delay)
}
collapseNotification = (id: string | number): void => {
const notification = this.getNotifications().find((n) => n.id === id)
if (notification) {
this.clearNotificationTimer(notification)
notification.collapsed = true
}
}
expandNotification = (id: string | number): void => {
const notification = this.getNotifications().find((n) => n.id === id)
if (notification) {
notification.collapsed = false
this.setNotificationTimer(notification)
}
}
stopNotificationTimer = (notification: WebNotification): void => {
this.clearNotificationTimer(notification)
}
private refreshNotificationTimer(notification: WebNotification): void {
this.setNotificationTimer(notification)
}
private clearNotificationTimer(notification: WebNotification): void {
if (notification.timer) {
clearTimeout(notification.timer)
notification.timer = undefined
}
}
private findExistingNotification(
notification: Partial<WebNotification>,
): WebNotification | undefined {
return this.getNotifications().find(
(existing) =>
existing.text === notification.text &&
existing.title === notification.title &&
existing.type === notification.type,
)
}
private createNotification(notification: Partial<WebNotification>): WebNotification {
// Notifications can be created in the same millisecond. Keep generated
// ids unique so dismissing one item never targets its siblings.
const now = Date.now()
const id = Math.max(now, this.lastGeneratedNotificationId + 1)
this.lastGeneratedNotificationId = id
return {
...notification,
id,
createdAt: Date.now(),
count: 1,
} as WebNotification
}
}
export const [injectNotificationManager, provideNotificationManager] =
createContext<AbstractWebNotificationManager>('root', 'notificationManager')