Skip to content
Merged
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
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"pinia": "^3.0.3",
"socket.io-client": "^4.7.2",
"vue": "^3.5.13",
"vue-advanced-cropper": "^2.6.2",
"vue-router": "^4.5.0",
"vue-sonner": "^2.0.9",
"vuedraggable": "^4.1.0",
Expand Down
299 changes: 299 additions & 0 deletions frontend/src/components/ImageUploader/ImageUploader.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,299 @@
<template>
<div>
<input
ref="inputRef"
type="file"
:accept="acceptString"
class="hidden"
@change="onFileAdd"
/>
<slot
v-bind="{
file,
uploading,
progress,
uploaded,
message,
error,
total,
success,
openFileSelector,
}"
>
<Button @click="openFileSelector" :loading="uploading">
{{ uploading ? `Uploading ${progress}%` : "Upload image" }}
</Button>
</slot>

<!-- Crop dialog: Frappe UI -->
<Dialog
v-model="cropDialogOpen"
:options="{
title: 'Crop image',
size: 'lg',
}"
>
<template #body-content>
<p class="text-sm text-ink-gray-6 mb-4">
Adjust the crop area to {{ cropDimensions.width }}×{{ cropDimensions.height }}
pixels, then upload.
</p>
<div class="cropper-container">
<Cropper
v-if="cropImageUrl"
ref="cropperRef"
:src="cropImageUrl"
:stencil-props="{
aspectRatio: cropDimensions.width / cropDimensions.height,
}"
:canvas="{
width: cropDimensions.width,
height: cropDimensions.height,
}"
image-restriction="stencil"
class="cropper"
/>
Comment on lines +42 to +55
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

cropperReady is set prematurely before the cropper has actually loaded the image.

The watch handler sets cropperReady = true immediately when the dialog opens (line 148), but the Cropper component needs time to load and initialize the image. If users click "Crop & Upload" before the image is fully loaded, getResult() may return an empty or incomplete canvas.

The vue-advanced-cropper provides a @ready event that fires when the cropper has finished initializing. Use this event to properly track readiness.

🐛 Proposed fix using the `@ready` event

Update the Cropper component to use the @ready event:

 <Cropper
     v-if="cropImageUrl"
     ref="cropperRef"
     :src="cropImageUrl"
     :stencil-props="{
         aspectRatio: cropDimensions.width / cropDimensions.height,
     }"
     :canvas="{
         width: cropDimensions.width,
         height: cropDimensions.height,
     }"
     image-restriction="stencil"
     class="cropper"
+    `@ready`="cropperReady = true"
 />

Update the watch handler to only reset cropperReady on close:

 watch(cropDialogOpen, (open) => {
     if (!open) {
         revokeCropUrl();
         file.value = null;
         cropperReady.value = false;
-    } else {
-        cropperReady.value = true;
     }
 });

