Explorar o código

修复编辑歌单,添加歌曲的报错,目前加载前100条而已,需要上拉加载更多分页功能

onecold hai 10 meses
pai
achega
0a9a4b8dc6

+ 131 - 156
entry/src/main/ets/dialog/AddSongsToPlaylistDialog.ets

@@ -1,17 +1,21 @@
 import { DialogHelper } from '@pura/harmony-dialog';
 import { Playlist } from '../viewmodel/Playlist';
-import { ToastUtil, LogUtil } from '@pura/harmony-utils';
+import { ToastUtil, LogUtil, ArrayUtil, StrUtil } from '@pura/harmony-utils';
 import { VideoItem } from '../viewmodel/VideoItem';
 import MediaTable from '../common/util/MediaTable';
 import PlaylistTable from '../common/util/PlaylistTable';
 import { LazyDataSource } from '../common/util/LazyDataSource';
+import { common } from '@kit.AbilityKit';
+import { CommonConstants } from '../common/constants/CommonConstants';
 
 /**
  * 添加歌曲到歌单对话框内容组件
  */
 @Component
 struct AddSongsToPlaylistDialogContent {
-  // @State allSongs: VideoItem[] = []
+  context = this.getUIContext().getHostContext() as common.UIAbilityContext
+  @State opacityItem: number = 1; // 控制透明度的状态变量
+  @StorageProp('themeColor') themeColor: string = CommonConstants.DEFAULT_THEME_COLOR;
   @State selectedSongs: VideoItem[] = []
   @State isLoading: boolean = false
   @State searchText: string = ''
@@ -20,6 +24,7 @@ struct AddSongsToPlaylistDialogContent {
   @State isSearchMode: boolean = false
   @Prop playlist: Playlist
   @Prop mediaKuList:  Array<VideoItem>
+  @StorageProp('mediaKuList')  mediaKuList2: Array<VideoItem> = []; //媒体库文件
   private mediaTable: MediaTable = new MediaTable(getContext(this))
   private playlistTable: PlaylistTable = new PlaylistTable(getContext(this))
   @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.filteredSongs)
@@ -30,56 +35,11 @@ struct AddSongsToPlaylistDialogContent {
   aboutToAppear() {
     LogUtil.info('heanup AddSongsToPlaylistDialogContent aboutToAppear 开始')
     LogUtil.info('heanup playlist: ' + (this.playlist ? JSON.stringify({ id: this.playlist.id, name: this.playlist.name }) : 'null'))
-    console.info('onecold mediaKuList 对话框 aboutToAppear='+this.mediaKuList.length)
-    this.updateListData(this.mediaKuList)
-
-    // 初始化数据库连接
-    // this.mediaTable.getRdbStore(getContext(this), () => {
-    //   LogUtil.info('heanup MediaTable 数据库初始化完成')
-    //   this.isDbInitialized = true
-    //   this.loadAllSongs()
-    // })
-    
-    LogUtil.info('heanup AddSongsToPlaylistDialogContent aboutToAppear 结束')
+    // console.info('onecold mediaKuList 对话框 aboutToAppear='+this.mediaKuList.length)
+    this.updateListData(this.mediaKuList2)
+
   }
 
-  /**
-   * 加载所有歌曲
-   */
-  // async loadAllSongs() {
-  //   if (!this.isDbInitialized) {
-  //     LogUtil.warn('heanup 数据库未初始化,等待初始化完成')
-  //     return
-  //   }
-  //
-  //   try {
-  //     LogUtil.info('heanup loadAllSongs 开始')
-  //     this.isLoading = true
-  //     LogUtil.info('heanup 开始查询所有歌曲')
-  //     // this.allSongs = await this.mediaTable.queryAllVideos()
-  //     // LogUtil.info('heanup 查询到 ' + this.allSongs.length + ' 首歌曲')
-  //     this.filteredSongs = [...this.allSongs]
-  //
-  //     // 过滤掉已经在歌单中的歌曲
-  //     if (this.playlist) {
-  //       LogUtil.info('heanup 开始查询歌单中的歌曲,歌单ID: ' + this.playlist.id)
-  //       const playlistSongs = await this.playlistTable.queryPlaylistSongs(this.playlist.id)
-  //       LogUtil.info('heanup 歌单中有 ' + playlistSongs.length + ' 首歌曲')
-  //       const playlistSongPaths = playlistSongs.map(song => song.songFilePath)
-  //       this.filteredSongs = this.filteredSongs.filter(song => !playlistSongPaths.includes(song.filePath))
-  //       this.allSongs = [...this.filteredSongs]
-  //       LogUtil.info('heanup 过滤后有 ' + this.filteredSongs.length + ' 首歌曲可添加')
-  //     } else {
-  //       LogUtil.warn('heanup playlist 为 null')
-  //     }
-  //   } catch (error) {
-  //     LogUtil.error('heanup 加载歌曲列表失败: ' + error)
-  //     ToastUtil.showToast('加载歌曲列表失败')
-  //   } finally {
-  //     LogUtil.info('heanup 设置 isLoading 为 false')
-  //     this.isLoading = false
-  //   }
-  // }
 
   /**
    * 搜索过滤歌曲
@@ -89,21 +49,33 @@ struct AddSongsToPlaylistDialogContent {
     if (!this.searchText.trim()) {
       this.filteredSongs = [...this.mediaKuList]
     } else {
-      const searchLower = this.searchText.toLowerCase()
-      this.filteredSongs = this.mediaKuList.filter(song =>
-        (song.name && song.name.toLowerCase().includes(searchLower)) ||
-        (song.artist && song.artist.toLowerCase().includes(searchLower)) ||
-        (song.album && song.album.toLowerCase().includes(searchLower))
-      )
+      this.filteredSongs = this.mediaKuList.filter(item =>{
+        //支持模糊匹配和艺术家 专辑匹配
+        const regex = new RegExp(this.searchText.replace(/\s+/g,  '.*'), 'i');
+        return regex.test(item.name.toLowerCase())||
+        regex.test(item.fileName?.toLowerCase()  ?? "") ||
+        regex.test(item.artist?.toLowerCase()  ?? "") ||
+        regex.test(item.album?.toLowerCase()  ?? "")
+      })
     }
     this.updateListData(this.filteredSongs)
   }
 
   updateListData(mList: Array<VideoItem>) {
+    this.getUIContext().animateTo({ duration: 666 }, () => {
+      this.opacityItem = 0;
+    })
     //只展示100条,不然会报错
     setTimeout(() => {
-      this.dataSource.pushArrayData(mList.slice(0,  100))
+      if (ArrayUtil.isNotEmpty(mList)&&mList.length  > 100) {
+        this.dataSource.pushArrayData(mList.slice(0,  100))
+      }else{
+        this.dataSource.pushArrayData(mList)
+      }
 
+      this.getUIContext().animateTo({ duration: 666 }, () => {
+        this.opacityItem = 1;
+      });
     }, 200);
 
   }
@@ -120,7 +92,7 @@ struct AddSongsToPlaylistDialogContent {
 
         TextInput({ placeholder: '搜索歌曲、歌手或专辑', text: this.searchText })
           .layoutWeight(1)
-          .height(40)
+          .height(35)
           .backgroundColor($r('app.color.input_background'))
           .borderRadius(8)
           .padding({ left: 8, right: 8 })
@@ -134,7 +106,7 @@ struct AddSongsToPlaylistDialogContent {
       .width('100%')
       .padding(12)
       .backgroundColor($r('app.color.input_background'))
-      .borderRadius(8)
+      .borderRadius(20)
 
       // 已选择歌曲数量
       if (this.selectedSongs.length > 0) {
@@ -161,22 +133,7 @@ struct AddSongsToPlaylistDialogContent {
       }
 
       // 歌曲列表
-      if (this.isLoading) {
-        Column() {
-          LoadingProgress()
-            .width(40)
-            .height(40)
-            .color($r('app.color.theme_color'))
-          
-          Text('加载中...')
-            .fontSize(14)
-            .fontColor($r('app.color.text_color'))
-            .margin({ top: 12 })
-        }
-        .width('100%')
-        .height(300)
-        .justifyContent(FlexAlign.Center)
-      } else if (this.filteredSongs.length === 0&&this.isSearchMode) {
+     if (this.filteredSongs.length === 0&&this.isSearchMode) {
         Column({ space: 12 }) {
           Image($r('app.media.music_red'))
             .width(64)
@@ -191,81 +148,7 @@ struct AddSongsToPlaylistDialogContent {
         .height(300)
         .justifyContent(FlexAlign.Center)
       } else {
-        Scroll() {
-          Column({ space: 0 }) {
-            List({ scroller: this.listScroller }) {
-              LazyForEach(this.dataSource, (song: VideoItem, index: number) => {
-                ListItem() {
-                  Row({ space: 12 }) {
-                    // 选择框
-                    Checkbox({ name: 'song_' + song.id })
-                      .select(this.selectedSongs.some(s => s.id === song.id))
-                      .selectedColor($r('app.color.theme_color'))
-                      .shape(CheckBoxShape.ROUNDED_SQUARE)
-                      .onChange((checked: boolean) => {
-                        if (checked) {
-                          if (!this.selectedSongs.some(s => s.id === song.id)) {
-                            this.selectedSongs.push(song)
-                          }
-                        } else {
-                          const index = this.selectedSongs.findIndex(s => s.id === song.id)
-                          if (index > -1) {
-                            this.selectedSongs.splice(index, 1)
-                          }
-                        }
-                      })
-
-                    // 歌曲信息
-                    Column({ space: 4 }) {
-                      Text(song.name || '未知歌曲')
-                        .fontSize(14)
-                        .fontColor($r('app.color.text_color'))
-                        .maxLines(1)
-                        .textOverflow({ overflow: TextOverflow.Ellipsis })
-                        .width('100%')
-
-                      Row() {
-                        if (song.artist) {
-                          Text(song.artist)
-                            .fontSize(12)
-                            .fontColor('#999999')
-                            .maxLines(1)
-                            .textOverflow({ overflow: TextOverflow.Ellipsis })
-                            .layoutWeight(1)
-                        }
-
-                      }
-                      .width('100%')
-                    }
-                    .alignItems(HorizontalAlign.Start)
-                    .layoutWeight(1)
-                  }
-                  .width('100%')
-                  .padding(12)
-                  .borderRadius(8)
-                  .onClick(() => {
-                    const isSelected = this.selectedSongs.some(s => s.id === song.id)
-                    if (isSelected) {
-                      const index = this.selectedSongs.findIndex(s => s.id === song.id)
-                      if (index > -1) {
-                        this.selectedSongs.splice(index, 1)
-                      }
-                    } else {
-                      this.selectedSongs.push(song)
-                    }
-                  })
-                }
-
-              }, (song: VideoItem) => song.id)
-            }
-            .cachedCount(6)
-          }
-
-        }
-        .scrollBar(BarState.Auto)
-
-        .scrollable(ScrollDirection.Vertical)
-        .height(300)
+        this.getListView()
       }
 
       // 按钮区域
@@ -318,6 +201,102 @@ struct AddSongsToPlaylistDialogContent {
     this.onConfirm?.(this.selectedSongs)
     DialogHelper.closeDialog('addSongsToPlaylistDialog')
   }
+
+  @Builder
+  getListView() {
+    Scroll() {
+      Column({ space: 0 }) {
+        List({ scroller: this.listScroller }) {
+          LazyForEach(this.dataSource, (song: VideoItem, index: number) => {
+            ListItem() {
+              Row({ space: 12 }) {
+
+                Image(StrUtil.isEmpty(song.pixelMapPath) ? $r('app.media.music_red') : song.pixelMapPath)
+                  .fillColor(this.themeColor)
+                  .height(40)
+                  .width(40)
+                  .alt($r('app.media.music_red'))
+                  .borderRadius('100%')
+                  .clip(true)
+                  .draggable(false)
+                  .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
+                  .autoResize(true) // 重采样,可减少内存占用
+                  .opacity(this.opacityItem)// 绑定透明度
+                // 歌曲信息
+                Column({ space: 4 }) {
+                  Text(song.name || '未知歌曲')
+                    .fontSize(14)
+                    .fontColor($r('app.color.text_color'))
+                    .maxLines(1)
+                    .textOverflow({ overflow: TextOverflow.Ellipsis })
+                    .width('100%')
+
+                  Row() {
+                    if (song.artist) {
+                      Text(song.artist)
+                        .fontSize(12)
+                        .fontColor('#999999')
+                        .maxLines(1)
+                        .textOverflow({ overflow: TextOverflow.Ellipsis })
+                        .layoutWeight(1)
+                    }
+
+                  }
+                  .width('100%')
+                }
+                .alignItems(HorizontalAlign.Start)
+                .layoutWeight(1)
+
+                // 选择框
+                Checkbox({ name: 'song_' + song.id })
+                  .select(this.selectedSongs.some(s => s.id === song.id))
+                  .selectedColor($r('app.color.theme_color'))
+                  .shape(CheckBoxShape.ROUNDED_SQUARE)
+                  .onChange((checked: boolean) => {
+                    if (checked) {
+                      if (!this.selectedSongs.some(s => s.id === song.id)) {
+                        this.selectedSongs.push(song)
+                      }
+                    } else {
+                      const index = this.selectedSongs.findIndex(s => s.id === song.id)
+                      if (index > -1) {
+                        this.selectedSongs.splice(index, 1)
+                      }
+                    }
+                  })
+              }
+              .width('100%')
+              .padding(12)
+              .borderRadius(10)
+              .onClick(() => {
+                const isSelected = this.selectedSongs.some(s => s.id === song.id)
+                if (isSelected) {
+                  const index = this.selectedSongs.findIndex(s => s.id === song.id)
+                  if (index > -1) {
+                    this.selectedSongs.splice(index, 1)
+                  }
+                } else {
+                  this.selectedSongs.push(song)
+                }
+              })
+            }
+            .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
+              .animation({ duration: 500 }),
+              TransitionEffect.scale({ x: 0, y: 0 })))
+            .clickEffect({ level: ClickEffectLevel.LIGHT })
+
+          }, (song: VideoItem) => song.id)
+        }
+        .cachedCount(6)
+      }
+
+    }
+    .scrollBar(BarState.Auto)
+
+    .scrollable(ScrollDirection.Vertical)
+    .height(300)
+  }
+
 }
 
 /**
@@ -332,13 +311,11 @@ export struct AddSongsToPlaylistDialogManager {
   buildAddSongsToPlaylistDialog(
     playlist: Playlist,
     onConfirm: (songs: VideoItem[]) => void,
-    mediaKuList: VideoItem[],
     onCancel?: () => void,
   ) {
     AddSongsToPlaylistDialogContent({
       playlist: playlist,
       onConfirm: onConfirm,
-      mediaKuList: mediaKuList,
       onCancel: onCancel
     })
   }
@@ -349,7 +326,6 @@ export struct AddSongsToPlaylistDialogManager {
   showAddSongsToPlaylistDialog(
     playlist: Playlist,
     onConfirm: (songs: VideoItem[]) => void,
-    mediaKuList: VideoItem[],
     onCancel?: () => void,
   ) {
     DialogHelper.showCustomContentDialog({
@@ -357,7 +333,7 @@ export struct AddSongsToPlaylistDialogManager {
       title: '添加歌曲到歌单',
       autoCancel: true,
       contentBuilder: () => {
-        this.buildAddSongsToPlaylistDialog(playlist, onConfirm, mediaKuList,onCancel)
+        this.buildAddSongsToPlaylistDialog(playlist, onConfirm,onCancel)
       },
       buttons: []
     })
@@ -376,8 +352,7 @@ const dialogManager = new AddSongsToPlaylistDialogManager()
 export function showAddSongsToPlaylistDialog(
   playlist: Playlist,
   onConfirm: (songs: VideoItem[]) => void,
-  mediaKuList: VideoItem[],
   onCancel?: () => void,
 ) {
-  dialogManager.showAddSongsToPlaylistDialog(playlist, onConfirm, mediaKuList,onCancel)
+  dialogManager.showAddSongsToPlaylistDialog(playlist, onConfirm, onCancel)
 }

+ 2 - 6
entry/src/main/ets/pages/PlaylistDetailPage.ets

@@ -31,7 +31,6 @@ interface PlaylistEventData {
 @Component
 export struct PlaylistDetailPage {
   context = this.getUIContext().getHostContext() as common.UIAbilityContext
-  @StorageProp('mediaKuList')  mediaKuList: Array<VideoItem> = []; //媒体库文件
   @State playlist: Playlist | null = null
   @State songList: VideoItem[] = []
   @State isLoading: boolean = true
@@ -59,7 +58,6 @@ export struct PlaylistDetailPage {
       this.playlistId = this.playlist.id
       this.loadPlaylistDetail()
     }
-    console.info('onecold mediaKuList 歌单详情页面 aboutToAppear='+this.mediaKuList.length)
     // 监听播放状态变化
     this.setupPlaybackStatusListener()
   }
@@ -1015,8 +1013,7 @@ export struct PlaylistDetailPage {
                     } else {
                       ToastUtil.showToast('添加歌曲失败')
                     }
-                  },
-                  this.mediaKuList!
+                  }
                 )
               })
               .stateStyles({
@@ -1110,8 +1107,7 @@ export struct PlaylistDetailPage {
           } else {
             ToastUtil.showToast('添加歌曲失败')
           }
-        },
-        this.mediaKuList
+        }
       )
     }
   }

+ 2 - 2
entry/src/main/ets/view/LocalMusic.ets

@@ -1314,7 +1314,7 @@ export struct LocalMusic {
 
   updateListData(mList: Array<VideoItem>, noSort?: boolean) {
 
-    animateTo({ duration: 888 }, () => {
+    animateTo({ duration: 666 }, () => {
       this.opacityItem = 0;
     });
     setTimeout(() => {
@@ -1326,7 +1326,7 @@ export struct LocalMusic {
         }
       }
       this.dataSource.pushArrayData(this.videoLocalList)
-      animateTo({ duration: 888 }, () => {
+      animateTo({ duration: 666 }, () => {
         this.opacityItem = 1;
       });
       this.setButtonStatus()