mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-22 21:50:42 -05:00
refac
This commit is contained in:
1 parent
6ac83ce14e
commit
b6a77a0f12
9 files changed
+357
-51
No files matched your search
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { WEBUI_BASE_URL } from '$lib/constants';
|
||||
import { settings, playingNotificationSound, isLastActiveTab } from '$lib/stores';
|
||||
import { settings, isLastActiveTab } from '$lib/stores';
|
||||
import { playNotificationSound } from '$lib/utils/audio';
|
||||
import DOMPurify from 'dompurify';
|
||||
import { marked } from 'marked';
|
||||
|
||||
@@ -14,6 +15,7 @@
|
||||
export let onClick: Function = () => {};
|
||||
export let title: string = 'HI';
|
||||
export let content: string;
|
||||
export let playSound = true;
|
||||
|
||||
let startX = 0,
|
||||
startY = 0;
|
||||
@@ -66,20 +68,8 @@
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (!navigator.userActivation.hasBeenActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($settings?.notificationSound ?? true) {
|
||||
if (!$playingNotificationSound && $isLastActiveTab) {
|
||||
playingNotificationSound.set(true);
|
||||
|
||||
const audio = new Audio(`/audio/notification.mp3`);
|
||||
audio.play().finally(() => {
|
||||
// Ensure the global state is reset after the sound finishes
|
||||
playingNotificationSound.set(false);
|
||||
});
|
||||
}
|
||||
if (playSound && ($settings?.notificationSound ?? true) && $isLastActiveTab) {
|
||||
void playNotificationSound($settings?.notificationSoundType);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -311,6 +311,7 @@
|
||||
|
||||
<div
|
||||
class="flex-1 {fileImageUrl !== null ||
|
||||
fileVideoUrl !== null ||
|
||||
fileDocxData !== null ||
|
||||
fileModelData !== null ||
|
||||
filePdfData !== null ||
|
||||
@@ -340,7 +341,7 @@
|
||||
{:else if fileVideoUrl !== null}
|
||||
<div class="w-full h-full flex items-center justify-center bg-black">
|
||||
<!-- svelte-ignore a11y-media-has-caption -->
|
||||
<video src={fileVideoUrl} controls class="max-w-full max-h-full">
|
||||
<video src={fileVideoUrl} controls class="w-full h-full object-contain">
|
||||
{$i18n.t('Your browser does not support the video tag.')}
|
||||
</video>
|
||||
</div>
|
||||
|
||||
@@ -13,6 +13,29 @@
|
||||
}
|
||||
]
|
||||
});
|
||||
/** Local document resources never become arbitrary network requests. */
|
||||
export function resolveDocumentPath(documentPath: string, reference: string): string | null {
|
||||
if (!reference || reference.startsWith('#') || reference.startsWith('//')) return null;
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(reference) && !/^[a-z]:[\\/]/i.test(reference)) return null;
|
||||
let path: string;
|
||||
try {
|
||||
path = decodeURIComponent(reference.split(/[?#]/)[0]).replace(/\\/g, '/');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (/[\x00-\x1f]/.test(path)) return null;
|
||||
const base = documentPath.replace(/\\/g, '/');
|
||||
if (!path.startsWith('/') && !/^[a-z]:\//i.test(path))
|
||||
path = base.slice(0, base.lastIndexOf('/') + 1) + path;
|
||||
const prefix = /^[a-z]:\//i.test(path) ? path.slice(0, 3) : '/';
|
||||
const parts: string[] = [];
|
||||
for (const part of path.slice(prefix.length).split('/')) {
|
||||
if (part === '..') parts.pop();
|
||||
else if (part && part !== '.') parts.push(part);
|
||||
}
|
||||
return prefix + parts.join('/');
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
@@ -35,28 +58,6 @@
|
||||
export let chatId: string | null = null;
|
||||
export let resourceVersion = 0;
|
||||
export let onLocalLink: (path: string) => void = () => {};
|
||||
/** Local document resources never become arbitrary network requests. */
|
||||
function resolveDocumentPath(documentPath: string, reference: string): string | null {
|
||||
if (!reference || reference.startsWith('#') || reference.startsWith('//')) return null;
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(reference) && !/^[a-z]:[\\/]/i.test(reference)) return null;
|
||||
let path: string;
|
||||
try {
|
||||
path = decodeURIComponent(reference.split(/[?#]/)[0]).replace(/\\/g, '/');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (/[\x00-\x1f]/.test(path)) return null;
|
||||
const base = documentPath.replace(/\\/g, '/');
|
||||
if (!path.startsWith('/') && !/^[a-z]:\//i.test(path))
|
||||
path = base.slice(0, base.lastIndexOf('/') + 1) + path;
|
||||
const prefix = /^[a-z]:\//i.test(path) ? path.slice(0, 3) : '/';
|
||||
const parts: string[] = [];
|
||||
for (const part of path.slice(prefix.length).split('/')) {
|
||||
if (part === '..') parts.pop();
|
||||
else if (part && part !== '.') parts.push(part);
|
||||
}
|
||||
return prefix + parts.join('/');
|
||||
}
|
||||
|
||||
let generation = 0;
|
||||
let urls = new Map<string, Promise<string | null>>();
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy } from 'svelte';
|
||||
import type { Editor } from '@tiptap/core';
|
||||
import { Marked } from 'marked';
|
||||
import DOMPurify from 'dompurify';
|
||||
import TurndownService from 'turndown';
|
||||
import { gfm } from '@joplin/turndown-plugin-gfm';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import RichTextInput from '$lib/components/common/RichTextInput.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { downloadFileBlob } from '$lib/apis/terminal';
|
||||
import { resolveDocumentPath } from './MarkdownDocument.svelte';
|
||||
|
||||
export let value = '';
|
||||
export let path = '';
|
||||
export let baseUrl = '';
|
||||
export let apiKey = '';
|
||||
export let chatId: string | null = null;
|
||||
export let readOnly = false;
|
||||
export let onSave: (() => Promise<void>) | null = null;
|
||||
const i18n = getContext<any>('i18n');
|
||||
const markdown = new Marked({
|
||||
breaks: false,
|
||||
renderer: {
|
||||
list: (body, ordered, start) =>
|
||||
body.includes('data-type="taskItem"')
|
||||
? `<ul data-type="taskList">${body}</ul>`
|
||||
: ordered ? `<ol start="${start}">${body}</ol>` : `<ul>${body}</ul>`,
|
||||
listitem: (text, task, checked) => task
|
||||
? `<li data-type="taskItem" data-checked="${checked}">${text.replace(/^<input[^>]*>\s*/, '')}</li>`
|
||||
: `<li>${text}</li>`
|
||||
}
|
||||
});
|
||||
const serializer = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' });
|
||||
serializer.use(gfm);
|
||||
serializer.addRule('taskCheckbox', { filter: (node) => node.nodeName === 'INPUT', replacement: () => '' });
|
||||
serializer.addRule('taskItem', {
|
||||
filter: (node) => node.nodeName === 'LI' && node.getAttribute('data-type') === 'taskItem',
|
||||
replacement: (content, node) => `- [${node.getAttribute('data-checked') === 'true' ? 'x' : ' '}] ${content.trim().replace(/\n(?=.)/g, '\n ')}\n`
|
||||
});
|
||||
|
||||
let editor: Editor | null = null;
|
||||
let html: string | null = null;
|
||||
let documentJSON: any = null;
|
||||
let lastValue: string | null = null;
|
||||
let original = '';
|
||||
let originalDocument = '';
|
||||
let header = '';
|
||||
let generation = 0;
|
||||
let revision = 0;
|
||||
const images = new Map<string, string>();
|
||||
const releaseImages = () => {
|
||||
for (const url of images.keys()) URL.revokeObjectURL(url);
|
||||
images.clear();
|
||||
};
|
||||
async function load(source: string) {
|
||||
const current = ++generation;
|
||||
lastValue = source;
|
||||
html = null;
|
||||
editor = null;
|
||||
releaseImages();
|
||||
original = source;
|
||||
// Keep document metadata out of the rich-text conversion.
|
||||
header = source.match(/^---\r?\n[\s\S]*?\r?\n(?:---|\.\.\.)\r?\n/)?.[0] ?? '';
|
||||
const dom = document.createElement('div');
|
||||
dom.innerHTML = DOMPurify.sanitize(markdown.parse(source.slice(header.length)) as string);
|
||||
await Promise.all(Array.from(dom.querySelectorAll('img')).map(async (image) => {
|
||||
const reference = image.getAttribute('src') ?? '';
|
||||
const file = resolveDocumentPath(path, reference);
|
||||
if (!file || !baseUrl) return;
|
||||
try {
|
||||
const result = await downloadFileBlob(baseUrl, apiKey, file, chatId ?? undefined);
|
||||
if (!result || current !== generation) return;
|
||||
const url = URL.createObjectURL(result.blob);
|
||||
images.set(url, reference);
|
||||
image.src = url;
|
||||
} catch { /* Keep the original reference if an image cannot be loaded. */ }
|
||||
}));
|
||||
if (current !== generation) return;
|
||||
documentJSON = null;
|
||||
revision++;
|
||||
html = dom.innerHTML;
|
||||
}
|
||||
$: if (value !== lastValue) void load(value);
|
||||
function attach(next: Editor | null) {
|
||||
if (!next || editor === next) return;
|
||||
editor = next;
|
||||
originalDocument = JSON.stringify(next.getJSON());
|
||||
next.view.dom.setAttribute('aria-label', i18n ? $i18n.t('Markdown editor') : 'Markdown editor');
|
||||
next.on('update', () => {
|
||||
if (readOnly) return;
|
||||
const dom = document.createElement('div');
|
||||
dom.innerHTML = next.getHTML();
|
||||
for (const image of dom.querySelectorAll('img')) {
|
||||
const reference = images.get(image.getAttribute('src') ?? '');
|
||||
if (reference) image.setAttribute('src', reference);
|
||||
}
|
||||
value = lastValue = JSON.stringify(next.getJSON()) === originalDocument
|
||||
? original
|
||||
: header + serializer.turndown(dom.innerHTML) + '\n';
|
||||
});
|
||||
}
|
||||
export const getSelection = () => {
|
||||
if (!editor || editor.state.selection.empty) return undefined;
|
||||
const { from, to } = editor.state.selection;
|
||||
return { text: editor.state.doc.textBetween(from, to, '\n'), location: '' };
|
||||
};
|
||||
onDestroy(() => { generation++; releaseImages(); });
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="min-h-full px-4 py-3"
|
||||
role="presentation"
|
||||
on:keydown={(event) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (!readOnly) void onSave?.().catch((error) => toast.error(String(error)));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{#if html !== null}
|
||||
{#key revision}
|
||||
<RichTextInput
|
||||
json={true}
|
||||
bind:value={documentJSON}
|
||||
{html}
|
||||
link={true}
|
||||
image={true}
|
||||
editable={!readOnly}
|
||||
className="input-prose-sm min-h-[12rem]"
|
||||
placeholder={$i18n.t('Write something...')}
|
||||
on:editor={(event) => attach(event.detail)}
|
||||
/>
|
||||
{/key}
|
||||
{:else}
|
||||
<Spinner className="size-4" />
|
||||
{/if}
|
||||
</div>
|
||||
@@ -2,13 +2,22 @@
|
||||
import UserSettingRow from './UserSettingRow.svelte';
|
||||
import { canUseNotificationTargets } from '$lib/utils/settings-access';
|
||||
import { getContext, onMount } from 'svelte';
|
||||
import {
|
||||
playNotificationSound,
|
||||
setNotificationSoundEnabled,
|
||||
notificationSoundStyles,
|
||||
unlockNotificationAudio,
|
||||
type NotificationSoundStyle
|
||||
} from '$lib/utils/audio';
|
||||
import type { Writable } from 'svelte/store';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
import { config, settings, user } from '$lib/stores';
|
||||
import Modal from '$lib/components/common/Modal.svelte';
|
||||
import Switch from '$lib/components/common/Switch.svelte';
|
||||
import SettingsSelect from '$lib/components/common/SettingsSelect.svelte';
|
||||
import Plus from '$lib/components/icons/Plus.svelte';
|
||||
import Play from '$lib/components/icons/Play.svelte';
|
||||
import {
|
||||
createNotificationTarget,
|
||||
deleteNotificationTarget,
|
||||
@@ -26,6 +35,15 @@
|
||||
|
||||
let notificationEnabled = false;
|
||||
let notificationSound = true;
|
||||
let notificationSoundType: NotificationSoundStyle = 'chime';
|
||||
const previewSound = async () => {
|
||||
if (!notificationSound) return;
|
||||
setNotificationSoundEnabled(true);
|
||||
if (!(await playNotificationSound(notificationSoundType))) {
|
||||
toast.error($i18n.t('Unable to play notification sound.'));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let targets: NotificationTarget[] = [];
|
||||
// Keep dynamically translated event keys visible to i18next-parser.
|
||||
// $i18n.t('Chat finished'); $i18n.t('A chat run finished successfully.');
|
||||
@@ -188,6 +206,8 @@
|
||||
onMount(async () => {
|
||||
notificationEnabled = $settings.notificationEnabled ?? false;
|
||||
notificationSound = $settings?.notificationSound ?? true;
|
||||
const savedSound = $settings?.notificationSoundType ?? 'chime';
|
||||
notificationSoundType = notificationSoundStyles.includes(savedSound) ? savedSound : 'chime';
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -213,7 +233,10 @@
|
||||
{$i18n.t('Allow browser notifications for completed responses.')}
|
||||
</p>
|
||||
|
||||
<UserSettingRow let:labelId>
|
||||
<UserSettingRow
|
||||
description={$i18n.t('settings.personal.notifications.notificationSound.description')}
|
||||
let:labelId
|
||||
>
|
||||
<span slot="label">
|
||||
{$i18n.t('settings.personal.notifications.notificationSound.label')}
|
||||
</span>
|
||||
@@ -222,11 +245,46 @@
|
||||
bind:state={notificationSound}
|
||||
ariaLabel={$i18n.t('settings.personal.notifications.notificationSound.label')}
|
||||
on:change={() => {
|
||||
setNotificationSoundEnabled(notificationSound);
|
||||
if (notificationSound) void unlockNotificationAudio();
|
||||
saveSettings({ notificationSound });
|
||||
}}
|
||||
/>
|
||||
</UserSettingRow>
|
||||
|
||||
{#if notificationSound}
|
||||
<UserSettingRow
|
||||
label={$i18n.t('settings.personal.notifications.soundStyle.label')}
|
||||
description={$i18n.t('settings.personal.notifications.soundStyle.description')}
|
||||
let:labelId
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<SettingsSelect
|
||||
id={`${labelId}-control`}
|
||||
aria-labelledby={labelId}
|
||||
bind:value={notificationSoundType}
|
||||
on:change={() => {
|
||||
saveSettings({ notificationSoundType });
|
||||
}}
|
||||
>
|
||||
<option value="chime">{$i18n.t('Chime')}</option>
|
||||
<option value="soft">{$i18n.t('Soft')}</option>
|
||||
<option value="bell">{$i18n.t('Bell')}</option>
|
||||
<option value="tap">{$i18n.t('Tap')}</option>
|
||||
</SettingsSelect>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg text-gray-400 transition-colors duration-75 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300"
|
||||
aria-label={$i18n.t('Preview notification sound')}
|
||||
title={$i18n.t('Preview notification sound')}
|
||||
on:click={previewSound}
|
||||
>
|
||||
<Play className="size-3.5" strokeWidth="2" />
|
||||
</button>
|
||||
</div>
|
||||
</UserSettingRow>
|
||||
{/if}
|
||||
|
||||
{#if canUseWebhooks}
|
||||
<div class="mt-3 flex items-center justify-between">
|
||||
<span class="text-xs font-medium text-gray-700 dark:text-gray-300">
|
||||
|
||||
@@ -406,6 +406,7 @@
|
||||
"Bearer": "",
|
||||
"before": "",
|
||||
"Being lazy": "",
|
||||
"Bell": "Bell",
|
||||
"Binary file — text comparison is unavailable.": "",
|
||||
"Binary file changed": "",
|
||||
"Binary file. Download to open.": "",
|
||||
@@ -500,6 +501,7 @@
|
||||
"Check what is running in this chat.": "",
|
||||
"Checking for updates...": "",
|
||||
"Checkout": "",
|
||||
"Chime": "Chime",
|
||||
"Choose a date range to compare": "",
|
||||
"Choose a model before saving...": "",
|
||||
"Choose a parent page. Subpages move with this page.": "",
|
||||
@@ -2292,6 +2294,7 @@
|
||||
"Preview behavior": "",
|
||||
"Preview failed": "",
|
||||
"Preview gesture": "",
|
||||
"Preview notification sound": "Preview notification sound",
|
||||
"Preview not available": "",
|
||||
"Previous": "",
|
||||
"Previous 30 days": "",
|
||||
@@ -3817,8 +3820,11 @@
|
||||
"settings.personal.interface.widescreenMode.label": "Widescreen Mode",
|
||||
"settings.personal.notifications.addNotificationTarget.label": "Add Notification Target",
|
||||
"settings.personal.notifications.browserNotifications.label": "Browser Notifications",
|
||||
"settings.personal.notifications.notificationSound.description": "Play a sound when a response is ready.",
|
||||
"settings.personal.notifications.notificationSound.label": "Notification Sound",
|
||||
"settings.personal.notifications.notificationTargets.label": "Notification Targets",
|
||||
"settings.personal.notifications.soundStyle.description": "Choose a sound and use the play button to preview it.",
|
||||
"settings.personal.notifications.soundStyle.label": "Notification sound style",
|
||||
"settings.personal.notifications.title": "Notifications",
|
||||
"settings.personal.personalization.clearMemory.label": "Clear memory",
|
||||
"settings.personal.personalization.manageMemories.label": "Manage",
|
||||
@@ -3970,6 +3976,7 @@
|
||||
"Slider": "",
|
||||
"Slim requires external services for embeddings, vector storage, and document extraction. Basic text files can be read locally.": "",
|
||||
"Slim requires external speech providers. Local speech models and audio conversion are unavailable.": "",
|
||||
"Soft": "Soft",
|
||||
"Something went wrong :/": "",
|
||||
"Sonar": "",
|
||||
"Sonar Deep Research": "",
|
||||
@@ -4068,6 +4075,7 @@
|
||||
"Tags": "",
|
||||
"Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting.": "",
|
||||
"Talk to Model": "",
|
||||
"Tap": "Tap",
|
||||
"Tap to interrupt": "",
|
||||
"Target ID": "",
|
||||
"Target ID for notify": "",
|
||||
@@ -4254,6 +4262,7 @@
|
||||
"Unable to load session.": "Unable to load session.",
|
||||
"Unable to load sessions.": "Unable to load sessions.",
|
||||
"Unable to load tools": "",
|
||||
"Unable to play notification sound.": "Unable to play notification sound.",
|
||||
"Unarchive": "",
|
||||
"Unarchive Chat": "",
|
||||
"Unassigned": "",
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { CommentTarget } from '$lib/apis/comments';
|
||||
import type { ModelConfig } from '$lib/apis';
|
||||
import type { Banner } from '$lib/types';
|
||||
import type { Socket } from 'socket.io-client';
|
||||
import type { AudioQueue } from '$lib/utils/audio';
|
||||
import type { AudioQueue, NotificationSoundStyle } from '$lib/utils/audio';
|
||||
import type { I18nOverrides } from '$lib/utils/translationDictionary';
|
||||
|
||||
import emojiShortCodes from '$lib/emoji-shortcodes.json';
|
||||
@@ -210,7 +210,6 @@ export type DesktopEvent =
|
||||
export const desktopEvent: Writable<DesktopEvent | null> = writable(null);
|
||||
|
||||
export const isLastActiveTab = writable(true);
|
||||
export const playingNotificationSound = writable(false);
|
||||
|
||||
export type Model = OpenAIModel | OllamaModel | AgentModel;
|
||||
|
||||
@@ -282,6 +281,7 @@ type Settings = {
|
||||
collapseCodeBlocks?: boolean;
|
||||
expandDetails?: boolean;
|
||||
notificationSound?: boolean;
|
||||
notificationSoundType?: NotificationSoundStyle;
|
||||
notificationSoundAlways?: boolean;
|
||||
stylizedPdfExport?: boolean;
|
||||
notifications?: any;
|
||||
|
||||
@@ -127,3 +127,102 @@ export class AudioQueue {
|
||||
this.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
export const notificationSoundStyles = ['chime', 'soft', 'bell', 'tap'] as const;
|
||||
export type NotificationSoundStyle = (typeof notificationSoundStyles)[number];
|
||||
|
||||
type NotificationTone = {
|
||||
frequency: number;
|
||||
duration: number;
|
||||
volume: number;
|
||||
delay?: number;
|
||||
endFrequency?: number;
|
||||
};
|
||||
|
||||
const notificationTones: Record<NotificationSoundStyle, NotificationTone[]> = {
|
||||
chime: [
|
||||
{ frequency: 659.25, duration: 0.36, volume: 0.08 },
|
||||
{ frequency: 880, duration: 0.48, volume: 0.06, delay: 0.09 }
|
||||
],
|
||||
soft: [
|
||||
{ frequency: 440, duration: 0.3, volume: 0.07 },
|
||||
{ frequency: 660, duration: 0.24, volume: 0.025 }
|
||||
],
|
||||
bell: [
|
||||
{ frequency: 1046.5, duration: 0.6, volume: 0.06 },
|
||||
{ frequency: 2093, duration: 0.24, volume: 0.025 },
|
||||
{ frequency: 2900, duration: 0.13, volume: 0.012 }
|
||||
],
|
||||
tap: [{ frequency: 200, endFrequency: 90, duration: 0.07, volume: 0.16 }]
|
||||
};
|
||||
|
||||
let notificationContext: AudioContext | null = null;
|
||||
let notificationSoundEnabled = true;
|
||||
const notificationVoices = new Set<{ oscillator: OscillatorNode; gain: GainNode }>();
|
||||
|
||||
function stopNotificationVoices() {
|
||||
if (!notificationContext) return;
|
||||
const now = notificationContext.currentTime;
|
||||
for (const { oscillator, gain } of notificationVoices) {
|
||||
gain.gain.cancelScheduledValues(now);
|
||||
gain.gain.setValueAtTime(gain.gain.value, now);
|
||||
gain.gain.linearRampToValueAtTime(0, now + 0.02);
|
||||
oscillator.stop(now + 0.02);
|
||||
}
|
||||
notificationVoices.clear();
|
||||
}
|
||||
|
||||
export function setNotificationSoundEnabled(enabled: boolean) {
|
||||
notificationSoundEnabled = enabled;
|
||||
if (!enabled) stopNotificationVoices();
|
||||
}
|
||||
|
||||
// Unlock inside a user gesture so later background completions can make sound.
|
||||
export async function unlockNotificationAudio(): Promise<boolean> {
|
||||
if (
|
||||
!notificationSoundEnabled ||
|
||||
typeof window === 'undefined' ||
|
||||
navigator.userActivation?.hasBeenActive === false ||
|
||||
!window.AudioContext
|
||||
)
|
||||
return false;
|
||||
try {
|
||||
notificationContext ??= new AudioContext();
|
||||
if (notificationContext.state === 'suspended') await notificationContext.resume();
|
||||
return notificationContext.state === 'running';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function playNotificationSound(
|
||||
style: NotificationSoundStyle = 'chime'
|
||||
): Promise<boolean> {
|
||||
if (!(await unlockNotificationAudio()) || !notificationSoundEnabled || !notificationContext)
|
||||
return false;
|
||||
stopNotificationVoices();
|
||||
const selected = notificationSoundStyles.includes(style) ? style : 'chime';
|
||||
for (const tone of notificationTones[selected]) {
|
||||
const oscillator = notificationContext.createOscillator();
|
||||
const gain = notificationContext.createGain();
|
||||
const start = notificationContext.currentTime + (tone.delay ?? 0);
|
||||
oscillator.frequency.setValueAtTime(tone.frequency, start);
|
||||
if (tone.endFrequency) {
|
||||
oscillator.frequency.exponentialRampToValueAtTime(tone.endFrequency, start + tone.duration);
|
||||
}
|
||||
gain.gain.setValueAtTime(0, start);
|
||||
gain.gain.linearRampToValueAtTime(tone.volume, start + (selected === 'soft' ? 0.03 : 0.005));
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, start + tone.duration);
|
||||
oscillator.connect(gain).connect(notificationContext.destination);
|
||||
const voice = { oscillator, gain };
|
||||
notificationVoices.add(voice);
|
||||
oscillator.onended = () => {
|
||||
oscillator.disconnect();
|
||||
gain.disconnect();
|
||||
notificationVoices.delete(voice);
|
||||
};
|
||||
oscillator.start(start);
|
||||
oscillator.stop(start + tone.duration + 0.02);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
+19
-10
@@ -1,5 +1,10 @@
|
||||
<script>
|
||||
import { setTheme } from '$lib/utils/theme';
|
||||
import {
|
||||
playNotificationSound,
|
||||
setNotificationSoundEnabled,
|
||||
unlockNotificationAudio
|
||||
} from '$lib/utils/audio';
|
||||
import CommentsHost from '$lib/components/comments/CommentsHost.svelte';
|
||||
import { io } from 'socket.io-client';
|
||||
import { spring } from 'svelte/motion';
|
||||
@@ -31,7 +36,6 @@
|
||||
isApp,
|
||||
appInfo,
|
||||
toolServers,
|
||||
playingNotificationSound,
|
||||
channels,
|
||||
channelId,
|
||||
channelRequestQueues,
|
||||
@@ -803,15 +807,10 @@
|
||||
if (done) {
|
||||
if (
|
||||
($settings?.notificationSound ?? true) &&
|
||||
($settings?.notificationSoundAlways ?? false)
|
||||
($settings?.notificationSoundAlways ?? false) &&
|
||||
$isLastActiveTab
|
||||
) {
|
||||
playingNotificationSound.set(true);
|
||||
|
||||
const audio = new Audio(`/audio/notification.mp3`);
|
||||
audio.play().finally(() => {
|
||||
// Ensure the global state is reset after the sound finishes
|
||||
playingNotificationSound.set(false);
|
||||
});
|
||||
void playNotificationSound($settings?.notificationSoundType);
|
||||
}
|
||||
|
||||
if ($isLastActiveTab) {
|
||||
@@ -836,7 +835,8 @@
|
||||
goto(`/c/${event.chat_id}`);
|
||||
},
|
||||
content: contentPreview,
|
||||
title: displayTitle
|
||||
title: displayTitle,
|
||||
playSound: !($settings?.notificationSoundAlways ?? false)
|
||||
},
|
||||
duration: 15000,
|
||||
unstyled: true
|
||||
@@ -1491,12 +1491,21 @@
|
||||
}
|
||||
}
|
||||
|
||||
$: if (typeof window !== 'undefined')
|
||||
setNotificationSoundEnabled($settings?.notificationSound ?? true);
|
||||
|
||||
const unlockNotificationSound = () => {
|
||||
if ($settings?.notificationSound ?? true) void unlockNotificationAudio();
|
||||
};
|
||||
|
||||
onDestroy(() => {
|
||||
stopTether();
|
||||
bc.close();
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:window on:click={unlockNotificationSound} on:keydown={unlockNotificationSound} />
|
||||
|
||||
<svelte:head>
|
||||
<!-- LICENSE covers this Open WebUI branding surface, including name, logo,
|
||||
visual, textual, symbolic identifiers, metadata, and surrounding UI.
|
||||
|
||||
Reference in new issue
Block a user