13 Commits
Author SHA1 Message Date
yugasun 9fa47676df 0.3.3 2022-11-23 11:56:17 +08:00
dyoshikawaandGitHub 0b7edb39df fix:type def of decodeFromImage() param (#23) 2022-11-23 11:53:11 +08:00
yugasun 8afbcdad33 chore: fix test ci 2022-10-11 14:39:25 +08:00
yugasun 0f2e84268c chore: add pnpm version 2022-10-11 14:15:15 +08:00
yugasun 33f115036f chore: update readme & ci 2022-10-11 14:08:21 +08:00
yugasun 17ced673e4 0.3.2 2022-10-11 14:03:43 +08:00
yugasun c236e43f21 chore: add type definition 2022-10-11 14:03:24 +08:00
yugasun e6fb08352f docs: update readme 2022-05-29 12:09:44 +08:00
yugasun b9d89e0545 0.3.1 2022-05-29 12:07:49 +08:00
yugasun aeee33ee6c chore: add unpkg browser field 2022-05-29 12:07:37 +08:00
yugasun a5cd17b951 0.3.0 2022-05-29 11:23:48 +08:00
yugasun 615081cc95 fix: support customize camera size 2022-05-29 11:23:04 +08:00
yugasun 7d77236fc0 fix: try to use rear camera by default 2022-05-29 11:04:57 +08:00
15 changed files with 7829 additions and 179 deletions
+108
View File
@@ -0,0 +1,108 @@
name: CI
env:
NODE_OPTIONS: --max-old-space-size=6144
# install playwright binary manually (because pnpm only runs install script once)
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1"
on:
push:
branches:
- main
- master
- release/*
- feat/*
- fix/*
- perf/*
- v1
- v2
pull_request:
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event.number || github.sha }}
cancel-in-progress: true
jobs:
build:
timeout-minutes: 20
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest]
node_version: [16]
fail-fast: false
name: "Build&Test: node-${{ matrix.node_version }}, ${{ matrix.os }}"
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Install pnpm
uses: pnpm/action-setup@v2.2.2
- name: Set node version to ${{ matrix.node_version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node_version }}
cache: "pnpm"
- name: Install deps
run: pnpm install
- name: Build
run: pnpm run build
test:
timeout-minutes: 10
runs-on: ubuntu-latest
name: "Lint: node-16, ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install pnpm
uses: pnpm/action-setup@v2.2.2
- name: Set node version to 16
uses: actions/setup-node@v3
with:
node-version: 16
cache: "pnpm"
- name: Install deps
run: pnpm install
- name: Build
run: pnpm run build
- name: Test
run: pnpm run test
lint:
timeout-minutes: 10
runs-on: ubuntu-latest
name: "Lint: node-16, ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install pnpm
uses: pnpm/action-setup@v2.2.2
- name: Set node version to 16
uses: actions/setup-node@v3
with:
node-version: 16
cache: "pnpm"
- name: Install deps
run: pnpm install
- name: Build
run: pnpm run build
- name: Check formatting
run: pnpm run prettier
+2
View File
@@ -9,3 +9,5 @@ tsconfig.tsbuildinfo
coverage coverage
yarn.lock yarn.lock
.rpt2_cache .rpt2_cache
demo/lib/index.min.js
+3 -1
View File
@@ -1 +1,3 @@
package-lock=false shamefully-hoist=true
strict-peer-dependencies=true
auto-install-peers=true
+8 -8
View File
@@ -23,10 +23,10 @@ A tool for decoding qrcode.
## Guide ## Guide
Use `npm` to install. Use `pnpm` to install.
```bash ```bash
$ npm install --save qrcode-decoder $ pnpm install --save qrcode-decoder
``` ```
Using in webpack: Using in webpack:
@@ -38,7 +38,7 @@ import QrcodeDecoder from 'qrcode-decoder';
Using in browser: Using in browser:
```html ```html
<script src="https://unpkg.com/qrcode-decoder"></script> <script src="https://unpkg.com/qrcode-decoder@0.3.1/dist/index.min.js"></script>
``` ```
## Demo ## Demo
@@ -96,31 +96,31 @@ Stops the current `qr` from searching for a QRCode.
Install dependencies: Install dependencies:
```bash ```bash
$ npm install $ pnpm install
``` ```
Build code: Build code:
```bash ```bash
$ npm run build $ pnpm run build
``` ```
Run unit test: Run unit test:
```bash ```bash
$ npm test $ pnpm test
``` ```
Modify version in `package.json`, run `release` script: Modify version in `package.json`, run `release` script:
```bash ```bash
$ npm run release $ pnpm run release
``` ```
Publish Publish
```bash ```bash
$ npm publish $ pnpm publish
``` ```
## License ## License
+9 -9
View File
@@ -23,10 +23,10 @@
## 使用者指南 ## 使用者指南
通过 npm 下载安装代码 通过 pnpm 下载安装代码
```bash ```bash
$ npm install --save qrcode-decoder $ pnpm install --save qrcode-decoder
``` ```
如果你是 webpack 等环境 如果你是 webpack 等环境
@@ -38,7 +38,7 @@ import QrcodeDecoder from 'qrcode-decoder';
如果你是浏览器环境 如果你是浏览器环境
```html ```html
<script src="https://unpkg.com/qrcode-decoder"></script> <script src="https://unpkg.com/qrcode-decoder@0.3.1/dist/index.min.js"></script>
``` ```
## 示例 ## 示例
@@ -96,31 +96,31 @@ qr.decodeFromCamera(videoElem).then((res) => {
首次运行需要先安装依赖 首次运行需要先安装依赖
```bash ```bash
$ npm install $ pnpm install
``` ```
一键打包生成生产代码 一键打包生成生产代码
```bash ```bash
$ npm run build $ pnpm run build
``` ```
运行单元测试,浏览器环境需要手动测试,位于`test/browser` 运行单元测试,浏览器环境需要手动测试,位于`test/browser`
```bash ```bash
$ npm test $ pnpm test
``` ```
修改 package.json 中的版本号,修改 README.md 中的版本号,修改 CHANGELOG.md,然后发布新版 修改 package.json 中的版本号,修改 README.md 中的版本号,修改 CHANGELOG.md,然后发布新版
```bash ```bash
$ npm run release $ pnpm run release
``` ```
将新版本发布到 npm 将新版本发布到 pnpm
```bash ```bash
$ npm publish $ pnpm publish
``` ```
## License ## License
+26
View File
@@ -0,0 +1,26 @@
import QrcodeDecoder from '../';
describe('QrcodeDecoder', () => {
test('use', async () => {
const res = await import('../dist');
expect(res.default).toEqual(QrcodeDecoder);
});
test('new QrcodeDecoder()', async () => {
const qr = new QrcodeDecoder();
expect(qr).toBeDefined();
expect(qr.videoConstraints).toEqual({
video: {
width: { min: 360, ideal: 720, max: 1080 },
height: { min: 360, ideal: 720, max: 1080 },
facingMode: { exact: 'environment' },
},
audio: false,
});
expect(qr.decodeFromImage).toBeDefined();
expect(qr.decodeFromCamera).toBeDefined();
expect(qr.decodeFromVideo).toBeDefined();
});
});
+16 -7
View File
@@ -1,19 +1,21 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head>
<head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>QrcodeDecoder - Camera</title> <title>QrcodeDecoder - Camera</title>
</head> </head>
<body>
<body>
<button id="start">Start</button> <button id="stop">Stop</button><br /> <button id="start">Start</button> <button id="stop">Stop</button><br />
<span id="result">Click start to scan qrcode.</span><br /> <span id="result">Click start to scan qrcode.</span><br />
<hr /> <hr />
<video id="video" autoplay></video> <video id="video" autoplay></video>
<script src="./lib/vconsole.min.js"></script> <script src="./lib/vconsole.min.js"></script>
<script src="./index.min.js"></script> <script src="./lib/index.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
var vConsole = new VConsole(); var vConsole = new VConsole();
console.log('Hello world'); console.log('Hello world');
@@ -29,17 +31,24 @@
throw new Error('Canvas and getUserMedia are required'); throw new Error('Canvas and getUserMedia are required');
} }
let code = await qr.decodeFromCamera(video); let code = await qr.decodeFromCamera(video,
// you can customize your camera size like below
// {
// width: 400,
// height: 400,
// }
);
console.log('code', code); console.log('code', code);
result.innerText = 'Result: ' + code.data; result.innerText = 'Result: ' + code.data;
} }
start.onclick = startScan; start.onclick = startScan;
stop.onclick = function() { stop.onclick = function () {
qr.stop(); qr.stop();
}; };
} }
main(); main();
</script> </script>
</body> </body>
</html> </html>
+9 -7
View File
@@ -1,12 +1,14 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>QrcodeDecoder - Image</title> <title>QrcodeDecoder - Image</title>
</head> </head>
<body>
<body>
<section> <section>
<h3>Same domain image</h3> <h3>Same domain image</h3>
<img id="img1" src="./assets/qrcode.png" alt="qr code" /><br /> <img id="img1" src="./assets/qrcode.png" alt="qr code" /><br />
@@ -19,13 +21,12 @@
<input <input
id="img2" id="img2"
value="https://yugasun.com/static/wechat.jpg" value="https://yugasun.com/static/wechat.jpg"
style="width: 400px" style="width: 400px" /><br />
/><br />
<button id="decode2">Decode!</button><br /> <button id="decode2">Decode!</button><br />
<span id="result2"></span><br /> <span id="result2"></span><br />
</section> </section>
<script src="./lib/vconsole.min.js"></script> <script src="./lib/vconsole.min.js"></script>
<script src="./index.min.js"></script> <script src="./lib/index.min.js"></script>
<script type="module"> <script type="module">
var vConsole = new VConsole(); var vConsole = new VConsole();
function main() { function main() {
@@ -60,5 +61,6 @@
main(); main();
}; };
</script> </script>
</body> </body>
</html> </html>
-1
View File
File diff suppressed because one or more lines are too long
+9 -7
View File
@@ -1,21 +1,22 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>QrcodeDecoder - Video</title> <title>QrcodeDecoder - Video</title>
</head> </head>
<body>
<body>
<button id="start">Start</button> <button id="stop">Stop</button><br /> <button id="start">Start</button> <button id="stop">Stop</button><br />
<span id="result">Click start to scan qrcode.</span><br /> <span id="result">Click start to scan qrcode.</span><br />
<video src="./assets/qrcode-video.mp4"></video> <video src="./assets/qrcode-video.mp4"></video>
<script src="./lib/vconsole.min.js"></script> <script src="./lib/vconsole.min.js"></script>
<script src="./index.min.js"></script> <script src="./lib/index.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
var vConsole = new VConsole(); var vConsole = new VConsole();
console.log('Hello world');
function main() { function main() {
var video = document.querySelector('video'); var video = document.querySelector('video');
var result = document.querySelector('#result'); var result = document.querySelector('#result');
@@ -25,7 +26,7 @@
start.onclick = startScan; start.onclick = startScan;
stop.onclick = function() { stop.onclick = function () {
qr.stop(); qr.stop();
video.pause(); video.pause();
}; };
@@ -39,5 +40,6 @@
} }
main(); main();
</script> </script>
</body> </body>
</html> </html>
+6
View File
@@ -1,5 +1,11 @@
const isDebug = process.env.DEBUG === 'true';
module.exports = { module.exports = {
verbose: true, verbose: true,
silent: !isDebug,
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testTimeout: 60000, testTimeout: 60000,
transform: { transform: {
'^.+\\.tsx?$': 'ts-jest', '^.+\\.tsx?$': 'ts-jest',
+12 -5
View File
@@ -1,19 +1,25 @@
{ {
"name": "qrcode-decoder", "name": "qrcode-decoder",
"version": "0.2.2", "version": "0.3.3",
"description": "Tool for decoding qrcode", "description": "Tool for decoding qrcode",
"main": "dist/index.js", "main": "dist/index.js",
"browser": "dist/index.min.js",
"unpkg": "dist/index.min.js",
"module": "dist/index.esm.js", "module": "dist/index.esm.js",
"types": "dist/index.d.ts",
"sideEffects": false, "sideEffects": false,
"packageManager": "pnpm@7.11.0",
"scripts": { "scripts": {
"build": "ts-node -P scripts/tsconfig.json scripts/bundle.ts umd,esm,aio && npm run copy-file", "build": "ts-node -P scripts/tsconfig.json scripts/bundle.ts commonjs,esm,aio && pnpm run dts && pnpm run copy-file",
"dts": "tsc src/index.ts --declaration --emitDeclarationOnly --outDir './dist'",
"prettier": "prettier --check '**/*.{ts,tsx,md}' --config .prettierrc", "prettier": "prettier --check '**/*.{ts,tsx,md}' --config .prettierrc",
"prettier:fix": "prettier --write '**/*.{ts,tsx,md}' --config .prettierrc", "prettier:fix": "prettier --write '**/*.{ts,tsx,md}' --config .prettierrc",
"test": "jest", "test": "jest",
"codecov": "jest --coverage && codecov", "codecov": "jest --coverage && codecov",
"copy-file": "cp dist/index.min.js demo/", "copy-file": "cp dist/index.min.js demo/lib",
"release": "git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags", "release": "git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags",
"pages": "gh-pages -d demo --remote origin" "pages": "gh-pages -d demo --remote origin",
"demo": "http-server demo -c-1"
}, },
"husky": { "husky": {
"hooks": { "hooks": {
@@ -22,7 +28,7 @@
}, },
"lint-staged": { "lint-staged": {
"*.{ts,tsx,md}": [ "*.{ts,tsx,md}": [
"npm run prettier:fix", "pnpm run prettier:fix",
"git add ." "git add ."
] ]
}, },
@@ -56,6 +62,7 @@
"cross-env": "^6.0.3", "cross-env": "^6.0.3",
"fancy-log": "^1.3.3", "fancy-log": "^1.3.3",
"gh-pages": "^3.1.0", "gh-pages": "^3.1.0",
"http-server": "^14.1.0",
"husky": "^3.0.9", "husky": "^3.0.9",
"jest": "^24.9.0", "jest": "^24.9.0",
"lint-staged": "^9.5.0", "lint-staged": "^9.5.0",
+7446
View File
File diff suppressed because it is too large Load Diff
+29 -12
View File
@@ -20,16 +20,6 @@ const plugins: rollup.Plugin[] = [
commonjs(), commonjs(),
typescript2({ typescript2({
tsconfig: path.join(__dirname, '..', 'tsconfig.json'), tsconfig: path.join(__dirname, '..', 'tsconfig.json'),
typescript: ts, // ensure we're using the same typescript (3.x) for rollup as for regular builds etc
tsconfigOverride: {
module: 'esnext',
stripInternal: true,
emitDeclarationOnly: false,
composite: false,
declaration: false,
declarationMap: false,
sourceMap: false,
},
}), }),
]; ];
@@ -69,6 +59,25 @@ async function bundleUmd() {
}); });
} }
async function bundleCommonjs() {
const bundle = await rollup.rollup({
input: path.join(process.cwd(), 'src/index.ts'),
plugins: [...plugins],
external: ['jsqr'],
});
await bundle.write({
file: 'dist/index.js',
exports: 'named',
name: 'QrcodeDecoder',
format: 'commonjs',
sourcemap: false,
globals: {
jsqr: 'jsqr',
tslib: 'tslib',
},
});
}
async function bundleAio() { async function bundleAio() {
const bundle = await rollup.rollup({ const bundle = await rollup.rollup({
input: path.join(process.cwd(), 'src/index.ts'), input: path.join(process.cwd(), 'src/index.ts'),
@@ -77,7 +86,7 @@ async function bundleAio() {
uglify({ uglify({
compress: { compress: {
drop_debugger: true, drop_debugger: true,
drop_console: true, drop_console: false,
}, },
}), }),
], ],
@@ -86,7 +95,7 @@ async function bundleAio() {
file: 'dist/index.min.js', file: 'dist/index.min.js',
name: 'QrcodeDecoder', name: 'QrcodeDecoder',
format: 'iife', format: 'iife',
sourcemap: false, sourcemap: true,
}); });
} }
@@ -110,6 +119,14 @@ async function bundle() {
await bundleUmd(); await bundleUmd();
} }
if (outputs.indexOf('commonjs') === -1) {
logBundle(`Skipping commonjs`);
} else {
logBundle(`Creating commonjs`);
await bundleCommonjs();
}
if (outputs.indexOf('aio') === -1) { if (outputs.indexOf('aio') === -1) {
logBundle(`Skipping umd aio`); logBundle(`Skipping umd aio`);
} else { } else {
+38 -14
View File
@@ -1,6 +1,11 @@
import { Options } from 'jsqr'; import { Options } from 'jsqr';
import jsQR from 'jsqr'; import jsQR from 'jsqr';
const videoSize = {
width: { min: 360, ideal: 720, max: 1080 },
height: { min: 360, ideal: 720, max: 1080 },
};
class QrcodeDecoder { class QrcodeDecoder {
timerCapture: null | NodeJS.Timeout; timerCapture: null | NodeJS.Timeout;
canvasElem: null | HTMLCanvasElement; canvasElem: null | HTMLCanvasElement;
@@ -19,7 +24,8 @@ class QrcodeDecoder {
this.videoElem = null; this.videoElem = null;
this.getUserMediaHandler = null; this.getUserMediaHandler = null;
this.videoConstraints = { this.videoConstraints = {
video: true, // default use rear camera
video: { ...videoSize, facingMode: { exact: 'environment' } },
audio: false, audio: false,
}; };
@@ -149,7 +155,7 @@ class QrcodeDecoder {
* inversionAttempts - (attemptBoth (default), dontInvert, onlyInvert, or invertFirst) * inversionAttempts - (attemptBoth (default), dontInvert, onlyInvert, or invertFirst)
* refer to jsqr options: https://github.com/cozmo/jsQR * refer to jsqr options: https://github.com/cozmo/jsQR
*/ */
async decodeFromCamera(videoElem: HTMLVideoElement, options = {}) { async decodeFromCamera(videoElem: HTMLVideoElement, options: any = {}) {
const opts = { const opts = {
...this.defaultOption, ...this.defaultOption,
...options, ...options,
@@ -160,10 +166,29 @@ class QrcodeDecoder {
throw new Error("Couldn't get video from camera"); throw new Error("Couldn't get video from camera");
} }
let stream: MediaStream;
try { try {
const stream = await navigator.mediaDevices.getUserMedia( stream = await navigator.mediaDevices.getUserMedia(this.videoConstraints);
this.videoConstraints, } catch (e) {
); if ((e as OverconstrainedError).name === 'OverconstrainedError') {
console.log('[OverconstrainedError] Can not use rear camera.');
stream = await navigator.mediaDevices.getUserMedia({
video: {
...videoSize,
...{
width: opts.width,
height: opts.height,
},
},
audio: false,
});
} else {
throw e;
}
}
if (stream) {
videoElem.srcObject = stream; videoElem.srcObject = stream;
// videoElem.src = window.URL.createObjectURL(stream); // videoElem.src = window.URL.createObjectURL(stream);
this.videoElem = videoElem; this.videoElem = videoElem;
@@ -171,8 +196,6 @@ class QrcodeDecoder {
const code = await this.decodeFromVideo(videoElem, opts); const code = await this.decodeFromVideo(videoElem, opts);
return code; return code;
} catch (e) {
throw e;
} }
} }
@@ -206,7 +229,7 @@ class QrcodeDecoder {
* refer to jsqr options: https://github.com/cozmo/jsQR * refer to jsqr options: https://github.com/cozmo/jsQR
*/ */
async decodeFromImage( async decodeFromImage(
img: HTMLImageElement, img: HTMLImageElement | string,
options: { crossOrigin?: string } = {}, options: { crossOrigin?: string } = {},
) { ) {
let imgDom: HTMLImageElement | null = null; let imgDom: HTMLImageElement | null = null;
@@ -214,12 +237,8 @@ class QrcodeDecoder {
...this.defaultOption, ...this.defaultOption,
...options, ...options,
}; };
if (+img.nodeType > 0) {
if (!img.src) { if (typeof img === 'string') {
throw new Error('The ImageElement must contain a src');
}
imgDom = img;
} else if (typeof img === 'string') {
imgDom = document.createElement('img'); imgDom = document.createElement('img');
if (options.crossOrigin) { if (options.crossOrigin) {
imgDom.crossOrigin = options.crossOrigin; imgDom.crossOrigin = options.crossOrigin;
@@ -230,6 +249,11 @@ class QrcodeDecoder {
imgDom!.onload = () => resolve(true); imgDom!.onload = () => resolve(true);
}); });
await proms(); await proms();
} else if (+img.nodeType > 0) {
if (!img.src) {
throw new Error('The ImageElement must contain a src');
}
imgDom = img;
} }
let code = null; let code = null;