Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions src/lib/components/DownloadSelector.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ A component for verse-on-image providing a dropdown where you can choose to down
-->

<script lang="ts">
import { convertStyle, s, t, themeColors } from '$lib/data/stores';
import { getPositioningCSS, t, themeColors } from '$lib/data/stores';
import { ImageIcon, VideoIcon } from '$lib/icons';
import Modal from './Modal.svelte';

Expand All @@ -15,18 +15,14 @@ A component for verse-on-image providing a dropdown where you can choose to down
export function showModal() {
modalThis.showModal();
}
const positioningCSS = $derived(
'position:absolute; top:' +
(Number(vertOffset.replace('rem', '')) + 1) +
'rem; inset-inline-end:1rem; width:auto;'
);
const positioningCSS = $derived(getPositioningCSS(vertOffset, 'top'));
</script>

<!-- svelte-ignore a11y_consider_explicit_label -->
<Modal
bind:this={modalThis}
id={modalId}
styling="background-color:{$themeColors['PopupBackgroundColor']}; {positioningCSS}"
styling="background-color:{$themeColors['PopupBackgroundColor']}; width:auto; {positioningCSS}"
>
<div class="grid gap-2 m-2">
<button
Expand Down
9 changes: 1 addition & 8 deletions src/lib/components/PlanStopDialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Plan Stop Modal Dialog component.
import { resolve } from '$lib/utils/paths';
import Modal from './Modal.svelte';

let { planId = $bindable(undefined), vertOffset = '1rem' } = $props();
let { planId = $bindable(undefined) } = $props();

const modalId = 'planStopDialog';
let modal: Modal | undefined = $state(undefined);
Expand All @@ -31,13 +31,6 @@ Plan Stop Modal Dialog component.
goto(resolve(`/plans`));
});
}

//The positioningCSS positions the modal 1rem below the navbar and 1rem from the right edge of the screen (on mobile it will be centered)
const positioningCSS = $derived(
'position:absolute; top:' +
(Number(vertOffset.replace('rem', '')) + 1) +
'rem; inset-inline-end:1rem;'
);
</script>

<Modal bind:this={modal} id={modalId}>
Expand Down
254 changes: 254 additions & 0 deletions src/lib/components/ShareSelector.svelte
Comment thread
TheNonPirate marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
<!--
@component
A component providing a dropdown where you can choose to download audio or video for selected text
-->

<script lang="ts">
import { scriptureConfig } from '$assets/config';
import { getBook, logShareContent } from '$lib/data/analytics';
import { getAudioSourceInfo } from '$lib/data/audio';
import { shareText } from '$lib/data/share';
import { getPositioningCSS, refs, selectedVerses, t } from '$lib/data/stores';
import { AudioIcon } from '$lib/icons';
import FormatAlignLeftIcon from '$lib/icons/image/FormatAlignLeftIcon.svelte';
import {
AudioBufferSource,
BufferTarget,
canEncodeAudio,
Mp4OutputFormat,
Output,
WavOutputFormat,
WebMOutputFormat
} from 'mediabunny';
import type { AudioEncodingConfig } from 'mediabunny';
import Modal from './Modal.svelte';

