avatar.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { useGlobSetting } from '@jeesite/core/hooks/setting';
  2. import { toLocalMapUrl } from '@jeesite/core/utils/map/offlineMap';
  3. const { ctxPath } = useGlobSetting();
  4. const ABSOLUTE_IMAGE_RE = /^(data:image\/|https?:\/\/|blob:|file:|localmap:|\/\/)/i;
  5. const RAW_BASE64_RE = /^[A-Za-z0-9+/=\s]+$/;
  6. const WINDOWS_ABSOLUTE_PATH_RE = /^[A-Za-z]:[\\/]/;
  7. const WINDOWS_UNC_PATH_RE = /^\\\\[^\\]+\\[^\\]+/;
  8. const appendCtxPath = (path: string) => {
  9. const normalizedPath = path.startsWith('/') ? path : `/${path}`;
  10. return ctxPath ? `${ctxPath}${normalizedPath}` : normalizedPath;
  11. };
  12. export const normalizeAvatarSrc = (value?: string | null) => {
  13. const source = String(value ?? '').trim();
  14. if (!source) return '';
  15. if (/^file:\/\//i.test(source)) return toLocalMapUrl(source);
  16. if (ABSOLUTE_IMAGE_RE.test(source)) return source;
  17. if (WINDOWS_ABSOLUTE_PATH_RE.test(source) || WINDOWS_UNC_PATH_RE.test(source)) {
  18. return toLocalMapUrl(source);
  19. }
  20. if (source.startsWith('/ctxPath/')) {
  21. return appendCtxPath(source.replace(/^\/ctxPath\/?/i, ''));
  22. }
  23. if (source.startsWith('ctxPath/')) {
  24. return appendCtxPath(source.replace(/^ctxPath\/?/i, ''));
  25. }
  26. const isLikelyBase64 =
  27. RAW_BASE64_RE.test(source) &&
  28. !source.startsWith('/') &&
  29. !source.includes('.') &&
  30. !source.includes('?') &&
  31. !source.includes('&');
  32. if (isLikelyBase64) {
  33. return `data:image/png;base64,${source}`;
  34. }
  35. return appendCtxPath(source);
  36. };