import { Dropdown } from "bootstrap";
import NoteContextAwareWidget from "./note_context_aware_widget.js";
import { getAvailableLocales } from "../services/i18n.js";
import { t } from "i18next";
import type { EventData } from "../components/app_context.js";
import type FNote from "../entities/fnote.js";
import attributes from "../services/attributes.js";
import type { Locale } from "../../../services/i18n.js";
const TPL = `\
`;
const DEFAULT_LOCALE: Locale = {
id: "",
name: t("note_language.not_set")
};
export default class NoteLanguageWidget extends NoteContextAwareWidget {
private dropdown!: Dropdown;
private $noteLanguageDropdown!: JQuery;
private $noteLanguageDesc!: JQuery;
private locales: (Locale | "---")[];
private currentLanguageId?: string;
constructor() {
super();
const allLanguages = getAvailableLocales();
const leftToRightLanguages = allLanguages.filter((l) => !l.rtl);
const rightToLeftLanguages = allLanguages.filter((l) => l.rtl);
this.locales = [
DEFAULT_LOCALE,
"---",
...leftToRightLanguages
];
if (rightToLeftLanguages.length > 0) {
this.locales = [
...this.locales,
"---",
...rightToLeftLanguages
];
}
}
doRender() {
this.$widget = $(TPL);
this.dropdown = Dropdown.getOrCreateInstance(this.$widget.find("[data-bs-toggle='dropdown']")[0]);
this.$widget.on("show.bs.dropdown", () => this.renderDropdown());
this.$noteLanguageDropdown = this.$widget.find(".note-language-dropdown")
this.$noteLanguageDesc = this.$widget.find(".note-language-desc");
}
renderDropdown() {
this.$noteLanguageDropdown.empty();
if (!this.note) {
return;
}
for (const locale of this.locales) {
if (typeof locale === "object") {
const $title = $("").text(locale.name);
if (locale.rtl) {
$title.attr("dir", "rtl");
}
const $link = $('')
.attr("data-language", locale.id)
.append('✓ ')
.append($title)
.on("click", () => {
const languageId = $link.attr("data-language") ?? "";
this.save(languageId);
});
if (locale.id === this.currentLanguageId) {
$link.addClass("selected");
}
this.$noteLanguageDropdown.append($link);
} else {
this.$noteLanguageDropdown.append('
');
}
}
}
async save(languageId: string) {
if (!this.note) {
return;
}
attributes.setAttribute(this.note, "label", "language", languageId);
}
async refreshWithNote(note: FNote) {
const currentLanguageId = note.getLabelValue("language") ?? "";
const language = (this.locales.find((l) => (typeof l === "object" && l.id === currentLanguageId)) as Locale | null) ?? DEFAULT_LOCALE;
this.currentLanguageId = currentLanguageId;
this.$noteLanguageDesc.text(language.name);
this.dropdown.hide();
}
async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
if (loadResults.getAttributeRows().find((a) => a.noteId === this.noteId && a.name === "language")) {
this.refresh();
}
}
}