let { vertOffset = '2rem' } = $props();
async function shareSelectedText() {
const book = $selectedVerses[0].book;
const reference = selectedVerses.getCompositeReference();
const text = await selectedVerses.getCompositeText();
const bookCol = $selectedVerses[0].collection;
const fullBook = getBook({ collection: bookCol, book: book });
const bookAbbrev = fullBook?.abbreviation ?? fullBook?.name;
const copyShareMessage = scriptureConfig.bookCollections?.find(
(x) => x.id === bookCol
)?.copyShareMessage;
shareText(
scriptureConfig.name ?? '',
text + '\n' + reference + (copyShareMessage ? '\n' + copyShareMessage : ''),
book + '.txt'
);
logShareContent('Text', bookCol, bookAbbrev ?? '', reference);
}
async function shareAudio() {
const reference = selectedVerses.getCompositeReference();
const audioCtx = new AudioContext();
try {
const audioConfig: AudioEncodingConfig = await pickSupportedAudioConfig();
const outputFormat =
audioConfig.codec === 'aac'
? { name: 'mp4', format: new Mp4OutputFormat() }
: audioConfig.codec === 'opus'
? { name: 'webm', format: new WebMOutputFormat() }
: { name: 'wav', format: new WavOutputFormat() };
const output = new Output({
format: outputFormat.format,
target: new BufferTarget()
});

const audioSourceInfo = await getAudioSourceInfo({
collection: $refs.collection,
book: $refs.book,
chapter: $refs.chapter
});
if (!audioSourceInfo?.source) {
throw new Error('No audio source available for this chapter');
}

const audioSource = new AudioBufferSource(audioConfig);
output.addAudioTrack(audioSource);
await output.start();
let isRemote;

try {
let url = new URL(audioSourceInfo.source);
isRemote = url.protocol === 'http:' || url.protocol === 'https:';
} catch (_) {
isRemote = false;
}
if (isRemote) {
try {
let verses = await selectedVerses.getCompositeText();
await navigator.share({
title: reference,
text: verses,
url: audioSourceInfo.source
});
return;
} catch (error) {
if ((error as { name?: string })?.name === 'AbortError') {
return; // user intentionally dismissed native share UI
}
console.error('Error sharing: ', error);
}

// if we're here, we failed to share, so we'll try to use the download link. This generally is just going to open the URL rather than downloading it.
const anchor = document.createElement('a');
anchor.href = audioSourceInfo.source;
anchor.download = '';
anchor.click();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
} else {
const audioBlob = await fetch(audioSourceInfo?.source).then((r) => r.blob());
const audioBuffer = await audioCtx.decodeAudioData(await audioBlob.arrayBuffer());

const sampleRate = audioBuffer.sampleRate;

for (let i = 0; i < $selectedVerses.length; i++) {
let startFrame = 0;
let endFrame = 0;
for (var j = 0; j < (audioSourceInfo?.timing?.length || 0); j++) {
const timing = audioSourceInfo?.timing?.[j];
const verse = timing?.tag?.replace(/\D/g, '');
if (verse === $selectedVerses[i].verse) {
if (!startFrame) {
startFrame = Math.floor((timing?.starttime || 0) * sampleRate);
endFrame = Math.floor((timing?.endtime || 0) * sampleRate);
} else {
endFrame = Math.floor((timing?.endtime || 0) * sampleRate);
}
}
}
if (endFrame <= startFrame) {
console.warn(
`No timing found for verse ${$selectedVerses[i].verse}, skipping`
);
continue;
}
const trimmedBuffer = audioCtx.createBuffer(
audioBuffer.numberOfChannels,
endFrame - startFrame,
sampleRate
);

for (let ch = 0; ch < audioBuffer.numberOfChannels; ch++) {
const src = audioBuffer.getChannelData(ch);
const dst = trimmedBuffer.getChannelData(ch);
dst.set(src.slice(startFrame, endFrame));
}

await audioSource.add(trimmedBuffer);
}
await output.finalize();

const buffer = output.target.buffer as BlobPart;
const blob = new Blob([buffer], {
type: 'audio/' + outputFormat.name
});
const filename = reference + '.' + outputFormat.name;
const file = new File([blob], filename, {
type: 'audio/' + outputFormat.name
});
try {
if (
navigator.share &&
navigator.canShare &&
navigator.canShare({ files: [file] })
) {
let verses = await selectedVerses.getCompositeText();
const shareData: ShareData = {
title: reference,
text: verses,
files: [file]
};

await navigator.share(shareData);
return;
}
} catch (error) {
if ((error as { name?: string })?.name === 'AbortError') {
return; // user intentionally dismissed native share UI
}
console.error('Error sharing: ', error);
}

// if we're here, we failed to share, so we'll try to use the download link
const url = URL.createObjectURL(file);

const anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
anchor.click();

URL.revokeObjectURL(url);
}
} catch (error) {
console.error('Error generating audio export:', error);
} finally {
await audioCtx?.close();
}
}
async function pickSupportedAudioConfig() {
const candidates: AudioEncodingConfig[] = [
{ codec: 'aac', bitrate: 128000 },
{ codec: 'aac', bitrate: 96000 },
{ codec: 'aac', bitrate: 64000 },
{
codec: 'opus',
bitrate: 96000
},
{ codec: 'pcm-f32' },
{ codec: 'pcm-s24' },
{ codec: 'pcm-s16' }
];

for (const cfg of candidates) {
if (await canEncodeAudio(cfg.codec, cfg)) {
return cfg;
}
}

throw new Error('No supported audio configuration found.');
} //This is used to determine a supported audio configuration. It first tries AAC, but then falls back to opus if AAC isn't supported. This is a duplicate of the function with the same name in VerseOnImage.svelte, so maybe it should be moved to somewhere that exports it for any place that needs it to use it?
let modalId = 'shareSelector';
let modalThis: Modal;
export function showModal(shareTextOnly: boolean) {
if (shareTextOnly) {
shareSelectedText();
} else {
modalThis.showModal();
}
}
const positioningCSS = $derived(getPositioningCSS(vertOffset, 'bottom'));
</script>

