refactor: streamline SVG handling and improve error messages in user and email controllers

This commit is contained in:
Ari Yeger
2025-07-23 16:24:47 -04:00
parent 8eaa0c3d06
commit 9add60735e
7 changed files with 72 additions and 72 deletions

View File

@ -1,35 +1,50 @@
<script setup lang="ts">
import { ref, watchEffect, computed} from 'vue';
import {ref, computed} from 'vue';
import vRecolorSvg from '@/directives/vRecolorSvg.ts';
const props = defineProps<{
svgUrl: string;
svg: string;
width?: number;
height?: number;
viewBox?: string;
}>();
const paths = ref<Array<{ clip: string; d: string; fill: "nonzero" | "evenodd" | "inherit" | undefined}>>([]);
const paths = ref<Array<{
'clip-rule': string | undefined;
d: string | undefined;
'fill-rule': "nonzero" | "evenodd" | "inherit" | undefined
}>>([]);
const svgPaths = props.svg
.replace(/%20/g, " ")
.replace(/%3c/g, "<")
.replace(/%3e/g, ">")
.split('path')
.map(chunk => chunk.trim())
.filter((chunk) => !chunk.startsWith('data:image'))
.map((path) => path
.split('/>')[0]
.replace(/fill=.* /g, "")
.replace(/["']/g, ""));
try {
for (const path of svgPaths) {
const match = {
'clip-rule': /clip-rule=(\w+)/.exec(path),
'd': /d=(.*Z)/.exec(path),
'fill-rule': /fill-rule=(\w+)/.exec(path),
}
paths.value.push({
'clip-rule': match['clip-rule'] ? match['clip-rule'][1].toString() : undefined,
'd': match['d'] ? match['d'][1].toString() : undefined,
'fill-rule': match['fill-rule'] ? match['fill-rule'][1].toString() as "nonzero" | "evenodd" | "inherit" : undefined,
});
watchEffect(async () => {
if (!props.svgUrl) {
paths.value = [];
return;
}
try {
const response = await fetch(props.svgUrl);
const svgText = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(svgText, 'image/svg+xml');
paths.value = Array.from(doc.querySelectorAll('path')).map(path => ({
clip: path.getAttribute('clip-rule') || 'nonzero',
d: path.getAttribute('d') || '',
fill: (path.getAttribute('fill-rule') as "nonzero" | "evenodd" | "inherit" | undefined) || "inherit",
}));
} catch {
paths.value = [];
}
});
} catch (error) {
console.error('Error processing SVG paths:', error);
paths.value = [];
}
const svgStyle = computed(() => ({
width: props.width ? `${props.width}px` : '100%',
@ -40,7 +55,8 @@ const svgStyle = computed(() => ({
<template>
<svg xmlns="http://www.w3.org/2000/svg" :viewBox="svgStyle.viewBox" :width="svgStyle.width"
:height="svgStyle.height">
<path v-for="(path, index) in paths" :key="index" :clip-rule="path.clip" :d="path.d" :fill-rule="path.fill" v-recolor-svg/>
<path v-for="(path, index) in paths" :key="index" :clip-rule="path['clip-rule']" :d="path['d']"
:fill-rule="path['fill-rule']" v-recolor-svg/>
</svg>
</template>

View File

@ -76,7 +76,7 @@ export function useReadableTextColor(bgColor: string): string {
let whiteRatio = (whiteLighter + 0.05) / (whiteDarker + 0.05);
// Return black or white based on luminance
if (blackRatio >= 4.5 || whiteRatio >= 4.5) {
console.debug("bgL:", bgLuminance, "bL:", blackLuminance, "wL:", whiteLuminance, "bR:", blackRatio, "wR:", whiteRatio);
//console.debug("bgL:", bgLuminance, "bL:", blackLuminance, "wL:", whiteLuminance, "bR:", blackRatio, "wR:", whiteRatio);
return blackRatio > whiteRatio ? '#181818' : '#E7E7E7';
}
// If contrast is not enough, use deep colors
@ -87,7 +87,7 @@ export function useReadableTextColor(bgColor: string): string {
blackRatio = (blackLighter + 0.05) / (blackDarker + 0.05);
whiteRatio = (whiteLighter + 0.05) / (whiteDarker + 0.05);
if (blackRatio >= 4.5 || whiteRatio >= 4.5) {
console.debug("bgL:", bgLuminance, "bL:", blackLuminanceDeep, "wL:", whiteLuminanceDeep, "bR:", blackRatio, "wR:", whiteRatio);
//console.debug("bgL:", bgLuminance, "bL:", blackLuminanceDeep, "wL:", whiteLuminanceDeep, "bR:", blackRatio, "wR:", whiteRatio);
return blackRatio > whiteRatio ? '#0B0B0B' : '#F4F4F4';
}
// If still not enough, use absolute colors
@ -98,10 +98,10 @@ export function useReadableTextColor(bgColor: string): string {
blackRatio = (blackLighter + 0.05) / (blackDarker + 0.05);
whiteRatio = (whiteLighter + 0.05) / (whiteDarker + 0.05);
if (blackRatio >= 4.5 || whiteRatio >= 4.5) {
console.debug("bgL:", bgLuminance, "bL:", blackLuminanceAbsolute, "wL:", whiteLuminanceAbsolute, "bR:", blackRatio, "wR:", whiteRatio);
//console.debug("bgL:", bgLuminance, "bL:", blackLuminanceAbsolute, "wL:", whiteLuminanceAbsolute, "bR:", blackRatio, "wR:", whiteRatio);
return blackRatio > whiteRatio ? '#000000' : '#FFFFFF';
}
console.warn(`Not enough contrast for background color: ${bgColor}. Using fallback colors.`);
//console.warn(`Not enough contrast for background color: ${bgColor}. Using fallback colors.`);
return bgLuminance > 0.5 ? blackTextColor : whiteTextColor; // Fallback to default colors
}

View File

@ -27,6 +27,7 @@ export function useLogin() {
async login(username: string, password: string): Promise<SecureUser> {
return await api<SecureUser>("/users/login", {username, password}, "POST")
.then((response: DataEnvelope<SecureUser> ) => {
if (!response.data) throw new Error("Invalid login credentials. Please try again.");
session.user = response.data;
if (!session.user) throw new Error("Invalid login credentials. Please try again.");
session.token = response.data.token || null;
@ -37,7 +38,9 @@ export function useLogin() {
localStorage.setItem("token", session.token ?? "");
return session.user;
})
.catch((err)=>{throw err}) as SecureUser;
.catch((envelope: DataEnvelope<any>)=>{
toast.error(envelope.message || envelope.error?.message || "An error occurred while trying to log in. Please try again later.")
}) as SecureUser;
},
async logout(): Promise<void> {
session.user = null;

View File

@ -2,16 +2,17 @@
import {ref} from 'vue';
import {useLogin} from "@models/session.ts";
import {isMobile} from "@models/globals.ts";
import vRecolorSvg from '@/directives/vRecolorSvg.ts';
import eye from '@/assets/svg/eye.svg';
import eyeSlash from '@/assets/svg/eye-slash.svg';
import BaseButton from "@components/baseComponents/BaseButton.vue";
import BaseSVG from "@components/baseComponents/BaseSVG.vue";
import BaseInput from "@components/baseComponents/BaseInput.vue";
const username = ref('');
const password = ref('');
const {login} = useLogin();
const showPassword = ref(false);
</script>
<template>
@ -29,17 +30,15 @@ const showPassword = ref(false);
<label class="form-label" for="password">Password</label>
<div class="input-group">
<BaseInput class="form-control" id="password" v-model="password"
:type="showPassword ? 'text' : 'password'"
autocomplete="current-password" required style="border-right:0;"/>
:type="showPassword ? 'text' : 'password'"
autocomplete="current-password" required style="border-right:0;"/>
<button type="button" class="input-group-text border-start-0"
style="cursor:pointer;"
@click="showPassword = !showPassword">
<BaseSVG svg-url="/src/assets/svg/eye.svg" :width="20" :height="20"
view-box="0 0 28 28"
v-recolor-svg v-if="!showPassword"/>
<BaseSVG svg-url="/src/assets/svg/eye-slash.svg" :width="20" :height="20"
view-box="0 0 28 28"
v-recolor-svg v-else/>
<BaseSVG :svg="eye" :width="20" :height="20"
view-box="0 0 28 28" v-if="!showPassword"/>
<BaseSVG :svg="eyeSlash" :width="20" :height="20"
view-box="0 0 28 28" v-else/>
</button>
</div>
</div>