import { API_SCAN_CODE } from '../protocol.uts' import { ScanCodeFail, ScanCodeSuccess, ScanCodeOptions, ScanCodeSupportedTypes, ScanCode } from '../interface.uts' import { getAbilityContext } from '@dcloudio/uni-runtime' import { scanCore, scanBarcode } from '@kit.ScanKit'; export { ScanCodeFail, ScanCodeSuccess, ScanCodeOptions, } let supportedScanTypesMap: Map function initScanTypesMapOnce() { if (supportedScanTypesMap) { return } supportedScanTypesMap = new Map([ ['barCode', scanCore.ScanType.CODABAR_CODE], ['qrCode', scanCore.ScanType.QR_CODE], ['datamatrix', scanCore.ScanType.DATAMATRIX_CODE], ['pdf417', scanCore.ScanType.PDF417_CODE] ]); } function getUniScanType(scanType: scanCore.ScanType): ScanCodeSupportedTypes { for (const [key, value] of supportedScanTypesMap.entries()) { if (value === scanType) { return key; } } return 'qrCode'; } export const scanCode: ScanCode = defineAsyncApi( API_SCAN_CODE, function (options: ScanCodeOptions, exec: ApiExecutor) { if (!canIUse('SystemCapability.Multimedia.Scan.ScanBarcode')) { exec.reject('not support'); return } initScanTypesMapOnce(); let scanTypes: scanCore.ScanType[] = [scanCore.ScanType.ALL]; if (options.scanType && Array.isArray(options.scanType) && options.scanType.length > 0) { scanTypes = options.scanType.filter((type) => { return supportedScanTypesMap.has(type); }).map((type) => { return supportedScanTypesMap.get(type)!; }) } const scanOptions: scanBarcode.ScanOptions = { scanTypes, enableMultiMode: true, enableAlbum: !options.onlyFromCamera }; scanBarcode.startScanForResult(getAbilityContext()!, scanOptions, (err, data) => { if (err) { exec.reject(err.message); return; } exec.resolve({ result: data.originalValue, scanType: getUniScanType(data.scanType), } as ScanCodeSuccess) }) } ) as ScanCode