PronounsPage/composables/useMainPronoun.ts

79 lines
2.5 KiB
TypeScript

import { computed } from 'vue';
import { buildPronoun, buildPronounUsage } from '../src/buildPronoun.ts';
import type { Pronoun, PronounLibrary, PronounUsage } from '../src/classes.ts';
import opinions from '../src/opinions.ts';
import type { Profile } from '../src/profile.ts';
import type { Translator } from '../src/translator';
import useConfig from './useConfig.ts';
import { getUrlForLocale } from '~/src/domain.ts';
export interface PronounOpinion extends PronounUsage {
link: string;
opinion: string;
}
export default (
pronounLibrary: PronounLibrary,
profile: Ref<Partial<Pick<Profile, 'pronouns'>> | null>,
translator: Translator,
) => {
const config = useConfig();
const pronouns = pronounLibrary.pronouns;
const pronounOpinions = computed((): PronounOpinion[] => {
if (!profile.value) {
return [];
}
return (profile.value.pronouns ?? [])
.map(({ value: pronoun, opinion }) => {
const baseUrl = getUrlForLocale(config.locale);
let link = pronoun
.trim()
.replace(new RegExp(`^${baseUrl}`), '')
.replace(new RegExp(`^${baseUrl.replace(/^https?:\/\//, '')}`), '')
.replace(new RegExp('^/'), '');
try {
link = decodeURIComponent(link);
} catch {
return;
}
const usage = buildPronounUsage(pronounLibrary, link, config, translator);
if (usage) {
return {
...usage,
link,
opinion,
};
}
})
.filter((usage) => usage !== undefined);
});
const mainPronoun = computed((): Pronoun | null => {
if (!config.profile.editorEnabled || !config.profile.flags?.defaultPronoun) {
return null;
}
let mainPronoun = buildPronoun(pronouns, config.profile.flags?.defaultPronoun, config, translator);
let mainOpinion = -1;
for (const { pronoun, opinion } of pronounOpinions.value) {
if (!pronoun) {
continue;
}
const opinionValue = opinions[opinion]?.value || 0;
if (opinionValue > mainOpinion) {
mainPronoun = pronoun;
mainOpinion = opinionValue;
}
}
return mainPronoun;
});
return {
pronounOpinions,
mainPronoun,
};
};