cellLocal.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const CELL_LOCAL_PATH_KEY = 'CELL_LOCAL_PATH__';
  2. const CELL_LOCAL_SERVER_PATH_KEY = 'CELL_LOCAL_SERVER_PATH__';
  3. export const CELL_LOCAL_PATH_CHANGED_EVENT = 'cell-local-path-changed';
  4. const FILE_PROTOCOL = 'file://';
  5. export function isValidCellLocalPath(value: string) {
  6. const text = String(value || '')
  7. .trim()
  8. .replace(/[\\/]+$/, '');
  9. if (!text) return false;
  10. if (text === '[object Object]') return false;
  11. if (text === 'null' || text === 'undefined') return false;
  12. if (!/\.bin$/i.test(text)) return false;
  13. return /^[a-zA-Z]:[\\/]/.test(text) || /^\\\\/.test(text) || text.startsWith('/') || text.startsWith(FILE_PROTOCOL);
  14. }
  15. function normalizePath(value: string) {
  16. const text = String(value || '')
  17. .trim()
  18. .replace(/[\\/]+$/, '');
  19. if (!isValidCellLocalPath(text)) return '';
  20. return text;
  21. }
  22. export function getCellLocalPath() {
  23. try {
  24. const serverPath = normalizePath(window.localStorage.getItem(CELL_LOCAL_SERVER_PATH_KEY) || '');
  25. if (serverPath) return serverPath;
  26. return normalizePath(window.localStorage.getItem(CELL_LOCAL_PATH_KEY) || '');
  27. } catch {
  28. return '';
  29. }
  30. }
  31. export function getManualCellLocalPath() {
  32. try {
  33. return normalizePath(window.localStorage.getItem(CELL_LOCAL_PATH_KEY) || '');
  34. } catch {
  35. return '';
  36. }
  37. }
  38. export function getServerCellLocalPath() {
  39. try {
  40. return normalizePath(window.localStorage.getItem(CELL_LOCAL_SERVER_PATH_KEY) || '');
  41. } catch {
  42. return '';
  43. }
  44. }
  45. export function setCellLocalPath(path: string) {
  46. const normalized = normalizePath(path);
  47. try {
  48. if (!normalized) {
  49. window.localStorage.removeItem(CELL_LOCAL_PATH_KEY);
  50. window.dispatchEvent(new CustomEvent(CELL_LOCAL_PATH_CHANGED_EVENT, { detail: '' }));
  51. return;
  52. }
  53. window.localStorage.setItem(CELL_LOCAL_PATH_KEY, normalized);
  54. window.dispatchEvent(new CustomEvent(CELL_LOCAL_PATH_CHANGED_EVENT, { detail: normalized }));
  55. } catch {}
  56. }
  57. export function clearCellLocalPath() {
  58. setCellLocalPath('');
  59. }
  60. export function setServerCellLocalPath(path: string) {
  61. const normalized = normalizePath(path);
  62. try {
  63. if (!normalized) {
  64. window.localStorage.removeItem(CELL_LOCAL_SERVER_PATH_KEY);
  65. window.dispatchEvent(new CustomEvent(CELL_LOCAL_PATH_CHANGED_EVENT, { detail: getCellLocalPath() }));
  66. return;
  67. }
  68. window.localStorage.setItem(CELL_LOCAL_SERVER_PATH_KEY, normalized);
  69. window.dispatchEvent(new CustomEvent(CELL_LOCAL_PATH_CHANGED_EVENT, { detail: normalized }));
  70. } catch {}
  71. }