<!-- svelte-ignore a11y_consider_explicit_label -->
<Modal
bind:this={modalThis}
id={modalId}
styling="background-color:red; box-shadow:none; padding:0; width:auto; {positioningCSS}"
>
<div class="grid">
<button
class="dy-btn flex items-center justify-center rounded-none"
onclick={() => shareSelectedText()}
>
<FormatAlignLeftIcon />
{$t['Share_Text']}
</button>
<button
class="dy-btn flex items-center justify-center rounded-none"
onclick={() => shareAudio()}
>
<AudioIcon.Volume />
{$t['Share_Audio']}
</button>
<!--<button

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this commented out?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's commented out because video download has not yet been implemented, but that is where the button would go if it was implemented.

class="dy-btn flex items-center justify-center rounded-none"
onclick={() => downloadVideo()}
>
<VideoIcon />
{$t['Share_Video']}
</button>-->
</div>
</Modal>
7 changes: 2 additions & 5 deletions src/lib/components/TextAppearanceSelector.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ The navbar component. We have sliders that update reactively to both font size a
contentsFontSize,
currentFont,
fontChoices,
getPositioningCSS,
language,
languages,
modal,
Expand Down Expand Up @@ -67,11 +68,7 @@ The navbar component. We have sliders that update reactively to both font size a

const contentsMode = $derived(options?.contentsMode ?? false);
//The positioningCSS positions the modal 1rem below the navbar and 1rem from the right edge of the screen (on mobile it will be centered)
const positioningCSS = $derived(
'position:absolute; top:' +
(Number(vertOffset.replace('rem', '')) + 1) +
'rem; inset-inline-end:1rem;'
);
const positioningCSS = $derived(getPositioningCSS(vertOffset, 'top'));
const barColor = $derived($themeColors['SliderBarColor']);
const progressColor = $derived($themeColors['SliderProgressColor']);
const _showFontSize = showFontSize();
Expand Down
32 changes: 7 additions & 25 deletions src/lib/components/TextSelectionToolbar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,17 @@
@component
Taken from modifying a copy of the AudioBar.svelte file
Enables users to copy, highlight, bookmark, share, and annotate selected verses.
TODO:
- Implement functionality for
-> Share
-> Play
-> Play Repeat
-> Verse On Image
Comment thread
TheNonPirate marked this conversation as resolved.
- Add note dialog
- Add highlight colors
-->
<script lang="ts">
import { goto } from '$app/navigation';
import { scriptureConfig } from '$assets/config';
import { getBook, logShareContent } from '$lib/data/analytics';
import { playVerses } from '$lib/data/audio';
import { addBookmark, findBookmark, removeBookmark } from '$lib/data/bookmarks';
import { addHighlights, removeHighlights } from '$lib/data/highlights';
import { shareText } from '$lib/data/share';
import {
audioActive,
modal,
ModalType,
refs,
s,
selectedVerses,
Expand Down Expand Up @@ -136,21 +128,11 @@ TODO:
}

async function shareSelectedText() {
const book = $selectedVerses[0].book;
const reference = selectedVerses.getCompositeReference();
const text = await selectedVerses.getCompositeText();
const bookCol = $selectedVerses[0].collection;
const fullBook = getBook({ collection: bookCol, book: book });
const bookAbbrev = fullBook?.abbreviation ?? fullBook?.name;
const copyShareMessage = scriptureConfig.bookCollections?.find(
(x) => x.id === bookCol
)?.copyShareMessage;
shareText(
scriptureConfig.name ?? '',
text + '\n' + reference + (copyShareMessage ? '\n' + copyShareMessage : ''),
book + '.txt'
);
logShareContent('Text', bookCol, bookAbbrev ?? '', reference);
if ($refs.hasAudio?.timingFile) {
modal.open(ModalType.Share);
} else {
modal.open(ModalType.Share, true); //Just share the text rather than giving the user a choice about how to share it
}
}

const backgroundColor = $derived($s['ui.bar.text-select']['background-color']);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/VerseOnImage.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,7 @@ The verse on image component.
downloadProgress = 0;
await audioCtx?.close();
}
} //Most of this is AI-generated, so serious testing is needed. I've done a lot of testing, but it would be good to make sure there aren't subtle problems with this code.
}

// EditorTabs centering feature:

Expand Down
Loading