Also applies to: 142-150

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@frontend/src/components/ImageUploader/ImageUploader.vue` around lines 42 -
55, The watch handler sets cropperReady too early causing getResult() to run
before the Cropper has initialized; instead, wire the Cropper component's `@ready`
event to set cropperReady = true and ensure cropperReady is only reset to false
when the dialog closes (leave the watcher to clear readiness on close only), and
use the cropperRef and getResult() as before so getResult() is only invoked
after the `@ready` event has fired.

</div>
</template>
<template #actions="{ close }">
<div class="flex justify-end gap-2">
<Button variant="ghost" label="Cancel" @click="close" />
<Button variant="outline" label="Reset" @click="onResetCrop" />
<Button
variant="solid"
label="Crop & Upload"
:loading="uploading"
:disabled="!cropperReady"
@click="onCropAndUpload"
/>
</div>
</template>
</Dialog>
</div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { Cropper } from "vue-advanced-cropper";
import "vue-advanced-cropper/dist/style.css";
import { Button, Dialog, FileUploadHandler } from "frappe-ui";
import type { UploadOptions, UploadedFile } from "frappe-ui";

const props = withDefaults(
defineProps<{
cropDimensions: { width: number; height: number };
fileTypes?: string | string[];
uploadArgs?: UploadOptions;
validateFile?: (file: File) => Promise<string | void>;
}>(),
{
fileTypes: () => ["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp"],
}
);

const emit = defineEmits<{
success: [data: UploadedFile];
failure: [error: unknown];
}>();

const acceptString = computed(() => {
const types = props.fileTypes;
if (typeof types === "string") return types;
return Array.isArray(types) ? types.join(",") : "image/*";
});

const inputRef = ref<HTMLInputElement | null>(null);
const cropperRef = ref<InstanceType<typeof Cropper> | null>(null);
const cropDialogOpen = ref(false);
const cropperReady = ref(false);

const file = ref<File | null>(null);
const uploading = ref(false);
const uploaded = ref(0);
const total = ref(0);
const error = ref<string | null>(null);
const message = ref("");
const finishedUploading = ref(false);
const cropImageUrl = ref<string | null>(null);
const pendingFileName = ref<string>("image.png");

const progress = computed(() => {
const value = total.value ? Math.floor((uploaded.value / total.value) * 100) : 0;
return Number.isNaN(value) ? 0 : value;
});

const success = computed(() => finishedUploading.value && !error.value);

function openFileSelector() {
inputRef.value?.click();
}

function inputRefMethod() {
return inputRef.value;
}

function revokeCropUrl() {
if (cropImageUrl.value) {
URL.revokeObjectURL(cropImageUrl.value);
cropImageUrl.value = null;
}
}

watch(cropDialogOpen, (open) => {
if (!open) {
revokeCropUrl();
file.value = null;
cropperReady.value = false;
} else {
cropperReady.value = true;
}
});

async function onFileAdd(e: Event) {
const target = e.target as HTMLInputElement;
const selectedFile = target.files?.[0];
target.value = "";

error.value = null;
file.value = selectedFile ?? null;

if (!selectedFile) return;

if (props.validateFile) {
try {
const msg = await props.validateFile(selectedFile);
if (msg) {
error.value = msg;
return;
}
} catch (err) {
error.value = err instanceof Error ? err.message : "Validation failed";
return;
}
}

revokeCropUrl();
cropImageUrl.value = URL.createObjectURL(selectedFile);
pendingFileName.value = selectedFile.name;
cropperReady.value = false;
cropDialogOpen.value = true;
}

function onResetCrop() {
cropperRef.value?.reset();
}

async function onCropAndUpload() {
const cropper = cropperRef.value;
if (!cropper || !cropImageUrl.value) return;

let result: { canvas?: HTMLCanvasElement };
try {
result = cropper.getResult();
} catch {
error.value = "Failed to get crop result";
return;
}

const canvas = result.canvas;
if (!canvas) {
error.value = "Cropper did not return a canvas";
return;
}

cropDialogOpen.value = false;
revokeCropUrl();

const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob(resolve, "image/png", 1);
});

if (!blob) {
error.value = "Failed to create image blob";
return;
}

const croppedFile = new File([blob], pendingFileName.value.replace(/\.[^.]+$/, "") + ".png", {
type: "image/png",
});

uploadFile(croppedFile);
}

function uploadFile(fileToUpload: File) {
error.value = null;
uploaded.value = 0;
total.value = 0;
finishedUploading.value = false;

const uploader = new FileUploadHandler();
uploader.on("start", () => {
uploading.value = true;
});
uploader.on("progress", (data: { uploaded: number; total: number }) => {
uploaded.value = data.uploaded;
total.value = data.total;
});
uploader.on("error", () => {
uploading.value = false;
error.value = "Error Uploading File";
});
uploader.on("finish", () => {
uploading.value = false;
finishedUploading.value = true;
});

uploader
.upload(fileToUpload, props.uploadArgs ?? {})
.then((data: UploadedFile) => {
emit("success", data);
})
.catch((err: unknown) => {
uploading.value = false;
let errorMessage = "Error Uploading File";
const errorObj = err as { _server_messages?: string; exc?: string };
if (errorObj?._server_messages) {
try {
const parsed = JSON.parse(JSON.parse(errorObj._server_messages)[0]);
if (parsed?.message) errorMessage = parsed.message;
} catch {
// keep default
}
} else if (errorObj?.exc) {
try {
const lines = JSON.parse(errorObj.exc)[0]?.split("\n") ?? [];
const last = lines.slice(-2, -1)[0];
if (last) errorMessage = last;
} catch {
// keep default
}
}
error.value = errorMessage;
emit("failure", err);
});
}

defineExpose({
openFileSelector,
inputRef: inputRefMethod,
});
</script>

<style scoped>
.cropper-container {
position: relative;
width: 100%;
max-width: 100%;
height: 360px;
overflow: hidden;
background: var(--color-surface-gray-1, #f3f4f6);
border-radius: 0.375rem;
}
.cropper-container :deep(.cropper),
.cropper-container :deep(.vue-advanced-cropper) {
width: 100% !important;
height: 100% !important;
max-width: 100%;
background: var(--color-surface-gray-1, #f3f4f6);
}
</style>
30 changes: 24 additions & 6 deletions frontend/src/components/team/ManageTeamHeader.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup lang="ts">
import TeamLogo from "@/components/team/TeamLogo.vue";
import { Button } from "frappe-ui";
import ImageUploader from "@/components/ImageUploader/ImageUploader.vue";
import { Button, ErrorMessage } from "frappe-ui";
import { useTeam } from "@/stores/team";
import { EditableArea, EditableInput, EditablePreview, EditableRoot } from "reka-ui";
import { ref, watch } from "vue";
Expand Down Expand Up @@ -29,11 +30,28 @@ function onSubmit() {
:team-name="teamStore.currentTeam!.team_name"
:logo-url="teamStore.currentTeam?.logo ?? null"
/>
<Button
:label="teamStore.currentTeam?.logo ? 'Change' : 'Upload Logo'"
icon-left="upload"
variant="outline"
/>
<ImageUploader
:crop-dimensions="{ width: 400, height: 400 }"
:upload-args="{ folder: 'Home' }"
@success="(file) => teamStore.save({ logo: file.file_url })"
>
<template #default="{ uploading, progress, error, openFileSelector }">
<ErrorMessage :message="error ?? undefined" />
<Button
:label="
teamStore.currentTeam?.logo
? 'Change'
: uploading
? `Uploading ${progress}%`
: 'Upload Logo'
"
icon-left="upload"
variant="outline"
:loading="uploading"
@click="openFileSelector"
/>
Comment on lines +40 to +52
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Bug: Button label shows "Change" during upload when a logo already exists.

The ternary condition checks teamStore.currentTeam?.logo first, so when a logo exists, the button always shows "Change" regardless of the uploading state. The uploading check should take precedence to show progress feedback.

🐛 Proposed fix to correct ternary precedence
 <Button
     :label="
-        teamStore.currentTeam?.logo
-            ? 'Change'
-            : uploading
+        uploading
             ? `Uploading ${progress}%`
+            : teamStore.currentTeam?.logo
+            ? 'Change'
             : 'Upload Logo'
     "
     icon-left="upload"
     variant="outline"
     :loading="uploading"
     `@click`="openFileSelector"
 />
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@frontend/src/components/team/ManageTeamHeader.vue` around lines 40 - 52, The
Button's label ternary gives precedence to teamStore.currentTeam?.logo so it
shows "Change" while uploading; update the label expression in the Button
component to check uploading first (use uploading ? `Uploading ${progress}%` :
teamStore.currentTeam?.logo ? 'Change' : 'Upload Logo') so progress text
displays during uploads and fallback to 'Change' or 'Upload Logo' otherwise.

