@sendbird/uikit-utils 2.3.0 → 2.4.1
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/lib/commonjs/hooks/index.js +38 -1
- package/lib/commonjs/hooks/index.js.map +1 -1
- package/lib/commonjs/hooks/react-native.js +5 -7
- package/lib/commonjs/hooks/react-native.js.map +1 -1
- package/lib/commonjs/index.js +65 -118
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/sendbird/channel.js +29 -1
- package/lib/commonjs/sendbird/channel.js.map +1 -1
- package/lib/commonjs/sendbird/message.js +56 -1
- package/lib/commonjs/sendbird/message.js.map +1 -1
- package/lib/commonjs/sendbird/user.js +0 -6
- package/lib/commonjs/sendbird/user.js.map +1 -1
- package/lib/commonjs/shared/file.js +225 -0
- package/lib/commonjs/shared/file.js.map +1 -0
- package/lib/commonjs/shared/index.js +18 -39
- package/lib/commonjs/shared/index.js.map +1 -1
- package/lib/commonjs/shared/regex.js +1 -46
- package/lib/commonjs/shared/regex.js.map +1 -1
- package/lib/commonjs/types.js.map +1 -1
- package/lib/commonjs/ui-format/openChannel.js +22 -0
- package/lib/commonjs/ui-format/openChannel.js.map +1 -0
- package/lib/module/hooks/index.js +29 -1
- package/lib/module/hooks/index.js.map +1 -1
- package/lib/module/hooks/react-native.js +6 -8
- package/lib/module/hooks/react-native.js.map +1 -1
- package/lib/module/index.js +11 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/sendbird/channel.js +23 -1
- package/lib/module/sendbird/channel.js.map +1 -1
- package/lib/module/sendbird/message.js +51 -1
- package/lib/module/sendbird/message.js.map +1 -1
- package/lib/module/sendbird/user.js +0 -4
- package/lib/module/sendbird/user.js.map +1 -1
- package/lib/module/shared/file.js +192 -0
- package/lib/module/shared/file.js.map +1 -0
- package/lib/module/shared/index.js +15 -32
- package/lib/module/shared/index.js.map +1 -1
- package/lib/module/shared/regex.js +0 -33
- package/lib/module/shared/regex.js.map +1 -1
- package/lib/module/types.js.map +1 -1
- package/lib/module/ui-format/openChannel.js +10 -0
- package/lib/module/ui-format/openChannel.js.map +1 -0
- package/lib/typescript/src/hooks/index.d.ts +3 -0
- package/lib/typescript/src/index.d.ts +10 -5
- package/lib/typescript/src/sendbird/channel.d.ts +10 -1
- package/lib/typescript/src/sendbird/message.d.ts +3 -0
- package/lib/typescript/src/sendbird/user.d.ts +0 -2
- package/lib/typescript/src/shared/file.d.ts +68 -0
- package/lib/typescript/src/shared/index.d.ts +13 -13
- package/lib/typescript/src/shared/regex.d.ts +0 -6
- package/lib/typescript/src/types.d.ts +8 -3
- package/lib/typescript/src/ui-format/openChannel.d.ts +3 -0
- package/package.json +4 -4
- package/src/hooks/index.ts +31 -1
- package/src/hooks/react-native.ts +6 -8
- package/src/index.ts +20 -20
- package/src/sendbird/channel.ts +33 -2
- package/src/sendbird/message.ts +54 -1
- package/src/sendbird/user.ts +0 -7
- package/src/shared/file.ts +193 -0
- package/src/shared/index.ts +15 -32
- package/src/shared/regex.ts +0 -34
- package/src/types.ts +17 -2
- package/src/ui-format/openChannel.ts +11 -0
- package/lib/commonjs/shared/pubsub.js +0 -54
- package/lib/commonjs/shared/pubsub.js.map +0 -1
- package/lib/module/shared/pubsub.js +0 -45
- package/lib/module/shared/pubsub.js.map +0 -1
- package/lib/typescript/src/shared/pubsub.d.ts +0 -8
- package/src/shared/pubsub.ts +0 -42
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.audioExtRegex = void 0;
|
|
7
|
+
exports.getDownscaleSize = getDownscaleSize;
|
|
8
|
+
exports.getFileExtension = getFileExtension;
|
|
9
|
+
exports.getFileExtensionFromMime = getFileExtensionFromMime;
|
|
10
|
+
exports.getFileExtensionFromUri = getFileExtensionFromUri;
|
|
11
|
+
exports.getFileType = void 0;
|
|
12
|
+
exports.getMimeFromFileExtension = getMimeFromFileExtension;
|
|
13
|
+
exports.imageExtRegex = void 0;
|
|
14
|
+
exports.isImage = isImage;
|
|
15
|
+
exports.normalizeFileName = normalizeFileName;
|
|
16
|
+
exports.parseMimeType = parseMimeType;
|
|
17
|
+
exports.shouldCompressImage = shouldCompressImage;
|
|
18
|
+
exports.videoExtRegex = void 0;
|
|
19
|
+
const EXTENSION_MIME_MAP = {
|
|
20
|
+
// Image
|
|
21
|
+
'jpeg': 'image/jpeg',
|
|
22
|
+
'jpg': 'image/jpeg',
|
|
23
|
+
'png': 'image/png',
|
|
24
|
+
'gif': 'image/gif',
|
|
25
|
+
'webp': 'image/webp',
|
|
26
|
+
'svg': 'image/svg+xml',
|
|
27
|
+
// Video
|
|
28
|
+
'3gp': 'video/3gpp',
|
|
29
|
+
'mp4': 'video/mp4',
|
|
30
|
+
'mpeg': 'video/mpeg',
|
|
31
|
+
'ogv': 'video/ogg',
|
|
32
|
+
'video/quicktime': 'mov',
|
|
33
|
+
'webm': 'video/webm',
|
|
34
|
+
'avi': 'video/x-msvideo',
|
|
35
|
+
// Audio
|
|
36
|
+
'aac': 'audio/aac',
|
|
37
|
+
'mid': 'audio/midi',
|
|
38
|
+
'mp3': 'audio/mpeg',
|
|
39
|
+
'ogg': 'audio/ogg',
|
|
40
|
+
'wav': 'audio/wav',
|
|
41
|
+
'weba': 'audio/webm',
|
|
42
|
+
// Files
|
|
43
|
+
'txt': 'text/plain',
|
|
44
|
+
'pdf': 'application/pdf',
|
|
45
|
+
'doc': 'application/msword',
|
|
46
|
+
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
47
|
+
'xls': 'application/vnd.ms-excel',
|
|
48
|
+
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
49
|
+
'ppt': 'application/vnd.ms-powerpoint',
|
|
50
|
+
'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
51
|
+
'zip': 'application/zip',
|
|
52
|
+
'json': 'application/json',
|
|
53
|
+
'gzip': 'application/x-gzip'
|
|
54
|
+
};
|
|
55
|
+
const imageExtRegex = /jpeg|jpg|png|webp|gif/i;
|
|
56
|
+
exports.imageExtRegex = imageExtRegex;
|
|
57
|
+
const audioExtRegex = /3gp|aac|aax|act|aiff|flac|gsm|m4a|m4b|m4p|tta|wma|mp3|webm|wav/i;
|
|
58
|
+
exports.audioExtRegex = audioExtRegex;
|
|
59
|
+
const videoExtRegex = /mov|vod|mp4|avi/i;
|
|
60
|
+
exports.videoExtRegex = videoExtRegex;
|
|
61
|
+
|
|
62
|
+
const getFileType = extOrType => {
|
|
63
|
+
if (extOrType.indexOf('/') > -1) {
|
|
64
|
+
const type = extOrType.split('/')[0];
|
|
65
|
+
if (type === 'video') return 'video';
|
|
66
|
+
if (type === 'audio') return 'audio';
|
|
67
|
+
if (type === 'image') return 'image';
|
|
68
|
+
return 'file';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (extOrType.match(imageExtRegex)) return 'image';
|
|
72
|
+
if (extOrType.match(audioExtRegex)) return 'audio';
|
|
73
|
+
if (extOrType.match(videoExtRegex)) return 'video';
|
|
74
|
+
return 'file';
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Calculates the downscaled size of an image while preserving its aspect ratio.
|
|
78
|
+
*
|
|
79
|
+
* @param {Object} origin - The original size object with `width` and `height` properties.
|
|
80
|
+
* @param {Object} resizing - The resizing object with optional `width` and `height` properties.
|
|
81
|
+
* @returns {Object} - A new size object with the downscaled `width` and `height` properties.
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* getDownscaleSize({ width: 1200, height: 800 }, { width: 600 }); // returns { width: 600, height: 400 }
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
exports.getFileType = getFileType;
|
|
90
|
+
|
|
91
|
+
function getDownscaleSize(origin, resizing) {
|
|
92
|
+
let ratio;
|
|
93
|
+
const maxWidth = resizing.width || origin.width,
|
|
94
|
+
maxHeight = resizing.height || origin.height;
|
|
95
|
+
|
|
96
|
+
if (origin.width <= maxWidth && origin.height <= maxHeight) {
|
|
97
|
+
ratio = 1;
|
|
98
|
+
} else if (origin.width > maxWidth && origin.height <= maxHeight) {
|
|
99
|
+
ratio = maxWidth / origin.width;
|
|
100
|
+
} else if (origin.width <= maxWidth && origin.height > maxHeight) {
|
|
101
|
+
ratio = maxHeight / origin.height;
|
|
102
|
+
} else {
|
|
103
|
+
ratio = Math.min(maxWidth / origin.width, maxHeight / origin.height);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
width: origin.width * ratio,
|
|
108
|
+
height: origin.height * ratio
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Normalize a file name by ensuring it has the given extension, if it doesn't already.
|
|
113
|
+
*
|
|
114
|
+
* @param {string} fileName - The file name to normalize.
|
|
115
|
+
* @param {string} extension - The desired extension, without a leading period.
|
|
116
|
+
* @returns {string} - The normalized file name, with the extension.
|
|
117
|
+
*/
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
function normalizeFileName(fileName, extension) {
|
|
121
|
+
if (!extension) return fileName; // .extension
|
|
122
|
+
|
|
123
|
+
let _extension = extension.toLowerCase();
|
|
124
|
+
|
|
125
|
+
if (_extension.indexOf('.') !== 0) {
|
|
126
|
+
_extension = '.' + _extension;
|
|
127
|
+
} // filename.extension | filename
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
const _filename = fileName.toLowerCase();
|
|
131
|
+
|
|
132
|
+
const hasExtension = _filename.lastIndexOf(_extension) === _filename.length - _extension.length;
|
|
133
|
+
|
|
134
|
+
if (!hasExtension) {
|
|
135
|
+
// filename.extension
|
|
136
|
+
return fileName + _extension;
|
|
137
|
+
} else {
|
|
138
|
+
// filename.extension
|
|
139
|
+
return fileName;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Parses a MIME type string into its components.
|
|
144
|
+
*
|
|
145
|
+
* @param mimeType - The MIME type string to parse.
|
|
146
|
+
* @returns An object containing the type, subtype, and parameters of the MIME type.
|
|
147
|
+
*/
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
function parseMimeType(mimeType) {
|
|
151
|
+
const [fullType, ...parts] = mimeType.split(';');
|
|
152
|
+
const [type, subtype] = fullType.split('/');
|
|
153
|
+
const parameters = {};
|
|
154
|
+
|
|
155
|
+
for (const part of parts) {
|
|
156
|
+
const [name, value] = part.trim().split('=');
|
|
157
|
+
parameters[name] = value;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
type,
|
|
162
|
+
subtype,
|
|
163
|
+
parameters
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Returns the file extension based on the MIME type.
|
|
168
|
+
*
|
|
169
|
+
* @param {string | null | undefined} mimeType - The MIME type to look up.
|
|
170
|
+
* @returns {string} - The file extension for the given MIME type, or an empty string if no matching file extension was found.
|
|
171
|
+
*/
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
function getFileExtensionFromMime(mimeType) {
|
|
175
|
+
if (!mimeType) return '';
|
|
176
|
+
const MIME_EXTENSION_MAP = Object.entries(EXTENSION_MIME_MAP).reduce((acc, _ref) => {
|
|
177
|
+
let [key, value] = _ref;
|
|
178
|
+
acc[value] = key;
|
|
179
|
+
return acc;
|
|
180
|
+
}, {});
|
|
181
|
+
return MIME_EXTENSION_MAP[mimeType.toLowerCase()] || '';
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Returns the MIME type based on the file extension.
|
|
185
|
+
*
|
|
186
|
+
* @param {string | null | undefined} ext - The file extension to look up.
|
|
187
|
+
* @returns {string} - The MIME type for the given file extension, or an empty string if no matching MIME type was found.
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
function getMimeFromFileExtension(ext) {
|
|
192
|
+
if (!ext) return '';
|
|
193
|
+
return EXTENSION_MIME_MAP[ext.toLowerCase()] || '';
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Returns the file extension of a file path.
|
|
197
|
+
*
|
|
198
|
+
* @param {string} filePath - The file path to extract the extension from.
|
|
199
|
+
* @returns {string} - The file extension, or an empty string if the file path does not have an extension.
|
|
200
|
+
*/
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
function getFileExtension(filePath) {
|
|
204
|
+
const pathWithoutParams = filePath.split('?')[0];
|
|
205
|
+
const idx = pathWithoutParams.lastIndexOf('.');
|
|
206
|
+
if (idx === -1) return '';
|
|
207
|
+
const result = pathWithoutParams.slice(idx - pathWithoutParams.length).toLowerCase();
|
|
208
|
+
if (result === '.') return '';else return result;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function getFileExtensionFromUri(uri) {
|
|
212
|
+
return fetch(uri).then(response => response.headers.get('content-type'));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function isImage(filePath, mimeType) {
|
|
216
|
+
const type = getFileType(mimeType || getFileExtension(filePath));
|
|
217
|
+
return type === 'image';
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function shouldCompressImage(mime) {
|
|
221
|
+
let compressionEnabled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
|
|
222
|
+
const extension = getFileExtensionFromMime(mime);
|
|
223
|
+
return Boolean(extension.match(/jpg|jpeg|png/i) && compressionEnabled);
|
|
224
|
+
}
|
|
225
|
+
//# sourceMappingURL=file.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["EXTENSION_MIME_MAP","imageExtRegex","audioExtRegex","videoExtRegex","getFileType","extOrType","indexOf","type","split","match","getDownscaleSize","origin","resizing","ratio","maxWidth","width","maxHeight","height","Math","min","normalizeFileName","fileName","extension","_extension","toLowerCase","_filename","hasExtension","lastIndexOf","length","parseMimeType","mimeType","fullType","parts","subtype","parameters","part","name","value","trim","getFileExtensionFromMime","MIME_EXTENSION_MAP","Object","entries","reduce","acc","key","getMimeFromFileExtension","ext","getFileExtension","filePath","pathWithoutParams","idx","result","slice","getFileExtensionFromUri","uri","fetch","then","response","headers","get","isImage","shouldCompressImage","mime","compressionEnabled","Boolean"],"sources":["file.ts"],"sourcesContent":["const EXTENSION_MIME_MAP = {\n // Image\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'png': 'image/png',\n 'gif': 'image/gif',\n 'webp': 'image/webp',\n 'svg': 'image/svg+xml',\n\n // Video\n '3gp': 'video/3gpp',\n 'mp4': 'video/mp4',\n 'mpeg': 'video/mpeg',\n 'ogv': 'video/ogg',\n 'video/quicktime': 'mov',\n 'webm': 'video/webm',\n 'avi': 'video/x-msvideo',\n\n // Audio\n 'aac': 'audio/aac',\n 'mid': 'audio/midi',\n 'mp3': 'audio/mpeg',\n 'ogg': 'audio/ogg',\n 'wav': 'audio/wav',\n 'weba': 'audio/webm',\n\n // Files\n 'txt': 'text/plain',\n 'pdf': 'application/pdf',\n 'doc': 'application/msword',\n 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'xls': 'application/vnd.ms-excel',\n 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'ppt': 'application/vnd.ms-powerpoint',\n 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'zip': 'application/zip',\n 'json': 'application/json',\n 'gzip': 'application/x-gzip',\n} as Record<string, string>;\n\nexport const imageExtRegex = /jpeg|jpg|png|webp|gif/i;\nexport const audioExtRegex = /3gp|aac|aax|act|aiff|flac|gsm|m4a|m4b|m4p|tta|wma|mp3|webm|wav/i;\nexport const videoExtRegex = /mov|vod|mp4|avi/i;\nexport const getFileType = (extOrType: string) => {\n if (extOrType.indexOf('/') > -1) {\n const type = extOrType.split('/')[0];\n if (type === 'video') return 'video';\n if (type === 'audio') return 'audio';\n if (type === 'image') return 'image';\n return 'file';\n }\n\n if (extOrType.match(imageExtRegex)) return 'image';\n if (extOrType.match(audioExtRegex)) return 'audio';\n if (extOrType.match(videoExtRegex)) return 'video';\n return 'file';\n};\n\n/**\n * Calculates the downscaled size of an image while preserving its aspect ratio.\n *\n * @param {Object} origin - The original size object with `width` and `height` properties.\n * @param {Object} resizing - The resizing object with optional `width` and `height` properties.\n * @returns {Object} - A new size object with the downscaled `width` and `height` properties.\n * @example\n * ```ts\n * getDownscaleSize({ width: 1200, height: 800 }, { width: 600 }); // returns { width: 600, height: 400 }\n * ```\n */\ntype Size = { width: number; height: number };\nexport function getDownscaleSize(origin: Size, resizing: Partial<Size>) {\n let ratio: number;\n\n const maxWidth = resizing.width || origin.width,\n maxHeight = resizing.height || origin.height;\n\n if (origin.width <= maxWidth && origin.height <= maxHeight) {\n ratio = 1;\n } else if (origin.width > maxWidth && origin.height <= maxHeight) {\n ratio = maxWidth / origin.width;\n } else if (origin.width <= maxWidth && origin.height > maxHeight) {\n ratio = maxHeight / origin.height;\n } else {\n ratio = Math.min(maxWidth / origin.width, maxHeight / origin.height);\n }\n\n return { width: origin.width * ratio, height: origin.height * ratio };\n}\n\n/**\n * Normalize a file name by ensuring it has the given extension, if it doesn't already.\n *\n * @param {string} fileName - The file name to normalize.\n * @param {string} extension - The desired extension, without a leading period.\n * @returns {string} - The normalized file name, with the extension.\n */\nexport function normalizeFileName(fileName: string, extension: string) {\n if (!extension) return fileName;\n\n // .extension\n let _extension = extension.toLowerCase();\n if (_extension.indexOf('.') !== 0) {\n _extension = '.' + _extension;\n }\n\n // filename.extension | filename\n const _filename = fileName.toLowerCase();\n const hasExtension = _filename.lastIndexOf(_extension) === _filename.length - _extension.length;\n if (!hasExtension) {\n // filename.extension\n return fileName + _extension;\n } else {\n // filename.extension\n return fileName;\n }\n}\n\n/**\n * Parses a MIME type string into its components.\n *\n * @param mimeType - The MIME type string to parse.\n * @returns An object containing the type, subtype, and parameters of the MIME type.\n */\ntype MimeType = { type: string; subtype: string; parameters: Record<string, string> };\nexport function parseMimeType(mimeType: string): MimeType {\n const [fullType, ...parts] = mimeType.split(';');\n const [type, subtype] = fullType.split('/');\n const parameters: MimeType['parameters'] = {};\n\n for (const part of parts) {\n const [name, value] = part.trim().split('=');\n parameters[name] = value;\n }\n\n return { type, subtype, parameters };\n}\n\n/**\n * Returns the file extension based on the MIME type.\n *\n * @param {string | null | undefined} mimeType - The MIME type to look up.\n * @returns {string} - The file extension for the given MIME type, or an empty string if no matching file extension was found.\n */\nexport function getFileExtensionFromMime(mimeType?: string | null): string {\n if (!mimeType) return '';\n const MIME_EXTENSION_MAP = Object.entries(EXTENSION_MIME_MAP).reduce((acc, [key, value]) => {\n acc[value] = key;\n return acc;\n }, {} as Record<string, string>);\n return MIME_EXTENSION_MAP[mimeType.toLowerCase()] || '';\n}\n\n/**\n * Returns the MIME type based on the file extension.\n *\n * @param {string | null | undefined} ext - The file extension to look up.\n * @returns {string} - The MIME type for the given file extension, or an empty string if no matching MIME type was found.\n */\nexport function getMimeFromFileExtension(ext?: string | null) {\n if (!ext) return '';\n return EXTENSION_MIME_MAP[ext.toLowerCase()] || '';\n}\n\n/**\n * Returns the file extension of a file path.\n *\n * @param {string} filePath - The file path to extract the extension from.\n * @returns {string} - The file extension, or an empty string if the file path does not have an extension.\n */\nexport function getFileExtension(filePath: string) {\n const pathWithoutParams = filePath.split('?')[0];\n\n const idx = pathWithoutParams.lastIndexOf('.');\n if (idx === -1) return '';\n\n const result = pathWithoutParams.slice(idx - pathWithoutParams.length).toLowerCase();\n if (result === '.') return '';\n else return result;\n}\n\nexport function getFileExtensionFromUri(uri: string) {\n return fetch(uri).then((response) => response.headers.get('content-type'));\n}\n\nexport function isImage(filePath: string, mimeType?: string) {\n const type = getFileType(mimeType || getFileExtension(filePath));\n return type === 'image';\n}\n\nexport function shouldCompressImage(mime: string, compressionEnabled = true) {\n const extension = getFileExtensionFromMime(mime);\n return Boolean(extension.match(/jpg|jpeg|png/i) && compressionEnabled);\n}\n"],"mappings":";;;;;;;;;;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AAEM,SAASC,OAAT,CAAiBZ,QAAjB,EAAmCnB,QAAnC,EAAsD;EAC3D,MAAMvB,IAAI,GAAGH,WAAW,CAAC0B,QAAQ,IAAIkB,gBAAgB,CAACC,QAAD,CAA7B,CAAxB;EACA,OAAO1C,IAAI,KAAK,OAAhB;AACD;;AAEM,SAASuD,mBAAT,CAA6BC,IAA7B,EAAsE;EAAA,IAA3BC,kBAA2B,uEAAN,IAAM;EAC3E,MAAM1C,SAAS,GAAGiB,wBAAwB,CAACwB,IAAD,CAA1C;EACA,OAAOE,OAAO,CAAC3C,SAAS,CAACb,KAAV,CAAgB,eAAhB,KAAoCuD,kBAArC,CAAd;AACD"}
|
|
@@ -4,13 +4,9 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
6
|
exports.conditionChaining = conditionChaining;
|
|
7
|
-
exports.getDownscaleSize = getDownscaleSize;
|
|
8
7
|
exports.hash = hash;
|
|
9
|
-
exports.
|
|
8
|
+
exports.pick = pick;
|
|
10
9
|
exports.replace = replace;
|
|
11
|
-
exports.shouldCompressImage = shouldCompressImage;
|
|
12
|
-
|
|
13
|
-
var _regex = require("./regex");
|
|
14
10
|
|
|
15
11
|
/**
|
|
16
12
|
* Converts a given string to a hashed string.
|
|
@@ -36,39 +32,22 @@ function conditionChaining(conditions, values) {
|
|
|
36
32
|
return idx > -1 ? values[idx] : values[values.length - 1];
|
|
37
33
|
}
|
|
38
34
|
/**
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
return {
|
|
59
|
-
width: origin.width * ratio,
|
|
60
|
-
height: origin.height * ratio
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function isImage(filePath, mimeType) {
|
|
65
|
-
const type = (0, _regex.getFileType)(mimeType || (0, _regex.getFileExtension)(filePath));
|
|
66
|
-
return type === 'image';
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function shouldCompressImage(filePath) {
|
|
70
|
-
let compressionEnabled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
|
|
71
|
-
const extension = (0, _regex.getFileExtension)(filePath);
|
|
72
|
-
return Boolean(extension.match(/jpg|jpeg|png/i) && compressionEnabled);
|
|
35
|
+
* Returns a new object with only the specified keys from the input object.
|
|
36
|
+
*
|
|
37
|
+
* @param {Object} obj - The input object to pick keys from.
|
|
38
|
+
* @param {Array<string>} keys - An array of keys to pick from the input object.
|
|
39
|
+
* @returns {Object} - A new object containing only the specified keys from the input object.
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* pick({ a: 1, b: '2', c: true }, ['a', 'c']); // returns { a: 1, c: true }
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
function pick(obj, keys) {
|
|
48
|
+
return keys.reduce((pickedObj, key) => {
|
|
49
|
+
pickedObj[key] = obj[key];
|
|
50
|
+
return pickedObj;
|
|
51
|
+
}, {});
|
|
73
52
|
}
|
|
74
53
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["hash","str","String","Math","abs","split","reduce","a","c","charCodeAt","replace","start","end","text","slice","conditionChaining","conditions","values","idx","findIndex","state","Boolean","length","
|
|
1
|
+
{"version":3,"names":["hash","str","String","Math","abs","split","reduce","a","c","charCodeAt","replace","start","end","text","slice","conditionChaining","conditions","values","idx","findIndex","state","Boolean","length","pick","obj","keys","pickedObj","key"],"sources":["index.ts"],"sourcesContent":["/**\n * Converts a given string to a hashed string.\n * */\nexport function hash(str: string) {\n return String(Math.abs(str.split('').reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)));\n}\n\n/**\n * Replace a specific range of text in the string with another text.\n * */\nexport function replace(str: string, start: number, end: number, text: string) {\n return str.slice(0, start) + text + str.slice(end);\n}\n\n/**\n * Returns the value corresponding to the first true index of a given condition array.\n * */\nexport function conditionChaining<T, V>(conditions: T[], values: V[]) {\n const idx = conditions.findIndex((state) => Boolean(state));\n return idx > -1 ? values[idx] : values[values.length - 1];\n}\n\n/**\n * Returns a new object with only the specified keys from the input object.\n *\n * @param {Object} obj - The input object to pick keys from.\n * @param {Array<string>} keys - An array of keys to pick from the input object.\n * @returns {Object} - A new object containing only the specified keys from the input object.\n * @example\n * ```ts\n * pick({ a: 1, b: '2', c: true }, ['a', 'c']); // returns { a: 1, c: true }\n * ```\n */\nexport function pick<T extends { [key: string]: unknown }, Keys extends keyof T>(obj: T, keys: Keys[]) {\n return keys.reduce((pickedObj, key) => {\n pickedObj[key] = obj[key];\n return pickedObj;\n }, {} as { [key in Keys]: T[key] });\n}\n"],"mappings":";;;;;;;;;;AAAA;AACA;AACA;AACO,SAASA,IAAT,CAAcC,GAAd,EAA2B;EAChC,OAAOC,MAAM,CAACC,IAAI,CAACC,GAAL,CAASH,GAAG,CAACI,KAAJ,CAAU,EAAV,EAAcC,MAAd,CAAqB,CAACC,CAAD,EAAIC,CAAJ,KAAW,CAACD,CAAC,IAAI,CAAN,IAAWA,CAAX,GAAeC,CAAC,CAACC,UAAF,CAAa,CAAb,CAAhB,GAAmC,CAAlE,EAAqE,CAArE,CAAT,CAAD,CAAb;AACD;AAED;AACA;AACA;;;AACO,SAASC,OAAT,CAAiBT,GAAjB,EAA8BU,KAA9B,EAA6CC,GAA7C,EAA0DC,IAA1D,EAAwE;EAC7E,OAAOZ,GAAG,CAACa,KAAJ,CAAU,CAAV,EAAaH,KAAb,IAAsBE,IAAtB,GAA6BZ,GAAG,CAACa,KAAJ,CAAUF,GAAV,CAApC;AACD;AAED;AACA;AACA;;;AACO,SAASG,iBAAT,CAAiCC,UAAjC,EAAkDC,MAAlD,EAA+D;EACpE,MAAMC,GAAG,GAAGF,UAAU,CAACG,SAAX,CAAsBC,KAAD,IAAWC,OAAO,CAACD,KAAD,CAAvC,CAAZ;EACA,OAAOF,GAAG,GAAG,CAAC,CAAP,GAAWD,MAAM,CAACC,GAAD,CAAjB,GAAyBD,MAAM,CAACA,MAAM,CAACK,MAAP,GAAgB,CAAjB,CAAtC;AACD;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASC,IAAT,CAA0EC,GAA1E,EAAkFC,IAAlF,EAAgG;EACrG,OAAOA,IAAI,CAACnB,MAAL,CAAY,CAACoB,SAAD,EAAYC,GAAZ,KAAoB;IACrCD,SAAS,CAACC,GAAD,CAAT,GAAiBH,GAAG,CAACG,GAAD,CAApB;IACA,OAAOD,SAAP;EACD,CAHM,EAGJ,EAHI,CAAP;AAID"}
|
|
@@ -3,11 +3,7 @@
|
|
|
3
3
|
Object.defineProperty(exports, "__esModule", {
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
|
-
exports.
|
|
7
|
-
exports.getFileExtension = getFileExtension;
|
|
8
|
-
exports.newLineRegex = exports.imageExtRegex = exports.getFileType = void 0;
|
|
9
|
-
exports.normalizeFileName = normalizeFileName;
|
|
10
|
-
exports.videoExtRegex = exports.urlRegexStrict = exports.urlRegexRough = exports.replaceWithRegex = exports.replaceUrlAsComponents = exports.phoneRegex = void 0;
|
|
6
|
+
exports.urlRegexStrict = exports.urlRegexRough = exports.replaceWithRegex = exports.replaceUrlAsComponents = exports.phoneRegex = exports.newLineRegex = exports.emailRegex = exports.createMentionTemplateRegex = void 0;
|
|
11
7
|
|
|
12
8
|
// For iOS 12 backwards compatibility
|
|
13
9
|
require('string.prototype.matchall').shim();
|
|
@@ -118,45 +114,4 @@ const replaceUrlAsComponents = (originText, replacer, strict) => {
|
|
|
118
114
|
};
|
|
119
115
|
|
|
120
116
|
exports.replaceUrlAsComponents = replaceUrlAsComponents;
|
|
121
|
-
const imageExtRegex = /jpeg|jpg|png|webp|gif/i;
|
|
122
|
-
exports.imageExtRegex = imageExtRegex;
|
|
123
|
-
const audioExtRegex = /3gp|aac|aax|act|aiff|flac|gsm|m4a|m4b|m4p|tta|wma|mp3|webm|wav/i;
|
|
124
|
-
exports.audioExtRegex = audioExtRegex;
|
|
125
|
-
const videoExtRegex = /mov|vod|mp4|avi/i;
|
|
126
|
-
exports.videoExtRegex = videoExtRegex;
|
|
127
|
-
|
|
128
|
-
const getFileType = extOrType => {
|
|
129
|
-
if (extOrType.indexOf('/') > -1) {
|
|
130
|
-
const type = extOrType.split('/')[0];
|
|
131
|
-
if (type === 'video') return 'video';
|
|
132
|
-
if (type === 'audio') return 'audio';
|
|
133
|
-
if (type === 'image') return 'image';
|
|
134
|
-
return 'file';
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
if (extOrType.match(imageExtRegex)) return 'image';
|
|
138
|
-
if (extOrType.match(audioExtRegex)) return 'audio';
|
|
139
|
-
if (extOrType.match(videoExtRegex)) return 'video';
|
|
140
|
-
return 'file';
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
exports.getFileType = getFileType;
|
|
144
|
-
|
|
145
|
-
function getFileExtension(filePath) {
|
|
146
|
-
const idx = filePath.lastIndexOf('.');
|
|
147
|
-
if (idx === -1) return '';
|
|
148
|
-
return filePath.slice(idx - filePath.length).toLowerCase();
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function normalizeFileName(fileName, extension) {
|
|
152
|
-
if (fileName.indexOf(extension) > -1) {
|
|
153
|
-
return fileName;
|
|
154
|
-
} else {
|
|
155
|
-
if (extension.indexOf('.') === 0) {
|
|
156
|
-
return `${fileName}${extension}`;
|
|
157
|
-
} else {
|
|
158
|
-
return `${fileName}.${extension}`;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
117
|
//# sourceMappingURL=regex.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["require","shim","urlRegexStrict","urlRegexRough","phoneRegex","emailRegex","newLineRegex","createMentionTemplateRegex","trigger","RegExp","replaceWithRegex","text","regex","replacer","keyPrefix","matches","matchAll","founds","map","value","start","index","end","length","groups","matchIndex","items","cursor","forEach","restText","pop","head","slice","mid","match","tail","push","replaceUrlAsComponents","originText","strict"
|
|
1
|
+
{"version":3,"names":["require","shim","urlRegexStrict","urlRegexRough","phoneRegex","emailRegex","newLineRegex","createMentionTemplateRegex","trigger","RegExp","replaceWithRegex","text","regex","replacer","keyPrefix","matches","matchAll","founds","map","value","start","index","end","length","groups","matchIndex","items","cursor","forEach","restText","pop","head","slice","mid","match","tail","push","replaceUrlAsComponents","originText","strict"],"sources":["regex.ts"],"sourcesContent":["// For iOS 12 backwards compatibility\nrequire('string.prototype.matchall').shim();\n\nexport const urlRegexStrict =\n /(https?:\\/\\/|www\\.)[-a-zA-Z0-9@:%._+~#=]{1,256}\\.(xn--)?[a-z0-9-]{2,20}\\b([-a-zA-Z0-9@:%_+[\\],.~#?&/=]*[-a-zA-Z0-9@:%_+\\]~#?&/=])*/g;\nexport const urlRegexRough =\n /(https?:\\/\\/|www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/g;\nexport const phoneRegex = /[+]?[(]?[0-9]{3}[)]?[-\\s.]?[0-9]{3}[-\\s.]?[0-9]{4,7}/;\nexport const emailRegex = /\\S+@\\S+\\.\\S+/;\nexport const newLineRegex = /\\r\\n|\\r|\\n/g;\n\nexport const createMentionTemplateRegex = (trigger: string) => new RegExp(`(${trigger}[{])(.*?)([}])`, 'g');\n\n// const cases = [\n// {\n// type: 'urlStrict',\n// regex: urlRegexStrict,\n// },\n// {\n// type: 'urlRough',\n// regex: urlRegexStrict,\n// },\n// {\n// type: 'email',\n// regex: emailRegex,\n// },\n// {\n// type: 'phone',\n// regex: urlRegexStrict,\n// },\n// ];\n\nexport const replaceWithRegex = <T>(\n text: string,\n regex: RegExp,\n replacer: (params: {\n match: string;\n groups: string[];\n matchIndex: number | undefined;\n index: number;\n keyPrefix: string;\n }) => T,\n keyPrefix: string,\n) => {\n const matches = [...text.matchAll(regex)];\n const founds = matches.map((value) => {\n const text = value[0];\n const start = value.index ?? 0;\n const end = start + text.length;\n return { text, start, end, groups: value, matchIndex: value.index };\n });\n\n const items: Array<T | string> = [text];\n let cursor = 0;\n founds.forEach(({ text, start, end, groups, matchIndex }, index) => {\n const restText = items.pop() as string;\n const head = restText.slice(0, start - cursor);\n const mid = replacer({ match: text, groups, matchIndex, index, keyPrefix });\n const tail = restText.slice(end - cursor);\n items.push(head, mid, tail);\n cursor = end;\n });\n return items;\n};\n\nexport const replaceUrlAsComponents = <T>(originText: string, replacer: (url: string) => T, strict?: boolean) => {\n const matches = [...originText.matchAll(strict ? urlRegexStrict : urlRegexRough)];\n const founds = matches.map((value) => {\n const text = value[0];\n const start = value.index ?? 0;\n const end = start + text.length;\n return { text, start, end };\n });\n\n const items: Array<string | T> = [originText];\n let cursor = 0;\n founds.forEach(({ text, start, end }) => {\n const restText = items.pop() as string;\n const head = restText.slice(0, start - cursor);\n const mid = replacer(text);\n const tail = restText.slice(end - cursor);\n items.push(head, mid, tail);\n cursor = end;\n });\n return items;\n};\n"],"mappings":";;;;;;;AAAA;AACAA,OAAO,CAAC,2BAAD,CAAP,CAAqCC,IAArC;;AAEO,MAAMC,cAAc,GACzB,qIADK;;AAEA,MAAMC,aAAa,GACxB,uGADK;;AAEA,MAAMC,UAAU,GAAG,sDAAnB;;AACA,MAAMC,UAAU,GAAG,cAAnB;;AACA,MAAMC,YAAY,GAAG,aAArB;;;AAEA,MAAMC,0BAA0B,GAAIC,OAAD,IAAqB,IAAIC,MAAJ,CAAY,IAAGD,OAAQ,gBAAvB,EAAwC,GAAxC,CAAxD,C,CAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport type React from 'react';\n\nimport type SendbirdChat from '@sendbird/chat';\nimport type {\n BaseChannel,\n Emoji,\n EmojiCategory,\n EmojiContainer,\n RestrictedUser,\n SendbirdError as SBError,\n User,\n UserUpdateParams,\n} from '@sendbird/chat';\nimport type {\n GroupChannel,\n GroupChannelCollection,\n GroupChannelCreateParams,\n GroupChannelListQuery,\n GroupChannelModule,\n GroupChannelUpdateParams,\n Member,\n MessageCollection,\n} from '@sendbird/chat/groupChannel';\nimport type {
|
|
1
|
+
{"version":3,"names":[],"sources":["types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport type React from 'react';\n\nimport type SendbirdChat from '@sendbird/chat';\nimport type {\n BaseChannel,\n Emoji,\n EmojiCategory,\n EmojiContainer,\n Participant,\n RestrictedUser,\n SendbirdError as SBError,\n User,\n UserUpdateParams,\n} from '@sendbird/chat';\nimport type {\n GroupChannel,\n GroupChannelCollection,\n GroupChannelCreateParams,\n GroupChannelListQuery,\n GroupChannelModule,\n GroupChannelUpdateParams,\n Member,\n MessageCollection,\n} from '@sendbird/chat/groupChannel';\nimport type {\n ModuleNamespaces,\n OpenChannelCreateParams,\n OpenChannelUpdateParams,\n SendableMessage,\n} from '@sendbird/chat/lib/__definition';\nimport type {\n AdminMessage,\n BaseMessage,\n FileMessage,\n FileMessageCreateParams,\n FileMessageUpdateParams,\n PreviousMessageListQuery,\n Reaction,\n UserMessage,\n UserMessageCreateParams,\n UserMessageUpdateParams,\n} from '@sendbird/chat/message';\nimport type { OpenChannel, OpenChannelListQuery, OpenChannelModule } from '@sendbird/chat/openChannel';\n\nexport type FilterByValueType<T extends object, Type> = {\n [K in keyof T as T[K] extends Type ? K : never]: T[K];\n};\n\nexport type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void\n ? I\n : never;\n\nexport type OmittedValues<T, K extends keyof T> = Omit<T, K>[keyof Omit<T, K>];\n\nexport type PartialDeep<T> = T extends object\n ? T extends Function\n ? T\n : {\n [P in keyof T]?: PartialDeep<T[P]>;\n }\n : T;\n\nexport type PartialNullable<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport type Optional<T> = T | undefined;\n\nexport type ContextValue<T extends React.Context<any>> = T extends React.Context<infer V> ? V : never;\n\nexport type OnBeforeHandler<T> = (params: T) => T | Promise<T>;\n\nexport interface UserStruct {\n userId: string;\n}\n\nexport type SendbirdChatSDK = SendbirdChat & ModuleNamespaces<[GroupChannelModule, OpenChannelModule]>;\nexport type SendbirdMessage = BaseMessage | FileMessage | UserMessage | AdminMessage | SendableMessage;\nexport type SendbirdChannel = BaseChannel | GroupChannel | OpenChannel;\nexport type SendbirdUserMessage = UserMessage;\nexport type SendbirdFileMessage = FileMessage;\nexport type SendbirdAdminMessage = AdminMessage;\nexport type SendbirdBaseMessage = BaseMessage;\nexport type SendbirdSendableMessage = SendableMessage;\nexport type SendbirdFileMessageCreateParams = FileMessageCreateParams;\nexport type SendbirdFileMessageUpdateParams = FileMessageUpdateParams;\nexport type SendbirdUserMessageCreateParams = UserMessageCreateParams;\nexport type SendbirdUserMessageUpdateParams = UserMessageUpdateParams;\n\nexport type SendbirdGroupChannelCreateParams = GroupChannelCreateParams;\nexport type SendbirdGroupChannelUpdateParams = GroupChannelUpdateParams;\nexport type SendbirdOpenChannelCreateParams = OpenChannelCreateParams;\nexport type SendbirdOpenChannelUpdateParams = OpenChannelUpdateParams;\n\nexport type SendbirdUserUpdateParams = UserUpdateParams;\nexport type SendbirdUser = User;\nexport type SendbirdRestrictedUser = RestrictedUser;\nexport type SendbirdMember = Member;\nexport type SendbirdParticipant = Participant;\n\nexport type SendbirdGroupChannel = GroupChannel;\nexport type SendbirdBaseChannel = BaseChannel;\nexport type SendbirdOpenChannel = OpenChannel;\n\nexport type SendbirdReaction = Reaction;\nexport type SendbirdEmoji = Emoji;\nexport type SendbirdEmojiCategory = EmojiCategory;\nexport type SendbirdEmojiContainer = EmojiContainer;\n\nexport type SendbirdGroupChannelCollection = GroupChannelCollection;\nexport type SendbirdGroupChannelListQuery = GroupChannelListQuery;\nexport type SendbirdOpenChannelListQuery = OpenChannelListQuery;\nexport type SendbirdMessageCollection = MessageCollection;\nexport type SendbirdPreviousMessageListQuery = PreviousMessageListQuery;\n\nexport type SendbirdError = SBError;\n\nexport interface SendbirdDataPayload {\n app_id: string;\n audience_type: string;\n category: string;\n channel: {\n channel_unread_message_count: number;\n channel_url: string;\n custom_type: string;\n name: string;\n };\n channel_type: string;\n created_at: number;\n custom_type: string;\n files: NotificationFiles[];\n mentioned_users: NotificationMentionedUsers[];\n message: string;\n message_id: number;\n push_sound: string;\n push_title: null;\n recipient: {\n id: string;\n name: string;\n push_template: string;\n };\n sender?: {\n id: string;\n name: string;\n profile_url: string;\n require_auth_for_profile_image: boolean;\n };\n sqs_ts: number;\n translations: NotificationTranslations;\n type: 'ADMM' | 'MESG' | 'FILE' | string;\n unread_message_count: number;\n}\nexport interface NotificationFiles {\n type: string;\n url: string;\n name: string;\n size: number;\n require_auth: boolean;\n}\n\nexport interface NotificationTranslations {}\nexport interface NotificationMentionedUsers {}\n"],"mappings":""}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.getOpenChannelTitle = exports.getOpenChannelParticipants = void 0;
|
|
7
|
+
|
|
8
|
+
const getOpenChannelTitle = function (channel) {
|
|
9
|
+
let DEFAULT_CHANNEL_NAME = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Open Channel';
|
|
10
|
+
const trimmedChannelName = channel.name.trim();
|
|
11
|
+
if (trimmedChannelName === '') return DEFAULT_CHANNEL_NAME;
|
|
12
|
+
return trimmedChannelName;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
exports.getOpenChannelTitle = getOpenChannelTitle;
|
|
16
|
+
|
|
17
|
+
const getOpenChannelParticipants = channel => {
|
|
18
|
+
return `${channel.participantCount} participants`;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
exports.getOpenChannelParticipants = getOpenChannelParticipants;
|
|
22
|
+
//# sourceMappingURL=openChannel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["getOpenChannelTitle","channel","DEFAULT_CHANNEL_NAME","trimmedChannelName","name","trim","getOpenChannelParticipants","participantCount"],"sources":["openChannel.ts"],"sourcesContent":["import type { SendbirdOpenChannel } from '../types';\n\nexport const getOpenChannelTitle = (channel: SendbirdOpenChannel, DEFAULT_CHANNEL_NAME = 'Open Channel') => {\n const trimmedChannelName = channel.name.trim();\n if (trimmedChannelName === '') return DEFAULT_CHANNEL_NAME;\n return trimmedChannelName;\n};\n\nexport const getOpenChannelParticipants = (channel: SendbirdOpenChannel) => {\n return `${channel.participantCount} participants`;\n};\n"],"mappings":";;;;;;;AAEO,MAAMA,mBAAmB,GAAG,UAACC,OAAD,EAAyE;EAAA,IAA1CC,oBAA0C,uEAAnB,cAAmB;EAC1G,MAAMC,kBAAkB,GAAGF,OAAO,CAACG,IAAR,CAAaC,IAAb,EAA3B;EACA,IAAIF,kBAAkB,KAAK,EAA3B,EAA+B,OAAOD,oBAAP;EAC/B,OAAOC,kBAAP;AACD,CAJM;;;;AAMA,MAAMG,0BAA0B,GAAIL,OAAD,IAAkC;EAC1E,OAAQ,GAAEA,OAAO,CAACM,gBAAiB,eAAnC;AACD,CAFM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
-
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
2
|
+
import { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState } from 'react';
|
|
3
3
|
const idPool = {};
|
|
4
4
|
export const useUniqId = key => {
|
|
5
5
|
return useState(() => {
|
|
@@ -7,6 +7,10 @@ export const useUniqId = key => {
|
|
|
7
7
|
return idPool[key]++;
|
|
8
8
|
})[0];
|
|
9
9
|
};
|
|
10
|
+
export const useUniqHandlerId = name => {
|
|
11
|
+
const id = useUniqId(name);
|
|
12
|
+
return `${name}_${id}`;
|
|
13
|
+
};
|
|
10
14
|
export const useForceUpdate = () => {
|
|
11
15
|
const [, updater] = useState(0);
|
|
12
16
|
return useCallback(() => updater(prev => prev + 1), []);
|
|
@@ -65,4 +69,28 @@ export const useFreshCallback = callback => {
|
|
|
65
69
|
return ref.current(...arguments);
|
|
66
70
|
}, []);
|
|
67
71
|
};
|
|
72
|
+
export const useDebounceEffect = function (action, delay) {
|
|
73
|
+
let deps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
|
|
74
|
+
const timeoutRef = useRef();
|
|
75
|
+
useEffect(() => {
|
|
76
|
+
timeoutRef.current = setTimeout(async () => {
|
|
77
|
+
try {
|
|
78
|
+
await action();
|
|
79
|
+
} finally {
|
|
80
|
+
timeoutRef.current = undefined;
|
|
81
|
+
}
|
|
82
|
+
}, delay);
|
|
83
|
+
return () => {
|
|
84
|
+
if (timeoutRef.current) {
|
|
85
|
+
clearTimeout(timeoutRef.current);
|
|
86
|
+
timeoutRef.current = undefined;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}, [delay, ...deps]);
|
|
90
|
+
};
|
|
91
|
+
export const usePartialState = initialState => {
|
|
92
|
+
return useReducer((prev, state) => ({ ...prev,
|
|
93
|
+
...state
|
|
94
|
+
}), initialState);
|
|
95
|
+
};
|
|
68
96
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["useCallback","useEffect","useLayoutEffect","useRef","useState","idPool","useUniqId","key","useForceUpdate","updater","prev","useAsyncEffect","asyncEffect","deps","createAsyncEffectCallback","useAsyncLayoutEffect","useIIFE","callback","iife","destructor","Promise","awaitedDestructor","useIsMountedRef","isMounted","current","useIsFirstMount","isFirstMount","useFreshCallback","ref"],"sources":["index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { DependencyList } from 'react';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\n\ntype Destructor = () => void;\ntype AsyncEffectCallback = () => void | Destructor | Promise<void> | Promise<Destructor>;\n\nconst idPool: { [key: string]: number } = {};\nexport const useUniqId = (key: string) => {\n return useState(() => {\n if (!idPool[key]) idPool[key] = 1;\n return idPool[key]++;\n })[0];\n};\n\nexport const useForceUpdate = () => {\n const [, updater] = useState(0);\n return useCallback(() => updater((prev) => prev + 1), []);\n};\n\nexport const useAsyncEffect = (asyncEffect: AsyncEffectCallback, deps?: DependencyList) => {\n useEffect(createAsyncEffectCallback(asyncEffect), deps);\n};\nexport const useAsyncLayoutEffect = (asyncEffect: AsyncEffectCallback, deps?: DependencyList) => {\n useLayoutEffect(createAsyncEffectCallback(asyncEffect), deps);\n};\nexport const useIIFE = <T>(callback: () => T) => {\n return iife(callback);\n};\nconst iife = <T extends (...args: any[]) => any>(callback: T): ReturnType<T> => callback();\nconst createAsyncEffectCallback = (asyncEffect: AsyncEffectCallback) => () => {\n const destructor = iife(asyncEffect);\n return () => {\n if (!destructor) return;\n\n if (destructor instanceof Promise) {\n iife(async () => {\n const awaitedDestructor = await destructor;\n if (awaitedDestructor) awaitedDestructor();\n });\n } else {\n iife(destructor);\n }\n };\n};\n\nexport const useIsMountedRef = () => {\n const isMounted = useRef(true);\n\n useEffect(() => {\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return isMounted;\n};\n\nexport const useIsFirstMount = () => {\n const isFirstMount = useRef(true);\n\n if (isFirstMount.current) {\n isFirstMount.current = false;\n return true;\n }\n\n return isFirstMount.current;\n};\n\nexport const useFreshCallback = <T extends (...args: any[]) => any>(callback: T): T => {\n const ref = useRef<T>(callback);\n ref.current = callback;\n return useCallback(((...args) => ref.current(...args)) as T, []);\n};\n"],"mappings":"AAAA;AAEA,SAASA,WAAT,EAAsBC,SAAtB,EAAiCC,eAAjC,EAAkDC,
|
|
1
|
+
{"version":3,"names":["useCallback","useEffect","useLayoutEffect","useReducer","useRef","useState","idPool","useUniqId","key","useUniqHandlerId","name","id","useForceUpdate","updater","prev","useAsyncEffect","asyncEffect","deps","createAsyncEffectCallback","useAsyncLayoutEffect","useIIFE","callback","iife","destructor","Promise","awaitedDestructor","useIsMountedRef","isMounted","current","useIsFirstMount","isFirstMount","useFreshCallback","ref","useDebounceEffect","action","delay","timeoutRef","setTimeout","undefined","clearTimeout","usePartialState","initialState","state"],"sources":["index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { DependencyList } from 'react';\nimport { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState } from 'react';\n\ntype Destructor = () => void;\ntype AsyncEffectCallback = () => void | Destructor | Promise<void> | Promise<Destructor>;\n\nconst idPool: { [key: string]: number } = {};\nexport const useUniqId = (key: string) => {\n return useState(() => {\n if (!idPool[key]) idPool[key] = 1;\n return idPool[key]++;\n })[0];\n};\n\nexport const useUniqHandlerId = (name: string) => {\n const id = useUniqId(name);\n return `${name}_${id}`;\n};\n\nexport const useForceUpdate = () => {\n const [, updater] = useState(0);\n return useCallback(() => updater((prev) => prev + 1), []);\n};\n\nexport const useAsyncEffect = (asyncEffect: AsyncEffectCallback, deps?: DependencyList) => {\n useEffect(createAsyncEffectCallback(asyncEffect), deps);\n};\nexport const useAsyncLayoutEffect = (asyncEffect: AsyncEffectCallback, deps?: DependencyList) => {\n useLayoutEffect(createAsyncEffectCallback(asyncEffect), deps);\n};\nexport const useIIFE = <T>(callback: () => T) => {\n return iife(callback);\n};\nconst iife = <T extends (...args: any[]) => any>(callback: T): ReturnType<T> => callback();\nconst createAsyncEffectCallback = (asyncEffect: AsyncEffectCallback) => () => {\n const destructor = iife(asyncEffect);\n return () => {\n if (!destructor) return;\n\n if (destructor instanceof Promise) {\n iife(async () => {\n const awaitedDestructor = await destructor;\n if (awaitedDestructor) awaitedDestructor();\n });\n } else {\n iife(destructor);\n }\n };\n};\n\nexport const useIsMountedRef = () => {\n const isMounted = useRef(true);\n\n useEffect(() => {\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return isMounted;\n};\n\nexport const useIsFirstMount = () => {\n const isFirstMount = useRef(true);\n\n if (isFirstMount.current) {\n isFirstMount.current = false;\n return true;\n }\n\n return isFirstMount.current;\n};\n\nexport const useFreshCallback = <T extends (...args: any[]) => any>(callback: T): T => {\n const ref = useRef<T>(callback);\n ref.current = callback;\n return useCallback(((...args) => ref.current(...args)) as T, []);\n};\n\nexport const useDebounceEffect = (action: () => void, delay: number, deps: DependencyList = []) => {\n const timeoutRef = useRef<NodeJS.Timeout>();\n\n useEffect(() => {\n timeoutRef.current = setTimeout(async () => {\n try {\n await action();\n } finally {\n timeoutRef.current = undefined;\n }\n }, delay);\n\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = undefined;\n }\n };\n }, [delay, ...deps]);\n};\n\nexport const usePartialState = <S>(initialState: S) => {\n return useReducer((prev: S, state: Partial<S>) => ({ ...prev, ...state }), initialState);\n};\n"],"mappings":"AAAA;AAEA,SAASA,WAAT,EAAsBC,SAAtB,EAAiCC,eAAjC,EAAkDC,UAAlD,EAA8DC,MAA9D,EAAsEC,QAAtE,QAAsF,OAAtF;AAKA,MAAMC,MAAiC,GAAG,EAA1C;AACA,OAAO,MAAMC,SAAS,GAAIC,GAAD,IAAiB;EACxC,OAAOH,QAAQ,CAAC,MAAM;IACpB,IAAI,CAACC,MAAM,CAACE,GAAD,CAAX,EAAkBF,MAAM,CAACE,GAAD,CAAN,GAAc,CAAd;IAClB,OAAOF,MAAM,CAACE,GAAD,CAAN,EAAP;EACD,CAHc,CAAR,CAGJ,CAHI,CAAP;AAID,CALM;AAOP,OAAO,MAAMC,gBAAgB,GAAIC,IAAD,IAAkB;EAChD,MAAM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,CAAT;AAgBD,CAnBM;AAqBP,OAAO,MAAMuB,eAAe,GAAOC,YAAJ,IAAwB;EACrD,OAAOtC,UAAU,CAAC,CAACW,IAAD,EAAU4B,KAAV,MAAiC,EAAE,GAAG5B,IAAL;IAAW,GAAG4B;EAAd,CAAjC,CAAD,EAA0DD,YAA1D,CAAjB;AACD,CAFM"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useEffect,
|
|
1
|
+
import { useEffect, useRef } from 'react';
|
|
2
2
|
import { AppState } from 'react-native';
|
|
3
3
|
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
|
4
4
|
const edgePaddingMap = {
|
|
@@ -9,13 +9,11 @@ const edgePaddingMap = {
|
|
|
9
9
|
};
|
|
10
10
|
export const useSafeAreaPadding = edges => {
|
|
11
11
|
const safeAreaInsets = useSafeAreaInsets();
|
|
12
|
-
return
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}, {});
|
|
18
|
-
}, edges);
|
|
12
|
+
return edges.reduce((map, edge) => {
|
|
13
|
+
const paddingKey = edgePaddingMap[edge];
|
|
14
|
+
map[paddingKey] = safeAreaInsets[edge];
|
|
15
|
+
return map;
|
|
16
|
+
}, {});
|
|
19
17
|
};
|
|
20
18
|
export const useAppState = (type, listener) => {
|
|
21
19
|
const callbackRef = useRef(listener);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["useEffect","
|
|
1
|
+
{"version":3,"names":["useEffect","useRef","AppState","useSafeAreaInsets","edgePaddingMap","left","right","top","bottom","useSafeAreaPadding","edges","safeAreaInsets","reduce","map","edge","paddingKey","useAppState","type","listener","callbackRef","current","eventListener","state","subscriber","addEventListener","remove","removeEventListener"],"sources":["react-native.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport { AppState, AppStateEvent, AppStateStatus } from 'react-native';\nimport { EdgeInsets, useSafeAreaInsets } from 'react-native-safe-area-context';\n\ntype EdgePaddingMap = {\n left: 'paddingLeft';\n right: 'paddingRight';\n top: 'paddingTop';\n bottom: 'paddingBottom';\n};\nconst edgePaddingMap: EdgePaddingMap = {\n left: 'paddingLeft',\n right: 'paddingRight',\n top: 'paddingTop',\n bottom: 'paddingBottom',\n};\n\nexport const useSafeAreaPadding = <\n T extends keyof EdgeInsets,\n Result extends { [key in EdgePaddingMap[T]]: EdgeInsets[T] },\n>(\n edges: T[],\n): Result => {\n const safeAreaInsets = useSafeAreaInsets();\n return edges.reduce((map, edge) => {\n const paddingKey = edgePaddingMap[edge];\n map[paddingKey] = safeAreaInsets[edge];\n return map;\n }, {} as { [key in EdgePaddingMap[T]]: EdgeInsets[T] }) as Result;\n};\n\ntype AppStateListener = (status: AppStateStatus) => void;\n\nexport const useAppState = (type: AppStateEvent, listener: AppStateListener) => {\n const callbackRef = useRef<AppStateListener>(listener);\n callbackRef.current = listener;\n\n useEffect(() => {\n const eventListener = (state: AppStateStatus) => callbackRef.current(state);\n const subscriber = AppState.addEventListener(type, eventListener);\n\n return () => {\n // @ts-ignore\n if (subscriber?.remove) {\n subscriber.remove();\n }\n // @ts-ignore\n else if (AppState.removeEventListener) {\n // @ts-ignore\n AppState.removeEventListener(type, eventListener);\n }\n };\n }, []);\n};\n"],"mappings":"AAAA,SAASA,SAAT,EAAoBC,MAApB,QAAkC,OAAlC;AACA,SAASC,QAAT,QAAwD,cAAxD;AACA,SAAqBC,iBAArB,QAA8C,gCAA9C;AAQA,MAAMC,cAA8B,GAAG;EACrCC,IAAI,EAAE,aAD+B;EAErCC,KAAK,EAAE,cAF8B;EAGrCC,GAAG,EAAE,YAHgC;EAIrCC,MAAM,EAAE;AAJ6B,CAAvC;AAOA,OAAO,MAAMC,kBAAkB,GAI7BC,KAJgC,IAKrB;EACX,MAAMC,cAAc,GAAGR,iBAAiB,EAAxC;EACA,OAAOO,KAAK,CAACE,MAAN,CAAa,CAACC,GAAD,EAAMC,IAAN,KAAe;IACjC,MAAMC,UAAU,GAAGX,cAAc,CAACU,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