beta audio capabilities

This commit is contained in:
adueck 2023-12-04 14:56:52 +04:00
parent 40c514deac
commit 77018ef252
3 changed files with 439 additions and 329 deletions

View File

@ -7,37 +7,39 @@
*/ */
import ExtraEntryInfo from "../components/ExtraEntryInfo"; import ExtraEntryInfo from "../components/ExtraEntryInfo";
import classNames from "classnames"; import classNames from "classnames";
import { import { Types as T, InlinePs } from "@lingdocs/ps-react";
Types as T,
InlinePs,
} from "@lingdocs/ps-react";
function Entry({ entry, textOptions, nonClickable, isolateEntry }: { function Entry({
entry: T.DictionaryEntry, entry,
textOptions: T.TextOptions, textOptions,
nonClickable?: boolean, nonClickable,
isolateEntry?: (ts: number) => void, isolateEntry,
}: {
entry: T.DictionaryEntry;
textOptions: T.TextOptions;
nonClickable?: boolean;
isolateEntry?: (ts: number) => void;
}) { }) {
return ( return (
<div <div
className={classNames("entry", { clickable: !nonClickable })} className={classNames("entry", { clickable: !nonClickable })}
onClick={(!nonClickable && isolateEntry) ? () => isolateEntry(entry.ts) : undefined} onClick={
data-testid="entry" !nonClickable && isolateEntry ? () => isolateEntry(entry.ts) : undefined
> }
<div> data-testid="entry"
<strong> >
<InlinePs opts={textOptions}>{{ p: entry.p, f: entry.f }}</InlinePs> <div>
</strong> <strong>
{` `} <InlinePs opts={textOptions}>{{ p: entry.p, f: entry.f }}</InlinePs>
<em>{entry.c}</em> </strong>
</div> {` `}
<ExtraEntryInfo <em>{entry.c}</em>
entry={entry} {entry.a && !nonClickable && <i className="ml-2 fas fa-volume-down" />}
textOptions={textOptions} </div>
/> <ExtraEntryInfo entry={entry} textOptions={textOptions} />
<div className="entry-definition">{entry.e}</div> <div className="entry-definition">{entry.e}</div>
</div> </div>
); );
}; }
export default Entry; export default Entry;

View File

@ -0,0 +1,13 @@
export default function playStorageAudio(ts: number, callback: () => void) {
if (!ts) return;
let audio = new Audio(`https://storage.lingdocs.com/${ts}.mp3`);
audio.addEventListener("ended", () => {
callback();
audio.remove();
audio.srcObject = null;
});
audio.play().catch((e) => {
console.error(e);
alert("Error playing audio - Connect to the internet and try again");
});
}

View File

