aio-capacitor 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -1,4 +1,13 @@
1
- import { type I_logItem } from 'aio-utils';
1
+ import { Directory } from '@capacitor/filesystem';
2
+
3
+ type I_logItem = {
4
+ tags?: string[];
5
+ id?: string;
6
+ message: string;
7
+ status?: 'error' | 'success' | 'warning' | 'info';
8
+ data?: any;
9
+ date?: number;
10
+ };
2
11
  export type NotificationItem = {
3
12
  id: number;
4
13
  title: string;
@@ -55,7 +64,13 @@ export declare class AIOCapacitor {
55
64
  success: boolean;
56
65
  error: any;
57
66
  }>;
58
- shareFile: (file: Blob | File, fileName?: string) => Promise<any>;
67
+ shareFile: (file: Blob | File, fileName?: string) => Promise<FileResult<string> | {
68
+ success: boolean;
69
+ error?: undefined;
70
+ } | {
71
+ success: boolean;
72
+ error: any;
73
+ }>;
59
74
  getLocation: () => Promise<{
60
75
  success: boolean;
61
76
  latitude?: number;
@@ -112,30 +127,9 @@ export type I_FileRecord = {
112
127
  createdAt: number;
113
128
  meta?: any;
114
129
  };
115
- export declare class FileRegistry {
116
- private store;
117
- private onChange;
118
- private storageKey;
119
- isNative: boolean;
120
- private webStorage;
121
- private initialRecords;
122
- constructor(p: {
123
- onChange: (v: I_FileRecord[]) => void;
124
- storageKey: string;
125
- mock?: I_FileRecord[];
126
- });
127
- private init;
128
- private initialLoad;
129
- private save;
130
- add(p: {
131
- type: I_FileRecordType;
132
- path: string;
133
- name?: string;
134
- meta?: any;
135
- }): I_FileRecord;
136
- rename(id: string, newName?: string): I_FileRecord;
137
- remove(id: string): void;
138
- list: () => I_FileRecord[];
139
- getById: (id: string) => I_FileRecord | null;
140
- }
130
+ type FileResult<T> = {
131
+ success: boolean;
132
+ result: T;
133
+ message?: string;
134
+ };
141
135
  export {};
package/index.js CHANGED
@@ -18,7 +18,6 @@ import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
18
18
  import { Haptics, ImpactStyle } from '@capacitor/haptics';
19
19
  import { Share } from '@capacitor/share';
20
20
  import { LocalNotifications } from '@capacitor/local-notifications';
21
- import { FileClass, Storage } from 'aio-utils';
22
21
  import { KeepAwake } from '@capacitor-community/keep-awake';
23
22
  export class AIOCapacitor {
24
23
  constructor(p) {
@@ -49,7 +48,7 @@ export class AIOCapacitor {
49
48
  console.error('Haptics pattern error:', err);
50
49
  }
51
50
  });
52
- this.vibrateImpact = (...args_1) => __awaiter(this, [...args_1], void 0, function* (style = 'medium') {
51
+ this.vibrateImpact = (style = 'medium') => __awaiter(this, void 0, void 0, function* () {
53
52
  try {
54
53
  const map = {
55
54
  light: ImpactStyle.Light,
@@ -191,7 +190,7 @@ export class AIOCapacitor {
191
190
  return { success: false, error: (err === null || err === void 0 ? void 0 : err.message) || err };
192
191
  }
193
192
  });
194
- this.shareFile = (file_1, ...args_2) => __awaiter(this, [file_1, ...args_2], void 0, function* (file, fileName = `file_${Date.now()}`) {
193
+ this.shareFile = (file, fileName = `file_${Date.now()}`) => __awaiter(this, void 0, void 0, function* () {
195
194
  try {
196
195
  const res = yield new FileClass().toDataUrl(file);
197
196
  if (!res.success) {
@@ -434,98 +433,265 @@ export class Tracker {
434
433
  return !!this.watchId;
435
434
  }
436
435
  }
437
- export class FileRegistry {
438
- constructor(p) {
439
- this.store = new Map();
440
- this.storageKey = '';
436
+ class FileClass {
437
+ constructor() {
441
438
  this.isNative = false;
442
- this.initialRecords = [];
443
- this.init = () => __awaiter(this, void 0, void 0, function* () {
444
- yield this.initialLoad();
445
- this.onChange(this.list());
439
+ this.isUrl = (input) => input.startsWith("http://") || input.startsWith("https://") || input.startsWith("blob:");
440
+ this.isDataUrl = (input) => input.startsWith("data:");
441
+ this.toDataUrl = (input) => __awaiter(this, void 0, void 0, function* () {
442
+ const blobRes = yield this.toBlob(input);
443
+ if (!blobRes.success) {
444
+ return { success: false, result: "", message: blobRes.message };
445
+ }
446
+ const fr = new FileReader();
447
+ return new Promise((resolve) => {
448
+ fr.onload = () => resolve({ success: true, result: fr.result, message: "" });
449
+ fr.onerror = () => resolve({ success: false, result: "", message: "FileReader error" });
450
+ fr.readAsDataURL(blobRes.result);
451
+ });
446
452
  });
447
- this.initialLoad = () => __awaiter(this, void 0, void 0, function* () {
448
- let raw;
449
- if (!this.isNative) {
450
- raw = this.webStorage.load('records', this.initialRecords);
453
+ this.fileToText = (file) => __awaiter(this, void 0, void 0, function* () {
454
+ return new Promise((resolve, reject) => {
455
+ const fr = new FileReader();
456
+ fr.onload = () => {
457
+ try {
458
+ const result = fr.result;
459
+ resolve(result);
460
+ }
461
+ catch (error) {
462
+ reject(new Error('Error parsing JSON: ' + error.message));
463
+ }
464
+ };
465
+ fr.onerror = () => reject(new Error('Error reading file.'));
466
+ fr.readAsText(file);
467
+ });
468
+ });
469
+ this.readText = (input) => __awaiter(this, void 0, void 0, function* () {
470
+ if (typeof input === 'object' && 'path' in input && 'directory' in input) {
471
+ return yield this.readCapacitorText(input.path, input.directory);
451
472
  }
452
473
  else {
453
- raw = yield new AIOCapacitor().storageLoad(this.storageKey, this.initialRecords);
474
+ try {
475
+ const blobRes = yield this.toBlob(input);
476
+ if (!blobRes.success)
477
+ return blobRes;
478
+ let result = yield blobRes.result.text();
479
+ return { success: true, result, message: "" };
480
+ }
481
+ catch (e) {
482
+ return { success: false, result: "", message: (e === null || e === void 0 ? void 0 : e.message) || `read text failed` };
483
+ }
454
484
  }
455
- raw = raw === null || !raw ? [] : raw;
456
- this.store = new Map(raw.map((i) => [i.id, i]));
457
485
  });
458
- this.save = () => __awaiter(this, void 0, void 0, function* () {
459
- const raw = this.list();
460
- if (!this.isNative) {
461
- this.webStorage.save('records', raw);
486
+ this.readCapacitorText = (path, directory) => __awaiter(this, void 0, void 0, function* () {
487
+ try {
488
+ const res = yield this.pathToBase64(path, directory);
489
+ if (!res.success) {
490
+ return { success: false, result: null, message: 'Empty file' };
491
+ }
492
+ const blobRes = this.base64ToBlob(res.result);
493
+ if (!blobRes.success) {
494
+ return blobRes;
495
+ }
496
+ return this.readText(blobRes.result);
462
497
  }
463
- else {
464
- yield new AIOCapacitor().storageSave(this.storageKey, raw);
498
+ catch (e) {
499
+ return { success: false, result: null, message: (e === null || e === void 0 ? void 0 : e.message) || 'Storage read failed' };
465
500
  }
466
- this.onChange(raw);
467
501
  });
468
- this.list = () => [...this.store.values()];
469
- this.getById = (id) => this.store.get(id) || null;
470
- if (p.mock) {
471
- this.initialRecords = p.mock;
472
- }
473
- const a = new AIOCapacitor();
474
- this.webStorage = new Storage(p.storageKey);
475
- this.isNative = a.isNative();
476
- this.storageKey = p.storageKey;
477
- this.onChange = p.onChange;
478
- this.init();
479
- }
480
- add(p) {
481
- const { type, path, meta } = p;
482
- if (['image', 'file', 'json', 'text'].indexOf(type) === -1) {
483
- alert('file type should be image or file or json or text');
484
- return;
485
- }
486
- if (!path) {
487
- alert('missing file path');
488
- return;
489
- }
490
- const id = crypto.randomUUID();
491
- const createdAt = Date.now();
492
- const name = p.name || window.prompt('inter file name');
493
- if (!name || name === null) {
494
- return;
495
- }
496
- const records = this.list();
497
- if (records.find((o) => o.name === name)) {
498
- const res = window.confirm('a file by this name is already exist, do you want to overwrite?');
499
- if (!res) {
500
- return;
502
+ this.pathToBase64 = (path, directory) => __awaiter(this, void 0, void 0, function* () {
503
+ const a = new AIOCapacitor();
504
+ const res = yield a.readFile(path, directory);
505
+ if (!(res === null || res === void 0 ? void 0 : res.data)) {
506
+ return { success: false, result: null, message: 'Empty file' };
501
507
  }
502
- }
503
- const record = { id, createdAt, name, type, path, meta };
504
- this.store.set(id, record);
505
- this.save();
506
- return record;
507
- }
508
- rename(id, newName) {
509
- const record = this.getById(id);
510
- if (!record) {
511
- return;
512
- }
513
- const name = newName || window.prompt('inter file new name');
514
- if (!name || name === null) {
515
- return;
516
- }
517
- const records = this.list();
518
- if (records.find((o) => o.name === name)) {
519
- alert('a file by this name is already exist, you cannot rename');
520
- return;
521
- }
522
- const newRecord = Object.assign(Object.assign({}, record), { name });
523
- this.store.set(id, newRecord);
524
- this.save();
525
- return newRecord;
526
- }
527
- remove(id) {
528
- this.store.delete(id);
529
- this.save();
508
+ return { success: true, result: res.data, message: '' };
509
+ });
510
+ this.pathToSrc = (path, directory) => __awaiter(this, void 0, void 0, function* () { return yield new AIOCapacitor().pathToSrc(path, directory); });
511
+ this.toSrc = (file) => typeof file === 'string' ? file : window.URL.createObjectURL(file);
512
+ this.toBase64 = (input) => __awaiter(this, void 0, void 0, function* () {
513
+ const dataUrl = yield this.toDataUrl(input);
514
+ if (!dataUrl.success) {
515
+ return { success: false, result: "", message: dataUrl.message };
516
+ }
517
+ return this.dataUrlToBase64(dataUrl.result);
518
+ });
519
+ this.GetDurationByUrl = (url) => __awaiter(this, void 0, void 0, function* () {
520
+ return new Promise((resolve) => {
521
+ const video = document.createElement("video");
522
+ video.preload = "metadata";
523
+ video.src = url;
524
+ video.onloadedmetadata = () => { resolve(isNaN(video.duration) ? null : video.duration); video.remove(); };
525
+ video.onerror = () => { resolve(null); video.remove(); };
526
+ });
527
+ });
528
+ this.GetSizeByUrl = (url) => __awaiter(this, void 0, void 0, function* () {
529
+ let size = null;
530
+ try {
531
+ const res = yield fetch(url, { method: "HEAD" });
532
+ const contentLength = res.headers.get("content-length");
533
+ if (contentLength)
534
+ size = parseInt(contentLength, 10);
535
+ }
536
+ catch (err) { }
537
+ return size;
538
+ });
539
+ this.GetNameByUrl = (url) => { var _a; return decodeURIComponent(((_a = url.split("/").pop()) === null || _a === void 0 ? void 0 : _a.split("?")[0]) || "unknown"); };
540
+ this.GetFileDetailsByUrl = (url) => __awaiter(this, void 0, void 0, function* () {
541
+ const name = this.GetNameByUrl(url);
542
+ const size = yield this.GetSizeByUrl(url);
543
+ const duration = yield this.GetDurationByUrl(url);
544
+ return { name, size, duration };
545
+ });
546
+ this.fetchBlob = (url) => __awaiter(this, void 0, void 0, function* () {
547
+ try {
548
+ const res = yield fetch(url);
549
+ if (!res.ok) {
550
+ return { success: false, result: null, message: `HTTP Error: ${res.status}` };
551
+ }
552
+ const blob = yield res.blob();
553
+ return { success: true, result: blob, message: "" };
554
+ }
555
+ catch (e) {
556
+ return { success: false, result: null, message: (e === null || e === void 0 ? void 0 : e.message) || "Fetch failed" };
557
+ }
558
+ });
559
+ this.fetchBlob2 = () => __awaiter(this, void 0, void 0, function* () {
560
+ });
561
+ this.base64ToBlob = (base64) => {
562
+ try {
563
+ const byteCharacters = atob(base64);
564
+ const byteNumbers = new Array(byteCharacters.length);
565
+ for (let i = 0; i < byteCharacters.length; i++) {
566
+ byteNumbers[i] = byteCharacters.charCodeAt(i);
567
+ }
568
+ const byteArray = new Uint8Array(byteNumbers);
569
+ return { success: true, result: new Blob([byteArray]), message: "" };
570
+ }
571
+ catch (e) {
572
+ return { success: false, result: null, message: (e === null || e === void 0 ? void 0 : e.message) || "Invalid base64" };
573
+ }
574
+ };
575
+ this.handleFileName = (selectedName) => selectedName || window.prompt('Please Enter File Name') || `file-${Date.now()}.json`;
576
+ this.generateFileName = (mimeType) => {
577
+ const map = {
578
+ 'application/json': 'file.json',
579
+ 'text/plain': 'file.txt',
580
+ 'text/html': 'file.html',
581
+ 'text/csv': 'file.csv',
582
+ 'application/pdf': 'file.pdf',
583
+ 'image/png': 'image.png',
584
+ 'image/jpeg': 'image.jpg',
585
+ 'image/webp': 'image.webp',
586
+ 'application/zip': 'archive.zip',
587
+ 'application/octet-stream': 'file.bin'
588
+ };
589
+ const base = map[mimeType || ''] || 'file.bin';
590
+ const timestamp = Date.now();
591
+ const [name, ext] = base.split('.');
592
+ return `${name}-${timestamp}.${ext}`;
593
+ };
594
+ this.saveWeb = (url, fileName) => __awaiter(this, void 0, void 0, function* () {
595
+ const a = document.createElement('a');
596
+ a.href = url;
597
+ a.download = fileName;
598
+ document.body.appendChild(a);
599
+ a.click();
600
+ document.body.removeChild(a);
601
+ URL.revokeObjectURL(url);
602
+ return { success: true, message: '' };
603
+ });
604
+ this.dataUrlToBase64 = (dataUrl) => {
605
+ try {
606
+ const base64 = dataUrl.split(",")[1];
607
+ return { success: true, result: base64, message: "" };
608
+ }
609
+ catch (_a) {
610
+ return { success: false, result: "", message: "Invalid data url" };
611
+ }
612
+ };
613
+ this.toBlob = (input) => __awaiter(this, void 0, void 0, function* () {
614
+ try {
615
+ if (input instanceof Blob) {
616
+ return { success: true, result: input, message: "" };
617
+ }
618
+ if (input instanceof ArrayBuffer) {
619
+ const result = new Blob([input], { type: 'application/octet-stream' });
620
+ return { success: true, result };
621
+ }
622
+ if (input instanceof Uint8Array) {
623
+ const buffer = input.buffer instanceof ArrayBuffer ? input.buffer : new ArrayBuffer(input.byteLength);
624
+ const result = new Blob([new Uint8Array(buffer)], { type: 'application/octet-stream' });
625
+ return { success: true, result };
626
+ }
627
+ if (typeof input !== "string") {
628
+ const result = new Blob([JSON.stringify(input)], { type: 'application/json' });
629
+ return { success: true, result, message: "" };
630
+ }
631
+ if (this.isDataUrl(input)) {
632
+ const base64 = this.dataUrlToBase64(input);
633
+ if (!base64.success) {
634
+ return { success: false, result: null, message: base64.message };
635
+ }
636
+ return this.base64ToBlob(base64.result);
637
+ }
638
+ if (this.isUrl(input)) {
639
+ return yield this.fetchBlob(input);
640
+ }
641
+ return { success: false, result: null, message: "Unsupported input" };
642
+ }
643
+ catch (e) {
644
+ return { success: false, result: null, message: e === null || e === void 0 ? void 0 : e.message };
645
+ }
646
+ });
647
+ this.saveText = (text, path) => __awaiter(this, void 0, void 0, function* () {
648
+ try {
649
+ if (this.isNative) {
650
+ return yield new AIOCapacitor().save(text, path);
651
+ }
652
+ else {
653
+ const blob = new Blob([text], { type: "text/plain" });
654
+ const url = URL.createObjectURL(blob);
655
+ try {
656
+ return yield this.saveWeb(url, path);
657
+ }
658
+ finally {
659
+ URL.revokeObjectURL(url);
660
+ }
661
+ }
662
+ }
663
+ catch (e) {
664
+ return { success: false, message: (e === null || e === void 0 ? void 0 : e.message) || "Text download failed" };
665
+ }
666
+ });
667
+ this.saveFile = (input, path) => __awaiter(this, void 0, void 0, function* () {
668
+ const blobRes = yield new FileClass().toBlob(input);
669
+ if (!blobRes.success) {
670
+ return { success: false, message: blobRes.message };
671
+ }
672
+ if (this.isNative) {
673
+ return yield new AIOCapacitor().save(blobRes.result, path);
674
+ }
675
+ else {
676
+ const url = URL.createObjectURL(blobRes.result);
677
+ yield this.saveWeb(url, path);
678
+ return { success: true, message: '' };
679
+ }
680
+ });
681
+ this.sizeToString = (size) => {
682
+ if (typeof size !== "number")
683
+ size = 0;
684
+ const gb = size / (Math.pow(1024, 3));
685
+ const mb = size / (Math.pow(1024, 2));
686
+ const kb = size / 1024;
687
+ if (gb >= 1)
688
+ return gb.toFixed(2) + " GB";
689
+ if (mb >= 1)
690
+ return mb.toFixed(2) + " MB";
691
+ if (kb >= 1)
692
+ return kb.toFixed(2) + " KB";
693
+ return size + " byte";
694
+ };
695
+ this.isNative = new AIOCapacitor().isNative();
530
696
  }
531
697
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aio-capacitor",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -8,8 +8,6 @@
8
8
  "test": "echo \"Error: no test specified\" && exit 1"
9
9
  },
10
10
  "dependencies": {
11
- "aio-utils": "latest",
12
- "aio-input": "latest",
13
11
  "@capacitor/core": "^8.4.0",
14
12
  "@capacitor/preferences": "^8.0.1",
15
13
  "@capacitor/clipboard": "^8.0.1",
package/index.css DELETED
@@ -1,24 +0,0 @@
1
- .io-manager{
2
- display: flex;
3
- flex-direction: column;
4
- align-items: center;
5
- justify-content: center;
6
- gap: 1em;
7
- height:100%;
8
- }
9
- .io-manager-button{
10
- background:#e9d171;
11
- width:8em;
12
- height:8em;
13
- color:#111;
14
- font-weight:bold;
15
- border-radius:1em;
16
- display:flex;
17
- align-items: center;
18
- justify-content: center;
19
- }
20
- .io-manager-button .aio-input{
21
- background: none;
22
- border: none;
23
- padding: 0;
24
- }
package/react.d.ts DELETED
@@ -1,69 +0,0 @@
1
- import { type FC, type ReactNode } from "react";
2
- import { type I_FileRecord } from "./index";
3
- import './index.css';
4
- export declare const useCapacitorStorage: <T>(p: {
5
- key: string;
6
- def: T;
7
- debugId?: string;
8
- }) => {
9
- value: any;
10
- save: (value: T) => Promise<void>;
11
- getValue: () => any;
12
- change: (obj: Partial<T>) => Promise<void>;
13
- isLoaded: any;
14
- };
15
- export declare const useCapacitorStorageList: <T>(p: {
16
- key: string;
17
- def: T[];
18
- getId: (row: T) => any;
19
- }) => {
20
- value: any;
21
- add: (row: T) => Promise<void>;
22
- edit: (row: T) => Promise<void>;
23
- remove: (id: any) => Promise<void>;
24
- getById: (id: any) => any;
25
- change: (id: any, obj: Partial<T>) => Promise<void>;
26
- };
27
- export declare const useAwake: () => {
28
- awake: any;
29
- setAwake: (state?: boolean) => Promise<any>;
30
- };
31
- declare const useFileManager: (p: {
32
- mock?: boolean;
33
- fa?: boolean;
34
- storageKey: string;
35
- option?: {
36
- text?: (o: I_FileRecord) => ReactNode;
37
- subtext?: (o: I_FileRecord) => ReactNode;
38
- before?: (o: I_FileRecord) => ReactNode;
39
- onClick?: (o: I_FileRecord) => void;
40
- };
41
- }) => {
42
- mainProps: {
43
- mock?: boolean;
44
- fa?: boolean;
45
- storageKey: string;
46
- option?: {
47
- text?: (o: I_FileRecord) => ReactNode;
48
- subtext?: (o: I_FileRecord) => ReactNode;
49
- before?: (o: I_FileRecord) => ReactNode;
50
- onClick?: (o: I_FileRecord) => void;
51
- };
52
- };
53
- files: any;
54
- registery: any;
55
- click: (actionName: string, row: I_FileRecord) => void;
56
- getActions: (row: I_FileRecord) => {
57
- text: string;
58
- onClick: () => void;
59
- }[];
60
- };
61
- export declare const FileManager: FC<{
62
- hook: ReturnType<typeof useFileManager>;
63
- }>;
64
- export declare const IOManager: <T>({ data, onImport, onExport }: {
65
- data: T;
66
- onImport?: (v: T) => void;
67
- onExport?: () => void;
68
- }) => import("react/jsx-runtime").JSX.Element;
69
- export {};
package/react.js DELETED
@@ -1,171 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
11
- import { useEffect, useRef, useState } from "react";
12
- import { AIOCapacitor, FileRegistry } from "./index";
13
- import { GetSvg, FileClass } from "aio-utils";
14
- import { Cards, AIFile } from "aio-input";
15
- import './index.css';
16
- export const useCapacitorStorage = (p) => {
17
- const { key, def } = p;
18
- const [data, setData] = useState({ isLoaded: false, value: def });
19
- const dataRef = useRef(data);
20
- dataRef.current = data;
21
- const ac = new AIOCapacitor();
22
- const isNative = ac.isNative();
23
- const load = () => __awaiter(void 0, void 0, void 0, function* () {
24
- if (!isNative) {
25
- const newData = Object.assign(Object.assign({}, dataRef.current), { isLoaded: true });
26
- setData(newData);
27
- }
28
- else {
29
- const res = yield ac.storageLoad(key, def);
30
- const newData = Object.assign(Object.assign({}, dataRef.current), { value: res, isLoaded: true });
31
- setData(newData);
32
- }
33
- });
34
- const save = (value) => __awaiter(void 0, void 0, void 0, function* () {
35
- if (isNative) {
36
- yield ac.storageSave(key, value);
37
- }
38
- const newData = Object.assign(Object.assign({}, dataRef.current), { value });
39
- setData(newData);
40
- });
41
- const change = (obj) => __awaiter(void 0, void 0, void 0, function* () {
42
- const oldData = dataRef.current;
43
- const { value } = oldData;
44
- save(Object.assign(Object.assign({}, value), obj));
45
- });
46
- const getValue = () => dataRef.current.value;
47
- useEffect(() => { load(); }, []);
48
- return { value: data.value, save, getValue, change, isLoaded: data.isLoaded };
49
- };
50
- export const useCapacitorStorageList = (p) => {
51
- const { key, def } = p;
52
- const [value, setValue] = useState(def);
53
- const ac = new AIOCapacitor();
54
- const isNative = ac.isNative();
55
- const getById = (id) => value.filter((o) => p.getId(o) === id)[0];
56
- const load = () => __awaiter(void 0, void 0, void 0, function* () {
57
- if (!ac.isNative()) {
58
- return;
59
- }
60
- const res = yield ac.storageLoad(key, def);
61
- setValue(res);
62
- });
63
- const save = (value) => __awaiter(void 0, void 0, void 0, function* () {
64
- if (isNative) {
65
- yield ac.storageSave(key, value);
66
- }
67
- setValue(value);
68
- });
69
- const add = (row) => __awaiter(void 0, void 0, void 0, function* () { return yield save([...value, Object.assign({}, row)]); });
70
- const edit = (row) => __awaiter(void 0, void 0, void 0, function* () {
71
- const newValue = value.map((o) => {
72
- if (p.getId(o) === p.getId(row)) {
73
- return row;
74
- }
75
- return o;
76
- });
77
- save(newValue);
78
- });
79
- const change = (id, obj) => __awaiter(void 0, void 0, void 0, function* () {
80
- const row = getById(id);
81
- if (!row) {
82
- return;
83
- }
84
- yield edit(Object.assign(Object.assign({}, row), obj));
85
- });
86
- const remove = (id) => __awaiter(void 0, void 0, void 0, function* () { return yield save(value.filter((o) => p.getId(o) !== id)); });
87
- useEffect(() => { load(); }, []);
88
- return { value, add, edit, remove, getById, change };
89
- };
90
- export const useAwake = () => {
91
- const ac = new AIOCapacitor();
92
- const [awake, setAwake] = useState(false);
93
- const getAwake = () => __awaiter(void 0, void 0, void 0, function* () {
94
- const awake = yield ac.isAwake();
95
- setAwake(awake.isKeptAwake);
96
- });
97
- useEffect(() => {
98
- getAwake();
99
- }, []);
100
- return { awake, setAwake: ac.awake };
101
- };
102
- const useFileManager = (p) => {
103
- const [files, setFiles] = useState([]);
104
- const registeryRef = useRef(undefined);
105
- useEffect(() => {
106
- const mock = [
107
- { name: 'file1', id: '64563454564', path: './ddsd/sddgf', "createdAt": Date.now(), type: 'text' },
108
- { name: 'file2', id: '7664564', path: './ddsd/sddgf', "createdAt": Date.now(), type: 'text' },
109
- { name: 'file3', id: '876456464', path: './ddsd/sddgf', "createdAt": Date.now(), type: 'text' },
110
- { name: 'file4', id: '544745345', path: './ddsd/sddgf', "createdAt": Date.now(), type: 'text' },
111
- { name: 'file5', id: '8965565', path: './ddsd/sddgf', "createdAt": Date.now(), type: 'text' },
112
- ];
113
- registeryRef.current = new FileRegistry({ storageKey: p.storageKey, onChange: (v) => setFiles(v), mock: p.mock ? mock : undefined });
114
- }, []);
115
- const click = (actionName, row) => {
116
- const registery = registeryRef.current;
117
- if (registery) {
118
- if (actionName === 'rename') {
119
- registery.rename(row.id);
120
- }
121
- else if (actionName === 'remove') {
122
- registery.remove(row.id);
123
- }
124
- }
125
- };
126
- const getActions = (row) => {
127
- return [
128
- { text: p.fa ? 'تغییر نام' : 'Rename', onClick: () => click('rename', row) },
129
- { text: p.fa ? 'حذف' : 'Remove', onClick: () => click('remove', row) },
130
- ];
131
- };
132
- return { mainProps: p, files, registery: registeryRef.current, click, getActions };
133
- };
134
- export const FileManager = ({ hook }) => {
135
- const { mainProps } = hook;
136
- const { option = {} } = mainProps;
137
- return (_jsx("div", { className: "fr-list", children: _jsx(Cards, { items: hook.files, option: {
138
- text: (row) => !option.text ? row.name : option.text(row),
139
- subtext: (row) => !option.subtext ? undefined : option.subtext(row),
140
- before: (row) => !(option === null || option === void 0 ? void 0 : option.before) ? new GetSvg().getIcon('mdiFile', 0.7) : option.before(row),
141
- actions: (o) => hook.getActions(o)
142
- } }) }));
143
- };
144
- export const IOManager = ({ data, onImport, onExport }) => {
145
- const importData = (file) => __awaiter(void 0, void 0, void 0, function* () {
146
- if (!onImport) {
147
- return;
148
- }
149
- const res = yield new FileClass().readText(file);
150
- if (res.success) {
151
- onImport(JSON.parse(res.result));
152
- }
153
- else {
154
- alert(res.message);
155
- }
156
- });
157
- const exportData = () => __awaiter(void 0, void 0, void 0, function* () {
158
- if (!onExport) {
159
- return;
160
- }
161
- const f = new FileClass();
162
- const res = yield f.saveFile(data, 'finance-data.json');
163
- if (res.success) {
164
- onExport();
165
- }
166
- else {
167
- alert(res.message);
168
- }
169
- });
170
- return (_jsxs("div", { className: "io-manager", children: [!!onImport && _jsx("div", { className: "io-manager-button", children: _jsx(AIFile, { text: 'Import', onChange: (file) => importData(file) }) }), !!onExport && _jsx("div", { className: "io-manager-button", onClick: () => exportData(), children: "Export" })] }));
171
- };