Compare commits

..

59 Commits

Author SHA1 Message Date
CI
52a03c76b6 chore(release): 1.1.2 2021-07-13 14:01:24 +00:00
439e365ea8 fix: text-shadow position with baseline (#2576) 2021-07-13 19:14:27 +08:00
e29af58661 ci: implement screenshot diffing (#2571) 2021-07-13 18:48:18 +08:00
171585491d fix: logger unique names (#2575) 2021-07-13 18:07:09 +08:00
CI
99b8182991 chore(release): 1.1.1 2021-07-12 11:31:49 +00:00
a4a3ce8a2e fix: allow proxy url with parameters (#2100) 2021-07-12 19:14:01 +08:00
084017a673 fix: crash on background-size with calc() (fix #2469) (#2569) 2021-07-12 19:09:57 +08:00
4555940d0b fix: handle unhandled promise rejections (#2568) 2021-07-12 19:01:43 +08:00
CI
382853cb33 chore(release): 1.1.0 2021-07-11 14:15:36 +00:00
44296e5293 fix: text-decoration-line fallback (#2088) (#2567) 2021-07-11 22:11:29 +08:00
b2902ec31c deps: update dependencies with lint fixes (#2565) 2021-07-11 20:25:22 +08:00
e7a021ab93 ci: fail build if no artifacts uploaded (#2566) 2021-07-11 19:48:18 +08:00
85f79c1a5e fix: use baseline for text positioning (#2109) 2021-07-11 13:23:23 +08:00
cf35a282b2 docs: update border-style support 2021-07-04 14:12:48 +08:00
bb9237155c fix: Ensure resizeImage's canvas has at least 1px of width and height (#2409)
* ensure resizeImage canvas has > 0 width, height

* add tests for sliver background images
2021-07-04 13:40:25 +08:00
CI
b09ee30dae chore(release): 1.0.0 2021-07-04 05:15:53 +00:00
72cd528429 add features for border-style dashed, dotted, double. (#2531) 2021-07-04 12:17:07 +08:00
2a013e20c8 deps: update www deps (#2525) 2021-05-08 20:31:35 +08:00
ff35c7dbd3 test: update karma runner (#2524)
* test: update karma runner

* fix: Promise polyfill for testrunner
2021-05-08 18:32:03 +08:00
ba172678f0 fix top right border radius (#2522) 2021-05-07 17:32:51 +08:00
7222aba1b4 ci: update docs publish action (#2451) 2020-12-29 15:25:08 +08:00
82b7da558c fix: opacity with overflow hidden (#2450) 2020-12-29 12:29:00 +08:00
CI
3982df1492 chore(release): 1.0.0-rc.7 2020-08-09 14:49:12 +00:00
1514220812 fix: external styles on svg elements (#2320) 2020-08-09 14:14:50 +08:00
d07b6811c6 fix(z-index):z-index order (fix #2089) 2020-08-09 12:49:31 +08:00
bacfadff96 fix: concatenate contiguous font-family tokens (#2219) 2020-08-09 12:41:53 +08:00
CI
d7d17adf70 chore(release): 1.0.0-rc.6 2020-08-08 10:19:43 +00:00
60f6b85083 Update release script (#2319) 2020-08-08 18:18:10 +08:00
CI
e3237dc4ce chore(release): 1.0.0-rc.6 2020-08-08 08:46:37 +00:00
659f820170 update standard-release (#2317) 2020-08-08 16:45:26 +08:00
f7b39c0914 update npm build (#2316) 2020-08-08 16:00:41 +08:00
cd77e1cea1 update dependencies (#2315) 2020-08-08 15:37:50 +08:00
f23e6f6f26 fix: image loading="lazy" fix #2312 (#2314) 2020-08-08 15:37:34 +08:00
04e145b5eb Update CI 2020-08-08 14:54:12 +08:00
003cfd9073 Update ci 2020-08-02 16:34:56 +08:00
9749bb1fb1 Update ci (#2307) 2020-08-02 16:14:29 +08:00
3c2c826ad7 Update ci (#2306) 2020-08-02 15:49:02 +08:00
e496047888 Update ci.yml 2020-08-02 14:39:09 +08:00
51de34787a ci: build docs (#2305) 2020-07-31 19:21:02 +08:00
6c86f5f653 Update ci.yml 2020-07-31 00:57:23 +08:00
8f4ec8a0c0 Update ci.yml 2020-07-31 00:18:23 +08:00
51aadbb7f1 Update ci.yml 2020-07-30 23:38:22 +08:00
8af7745e80 Update release.yml 2020-07-30 23:20:26 +08:00
610997923a Create release.yml 2020-07-30 23:11:27 +08:00
d844328e0a Update ci.yml 2020-07-29 18:52:46 +08:00
e0d536777a Update new ios simulators 2020-07-29 18:47:43 +08:00
cc19105c91 Update ci.yml 2020-07-29 18:30:41 +08:00
2d30554b2a Update ci.yml 2020-07-29 18:17:46 +08:00
401df79087 Update ci.yml 2020-07-29 18:16:52 +08:00
7cb0019594 Update ci.yml 2020-07-28 23:59:49 +08:00
ebe9eccbd2 Update ci.yml 2020-07-28 23:48:05 +08:00
df44c86f68 Update ci.yml 2020-07-28 23:47:14 +08:00
e083e229c9 Update ci.yml 2020-07-28 23:07:29 +08:00
b308cbd998 Create ci.yml 2020-07-28 22:59:26 +08:00
4dd4a69c7a tests(reftests): Upgrade to fontawesome v5.13.0 (#2202)
* support font-family names with numbers in (e.g. Font Awesome 5)

* check for spaces in font family names first so generic font names don't get wrapped in quotes

* Update reftest to use fontawesome 5.13.0

* Add fontawesome v4 shims

* Revert "Merge remote-tracking branch 'grahamkane/master' into issue-1948-test-coverage"

This reverts commit 5211ab4065, reversing
changes made to ae0bd29d37.

* Revert "Revert "Merge remote-tracking branch 'grahamkane/master' into issue-1948-test-coverage""

This reverts commit 4911fe25f4.

* Revert "Merge remote-tracking branch 'grahamkane/master' into issue-1948-test-coverage"

This reverts commit 5211ab4065, reversing
changes made to ae0bd29d37.

Co-authored-by: Graham Kane <grahamkane@gmail.com>
2020-04-19 16:46:25 +08:00
c366e8790d ci: Azure Pipelines: upgrade from macOS 10.13 -> 10.14 (#2204) 2020-04-15 13:03:04 +08:00
ae5f866b37 Migrate base Chrome profiles to ChromeHeadless (#2203) 2020-04-14 18:15:13 +08:00
f139b513c5 fix: #1868 Clone node, Setting className for SVG element raises error (#2079)
* fix: #1868 Clone node, Setting className for SVG element raises error

* fix: svg element type information
2019-11-25 20:55:28 -08:00
e4d52a1ac6 Fix error in server-side rendering (#2039) 2019-11-25 20:16:07 -08:00
90 changed files with 70335 additions and 12828 deletions

View File

@ -11,7 +11,7 @@ insert_final_newline = true
indent_style = space
indent_size = 4
[{azure-pipelines.yml,package.json, ci/*.yml}]
[{*.yml,package.json}]
# The indent size used in the `package.json` file cannot be changed
# https://github.com/npm/npm/pull/3180#issuecomment-16336516
indent_size = 2

View File

@ -2,8 +2,7 @@
"parser": "@typescript-eslint/parser",
"extends": [
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"plugin:prettier/recommended",
"prettier"
],
"parserOptions": {
"project": "./tsconfig.json",

351
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,351 @@
name: CI
on:
push:
branches: [ master ]
tags:
- 'v*'
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
name: Build
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
- name: Cache node modules
uses: actions/cache@v2
env:
cache-name: cache-node-modules
with:
# npm cache files are stored in `~/.npm` on Linux/macOS
path: ~/.npm
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-
- name: Npm install
run: npm ci
- name: Build
run: npm run build
- name: Pack
run: |
npm pack
mv html2canvas-*.tgz html2canvas.tgz
tar --list --verbose --file=html2canvas.tgz
- name: Upload npm pack
uses: actions/upload-artifact@v2
with:
name: npm
path: html2canvas.tgz
if-no-files-found: error
- name: Upload dist
uses: actions/upload-artifact@v2
with:
name: dist
path: dist
if-no-files-found: error
- name: Upload build
uses: actions/upload-artifact@v2
with:
name: build
path: build
if-no-files-found: error
test:
runs-on: ubuntu-latest
name: Test
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
- name: Cache node modules
uses: actions/cache@v2
env:
cache-name: cache-node-modules
with:
# npm cache files are stored in `~/.npm` on Linux/macOS
path: ~/.npm
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-
- name: Npm install
run: npm ci
- name: Build
run: npm run build
- name: Lint
run: npm run lint
- name: Unit tests
run: npm run unittest
browser-test:
strategy:
fail-fast: false
matrix:
config:
- os: ubuntu-latest
name: Linux Firefox Stable
targetBrowser: Firefox_Stable
xvfb: true
- os: ubuntu-latest
name: Linux Chrome Stable
targetBrowser: Chrome_Stable
xvfb: true
- os: macos-latest
name: OSX Safari Stable
targetBrowser: Safari_Stable
- os: macos-latest
name: iOS Simulator Safari 12
targetBrowser: Safari_IOS_12
xcode: /Applications/Xcode_10.3.app
- os: macos-latest
name: iOS Simulator Safari 13
targetBrowser: Safari_IOS_13
xcode: /Applications/Xcode_11.6_beta.app
- os: macos-latest
name: iOS Simulator Safari 14
targetBrowser: Safari_IOS_14
xcode: /Applications/Xcode_12_beta.app
- os: windows-latest
name: Windows Internet Explorer 9 (Emulated)
targetBrowser: IE_9
- os: windows-latest
name: Windows Internet Explorer 10 (Emulated)
targetBrowser: IE_10
- os: windows-latest
name: Windows Internet Explorer 11
targetBrowser: IE_11
runs-on: ${{ matrix.config.os }}
name: ${{ matrix.config.name }}
env:
TARGET_BROWSER: ${{ matrix.config.targetBrowser }}
needs: build
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
- name: Cache node modules
uses: actions/cache@v2
env:
cache-name: cache-node-modules
with:
# npm cache files are stored in `~/.npm` on Linux/macOS
path: ~/.npm
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-
- name: Npm install
run: npm ci
- name: Download library
uses: actions/download-artifact@v2
with:
name: dist
path: dist
- name: Download test-runner
uses: actions/download-artifact@v2
with:
name: build
path: build
- name: xcode selection
if: ${{ matrix.config.xcode != '' }}
run: sudo xcode-select -s "${{ matrix.config.xcode }}"
- name: Run browser tests
if: ${{ matrix.config.xvfb != true }}
run: npm run karma
- name: Start Xvfb
if: ${{ matrix.config.xvfb == true }}
run: Xvfb :99 &
- name: Run browser tests
if: ${{ matrix.config.xvfb == true }}
run: DISPLAY=:99 npm run karma
- name: Upload screenshots
uses: actions/upload-artifact@v2
with:
name: reftest-results
path: tmp/reftests
if-no-files-found: error
publish:
runs-on: ubuntu-latest
name: Publish
if: startsWith(github.ref, 'refs/tags/v')
needs: browser-test
steps:
- uses: actions/checkout@v2
- name: Download NPM package
uses: actions/download-artifact@v2
with:
name: npm
path: npm
- name: Download library
uses: actions/download-artifact@v2
with:
name: dist
path: dist
- name: Create Github Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
draft: false
prerelease: ${{ contains(github.ref, '-rc.') || contains(github.ref, '-alpha.') }}
- name: Upload html2canvas.js
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./dist/html2canvas.js
asset_name: html2canvas.js
asset_content_type: text/javascript
- name: Upload html2canvas.min.js
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./dist/html2canvas.min.js
asset_name: html2canvas.min.js
asset_content_type: text/javascript
- name: Upload html2canvas.esm.js
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./dist/html2canvas.esm.js
asset_name: html2canvas.esm.js
asset_content_type: text/javascript
- name: Unpack npm
run: cd npm && tar -xvzf "html2canvas.tgz"
- uses: actions/setup-node@v1
with:
node-version: 12
registry-url: 'https://registry.npmjs.org'
- name: NPM Publish
run: cd npm/package && npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
docs:
runs-on: ubuntu-latest
name: Build docs
needs: browser-test
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
- name: Cache node modules
uses: actions/cache@v2
env:
cache-name: cache-node-modules
with:
# npm cache files are stored in `~/.npm` on Linux/macOS
path: ~/.npm
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-
- name: Npm install
run: npm ci
- name: Download library
uses: actions/download-artifact@v2
with:
name: dist
path: www/static/dist
- name: Download test results
uses: actions/download-artifact@v2
with:
name: reftest-results
path: www/static/results
- name: Copy reftests to docs website
run: cp -R tests/reftests www/static/tests/reftests && cp -R tests/assets www/static/tests/assets && cp tests/test.js www/static/tests/test.js
- name: Create reftest result index
run: npm run build:reftest-result-list www/static/results/metadata www/src/results.json
- name: Create reftest previewer
run: npm run build:reftest-preview
- name: Clean metadata folder
run: rm -rf www/static/results/metadata
- name: Build docs
run: npm run build && cd www && npm install && npm run build && cd ..
- name: Upload docs
uses: actions/upload-artifact@v2
with:
name: docs
path: www/public
if-no-files-found: error
publish-docs:
runs-on: ubuntu-latest
name: Publish Docs
if: ${{ github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v') }}
needs: docs
steps:
- uses: actions/checkout@v2
with:
persist-credentials: false
- name: Download docs
uses: actions/download-artifact@v2
with:
name: docs
path: docs
- name: Publish docs
uses: JamesIves/github-pages-deploy-action@3.7.1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: gh-pages
FOLDER: docs
SINGLE_COMMIT: true
CLEAN: true
diff-reftests:
runs-on: ubuntu-latest
name: Diff reftest screenshots
needs: browser-test
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- uses: actions/setup-node@v1
with:
node-version: 12
- name: Cache node modules
uses: actions/cache@v2
env:
cache-name: cache-node-modules
with:
# npm cache files are stored in `~/.npm` on Linux/macOS
path: ~/.npm
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-build-${{ env.cache-name }}-
${{ runner.os }}-build-
${{ runner.os }}-
- name: Npm install
run: npm ci
- name: Checkout current snapshots
run: git checkout origin/gh-pages results
- name: Download test results
uses: actions/download-artifact@v2
with:
name: reftest-results
path: tmp/reftests
- name: Run diff
run: npm run reftests-diff
continue-on-error: true
- name: Upload diff
uses: actions/upload-artifact@v2
with:
name: snapshot-diffs
path: tmp/snapshot-diffs

37
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,37 @@
name: Create Release
on:
workflow_dispatch:
inputs:
version:
description: 'Semantic version (major | minor | patch | premajor | preminor | prepatch | prerelease)'
default: 'patch'
required: true
jobs:
version:
name: Create version
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
token: ${{ secrets.PAT_TOKEN }}
- uses: actions/setup-node@v1
with:
node-version: 12
- name: Npm install
run: npm ci
- name: Configure git
run: |
git config user.name "CI"
git config user.email "niklasvh@gmail.com"
- name: Create release
run: npm run release -- --preset eslint --release-as ${{ github.event.inputs.version }}
- name: Print details
run: |
cat package.json
cat CHANGELOG.md
git tag
- name: Push git version
run: git push --follow-tags origin master

View File

@ -1,4 +1,8 @@
.github/
.idea/
.rpt2_cache
build/
configs/
docs/
examples/
scripts/
@ -6,17 +10,13 @@ src/
tests/
www/
tmp/
.github/
*.iml
.babelrc
.idea/
.editorconfig
.npmignore
.eslintrc
.travis.yml
azure-pipelines.yml
karma.js
.npmignore
.prettierrc
jest.config.js
karma.conf.js
rollup.config.js
webpack.config.js
.rpt2_cache
karma.js
rollup.config.ts

View File

@ -1,7 +1,101 @@
# Change Log
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [1.1.2](https://github.com/niklasvh/html2canvas/compare/v1.1.1...v1.1.2) (2021-07-13)
### ci
* implement screenshot diffing (#2571) ([e29af58](https://github.com/niklasvh/html2canvas/commit/e29af586618125bbad10ad6bee3d69fddbc5d22a)), closes [#2571](https://github.com/niklasvh/html2canvas/issues/2571)
### fix
* logger unique names (#2575) ([1715854](https://github.com/niklasvh/html2canvas/commit/171585491dd1bee4f30691328bd22e978f3ac79e)), closes [#2575](https://github.com/niklasvh/html2canvas/issues/2575)
* text-shadow position with baseline (#2576) ([439e365](https://github.com/niklasvh/html2canvas/commit/439e365ea8c703b528778a268dcfc3bf9ccad6a9)), closes [#2576](https://github.com/niklasvh/html2canvas/issues/2576)
## [1.1.1](https://github.com/niklasvh/html2canvas/compare/v1.1.0...v1.1.1) (2021-07-12)
### fix
* allow proxy url with parameters (#2100) ([a4a3ce8](https://github.com/niklasvh/html2canvas/commit/a4a3ce8a2eb6a4f43f1bc9a7935eb16f2b98a3cd)), closes [#2100](https://github.com/niklasvh/html2canvas/issues/2100)
* crash on background-size with calc() (fix #2469) (#2569) ([084017a](https://github.com/niklasvh/html2canvas/commit/084017a67319a993d73c6bdf612dd8532f1b8dbe)), closes [#2469](https://github.com/niklasvh/html2canvas/issues/2469) [#2569](https://github.com/niklasvh/html2canvas/issues/2569)
* handle unhandled promise rejections (#2568) ([4555940](https://github.com/niklasvh/html2canvas/commit/4555940d0bc17b7fd9327dd0164c382a3dbf1858)), closes [#2568](https://github.com/niklasvh/html2canvas/issues/2568)
# [1.1.0](https://github.com/niklasvh/html2canvas/compare/v1.0.0...v1.1.0) (2021-07-11)
### ci
* fail build if no artifacts uploaded (#2566) ([e7a021a](https://github.com/niklasvh/html2canvas/commit/e7a021ab931f3c0de060b4643e88fad85345c3d3)), closes [#2566](https://github.com/niklasvh/html2canvas/issues/2566)
### deps
* update dependencies with lint fixes (#2565) ([b2902ec](https://github.com/niklasvh/html2canvas/commit/b2902ec31c2a414ea26f864f8e00aa8846890ffc)), closes [#2565](https://github.com/niklasvh/html2canvas/issues/2565)
### docs
* update border-style support ([cf35a28](https://github.com/niklasvh/html2canvas/commit/cf35a282b2c9d41b601c3148e8c08fe7ba61a5f9))
### fix
* Ensure resizeImage's canvas has at least 1px of width and height (#2409) ([bb92371](https://github.com/niklasvh/html2canvas/commit/bb9237155cf0ec090432ee6c5d9c555eb6ffa81f)), closes [#2409](https://github.com/niklasvh/html2canvas/issues/2409)
* text-decoration-line fallback (#2088) (#2567) ([44296e5](https://github.com/niklasvh/html2canvas/commit/44296e529368140ec06a937383e05f3074b19ee2)), closes [#2088](https://github.com/niklasvh/html2canvas/issues/2088) [#2567](https://github.com/niklasvh/html2canvas/issues/2567)
* use baseline for text positioning (#2109) ([85f79c1](https://github.com/niklasvh/html2canvas/commit/85f79c1a5e4c0b422ace552c430dd389c8477a44)), closes [#2109](https://github.com/niklasvh/html2canvas/issues/2109)
# [1.0.0](https://github.com/niklasvh/html2canvas/compare/v1.0.0-rc.7...v1.0.0) (2021-07-04)
### ci
* update docs publish action (#2451) ([7222aba](https://github.com/niklasvh/html2canvas/commit/7222aba1b42138c3d466525172411b3d9869095f)), closes [#2451](https://github.com/niklasvh/html2canvas/issues/2451)
### deps
* update www deps (#2525) ([2a013e2](https://github.com/niklasvh/html2canvas/commit/2a013e20c814b7dbaea98f54f0bde8f553eb79a2)), closes [#2525](https://github.com/niklasvh/html2canvas/issues/2525)
### fix
* opacity with overflow hidden (#2450) ([82b7da5](https://github.com/niklasvh/html2canvas/commit/82b7da558c342e7f53d298bb1d843a5db86c3b21)), closes [#2450](https://github.com/niklasvh/html2canvas/issues/2450)
### test
* update karma runner (#2524) ([ff35c7d](https://github.com/niklasvh/html2canvas/commit/ff35c7dbd33f863f5b614d778baf8cb1e8dded60)), closes [#2524](https://github.com/niklasvh/html2canvas/issues/2524)
# [1.0.0-rc.7](https://github.com/niklasvh/html2canvas/compare/v1.0.0-rc.6...v1.0.0-rc.7) (2020-08-09)
### fix
* concatenate contiguous font-family tokens (#2219) ([bacfadf](https://github.com/niklasvh/html2canvas/commit/bacfadff96d907d9e8ab4ef515ca6487de9e51fc)), closes [#2219](https://github.com/niklasvh/html2canvas/issues/2219)
* external styles on svg elements (#2320) ([1514220](https://github.com/niklasvh/html2canvas/commit/1514220812cfb22d64d0974558d9c14fe90a41d3)), closes [#2320](https://github.com/niklasvh/html2canvas/issues/2320)
# [1.0.0-rc.6](https://github.com/niklasvh/html2canvas/compare/v1.0.0-rc.5...v1.0.0-rc.6) (2020-08-08)
### ci
* Azure Pipelines: upgrade from macOS 10.13 -> 10.14 (#2204) ([c366e87](https://github.com/niklasvh/html2canvas/commit/c366e8790d346ea981b24b7425aef6bf6d7ebcec)), closes [#2204](https://github.com/niklasvh/html2canvas/issues/2204)
* build docs (#2305) ([51de347](https://github.com/niklasvh/html2canvas/commit/51de34787ad8aba3f213800be45e878cddb064e9)), closes [#2305](https://github.com/niklasvh/html2canvas/issues/2305)
### fix
* #1868 Clone node, Setting className for SVG element raises error (#2079) ([f139b51](https://github.com/niklasvh/html2canvas/commit/f139b513c5cf9673dc727fd47124e0d779891e3a)), closes [#1868](https://github.com/niklasvh/html2canvas/issues/1868) [#2079](https://github.com/niklasvh/html2canvas/issues/2079) [#1868](https://github.com/niklasvh/html2canvas/issues/1868)
* image loading="lazy" fix #2312 (#2314) ([f23e6f6](https://github.com/niklasvh/html2canvas/commit/f23e6f6f2690dc0dbd02621c3bb81025904e6647)), closes [#2312](https://github.com/niklasvh/html2canvas/issues/2312) [#2314](https://github.com/niklasvh/html2canvas/issues/2314)
# [1.0.0-rc.5](https://github.com/niklasvh/html2canvas/compare/v1.0.0-rc.4...v1.0.0-rc.5) (2019-09-27)

View File

@ -4,7 +4,7 @@ html2canvas
[Homepage](https://html2canvas.hertzen.com) | [Downloads](https://github.com/niklasvh/html2canvas/releases) | [Questions](http://stackoverflow.com/questions/tagged/html2canvas?sort=newest)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/niklasvh/html2canvas?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Build Status](https://dev.azure.com/niklasvh/html2canvas/_apis/build/status/niklasvh.html2canvas?branchName=master)](https://dev.azure.com/niklasvh/html2canvas/_build/latest?definitionId=1&branchName=master)
![CI](https://github.com/niklasvh/html2canvas/workflows/CI/badge.svg?branch=master)
[![NPM Downloads](https://img.shields.io/npm/dm/html2canvas.svg)](https://www.npmjs.org/package/html2canvas)
[![NPM Version](https://img.shields.io/npm/v/html2canvas.svg)](https://www.npmjs.org/package/html2canvas)

View File

@ -1,170 +0,0 @@
trigger:
- master
jobs:
- job: Build
displayName: Build
pool:
vmImage: 'Ubuntu-16.04'
steps:
- task: NodeTool@0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- task: Npm@0
inputs:
command: install
- script: npm run build
displayName: Build
- script: |
npm pack
mv html2canvas-*.tgz html2canvas.tgz
tar --list --verbose --file=html2canvas.tgz
displayName: Pack
name: pack
- task: PublishBuildArtifacts@1
inputs:
PathtoPublish: html2canvas.tgz
artifactName: npm
- task: PublishBuildArtifacts@1
inputs:
PathtoPublish: 'dist'
artifactName: dist
- task: PublishBuildArtifacts@1
inputs:
PathtoPublish: 'build'
artifactName: build
- job: Test
displayName: Tests
pool:
vmImage: 'Ubuntu-16.04'
steps:
- task: NodeTool@0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- task: Npm@0
inputs:
command: install
- script: npm run build
displayName: Build
- script: npm run lint
displayName: Lint
- script: npm run unittest
displayName: Unit tests
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_Linux_Firefox_Stable
displayName: Linux Firefox Stable
vmImage: 'ubuntu-16.04'
targetBrowser: Firefox_Stable
xvfb: true
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_Linux_Chrome_Stable
displayName: Linux Chrome Stable
vmImage: 'ubuntu-16.04'
targetBrowser: Chrome_Stable
xvfb: true
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_OSX_Safari_IOS_9
displayName: iOS Simulator Safari 9
vmImage: 'macOS-10.13'
targetBrowser: Safari_IOS_9
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_OSX_Safari_IOS_10
displayName: iOS Simulator Safari 10
vmImage: 'macOS-10.13'
targetBrowser: Safari_IOS_10
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_OSX_Safari_IOS_12
displayName: iOS Simulator Safari 12
vmImage: 'macOS-10.13'
targetBrowser: Safari_IOS_12
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_OSX_Safari_Stable
displayName: OSX Safari Stable
vmImage: 'macOS-10.13'
targetBrowser: Safari_Stable
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_Windows_IE9
displayName: Windows Internet Explorer 9 (Emulated)
vmImage: 'vs2017-win2016'
targetBrowser: IE_9
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_Windows_IE10
displayName: Windows Internet Explorer 10 (Emulated)
vmImage: 'vs2017-win2016'
targetBrowser: IE_10
- template: ci/browser-tests.yml
parameters:
name: Browser_Tests_Windows_IE11
displayName: Windows Internet Explorer 11
vmImage: 'vs2017-win2016'
targetBrowser: IE_11
- job: Build_docs
displayName: Build docs
pool:
vmImage: 'Ubuntu-16.04'
dependsOn:
- Browser_Tests_Linux_Firefox_Stable
- Browser_Tests_Linux_Chrome_Stable
- Browser_Tests_OSX_Safari_IOS_9
- Browser_Tests_OSX_Safari_IOS_10
- Browser_Tests_OSX_Safari_IOS_12
- Browser_Tests_OSX_Safari_Stable
- Browser_Tests_Windows_IE9
- Browser_Tests_Windows_IE10
- Browser_Tests_Windows_IE11
steps:
- task: NodeTool@0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- task: Npm@0
inputs:
command: install
- task: DownloadBuildArtifacts@0
displayName: 'Download test results'
inputs:
artifactName: ReftestResults
downloadPath: $(System.DefaultWorkingDirectory)
- task: DownloadBuildArtifacts@0
displayName: 'Download dist'
inputs:
artifactName: dist
downloadPath: $(System.DefaultWorkingDirectory)
- script: cp -R tests/reftests www/static/tests/reftests && cp -R tests/assets www/static/tests/assets && cp tests/test.js www/static/tests/test.js && cp -R ReftestResults ./www/static/results
displayName: Copy reftests to docs website
- script: cp -R dist ./www/static/dist
displayName: Copy dist to docs website
- script: npm run build:reftest-result-list www/static/results/metadata www/src/results.json
displayName: Create reftest result index
- script: npm run build:reftest-preview
displayName: Create reftest previewer
- script: rm -rf www/static/results/metadata
displayName: Clean metadata folder
- script: npm run build && cd www && npm install && npm run build && cd ..
displayName: Build docs
- task: PublishBuildArtifacts@1
displayName: Upload docs website artifact
inputs:
PathtoPublish: 'www/public'
artifactName: docs

View File

@ -1,52 +0,0 @@
parameters:
name: ''
vmImage: ''
targetBrowser: ''
xvfb: false
jobs:
- job: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
pool:
vmImage: ${{ parameters.vmImage }}
variables:
TARGET_BROWSER: ${{ parameters.targetBrowser }}
dependsOn: Build
condition: succeeded()
steps:
- task: NodeTool@0
inputs:
versionSpec: '10.x'
displayName: 'Install Node.js'
- task: Npm@0
inputs:
command: install
- task: DownloadBuildArtifacts@0
displayName: 'Download library'
inputs:
artifactName: dist
downloadPath: $(System.DefaultWorkingDirectory)
- task: DownloadBuildArtifacts@0
displayName: 'Download testrunner'
inputs:
artifactName: build
downloadPath: $(System.DefaultWorkingDirectory)
- ${{ if not(eq(parameters.xvfb, 'true')) }}:
- script: npm run karma
displayName: 'Run browser tests'
- ${{ if eq(parameters.xvfb, 'true') }}:
- script: Xvfb :99 &
displayName: 'Start Xvfb'
- script: DISPLAY=:99 npm run karma
displayName: 'Run browser tests'
- task: PublishTestResults@2
condition: succeededOrFailed()
inputs:
testRunner: JUnit
testResultsFiles: 'tmp/junit/*.xml'
- task: PublishBuildArtifacts@1
displayName: Upload Screenshots
condition: succeededOrFailed()
inputs:
PathtoPublish: 'tmp/reftests'
artifactName: ReftestResults

View File

@ -18,7 +18,7 @@ Below is a list of all the supported CSS properties and values.
- border
- border-color
- border-radius
- border-style (**Only supports `solid`**)
- border-style
- border-width
- bottom
- box-sizing

View File

@ -4,26 +4,43 @@
const path = require('path');
const simctl = require('node-simctl');
const iosSimulator = require('appium-ios-simulator');
const listenAddress = 'localhost';
const port = 9876;
const log = require('karma/lib/logger').create('launcher:MobileSafari');
module.exports = function(config) {
// https://github.com/actions/virtual-environments/blob/master/images/macos/macos-10.15-Readme.md
const launchers = {
Safari_IOS_9: {
base: 'MobileSafari',
name: 'iPhone 5s',
platform: 'iOS',
sdk: '9.0'
},
Safari_IOS_10: {
base: 'MobileSafari',
name: 'iPhone 5s',
platform: 'iOS',
sdk: '10.0'
},
Safari_IOS_12: {
base: 'MobileSafari',
name: 'iPhone 5s',
sdk: '12.1'
platform: 'iOS',
sdk: '12.4'
},
Safari_IOS_13: {
base: 'MobileSafari',
name: 'iPhone 8',
platform: 'iOS',
sdk: '13.6'
},
Safari_IOS_14: {
base: 'MobileSafari',
name: 'iPhone 8',
platform: 'iOS',
sdk: '14.0'
},
SauceLabs_IE9: {
base: 'SauceLabs',
@ -85,10 +102,10 @@ module.exports = function(config) {
flags: ['-extoff']
},
Safari_Stable: {
base: 'Safari'
base: 'SafariNative'
},
Chrome_Stable: {
base: 'Chrome'
base: 'ChromeHeadless'
},
Firefox_Stable: {
base: 'Firefox'
@ -99,7 +116,7 @@ module.exports = function(config) {
const customLaunchers = ciLauncher ? {target_browser: ciLauncher} : {
stable_chrome: {
base: 'Chrome'
base: 'ChromeHeadless'
},
stable_firefox: {
base: 'Firefox'
@ -125,8 +142,8 @@ module.exports = function(config) {
}
baseBrowserDecorator(this);
this.on('start', url => {
simctl.getDevices().then(devices => {
const d = devices[args.sdk].find(d => {
simctl.getDevices(args.sdk, args.platform).then(devices => {
const d = devices.find(d => {
return d.name === args.name;
});
@ -208,6 +225,9 @@ module.exports = function(config) {
outputDir: 'tmp/junit/'
},
// web server listen address,
listenAddress,
// web server port
port,

103
karma.js
View File

@ -1,103 +0,0 @@
const Server = require('karma').Server;
const cfg = require('karma').config;
const path = require('path');
const proxy = require('html2canvas-proxy');
const karmaConfig = cfg.parseConfig(path.resolve('./karma.conf.js'));
const server = new Server(karmaConfig, (exitCode) => {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode)
});
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const filenamifyUrl = require('filenamify-url');
const mkdirp = require('mkdirp');
const screenshotFolder = './tmp/reftests';
const metadataFolder = './tmp/reftests/metadata';
mkdirp.sync(path.resolve(__dirname, screenshotFolder));
mkdirp.sync(path.resolve(__dirname, metadataFolder));
const CORS_PORT = 8081;
const corsApp = express();
corsApp.use('/proxy', proxy());
corsApp.use('/cors', cors(), express.static(path.resolve(__dirname)));
corsApp.use('/', express.static(path.resolve(__dirname, '/tests')));
corsApp.use((error, req, res, next) => {
console.error(error);
next();
});
process.on('uncaughtException', (err) => {
if(err.errno === 'EADDRINUSE') {
console.warn(err);
} else {
console.log(err);
process.exit(1);
}
});
corsApp.listen(CORS_PORT, () => {
console.log(`CORS server running on port ${CORS_PORT}`);
});
const app = express();
app.use(cors());
app.use((req, res, next) => {
// IE9 doesn't set headers for cross-domain ajax requests
if(typeof(req.headers['content-type']) === 'undefined'){
req.headers['content-type'] = "application/json";
}
next();
});
app.use(
bodyParser.json({
limit: '15mb',
type: '*/*'
})
);
const prefix = 'data:image/png;base64,';
const writeScreenshot = (buffer, body) => {
const filename = `${filenamifyUrl(
body.test.replace(/^\/tests\/reftests\//, '').replace(/\.html$/, ''),
{replacement: '-'}
)}!${[process.env.TARGET_BROWSER, body.platform.name, body.platform.version].join('-')}`;
fs.writeFileSync(path.resolve(__dirname, screenshotFolder, `${filename}.png`), buffer);
return filename;
};
app.post('/screenshot', (req, res) => {
if (!req.body || !req.body.screenshot) {
return res.sendStatus(400);
}
const buffer = new Buffer(req.body.screenshot.substring(prefix.length), 'base64');
const filename = writeScreenshot(buffer, req.body);
fs.writeFileSync(path.resolve(__dirname, metadataFolder, `${filename}.json`), JSON.stringify({
windowWidth: req.body.windowWidth,
windowHeight: req.body.windowHeight,
platform: req.body.platform,
devicePixelRatio: req.body.devicePixelRatio,
test: req.body.test,
id: process.env.TARGET_BROWSER,
screenshot: filename
}));
return res.sendStatus(200);
});
app.use((error, req, res, next) => {
console.error(error);
next();
});
const listener = app.listen(8000, () => {
server.start();
});

42801
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
"module": "dist/html2canvas.esm.js",
"typings": "dist/types/index.d.ts",
"browser": "dist/html2canvas.js",
"version": "1.0.0-rc.5",
"version": "1.1.2",
"author": {
"name": "Niklas von Hertzen",
"email": "niklasvh@gmail.com",
@ -27,68 +27,74 @@
"@babel/core": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"@babel/preset-flow": "^7.0.0",
"@rollup/plugin-commonjs": "^19.0.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.0.0",
"@rollup/plugin-typescript": "^8.2.1",
"@types/chai": "^4.1.7",
"@types/express": "^4.17.13",
"@types/glob": "^7.1.1",
"@types/jest": "^24.0.18",
"@types/mocha": "^5.2.6",
"@types/node": "^11.13.2",
"@types/platform": "^1.3.2",
"@types/jest": "^26.0.24",
"@types/jest-image-snapshot": "^4.3.1",
"@types/karma": "^6.3.0",
"@types/mocha": "^8.2.3",
"@types/node": "^16.3.1",
"@types/platform": "^1.3.4",
"@types/promise-polyfill": "^6.0.3",
"@typescript-eslint/eslint-plugin": "^1.7.0",
"@typescript-eslint/parser": "^1.7.0",
"@typescript-eslint/eslint-plugin": "^4.28.2",
"@typescript-eslint/parser": "^4.28.2",
"appium-ios-simulator": "^3.10.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.5",
"babel-plugin-add-module-exports": "^1.0.0",
"babel-plugin-add-module-exports": "^1.0.2",
"babel-plugin-dev-expression": "^0.2.1",
"base64-arraybuffer": "0.2.0",
"body-parser": "^1.18.3",
"body-parser": "^1.19.0",
"chai": "4.1.1",
"chromeless": "^1.5.2",
"cors": "2.8.4",
"es6-promise": "^4.2.6",
"eslint": "^5.16.0",
"eslint-config-prettier": "^4.2.0",
"eslint-plugin-prettier": "3.0.1",
"express": "^4.16.4",
"cors": "^2.8.5",
"es6-promise": "^4.2.8",
"eslint": "^7.30.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "3.4.0",
"express": "^4.17.1",
"filenamify-url": "1.0.0",
"glob": "7.1.3",
"html2canvas-proxy": "1.0.1",
"jest": "^24.9.0",
"jquery": "^3.4.0",
"jest": "^27.0.6",
"jest-image-snapshot": "^4.5.1",
"jquery": "^3.5.1",
"js-polyfills": "^0.1.42",
"karma": "^4.0.1",
"karma-chrome-launcher": "^2.2.0",
"karma": "^6.3.2",
"karma-chrome-launcher": "^3.1.0",
"karma-edge-launcher": "^0.4.2",
"karma-firefox-launcher": "^1.1.0",
"karma-firefox-launcher": "^2.1.0",
"karma-ie-launcher": "^1.0.0",
"karma-junit-reporter": "^1.2.0",
"karma-mocha": "^1.3.0",
"karma-safari-launcher": "^1.0.0",
"karma-junit-reporter": "^2.0.1",
"karma-mocha": "^2.0.1",
"karma-safarinative-launcher": "^1.1.0",
"karma-sauce-launcher": "^2.0.2",
"mocha": "^6.1.4",
"node-simctl": "^5.0.0",
"platform": "1.3.4",
"prettier": "1.17.0",
"mocha": "^9.0.2",
"node-simctl": "^5.3.0",
"platform": "^1.3.6",
"prettier": "^2.3.2",
"replace-in-file": "^3.0.0",
"rimraf": "2.6.1",
"rollup": "^1.10.1",
"rollup-plugin-commonjs": "^9.3.4",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-node-resolve": "^4.2.3",
"rollup-plugin-sourcemaps": "^0.4.2",
"rollup-plugin-typescript2": "^0.21.0",
"rimraf": "^3.0.2",
"rollup": "^2.53.1",
"rollup-plugin-sourcemaps": "^0.6.3",
"serve-index": "^1.9.1",
"slash": "1.0.0",
"standard-version": "^5.0.2",
"ts-jest": "^24.1.0",
"ts-loader": "^5.3.3",
"ts-node": "^8.0.3",
"typescript": "^3.4.3",
"uglify-js": "^3.5.11",
"uglifyjs-webpack-plugin": "^1.1.2",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0"
"standard-version": "^8.0.2",
"ts-jest": "^27.0.3",
"ts-loader": "^8.3.0",
"ts-node": "^10.1.0",
"tslib": "^2.3.0",
"typescript": "^4.3.5",
"uglify-js": "^3.13.10",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12",
"yargs": "^17.0.1"
},
"scripts": {
"prebuild": "rimraf dist/ && rimraf build/ && mkdirp dist && mkdirp build",
@ -100,13 +106,14 @@
"build:reftest-preview": "webpack --config www/webpack.config.js",
"release": "standard-version",
"format": "prettier --write \"{src,www/src,tests,scripts}/**/*.ts\"",
"lint": "eslint src/**/*.ts",
"lint": "eslint src/**/*.ts --max-warnings 0",
"test": "npm run lint && npm run unittest && npm run karma",
"unittest": "jest",
"karma": "node karma",
"reftests-diff": "mkdirp tmp/snapshots && jest --roots=tests --testMatch=**/reftest-diff.ts",
"karma": "ts-node tests/karma",
"watch": "rollup -c rollup.config.ts -w",
"watch:unittest": "mocha --require ts-node/register --watch-extensions ts -w src/**/__tests__/*.ts",
"start": "node tests/server"
"start": "ts-node tests/server --port=8080 --cors=8081"
},
"homepage": "https://html2canvas.hertzen.com",
"license": "MIT",

View File

@ -1,8 +1,8 @@
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import typescript from 'rollup-plugin-typescript2';
import json from 'rollup-plugin-json';
import typescript from '@rollup/plugin-typescript';
import json from '@rollup/plugin-json';
const pkg = require('./package.json');
@ -30,7 +30,7 @@ export default {
// Allow json resolution
json(),
// Compile TypeScript files
typescript({ useTsconfigDeclarationDir: true }),
typescript(),
// Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
commonjs({
include: 'node_modules/**'

View File

@ -21,7 +21,7 @@ const outputPath = resolve(__dirname, '../', process.argv[3]);
const ignoredTests = readFileSync(path)
.toString()
.split(/\r\n|\r|\n/)
.filter(l => l.length)
.filter((l) => l.length)
.reduce((acc: {[key: string]: string[]}, l) => {
const m = l.match(/^(\[(.+)\])?(.+)$/i);
if (m) {

View File

@ -17,7 +17,7 @@ const files = readdirSync(path);
interface RefTestMetadata {}
interface RefTestSingleMetadata extends RefTestMetadata {
test: string;
test?: string;
}
interface RefTestResults {
@ -26,12 +26,14 @@ interface RefTestResults {
const result: RefTestResults = files.reduce((result: RefTestResults, file) => {
const json: RefTestSingleMetadata = JSON.parse(readFileSync(resolve(__dirname, path, file)).toString());
if (!result[json.test]) {
result[json.test] = [];
}
if (json.test) {
if (!result[json.test]) {
result[json.test] = [];
}
result[json.test].push(json);
delete json.test;
result[json.test].push(json);
delete json.test;
}
return result;
}, {});

View File

@ -21,7 +21,6 @@ jest.mock('../render/stacking-context');
jest.mock('../render/canvas/canvas-renderer');
describe('html2canvas', () => {
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
const element = {
ownerDocument: {
defaultView: {
@ -60,7 +59,6 @@ describe('html2canvas', () => {
});
it('should use existing canvas when given as option', async () => {
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
const canvas = {} as HTMLCanvasElement;
await html2canvas(element, {canvas});
expect(CanvasRenderer).toHaveBeenLastCalledWith(

View File

@ -1,17 +1,22 @@
export class Logger {
debug() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
debug(): void {}
static create() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
static create(): void {}
static destroy() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
static destroy(): void {}
static getInstance(): Logger {
return logger;
}
info() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
info(): void {}
error() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
error(): void {}
}
const logger = new Logger();

View File

@ -47,12 +47,12 @@ const createMockContext = (origin: string, opts = {}) => {
const images: ImageMock[] = [];
const xhr: XMLHttpRequestMock[] = [];
const sleep = async (timeout: number) => await new Promise(resolve => setTimeout(resolve, timeout));
const sleep = async (timeout: number) => await new Promise((resolve) => setTimeout(resolve, timeout));
class ImageMock {
src?: string;
crossOrigin?: string;
onload?: () => {};
onload?: () => void;
constructor() {
images.push(this);
}
@ -65,8 +65,8 @@ class XMLHttpRequestMock {
method?: string;
url?: string;
response?: string;
onload?: () => {};
ontimeout?: () => {};
onload?: () => void;
ontimeout?: () => void;
constructor() {
this.sent = false;
this.status = 500;
@ -106,7 +106,7 @@ const setFeatures = (opts: {[key: string]: boolean} = {}) => {
SUPPORT_RESPONSE_TYPE: false
};
Object.keys(defaults).forEach(key => {
Object.keys(defaults).forEach((key) => {
Object.defineProperty(FEATURES, key, {
value: typeof opts[key] === 'boolean' ? opts[key] : defaults[key],
writable: true

View File

@ -1,10 +1,13 @@
import {Logger} from '../logger';
describe('logger', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let infoSpy: any;
beforeEach(() => {
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {});
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {
// do nothing
});
});
afterEach(() => {

View File

@ -4,7 +4,7 @@ import {Logger} from './logger';
export class CacheStorage {
private static _caches: {[key: string]: Cache} = {};
private static _link?: HTMLAnchorElement;
private static _origin: string = 'about:blank';
private static _origin = 'about:blank';
private static _current: Cache | null = null;
static create(name: string, options: ResourceOptions): Cache {
@ -39,7 +39,7 @@ export class CacheStorage {
return CacheStorage.getOrigin(src) === CacheStorage._origin;
}
static setContext(window: Window) {
static setContext(window: Window): void {
CacheStorage._link = window.document.createElement('a');
CacheStorage._origin = CacheStorage.getOrigin(window.location.href);
}
@ -52,11 +52,11 @@ export class CacheStorage {
return current;
}
static attachInstance(cache: Cache) {
static attachInstance(cache: Cache): void {
CacheStorage._current = cache;
}
static detachInstance() {
static detachInstance(): void {
CacheStorage._current = null;
}
}
@ -87,7 +87,9 @@ export class Cache {
}
if (isBlobImage(src) || isRenderable(src)) {
this._cache[src] = this.loadImage(src);
(this._cache[src] = this.loadImage(src)).catch(() => {
// prevent unhandled rejection
});
return result;
}
@ -169,7 +171,7 @@ export class Cache {
} else {
const reader = new FileReader();
reader.addEventListener('load', () => resolve(reader.result as string), false);
reader.addEventListener('error', e => reject(e), false);
reader.addEventListener('error', (e) => reject(e), false);
reader.readAsDataURL(xhr.response);
}
} else {
@ -178,7 +180,8 @@ export class Cache {
};
xhr.onerror = reject;
xhr.open('GET', `${proxy}?url=${encodeURIComponent(src)}&responseType=${responseType}`);
const queryString = proxy.indexOf('?') > -1 ? '&' : '?';
xhr.open('GET', `${proxy}${queryString}url=${encodeURIComponent(src)}&responseType=${responseType}`);
if (responseType !== 'text' && xhr instanceof XMLHttpRequest) {
xhr.responseType = responseType;

View File

@ -90,7 +90,13 @@ const testForeignObject = (document: Document): Promise<boolean> => {
.catch(() => false);
};
export const createForeignObjectSVG = (width: number, height: number, x: number, y: number, node: Node) => {
export const createForeignObjectSVG = (
width: number,
height: number,
x: number,
y: number,
node: Node
): SVGForeignObjectElement => {
const xmlns = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(xmlns, 'svg');
const foreignObject = document.createElementNS(xmlns, 'foreignObject');
@ -120,19 +126,19 @@ export const loadSerializedSVG = (svg: Node): Promise<HTMLImageElement> => {
};
export const FEATURES = {
get SUPPORT_RANGE_BOUNDS() {
get SUPPORT_RANGE_BOUNDS(): boolean {
'use strict';
const value = testRangeBounds(document);
Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', {value});
return value;
},
get SUPPORT_SVG_DRAWING() {
get SUPPORT_SVG_DRAWING(): boolean {
'use strict';
const value = testSVG(document);
Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', {value});
return value;
},
get SUPPORT_FOREIGNOBJECT_DRAWING() {
get SUPPORT_FOREIGNOBJECT_DRAWING(): Promise<boolean> {
'use strict';
const value =
typeof Array.from === 'function' && typeof window.fetch === 'function'
@ -141,19 +147,19 @@ export const FEATURES = {
Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', {value});
return value;
},
get SUPPORT_CORS_IMAGES() {
get SUPPORT_CORS_IMAGES(): boolean {
'use strict';
const value = testCORS();
Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', {value});
return value;
},
get SUPPORT_RESPONSE_TYPE() {
get SUPPORT_RESPONSE_TYPE(): boolean {
'use strict';
const value = testResponseType();
Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', {value});
return value;
},
get SUPPORT_CORS_XHR() {
get SUPPORT_CORS_XHR(): boolean {
'use strict';
const value = 'withCredentials' in new XMLHttpRequest();
Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', {value});

View File

@ -17,7 +17,7 @@ export class Logger {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
debug(...args: any) {
debug(...args: unknown[]): void {
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.debug === 'function') {
@ -33,11 +33,11 @@ export class Logger {
return Date.now() - this.start;
}
static create(options: LoggerOptions) {
static create(options: LoggerOptions): void {
Logger.instances[options.id] = new Logger(options);
}
static destroy(id: string) {
static destroy(id: string): void {
delete Logger.instances[id];
}
@ -50,7 +50,7 @@ export class Logger {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
info(...args: any) {
info(...args: unknown[]): void {
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.info === 'function') {
@ -61,7 +61,7 @@ export class Logger {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error(...args: any) {
error(...args: unknown[]): void {
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.error === 'function') {

View File

@ -191,8 +191,11 @@ export class CSSParsedDeclaration {
this.paddingLeft = parse(paddingLeft, declaration.paddingLeft);
this.position = parse(position, declaration.position);
this.textAlign = parse(textAlign, declaration.textAlign);
this.textDecorationColor = parse(textDecorationColor, declaration.textDecorationColor || declaration.color);
this.textDecorationLine = parse(textDecorationLine, declaration.textDecorationLine);
this.textDecorationColor = parse(textDecorationColor, declaration.textDecorationColor ?? declaration.color);
this.textDecorationLine = parse(
textDecorationLine,
declaration.textDecorationLine ?? declaration.textDecoration
);
this.textShadow = parse(textShadow, declaration.textShadow);
this.textTransform = parse(textTransform, declaration.textTransform);
this.transform = parse(transform, declaration.transform);
@ -289,7 +292,6 @@ const parse = (descriptor: CSSPropertyDescriptor<any>, style?: string | null) =>
const value = parser.parseComponentValue();
return isLengthPercentage(value) ? value : ZERO_LENGTH;
}
break;
}
throw new Error(`Attempting to parse unsupported css format type ${descriptor.format}`);
};

View File

@ -1,4 +1,4 @@
export const {Bounds} = jest.requireActual('../bounds');
export const parseBounds = () => {
export const parseBounds = (): typeof Bounds => {
return new Bounds(0, 0, 200, 50);
};

View File

@ -18,7 +18,7 @@ export const parseTextBounds = (value: string, styles: CSSParsedDeclaration, nod
const textList = breakText(value, styles);
const textBounds: TextBounds[] = [];
let offset = 0;
textList.forEach(text => {
textList.forEach((text) => {
if (styles.textDecorationLine.length || text.trim().length > 0) {
if (FEATURES.SUPPORT_RANGE_BOUNDS) {
textBounds.push(new TextBounds(text, getRangeBounds(node, offset, text.length)));
@ -67,7 +67,7 @@ const getRangeBounds = (node: Text, offset: number, length: number): Bounds => {
};
const breakText = (value: string, styles: CSSParsedDeclaration): string[] => {
return styles.letterSpacing !== 0 ? toCodePoints(value).map(i => fromCodePoint(i)) : breakWords(value, styles);
return styles.letterSpacing !== 0 ? toCodePoints(value).map((i) => fromCodePoint(i)) : breakWords(value, styles);
};
const breakWords = (str: string, styles: CSSParsedDeclaration): string[] => {

View File

@ -32,7 +32,10 @@ describe('property-descriptors', () => {
{
angle: deg(180),
type: CSSImageType.LINEAR_GRADIENT,
stops: [{color: pack(255, 255, 0, 0.5), stop: null}, {color: pack(0, 0, 255, 0.5), stop: null}]
stops: [
{color: pack(255, 255, 0, 0.5), stop: null},
{color: pack(0, 0, 255, 0.5), stop: null}
]
},
{url: 'https://html2canvas.hertzen.com', type: CSSImageType.URL}
]

View File

@ -0,0 +1,24 @@
import {deepEqual} from 'assert';
import {Parser} from '../../syntax/parser';
import {fontFamily} from '../font-family';
const fontFamilyParse = (value: string) => fontFamily.parse(Parser.parseValues(value));
describe('property-descriptors', () => {
describe('font-family', () => {
it('sans-serif', () => deepEqual(fontFamilyParse('sans-serif'), ['sans-serif']));
it('great fonts 40 library', () =>
deepEqual(fontFamilyParse('great fonts 40 library'), ["'great fonts 40 library'"]));
it('preferred font, "quoted fallback font", font', () =>
deepEqual(fontFamilyParse('preferred font, "quoted fallback font", font'), [
"'preferred font'",
"'quoted fallback font'",
'font'
]));
it("'escaping test\\'s font'", () =>
deepEqual(fontFamilyParse("'escaping test\\'s font'"), ["'escaping test's font'"]));
});
});

View File

@ -9,13 +9,9 @@ describe('property-descriptors', () => {
it('matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)', () =>
deepStrictEqual(parseValue('matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)'), [1, 2, 3, 4, 5, 6]));
it('matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)', () =>
deepStrictEqual(parseValue('matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)'), [
1,
0,
0,
1,
0,
0
]));
deepStrictEqual(
parseValue('matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)'),
[1, 0, 0, 1, 0, 0]
));
});
});

View File

@ -14,7 +14,7 @@ export const backgroundClip: IPropertyListDescriptor<BackgroundClip> = {
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundClip => {
return tokens.map(token => {
return tokens.map((token) => {
if (isIdentToken(token)) {
switch (token.value) {
case 'padding-box':

View File

@ -19,6 +19,6 @@ export const backgroundImage: IPropertyListDescriptor<ICSSImage[]> = {
return [];
}
return tokens.filter(value => nonFunctionArgSeparator(value) && isSupportedImage(value)).map(image.parse);
return tokens.filter((value) => nonFunctionArgSeparator(value) && isSupportedImage(value)).map(image.parse);
}
};

View File

@ -15,7 +15,7 @@ export const backgroundOrigin: IPropertyListDescriptor<BackgroundOrigin> = {
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundOrigin => {
return tokens.map(token => {
return tokens.map((token) => {
if (isIdentToken(token)) {
switch (token.value) {
case 'padding-box':

View File

@ -16,10 +16,10 @@ export const backgroundRepeat: IPropertyListDescriptor<BackgroundRepeat> = {
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundRepeat => {
return parseFunctionArgs(tokens)
.map(values =>
.map((values) =>
values
.filter(isIdentToken)
.map(token => token.value)
.map((token) => token.value)
.join(' ')
)
.map(parseBackgroundRepeat);

View File

@ -18,7 +18,7 @@ export const backgroundSize: IPropertyListDescriptor<BackgroundSize> = {
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundSize => {
return parseFunctionArgs(tokens).map(values => values.filter(isBackgroundSizeInfoToken));
return parseFunctionArgs(tokens).map((values) => values.filter(isBackgroundSizeInfoToken));
}
};

View File

@ -1,7 +1,10 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum BORDER_STYLE {
NONE = 0,
SOLID = 1
SOLID = 1,
DASHED = 2,
DOTTED = 3,
DOUBLE = 4
}
const borderStyleForSide = (side: string): IPropertyIdentValueDescriptor<BORDER_STYLE> => ({
@ -13,6 +16,12 @@ const borderStyleForSide = (side: string): IPropertyIdentValueDescriptor<BORDER_
switch (style) {
case 'none':
return BORDER_STYLE.NONE;
case 'dashed':
return BORDER_STYLE.DASHED;
case 'dotted':
return BORDER_STYLE.DOTTED;
case 'double':
return BORDER_STYLE.DOUBLE;
}
return BORDER_STYLE.SOLID;
}

View File

@ -50,6 +50,7 @@ export const display: IPropertyListDescriptor<Display> = {
const parseDisplayValue = (display: string): Display => {
switch (display) {
case 'block':
case '-webkit-box':
return DISPLAY.BLOCK;
case 'inline':
return DISPLAY.INLINE;

View File

@ -1,6 +1,6 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue} from '../syntax/parser';
import {StringValueToken, TokenType} from '../syntax/tokenizer';
import {TokenType} from '../syntax/tokenizer';
export type FONT_FAMILY = string;
@ -12,9 +12,26 @@ export const fontFamily: IPropertyListDescriptor<FontFamily> = {
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]) => {
return tokens.filter(isStringToken).map(token => token.value);
const accumulator: string[] = [];
const results: string[] = [];
tokens.forEach((token) => {
switch (token.type) {
case TokenType.IDENT_TOKEN:
case TokenType.STRING_TOKEN:
accumulator.push(token.value);
break;
case TokenType.NUMBER_TOKEN:
accumulator.push(token.number.toString());
break;
case TokenType.COMMA_TOKEN:
results.push(accumulator.join(' '));
accumulator.length = 0;
break;
}
});
if (accumulator.length) {
results.push(accumulator.join(' '));
}
return results.map((result) => (result.indexOf(' ') === -1 ? result : `'${result}'`));
}
};
const isStringToken = (token: CSSValue): token is StringValueToken =>
token.type === TokenType.STRING_TOKEN || token.type === TokenType.IDENT_TOKEN;

View File

@ -6,6 +6,6 @@ export const fontVariant: IPropertyListDescriptor<string[]> = {
type: PropertyDescriptorParsingType.LIST,
prefix: false,
parse: (tokens: CSSValue[]): string[] => {
return tokens.filter(isIdentToken).map(token => token.value);
return tokens.filter(isIdentToken).map((token) => token.value);
}
};

View File

@ -13,7 +13,7 @@ export const overflow: IPropertyListDescriptor<OVERFLOW[]> = {
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): OVERFLOW[] => {
return tokens.filter(isIdentToken).map(overflow => {
return tokens.filter(isIdentToken).map((overflow) => {
switch (overflow.value) {
case 'hidden':
return OVERFLOW.HIDDEN;

View File

@ -19,7 +19,7 @@ export const textDecorationLine: IPropertyListDescriptor<TextDecorationLine> = {
parse: (tokens: CSSValue[]): TextDecorationLine => {
return tokens
.filter(isIdentToken)
.map(token => {
.map((token) => {
switch (token.value) {
case 'underline':
return TEXT_DECORATION_LINE.UNDERLINE;
@ -32,6 +32,6 @@ export const textDecorationLine: IPropertyListDescriptor<TextDecorationLine> = {
}
return TEXT_DECORATION_LINE.NONE;
})
.filter(line => line !== TEXT_DECORATION_LINE.NONE);
.filter((line) => line !== TEXT_DECORATION_LINE.NONE);
}
};

View File

@ -27,14 +27,14 @@ export const transform: IPropertyValueDescriptor<Transform> = {
};
const matrix = (args: CSSValue[]): Transform => {
const values = args.filter(arg => arg.type === TokenType.NUMBER_TOKEN).map((arg: NumberValueToken) => arg.number);
const values = args.filter((arg) => arg.type === TokenType.NUMBER_TOKEN).map((arg: NumberValueToken) => arg.number);
return values.length === 6 ? (values as Matrix) : null;
};
// doesn't support 3D transforms at the moment
const matrix3d = (args: CSSValue[]): Transform => {
const values = args.filter(arg => arg.type === TokenType.NUMBER_TOKEN).map((arg: NumberValueToken) => arg.number);
const values = args.filter((arg) => arg.type === TokenType.NUMBER_TOKEN).map((arg: NumberValueToken) => arg.number);
const [a1, b1, {}, {}, a2, b2, {}, {}, {}, {}, {}, {}, a4, b4, {}, {}] = values;

View File

@ -74,7 +74,7 @@ export class Parser {
parseComponentValues(): CSSValue[] {
const values = [];
while (true) {
let value = this.consumeComponentValue();
const value = this.consumeComponentValue();
if (value.type === TokenType.EOF_TOKEN) {
return values;
}
@ -148,14 +148,14 @@ export const isStringToken = (token: CSSValue): token is StringValueToken => tok
export const isIdentWithValue = (token: CSSValue, value: string): boolean =>
isIdentToken(token) && token.value === value;
export const nonWhiteSpace = (token: CSSValue) => token.type !== TokenType.WHITESPACE_TOKEN;
export const nonFunctionArgSeparator = (token: CSSValue) =>
export const nonWhiteSpace = (token: CSSValue): boolean => token.type !== TokenType.WHITESPACE_TOKEN;
export const nonFunctionArgSeparator = (token: CSSValue): boolean =>
token.type !== TokenType.WHITESPACE_TOKEN && token.type !== TokenType.COMMA_TOKEN;
export const parseFunctionArgs = (tokens: CSSValue[]): CSSValue[][] => {
const args: CSSValue[][] = [];
let arg: CSSValue[] = [];
tokens.forEach(token => {
tokens.forEach((token) => {
if (token.type === TokenType.COMMA_TOKEN) {
if (arg.length === 0) {
throw new Error(`Error parsing function args, zero tokens for arg`);

View File

@ -315,7 +315,7 @@ export class Tokenizer {
this._value = [];
}
write(chunk: string) {
write(chunk: string): void {
this._value = this._value.concat(toCodePoints(chunk));
}
@ -542,8 +542,11 @@ export class Tokenizer {
}
if (questionMarks) {
const start = parseInt(fromCodePoint(...digits.map(digit => (digit === QUESTION_MARK ? ZERO : digit))), 16);
const end = parseInt(fromCodePoint(...digits.map(digit => (digit === QUESTION_MARK ? F : digit))), 16);
const start = parseInt(
fromCodePoint(...digits.map((digit) => (digit === QUESTION_MARK ? ZERO : digit))),
16
);
const end = parseInt(fromCodePoint(...digits.map((digit) => (digit === QUESTION_MARK ? F : digit))), 16);
return {type: TokenType.UNICODE_RANGE_TOKEN, start, end};
}
@ -642,7 +645,7 @@ export class Tokenizer {
private consumeBadUrlRemnants(): void {
while (true) {
let codePoint = this.consumeCodePoint();
const codePoint = this.consumeCodePoint();
if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) {
return;
}
@ -702,7 +705,7 @@ export class Tokenizer {
}
private consumeNumber() {
let repr = [];
const repr = [];
let type = FLAG_INTEGER;
let c1 = this.peekCodePoint(0);
if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
@ -724,7 +727,7 @@ export class Tokenizer {
c1 = this.peekCodePoint(0);
c2 = this.peekCodePoint(1);
let c3 = this.peekCodePoint(2);
const c3 = this.peekCodePoint(2);
if ((c1 === E || c1 === e) && (((c2 === PLUS_SIGN || c2 === HYPHEN_MINUS) && isDigit(c3)) || isDigit(c2))) {
repr.push(this.consumeCodePoint(), this.consumeCodePoint());
type = FLAG_NUMBER;
@ -743,7 +746,7 @@ export class Tokenizer {
const c3 = this.peekCodePoint(2);
if (isIdentifierStart(c1, c2, c3)) {
let unit = this.consumeName();
const unit = this.consumeName();
return {type: TokenType.DIMENSION_TOKEN, number, flags, unit};
}

View File

@ -40,25 +40,37 @@ describe('types', () => {
deepStrictEqual(parse('linear-gradient(yellow, blue)'), {
angle: deg(180),
type: CSSImageType.LINEAR_GRADIENT,
stops: [{color: colorParse('yellow'), stop: null}, {color: colorParse('blue'), stop: null}]
stops: [
{color: colorParse('yellow'), stop: null},
{color: colorParse('blue'), stop: null}
]
}));
it('linear-gradient(to bottom, yellow, blue)', () =>
deepStrictEqual(parse('linear-gradient(to bottom, yellow, blue)'), {
angle: deg(180),
type: CSSImageType.LINEAR_GRADIENT,
stops: [{color: colorParse('yellow'), stop: null}, {color: colorParse('blue'), stop: null}]
stops: [
{color: colorParse('yellow'), stop: null},
{color: colorParse('blue'), stop: null}
]
}));
it('linear-gradient(180deg, yellow, blue)', () =>
deepStrictEqual(parse('linear-gradient(180deg, yellow, blue)'), {
angle: deg(180),
type: CSSImageType.LINEAR_GRADIENT,
stops: [{color: colorParse('yellow'), stop: null}, {color: colorParse('blue'), stop: null}]
stops: [
{color: colorParse('yellow'), stop: null},
{color: colorParse('blue'), stop: null}
]
}));
it('linear-gradient(to top, blue, yellow)', () =>
deepStrictEqual(parse('linear-gradient(to top, blue, yellow)'), {
angle: 0,
type: CSSImageType.LINEAR_GRADIENT,
stops: [{color: colorParse('blue'), stop: null}, {color: colorParse('yellow'), stop: null}]
stops: [
{color: colorParse('blue'), stop: null},
{color: colorParse('yellow'), stop: null}
]
}));
it('linear-gradient(to top right, blue, yellow)', () =>
deepStrictEqual(parse('linear-gradient(to top right, blue, yellow)'), {
@ -67,7 +79,10 @@ describe('types', () => {
{type: TokenType.NUMBER_TOKEN, number: 0, flags: 4}
],
type: CSSImageType.LINEAR_GRADIENT,
stops: [{color: colorParse('blue'), stop: null}, {color: colorParse('yellow'), stop: null}]
stops: [
{color: colorParse('blue'), stop: null},
{color: colorParse('yellow'), stop: null}
]
}));
it('linear-gradient(to bottom, yellow 0%, blue 100%)', () =>
deepStrictEqual(parse('linear-gradient(to bottom, yellow 0%, blue 100%)'), {

View File

@ -41,7 +41,7 @@ export const isAngle = (value: CSSValue): boolean => {
export const parseNamedSide = (tokens: CSSValue[]): number | GradientCorner => {
const sideOrCorner = tokens
.filter(isIdentToken)
.map(ident => ident.value)
.map((ident) => ident.value)
.join(' ');
switch (sideOrCorner) {

View File

@ -59,9 +59,9 @@ export const color: ITypeDescriptor<Color> = {
}
};
export const isTransparent = (color: Color) => (0xff & color) === 0;
export const isTransparent = (color: Color): boolean => (0xff & color) === 0;
export const asString = (color: Color) => {
export const asString = (color: Color): string => {
const alpha = 0xff & color;
const blue = 0xff & (color >> 8);
const green = 0xff & (color >> 16);

View File

@ -14,11 +14,11 @@ import {color as colorType} from '../color';
import {HUNDRED_PERCENT, LengthPercentage, ZERO_LENGTH} from '../length-percentage';
export const webkitGradient = (tokens: CSSValue[]): CSSLinearGradientImage | CSSRadialGradientImage => {
let angle = deg(180);
const angle = deg(180);
const stops: UnprocessedGradientColorStop[] = [];
let type = CSSImageType.LINEAR_GRADIENT;
let shape: CSSRadialShape = CSSRadialShape.CIRCLE;
let size: CSSRadialSize = CSSRadialExtent.FARTHEST_CORNER;
const shape: CSSRadialShape = CSSRadialShape.CIRCLE;
const size: CSSRadialSize = CSSRadialExtent.FARTHEST_CORNER;
const position: LengthPercentage[] = [];
parseFunctionArgs(tokens).forEach((arg, i) => {
const firstToken = arg[0];

View File

@ -55,7 +55,10 @@ describe('functions', () => {
shape: CSSRadialShape.CIRCLE,
size: [{type: TokenType.DIMENSION_TOKEN, number: 20, flags: 4, unit: 'px'}],
position: [],
stops: [{color: colorParse('red'), stop: null}, {color: colorParse('blue'), stop: null}]
stops: [
{color: colorParse('red'), stop: null},
{color: colorParse('blue'), stop: null}
]
}));
});
});

View File

@ -9,7 +9,7 @@ export class CounterState {
this.counters = {};
}
getCounterValue(name: string) {
getCounterValue(name: string): number {
const counter = this.counters[name];
if (counter && counter.length) {
@ -23,8 +23,8 @@ export class CounterState {
return counter ? counter : [];
}
pop(counters: string[]) {
counters.forEach(counter => this.counters[counter].pop());
pop(counters: string[]): void {
counters.forEach((counter) => this.counters[counter].pop());
}
parse(style: CSSParsedCounterDeclaration): string[] {
@ -33,7 +33,7 @@ export class CounterState {
let canReset = true;
if (counterIncrement !== null) {
counterIncrement.forEach(entry => {
counterIncrement.forEach((entry) => {
const counter = this.counters[entry.counter];
if (counter && entry.increment !== 0) {
canReset = false;
@ -44,7 +44,7 @@ export class CounterState {
const counterNames: string[] = [];
if (canReset) {
counterReset.forEach(entry => {
counterReset.forEach((entry) => {
let counter = this.counters[entry.counter];
counterNames.push(entry.counter);
if (!counter) {
@ -70,42 +70,8 @@ const ROMAN_UPPER: CounterSymbols = {
const ARMENIAN: CounterSymbols = {
integers: [
9000,
8000,
7000,
6000,
5000,
4000,
3000,
2000,
1000,
900,
800,
700,
600,
500,
400,
300,
200,
100,
90,
80,
70,
60,
50,
40,
30,
20,
10,
9,
8,
7,
6,
5,
4,
3,
2,
1
9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70,
60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
],
values: [
'Ք',
@ -149,43 +115,8 @@ const ARMENIAN: CounterSymbols = {
const HEBREW: CounterSymbols = {
integers: [
10000,
9000,
8000,
7000,
6000,
5000,
4000,
3000,
2000,
1000,
400,
300,
200,
100,
90,
80,
70,
60,
50,
40,
30,
20,
19,
18,
17,
16,
15,
10,
9,
8,
7,
6,
5,
4,
3,
2,
1
10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20,
19, 18, 17, 16, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
],
values: [
'י׳',
@ -230,43 +161,8 @@ const HEBREW: CounterSymbols = {
const GEORGIAN: CounterSymbols = {
integers: [
10000,
9000,
8000,
7000,
6000,
5000,
4000,
3000,
2000,
1000,
900,
800,
700,
600,
500,
400,
300,
200,
100,
90,
80,
70,
60,
50,
40,
30,
20,
10,
9,
8,
7,
6,
5,
4,
3,
2,
1
10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90,
80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
],
values: [
'ჵ',
@ -362,21 +258,21 @@ const createCounterStyleFromRange = (
return (
(value < 0 ? '-' : '') +
(createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, codePoint =>
(createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, (codePoint) =>
fromCodePoint(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart)
) +
suffix)
);
};
const createCounterStyleFromSymbols = (value: number, symbols: string, suffix: string = '. '): string => {
const createCounterStyleFromSymbols = (value: number, symbols: string, suffix = '. '): string => {
const codePointRangeLength = symbols.length;
return (
createCounterStyleWithSymbolResolver(
Math.abs(value),
codePointRangeLength,
false,
codePoint => symbols[Math.floor(codePoint % codePointRangeLength)]
(codePoint) => symbols[Math.floor(codePoint % codePointRangeLength)]
) + suffix
);
};
@ -405,7 +301,7 @@ const createCJKCounter = (
}
for (let digit = 0; tmp > 0 && digit <= 4; digit++) {
let coefficient = tmp % 10;
const coefficient = tmp % 10;
if (coefficient === 0 && contains(flags, CJK_ZEROS) && string !== '') {
string = numbers[coefficient] + string;

View File

@ -98,7 +98,12 @@ export const calculateGradientDirection = (
const distance = (a: number, b: number): number => Math.sqrt(a * a + b * b);
const findCorner = (width: number, height: number, x: number, y: number, closest: boolean): [number, number] => {
const corners = [[0, 0], [0, height], [width, 0], [width, height]];
const corners = [
[0, 0],
[0, height],
[width, 0],
[width, height]
];
return corners.reduce(
(stat, corner) => {

View File

@ -98,8 +98,8 @@ export const image: ITypeDescriptor<ICSSImage> = {
}
};
export function isSupportedImage(value: CSSValue) {
return value.type !== TokenType.FUNCTION || SUPPORTED_IMAGE_FUNCTIONS[value.name];
export function isSupportedImage(value: CSSValue): boolean {
return value.type !== TokenType.FUNCTION || !!SUPPORTED_IMAGE_FUNCTIONS[value.name];
}
const SUPPORTED_IMAGE_FUNCTIONS: Record<string, (args: CSSValue[]) => ICSSImage> = {

View File

@ -31,10 +31,10 @@ export const getAbsoluteValueForTuple = (
width: number,
height: number
): [number, number] => {
let [x, y] = tuple;
const [x, y] = tuple;
return [getAbsoluteValue(x, width), getAbsoluteValue(typeof y !== 'undefined' ? y : x, height)];
};
export const getAbsoluteValue = (token: LengthPercentage, parent: number) => {
export const getAbsoluteValue = (token: LengthPercentage, parent: number): number => {
if (token.type === TokenType.PERCENTAGE_TOKEN) {
return (token.number / 100) * parent;
}

View File

@ -2,15 +2,14 @@ export class DocumentCloner {
clonedReferenceElement?: HTMLElement;
constructor() {
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
this.clonedReferenceElement = {} as HTMLElement;
}
toIFrame() {
return Promise.resolve({});
toIFrame(): Promise<HTMLIFrameElement> {
return Promise.resolve({} as HTMLIFrameElement);
}
static destroy() {
static destroy(): boolean {
return true;
}
}

View File

@ -5,9 +5,11 @@ import {
isElementNode,
isHTMLElementNode,
isIFrameElement,
isImageElement,
isScriptElement,
isSelectElement,
isStyleElement,
isSVGElementNode,
isTextareaElement,
isTextNode
} from './node-parser';
@ -114,7 +116,7 @@ export class DocumentCloner {
return iframeLoad;
}
createElementClone(node: HTMLElement): HTMLElement {
createElementClone<T extends HTMLElement | SVGElement>(node: T): HTMLElement | SVGElement {
if (isCanvasElement(node)) {
return this.createCanvasClone(node);
}
@ -127,7 +129,12 @@ export class DocumentCloner {
return this.createStyleClone(node);
}
return node.cloneNode(false) as HTMLElement;
const clone = node.cloneNode(false) as T;
if (isImageElement(clone) && clone.loading === 'lazy') {
clone.loading = 'eager';
}
return clone;
}
createStyleClone(node: HTMLStyleElement): HTMLStyleElement {
@ -256,14 +263,14 @@ export class DocumentCloner {
const window = node.ownerDocument.defaultView;
if (isHTMLElementNode(node) && window) {
if (window && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
const clone = this.createElementClone(node);
const style = window.getComputedStyle(node);
const styleBefore = window.getComputedStyle(node, ':before');
const styleAfter = window.getComputedStyle(node, ':after');
if (this.referenceElement === node) {
if (this.referenceElement === node && isHTMLElementNode(clone)) {
this.clonedReferenceElement = clone;
}
if (isBodyElement(clone)) {
@ -297,7 +304,7 @@ export class DocumentCloner {
this.counters.pop(counters);
if (style && this.options.copyStyles && !isIFrameElement(node)) {
if (style && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node)) {
copyCSSStyles(style, clone);
}
@ -342,7 +349,7 @@ export class DocumentCloner {
const anonymousReplacedElement = document.createElement('html2canvaspseudoelement');
copyCSSStyles(style, anonymousReplacedElement);
declaration.content.forEach(token => {
declaration.content.forEach((token) => {
if (token.type === TokenType.STRING_TOKEN) {
anonymousReplacedElement.appendChild(document.createTextNode(token.value));
} else if (token.type === TokenType.URL_TOKEN) {
@ -381,7 +388,7 @@ export class DocumentCloner {
: LIST_STYLE_TYPE.DECIMAL;
const separator = delim && delim.type === TokenType.STRING_TOKEN ? delim.value : '';
const text = counterStates
.map(value => createCounterText(value, counterType, false))
.map((value) => createCounterText(value, counterType, false))
.join(separator);
anonymousReplacedElement.appendChild(document.createTextNode(text));
@ -409,10 +416,17 @@ export class DocumentCloner {
});
anonymousReplacedElement.className = `${PSEUDO_HIDE_ELEMENT_CLASS_BEFORE} ${PSEUDO_HIDE_ELEMENT_CLASS_AFTER}`;
clone.className +=
const newClassName =
pseudoElt === PseudoElementType.BEFORE
? ` ${PSEUDO_HIDE_ELEMENT_CLASS_BEFORE}`
: ` ${PSEUDO_HIDE_ELEMENT_CLASS_AFTER}`;
if (isSVGElementNode(clone)) {
clone.className.baseValue += newClassName;
} else {
clone.className += newClassName;
}
return anonymousReplacedElement;
}
@ -458,19 +472,22 @@ const iframeLoader = (iframe: HTMLIFrameElement): Promise<HTMLIFrameElement> =>
const documentClone = cloneWindow.document;
cloneWindow.onload = iframe.onload = documentClone.onreadystatechange = () => {
cloneWindow.onload = iframe.onload = documentClone.onreadystatechange = null;
const interval = setInterval(() => {
if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
clearInterval(interval);
resolve(iframe);
}
}, 50);
};
cloneWindow.onload =
iframe.onload =
documentClone.onreadystatechange =
() => {
cloneWindow.onload = iframe.onload = documentClone.onreadystatechange = null;
const interval = setInterval(() => {
if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
clearInterval(interval);
resolve(iframe);
}
}, 50);
};
});
};
export const copyCSSStyles = (style: CSSStyleDeclaration, target: HTMLElement): HTMLElement => {
export const copyCSSStyles = <T extends HTMLElement | SVGElement>(style: CSSStyleDeclaration, target: T): T => {
// Edge does not provide value for cssText
for (let i = style.length - 1; i >= 0; i--) {
const property = style.item(i);

View File

@ -102,8 +102,9 @@ const createsStackingContext = (styles: CSSParsedDeclaration): boolean => styles
export const isTextNode = (node: Node): node is Text => node.nodeType === Node.TEXT_NODE;
export const isElementNode = (node: Node): node is Element => node.nodeType === Node.ELEMENT_NODE;
export const isHTMLElementNode = (node: Node): node is HTMLElement =>
typeof (node as HTMLElement).style !== 'undefined';
isElementNode(node) && typeof (node as HTMLElement).style !== 'undefined' && !isSVGElementNode(node);
export const isSVGElementNode = (element: Element): element is SVGElement =>
typeof (element as SVGElement).className === 'object';
export const isLIElement = (node: Element): node is HTMLLIElement => node.tagName === 'LI';
export const isOLElement = (node: Element): node is HTMLOListElement => node.tagName === 'OL';
export const isInputElement = (node: Element): node is HTMLInputElement => node.tagName === 'INPUT';

View File

@ -28,8 +28,9 @@ export class IFrameElementContainer extends ElementContainer {
// http://www.w3.org/TR/css3-background/#special-backgrounds
const documentBackgroundColor = iframe.contentWindow.document.documentElement
? parseColor(getComputedStyle(iframe.contentWindow.document.documentElement)
.backgroundColor as string)
? parseColor(
getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor as string
)
: COLORS.TRANSPARENT;
const bodyBackgroundColor = iframe.contentWindow.document.body
? parseColor(getComputedStyle(iframe.contentWindow.document.body).backgroundColor as string)

View File

@ -56,10 +56,21 @@ export class InputElementContainer extends ElementContainer {
if (this.type === CHECKBOX || this.type === RADIO) {
this.styles.backgroundColor = 0xdededeff;
this.styles.borderTopColor = this.styles.borderRightColor = this.styles.borderBottomColor = this.styles.borderLeftColor = 0xa5a5a5ff;
this.styles.borderTopWidth = this.styles.borderRightWidth = this.styles.borderBottomWidth = this.styles.borderLeftWidth = 1;
this.styles.borderTopStyle = this.styles.borderRightStyle = this.styles.borderBottomStyle = this.styles.borderLeftStyle =
BORDER_STYLE.SOLID;
this.styles.borderTopColor =
this.styles.borderRightColor =
this.styles.borderBottomColor =
this.styles.borderLeftColor =
0xa5a5a5ff;
this.styles.borderTopWidth =
this.styles.borderRightWidth =
this.styles.borderBottomWidth =
this.styles.borderLeftWidth =
1;
this.styles.borderTopStyle =
this.styles.borderRightStyle =
this.styles.borderBottomStyle =
this.styles.borderLeftStyle =
BORDER_STYLE.SOLID;
this.styles.backgroundClip = [BACKGROUND_CLIP.BORDER_BOX];
this.styles.backgroundOrigin = [BACKGROUND_ORIGIN.BORDER_BOX];
this.bounds = reformatInputBounds(this.bounds);
@ -67,10 +78,18 @@ export class InputElementContainer extends ElementContainer {
switch (this.type) {
case CHECKBOX:
this.styles.borderTopRightRadius = this.styles.borderTopLeftRadius = this.styles.borderBottomRightRadius = this.styles.borderBottomLeftRadius = CHECKBOX_BORDER_RADIUS;
this.styles.borderTopRightRadius =
this.styles.borderTopLeftRadius =
this.styles.borderBottomRightRadius =
this.styles.borderBottomLeftRadius =
CHECKBOX_BORDER_RADIUS;
break;
case RADIO:
this.styles.borderTopRightRadius = this.styles.borderTopLeftRadius = this.styles.borderBottomRightRadius = this.styles.borderBottomLeftRadius = RADIO_BORDER_RADIUS;
this.styles.borderTopRightRadius =
this.styles.borderTopLeftRadius =
this.styles.borderBottomRightRadius =
this.styles.borderBottomLeftRadius =
RADIO_BORDER_RADIUS;
break;
}
}

7
src/global.d.ts vendored
View File

@ -1,7 +1,7 @@
interface CSSStyleDeclaration {
textDecorationColor: string | null;
textDecorationLine: string | null;
overflowWrap: string | null;
textDecorationColor: string;
textDecorationLine: string;
overflowWrap: string;
}
interface DocumentType extends Node, ChildNode {
@ -9,5 +9,6 @@ interface DocumentType extends Node, ChildNode {
}
interface Document {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
fonts: any;
}

View File

@ -25,9 +25,16 @@ const html2canvas = (element: HTMLElement, options: Partial<Options> = {}): Prom
export default html2canvas;
CacheStorage.setContext(window);
if (typeof window !== 'undefined') {
CacheStorage.setContext(window);
}
let instanceCount = 1;
const renderElement = async (element: HTMLElement, opts: Partial<Options>): Promise<HTMLCanvasElement> => {
if (typeof element !== 'object') {
return Promise.reject('Invalid element provided as first argument');
}
const ownerDocument = element.ownerDocument;
if (!ownerDocument) {
@ -40,7 +47,7 @@ const renderElement = async (element: HTMLElement, opts: Partial<Options>): Prom
throw new Error(`Document is not attached to a Window`);
}
const instanceName = (Math.round(Math.random() * 1000) + Date.now()).toString(16);
const instanceName = `#${instanceCount++}`;
const {width, height, left, top} =
isBodyElement(element) || isHTMLElement(element) ? parseDocumentSize(ownerDocument) : parseBounds(element);

View File

@ -1,4 +1,4 @@
export const invariant = (assertion: boolean, error: string) => {
export const invariant = (assertion: boolean, error: string): void => {
if (!assertion) {
console.error(error);
}

View File

@ -91,6 +91,10 @@ export const calculateBackgroundSize = (
): [number, number] => {
const [first, second] = size;
if (!first) {
return [0, 0];
}
if (isLengthPercentage(first) && second && isLengthPercentage(second)) {
return [getAbsoluteValue(first, bounds.width), getAbsoluteValue(second, bounds.height)];
}
@ -218,7 +222,7 @@ export const calculateBackgroundRepeatPath = (
[width, height]: [number, number],
backgroundPositioningArea: Bounds,
backgroundPaintingArea: Bounds
) => {
): [Vector, Vector, Vector, Vector] => {
switch (repeat) {
case BACKGROUND_REPEAT.REPEAT_X:
return [

View File

@ -36,6 +36,105 @@ export const parsePathForBorder = (curves: BoundCurves, borderSide: number): Pat
}
};
export const parsePathForBorderDoubleOuter = (curves: BoundCurves, borderSide: number): Path[] => {
switch (borderSide) {
case 0:
return createPathFromCurves(
curves.topLeftBorderBox,
curves.topLeftBorderDoubleOuterBox,
curves.topRightBorderBox,
curves.topRightBorderDoubleOuterBox
);
case 1:
return createPathFromCurves(
curves.topRightBorderBox,
curves.topRightBorderDoubleOuterBox,
curves.bottomRightBorderBox,
curves.bottomRightBorderDoubleOuterBox
);
case 2:
return createPathFromCurves(
curves.bottomRightBorderBox,
curves.bottomRightBorderDoubleOuterBox,
curves.bottomLeftBorderBox,
curves.bottomLeftBorderDoubleOuterBox
);
case 3:
default:
return createPathFromCurves(
curves.bottomLeftBorderBox,
curves.bottomLeftBorderDoubleOuterBox,
curves.topLeftBorderBox,
curves.topLeftBorderDoubleOuterBox
);
}
};
export const parsePathForBorderDoubleInner = (curves: BoundCurves, borderSide: number): Path[] => {
switch (borderSide) {
case 0:
return createPathFromCurves(
curves.topLeftBorderDoubleInnerBox,
curves.topLeftPaddingBox,
curves.topRightBorderDoubleInnerBox,
curves.topRightPaddingBox
);
case 1:
return createPathFromCurves(
curves.topRightBorderDoubleInnerBox,
curves.topRightPaddingBox,
curves.bottomRightBorderDoubleInnerBox,
curves.bottomRightPaddingBox
);
case 2:
return createPathFromCurves(
curves.bottomRightBorderDoubleInnerBox,
curves.bottomRightPaddingBox,
curves.bottomLeftBorderDoubleInnerBox,
curves.bottomLeftPaddingBox
);
case 3:
default:
return createPathFromCurves(
curves.bottomLeftBorderDoubleInnerBox,
curves.bottomLeftPaddingBox,
curves.topLeftBorderDoubleInnerBox,
curves.topLeftPaddingBox
);
}
};
export const parsePathForBorderStroke = (curves: BoundCurves, borderSide: number): Path[] => {
switch (borderSide) {
case 0:
return createStrokePathFromCurves(curves.topLeftBorderStroke, curves.topRightBorderStroke);
case 1:
return createStrokePathFromCurves(curves.topRightBorderStroke, curves.bottomRightBorderStroke);
case 2:
return createStrokePathFromCurves(curves.bottomRightBorderStroke, curves.bottomLeftBorderStroke);
case 3:
default:
return createStrokePathFromCurves(curves.bottomLeftBorderStroke, curves.topLeftBorderStroke);
}
};
const createStrokePathFromCurves = (outer1: Path, outer2: Path): Path[] => {
const path = [];
if (isBezierCurve(outer1)) {
path.push(outer1.subdivide(0.5, false));
} else {
path.push(outer1);
}
if (isBezierCurve(outer2)) {
path.push(outer2.subdivide(0.5, true));
} else {
path.push(outer2);
}
return path;
};
const createPathFromCurves = (outer1: Path, inner1: Path, outer2: Path, inner2: Path): Path[] => {
const path = [];
if (isBezierCurve(outer1)) {

View File

@ -5,6 +5,18 @@ import {BezierCurve} from './bezier-curve';
import {Path} from './path';
export class BoundCurves {
readonly topLeftBorderDoubleOuterBox: Path;
readonly topRightBorderDoubleOuterBox: Path;
readonly bottomRightBorderDoubleOuterBox: Path;
readonly bottomLeftBorderDoubleOuterBox: Path;
readonly topLeftBorderDoubleInnerBox: Path;
readonly topRightBorderDoubleInnerBox: Path;
readonly bottomRightBorderDoubleInnerBox: Path;
readonly bottomLeftBorderDoubleInnerBox: Path;
readonly topLeftBorderStroke: Path;
readonly topRightBorderStroke: Path;
readonly bottomRightBorderStroke: Path;
readonly bottomLeftBorderStroke: Path;
readonly topLeftBorderBox: Path;
readonly topRightBorderBox: Path;
readonly bottomRightBorderBox: Path;
@ -60,6 +72,141 @@ export class BoundCurves {
const paddingBottom = getAbsoluteValue(styles.paddingBottom, element.bounds.width);
const paddingLeft = getAbsoluteValue(styles.paddingLeft, element.bounds.width);
this.topLeftBorderDoubleOuterBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 3,
bounds.top + borderTopWidth / 3,
tlh - borderLeftWidth / 3,
tlv - borderTopWidth / 3,
CORNER.TOP_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 3, bounds.top + borderTopWidth / 3);
this.topRightBorderDoubleOuterBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + topWidth,
bounds.top + borderTopWidth / 3,
trh - borderRightWidth / 3,
trv - borderTopWidth / 3,
CORNER.TOP_RIGHT
)
: new Vector(bounds.left + bounds.width - borderRightWidth / 3, bounds.top + borderTopWidth / 3);
this.bottomRightBorderDoubleOuterBox =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + bottomWidth,
bounds.top + rightHeight,
brh - borderRightWidth / 3,
brv - borderBottomWidth / 3,
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - borderRightWidth / 3,
bounds.top + bounds.height - borderBottomWidth / 3
);
this.bottomLeftBorderDoubleOuterBox =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 3,
bounds.top + leftHeight,
blh - borderLeftWidth / 3,
blv - borderBottomWidth / 3,
CORNER.BOTTOM_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 3, bounds.top + bounds.height - borderBottomWidth / 3);
this.topLeftBorderDoubleInnerBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + (borderLeftWidth * 2) / 3,
bounds.top + (borderTopWidth * 2) / 3,
tlh - (borderLeftWidth * 2) / 3,
tlv - (borderTopWidth * 2) / 3,
CORNER.TOP_LEFT
)
: new Vector(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3);
this.topRightBorderDoubleInnerBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + topWidth,
bounds.top + (borderTopWidth * 2) / 3,
trh - (borderRightWidth * 2) / 3,
trv - (borderTopWidth * 2) / 3,
CORNER.TOP_RIGHT
)
: new Vector(
bounds.left + bounds.width - (borderRightWidth * 2) / 3,
bounds.top + (borderTopWidth * 2) / 3
);
this.bottomRightBorderDoubleInnerBox =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + bottomWidth,
bounds.top + rightHeight,
brh - (borderRightWidth * 2) / 3,
brv - (borderBottomWidth * 2) / 3,
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - (borderRightWidth * 2) / 3,
bounds.top + bounds.height - (borderBottomWidth * 2) / 3
);
this.bottomLeftBorderDoubleInnerBox =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + (borderLeftWidth * 2) / 3,
bounds.top + leftHeight,
blh - (borderLeftWidth * 2) / 3,
blv - (borderBottomWidth * 2) / 3,
CORNER.BOTTOM_LEFT
)
: new Vector(
bounds.left + (borderLeftWidth * 2) / 3,
bounds.top + bounds.height - (borderBottomWidth * 2) / 3
);
this.topLeftBorderStroke =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 2,
bounds.top + borderTopWidth / 2,
tlh - borderLeftWidth / 2,
tlv - borderTopWidth / 2,
CORNER.TOP_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 2, bounds.top + borderTopWidth / 2);
this.topRightBorderStroke =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + topWidth,
bounds.top + borderTopWidth / 2,
trh - borderRightWidth / 2,
trv - borderTopWidth / 2,
CORNER.TOP_RIGHT
)
: new Vector(bounds.left + bounds.width - borderRightWidth / 2, bounds.top + borderTopWidth / 2);
this.bottomRightBorderStroke =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + bottomWidth,
bounds.top + rightHeight,
brh - borderRightWidth / 2,
brv - borderBottomWidth / 2,
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - borderRightWidth / 2,
bounds.top + bounds.height - borderBottomWidth / 2
);
this.bottomLeftBorderStroke =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth / 2,
bounds.top + leftHeight,
blh - borderLeftWidth / 2,
blv - borderBottomWidth / 2,
CORNER.BOTTOM_LEFT
)
: new Vector(bounds.left + borderLeftWidth / 2, bounds.top + bounds.height - borderBottomWidth / 2);
this.topLeftBorderBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT)
@ -89,10 +236,10 @@ export class BoundCurves {
this.topRightPaddingBox =
trh > 0 || trv > 0
? getCurvePoints(
bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth),
bounds.left + Math.min(topWidth, bounds.width - borderRightWidth),
bounds.top + borderTopWidth,
topWidth > bounds.width + borderLeftWidth ? 0 : trh - borderLeftWidth,
trv - borderTopWidth,
topWidth > bounds.width + borderRightWidth ? 0 : Math.max(0, trh - borderRightWidth),
Math.max(0, trv - borderTopWidth),
CORNER.TOP_RIGHT
)
: new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + borderTopWidth);
@ -100,9 +247,9 @@ export class BoundCurves {
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + Math.min(bottomWidth, bounds.width - borderLeftWidth),
bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth),
bounds.top + Math.min(rightHeight, bounds.height - borderBottomWidth),
Math.max(0, brh - borderRightWidth),
brv - borderBottomWidth,
Math.max(0, brv - borderBottomWidth),
CORNER.BOTTOM_RIGHT
)
: new Vector(
@ -113,9 +260,9 @@ export class BoundCurves {
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth,
bounds.top + leftHeight,
bounds.top + Math.min(leftHeight, bounds.height - borderBottomWidth),
Math.max(0, blh - borderLeftWidth),
blv - borderBottomWidth,
Math.max(0, blv - borderBottomWidth),
CORNER.BOTTOM_LEFT
)
: new Vector(bounds.left + borderLeftWidth, bounds.top + bounds.height - borderBottomWidth);

View File

@ -8,10 +8,15 @@ import {TextContainer} from '../../dom/text-container';
import {Path, transformPath} from '../path';
import {BACKGROUND_CLIP} from '../../css/property-descriptors/background-clip';
import {BoundCurves, calculateBorderBoxPath, calculateContentBoxPath, calculatePaddingBoxPath} from '../bound-curves';
import {isBezierCurve} from '../bezier-curve';
import {BezierCurve, isBezierCurve} from '../bezier-curve';
import {Vector} from '../vector';
import {CSSImageType, CSSURLImage, isLinearGradient, isRadialGradient} from '../../css/types/image';
import {parsePathForBorder} from '../border';
import {
parsePathForBorder,
parsePathForBorderDoubleInner,
parsePathForBorderDoubleOuter,
parsePathForBorderStroke
} from '../border';
import {Cache} from '../../core/cache-storage';
import {calculateBackgroundRendering, getBackgroundValueForIndex} from '../background';
import {isDimensionToken} from '../../css/syntax/parser';
@ -22,7 +27,7 @@ import {contentBox} from '../box-sizing';
import {CanvasElementContainer} from '../../dom/replaced-elements/canvas-element-container';
import {SVGElementContainer} from '../../dom/replaced-elements/svg-element-container';
import {ReplacedElementContainer} from '../../dom/replaced-elements/index';
import {EffectTarget, IElementEffect, isClipEffect, isTransformEffect} from '../effects';
import {EffectTarget, IElementEffect, isClipEffect, isOpacityEffect, isTransformEffect} from '../effects';
import {contains} from '../../core/bitwise';
import {calculateGradientDirection, calculateRadius, processColorStops} from '../../css/types/functions/gradient';
import {FIFTY_PERCENT, getAbsoluteValue} from '../../css/types/length-percentage';
@ -83,22 +88,24 @@ export class CanvasRenderer {
this.ctx.textBaseline = 'bottom';
this._activeEffects = [];
Logger.getInstance(options.id).debug(
`Canvas renderer initialized (${options.width}x${options.height} at ${options.x},${options.y}) with scale ${
options.scale
}`
`Canvas renderer initialized (${options.width}x${options.height} at ${options.x},${options.y}) with scale ${options.scale}`
);
}
applyEffects(effects: IElementEffect[], target: EffectTarget) {
applyEffects(effects: IElementEffect[], target: EffectTarget): void {
while (this._activeEffects.length) {
this.popEffect();
}
effects.filter(effect => contains(effect.target, target)).forEach(effect => this.applyEffect(effect));
effects.filter((effect) => contains(effect.target, target)).forEach((effect) => this.applyEffect(effect));
}
applyEffect(effect: IElementEffect) {
applyEffect(effect: IElementEffect): void {
this.ctx.save();
if (isOpacityEffect(effect)) {
this.ctx.globalAlpha = effect.opacity;
}
if (isTransformEffect(effect)) {
this.ctx.translate(effect.offsetX, effect.offsetY);
this.ctx.transform(
@ -120,33 +127,32 @@ export class CanvasRenderer {
this._activeEffects.push(effect);
}
popEffect() {
popEffect(): void {
this._activeEffects.pop();
this.ctx.restore();
}
async renderStack(stack: StackingContext) {
async renderStack(stack: StackingContext): Promise<void> {
const styles = stack.element.container.styles;
if (styles.isVisible()) {
this.ctx.globalAlpha = styles.opacity;
await this.renderStackContent(stack);
}
}
async renderNode(paint: ElementPaint) {
async renderNode(paint: ElementPaint): Promise<void> {
if (paint.container.styles.isVisible()) {
await this.renderNodeBackgroundAndBorders(paint);
await this.renderNodeContent(paint);
}
}
renderTextWithLetterSpacing(text: TextBounds, letterSpacing: number) {
renderTextWithLetterSpacing(text: TextBounds, letterSpacing: number, baseline: number): void {
if (letterSpacing === 0) {
this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + baseline);
} else {
const letters = toCodePoints(text.text).map(i => fromCodePoint(i));
const letters = toCodePoints(text.text).map((i) => fromCodePoint(i));
letters.reduce((left, letter) => {
this.ctx.fillText(letter, left, text.bounds.top + text.bounds.height);
this.ctx.fillText(letter, left, text.bounds.top + baseline);
return left + this.ctx.measureText(letter).width;
}, text.bounds.left);
@ -155,7 +161,7 @@ export class CanvasRenderer {
private createFontStyle(styles: CSSParsedDeclaration): string[] {
const fontVariant = styles.fontVariant
.filter(variant => variant === 'normal' || variant === 'small-caps')
.filter((variant) => variant === 'normal' || variant === 'small-caps')
.join('');
const fontFamily = styles.fontFamily.join(', ');
const fontSize = isDimensionToken(styles.fontSize)
@ -169,27 +175,30 @@ export class CanvasRenderer {
];
}
async renderTextNode(text: TextContainer, styles: CSSParsedDeclaration) {
async renderTextNode(text: TextContainer, styles: CSSParsedDeclaration): Promise<void> {
const [font, fontFamily, fontSize] = this.createFontStyle(styles);
this.ctx.font = font;
this.ctx.textBaseline = 'alphabetic';
text.textBounds.forEach(text => {
const {baseline, middle} = this.fontMetrics.getMetrics(fontFamily, fontSize);
text.textBounds.forEach((text) => {
this.ctx.fillStyle = asString(styles.color);
this.renderTextWithLetterSpacing(text, styles.letterSpacing);
this.renderTextWithLetterSpacing(text, styles.letterSpacing, baseline);
const textShadows: TextShadow = styles.textShadow;
if (textShadows.length && text.text.trim().length) {
textShadows
.slice(0)
.reverse()
.forEach(textShadow => {
.forEach((textShadow) => {
this.ctx.shadowColor = asString(textShadow.color);
this.ctx.shadowOffsetX = textShadow.offsetX.number * this.options.scale;
this.ctx.shadowOffsetY = textShadow.offsetY.number * this.options.scale;
this.ctx.shadowBlur = textShadow.blur.number;
this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
this.renderTextWithLetterSpacing(text, styles.letterSpacing, baseline);
});
this.ctx.shadowColor = '';
@ -200,13 +209,12 @@ export class CanvasRenderer {
if (styles.textDecorationLine.length) {
this.ctx.fillStyle = asString(styles.textDecorationColor || styles.color);
styles.textDecorationLine.forEach(textDecorationLine => {
styles.textDecorationLine.forEach((textDecorationLine) => {
switch (textDecorationLine) {
case TEXT_DECORATION_LINE.UNDERLINE:
// Draws a line at the baseline of the font
// TODO As some browsers display the line as more than 1px if the font-size is big,
// need to take that into account both in position and size
const {baseline} = this.fontMetrics.getMetrics(fontFamily, fontSize);
this.ctx.fillRect(
text.bounds.left,
Math.round(text.bounds.top + baseline),
@ -220,7 +228,6 @@ export class CanvasRenderer {
break;
case TEXT_DECORATION_LINE.LINE_THROUGH:
// TODO try and find exact position for line-through
const {middle} = this.fontMetrics.getMetrics(fontFamily, fontSize);
this.ctx.fillRect(
text.bounds.left,
Math.ceil(text.bounds.top + middle),
@ -238,7 +245,7 @@ export class CanvasRenderer {
container: ReplacedElementContainer,
curves: BoundCurves,
image: HTMLImageElement | HTMLCanvasElement
) {
): void {
if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
const box = contentBox(container);
const path = calculatePaddingBoxPath(curves);
@ -260,7 +267,7 @@ export class CanvasRenderer {
}
}
async renderNodeContent(paint: ElementPaint) {
async renderNodeContent(paint: ElementPaint): Promise<void> {
this.applyEffects(paint.effects, EffectTarget.CONTENT);
const container = paint.container;
const curves = paint.curves;
@ -363,7 +370,10 @@ export class CanvasRenderer {
}
if (isTextInputElement(container) && container.value.length) {
[this.ctx.font] = this.createFontStyle(styles);
const [fontFamily, fontSize] = this.createFontStyle(styles);
const {baseline} = this.fontMetrics.getMetrics(fontFamily, fontSize);
this.ctx.font = fontFamily;
this.ctx.fillStyle = asString(styles.color);
this.ctx.textBaseline = 'middle';
@ -393,7 +403,11 @@ export class CanvasRenderer {
]);
this.ctx.clip();
this.renderTextWithLetterSpacing(new TextBounds(container.value, textBounds), styles.letterSpacing);
this.renderTextWithLetterSpacing(
new TextBounds(container.value, textBounds),
styles.letterSpacing,
baseline
);
this.ctx.restore();
this.ctx.textBaseline = 'bottom';
this.ctx.textAlign = 'left';
@ -413,7 +427,9 @@ export class CanvasRenderer {
}
}
} else if (paint.listValue && container.styles.listStyleType !== LIST_STYLE_TYPE.NONE) {
[this.ctx.font] = this.createFontStyle(styles);
const [fontFamily, fontSize] = this.createFontStyle(styles);
this.ctx.font = fontFamily;
this.ctx.fillStyle = asString(styles.color);
this.ctx.textBaseline = 'middle';
@ -425,14 +441,20 @@ export class CanvasRenderer {
computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1
);
this.renderTextWithLetterSpacing(new TextBounds(paint.listValue, bounds), styles.letterSpacing);
const {baseline} = this.fontMetrics.getMetrics(fontFamily, fontSize);
this.renderTextWithLetterSpacing(
new TextBounds(paint.listValue, bounds),
styles.letterSpacing,
baseline
);
this.ctx.textBaseline = 'bottom';
this.ctx.textAlign = 'left';
}
}
}
async renderStackContent(stack: StackingContext) {
async renderStackContent(stack: StackingContext): Promise<void> {
// https://www.w3.org/TR/css-position-3/#painting-order
// 1. the background and borders of the element forming the stacking context.
await this.renderNodeBackgroundAndBorders(stack.element);
@ -480,7 +502,7 @@ export class CanvasRenderer {
}
}
mask(paths: Path[]) {
mask(paths: Path[]): void {
this.ctx.beginPath();
this.ctx.moveTo(0, 0);
this.ctx.lineTo(this.canvas.width, 0);
@ -491,13 +513,13 @@ export class CanvasRenderer {
this.ctx.closePath();
}
path(paths: Path[]) {
path(paths: Path[]): void {
this.ctx.beginPath();
this.formatPath(paths);
this.ctx.closePath();
}
formatPath(paths: Path[]) {
formatPath(paths: Path[]): void {
paths.forEach((point, index) => {
const start: Vector = isBezierCurve(point) ? point.start : point;
if (index === 0) {
@ -519,7 +541,7 @@ export class CanvasRenderer {
});
}
renderRepeat(path: Path[], pattern: CanvasPattern | CanvasGradient, offsetX: number, offsetY: number) {
renderRepeat(path: Path[], pattern: CanvasPattern | CanvasGradient, offsetX: number, offsetY: number): void {
this.path(path);
this.ctx.fillStyle = pattern;
this.ctx.translate(offsetX, offsetY);
@ -533,14 +555,14 @@ export class CanvasRenderer {
}
const canvas = (this.canvas.ownerDocument as Document).createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.width = Math.max(1, width);
canvas.height = Math.max(1, height);
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, width, height);
return canvas;
}
async renderBackgroundImage(container: ElementContainer) {
async renderBackgroundImage(container: ElementContainer): Promise<void> {
let index = container.styles.backgroundImage.length - 1;
for (const backgroundImage of container.styles.backgroundImage.slice(0).reverse()) {
if (backgroundImage.type === CSSImageType.URL) {
@ -574,7 +596,7 @@ export class CanvasRenderer {
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
const gradient = ctx.createLinearGradient(x0, y0, x1, y1);
processColorStops(backgroundImage.stops, lineLength).forEach(colorStop =>
processColorStops(backgroundImage.stops, lineLength).forEach((colorStop) =>
gradient.addColorStop(colorStop.stop, asString(colorStop.color))
);
@ -598,7 +620,7 @@ export class CanvasRenderer {
if (rx > 0 && rx > 0) {
const radialGradient = this.ctx.createRadialGradient(left + x, top + y, 0, left + x, top + y, rx);
processColorStops(backgroundImage.stops, rx * 2).forEach(colorStop =>
processColorStops(backgroundImage.stops, rx * 2).forEach((colorStop) =>
radialGradient.addColorStop(colorStop.stop, asString(colorStop.color))
);
@ -627,22 +649,37 @@ export class CanvasRenderer {
}
}
async renderBorder(color: Color, side: number, curvePoints: BoundCurves) {
async renderSolidBorder(color: Color, side: number, curvePoints: BoundCurves): Promise<void> {
this.path(parsePathForBorder(curvePoints, side));
this.ctx.fillStyle = asString(color);
this.ctx.fill();
}
async renderNodeBackgroundAndBorders(paint: ElementPaint) {
async renderDoubleBorder(color: Color, width: number, side: number, curvePoints: BoundCurves): Promise<void> {
if (width < 3) {
await this.renderSolidBorder(color, side, curvePoints);
return;
}
const outerPaths = parsePathForBorderDoubleOuter(curvePoints, side);
this.path(outerPaths);
this.ctx.fillStyle = asString(color);
this.ctx.fill();
const innerPaths = parsePathForBorderDoubleInner(curvePoints, side);
this.path(innerPaths);
this.ctx.fill();
}
async renderNodeBackgroundAndBorders(paint: ElementPaint): Promise<void> {
this.applyEffects(paint.effects, EffectTarget.BACKGROUND_BORDERS);
const styles = paint.container.styles;
const hasBackground = !isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
const borders = [
{style: styles.borderTopStyle, color: styles.borderTopColor},
{style: styles.borderRightStyle, color: styles.borderRightColor},
{style: styles.borderBottomStyle, color: styles.borderBottomColor},
{style: styles.borderLeftStyle, color: styles.borderLeftColor}
{style: styles.borderTopStyle, color: styles.borderTopColor, width: styles.borderTopWidth},
{style: styles.borderRightStyle, color: styles.borderRightColor, width: styles.borderRightWidth},
{style: styles.borderBottomStyle, color: styles.borderBottomColor, width: styles.borderBottomWidth},
{style: styles.borderLeftStyle, color: styles.borderLeftColor, width: styles.borderLeftWidth}
];
const backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(
@ -667,7 +704,7 @@ export class CanvasRenderer {
styles.boxShadow
.slice(0)
.reverse()
.forEach(shadow => {
.forEach((shadow) => {
this.ctx.save();
const borderBoxArea = calculateBorderBoxPath(paint.curves);
const maskOffset = shadow.inset ? 0 : MASK_OFFSET;
@ -702,13 +739,143 @@ export class CanvasRenderer {
let side = 0;
for (const border of borders) {
if (border.style !== BORDER_STYLE.NONE && !isTransparent(border.color)) {
await this.renderBorder(border.color, side, paint.curves);
if (border.style !== BORDER_STYLE.NONE && !isTransparent(border.color) && border.width > 0) {
if (border.style === BORDER_STYLE.DASHED) {
await this.renderDashedDottedBorder(
border.color,
border.width,
side,
paint.curves,
BORDER_STYLE.DASHED
);
} else if (border.style === BORDER_STYLE.DOTTED) {
await this.renderDashedDottedBorder(
border.color,
border.width,
side,
paint.curves,
BORDER_STYLE.DOTTED
);
} else if (border.style === BORDER_STYLE.DOUBLE) {
await this.renderDoubleBorder(border.color, border.width, side, paint.curves);
} else {
await this.renderSolidBorder(border.color, side, paint.curves);
}
}
side++;
}
}
async renderDashedDottedBorder(
color: Color,
width: number,
side: number,
curvePoints: BoundCurves,
style: BORDER_STYLE
): Promise<void> {
this.ctx.save();
const strokePaths = parsePathForBorderStroke(curvePoints, side);
const boxPaths = parsePathForBorder(curvePoints, side);
if (style === BORDER_STYLE.DASHED) {
this.path(boxPaths);
this.ctx.clip();
}
let startX, startY, endX, endY;
if (isBezierCurve(boxPaths[0])) {
startX = (boxPaths[0] as BezierCurve).start.x;
startY = (boxPaths[0] as BezierCurve).start.y;
} else {
startX = (boxPaths[0] as Vector).x;
startY = (boxPaths[0] as Vector).y;
}
if (isBezierCurve(boxPaths[1])) {
endX = (boxPaths[1] as BezierCurve).end.x;
endY = (boxPaths[1] as BezierCurve).end.y;
} else {
endX = (boxPaths[1] as Vector).x;
endY = (boxPaths[1] as Vector).y;
}
let length;
if (side === 0 || side === 2) {
length = Math.abs(startX - endX);
} else {
length = Math.abs(startY - endY);
}
this.ctx.beginPath();
if (style === BORDER_STYLE.DOTTED) {
this.formatPath(strokePaths);
} else {
this.formatPath(boxPaths.slice(0, 2));
}
let dashLength = width < 3 ? width * 3 : width * 2;
let spaceLength = width < 3 ? width * 2 : width;
if (style === BORDER_STYLE.DOTTED) {
dashLength = width;
spaceLength = width;
}
let useLineDash = true;
if (length <= dashLength * 2) {
useLineDash = false;
} else if (length <= dashLength * 2 + spaceLength) {
const multiplier = length / (2 * dashLength + spaceLength);
dashLength *= multiplier;
spaceLength *= multiplier;
} else {
const numberOfDashes = Math.floor((length + spaceLength) / (dashLength + spaceLength));
const minSpace = (length - numberOfDashes * dashLength) / (numberOfDashes - 1);
const maxSpace = (length - (numberOfDashes + 1) * dashLength) / numberOfDashes;
spaceLength =
maxSpace <= 0 || Math.abs(spaceLength - minSpace) < Math.abs(spaceLength - maxSpace)
? minSpace
: maxSpace;
}
if (useLineDash) {
if (style === BORDER_STYLE.DOTTED) {
this.ctx.setLineDash([0, dashLength + spaceLength]);
} else {
this.ctx.setLineDash([dashLength, spaceLength]);
}
}
if (style === BORDER_STYLE.DOTTED) {
this.ctx.lineCap = 'round';
this.ctx.lineWidth = width;
} else {
this.ctx.lineWidth = width * 2 + 1.1;
}
this.ctx.strokeStyle = asString(color);
this.ctx.stroke();
this.ctx.setLineDash([]);
// dashed round edge gap
if (style === BORDER_STYLE.DASHED) {
if (isBezierCurve(boxPaths[0])) {
const path1 = boxPaths[3] as BezierCurve;
const path2 = boxPaths[0] as BezierCurve;
this.ctx.beginPath();
this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
this.ctx.stroke();
}
if (isBezierCurve(boxPaths[1])) {
const path1 = boxPaths[1] as BezierCurve;
const path2 = boxPaths[2] as BezierCurve;
this.ctx.beginPath();
this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
this.ctx.stroke();
}
}
this.ctx.restore();
}
async render(element: ElementContainer): Promise<HTMLCanvasElement> {
if (this.options.backgroundColor) {
this.ctx.fillStyle = asString(this.options.backgroundColor);

View File

@ -20,13 +20,11 @@ export class ForeignObjectRenderer {
this.ctx.scale(this.options.scale, this.options.scale);
this.ctx.translate(-options.x + options.scrollX, -options.y + options.scrollY);
Logger.getInstance(options.id).debug(
`EXPERIMENTAL ForeignObject renderer initialized (${options.width}x${options.height} at ${options.x},${
options.y
}) with scale ${options.scale}`
`EXPERIMENTAL ForeignObject renderer initialized (${options.width}x${options.height} at ${options.x},${options.y}) with scale ${options.scale}`
);
}
async render(element: HTMLElement) {
async render(element: HTMLElement): Promise<HTMLCanvasElement> {
const svg = createForeignObjectSVG(
Math.max(this.options.windowWidth, this.options.width) * this.options.scale,
Math.max(this.options.windowHeight, this.options.height) * this.options.scale,

View File

@ -3,7 +3,8 @@ import {Path} from './path';
export const enum EffectType {
TRANSFORM = 0,
CLIP = 1
CLIP = 1,
OPACITY = 2
}
export const enum EffectTarget {
@ -17,33 +18,41 @@ export interface IElementEffect {
}
export class TransformEffect implements IElementEffect {
readonly type: EffectType;
readonly target: number;
readonly type: EffectType = EffectType.TRANSFORM;
readonly target: number = EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT;
readonly offsetX: number;
readonly offsetY: number;
readonly matrix: Matrix;
constructor(offsetX: number, offsetY: number, matrix: Matrix) {
this.type = EffectType.TRANSFORM;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.matrix = matrix;
this.target = EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT;
}
}
export class ClipEffect implements IElementEffect {
readonly type: EffectType;
readonly type: EffectType = EffectType.CLIP;
readonly target: number;
readonly path: Path[];
constructor(path: Path[], target: EffectTarget) {
this.type = EffectType.CLIP;
this.target = target;
this.path = path;
}
}
export class OpacityEffect implements IElementEffect {
readonly type: EffectType = EffectType.OPACITY;
readonly target: number = EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT;
readonly opacity: number;
constructor(opacity: number) {
this.opacity = opacity;
}
}
export const isTransformEffect = (effect: IElementEffect): effect is TransformEffect =>
effect.type === EffectType.TRANSFORM;
export const isClipEffect = (effect: IElementEffect): effect is ClipEffect => effect.type === EffectType.CLIP;
export const isOpacityEffect = (effect: IElementEffect): effect is OpacityEffect => effect.type === EffectType.OPACITY;

View File

@ -1,7 +1,7 @@
import {ElementContainer, FLAGS} from '../dom/element-container';
import {contains} from '../core/bitwise';
import {BoundCurves, calculateBorderBoxPath, calculatePaddingBoxPath} from './bound-curves';
import {ClipEffect, EffectTarget, IElementEffect, TransformEffect} from './effects';
import {ClipEffect, EffectTarget, IElementEffect, OpacityEffect, TransformEffect} from './effects';
import {OVERFLOW} from '../css/property-descriptors/overflow';
import {equalPath} from './path';
import {DISPLAY} from '../css/property-descriptors/display';
@ -41,6 +41,10 @@ export class ElementPaint {
this.container = element;
this.effects = parentStack.slice(0);
this.curves = new BoundCurves(element);
if (element.styles.opacity < 1) {
this.effects.push(new OpacityEffect(element.styles.opacity));
}
if (element.styles.transform !== null) {
const offsetX = element.bounds.left + element.styles.transformOrigin[0].number;
const offsetY = element.bounds.top + element.styles.transformOrigin[1].number;
@ -80,7 +84,7 @@ const parseStackTree = (
realStackingContext: StackingContext,
listItems: ElementPaint[]
) => {
parent.container.elements.forEach(child => {
parent.container.elements.forEach((child) => {
const treatAsRealStackingContext = contains(child.flags, FLAGS.CREATES_REAL_STACKING_CONTEXT);
const createsStackingContext = contains(child.flags, FLAGS.CREATES_STACKING_CONTEXT);
const paintContainer = new ElementPaint(child, parent.getParentEffects());
@ -115,7 +119,7 @@ const parseStackTree = (
} else if (order > 0) {
let index = 0;
parentStack.positiveZIndex.some((current, i) => {
if (order > current.element.container.styles.zIndex.order) {
if (order >= current.element.container.styles.zIndex.order) {
index = i + 1;
return false;
} else if (index > 0) {

BIN
tests/assets/bg-sliver.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 B

33
tests/karma.ts Normal file
View File

@ -0,0 +1,33 @@
import {screenshotApp, corsApp} from './server';
import {Server} from 'http';
import {config as KarmaConfig, Server as KarmaServer, TestResults} from 'karma';
import * as path from 'path';
const karmaTestRunner = (): Promise<void> =>
new Promise<void>((resolve, reject) => {
const karmaConfig = KarmaConfig.parseConfig(path.resolve(__dirname, '../karma.conf.js'), {});
const server = new KarmaServer(karmaConfig, (exitCode: number) => {
if (exitCode > 0) {
reject(`Karma has exited with ${exitCode}`);
} else {
resolve();
}
});
server.on('run_complete', (_browsers: any, _results: TestResults) => {
server.stop();
});
server.start();
});
const servers: Server[] = [];
servers.push(screenshotApp.listen(8000));
servers.push(corsApp.listen(8081));
karmaTestRunner()
.then(() => {
servers.forEach((server) => server.close());
})
.catch((e) => {
console.error(e);
process.exit(1);
});

32
tests/reftest-diff.ts Normal file
View File

@ -0,0 +1,32 @@
import {sync} from 'glob';
import {resolve, basename} from 'path';
import {existsSync, promises} from 'fs';
import {toMatchImageSnapshot} from 'jest-image-snapshot';
const resultsDir = resolve(__dirname, '../results');
const customSnapshotsDir = resolve(__dirname, '../tmp/snapshots');
const customDiffDir = resolve(__dirname, '../tmp/snapshot-diffs');
expect.extend({toMatchImageSnapshot});
describe('Image diff', () => {
const files: string[] = sync('../tmp/reftests/**/*.png', {
cwd: __dirname,
root: resolve(__dirname, '../../')
}).filter((path) => existsSync(resolve(resultsDir, basename(path))));
it.each(files.map((path) => basename(path)))('%s', async (filename) => {
const previous = resolve(resultsDir, filename);
const previousSnap = resolve(customSnapshotsDir, `${filename}-snap.png`);
await promises.copyFile(previous, previousSnap);
const updated = resolve(__dirname, '../tmp/reftests/', filename);
const buffer = await promises.readFile(updated);
// @ts-ignore
expect(buffer).toMatchImageSnapshot({
customSnapshotsDir,
customSnapshotIdentifier: () => filename,
customDiffDir
});
});
});

View File

@ -9,6 +9,10 @@
display: block;
background:url("../../assets/image.jpg") center center;
}
.sliver div {
background:url("../../assets/bg-sliver.png") center center;
background-size: 650px auto;
}
.vertical {
float: right;
@ -57,5 +61,9 @@
<div style='background-size: auto;'></div>
</div>
<div class="container" style="padding: 10px; background-size: contain; background-origin: content-box; background-clip: content-box"></div>
<div class="container" style="background-size: calc(100% - 10px)"></div>
<div class="sliver">
<div></div>
</div>
</body>
</html>

View File

@ -63,6 +63,13 @@
border-radius: 200px;
}
.box7 {
border-width: 10px 10px 10px 1px;
border-left-color: transparent;
border-top-color: red;
border-right-color: green;
}
.gauge{
display: inline-block;
width: 100px;
@ -91,6 +98,7 @@
<div class="box box4">&nbsp;</div>
<div class="box box5">&nbsp;</div>
<div class="box box6">&nbsp;</div>
<div class="box box7">&nbsp;</div>
<div class="gauge gauge1"></div>
<div class="gauge gauge2"></div>
<div class="gauge gauge3"></div>

View File

@ -2,10 +2,21 @@
<html>
<head>
<title>iframe test</title>
<script>
h2cOptions = {useCORS: true, proxy: null};
</script>
<script type="text/javascript" src="../test.js"></script>
</head>
<body>
<div style="background: cornflowerblue; padding: 20px; width: 200px;">Parent document content</div>
<iframe src="/tests/assets/iframe/frame1.html" width="500" height="500"></iframe>
<iframe
title="Github"
src="https://ghbtns.com/github-btn.html?user=niklasvh&repo=html2canvas&type=star&count=true&size=large"
frameBorder="0"
scrolling="0"
width="160px"
height="30px"
></iframe>
</body>
</html>

View File

@ -7,6 +7,7 @@
</head>
<body>
<img src="../../assets/image.jpg" />
<img src="../../assets/image.jpg" loading="lazy" />
<img src="../../assets/image.jpg" style="width:50px;height:400px;" />
<img src="../../assets/image.jpg" style="width:500px;" />
<img src="../../assets/image.jpg" style="width:100px;border-radius:50px;" />

View File

@ -11,13 +11,22 @@
body {
font-family: Arial;
}
svg:before {
content: " ";
}
</style>
<style>
.html { font: italic 13px sans-serif; }
.two { font: bold 14px sans-serif; }
.canvas { font: italic 15px serif; fill: red; }
</style>
</head>
<body>
<div>
<img src="../../../assets/image.svg" />
<img width="200" height="200" src='data:image/svg+xml,<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" version="1.1" width="306" height="296"><defs id="defs4" /><g transform="translate(-162.46995,-477.2863)" id="layer1"><path d="m 314.15745,481.69558 c -59.20089,0.53774 -114.80979,36.72219 -137.3125,95.34375 -29.39129,76.56693 8.83932,162.45246 85.40625,191.84375 l 34.03125,-88.6875 c -20.0678,-7.71358 -34.3125,-27.15324 -34.3125,-49.9375 0,-29.54723 23.95277,-53.5 53.5,-53.5 29.54723,0 53.5,23.95277 53.5,53.5 0,22.78426 -14.2447,42.22392 -34.3125,49.9375 l 34.03125,88.6875 c 39.29085,-15.08234 70.3239,-46.1154 85.40625,-85.40625 29.39129,-76.56693 -8.83932,-162.48371 -85.40625,-191.875 -17.94537,-6.88859 -36.40853,-10.07087 -54.53125,-9.90625 z" id="path2830" style="fill:#40aa54;fill-opacity:1;stroke:#20552a;stroke-width:7.99999952;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" /></g></svg>' />
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="306" height="296" id="svg2">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="306" height="296" id="svg2" class="test">
<defs id="defs4"/>
<g transform="translate(-162.46995,-477.2863)" id="layer1">
<path d="m 314.15745,481.69558 c -59.20089,0.53774 -114.80979,36.72219 -137.3125,95.34375 -29.39129,76.56693 8.83932,162.45246 85.40625,191.84375 l 34.03125,-88.6875 c -20.0678,-7.71358 -34.3125,-27.15324 -34.3125,-49.9375 0,-29.54723 23.95277,-53.5 53.5,-53.5 29.54723,0 53.5,23.95277 53.5,53.5 0,22.78426 -14.2447,42.22392 -34.3125,49.9375 l 34.03125,88.6875 c 39.29085,-15.08234 70.3239,-46.1154 85.40625,-85.40625 29.39129,-76.56693 -8.83932,-162.48371 -85.40625,-191.875 -17.94537,-6.88859 -36.40853,-10.07087 -54.53125,-9.90625 z"
@ -25,6 +34,11 @@
style="fill:#40aa54;fill-opacity:1;stroke:#20552a;stroke-width:7.99999952;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"/>
</g>
</svg>
<svg width="240" height="160" viewBox="0 0 120 80" xmlns="http://www.w3.org/2000/svg">
<text x="40" y="20" class="html">html</text>
<text x="55" y="25" class="two">2</text>
<text x="65" y="35" class="canvas">canvas</text>
</svg>
<img width="200" height="200" src="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjMwNiIgaGVpZ2h0PSIyOTYiPjxkZWZzIGlkPSJkZWZzNCIgLz48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTYyLjQ2OTk1LC00NzcuMjg2MykiIGlkPSJsYXllcjEiPjxwYXRoIGQ9Im0gMzE0LjE1NzQ1LDQ4MS42OTU1OCBjIC01OS4yMDA4OSwwLjUzNzc0IC0xMTQuODA5NzksMzYuNzIyMTkgLTEzNy4zMTI1LDk1LjM0Mzc1IC0yOS4zOTEyOSw3Ni41NjY5MyA4LjgzOTMyLDE2Mi40NTI0NiA4NS40MDYyNSwxOTEuODQzNzUgbCAzNC4wMzEyNSwtODguNjg3NSBjIC0yMC4wNjc4LC03LjcxMzU4IC0zNC4zMTI1LC0yNy4xNTMyNCAtMzQuMzEyNSwtNDkuOTM3NSAwLC0yOS41NDcyMyAyMy45NTI3NywtNTMuNSA1My41LC01My41IDI5LjU0NzIzLDAgNTMuNSwyMy45NTI3NyA1My41LDUzLjUgMCwyMi43ODQyNiAtMTQuMjQ0Nyw0Mi4yMjM5MiAtMzQuMzEyNSw0OS45Mzc1IGwgMzQuMDMxMjUsODguNjg3NSBjIDM5LjI5MDg1LC0xNS4wODIzNCA3MC4zMjM5LC00Ni4xMTU0IDg1LjQwNjI1LC04NS40MDYyNSAyOS4zOTEyOSwtNzYuNTY2OTMgLTguODM5MzIsLTE2Mi40ODM3MSAtODUuNDA2MjUsLTE5MS44NzUgLTE3Ljk0NTM3LC02Ljg4ODU5IC0zNi40MDg1MywtMTAuMDcwODcgLTU0LjUzMTI1LC05LjkwNjI1IHoiIGlkPSJwYXRoMjgzMCIgc3R5bGU9ImZpbGw6IzQwYWE1NDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6IzIwNTUyYTtzdHJva2Utd2lkdGg6Ny45OTk5OTk1MjtzdHJva2UtbWl0ZXJsaW1pdDo0O3N0cm9rZS1vcGFjaXR5OjE7c3Ryb2tlLWRhc2hhcnJheTpub25lIiAvPjwvZz48L3N2Zz4=" /></div>
</body>
</html>

View File

@ -128,5 +128,6 @@
</script>
</div>
<div class="hidden">Hidden<div style="opacity: 0.5">With opacity</div></div>
</body>
</html>

View File

@ -3,7 +3,8 @@
<head lang="en">
<meta charset="UTF-8">
<title>fontawesome icons</title>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.13.0/css/v4-shims.css" rel="stylesheet">
<script type="text/javascript" src="../../test.js"></script>
<style>
body {

View File

@ -0,0 +1,41 @@
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>z-index20</title>
<style>
.container {
width: 375px;
height: 603px;
background-color: #999;
position: relative;
margin-bottom: 30px;
}
.child1 {
height: 500px;
width: 200px;
background-color: red;
z-index: 20;
position: absolute;
left: 0;
top: 0;
}
.child2 {
height: 50px;
width: 100px;
background-color: blue;
z-index: 20;
position: absolute;
left: 30px;
top: 30px;
}
</style>
<script type="text/javascript" src="../../test.js"></script>
</head>
<body>
<div class="container" id="___id___">
<div class="child1"></div>
<div class="child2"></div>
</div>
</body>
</html>

View File

@ -1,8 +1,8 @@
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import typescript from 'rollup-plugin-typescript2';
import json from 'rollup-plugin-json';
import typescript from '@rollup/plugin-typescript';
import json from '@rollup/plugin-json';
import {resolve} from 'path';
const pkg = require('../package.json');
@ -36,14 +36,12 @@ export default {
// Allow json resolution
json(),
// Compile TypeScript files
typescript({useTsconfigDeclarationDir: true, tsconfig: resolve(__dirname, 'tsconfig.json')}),
typescript({
tsconfig: resolve(__dirname, 'tsconfig.json')
}),
// Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
commonjs({
include: 'node_modules/**',
namedModules: {
'node_modules/platform/platform.js': ['name', 'version'],
'node_modules/es6-promise/dist/es6-promise.js': ['Promise']
}
include: 'node_modules/**'
}),
// Resolve source maps to the original source

View File

@ -1,24 +0,0 @@
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const serveIndex = require('serve-index');
const proxy = require('html2canvas-proxy');
const PORT = 8080;
const CORS_PORT = 8081;
const app = express();
app.use('/', serveIndex(path.resolve(__dirname, '../'), {icons: true}));
app.use('/', express.static(path.resolve(__dirname, '../')));
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
const corsApp = express();
corsApp.use('/proxy', proxy());
corsApp.use('/cors', cors(), express.static(path.resolve(__dirname, '../')));
corsApp.use('/', express.static(path.resolve(__dirname, '.')));
corsApp.listen(CORS_PORT, () => {
console.log(`CORS server running on port ${CORS_PORT}`);
});

93
tests/server.ts Normal file
View File

@ -0,0 +1,93 @@
import * as express from 'express';
const cors = require('cors');
const path = require('path');
const serveIndex = require('serve-index');
const proxy = require('html2canvas-proxy');
import yargs from 'yargs';
import {ScreenshotRequest} from './types';
const fs = require('fs');
const bodyParser = require('body-parser');
const filenamifyUrl = require('filenamify-url');
const mkdirp = require('mkdirp');
export const app = express();
app.use('/', serveIndex(path.resolve(__dirname, '../'), {icons: true}));
app.use('/', express.static(path.resolve(__dirname, '../')));
export const corsApp = express();
corsApp.use('/proxy', proxy());
corsApp.use('/cors', cors(), express.static(path.resolve(__dirname, '../')));
corsApp.use('/', express.static(path.resolve(__dirname, '.')));
export const screenshotApp = express();
screenshotApp.use(cors());
screenshotApp.use((req: express.Request, _res: express.Response, next: express.NextFunction) => {
// IE9 doesn't set headers for cross-domain ajax requests
if (typeof req.headers['content-type'] === 'undefined') {
req.headers['content-type'] = 'application/json';
}
next();
});
screenshotApp.use(
bodyParser.json({
limit: '15mb',
type: '*/*'
})
);
const prefix = 'data:image/png;base64,';
const screenshotFolder = '../tmp/reftests';
const metadataFolder = '../tmp/reftests/metadata';
mkdirp.sync(path.resolve(__dirname, screenshotFolder));
mkdirp.sync(path.resolve(__dirname, metadataFolder));
const writeScreenshot = (buffer: Buffer, body: ScreenshotRequest) => {
const filename = `${filenamifyUrl(body.test.replace(/^\/tests\/reftests\//, '').replace(/\.html$/, ''), {
replacement: '-'
})}!${[process.env.TARGET_BROWSER, body.platform.name, body.platform.version].join('-')}`;
fs.writeFileSync(path.resolve(__dirname, screenshotFolder, `${filename}.png`), buffer);
return filename;
};
screenshotApp.post('/screenshot', (req: express.Request<{}, void, ScreenshotRequest>, res: express.Response) => {
if (!req.body || !req.body.screenshot) {
return res.sendStatus(400);
}
const buffer = Buffer.from(req.body.screenshot.substring(prefix.length), 'base64');
const filename = writeScreenshot(buffer, req.body);
fs.writeFileSync(
path.resolve(__dirname, metadataFolder, `${filename}.json`),
JSON.stringify({
windowWidth: req.body.windowWidth,
windowHeight: req.body.windowHeight,
platform: req.body.platform,
devicePixelRatio: req.body.devicePixelRatio,
test: req.body.test,
id: process.env.TARGET_BROWSER,
screenshot: filename
})
);
return res.sendStatus(200);
});
screenshotApp.use((error: Error, _req: express.Request, _res: express.Response, next: express.NextFunction) => {
console.error(error);
next();
});
const args = yargs(process.argv.slice(2)).number(['port', 'cors']).argv;
if (args.port) {
app.listen(args.port, () => {
console.log(`Server running on port ${args.port}`);
});
}
if (args.cors) {
corsApp.listen(args.cors, () => {
console.log(`CORS server running on port ${args.cors}`);
});
}

View File

@ -24,6 +24,10 @@ var REFTEST = window.location.search.indexOf('reftest') !== -1;
])
.forEach(appendScript);
window.addEventListener("unhandledrejection", function(event) {
console.info('UNHANDLED PROMISE REJECTION:', event);
});
window.onload = function() {
(function($) {
$.fn.html2canvas = function(options) {

View File

@ -3,7 +3,10 @@ import {testList, ignoredTests} from '../build/reftests';
import {default as platform} from 'platform';
// @ts-ignore
import Promise from 'es6-promise';
import {ScreenshotRequest} from './types';
// @ts-ignore
window.Promise = Promise;
const testRunnerUrl = location.href;
const hasHistoryApi = typeof window.history !== 'undefined' && typeof window.history.replaceState !== 'undefined';
@ -21,29 +24,29 @@ const uploadResults = (canvas: HTMLCanvasElement, url: string) => {
};
xhr.onerror = reject;
const request: ScreenshotRequest = {
screenshot: canvas.toDataURL(),
test: url,
platform: {
name: platform.name,
version: platform.version
},
devicePixelRatio: window.devicePixelRatio || 1,
windowWidth: window.innerWidth,
windowHeight: window.innerHeight
};
xhr.open('POST', 'http://localhost:8000/screenshot', true);
xhr.send(
JSON.stringify({
screenshot: canvas.toDataURL(),
test: url,
platform: {
name: platform.name,
version: platform.version
},
devicePixelRatio: window.devicePixelRatio || 1,
windowWidth: window.innerWidth,
windowHeight: window.innerHeight
})
);
xhr.send(JSON.stringify(request));
});
};
testList
.filter(test => {
.filter((test) => {
return !Array.isArray(ignoredTests[test]) || ignoredTests[test].indexOf(platform.name || '') === -1;
})
.forEach(url => {
describe(url, function() {
.forEach((url) => {
describe(url, function () {
this.timeout(60000);
this.retries(2);
const windowWidth = 800;
@ -55,7 +58,7 @@ testList
testContainer.style.position = 'fixed';
testContainer.style.left = '10000px';
before(done => {
before((done) => {
testContainer.onload = () => done();
testContainer.src = url + '?selenium&run=false&reftest&' + Math.random();
@ -76,40 +79,43 @@ testList
}
document.body.removeChild(testContainer);
});
it('Should render untainted canvas', () => {
it('Should render untainted canvas', async () => {
const contentWindow = testContainer.contentWindow;
if (!contentWindow) {
throw new Error('Window not found for iframe');
}
return (
contentWindow
// @ts-ignore
.html2canvas(contentWindow.forceElement || contentWindow.document.documentElement, {
removeContainer: true,
backgroundColor: '#ffffff',
proxy: 'http://localhost:8081/proxy',
// @ts-ignore
...(contentWindow.h2cOptions || {})
})
.then((canvas: HTMLCanvasElement) => {
try {
(canvas.getContext('2d') as CanvasRenderingContext2D).getImageData(
0,
0,
canvas.width,
canvas.height
);
} catch (e) {
return Promise.reject('Canvas is tainted');
}
contentWindow.addEventListener('unhandledrejection', (event) => {
console.error(event.reason);
throw new Error(`unhandledrejection: ${JSON.stringify(event.reason)}`);
});
// @ts-ignore
if (window.__karma__) {
return uploadResults(canvas, url);
}
})
);
const canvas: HTMLCanvasElement = await contentWindow
// @ts-ignore
.html2canvas(contentWindow.forceElement || contentWindow.document.documentElement, {
removeContainer: true,
backgroundColor: '#ffffff',
proxy: 'http://localhost:8081/proxy',
// @ts-ignore
...(contentWindow.h2cOptions || {})
});
try {
(canvas.getContext('2d') as CanvasRenderingContext2D).getImageData(
0,
0,
canvas.width,
canvas.height
);
} catch (e) {
throw new Error('Canvas is tainted');
}
// @ts-ignore
if (window.__karma__) {
return uploadResults(canvas, url);
}
});
});
});

View File

@ -1,6 +1,9 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"types": ["node", "mocha"]
}
"types": ["node", "mocha"],
"rootDir": "../",
"declaration": false
},
"include": ["**/*.ts"]
}

13
tests/types.ts Normal file
View File

@ -0,0 +1,13 @@
export interface PlatformDetails {
name: string;
version: string;
}
export interface ScreenshotRequest {
screenshot: string;
test: string;
platform: PlatformDetails;
devicePixelRatio: number;
windowWidth: number;
windowHeight: number;
}

View File

@ -6,14 +6,14 @@
"noUnusedParameters": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
"resolveJsonModule": true,
"types": ["node", "jest"],
"target": "es5",
"lib": ["es2015", "dom"],
"sourceMap": true,
"outDir": "dist/lib",
"declaration": true,
"declarationDir": "dist/types"
"declarationDir": "dist/types",
"resolveJsonModule": true
},
"include": [
"src"

37840
www/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -19,7 +19,7 @@
"gatsby-transformer-remark": "^2.3.8",
"glamor": "^2.20.40",
"gzip-size": "^5.0.0",
"html2canvas": "^1.0.0-alpha.12",
"html2canvas": "file:../",
"mkdirp": "^0.5.1",
"prismjs": "^1.16.0",
"react": "^16.8.6",

View File

@ -62,7 +62,7 @@ const DOWN_ARROW = 40;
const LEFT_ARROW = 37;
const RIGHT_ARROW = 39;
window.addEventListener('keydown', e => {
window.addEventListener('keydown', (e) => {
if (testSelector && browserSelector) {
if (e.keyCode === UP_ARROW) {
testSelector.selectedIndex = Math.max(0, testSelector.selectedIndex - 1);
@ -103,7 +103,7 @@ if (testSelector && browserSelector) {
browserSelector.addEventListener(
'change',
() => {
testList[testSelector.value].some(browser => {
testList[testSelector.value].some((browser) => {
if (browser.id === browserSelector.value) {
if (browser) {
onBrowserChange(browser);