• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import { BYTE } from '../constants/Constant';
17import LanguageUtil from './LanguageUtil';
18import { FileMimeTypeUtil } from './FileMimeTypeUtil';
19import { MimeType } from '../../databases/model/MimeType';
20import Logger from '../log/Logger';
21import { FileBase } from '../../databases/model/base/FileBase';
22
23const TAG = 'Tools';
24
25/**
26 *  格式化显示大小
27 */
28export const renderSize = (value, carry = BYTE.ONE_KB) => {
29  if (!value) {
30    return '0 B';
31  }
32  let unitArr = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
33  const srcSize = parseFloat(value);
34  let index = Math.floor(Math.log(srcSize) / Math.log(BYTE.ONE_KB));
35  let size = srcSize / Math.pow(BYTE.ONE_KB, index);
36  if (size >= carry) {
37    size = size / BYTE.ONE_KB;
38    index++;
39  }
40  //  保留的小数位数
41  return size.toFixed(2) + ' ' + unitArr[index];
42}
43
44/**
45 * @description 截取文件名后缀 文件格式
46 * @param fileName 文件名带后缀
47 */
48export const formatSuffix = (fileName: string) => {
49  if (!fileName) {
50    return '';
51  }
52  let newValue = fileName.split('.');
53  if (newValue[newValue.length - 1].toUpperCase() === FileMimeTypeUtil.SUFFIX_DLP) {
54    newValue.pop();
55  }
56  return newValue.pop().toUpperCase();
57}
58
59/**
60 * @description 多选框选中状态
61 * @param flag 是否选中
62 */
63export const getRightIcon = (flag) => {
64  return flag ? $r('app.media.checkbox_b') : $r('app.media.checkbox_g');
65}
66
67/**
68 * @description 生成随机id
69 * @param
70 */
71export const randomId = (): string => {
72  let str: string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
73  let res: string = '';
74  for (let i = 0; i < 6; i++) {
75    // 随机产生字符串的下标
76    let n = parseInt(Math.random() * str.length + '');
77    res += str[n];
78  }
79  return res;
80}
81
82/**
83 * @description 获取指定资源ID对应的字符串
84 * @param resource: 指定资源
85 * @return
86 */
87export function getResourceString(resource: Resource, ...args): string {
88  let isString = /%s/; // 字符串类型
89  let isNum = /%d/; // 数字类型
90  let resStr = '';
91  try {
92    resStr = globalThis.abilityContext.resourceManager.getStringSync(resource.id);
93  } catch (error) {
94    Logger.e(TAG, `getResourceString bundleName: ${globalThis.abilityContext.abilityInfo.bundleName}` +
95      `, abilityName: ${globalThis.abilityContext.abilityInfo.name}`);
96    Logger.e(TAG, `getResourceString error,message: ${error}, Resource:${JSON.stringify(resource)}`);
97    return resStr;
98  }
99
100  if (args.length) {
101    args.forEach(item => {
102      if (typeof item === 'string') {
103        resStr = resStr.replace(isString, item);
104      } else if (typeof item === 'number') {
105        resStr = resStr.replace(isNum, item.toString());
106      }
107    })
108  }
109  return resStr;
110}
111
112/**
113 * @description 获取文件夹/文件图标
114 * @param Object<FilesData> 文件对象
115 */
116export const getFileIcon = (fileName: string, isFolder: boolean = false): MimeType => {
117  if (isFolder) {
118    return new MimeType(
119      null,
120      MimeType.FILE_CATEGORY_UNKNOW,
121      FileMimeTypeUtil.FILE_TYPE_UNKNOW,
122      $r('app.media.hidisk_icon_folder'),
123      $r('app.media.hidisk_icon_folder_grid'),
124      $r('app.media.hidisk_icon_folder_grid'),
125      null
126    );
127  }
128  return FileMimeTypeUtil.getFileMimeType(fileName);
129}
130
131/**
132 * @description 实现文件排序,时间倒序
133 * @param dataList: 待排序的文件列表
134 */
135export const sortDataByTime = (dataList) => {
136  // 按照时间排序
137  // 规避@State修饰的数组变量执行sort方法不生效问题
138  const fileList = dataList.filter(item => item);
139  return fileList.sort((a, b) => {
140    if (b.mtime !== a.mtime) {
141      return b.mtime - a.mtime;
142    } else {
143      return compareStr(a.fileName, b.fileName);
144    }
145  })
146}
147
148function compareStr(str1: string, str2: string) {
149  const language = LanguageUtil.getSystemLanguage();
150  return str2.localeCompare(str1, language);
151}
152
153export const gridName = (fileName) => {
154  // 文件名超长是中间部分'...'显示
155  const MAX_LENGTH = 11;
156  if (fileName.length > MAX_LENGTH) {
157    return fileName.slice(0, 6) + '...' + fileName.slice(-5);
158  } else {
159    return fileName;
160  }
161}
162
163/**
164 * @description 获取当前文件是否是DLP文件
165 * @param value: 文件名
166 * @result true/false
167 */
168export const isDlpFile = (value): boolean => {
169  let newValue = value.split('.');
170  if (newValue.pop().toUpperCase() === 'DLP') {
171    return true;
172  }
173  return false;
174}
175
176
177export const sortBaseDataByOrderTime = (dataList: Array<FileBase>, isDesc: boolean = false) => {
178  // 规避@State修饰的数组变量执行sort方法不生效问题
179  const fileList = dataList.filter(item => item);
180  return fileList.sort((a, b) => {
181    if (b.modifyTime !== a.modifyTime) {
182      return isDesc ? b.modifyTime - a.modifyTime : a.modifyTime - b.modifyTime;
183    } else {
184      const language = LanguageUtil.getSystemLanguage();
185      return isDesc ? b.fileName.localeCompare(a.fileName, language) : a.fileName.localeCompare(b.fileName, language);
186    }
187  })
188}