</template>
</ImageUploader>
</div>
<div class="flex pt-4">
<EditableRoot
Expand Down
21 changes: 20 additions & 1 deletion frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1482,7 +1482,7 @@ chokidar@^3.6.0:
optionalDependencies:
fsevents "~2.3.2"

classnames@^2.2.5:
classnames@^2.2.5, classnames@^2.2.6:
version "2.5.1"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.5.1.tgz#ba774c614be0f016da105c858e7159eae8e7687b"
integrity sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==
Expand Down Expand Up @@ -1600,6 +1600,11 @@ dayjs@^1.11.19:
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.19.tgz#15dc98e854bb43917f12021806af897c58ae2938"
integrity sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==

debounce@^1.2.0:
version "1.2.1"
resolved "https://registry.yarnpkg.com/debounce/-/debounce-1.2.1.tgz#38881d8f4166a5c5848020c11827b834bcb3e0a5"
integrity sha512-XRRe6Glud4rd/ZGQfiV1ruXSfbvfJedlV9Y6zOlP+2K04vBYiJEte6stfFkCP03aMnY5tsipamumUjL14fofug==

debug@4, debug@^4.1.1, debug@^4.3.4, debug@^4.3.7, debug@^4.4.0, debug@^4.4.1:
version "4.4.1"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.1.tgz#e5a8bc6cbc4c6cd3e64308b0693a3d4fa550189b"
Expand Down Expand Up @@ -1684,6 +1689,11 @@ eastasianwidth@^0.2.0:
resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb"
integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==

easy-bem@^1.0.2:
version "1.1.1"
resolved "https://registry.yarnpkg.com/easy-bem/-/easy-bem-1.1.1.tgz#1bfcc10425498090bcfddc0f9c000aba91399e03"
integrity sha512-GJRqdiy2h+EXy6a8E6R+ubmqUM08BK0FWNq41k24fup6045biQ8NXxoXimiwegMQvFFV3t1emADdGNL1TlS61A==

echarts@^5.6.0:
version "5.6.0"
resolved "https://registry.yarnpkg.com/echarts/-/echarts-5.6.0.tgz#2377874dca9fb50f104051c3553544752da3c9d6"
Expand Down Expand Up @@ -3597,6 +3607,15 @@ vscode-uri@^3.0.8:
resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.1.0.tgz#dd09ec5a66a38b5c3fffc774015713496d14e09c"
integrity sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==

vue-advanced-cropper@^2.6.2:
version "2.8.9"
resolved "https://registry.yarnpkg.com/vue-advanced-cropper/-/vue-advanced-cropper-2.8.9.tgz#119ec7ade91dcf80fb22940ecbbf265ad0ae1bc4"
integrity sha512-1jc5gO674kVGpJKekoaol6ZlwaF5VYDLSBwBOUpViW0IOrrRsyLw6XNszjEqgbavvqinlKNS6Kqlom3B5M72Tw==
dependencies:
classnames "^2.2.6"
debounce "^1.2.0"
easy-bem "^1.0.2"

vue-demi@>=0.13.0, vue-demi@>=0.14.8:
version "0.14.10"
resolved "https://registry.yarnpkg.com/vue-demi/-/vue-demi-0.14.10.tgz#afc78de3d6f9e11bf78c55e8510ee12814522f04"
Expand Down