@@ -541,6 +541,34 @@ const closePlaceholder = () => {
541541
542542const normalizeTextValue = (value ? : string | null ) => (value ?? ' ' ).trim ();
543543
544+ const getDedupedImagesForSave = (row : VariationRow ) => {
545+ const mediaMap = new Map <string , { slot: VariationImageSlot ; sortOrder: number ; isMainImage: boolean }>();
546+
547+ row .images .forEach ((slot , index ) => {
548+ if (! slot ?.mediaId ) {
549+ return ;
550+ }
551+
552+ const existing = mediaMap .get (slot .mediaId );
553+ if (! existing ) {
554+ mediaMap .set (slot .mediaId , {
555+ slot ,
556+ sortOrder: index ,
557+ isMainImage: !! slot .isMainImage ,
558+ });
559+ return ;
560+ }
561+
562+ existing .sortOrder = Math .min (existing .sortOrder , index );
563+ existing .isMainImage = existing .isMainImage || !! slot .isMainImage ;
564+ if (! existing .slot .id && slot .id ) {
565+ existing .slot = slot ;
566+ }
567+ });
568+
569+ return Array .from (mediaMap .values ()).sort ((a , b ) => a .sortOrder - b .sortOrder );
570+ };
571+
544572const applyEditFormFromSlot = (slot : VariationImageSlot ) => {
545573 syncingEditForm .value = true ;
546574 editTitle .value = slot .title ?? ' ' ;
@@ -934,8 +962,9 @@ const save = async () => {
934962 variations .value .forEach ((row ) => {
935963 const original = originalMap .get (row .variation .id );
936964 const currentIds = new Set <string >();
965+ const dedupedImages = getDedupedImagesForSave (row );
937966
938- row . images . forEach ((slot , index ) => {
967+ dedupedImages . forEach (({ slot , sortOrder , isMainImage } ) => {
939968 if (! slot || ! slot .mediaId ) {
940969 return ;
941970 }
@@ -951,17 +980,17 @@ const save = async () => {
951980 toCreate .push ({
952981 productId: row .variation .id ,
953982 mediaId: slot .mediaId ,
954- sortOrder: index ,
955- isMainImage: !! slot . isMainImage ,
983+ sortOrder ,
984+ isMainImage ,
956985 });
957986 return ;
958987 }
959988 currentIds .add (slot .id );
960989 const originalSlot = original ?.images .find ((item ) => item ?.id === slot .id ) ?? null ;
961990 const originalSort = originalSlot ?.sortOrder ?? null ;
962991 const originalMain = originalSlot ?.isMainImage ?? false ;
963- if (originalSort !== index || originalMain !== slot . isMainImage ) {
964- toUpdate .push ({ id: slot .id , sortOrder: index , isMainImage: !! slot . isMainImage });
992+ if (originalSort !== sortOrder || originalMain !== isMainImage ) {
993+ toUpdate .push ({ id: slot .id , sortOrder , isMainImage });
965994 }
966995 });
967996
0 commit comments