@ -8,334 +8,429 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { import {
VPExplorer, VPExplorer,
InflectionsTable, InflectionsTable,
inflectWord, inflectWord,
InlinePs, InlinePs,
Types as T, Types as T,
typePredicates as tp, typePredicates as tp,
getInflectionPattern, getInflectionPattern,
HumanReadableInflectionPattern, HumanReadableInflectionPattern,
} from "@lingdocs/ps-react"; } from "@lingdocs/ps-react";
import { import { submissionBase, addSubmission } from "../lib/submissions";
submissionBase,
addSubmission,
} from "../lib/submissions";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import Entry from "../components/Entry"; import Entry from "../components/Entry";
import Results from "../screens/Results"; import Results from "../screens/Results";
import WordlistWordEditor from "../components/WordlistWordEditor"; import WordlistWordEditor from "../components/WordlistWordEditor";
import { import {
addToWordlist, addToWordlist,
deleteWordFromWordlist, deleteWordFromWordlist,
hasAttachment, hasAttachment,
} from "../lib/wordlist-database"; } from "../lib/wordlist-database";
import { wordlistEnabled } from "../lib/level-management"; import { wordlistEnabled } from "../lib/level-management";
import AudioPlayButton from "../components/AudioPlayButton"; import AudioPlayButton from "../components/AudioPlayButton";
import { Helmet } from "react-helmet"; import { Helmet } from "react-helmet";
import { Modal } from "react-bootstrap"; import { Modal } from "react-bootstrap";
import { getTextOptions } from "../lib/get-text-options"; import { getTextOptions } from "../lib/get-text-options";
import { import { entryFeeder } from "../lib/dictionary";
entryFeeder, import { State, DictionaryAPI } from "../types/dictionary-types";
} from "../lib/dictionary"; import playStorageAudio from "../components/PlayStorageAudio";
import {
State,
DictionaryAPI,
} from "../types/dictionary-types";
function IsolatedEntry({ state, dictionary, isolateEntry }: { function IsolatedEntry({
state: State, state,
dictionary: DictionaryAPI, dictionary,
isolateEntry: (ts: number) => void, isolateEntry,
}: {
state: State;
dictionary: DictionaryAPI;
isolateEntry: (ts: number) => void;
}) { }) {
const [exploded, setExploded] = useState<boolean>(false); const [exploded, setExploded] = useState<boolean>(false);
const [editing, setEditing] = useState<boolean>(false); const [playing, setPlaying] = useState<boolean>(false);
const [comment, setComment] = useState<string>(""); const [editing, setEditing] = useState<boolean>(false);
const [editSubmitted, setEditSubmitted] = useState<boolean>(false); const [comment, setComment] = useState<string>("");
const [showingDeleteWarning, setShowingDeleteWarning] = useState<boolean>(false); const [editSubmitted, setEditSubmitted] = useState<boolean>(false);
const [showClipped, setShowClipped] = useState<string>(""); const [showingDeleteWarning, setShowingDeleteWarning] =
useEffect(() => { useState<boolean>(false);
setEditing(false); const [showClipped, setShowClipped] = useState<string>("");
setComment(""); useEffect(() => {
setEditSubmitted(false); setEditing(false);
}, [state]); setComment("");
function flashClippedMessage(m: string) { setEditSubmitted(false);
setShowClipped(m); setPlaying(false);
setTimeout(() => { }, [state]);
setShowClipped(""); function flashClippedMessage(m: string) {
}, 1250); setShowClipped(m);
setTimeout(() => {
setShowClipped("");
}, 1250);
}
const wordlistWord = state.wordlist.find(
(w) => w.entry.ts === state.isolatedEntry?.ts
);
const textOptions = getTextOptions(state);
function submitEdit() {
if (!state.isolatedEntry) return;
if (!state.user) return;
addSubmission(
{
...submissionBase(state.user),
type: "edit suggestion",
entry: state.isolatedEntry,
comment,
},
state.user
);
setEditing(false);
setComment("");
setEditSubmitted(true);
}
function handleAddToWordlist() {
if (!state.isolatedEntry) return;
const toAdd = {
entry: state.isolatedEntry,
notes: "",
};
addToWordlist(toAdd);
}
function handleDeleteFromWordlist() {
if (!state.isolatedEntry) return;
if (!wordlistWord) return;
setShowingDeleteWarning(false);
deleteWordFromWordlist(wordlistWord._id);
}
const entry = state.isolatedEntry;
if (!entry) {
return (
<div className="text-center">
<h4 className="mb-4 mt-4">Word not found</h4>
<h5>
<Link to="/">Home</Link>
</h5>
</div>
);
}
const complement = entry.l ? dictionary.findOneByTs(entry.l) : undefined;
const relatedEntries = dictionary.findRelatedEntries(entry);
const inf = ((): T.InflectorOutput | false => {
try {
return inflectWord(entry);
} catch (e) {
console.error("error inflecting entry", entry);
return false;
} }
const wordlistWord = state.wordlist.find((w) => w.entry.ts === state.isolatedEntry?.ts); })();
const textOptions = getTextOptions(state); const isVerbEntry = tp.isVerbEntry({ entry, complement });
function submitEdit() { function DisplayVPExplorer(props: {
if (!state.isolatedEntry) return; entry: T.DictionaryEntry;
if (!state.user) return; complement: T.DictionaryEntry | undefined;
addSubmission({ }) {
...submissionBase(state.user), try {
type: "edit suggestion", return (
entry: state.isolatedEntry, <VPExplorer
comment, verb={{
}, state.user); // TODO: CLEAN THIS UP!
setEditing(false); // @ts-ignore
setComment(""); entry: props.entry,
setEditSubmitted(true); complement: props.complement,
}}
opts={textOptions}
entryFeeder={entryFeeder}
handleLinkClick={isolateEntry}
/>
);
} catch (e) {
console.error("error rendering VPExplorer", e);
return null;
} }
function handleAddToWordlist() { }
if (!state.isolatedEntry) return; function handleClipId() {
const toAdd = { if (!entry) return;
entry: state.isolatedEntry, navigator.clipboard.writeText(entry.ts.toString());
notes: "", flashClippedMessage("word id copied to clipboard");
}; }
addToWordlist(toAdd); function handleClipEntry() {
} if (!entry) return;
function handleDeleteFromWordlist() { navigator.clipboard.writeText(JSON.stringify(entry));
if (!state.isolatedEntry) return; flashClippedMessage("entry data copied to clipboard");
if (!wordlistWord) return; }
setShowingDeleteWarning(false); function handlePlayStorageAudio() {
deleteWordFromWordlist(wordlistWord._id); if (!entry) return;
} setPlaying(true);
const entry = state.isolatedEntry; playStorageAudio(entry.ts, () => {
if (!entry) { setPlaying(false);
return <div className="text-center"> });
<h4 className="mb-4 mt-4">Word not found</h4> }
<h5><Link to="/">Home</Link></h5> return (
</div>; <div className="wide-width-limiter">
} <Helmet>
const complement = entry.l <title>{entry.p} - LingDocs Pashto Dictionary</title>
? dictionary.findOneByTs(entry.l) </Helmet>
: undefined; <div className="row">
const relatedEntries = dictionary.findRelatedEntries(entry); <div className="col-8">
const inf = ((): T.InflectorOutput | false => { <Entry
try { nonClickable
return inflectWord(entry); entry={exploded ? explodeEntry(entry) : entry}
} catch (e) { textOptions={textOptions}
console.error("error inflecting entry", entry); isolateEntry={isolateEntry}
return false; />
}
})();
const isVerbEntry = tp.isVerbEntry({ entry, complement });
function DisplayVPExplorer(props: {
entry: T.DictionaryEntry,
complement: T.DictionaryEntry | undefined,
}) {
try {
return <VPExplorer
verb={{
// TODO: CLEAN THIS UP!
// @ts-ignore
entry: props.entry,
complement: props.complement,
}}
opts={textOptions}
entryFeeder={entryFeeder}
handleLinkClick={isolateEntry}
/>
} catch (e) {
console.error("error rendering VPExplorer", e);
return null;
}
}
function handleClipId() {
if (!entry) return
navigator.clipboard.writeText(entry.ts.toString());
flashClippedMessage("word id copied to clipboard");
}
function handleClipEntry() {
if (!entry) return
navigator.clipboard.writeText(JSON.stringify(entry));
flashClippedMessage("entry data copied to clipboard");
}
return <div className="wide-width-limiter">
<Helmet>
<title>{entry.p} - LingDocs Pashto Dictionary</title>
</Helmet>
<div className="row">
<div className="col-8">
<Entry
nonClickable
entry={exploded ? explodeEntry(entry) : entry}
textOptions={textOptions}
isolateEntry={isolateEntry}
/>
</div>
<div className="col-4">
<div className="d-flex flex-row justify-content-end">
<div
className="clickable mr-3"
onClick={() => setExploded(os => !os)}
>
<i className={`fas fa-${exploded ? "compress" : "expand"}-alt`} />
</div>
<div className="clickable mr-3" onClick={handleClipId}>
<i className="fas fa-tag"></i>
</div>
{state.user && state.user.level === "editor" && <>
<div className="clickable mr-3" onClick={handleClipEntry}>
<i className="fas fa-code"></i>
</div>
<Link to={`/edit?id=${entry.ts}`} className="plain-link">
<div
className="clickable mr-3"
data-testid="finalEditEntryButton"
>
<i className="fa fa-gavel" />
</div>
</Link>
</>}
{state.user && <>
<div
className="clickable mr-3"
data-testid="editEntryButton"
onClick={() => setEditing(os => !os)}
>
<i className="fa fa-pen" />
</div>
{wordlistEnabled(state.user) && <div
className="clickable"
data-testid={wordlistWord ? "fullStarButton" : "emptyStarButton"}
onClick={wordlistWord
? () => setShowingDeleteWarning(true)
: () => handleAddToWordlist()
}
>
<i className={`fa${wordlistWord ? "s" : "r"} fa-star fa-lg`}/>
</div>}
</>}
</div>
</div>
</div> </div>
{wordlistWord && <> <div className="col-4">
{hasAttachment(wordlistWord, "audio") && <AudioPlayButton word={wordlistWord} />} <div className="d-flex flex-row justify-content-end">
<WordlistWordEditor word={wordlistWord} /> {entry.a && (
</>} <div className="clickable mr-3" onClick={handlePlayStorageAudio}>
{editing && <i
<div className="mb-3"> className={`fas fa-lg fa-volume-${playing ? "down" : "off"}`}
<div className="form-group" style={{ maxWidth: "500px" }}> />
<label htmlFor="editSuggestionForm">Suggest correction/edit:</label> </div>
<input )}
type="text" <div
className="form-control" className="clickable mr-3"
id="editSuggestionForm" onClick={() => setExploded((os) => !os)}
data-lpignore="true" >
value={comment} <i className={`fas fa-${exploded ? "compress" : "expand"}-alt`} />
onChange={(e) => setComment(e.target.value)}
/>
</div>
<div className="btn-group">
<button
type="button"
className="btn btn-outline-secondary"
onClick={comment ? submitEdit : () => null}
data-testid="editWordSubmitButton"
>
Submit
</button>
<button
type="button"
className="btn btn-outline-secondary"
onClick={() => { setEditing(false); setComment("") }}
data-testid="editWordCancelButton"
>
Cancel
</button>
</div>
</div> </div>
} <div className="clickable mr-3" onClick={handleClipId}>
{editSubmitted && <p>Thank you for your help!</p>} <i className="fas fa-tag"></i>
{inf && <> </div>
{inf.inflections && (() => { {state.user && state.user.level === "editor" && (
const pattern = getInflectionPattern( <>
// @ts-ignore <div className="clickable mr-3" onClick={handleClipEntry}>
entry <i className="fas fa-code"></i>
); </div>
return <div> <Link to={`/edit?id=${entry.ts}`} className="plain-link">
<a href={`https://grammar.lingdocs.com/inflection/inflection-patterns/${inflectionSubUrl(pattern)}`} rel="noreferrer" target="_blank"> <div
<div className="badge bg-light mb-2">Inflection pattern {HumanReadableInflectionPattern(pattern, textOptions)} className="clickable mr-3"
</div> data-testid="finalEditEntryButton"
</a> >
<InflectionsTable inf={inf.inflections} textOptions={textOptions} /> <i className="fa fa-gavel" />
</div>; </div>
</Link>
</>
)}
{state.user && (
<>
<div
className="clickable mr-3"
data-testid="editEntryButton"
onClick={() => setEditing((os) => !os)}
>
<i className="fa fa-pen" />
</div>
{wordlistEnabled(state.user) && (
<div
className="clickable"
data-testid={
wordlistWord ? "fullStarButton" : "emptyStarButton"
}
onClick={
wordlistWord
? () => setShowingDeleteWarning(true)
: () => handleAddToWordlist()
}
>
<i
className={`fa${wordlistWord ? "s" : "r"} fa-star fa-lg`}
/>
</div>
)}
</>
)}
</div>
</div>
</div>
{wordlistWord && (
<>
{hasAttachment(wordlistWord, "audio") && (
<AudioPlayButton word={wordlistWord} />
)}
<WordlistWordEditor word={wordlistWord} />
</>
)}
{editing && (
<div className="mb-3">
<div className="form-group" style={{ maxWidth: "500px" }}>
<label htmlFor="editSuggestionForm">Suggest correction/edit:</label>
<input
type="text"
className="form-control"
id="editSuggestionForm"
data-lpignore="true"
value={comment}
onChange={(e) => setComment(e.target.value)}
/>
</div>
<div className="btn-group">
<button
type="button"
className="btn btn-outline-secondary"
onClick={comment ? submitEdit : () => null}
data-testid="editWordSubmitButton"
>
Submit
</button>
<button
type="button"
className="btn btn-outline-secondary"
onClick={() => {
setEditing(false);
setComment("");
}}
data-testid="editWordCancelButton"
>
Cancel
</button>
</div>
</div>
)}
{editSubmitted && <p>Thank you for your help!</p>}
{inf && (
<>
{inf.inflections &&
(() => {
const pattern = getInflectionPattern(
// @ts-ignore
entry
);
return (
<div>
<a
href={`https://grammar.lingdocs.com/inflection/inflection-patterns/${inflectionSubUrl(
pattern
)}`}
rel="noreferrer"
target="_blank"
>
<div className="badge bg-light mb-2">
Inflection pattern{" "}
{HumanReadableInflectionPattern(pattern, textOptions)}
</div>
</a>
<InflectionsTable
inf={inf.inflections}
textOptions={textOptions}
/>
</div>
);
})()} })()}
{"plural" in inf && inf.plural !== undefined && <div> {"plural" in inf && inf.plural !== undefined && (
<h5>Plural</h5> <div>
<InflectionsTable inf={inf.plural} textOptions={textOptions} /> <h5>Plural</h5>
</div>} <InflectionsTable inf={inf.plural} textOptions={textOptions} />
{"bundledPlural" in inf && inf.bundledPlural !== undefined && <div> </div>
<h5>Bundled Plural</h5> )}
<InflectionsTable inf={inf.bundledPlural} textOptions={textOptions} /> {"bundledPlural" in inf && inf.bundledPlural !== undefined && (
</div>} <div>
{"arabicPlural" in inf && inf.arabicPlural !== undefined && <div> <h5>Bundled Plural</h5>
<h5>Arabic Plural</h5> <InflectionsTable
<InflectionsTable inf={inf.arabicPlural} textOptions={textOptions} /> inf={inf.bundledPlural}
</div>} textOptions={textOptions}
</>} />
{isVerbEntry && <div className="pb-4"> </div>
<DisplayVPExplorer entry={entry} complement={complement} /> )}
</div>} {"arabicPlural" in inf && inf.arabicPlural !== undefined && (
{showClipped && <div className="alert alert-primary text-center" role="alert" style={{ <div>
<h5>Arabic Plural</h5>
<InflectionsTable
inf={inf.arabicPlural}
textOptions={textOptions}
/>
</div>
)}
</>
)}
{isVerbEntry && (
<div className="pb-4">
<DisplayVPExplorer entry={entry} complement={complement} />
</div>
)}
{showClipped && (
<div
className="alert alert-primary text-center"
role="alert"
style={{
position: "fixed", position: "fixed",
top: "30%", top: "30%",
left: "50%", left: "50%",
transform: "translate(-50%, -50%)", transform: "translate(-50%, -50%)",
zIndex: 9999999999999, zIndex: 9999999999999,
}}> }}
{showClipped}
</div>}
{!!(relatedEntries && relatedEntries.length) ? <>
<h4 style={{ marginTop: isVerbEntry ? "10rem" : "5rem" }}>Related Words</h4>
<Results
state={{ ...state, results: relatedEntries }}
isolateEntry={isolateEntry}
handleInflectionSearch={() => null}
/>
</> : <div style={{ height: "500px" }} />}
<Modal
show={showingDeleteWarning}
onHide={() => setShowingDeleteWarning(false)}
animation={false}
> >
<Modal.Header closeButton> {showClipped}
<Modal.Title>Delete from wordlist?</Modal.Title> </div>
</Modal.Header> )}
<Modal.Body>Delete <InlinePs
opts={textOptions} {!!(relatedEntries && relatedEntries.length) ? (
>{{ p: entry.p, f: entry.f }}</InlinePs> from your wordlist? <>
</Modal.Body> <h4 style={{ marginTop: isVerbEntry ? "10rem" : "5rem" }}>
<Modal.Footer> Related Words
<button type="button" className="btn btn-secorndary clb" onClick={() => setShowingDeleteWarning(false)}> </h4>
Cancel <Results
</button> state={{ ...state, results: relatedEntries }}
<button type="button" data-testid="confirmDeleteFromWordlist" className="btn btn-primary clb" onClick={handleDeleteFromWordlist}> isolateEntry={isolateEntry}
Delete handleInflectionSearch={() => null}
</button> />
</Modal.Footer> </>
</Modal> ) : (
</div>; <div style={{ height: "500px" }} />
)}
<Modal
show={showingDeleteWarning}
onHide={() => setShowingDeleteWarning(false)}
animation={false}
>
<Modal.Header closeButton>
<Modal.Title>Delete from wordlist?</Modal.Title>
</Modal.Header>
<Modal.Body>
Delete{" "}
<InlinePs opts={textOptions}>{{ p: entry.p, f: entry.f }}</InlinePs>{" "}
from your wordlist?
</Modal.Body>
<Modal.Footer>
<button
type="button"
className="btn btn-secorndary clb"
onClick={() => setShowingDeleteWarning(false)}
>
Cancel
</button>
<button
type="button"
data-testid="confirmDeleteFromWordlist"
className="btn btn-primary clb"
onClick={handleDeleteFromWordlist}
>
Delete
</button>
</Modal.Footer>
</Modal>
</div>
);
} }
function explodeEntry(entry: T.DictionaryEntry): T.DictionaryEntry { function explodeEntry(entry: T.DictionaryEntry): T.DictionaryEntry {
return { return {
...entry, ...entry,
p: entry.p.split("").join(" "), p: entry.p.split("").join(" "),
}; };
} }
function inflectionSubUrl(pattern: T.InflectionPattern): string { function inflectionSubUrl(pattern: T.InflectionPattern): string {
return pattern === 0 return pattern === 0
? "" ? ""
: pattern === 1 : pattern === 1
? "#1-basic" ? "#1-basic"
: pattern === 2 : pattern === 2
? "#2-words-ending-in-an-unstressed-ی---ey" ? "#2-words-ending-in-an-unstressed-ی---ey"
: pattern === 3 : pattern === 3
? "#3-words-ending-in-a-stressed-ی---éy" ? "#3-words-ending-in-a-stressed-ی---éy"
: pattern === 4 : pattern === 4
? "#4-words-with-the-pashtoon-pattern" ? "#4-words-with-the-pashtoon-pattern"
: pattern === 5 : pattern === 5
? "#5-shorter-words-that-squish" ? "#5-shorter-words-that-squish"
// : pattern === 6 : // : pattern === 6
: "#6-inanimate-feminine-nouns-ending-in-ي---ee" "#6-inanimate-feminine-nouns-ending-in-ي---ee";
} }
export default IsolatedEntry; export default IsolatedEntry;