Compare commits

...

83 Commits

Author SHA1 Message Date
6020386bbe examples: fix duplication (#2813) 2022-01-23 00:27:44 +08:00
f7c2289db1 Update CHANGELOG.md 2022-01-23 00:24:05 +08:00
CI
7c3269bdbe chore(release): 1.4.1 2022-01-22 16:19:57 +00:00
e587a82dca fix: Properties x and y of BoundingRect is undefined in old browser (#2797) 2022-01-23 00:18:49 +08:00
67c5e8dec4 deps: fix source maps (#2812) 2022-01-23 00:17:25 +08:00
181d1b1103 feat: add support for <video> elements (#2788) 2022-01-02 16:14:27 +08:00
46db86755f fix: source maps (#2787) 2022-01-02 16:08:10 +08:00
CI
9fda3e1ede chore(release): 1.4.0 2022-01-01 15:08:48 +00:00
6521a487d7 feat: use native text segmenter where available (#2782) 2022-01-01 21:22:31 +08:00
0476d06515 fix: ios text wrapping with 0 width rect (#2786) 2022-01-01 13:07:52 +08:00
74696faf47 fix: adopted stylesheets (#2785) 2022-01-01 01:57:17 +08:00
1cc853a318 fix: reduce SLICE_STACK_SIZE to 50k (#2784) 2021-12-31 15:30:18 +08:00
CI
04787ee88a chore(release): 1.3.4 2021-12-29 14:11:55 +00:00
ba2b1cd8e9 fix: ios 15 font rendering crash (#2645) 2021-12-29 22:09:32 +08:00
d9222075da ci: add ios 15.0 testing (#2780) 2021-12-29 21:02:16 +08:00
CI
101c32ed71 chore(release): 1.3.3 2021-11-23 10:09:40 +00:00
ddffaecf6d add missing changelog entries for 1.0.0 (#2758) 2021-11-23 17:47:45 +08:00
fd22a01a3c fix: "offsets" text when font is big 2021-11-23 17:32:41 +08:00
ed57781594 ci: fix macos action runners (#2757) 2021-11-23 17:17:51 +08:00
eeda86bd5e fix: const enums (#2651) 2021-08-16 19:30:33 +08:00
CI
0b1f0a7e90 chore(release): 1.3.2 2021-08-15 12:54:26 +00:00
38c682955a fix: overflows with absolutely positioned content (#2663) 2021-08-15 19:41:57 +08:00
01ed87907a docs: add warning for webgl cloning with preserveDrawingBuffer=false (#2661) 2021-08-14 17:18:30 +08:00
58ff0003f7 docs: include src files on www (#2660) 2021-08-14 16:48:22 +08:00
f143166551 fix: disable transition properties (#2659) 2021-08-14 16:22:36 +08:00
cd0d7258c3 feat: add support for data-html2canvas-debug property for debugging (#2658) 2021-08-14 15:01:41 +08:00
CI
b482725994 chore(release): 1.3.1 2021-08-14 06:06:09 +00:00
1b55ed5668 fix: multi arg transition/animation duration (#2657) 2021-08-14 14:05:15 +08:00
CI
68377b3244 chore(release): 1.3.0 2021-08-13 11:52:05 +00:00
6947982848 feat: add rtl render support (#2653) 2021-08-13 19:50:59 +08:00
437b367d3b feat: correctly break graphemes (#2652) 2021-08-13 18:57:49 +08:00
969638fb94 fix: finish animation/transitions for elements (#2632) 2021-08-13 18:15:55 +08:00
f919204efa test: add letter-spacing test for zwj emoji (#2650) 2021-08-13 17:45:42 +08:00
c378e22069 fix: correctly handle allowTaint canvas cloning (#2649) 2021-08-13 17:32:55 +08:00
CI
2b4de68e92 chore(release): 1.2.2 2021-08-10 10:39:01 +00:00
1941b9e0ac fix: parsing counter content in pseudo element (#2640) 2021-08-09 18:43:42 +08:00
e429e0443a ci: add ios15 target (#2564) 2021-08-09 17:15:00 +08:00
f43f942fcd fix: test for ios range line break error (#2635) 2021-08-09 17:14:40 +08:00
7a06d0c2c2 docs: update test previewer (#2637) 2021-08-07 18:05:08 +08:00
e36408ad03 test: large base64 encoded background (#2636) 2021-08-07 15:47:15 +08:00
a0dd38a8be fix: radial gradient ry check (#2631) 2021-08-05 14:07:10 +08:00
CI
b988d9d657 chore(release): 1.2.1 2021-08-05 02:39:44 +00:00
c5c6fa00d7 fix: type import that is only available ts 3.8 or higher (#2629) 2021-08-05 10:17:30 +08:00
6651fc6789 fix: none image (#2627) 2021-08-05 09:30:22 +08:00
CI
df223c3ff2 chore(release): 1.2.0 2021-08-04 15:00:38 +00:00
95a46b00c5 fix: overflow-wrap break-word (#2626) 2021-08-04 22:53:48 +08:00
878e37a242 fix: element cropping & scrolling (#2625) 2021-08-04 20:58:17 +08:00
1338c7b203 test: element with scrolled window (#2624) 2021-08-04 11:28:05 +08:00
CI
f284752295 chore(release): 1.1.5 2021-08-02 10:38:51 +00:00
96e23d1851 fix: natural sizes for images with srcset (#2622) 2021-08-02 18:27:03 +08:00
7d788c6f3d fix: emoji line breaking (fix #1813) (#2621)
* fix: emoji line breaking (fix #1813)

* test: fix text.html reftest
2021-08-02 17:49:46 +08:00
5dea36bd69 docs: update README to github discussion Q/A 2021-07-17 17:24:15 +08:00
CI
11d16d2b77 chore(release): 1.1.4 2021-07-15 16:44:42 +00:00
e9f7f48d57 fix: word-break seperators (#2593) 2021-07-15 21:05:26 +08:00
4c360fc1f0 test: refactor language tests (#2594) 2021-07-15 20:58:04 +08:00
578bb771bf test: update box-shadow with radius 2021-07-15 18:24:39 +08:00
522e5aac5f feat: add support for webkit-text-stroke and paint-order (#2591) 2021-07-15 18:19:26 +08:00
dd6d8856ec fix: svg d path getting truncated on copy (#2589) 2021-07-15 17:15:47 +08:00
45efe54da8 fix: this.canvas.ownerDocument is undefined (#2590) 2021-07-15 17:08:43 +08:00
cd99f11b1b fix: text position for form elements and list markers (#2588) 2021-07-15 16:54:01 +08:00
fa60716d07 fix: don't copy 'all' css property (#2586) 2021-07-14 22:49:52 +08:00
CI
99b687c412 chore(release): 1.1.3 2021-07-14 13:08:25 +00:00
1d00bfe175 test: add test cases for text-stroke and textarea from (#1540 and #2132) (#2585) 2021-07-14 21:07:39 +08:00
58b4591174 feat: allow access to reference element in onclone (#2584) 2021-07-14 21:07:10 +08:00
92fa448913 fix: responsive svg images (#2583) 2021-07-14 20:44:04 +08:00
1acdc827a4 fix: image blob rendering 2021-07-14 20:21:57 +08:00
acb4cd24b8 feat: support for custom and slot elements (#2581) 2021-07-14 17:59:08 +08:00
eeb5a3ea1d fix: iframe load to ensure images are loaded (#2577) 2021-07-14 16:18:43 +08:00
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
158 changed files with 18103 additions and 14252 deletions

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",

View File

@ -43,16 +43,19 @@ jobs:
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
@ -98,18 +101,26 @@ jobs:
- os: macos-latest
name: OSX Safari Stable
targetBrowser: Safari_Stable
- os: macos-latest
- os: macos-10.15
name: iOS Simulator Safari 12
targetBrowser: Safari_IOS_12
xcode: /Applications/Xcode_10.3.app
- os: macos-latest
- os: macos-10.15
name: iOS Simulator Safari 13
targetBrowser: Safari_IOS_13
xcode: /Applications/Xcode_11.6_beta.app
- os: macos-latest
xcode: /Applications/Xcode_11.7.app
- os: macos-10.15
name: iOS Simulator Safari 14
targetBrowser: Safari_IOS_14
xcode: /Applications/Xcode_12_beta.app
xcode: /Applications/Xcode_12.4.app
- os: macos-11
name: iOS Simulator Safari 15.0
targetBrowser: Safari_IOS_15_0
xcode: /Applications/Xcode_13.0.app
- os: macos-11
name: iOS Simulator Safari 15
targetBrowser: Safari_IOS_15
xcode: /Applications/Xcode_13.2.app
- os: windows-latest
name: Windows Internet Explorer 9 (Emulated)
targetBrowser: IE_9
@ -170,6 +181,7 @@ jobs:
with:
name: reftest-results
path: tmp/reftests
if-no-files-found: error
publish:
runs-on: ubuntu-latest
name: Publish
@ -282,6 +294,7 @@ jobs:
with:
name: docs
path: www/public
if-no-files-found: error
publish-docs:
runs-on: ubuntu-latest
name: Publish Docs
@ -304,3 +317,43 @@ jobs:
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

View File

@ -2,6 +2,264 @@
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.4.1](https://github.com/niklasvh/html2canvas/compare/v1.4.0...v1.4.1) (2022-01-22)
### deps
* fix source maps (#2812) ([67c5e8d](https://github.com/niklasvh/html2canvas/commit/67c5e8dec4b2af9260a2b5b75b3399495fd1fee9)), closes [#2812](https://github.com/niklasvh/html2canvas/issues/2812)
### feat
* add support for `<video>` elements (#2788) ([181d1b1](https://github.com/niklasvh/html2canvas/commit/181d1b1103910d6e1b5277d5c007fc5e3006c6bf)), closes [#2788](https://github.com/niklasvh/html2canvas/issues/2788)
### fix
* Properties x and y of BoundingRect is undefined in old browser (#2797) ([e587a82](https://github.com/niklasvh/html2canvas/commit/e587a82dca01d9ada78cae34fd1bdb934e547f9b)), closes [#2797](https://github.com/niklasvh/html2canvas/issues/2797)
* source maps (#2787) ([46db867](https://github.com/niklasvh/html2canvas/commit/46db86755f064828559a4b0b37310f3ae94f5494)), closes [#2787](https://github.com/niklasvh/html2canvas/issues/2787)
# [1.4.0](https://github.com/niklasvh/html2canvas/compare/v1.3.4...v1.4.0) (2022-01-01)
### feat
* use native text segmenter where available (#2782) ([6521a48](https://github.com/niklasvh/html2canvas/commit/6521a487d78172f7179f7c973c1a3af40eb92009)), closes [#2782](https://github.com/niklasvh/html2canvas/issues/2782)
### fix
* adopted stylesheets (#2785) ([74696fa](https://github.com/niklasvh/html2canvas/commit/74696faf47c07b48b9c9587db0b999da1c08a8be)), closes [#2785](https://github.com/niklasvh/html2canvas/issues/2785)
* ios text wrapping with 0 width rect (#2786) ([0476d06](https://github.com/niklasvh/html2canvas/commit/0476d065158c33d2020a9f602b3043e5e2f90c75)), closes [#2786](https://github.com/niklasvh/html2canvas/issues/2786)
* reduce SLICE_STACK_SIZE to 50k (#2784) ([1cc853a](https://github.com/niklasvh/html2canvas/commit/1cc853a3186853eaca00af060f651697dc3497a9)), closes [#2784](https://github.com/niklasvh/html2canvas/issues/2784)
## [1.3.4](https://github.com/niklasvh/html2canvas/compare/v1.3.3...v1.3.4) (2021-12-29)
### ci
* add ios 15.0 testing (#2780) ([d922207](https://github.com/niklasvh/html2canvas/commit/d9222075daaed08884491b0563fc899ee0ced731)), closes [#2780](https://github.com/niklasvh/html2canvas/issues/2780)
### fix
* ios 15 font rendering crash (#2645) ([ba2b1cd](https://github.com/niklasvh/html2canvas/commit/ba2b1cd8e9a9d7932675d7abffce1526a609e769)), closes [#2645](https://github.com/niklasvh/html2canvas/issues/2645)
## [1.3.3](https://github.com/niklasvh/html2canvas/compare/v1.3.2...v1.3.3) (2021-11-23)
### ci
* fix macos action runners (#2757) ([ed57781](https://github.com/niklasvh/html2canvas/commit/ed577815949b6a565df54f2101cf6f0fb731c290)), closes [#2757](https://github.com/niklasvh/html2canvas/issues/2757)
### fix
* "offsets" text when font is big ([fd22a01](https://github.com/niklasvh/html2canvas/commit/fd22a01a3c9e39293f47caaed0c0e13d2dc8170c))
* const enums (#2651) ([eeda86b](https://github.com/niklasvh/html2canvas/commit/eeda86bd5e81fb4e97675fe9bee3d4d15899997f)), closes [#2651](https://github.com/niklasvh/html2canvas/issues/2651)
## [1.3.2](https://github.com/niklasvh/html2canvas/compare/v1.3.1...v1.3.2) (2021-08-15)
### docs
* add warning for webgl cloning with preserveDrawingBuffer=false (#2661) ([01ed879](https://github.com/niklasvh/html2canvas/commit/01ed87907ad9c7688880e2c5cb8ebc22ef73a4d8)), closes [#2661](https://github.com/niklasvh/html2canvas/issues/2661)
* include src files on www (#2660) ([58ff000](https://github.com/niklasvh/html2canvas/commit/58ff0003f77d825ac027eeec95fa80c0123eaf8f)), closes [#2660](https://github.com/niklasvh/html2canvas/issues/2660)
### feat
* add support for data-html2canvas-debug property for debugging (#2658) ([cd0d725](https://github.com/niklasvh/html2canvas/commit/cd0d7258c3a93f2989d5d9ec0244ba2763ea2d23)), closes [#2658](https://github.com/niklasvh/html2canvas/issues/2658)
### fix
* disable transition properties (#2659) ([f143166](https://github.com/niklasvh/html2canvas/commit/f1431665513e0a4636fb167a241f4a0571ba728a)), closes [#2659](https://github.com/niklasvh/html2canvas/issues/2659)
* overflows with absolutely positioned content (#2663) ([38c6829](https://github.com/niklasvh/html2canvas/commit/38c682955a9299ca7785af71d8f251df799405b0)), closes [#2663](https://github.com/niklasvh/html2canvas/issues/2663)
## [1.3.1](https://github.com/niklasvh/html2canvas/compare/v1.3.0...v1.3.1) (2021-08-14)
### fix
* multi arg transition/animation duration (#2657) ([1b55ed5](https://github.com/niklasvh/html2canvas/commit/1b55ed5668dcbbe1c6d8d7e94736d8f2da2d31c5)), closes [#2657](https://github.com/niklasvh/html2canvas/issues/2657)
# [1.3.0](https://github.com/niklasvh/html2canvas/compare/v1.2.2...v1.3.0) (2021-08-13)
### feat
* add rtl render support (#2653) ([6947982](https://github.com/niklasvh/html2canvas/commit/694798284838b16882e648914da0905818aa366c)), closes [#2653](https://github.com/niklasvh/html2canvas/issues/2653)
* correctly break graphemes (#2652) ([437b367](https://github.com/niklasvh/html2canvas/commit/437b367d3ba9dfd7f9a4c8042ac8d00208c09770)), closes [#2652](https://github.com/niklasvh/html2canvas/issues/2652)
### fix
* correctly handle allowTaint canvas cloning (#2649) ([c378e22](https://github.com/niklasvh/html2canvas/commit/c378e220694c14cb7b3b4b8650a7757f8fc23c7a)), closes [#2649](https://github.com/niklasvh/html2canvas/issues/2649)
* finish animation/transitions for elements (#2632) ([969638f](https://github.com/niklasvh/html2canvas/commit/969638fb94a0a14c64a667fa6e5689f79d9f1044)), closes [#2632](https://github.com/niklasvh/html2canvas/issues/2632)
### test
* add letter-spacing test for zwj emoji (#2650) ([f919204](https://github.com/niklasvh/html2canvas/commit/f919204efa06af219f155ca279f96124bb92862b)), closes [#2650](https://github.com/niklasvh/html2canvas/issues/2650)
## [1.2.2](https://github.com/niklasvh/html2canvas/compare/v1.2.1...v1.2.2) (2021-08-10)
### ci
* add ios15 target (#2564) ([e429e04](https://github.com/niklasvh/html2canvas/commit/e429e0443adf5c7ca3041b97a8157b8911302206)), closes [#2564](https://github.com/niklasvh/html2canvas/issues/2564)
### docs
* update test previewer (#2637) ([7a06d0c](https://github.com/niklasvh/html2canvas/commit/7a06d0c2c2f3b8a1d1a8a85c540f8288b782e8c6)), closes [#2637](https://github.com/niklasvh/html2canvas/issues/2637)
### fix
* parsing counter content in pseudo element (#2640) ([1941b9e](https://github.com/niklasvh/html2canvas/commit/1941b9e0acfd9243da0beaf70e1643cab1b4a963)), closes [#2640](https://github.com/niklasvh/html2canvas/issues/2640)
* radial gradient ry check (#2631) ([a0dd38a](https://github.com/niklasvh/html2canvas/commit/a0dd38a8be4e540ae1c1f4b4e41f6c386f3e454f)), closes [#2631](https://github.com/niklasvh/html2canvas/issues/2631)
* test for ios range line break error (#2635) ([f43f942](https://github.com/niklasvh/html2canvas/commit/f43f942fcd793dde9cdc6c0438f379ec3c05c405)), closes [#2635](https://github.com/niklasvh/html2canvas/issues/2635)
### test
* large base64 encoded background (#2636) ([e36408a](https://github.com/niklasvh/html2canvas/commit/e36408ad030fe31acd9969a37fe24c1621c0bd04)), closes [#2636](https://github.com/niklasvh/html2canvas/issues/2636)
## [1.2.1](https://github.com/niklasvh/html2canvas/compare/v1.2.0...v1.2.1) (2021-08-05)
### fix
* none image (#2627) ([6651fc6](https://github.com/niklasvh/html2canvas/commit/6651fc6789d5902d171dc53b4094887870433018)), closes [#2627](https://github.com/niklasvh/html2canvas/issues/2627)
* type import that is only available ts 3.8 or higher (#2629) ([c5c6fa0](https://github.com/niklasvh/html2canvas/commit/c5c6fa00d71f36ef963ba5170ebc7b668d39c407)), closes [#2629](https://github.com/niklasvh/html2canvas/issues/2629)
# [1.2.0](https://github.com/niklasvh/html2canvas/compare/v1.1.5...v1.2.0) (2021-08-04)
### fix
* element cropping & scrolling (#2625) ([878e37a](https://github.com/niklasvh/html2canvas/commit/878e37a24272d0412fe589975ef8eed931c56e0b)), closes [#2625](https://github.com/niklasvh/html2canvas/issues/2625)
* overflow-wrap break-word (#2626) ([95a46b0](https://github.com/niklasvh/html2canvas/commit/95a46b00c53563722c035a0e45fdf5fb507275e4)), closes [#2626](https://github.com/niklasvh/html2canvas/issues/2626)
### test
* element with scrolled window (#2624) ([1338c7b](https://github.com/niklasvh/html2canvas/commit/1338c7b203535d53509416358d74014200a994eb)), closes [#2624](https://github.com/niklasvh/html2canvas/issues/2624)
## [1.1.5](https://github.com/niklasvh/html2canvas/compare/v1.1.4...v1.1.5) (2021-08-02)
### docs
* update README to github discussion Q/A ([5dea36b](https://github.com/niklasvh/html2canvas/commit/5dea36bd6964164e8ba3f8780309e792f5d16255))
### fix
* emoji line breaking (fix #1813) (#2621) ([7d788c6](https://github.com/niklasvh/html2canvas/commit/7d788c6f3d221b87f6b59fcda8517731340b2d1f)), closes [#1813](https://github.com/niklasvh/html2canvas/issues/1813) [#2621](https://github.com/niklasvh/html2canvas/issues/2621) [#1813](https://github.com/niklasvh/html2canvas/issues/1813)
* natural sizes for images with srcset (#2622) ([96e23d1](https://github.com/niklasvh/html2canvas/commit/96e23d185198b7131cf0cfa31c14c165790464e9)), closes [#2622](https://github.com/niklasvh/html2canvas/issues/2622)
## [1.1.4](https://github.com/niklasvh/html2canvas/compare/v1.1.3...v1.1.4) (2021-07-15)
### feat
* add support for webkit-text-stroke and paint-order (#2591) ([522e5aa](https://github.com/niklasvh/html2canvas/commit/522e5aac5fdad090953d095b5d558053a5e2d43d)), closes [#2591](https://github.com/niklasvh/html2canvas/issues/2591)
### fix
* don't copy 'all' css property (#2586) ([fa60716](https://github.com/niklasvh/html2canvas/commit/fa60716d07ed590ec64543a586a7960cbc8557df)), closes [#2586](https://github.com/niklasvh/html2canvas/issues/2586)
* svg d path getting truncated on copy (#2589) ([dd6d885](https://github.com/niklasvh/html2canvas/commit/dd6d8856eca820a13a0990c467b9e531433fd4a9)), closes [#2589](https://github.com/niklasvh/html2canvas/issues/2589)
* text position for form elements and list markers (#2588) ([cd99f11](https://github.com/niklasvh/html2canvas/commit/cd99f11b1b9eb1260a548a63e2a370a0a5ddafa0)), closes [#2588](https://github.com/niklasvh/html2canvas/issues/2588)
* this.canvas.ownerDocument is undefined (#2590) ([45efe54](https://github.com/niklasvh/html2canvas/commit/45efe54da8145f97b9ee0463e686103280e3c8b1)), closes [#2590](https://github.com/niklasvh/html2canvas/issues/2590)
* word-break seperators (#2593) ([e9f7f48](https://github.com/niklasvh/html2canvas/commit/e9f7f48d571304be14610a181feedca3c3b42864)), closes [#2593](https://github.com/niklasvh/html2canvas/issues/2593)
### test
* refactor language tests (#2594) ([4c360fc](https://github.com/niklasvh/html2canvas/commit/4c360fc1f059f4dcab71a79f9dc8a5b2e25411ea)), closes [#2594](https://github.com/niklasvh/html2canvas/issues/2594)
* update box-shadow with radius ([578bb77](https://github.com/niklasvh/html2canvas/commit/578bb771bfeb7e81362e9e355d6cc9ae910e3920))
## [1.1.3](https://github.com/niklasvh/html2canvas/compare/v1.1.2...v1.1.3) (2021-07-14)
### feat
* allow access to reference element in onclone (#2584) ([58b4591](https://github.com/niklasvh/html2canvas/commit/58b45911741c0dbbccd462b2976560bb3999eaef)), closes [#2584](https://github.com/niklasvh/html2canvas/issues/2584)
* support for custom and slot elements (#2581) ([acb4cd2](https://github.com/niklasvh/html2canvas/commit/acb4cd24b85527908c02a60794768949578678f0)), closes [#2581](https://github.com/niklasvh/html2canvas/issues/2581)
### fix
* iframe load to ensure images are loaded (#2577) ([eeb5a3e](https://github.com/niklasvh/html2canvas/commit/eeb5a3ea1d6c94e0f6dcfd40695eb88ebb3e0041)), closes [#2577](https://github.com/niklasvh/html2canvas/issues/2577)
* image blob rendering ([1acdc82](https://github.com/niklasvh/html2canvas/commit/1acdc827a4e05933c2f7c9558405c66b7cd82f58))
* responsive svg images (#2583) ([92fa448](https://github.com/niklasvh/html2canvas/commit/92fa448913192d5e4e82bfe14f6644b669d4e6ef)), closes [#2583](https://github.com/niklasvh/html2canvas/issues/2583)
### test
* add test cases for text-stroke and textarea from (#1540 and #2132) (#2585) ([1d00bfe](https://github.com/niklasvh/html2canvas/commit/1d00bfe175d51e663d0bae88b6dbd10a266a71f1)), closes [#1540](https://github.com/niklasvh/html2canvas/issues/1540) [#2132](https://github.com/niklasvh/html2canvas/issues/2132) [#2585](https://github.com/niklasvh/html2canvas/issues/2585)
## [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)
@ -13,9 +271,14 @@ All notable changes to this project will be documented in this file. See [standa
* update www deps (#2525) ([2a013e2](https://github.com/niklasvh/html2canvas/commit/2a013e20c814b7dbaea98f54f0bde8f553eb79a2)), closes [#2525](https://github.com/niklasvh/html2canvas/issues/2525)
### feat
* add support for border-style dashed, dotted, double (#2531) ([72cd528](https://github.com/niklasvh/html2canvas/commit/72cd5284296e4cdb3fe88f2982ec7528604b6618))
### fix
* opacity with overflow hidden (#2450) ([82b7da5](https://github.com/niklasvh/html2canvas/commit/82b7da558c342e7f53d298bb1d843a5db86c3b21)), closes [#2450](https://github.com/niklasvh/html2canvas/issues/2450)
* top right border radius (#2522) ([ba17267](https://github.com/niklasvh/html2canvas/commit/ba172678f07f962e9f54b398df087e86217d7a13))
### test
@ -163,16 +426,16 @@ All notable changes to this project will be documented in this file. See [standa
* Fix white space appearing on element rendering (Fix #1438)
* Reset canvas transform on finish (Fix #1494)
# v1.0.0-alpha.11 - 1.4.2018
* Fix IE11 member not found error
# v1.0.0-alpha.11 - 1.4.2018
* Fix IE11 member not found error
* Support blob image resources in non-foreignObjectRendering mode
# v1.0.0-alpha.10 - 15.2.2018
# v1.0.0-alpha.10 - 15.2.2018
* Re-introduce `onclone` option (Fix #1434)
* Add `ignoreElements` predicate function option
* Fix version console logging
# v1.0.0-alpha.9 - 7.1.2018
# v1.0.0-alpha.9 - 7.1.2018
* Fix dynamic style sheets
* Fix > 50% border-radius values
@ -184,7 +447,7 @@ All notable changes to this project will be documented in this file. See [standa
* Fix form input rendering (#1338)
* Improve word line breaking algorithm
# v1.0.0-alpha.6 - 28.12.2017
# v1.0.0-alpha.6 - 28.12.2017
* Fix list-style: none (#1340)
* Extend supported values for pseudo element content
@ -194,7 +457,7 @@ All notable changes to this project will be documented in this file. See [standa
* Fix overflow: auto
* Added support for rendering list-style
v1.0.0-alpha.4 - 12.12.2017
v1.0.0-alpha.4 - 12.12.2017
* Fix rendering with multiple fonts defined (Fix #796)
* Add support for radial-gradients
* Fix logging option (#1302)
@ -216,8 +479,8 @@ All notable changes to this project will be documented in this file. See [standa
##### Breaking Changes #####
* Remove deprecated onrendered callback, calling `html2canvas` returns a `Promise<HTMLCanvasElement>`
* Removed option `type`, same results can be achieved by assigning `x`, `y`, `scrollX`, `scrollY`, `width` and `height` properties.
## New featues / fixes
## New featues / fixes
* Add support for scaling canvas (defaults to device pixel ratio)
* Add support for multiple text-shadows
* Add support for multiple text-decorations
@ -226,7 +489,7 @@ All notable changes to this project will be documented in this file. See [standa
* Correctly handle px and percentage values in linear-gradients
* Correctly support all angle types for linear-gradients
* Add support for multiple values for background-repeat, background-position and background-size
# v0.5.0-beta4 - 23.1.2016
* Fix logger requiring access to window object
* Derequire browserify build
@ -246,11 +509,11 @@ All notable changes to this project will be documented in this file. See [standa
* Fix transparent colors breaking gradients
* Preserve scrolling positions on render
# v0.5.0-alpha2 - 3.2.2015
# v0.5.0-alpha2 - 3.2.2015
* Switch to using browserify for building
* Fix (#517) Chrome stretches background images with 'auto' or single attributes
# v0.5.0-alpha - 19.1.2015
# v0.5.0-alpha - 19.1.2015
* Complete rewrite of library
* Switched interface to return Promise
* Uses hidden iframe window to perform rendering, allowing async rendering and doesn't force the viewport to be scrolled to the top anymore.
@ -261,14 +524,14 @@ All notable changes to this project will be documented in this file. See [standa
* Changed format for proxy requests, permitting binary responses with CORS headers as well
* Fixed many layering issues (see z-index tests)
# v0.4.1 - 7.9.2013
# v0.4.1 - 7.9.2013
* Added support for bower
* Improved z-index ordering
* Basic implementation for CSS transformations
* Fixed inline text in top element
* Basic implementation for text-shadow
# v0.4.0 - 30.1.2013
# v0.4.0 - 30.1.2013
* Added rendering tests with <a href="https://github.com/niklasvh/webdriver.js">webdriver</a>
* Switched to using grunt for building
* Removed support for IE<9, including any FlashCanvas bits
@ -278,7 +541,7 @@ All notable changes to this project will be documented in this file. See [standa
* Support for placeholder rendering
* Reformatted all tests to small units to test specific features
# v0.3.4 - 26.6.2012
# v0.3.4 - 26.6.2012
* Removed (last?) jQuery dependencies (<a href="https://github.com/niklasvh/html2canvas/commit/343b86705fe163766fcf735eb0217130e4bd5b17">niklasvh</a>)
* SVG-powered rendering (<a href="https://github.com/niklasvh/html2canvas/commit/67d3e0d0f59a5a654caf71a2e3be6494ff146c75">niklasvh</a>)

View File

@ -1,7 +1,7 @@
html2canvas
===========
[Homepage](https://html2canvas.hertzen.com) | [Downloads](https://github.com/niklasvh/html2canvas/releases) | [Questions](http://stackoverflow.com/questions/tagged/html2canvas?sort=newest)
[Homepage](https://html2canvas.hertzen.com) | [Downloads](https://github.com/niklasvh/html2canvas/releases) | [Questions](https://github.com/niklasvh/html2canvas/discussions/categories/q-a)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/niklasvh/html2canvas?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
![CI](https://github.com/niklasvh/html2canvas/workflows/CI/badge.svg?branch=master)

View File

@ -12,13 +12,13 @@ Below is a list of all the supported CSS properties and values.
- url()
- linear-gradient()
- radial-gradient()
- background-origin
- background-origin
- background-position
- background-size
- background-size
- border
- border-color
- border-radius
- border-style (**Only supports `solid`**)
- border-style
- border-width
- bottom
- box-sizing
@ -50,6 +50,7 @@ Below is a list of all the supported CSS properties and values.
- overflow
- overflow-wrap
- padding
- paint-order
- position
- right
- text-align
@ -58,17 +59,18 @@ Below is a list of all the supported CSS properties and values.
- text-decoration-line
- text-decoration-style (**Only supports `solid`**)
- text-shadow
- text-transform
- text-transform
- top
- transform (**Limited support**)
- visibility
- white-space
- width
- webkit-text-stroke
- word-break
- word-spacing
- word-wrap
- z-index
## Unsupported CSS properties
These CSS properties are **NOT** currently supported
- [background-blend-mode](https://github.com/niklasvh/html2canvas/issues/966)

View File

@ -29,8 +29,6 @@
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
ctx.moveTo(110,75);

View File

@ -34,13 +34,25 @@ module.exports = function(config) {
base: 'MobileSafari',
name: 'iPhone 8',
platform: 'iOS',
sdk: '13.6'
sdk: '13.7'
},
Safari_IOS_14: {
base: 'MobileSafari',
name: 'iPhone 8',
platform: 'iOS',
sdk: '14.0'
sdk: '14.4'
},
Safari_IOS_15_0: {
base: 'MobileSafari',
name: 'iPhone 13',
platform: 'iOS',
sdk: '15.0'
},
Safari_IOS_15: {
base: 'MobileSafari',
name: 'iPhone 13',
platform: 'iOS',
sdk: '15.2'
},
SauceLabs_IE9: {
base: 'SauceLabs',

27869
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",
"version": "1.4.1",
"author": {
"name": "Niklas von Hertzen",
"email": "niklasvh@gmail.com",
@ -27,36 +27,42 @@
"@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.11",
"@types/express": "^4.17.13",
"@types/glob": "^7.1.1",
"@types/jest": "^24.0.18",
"@types/jest": "^26.0.24",
"@types/jest-image-snapshot": "^4.3.1",
"@types/karma": "^6.3.0",
"@types/mocha": "^5.2.6",
"@types/node": "^11.13.2",
"@types/platform": "^1.3.2",
"@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.2",
"babel-plugin-dev-expression": "^0.2.1",
"base64-arraybuffer": "0.2.0",
"body-parser": "^1.18.3",
"base64-arraybuffer": "1.0.1",
"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",
"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",
"jest": "^27.0.6",
"jest-image-snapshot": "^4.5.1",
"jquery": "^3.5.1",
"js-polyfills": "^0.1.42",
"karma": "^6.3.2",
@ -68,28 +74,25 @@
"karma-mocha": "^2.0.1",
"karma-safarinative-launcher": "^1.1.0",
"karma-sauce-launcher": "^2.0.2",
"mocha": "^6.1.4",
"mocha": "^9.0.2",
"node-simctl": "^5.3.0",
"platform": "1.3.4",
"prettier": "1.17.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": "^8.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",
"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"
},
@ -103,9 +106,10 @@
"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",
"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",
@ -114,6 +118,7 @@
"homepage": "https://html2canvas.hertzen.com",
"license": "MIT",
"dependencies": {
"css-line-break": "1.1.1"
"css-line-break": "^2.1.0",
"text-segmentation": "^1.0.3"
}
}

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({ sourceMap: true, inlineSources: true }),
// 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: {
@ -35,6 +34,11 @@ describe('html2canvas', () => {
DocumentCloner.destroy = jest.fn().mockReturnValue(true);
await html2canvas(element);
expect(CanvasRenderer).toHaveBeenLastCalledWith(
expect.objectContaining({
cache: expect.any(Object),
logger: expect.any(Object),
windowBounds: expect.objectContaining({left: 12, top: 34})
}),
expect.objectContaining({
backgroundColor: 0xffffffff,
scale: 1,
@ -42,8 +46,6 @@ describe('html2canvas', () => {
width: 200,
x: 0,
y: 0,
scrollX: 12,
scrollY: 34,
canvas: undefined
})
);
@ -53,6 +55,7 @@ describe('html2canvas', () => {
it('should have transparent background with backgroundColor: null', async () => {
await html2canvas(element, {backgroundColor: null});
expect(CanvasRenderer).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({
backgroundColor: COLORS.TRANSPARENT
})
@ -60,10 +63,10 @@ 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(
expect.anything(),
expect.objectContaining({
canvas
})
@ -74,6 +77,7 @@ describe('html2canvas', () => {
DocumentCloner.destroy = jest.fn();
await html2canvas(element, {removeContainer: false});
expect(CanvasRenderer).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({
backgroundColor: 0xffffffff,
scale: 1,
@ -81,8 +85,6 @@ describe('html2canvas', () => {
width: 200,
x: 0,
y: 0,
scrollX: 12,
scrollY: 34,
canvas: undefined
})
);

View File

@ -1,22 +1 @@
class MockCache {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private readonly _cache: {[key: string]: Promise<any>};
constructor() {
this._cache = {};
}
addImage(src: string): Promise<void> {
const result = Promise.resolve();
this._cache[src] = result;
return result;
}
}
const current = new MockCache();
export class CacheStorage {
static getInstance(): MockCache {
return current;
}
}
export class CacheStorage {}

View File

@ -0,0 +1,19 @@
import {logger, Logger} from './logger';
export class Context {
readonly logger: Logger = logger;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly _cache: {[key: string]: Promise<any>} = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly cache: any;
constructor() {
this.cache = {
addImage: jest.fn().mockImplementation((src: string): Promise<void> => {
const result = Promise.resolve();
this._cache[src] = result;
return result;
})
};
}
}

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();
export const logger = new Logger();

View File

@ -1,7 +1,8 @@
import {deepStrictEqual, fail} from 'assert';
import {FEATURES} from '../features';
import {CacheStorage} from '../cache-storage';
import {Logger} from '../logger';
import {Context} from '../context';
import {Bounds} from '../../css/layout/bounds';
const proxy = 'http://example.com/proxy';
@ -35,24 +36,28 @@ const createMockContext = (origin: string, opts = {}) => {
};
CacheStorage.setContext(context as Window);
Logger.create({id: 'test', enabled: false});
return CacheStorage.create('test', {
imageTimeout: 0,
useCORS: false,
allowTaint: false,
proxy,
...opts
});
return new Context(
{
logging: false,
imageTimeout: 0,
useCORS: false,
allowTaint: false,
proxy,
...opts
},
new Bounds(0, 0, 0, 0)
);
};
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 +70,8 @@ class XMLHttpRequestMock {
method?: string;
url?: string;
response?: string;
onload?: () => {};
ontimeout?: () => {};
onload?: () => void;
ontimeout?: () => void;
constructor() {
this.sent = false;
this.status = 500;
@ -106,7 +111,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
@ -121,7 +126,7 @@ describe('cache-storage', () => {
images.splice(0, images.length);
});
it('addImage adds images to cache', async () => {
const cache = createMockContext('http://example.com', {proxy: null});
const {cache} = createMockContext('http://example.com', {proxy: null});
await cache.addImage('http://example.com/test.jpg');
await cache.addImage('http://example.com/test2.jpg');
@ -131,7 +136,7 @@ describe('cache-storage', () => {
});
it('addImage should not add duplicate entries', async () => {
const cache = createMockContext('http://example.com');
const {cache} = createMockContext('http://example.com');
await cache.addImage('http://example.com/test.jpg');
await cache.addImage('http://example.com/test.jpg');
@ -141,7 +146,7 @@ describe('cache-storage', () => {
describe('svg', () => {
it('should add svg images correctly', async () => {
const cache = createMockContext('http://example.com');
const {cache} = createMockContext('http://example.com');
await cache.addImage('http://example.com/test.svg');
await cache.addImage('http://example.com/test2.svg');
@ -152,7 +157,7 @@ describe('cache-storage', () => {
it('should omit svg images if not supported', async () => {
setFeatures({SUPPORT_SVG_DRAWING: false});
const cache = createMockContext('http://example.com');
const {cache} = createMockContext('http://example.com');
await cache.addImage('http://example.com/test.svg');
await cache.addImage('http://example.com/test2.svg');
@ -162,7 +167,7 @@ describe('cache-storage', () => {
describe('cross-origin', () => {
it('addImage should not add images it cannot load/render', async () => {
const cache = createMockContext('http://example.com', {
const {cache} = createMockContext('http://example.com', {
proxy: undefined
});
await cache.addImage('http://html2canvas.hertzen.com/test.jpg');
@ -170,7 +175,7 @@ describe('cache-storage', () => {
});
it('addImage should add images if tainting enabled', async () => {
const cache = createMockContext('http://example.com', {
const {cache} = createMockContext('http://example.com', {
allowTaint: true,
proxy: undefined
});
@ -181,7 +186,7 @@ describe('cache-storage', () => {
});
it('addImage should add images if cors enabled', async () => {
const cache = createMockContext('http://example.com', {useCORS: true});
const {cache} = createMockContext('http://example.com', {useCORS: true});
await cache.addImage('http://html2canvas.hertzen.com/test.jpg');
deepStrictEqual(images.length, 1);
deepStrictEqual(images[0].src, 'http://html2canvas.hertzen.com/test.jpg');
@ -191,7 +196,7 @@ describe('cache-storage', () => {
it('addImage should not add images if cors enabled but not supported', async () => {
setFeatures({SUPPORT_CORS_IMAGES: false});
const cache = createMockContext('http://example.com', {
const {cache} = createMockContext('http://example.com', {
useCORS: true,
proxy: undefined
});
@ -200,7 +205,7 @@ describe('cache-storage', () => {
});
it('addImage should not add images to proxy if cors enabled', async () => {
const cache = createMockContext('http://example.com', {useCORS: true});
const {cache} = createMockContext('http://example.com', {useCORS: true});
await cache.addImage('http://html2canvas.hertzen.com/test.jpg');
deepStrictEqual(images.length, 1);
deepStrictEqual(images[0].src, 'http://html2canvas.hertzen.com/test.jpg');
@ -208,7 +213,7 @@ describe('cache-storage', () => {
});
it('addImage should use proxy ', async () => {
const cache = createMockContext('http://example.com');
const {cache} = createMockContext('http://example.com');
await cache.addImage('http://html2canvas.hertzen.com/test.jpg');
deepStrictEqual(xhr.length, 1);
deepStrictEqual(
@ -222,7 +227,7 @@ describe('cache-storage', () => {
});
it('proxy should respect imageTimeout', async () => {
const cache = createMockContext('http://example.com', {
const {cache} = createMockContext('http://example.com', {
imageTimeout: 10
});
await cache.addImage('http://html2canvas.hertzen.com/test.jpg');
@ -244,7 +249,7 @@ describe('cache-storage', () => {
});
it('match should return cache entry', async () => {
const cache = createMockContext('http://example.com');
const {cache} = createMockContext('http://example.com');
await cache.addImage('http://example.com/test.jpg');
if (images[0].onload) {
@ -257,7 +262,7 @@ describe('cache-storage', () => {
});
it('image should respect imageTimeout', async () => {
const cache = createMockContext('http://example.com', {imageTimeout: 10});
const {cache} = createMockContext('http://example.com', {imageTimeout: 10});
cache.addImage('http://example.com/test.jpg');
try {

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

@ -1,28 +1,9 @@
import {FEATURES} from './features';
import {Logger} from './logger';
import {Context} from './context';
export class CacheStorage {
private static _caches: {[key: string]: Cache} = {};
private static _link?: HTMLAnchorElement;
private static _origin: string = 'about:blank';
private static _current: Cache | null = null;
static create(name: string, options: ResourceOptions): Cache {
return (CacheStorage._caches[name] = new Cache(name, options));
}
static destroy(name: string): void {
delete CacheStorage._caches[name];
}
static open(name: string): Cache {
const cache = CacheStorage._caches[name];
if (typeof cache !== 'undefined') {
return cache;
}
throw new Error(`Cache with key "${name}" not found`);
}
private static _origin = 'about:blank';
static getOrigin(url: string): string {
const link = CacheStorage._link;
@ -39,26 +20,10 @@ 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);
}
static getInstance(): Cache {
const current = CacheStorage._current;
if (current === null) {
throw new Error(`No cache instance attached`);
}
return current;
}
static attachInstance(cache: Cache) {
CacheStorage._current = cache;
}
static detachInstance() {
CacheStorage._current = null;
}
}
export interface ResourceOptions {
@ -70,15 +35,9 @@ export interface ResourceOptions {
export class Cache {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private readonly _cache: {[key: string]: Promise<any>};
private readonly _options: ResourceOptions;
private readonly id: string;
private readonly _cache: {[key: string]: Promise<any>} = {};
constructor(id: string, options: ResourceOptions) {
this.id = id;
this._options = options;
this._cache = {};
}
constructor(private readonly context: Context, private readonly _options: ResourceOptions) {}
addImage(src: string): Promise<void> {
const result = Promise.resolve();
@ -87,7 +46,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;
}
@ -106,10 +67,18 @@ export class Cache {
const useProxy =
!isInlineImage(key) &&
!isSameOrigin &&
!isBlobImage(key) &&
typeof this._options.proxy === 'string' &&
FEATURES.SUPPORT_CORS_XHR &&
!useCORS;
if (!isSameOrigin && this._options.allowTaint === false && !isInlineImage(key) && !useProxy && !useCORS) {
if (
!isSameOrigin &&
this._options.allowTaint === false &&
!isInlineImage(key) &&
!isBlobImage(key) &&
!useProxy &&
!useCORS
) {
return;
}
@ -118,7 +87,7 @@ export class Cache {
src = await this.proxy(src);
}
Logger.getInstance(this.id).debug(`Added image ${key.substring(0, 256)}`);
this.context.logger.debug(`Added image ${key.substring(0, 256)}`);
return await new Promise((resolve, reject) => {
const img = new Image();
@ -169,7 +138,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 +147,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;

21
src/core/context.ts Normal file
View File

@ -0,0 +1,21 @@
import {Logger} from './logger';
import {Cache, ResourceOptions} from './cache-storage';
import {Bounds} from '../css/layout/bounds';
export type ContextOptions = {
logging: boolean;
cache?: Cache;
} & ResourceOptions;
export class Context {
private readonly instanceName = `#${Context.instanceCount++}`;
readonly logger: Logger;
readonly cache: Cache;
private static instanceCount = 1;
constructor(options: ContextOptions, public windowBounds: Bounds) {
this.logger = new Logger({id: this.instanceName, enabled: options.logging});
this.cache = options.cache ?? new Cache(this, options);
}
}

29
src/core/debugger.ts Normal file
View File

@ -0,0 +1,29 @@
const elementDebuggerAttribute = 'data-html2canvas-debug';
export const enum DebuggerType {
NONE,
ALL,
CLONE,
PARSE,
RENDER
}
const getElementDebugType = (element: Element): DebuggerType => {
const attribute = element.getAttribute(elementDebuggerAttribute);
switch (attribute) {
case 'all':
return DebuggerType.ALL;
case 'clone':
return DebuggerType.CLONE;
case 'parse':
return DebuggerType.PARSE;
case 'render':
return DebuggerType.RENDER;
default:
return DebuggerType.NONE;
}
};
export const isDebugging = (element: Element, type: Omit<DebuggerType, DebuggerType.NONE>): boolean => {
const elementType = getElementDebugType(element);
return elementType === DebuggerType.ALL || type === elementType;
};

View File

@ -1,3 +1,5 @@
import {fromCodePoint, toCodePoints} from 'css-line-break';
const testRangeBounds = (document: Document) => {
const TEST_HEIGHT = 123;
@ -22,6 +24,45 @@ const testRangeBounds = (document: Document) => {
return false;
};
const testIOSLineBreak = (document: Document) => {
const testElement = document.createElement('boundtest');
testElement.style.width = '50px';
testElement.style.display = 'block';
testElement.style.fontSize = '12px';
testElement.style.letterSpacing = '0px';
testElement.style.wordSpacing = '0px';
document.body.appendChild(testElement);
const range = document.createRange();
testElement.innerHTML = typeof ''.repeat === 'function' ? '&#128104;'.repeat(10) : '';
const node = testElement.firstChild as Text;
const textList = toCodePoints(node.data).map((i) => fromCodePoint(i));
let offset = 0;
let prev: DOMRect = {} as DOMRect;
// ios 13 does not handle range getBoundingClientRect line changes correctly #2177
const supports = textList.every((text, i) => {
range.setStart(node, offset);
range.setEnd(node, offset + text.length);
const rect = range.getBoundingClientRect();
offset += text.length;
const boundAhead = rect.x > prev.x || rect.y > prev.y;
prev = rect;
if (i === 0) {
return true;
}
return boundAhead;
});
document.body.removeChild(testElement);
return supports;
};
const testCORS = (): boolean => typeof new Image().crossOrigin !== 'undefined';
const testResponseType = (): boolean => typeof new XMLHttpRequest().responseType === 'string';
@ -90,7 +131,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 +167,25 @@ 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_WORD_BREAKING(): boolean {
'use strict';
const value = FEATURES.SUPPORT_RANGE_BOUNDS && testIOSLineBreak(document);
Object.defineProperty(FEATURES, 'SUPPORT_WORD_BREAKING', {value});
return value;
},
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,22 +194,29 @@ 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});
return value;
},
get SUPPORT_NATIVE_TEXT_SEGMENTATION(): boolean {
'use strict';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const value = !!(typeof Intl !== 'undefined' && (Intl as any).Segmenter);
Object.defineProperty(FEATURES, 'SUPPORT_NATIVE_TEXT_SEGMENTATION', {value});
return 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,24 +33,8 @@ export class Logger {
return Date.now() - this.start;
}
static create(options: LoggerOptions) {
Logger.instances[options.id] = new Logger(options);
}
static destroy(id: string) {
delete Logger.instances[id];
}
static getInstance(id: string): Logger {
const instance = Logger.instances[id];
if (typeof instance === 'undefined') {
throw new Error(`No logger instance found with id ${id}`);
}
return instance;
}
// 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 +45,20 @@ export class Logger {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error(...args: any) {
warn(...args: unknown[]): void {
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.warn === 'function') {
// eslint-disable-next-line no-console
console.warn(this.id, `${this.getTime()}ms`, ...args);
} else {
this.info(...args);
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-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

@ -1,7 +1,8 @@
import {CSSValue} from './syntax/parser';
import {CSSTypes} from './types/index';
import {CSSTypes} from './types';
import {Context} from '../core/context';
export enum PropertyDescriptorParsingType {
export const enum PropertyDescriptorParsingType {
VALUE,
LIST,
IDENT_VALUE,
@ -18,7 +19,7 @@ export interface IPropertyDescriptor {
export interface IPropertyIdentValueDescriptor<T> extends IPropertyDescriptor {
type: PropertyDescriptorParsingType.IDENT_VALUE;
parse: (token: string) => T;
parse: (context: Context, token: string) => T;
}
export interface IPropertyTypeValueDescriptor extends IPropertyDescriptor {
@ -28,12 +29,12 @@ export interface IPropertyTypeValueDescriptor extends IPropertyDescriptor {
export interface IPropertyValueDescriptor<T> extends IPropertyDescriptor {
type: PropertyDescriptorParsingType.VALUE;
parse: (token: CSSValue) => T;
parse: (context: Context, token: CSSValue) => T;
}
export interface IPropertyListDescriptor<T> extends IPropertyDescriptor {
type: PropertyDescriptorParsingType.LIST;
parse: (tokens: CSSValue[]) => T;
parse: (context: Context, tokens: CSSValue[]) => T;
}
export interface IPropertyTokenValueDescriptor extends IPropertyDescriptor {

View File

@ -1,6 +1,7 @@
import {CSSValue} from './syntax/parser';
import {Context} from '../core/context';
export interface ITypeDescriptor<T> {
name: string;
parse: (value: CSSValue) => T;
parse: (context: Context, value: CSSValue) => T;
}

View File

@ -31,6 +31,7 @@ import {
borderTopWidth
} from './property-descriptors/border-width';
import {color} from './property-descriptors/color';
import {direction} from './property-descriptors/direction';
import {display, DISPLAY} from './property-descriptors/display';
import {float, FLOAT} from './property-descriptors/float';
import {letterSpacing} from './property-descriptors/letter-spacing';
@ -57,6 +58,7 @@ import {Tokenizer} from './syntax/tokenizer';
import {Color, color as colorType, isTransparent} from './types/color';
import {angle} from './types/angle';
import {image} from './types/image';
import {time} from './types/time';
import {opacity} from './property-descriptors/opacity';
import {textDecorationColor} from './property-descriptors/text-decoration-color';
import {textDecorationLine} from './property-descriptors/text-decoration-line';
@ -71,10 +73,16 @@ import {contains} from '../core/bitwise';
import {content} from './property-descriptors/content';
import {counterIncrement} from './property-descriptors/counter-increment';
import {counterReset} from './property-descriptors/counter-reset';
import {duration} from './property-descriptors/duration';
import {quotes} from './property-descriptors/quotes';
import {boxShadow} from './property-descriptors/box-shadow';
import {paintOrder} from './property-descriptors/paint-order';
import {webkitTextStrokeColor} from './property-descriptors/webkit-text-stroke-color';
import {webkitTextStrokeWidth} from './property-descriptors/webkit-text-stroke-width';
import {Context} from '../core/context';
export class CSSParsedDeclaration {
animationDuration: ReturnType<typeof duration.parse>;
backgroundClip: ReturnType<typeof backgroundClip.parse>;
backgroundColor: Color;
backgroundImage: ReturnType<typeof backgroundImage.parse>;
@ -100,6 +108,7 @@ export class CSSParsedDeclaration {
borderLeftWidth: ReturnType<typeof borderLeftWidth.parse>;
boxShadow: ReturnType<typeof boxShadow.parse>;
color: Color;
direction: ReturnType<typeof direction.parse>;
display: ReturnType<typeof display.parse>;
float: ReturnType<typeof float.parse>;
fontFamily: ReturnType<typeof fontFamily.parse>;
@ -125,6 +134,7 @@ export class CSSParsedDeclaration {
paddingRight: LengthPercentage;
paddingBottom: LengthPercentage;
paddingLeft: LengthPercentage;
paintOrder: ReturnType<typeof paintOrder.parse>;
position: ReturnType<typeof position.parse>;
textAlign: ReturnType<typeof textAlign.parse>;
textDecorationColor: Color;
@ -134,72 +144,87 @@ export class CSSParsedDeclaration {
transform: ReturnType<typeof transform.parse>;
transformOrigin: ReturnType<typeof transformOrigin.parse>;
visibility: ReturnType<typeof visibility.parse>;
webkitTextStrokeColor: Color;
webkitTextStrokeWidth: ReturnType<typeof webkitTextStrokeWidth.parse>;
wordBreak: ReturnType<typeof wordBreak.parse>;
zIndex: ReturnType<typeof zIndex.parse>;
constructor(declaration: CSSStyleDeclaration) {
this.backgroundClip = parse(backgroundClip, declaration.backgroundClip);
this.backgroundColor = parse(backgroundColor, declaration.backgroundColor);
this.backgroundImage = parse(backgroundImage, declaration.backgroundImage);
this.backgroundOrigin = parse(backgroundOrigin, declaration.backgroundOrigin);
this.backgroundPosition = parse(backgroundPosition, declaration.backgroundPosition);
this.backgroundRepeat = parse(backgroundRepeat, declaration.backgroundRepeat);
this.backgroundSize = parse(backgroundSize, declaration.backgroundSize);
this.borderTopColor = parse(borderTopColor, declaration.borderTopColor);
this.borderRightColor = parse(borderRightColor, declaration.borderRightColor);
this.borderBottomColor = parse(borderBottomColor, declaration.borderBottomColor);
this.borderLeftColor = parse(borderLeftColor, declaration.borderLeftColor);
this.borderTopLeftRadius = parse(borderTopLeftRadius, declaration.borderTopLeftRadius);
this.borderTopRightRadius = parse(borderTopRightRadius, declaration.borderTopRightRadius);
this.borderBottomRightRadius = parse(borderBottomRightRadius, declaration.borderBottomRightRadius);
this.borderBottomLeftRadius = parse(borderBottomLeftRadius, declaration.borderBottomLeftRadius);
this.borderTopStyle = parse(borderTopStyle, declaration.borderTopStyle);
this.borderRightStyle = parse(borderRightStyle, declaration.borderRightStyle);
this.borderBottomStyle = parse(borderBottomStyle, declaration.borderBottomStyle);
this.borderLeftStyle = parse(borderLeftStyle, declaration.borderLeftStyle);
this.borderTopWidth = parse(borderTopWidth, declaration.borderTopWidth);
this.borderRightWidth = parse(borderRightWidth, declaration.borderRightWidth);
this.borderBottomWidth = parse(borderBottomWidth, declaration.borderBottomWidth);
this.borderLeftWidth = parse(borderLeftWidth, declaration.borderLeftWidth);
this.boxShadow = parse(boxShadow, declaration.boxShadow);
this.color = parse(color, declaration.color);
this.display = parse(display, declaration.display);
this.float = parse(float, declaration.cssFloat);
this.fontFamily = parse(fontFamily, declaration.fontFamily);
this.fontSize = parse(fontSize, declaration.fontSize);
this.fontStyle = parse(fontStyle, declaration.fontStyle);
this.fontVariant = parse(fontVariant, declaration.fontVariant);
this.fontWeight = parse(fontWeight, declaration.fontWeight);
this.letterSpacing = parse(letterSpacing, declaration.letterSpacing);
this.lineBreak = parse(lineBreak, declaration.lineBreak);
this.lineHeight = parse(lineHeight, declaration.lineHeight);
this.listStyleImage = parse(listStyleImage, declaration.listStyleImage);
this.listStylePosition = parse(listStylePosition, declaration.listStylePosition);
this.listStyleType = parse(listStyleType, declaration.listStyleType);
this.marginTop = parse(marginTop, declaration.marginTop);
this.marginRight = parse(marginRight, declaration.marginRight);
this.marginBottom = parse(marginBottom, declaration.marginBottom);
this.marginLeft = parse(marginLeft, declaration.marginLeft);
this.opacity = parse(opacity, declaration.opacity);
const overflowTuple = parse(overflow, declaration.overflow);
constructor(context: Context, declaration: CSSStyleDeclaration) {
this.animationDuration = parse(context, duration, declaration.animationDuration);
this.backgroundClip = parse(context, backgroundClip, declaration.backgroundClip);
this.backgroundColor = parse(context, backgroundColor, declaration.backgroundColor);
this.backgroundImage = parse(context, backgroundImage, declaration.backgroundImage);
this.backgroundOrigin = parse(context, backgroundOrigin, declaration.backgroundOrigin);
this.backgroundPosition = parse(context, backgroundPosition, declaration.backgroundPosition);
this.backgroundRepeat = parse(context, backgroundRepeat, declaration.backgroundRepeat);
this.backgroundSize = parse(context, backgroundSize, declaration.backgroundSize);
this.borderTopColor = parse(context, borderTopColor, declaration.borderTopColor);
this.borderRightColor = parse(context, borderRightColor, declaration.borderRightColor);
this.borderBottomColor = parse(context, borderBottomColor, declaration.borderBottomColor);
this.borderLeftColor = parse(context, borderLeftColor, declaration.borderLeftColor);
this.borderTopLeftRadius = parse(context, borderTopLeftRadius, declaration.borderTopLeftRadius);
this.borderTopRightRadius = parse(context, borderTopRightRadius, declaration.borderTopRightRadius);
this.borderBottomRightRadius = parse(context, borderBottomRightRadius, declaration.borderBottomRightRadius);
this.borderBottomLeftRadius = parse(context, borderBottomLeftRadius, declaration.borderBottomLeftRadius);
this.borderTopStyle = parse(context, borderTopStyle, declaration.borderTopStyle);
this.borderRightStyle = parse(context, borderRightStyle, declaration.borderRightStyle);
this.borderBottomStyle = parse(context, borderBottomStyle, declaration.borderBottomStyle);
this.borderLeftStyle = parse(context, borderLeftStyle, declaration.borderLeftStyle);
this.borderTopWidth = parse(context, borderTopWidth, declaration.borderTopWidth);
this.borderRightWidth = parse(context, borderRightWidth, declaration.borderRightWidth);
this.borderBottomWidth = parse(context, borderBottomWidth, declaration.borderBottomWidth);
this.borderLeftWidth = parse(context, borderLeftWidth, declaration.borderLeftWidth);
this.boxShadow = parse(context, boxShadow, declaration.boxShadow);
this.color = parse(context, color, declaration.color);
this.direction = parse(context, direction, declaration.direction);
this.display = parse(context, display, declaration.display);
this.float = parse(context, float, declaration.cssFloat);
this.fontFamily = parse(context, fontFamily, declaration.fontFamily);
this.fontSize = parse(context, fontSize, declaration.fontSize);
this.fontStyle = parse(context, fontStyle, declaration.fontStyle);
this.fontVariant = parse(context, fontVariant, declaration.fontVariant);
this.fontWeight = parse(context, fontWeight, declaration.fontWeight);
this.letterSpacing = parse(context, letterSpacing, declaration.letterSpacing);
this.lineBreak = parse(context, lineBreak, declaration.lineBreak);
this.lineHeight = parse(context, lineHeight, declaration.lineHeight);
this.listStyleImage = parse(context, listStyleImage, declaration.listStyleImage);
this.listStylePosition = parse(context, listStylePosition, declaration.listStylePosition);
this.listStyleType = parse(context, listStyleType, declaration.listStyleType);
this.marginTop = parse(context, marginTop, declaration.marginTop);
this.marginRight = parse(context, marginRight, declaration.marginRight);
this.marginBottom = parse(context, marginBottom, declaration.marginBottom);
this.marginLeft = parse(context, marginLeft, declaration.marginLeft);
this.opacity = parse(context, opacity, declaration.opacity);
const overflowTuple = parse(context, overflow, declaration.overflow);
this.overflowX = overflowTuple[0];
this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0];
this.overflowWrap = parse(overflowWrap, declaration.overflowWrap);
this.paddingTop = parse(paddingTop, declaration.paddingTop);
this.paddingRight = parse(paddingRight, declaration.paddingRight);
this.paddingBottom = parse(paddingBottom, declaration.paddingBottom);
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.textShadow = parse(textShadow, declaration.textShadow);
this.textTransform = parse(textTransform, declaration.textTransform);
this.transform = parse(transform, declaration.transform);
this.transformOrigin = parse(transformOrigin, declaration.transformOrigin);
this.visibility = parse(visibility, declaration.visibility);
this.wordBreak = parse(wordBreak, declaration.wordBreak);
this.zIndex = parse(zIndex, declaration.zIndex);
this.overflowWrap = parse(context, overflowWrap, declaration.overflowWrap);
this.paddingTop = parse(context, paddingTop, declaration.paddingTop);
this.paddingRight = parse(context, paddingRight, declaration.paddingRight);
this.paddingBottom = parse(context, paddingBottom, declaration.paddingBottom);
this.paddingLeft = parse(context, paddingLeft, declaration.paddingLeft);
this.paintOrder = parse(context, paintOrder, declaration.paintOrder);
this.position = parse(context, position, declaration.position);
this.textAlign = parse(context, textAlign, declaration.textAlign);
this.textDecorationColor = parse(
context,
textDecorationColor,
declaration.textDecorationColor ?? declaration.color
);
this.textDecorationLine = parse(
context,
textDecorationLine,
declaration.textDecorationLine ?? declaration.textDecoration
);
this.textShadow = parse(context, textShadow, declaration.textShadow);
this.textTransform = parse(context, textTransform, declaration.textTransform);
this.transform = parse(context, transform, declaration.transform);
this.transformOrigin = parse(context, transformOrigin, declaration.transformOrigin);
this.visibility = parse(context, visibility, declaration.visibility);
this.webkitTextStrokeColor = parse(context, webkitTextStrokeColor, declaration.webkitTextStrokeColor);
this.webkitTextStrokeWidth = parse(context, webkitTextStrokeWidth, declaration.webkitTextStrokeWidth);
this.wordBreak = parse(context, wordBreak, declaration.wordBreak);
this.zIndex = parse(context, zIndex, declaration.zIndex);
}
isVisible(): boolean {
@ -242,9 +267,9 @@ export class CSSParsedPseudoDeclaration {
content: ReturnType<typeof content.parse>;
quotes: ReturnType<typeof quotes.parse>;
constructor(declaration: CSSStyleDeclaration) {
this.content = parse(content, declaration.content);
this.quotes = parse(quotes, declaration.quotes);
constructor(context: Context, declaration: CSSStyleDeclaration) {
this.content = parse(context, content, declaration.content);
this.quotes = parse(context, quotes, declaration.quotes);
}
}
@ -252,14 +277,14 @@ export class CSSParsedCounterDeclaration {
counterIncrement: ReturnType<typeof counterIncrement.parse>;
counterReset: ReturnType<typeof counterReset.parse>;
constructor(declaration: CSSStyleDeclaration) {
this.counterIncrement = parse(counterIncrement, declaration.counterIncrement);
this.counterReset = parse(counterReset, declaration.counterReset);
constructor(context: Context, declaration: CSSStyleDeclaration) {
this.counterIncrement = parse(context, counterIncrement, declaration.counterIncrement);
this.counterReset = parse(context, counterReset, declaration.counterReset);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const parse = (descriptor: CSSPropertyDescriptor<any>, style?: string | null) => {
const parse = (context: Context, descriptor: CSSPropertyDescriptor<any>, style?: string | null) => {
const tokenizer = new Tokenizer();
const value = style !== null && typeof style !== 'undefined' ? style.toString() : descriptor.initialValue;
tokenizer.write(value);
@ -267,29 +292,30 @@ const parse = (descriptor: CSSPropertyDescriptor<any>, style?: string | null) =>
switch (descriptor.type) {
case PropertyDescriptorParsingType.IDENT_VALUE:
const token = parser.parseComponentValue();
return descriptor.parse(isIdentToken(token) ? token.value : descriptor.initialValue);
return descriptor.parse(context, isIdentToken(token) ? token.value : descriptor.initialValue);
case PropertyDescriptorParsingType.VALUE:
return descriptor.parse(parser.parseComponentValue());
return descriptor.parse(context, parser.parseComponentValue());
case PropertyDescriptorParsingType.LIST:
return descriptor.parse(parser.parseComponentValues());
return descriptor.parse(context, parser.parseComponentValues());
case PropertyDescriptorParsingType.TOKEN_VALUE:
return parser.parseComponentValue();
case PropertyDescriptorParsingType.TYPE_VALUE:
switch (descriptor.format) {
case 'angle':
return angle.parse(parser.parseComponentValue());
return angle.parse(context, parser.parseComponentValue());
case 'color':
return colorType.parse(parser.parseComponentValue());
return colorType.parse(context, parser.parseComponentValue());
case 'image':
return image.parse(parser.parseComponentValue());
return image.parse(context, parser.parseComponentValue());
case 'length':
const length = parser.parseComponentValue();
return isLength(length) ? length : ZERO_LENGTH;
case 'length-percentage':
const value = parser.parseComponentValue();
return isLengthPercentage(value) ? value : ZERO_LENGTH;
case 'time':
return time.parse(context, parser.parseComponentValue());
}
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

@ -1,27 +1,38 @@
export class Bounds {
readonly top: number;
readonly left: number;
readonly width: number;
readonly height: number;
import {Context} from '../../core/context';
constructor(x: number, y: number, w: number, h: number) {
this.left = x;
this.top = y;
this.width = w;
this.height = h;
}
export class Bounds {
constructor(readonly left: number, readonly top: number, readonly width: number, readonly height: number) {}
add(x: number, y: number, w: number, h: number): Bounds {
return new Bounds(this.left + x, this.top + y, this.width + w, this.height + h);
}
static fromClientRect(clientRect: ClientRect): Bounds {
return new Bounds(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
static fromClientRect(context: Context, clientRect: ClientRect): Bounds {
return new Bounds(
clientRect.left + context.windowBounds.left,
clientRect.top + context.windowBounds.top,
clientRect.width,
clientRect.height
);
}
static fromDOMRectList(context: Context, domRectList: DOMRectList): Bounds {
const domRect = Array.from(domRectList).find((rect) => rect.width !== 0);
return domRect
? new Bounds(
domRect.left + context.windowBounds.left,
domRect.top + context.windowBounds.top,
domRect.width,
domRect.height
)
: Bounds.EMPTY;
}
static EMPTY = new Bounds(0, 0, 0, 0);
}
export const parseBounds = (node: Element): Bounds => {
return Bounds.fromClientRect(node.getBoundingClientRect());
export const parseBounds = (context: Context, node: Element): Bounds => {
return Bounds.fromClientRect(context, node.getBoundingClientRect());
};
export const parseDocumentSize = (document: Document): Bounds => {

View File

@ -1,8 +1,10 @@
import {OVERFLOW_WRAP} from '../property-descriptors/overflow-wrap';
import {CSSParsedDeclaration} from '../index';
import {fromCodePoint, LineBreaker, toCodePoints} from 'css-line-break';
import {splitGraphemes} from 'text-segmentation';
import {Bounds, parseBounds} from './bounds';
import {FEATURES} from '../../core/features';
import {Context} from '../../core/context';
export class TextBounds {
readonly text: string;
@ -14,17 +16,40 @@ export class TextBounds {
}
}
export const parseTextBounds = (value: string, styles: CSSParsedDeclaration, node: Text): TextBounds[] => {
export const parseTextBounds = (
context: Context,
value: string,
styles: CSSParsedDeclaration,
node: Text
): TextBounds[] => {
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)));
const clientRects = createRange(node, offset, text.length).getClientRects();
if (clientRects.length > 1) {
const subSegments = segmentGraphemes(text);
let subOffset = 0;
subSegments.forEach((subSegment) => {
textBounds.push(
new TextBounds(
subSegment,
Bounds.fromDOMRectList(
context,
createRange(node, subOffset + offset, subSegment.length).getClientRects()
)
)
);
subOffset += subSegment.length;
});
} else {
textBounds.push(new TextBounds(text, Bounds.fromDOMRectList(context, clientRects)));
}
} else {
const replacementNode = node.splitText(text.length);
textBounds.push(new TextBounds(text, getWrapperBounds(node)));
textBounds.push(new TextBounds(text, getWrapperBounds(context, node)));
node = replacementNode;
}
} else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
@ -36,7 +61,7 @@ export const parseTextBounds = (value: string, styles: CSSParsedDeclaration, nod
return textBounds;
};
const getWrapperBounds = (node: Text): Bounds => {
const getWrapperBounds = (context: Context, node: Text): Bounds => {
const ownerDocument = node.ownerDocument;
if (ownerDocument) {
const wrapper = ownerDocument.createElement('html2canvaswrapper');
@ -44,7 +69,7 @@ const getWrapperBounds = (node: Text): Bounds => {
const parentNode = node.parentNode;
if (parentNode) {
parentNode.replaceChild(wrapper, node);
const bounds = parseBounds(wrapper);
const bounds = parseBounds(context, wrapper);
if (wrapper.firstChild) {
parentNode.replaceChild(wrapper.firstChild, wrapper);
}
@ -52,10 +77,10 @@ const getWrapperBounds = (node: Text): Bounds => {
}
}
return new Bounds(0, 0, 0, 0);
return Bounds.EMPTY;
};
const getRangeBounds = (node: Text, offset: number, length: number): Bounds => {
const createRange = (node: Text, offset: number, length: number): Range => {
const ownerDocument = node.ownerDocument;
if (!ownerDocument) {
throw new Error('Node has no owner document');
@ -63,13 +88,40 @@ const getRangeBounds = (node: Text, offset: number, length: number): Bounds => {
const range = ownerDocument.createRange();
range.setStart(node, offset);
range.setEnd(node, offset + length);
return Bounds.fromClientRect(range.getBoundingClientRect());
return range;
};
export const segmentGraphemes = (value: string): string[] => {
if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const segmenter = new (Intl as any).Segmenter(void 0, {granularity: 'grapheme'});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Array.from(segmenter.segment(value)).map((segment: any) => segment.segment);
}
return splitGraphemes(value);
};
const segmentWords = (value: string, styles: CSSParsedDeclaration): string[] => {
if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const segmenter = new (Intl as any).Segmenter(void 0, {
granularity: 'word'
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Array.from(segmenter.segment(value)).map((segment: any) => segment.segment);
}
return breakWords(value, styles);
};
const breakText = (value: string, styles: CSSParsedDeclaration): string[] => {
return styles.letterSpacing !== 0 ? toCodePoints(value).map(i => fromCodePoint(i)) : breakWords(value, styles);
return styles.letterSpacing !== 0 ? segmentGraphemes(value) : segmentWords(value, styles);
};
// https://drafts.csswg.org/css-text/#word-separator
const wordSeparators = [0x0020, 0x00a0, 0x1361, 0x10100, 0x10101, 0x1039, 0x1091];
const breakWords = (str: string, styles: CSSParsedDeclaration): string[] => {
const breaker = LineBreaker(str, {
lineBreak: styles.lineBreak,
@ -81,7 +133,24 @@ const breakWords = (str: string, styles: CSSParsedDeclaration): string[] => {
while (!(bk = breaker.next()).done) {
if (bk.value) {
words.push(bk.value.slice());
const value = bk.value.slice();
const codePoints = toCodePoints(value);
let word = '';
codePoints.forEach((codePoint) => {
if (wordSeparators.indexOf(codePoint) === -1) {
word += fromCodePoint(codePoint);
} else {
if (word.length) {
words.push(word);
}
words.push(fromCodePoint(codePoint));
word = '';
}
});
if (word.length) {
words.push(word);
}
}
}

View File

@ -5,34 +5,52 @@ import {CSSImageType} from '../../types/image';
import {pack} from '../../types/color';
import {deg} from '../../types/angle';
jest.mock('../../../core/cache-storage');
jest.mock('../../../core/context');
import {Context} from '../../../core/context';
jest.mock('../../../core/features');
const backgroundImageParse = (value: string) => backgroundImage.parse(Parser.parseValues(value));
const backgroundImageParse = (context: Context, value: string) =>
backgroundImage.parse(context, Parser.parseValues(value));
describe('property-descriptors', () => {
let context: Context;
beforeEach(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
context = new Context({} as any, {} as any);
});
describe('background-image', () => {
it('none', () => deepStrictEqual(backgroundImageParse('none'), []));
it('none', () => {
deepStrictEqual(backgroundImageParse(context, 'none'), []);
expect(context.cache.addImage).not.toHaveBeenCalled();
});
it('url(test.jpg), url(test2.jpg)', () =>
it('url(test.jpg), url(test2.jpg)', () => {
deepStrictEqual(
backgroundImageParse('url(http://example.com/test.jpg), url(http://example.com/test2.jpg)'),
backgroundImageParse(context, 'url(http://example.com/test.jpg), url(http://example.com/test2.jpg)'),
[
{url: 'http://example.com/test.jpg', type: CSSImageType.URL},
{url: 'http://example.com/test2.jpg', type: CSSImageType.URL}
]
));
);
expect(context.cache.addImage).toHaveBeenCalledWith('http://example.com/test.jpg');
expect(context.cache.addImage).toHaveBeenCalledWith('http://example.com/test2.jpg');
});
it(`linear-gradient(to bottom, rgba(255,255,0,0.5), rgba(0,0,255,0.5)), url('https://html2canvas.hertzen.com')`, () =>
deepStrictEqual(
backgroundImageParse(
context,
`linear-gradient(to bottom, rgba(255,255,0,0.5), rgba(0,0,255,0.5)), url('https://html2canvas.hertzen.com')`
),
[
{
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

@ -1,8 +1,9 @@
import {deepEqual} from 'assert';
import {Parser} from '../../syntax/parser';
import {fontFamily} from '../font-family';
import {Context} from '../../../core/context';
const fontFamilyParse = (value: string) => fontFamily.parse(Parser.parseValues(value));
const fontFamilyParse = (value: string) => fontFamily.parse({} as Context, Parser.parseValues(value));
describe('property-descriptors', () => {
describe('font-family', () => {

View File

@ -0,0 +1,87 @@
import {deepStrictEqual} from 'assert';
import {Parser} from '../../syntax/parser';
import {paintOrder, PAINT_ORDER_LAYER} from '../paint-order';
import {Context} from '../../../core/context';
const paintOrderParse = (value: string) => paintOrder.parse({} as Context, Parser.parseValues(value));
describe('property-descriptors', () => {
describe('paint-order', () => {
it('none', () =>
deepStrictEqual(paintOrderParse('none'), [
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.MARKERS
]));
it('EMPTY', () =>
deepStrictEqual(paintOrderParse(''), [
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.MARKERS
]));
it('other values', () =>
deepStrictEqual(paintOrderParse('other values'), [
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.MARKERS
]));
it('normal', () =>
deepStrictEqual(paintOrderParse('normal'), [
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.MARKERS
]));
it('stroke', () =>
deepStrictEqual(paintOrderParse('stroke'), [
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.MARKERS
]));
it('fill', () =>
deepStrictEqual(paintOrderParse('fill'), [
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.MARKERS
]));
it('markers', () =>
deepStrictEqual(paintOrderParse('markers'), [
PAINT_ORDER_LAYER.MARKERS,
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.STROKE
]));
it('stroke fill', () =>
deepStrictEqual(paintOrderParse('stroke fill'), [
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.MARKERS
]));
it('markers stroke', () =>
deepStrictEqual(paintOrderParse('markers stroke'), [
PAINT_ORDER_LAYER.MARKERS,
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.FILL
]));
it('markers stroke fill', () =>
deepStrictEqual(paintOrderParse('markers stroke fill'), [
PAINT_ORDER_LAYER.MARKERS,
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.FILL
]));
it('stroke fill markers', () =>
deepStrictEqual(paintOrderParse('stroke fill markers'), [
PAINT_ORDER_LAYER.STROKE,
PAINT_ORDER_LAYER.FILL,
PAINT_ORDER_LAYER.MARKERS
]));
});
});

View File

@ -4,9 +4,10 @@ import {color, COLORS} from '../../types/color';
import {textShadow} from '../text-shadow';
import {FLAG_INTEGER, DimensionToken, TokenType} from '../../syntax/tokenizer';
import {ZERO_LENGTH} from '../../types/length-percentage';
import {Context} from '../../../core/context';
const textShadowParse = (value: string) => textShadow.parse(Parser.parseValues(value));
const colorParse = (value: string) => color.parse(Parser.parseValue(value));
const textShadowParse = (value: string) => textShadow.parse({} as Context, Parser.parseValues(value));
const colorParse = (value: string) => color.parse({} as Context, Parser.parseValue(value));
const dimension = (number: number, unit: string): DimensionToken => ({
flags: FLAG_INTEGER,
number,

View File

@ -1,7 +1,8 @@
import {transform} from '../transform';
import {Parser} from '../../syntax/parser';
import {deepStrictEqual} from 'assert';
const parseValue = (value: string) => transform.parse(Parser.parseValue(value));
import {Context} from '../../../core/context';
const parseValue = (value: string) => transform.parse({} as Context, Parser.parseValue(value));
describe('property-descriptors', () => {
describe('transform', () => {
@ -9,13 +10,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

@ -1,6 +1,7 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken} from '../syntax/parser';
export enum BACKGROUND_CLIP {
import {Context} from '../../core/context';
export const enum BACKGROUND_CLIP {
BORDER_BOX = 0,
PADDING_BOX = 1,
CONTENT_BOX = 2
@ -13,8 +14,8 @@ export const backgroundClip: IPropertyListDescriptor<BackgroundClip> = {
initialValue: 'border-box',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundClip => {
return tokens.map(token => {
parse: (_context: Context, tokens: CSSValue[]): BackgroundClip => {
return tokens.map((token) => {
if (isIdentToken(token)) {
switch (token.value) {
case 'padding-box':

View File

@ -2,13 +2,14 @@ import {TokenType} from '../syntax/tokenizer';
import {ICSSImage, image, isSupportedImage} from '../types/image';
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, nonFunctionArgSeparator} from '../syntax/parser';
import {Context} from '../../core/context';
export const backgroundImage: IPropertyListDescriptor<ICSSImage[]> = {
name: 'background-image',
initialValue: 'none',
type: PropertyDescriptorParsingType.LIST,
prefix: false,
parse: (tokens: CSSValue[]) => {
parse: (context: Context, tokens: CSSValue[]) => {
if (tokens.length === 0) {
return [];
}
@ -19,6 +20,8 @@ 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((value) => image.parse(context, value));
}
};

View File

@ -1,5 +1,6 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken} from '../syntax/parser';
import {Context} from '../../core/context';
export const enum BACKGROUND_ORIGIN {
BORDER_BOX = 0,
@ -14,8 +15,8 @@ export const backgroundOrigin: IPropertyListDescriptor<BackgroundOrigin> = {
initialValue: 'border-box',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundOrigin => {
return tokens.map(token => {
parse: (_context: Context, tokens: CSSValue[]): BackgroundOrigin => {
return tokens.map((token) => {
if (isIdentToken(token)) {
switch (token.value) {
case 'padding-box':

View File

@ -1,6 +1,7 @@
import {PropertyDescriptorParsingType, IPropertyListDescriptor} from '../IPropertyDescriptor';
import {CSSValue, parseFunctionArgs} from '../syntax/parser';
import {isLengthPercentage, LengthPercentageTuple, parseLengthPercentageTuple} from '../types/length-percentage';
import {Context} from '../../core/context';
export type BackgroundPosition = BackgroundImagePosition[];
export type BackgroundImagePosition = LengthPercentageTuple;
@ -10,7 +11,7 @@ export const backgroundPosition: IPropertyListDescriptor<BackgroundPosition> = {
initialValue: '0% 0%',
type: PropertyDescriptorParsingType.LIST,
prefix: false,
parse: (tokens: CSSValue[]): BackgroundPosition => {
parse: (_context: Context, tokens: CSSValue[]): BackgroundPosition => {
return parseFunctionArgs(tokens)
.map((values: CSSValue[]) => values.filter(isLengthPercentage))
.map(parseLengthPercentageTuple);

View File

@ -1,8 +1,9 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken, parseFunctionArgs} from '../syntax/parser';
import {Context} from '../../core/context';
export type BackgroundRepeat = BACKGROUND_REPEAT[];
export enum BACKGROUND_REPEAT {
export const enum BACKGROUND_REPEAT {
REPEAT = 0,
NO_REPEAT = 1,
REPEAT_X = 2,
@ -14,12 +15,12 @@ export const backgroundRepeat: IPropertyListDescriptor<BackgroundRepeat> = {
initialValue: 'repeat',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundRepeat => {
parse: (_context: Context, 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

@ -2,6 +2,7 @@ import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IProper
import {CSSValue, isIdentToken, parseFunctionArgs} from '../syntax/parser';
import {isLengthPercentage, LengthPercentage} from '../types/length-percentage';
import {StringValueToken} from '../syntax/tokenizer';
import {Context} from '../../core/context';
export enum BACKGROUND_SIZE {
AUTO = 'auto',
@ -17,8 +18,8 @@ export const backgroundSize: IPropertyListDescriptor<BackgroundSize> = {
initialValue: '0',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BackgroundSize => {
return parseFunctionArgs(tokens).map(values => values.filter(isBackgroundSizeInfoToken));
parse: (_context: Context, tokens: CSSValue[]): BackgroundSize => {
return parseFunctionArgs(tokens).map((values) => values.filter(isBackgroundSizeInfoToken));
}
};

View File

@ -1,6 +1,7 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue} from '../syntax/parser';
import {isLengthPercentage, LengthPercentageTuple, parseLengthPercentageTuple} from '../types/length-percentage';
import {Context} from '../../core/context';
export type BorderRadius = LengthPercentageTuple;
const borderRadiusForSide = (side: string): IPropertyListDescriptor<BorderRadius> => ({
@ -8,7 +9,8 @@ const borderRadiusForSide = (side: string): IPropertyListDescriptor<BorderRadius
initialValue: '0 0',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): BorderRadius => parseLengthPercentageTuple(tokens.filter(isLengthPercentage))
parse: (_context: Context, tokens: CSSValue[]): BorderRadius =>
parseLengthPercentageTuple(tokens.filter(isLengthPercentage))
});
export const borderTopLeftRadius: IPropertyListDescriptor<BorderRadius> = borderRadiusForSide('top-left');

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum BORDER_STYLE {
import {Context} from '../../core/context';
export const enum BORDER_STYLE {
NONE = 0,
SOLID = 1,
DASHED = 2,
@ -12,7 +13,7 @@ const borderStyleForSide = (side: string): IPropertyIdentValueDescriptor<BORDER_
initialValue: 'solid',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (style: string): BORDER_STYLE => {
parse: (_context: Context, style: string): BORDER_STYLE => {
switch (style) {
case 'none':
return BORDER_STYLE.NONE;

View File

@ -1,11 +1,12 @@
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isDimensionToken} from '../syntax/parser';
import {Context} from '../../core/context';
const borderWidthForSide = (side: string): IPropertyValueDescriptor<number> => ({
name: `border-${side}-width`,
initialValue: '0',
type: PropertyDescriptorParsingType.VALUE,
prefix: false,
parse: (token: CSSValue): number => {
parse: (_context: Context, token: CSSValue): number => {
if (isDimensionToken(token)) {
return token.number;
}

View File

@ -3,6 +3,7 @@ import {CSSValue, isIdentWithValue, parseFunctionArgs} from '../syntax/parser';
import {ZERO_LENGTH} from '../types/length-percentage';
import {color, Color} from '../types/color';
import {isLength, Length} from '../types/length';
import {Context} from '../../core/context';
export type BoxShadow = BoxShadowItem[];
interface BoxShadowItem {
@ -19,7 +20,7 @@ export const boxShadow: IPropertyListDescriptor<BoxShadow> = {
initialValue: 'none',
type: PropertyDescriptorParsingType.LIST,
prefix: false,
parse: (tokens: CSSValue[]): BoxShadow => {
parse: (context: Context, tokens: CSSValue[]): BoxShadow => {
if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
return [];
}
@ -50,7 +51,7 @@ export const boxShadow: IPropertyListDescriptor<BoxShadow> = {
}
c++;
} else {
shadow.color = color.parse(token);
shadow.color = color.parse(context, token);
}
}
return shadow;

View File

@ -1,6 +1,7 @@
import {TokenType} from '../syntax/tokenizer';
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue} from '../syntax/parser';
import {Context} from '../../core/context';
export type Content = CSSValue[];
@ -9,7 +10,7 @@ export const content: IPropertyListDescriptor<Content> = {
initialValue: 'none',
type: PropertyDescriptorParsingType.LIST,
prefix: false,
parse: (tokens: CSSValue[]) => {
parse: (_context: Context, tokens: CSSValue[]) => {
if (tokens.length === 0) {
return [];
}

View File

@ -1,6 +1,7 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isNumberToken, nonWhiteSpace} from '../syntax/parser';
import {TokenType} from '../syntax/tokenizer';
import {Context} from '../../core/context';
export interface COUNTER_INCREMENT {
counter: string;
@ -14,7 +15,7 @@ export const counterIncrement: IPropertyListDescriptor<CounterIncrement> = {
initialValue: 'none',
prefix: true,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]) => {
parse: (_context: Context, tokens: CSSValue[]) => {
if (tokens.length === 0) {
return null;
}

View File

@ -1,5 +1,6 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken, isNumberToken, nonWhiteSpace} from '../syntax/parser';
import {Context} from '../../core/context';
export interface COUNTER_RESET {
counter: string;
@ -13,7 +14,7 @@ export const counterReset: IPropertyListDescriptor<CounterReset> = {
initialValue: 'none',
prefix: true,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]) => {
parse: (_context: Context, tokens: CSSValue[]) => {
if (tokens.length === 0) {
return [];
}

View File

@ -0,0 +1,23 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {Context} from '../../core/context';
export const enum DIRECTION {
LTR = 0,
RTL = 1
}
export const direction: IPropertyIdentValueDescriptor<DIRECTION> = {
name: 'direction',
initialValue: 'ltr',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (_context: Context, direction: string) => {
switch (direction) {
case 'rtl':
return DIRECTION.RTL;
case 'ltr':
default:
return DIRECTION.LTR;
}
}
};

View File

@ -1,5 +1,6 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken} from '../syntax/parser';
import {Context} from '../../core/context';
export const enum DISPLAY {
NONE = 0,
BLOCK = 1 << 1,
@ -40,7 +41,7 @@ export const display: IPropertyListDescriptor<Display> = {
initialValue: 'inline-block',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): Display => {
parse: (_context: Context, tokens: CSSValue[]): Display => {
return tokens.filter(isIdentToken).reduce((bit, token) => {
return bit | parseDisplayValue(token.value);
}, DISPLAY.NONE);

View File

@ -0,0 +1,14 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {Context} from '../../core/context';
import {CSSValue, isDimensionToken} from '../syntax/parser';
import {time} from '../types/time';
export const duration: IPropertyListDescriptor<number[]> = {
name: 'duration',
initialValue: '0s',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (context: Context, tokens: CSSValue[]) => {
return tokens.filter(isDimensionToken).map((token) => time.parse(context, token));
}
};

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum FLOAT {
import {Context} from '../../core/context';
export const enum FLOAT {
NONE = 0,
LEFT = 1,
RIGHT = 2,
@ -12,7 +13,7 @@ export const float: IPropertyIdentValueDescriptor<FLOAT> = {
initialValue: 'none',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (float: string) => {
parse: (_context: Context, float: string) => {
switch (float) {
case 'left':
return FLOAT.LEFT;

View File

@ -1,6 +1,7 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue} from '../syntax/parser';
import {TokenType} from '../syntax/tokenizer';
import {Context} from '../../core/context';
export type FONT_FAMILY = string;
@ -11,10 +12,10 @@ export const fontFamily: IPropertyListDescriptor<FontFamily> = {
initialValue: '',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]) => {
parse: (_context: Context, tokens: CSSValue[]) => {
const accumulator: string[] = [];
const results: string[] = [];
tokens.forEach(token => {
tokens.forEach((token) => {
switch (token.type) {
case TokenType.IDENT_TOKEN:
case TokenType.STRING_TOKEN:
@ -32,6 +33,6 @@ export const fontFamily: IPropertyListDescriptor<FontFamily> = {
if (accumulator.length) {
results.push(accumulator.join(' '));
}
return results.map(result => (result.indexOf(' ') === -1 ? result : `'${result}'`));
return results.map((result) => (result.indexOf(' ') === -1 ? result : `'${result}'`));
}
};

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum FONT_STYLE {
import {Context} from '../../core/context';
export const enum FONT_STYLE {
NORMAL = 'normal',
ITALIC = 'italic',
OBLIQUE = 'oblique'
@ -10,7 +11,7 @@ export const fontStyle: IPropertyIdentValueDescriptor<FONT_STYLE> = {
initialValue: 'normal',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (overflow: string) => {
parse: (_context: Context, overflow: string) => {
switch (overflow) {
case 'oblique':
return FONT_STYLE.OBLIQUE;

View File

@ -1,11 +1,12 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken} from '../syntax/parser';
import {Context} from '../../core/context';
export const fontVariant: IPropertyListDescriptor<string[]> = {
name: 'font-variant',
initialValue: 'none',
type: PropertyDescriptorParsingType.LIST,
prefix: false,
parse: (tokens: CSSValue[]): string[] => {
return tokens.filter(isIdentToken).map(token => token.value);
parse: (_context: Context, tokens: CSSValue[]): string[] => {
return tokens.filter(isIdentToken).map((token) => token.value);
}
};

View File

@ -1,11 +1,12 @@
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken, isNumberToken} from '../syntax/parser';
import {Context} from '../../core/context';
export const fontWeight: IPropertyValueDescriptor<number> = {
name: 'font-weight',
initialValue: 'normal',
type: PropertyDescriptorParsingType.VALUE,
prefix: false,
parse: (token: CSSValue): number => {
parse: (_context: Context, token: CSSValue): number => {
if (isNumberToken(token)) {
return token.number;
}

View File

@ -1,12 +1,13 @@
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue} from '../syntax/parser';
import {TokenType} from '../syntax/tokenizer';
import {Context} from '../../core/context';
export const letterSpacing: IPropertyValueDescriptor<number> = {
name: 'letter-spacing',
initialValue: '0',
prefix: false,
type: PropertyDescriptorParsingType.VALUE,
parse: (token: CSSValue) => {
parse: (_context: Context, token: CSSValue) => {
if (token.type === TokenType.IDENT_TOKEN && token.value === 'normal') {
return 0;
}

View File

@ -1,4 +1,5 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {Context} from '../../core/context';
export enum LINE_BREAK {
NORMAL = 'normal',
STRICT = 'strict'
@ -9,7 +10,7 @@ export const lineBreak: IPropertyIdentValueDescriptor<LINE_BREAK> = {
initialValue: 'normal',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (lineBreak: string): LINE_BREAK => {
parse: (_context: Context, lineBreak: string): LINE_BREAK => {
switch (lineBreak) {
case 'strict':
return LINE_BREAK.STRICT;

View File

@ -2,17 +2,18 @@ import {TokenType} from '../syntax/tokenizer';
import {ICSSImage, image} from '../types/image';
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue} from '../syntax/parser';
import {Context} from '../../core/context';
export const listStyleImage: IPropertyValueDescriptor<ICSSImage | null> = {
name: 'list-style-image',
initialValue: 'none',
type: PropertyDescriptorParsingType.VALUE,
prefix: false,
parse: (token: CSSValue) => {
parse: (context: Context, token: CSSValue) => {
if (token.type === TokenType.IDENT_TOKEN && token.value === 'none') {
return null;
}
return image.parse(token);
return image.parse(context, token);
}
};

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum LIST_STYLE_POSITION {
import {Context} from '../../core/context';
export const enum LIST_STYLE_POSITION {
INSIDE = 0,
OUTSIDE = 1
}
@ -9,7 +10,7 @@ export const listStylePosition: IPropertyIdentValueDescriptor<LIST_STYLE_POSITIO
initialValue: 'outside',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (position: string) => {
parse: (_context: Context, position: string) => {
switch (position) {
case 'inside':
return LIST_STYLE_POSITION.INSIDE;

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum LIST_STYLE_TYPE {
import {Context} from '../../core/context';
export const enum LIST_STYLE_TYPE {
NONE = -1,
DISC = 0,
CIRCLE = 1,
@ -61,7 +62,7 @@ export const listStyleType: IPropertyIdentValueDescriptor<LIST_STYLE_TYPE> = {
initialValue: 'none',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (type: string) => {
parse: (_context: Context, type: string) => {
switch (type) {
case 'disc':
return LIST_STYLE_TYPE.DISC;

View File

@ -1,11 +1,12 @@
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isNumberToken} from '../syntax/parser';
import {Context} from '../../core/context';
export const opacity: IPropertyValueDescriptor<number> = {
name: 'opacity',
initialValue: '1',
type: PropertyDescriptorParsingType.VALUE,
prefix: false,
parse: (token: CSSValue): number => {
parse: (_context: Context, token: CSSValue): number => {
if (isNumberToken(token)) {
return token.number;
}

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum OVERFLOW_WRAP {
import {Context} from '../../core/context';
export const enum OVERFLOW_WRAP {
NORMAL = 'normal',
BREAK_WORD = 'break-word'
}
@ -9,7 +10,7 @@ export const overflowWrap: IPropertyIdentValueDescriptor<OVERFLOW_WRAP> = {
initialValue: 'normal',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (overflow: string) => {
parse: (_context: Context, overflow: string) => {
switch (overflow) {
case 'break-word':
return OVERFLOW_WRAP.BREAK_WORD;

View File

@ -1,10 +1,12 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken} from '../syntax/parser';
export enum OVERFLOW {
import {Context} from '../../core/context';
export const enum OVERFLOW {
VISIBLE = 0,
HIDDEN = 1,
SCROLL = 2,
AUTO = 3
CLIP = 3,
AUTO = 4
}
export const overflow: IPropertyListDescriptor<OVERFLOW[]> = {
@ -12,13 +14,15 @@ export const overflow: IPropertyListDescriptor<OVERFLOW[]> = {
initialValue: 'visible',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): OVERFLOW[] => {
return tokens.filter(isIdentToken).map(overflow => {
parse: (_context: Context, tokens: CSSValue[]): OVERFLOW[] => {
return tokens.filter(isIdentToken).map((overflow) => {
switch (overflow.value) {
case 'hidden':
return OVERFLOW.HIDDEN;
case 'scroll':
return OVERFLOW.SCROLL;
case 'clip':
return OVERFLOW.CLIP;
case 'auto':
return OVERFLOW.AUTO;
case 'visible':

View File

@ -0,0 +1,42 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken} from '../syntax/parser';
import {Context} from '../../core/context';
export const enum PAINT_ORDER_LAYER {
FILL,
STROKE,
MARKERS
}
export type PaintOrder = PAINT_ORDER_LAYER[];
export const paintOrder: IPropertyListDescriptor<PaintOrder> = {
name: 'paint-order',
initialValue: 'normal',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (_context: Context, tokens: CSSValue[]): PaintOrder => {
const DEFAULT_VALUE = [PAINT_ORDER_LAYER.FILL, PAINT_ORDER_LAYER.STROKE, PAINT_ORDER_LAYER.MARKERS];
const layers: PaintOrder = [];
tokens.filter(isIdentToken).forEach((token) => {
switch (token.value) {
case 'stroke':
layers.push(PAINT_ORDER_LAYER.STROKE);
break;
case 'fill':
layers.push(PAINT_ORDER_LAYER.FILL);
break;
case 'markers':
layers.push(PAINT_ORDER_LAYER.MARKERS);
break;
}
});
DEFAULT_VALUE.forEach((value) => {
if (layers.indexOf(value) === -1) {
layers.push(value);
}
});
return layers;
}
};

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum POSITION {
import {Context} from '../../core/context';
export const enum POSITION {
STATIC = 0,
RELATIVE = 1,
ABSOLUTE = 2,
@ -12,7 +13,7 @@ export const position: IPropertyIdentValueDescriptor<POSITION> = {
initialValue: 'static',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (position: string) => {
parse: (_context: Context, position: string) => {
switch (position) {
case 'relative':
return POSITION.RELATIVE;

View File

@ -1,6 +1,7 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isStringToken} from '../syntax/parser';
import {TokenType} from '../syntax/tokenizer';
import {Context} from '../../core/context';
export interface QUOTE {
open: string;
@ -14,7 +15,7 @@ export const quotes: IPropertyListDescriptor<Quotes> = {
initialValue: 'none',
prefix: true,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]) => {
parse: (_context: Context, tokens: CSSValue[]) => {
if (tokens.length === 0) {
return null;
}

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum TEXT_ALIGN {
import {Context} from '../../core/context';
export const enum TEXT_ALIGN {
LEFT = 0,
CENTER = 1,
RIGHT = 2
@ -10,7 +11,7 @@ export const textAlign: IPropertyIdentValueDescriptor<TEXT_ALIGN> = {
initialValue: 'left',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (textAlign: string) => {
parse: (_context: Context, textAlign: string) => {
switch (textAlign) {
case 'right':
return TEXT_ALIGN.RIGHT;

View File

@ -1,5 +1,6 @@
import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isIdentToken} from '../syntax/parser';
import {Context} from '../../core/context';
export const enum TEXT_DECORATION_LINE {
NONE = 0,
@ -16,10 +17,10 @@ export const textDecorationLine: IPropertyListDescriptor<TextDecorationLine> = {
initialValue: 'none',
prefix: false,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]): TextDecorationLine => {
parse: (_context: Context, tokens: CSSValue[]): TextDecorationLine => {
return tokens
.filter(isIdentToken)
.map(token => {
.map((token) => {
switch (token.value) {
case 'underline':
return TEXT_DECORATION_LINE.UNDERLINE;
@ -32,6 +33,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

@ -3,6 +3,7 @@ import {CSSValue, isIdentWithValue, parseFunctionArgs} from '../syntax/parser';
import {ZERO_LENGTH} from '../types/length-percentage';
import {color, Color, COLORS} from '../types/color';
import {isLength, Length} from '../types/length';
import {Context} from '../../core/context';
export type TextShadow = TextShadowItem[];
interface TextShadowItem {
@ -17,7 +18,7 @@ export const textShadow: IPropertyListDescriptor<TextShadow> = {
initialValue: 'none',
type: PropertyDescriptorParsingType.LIST,
prefix: false,
parse: (tokens: CSSValue[]): TextShadow => {
parse: (context: Context, tokens: CSSValue[]): TextShadow => {
if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
return [];
}
@ -42,7 +43,7 @@ export const textShadow: IPropertyListDescriptor<TextShadow> = {
}
c++;
} else {
shadow.color = color.parse(token);
shadow.color = color.parse(context, token);
}
}
return shadow;

View File

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum TEXT_TRANSFORM {
import {Context} from '../../core/context';
export const enum TEXT_TRANSFORM {
NONE = 0,
LOWERCASE = 1,
UPPERCASE = 2,
@ -11,7 +12,7 @@ export const textTransform: IPropertyIdentValueDescriptor<TEXT_TRANSFORM> = {
initialValue: 'none',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (textTransform: string) => {
parse: (_context: Context, textTransform: string) => {
switch (textTransform) {
case 'uppercase':
return TEXT_TRANSFORM.UPPERCASE;

View File

@ -2,6 +2,7 @@ import {IPropertyListDescriptor, PropertyDescriptorParsingType} from '../IProper
import {CSSValue} from '../syntax/parser';
import {isLengthPercentage, LengthPercentage} from '../types/length-percentage';
import {FLAG_INTEGER, TokenType} from '../syntax/tokenizer';
import {Context} from '../../core/context';
export type TransformOrigin = [LengthPercentage, LengthPercentage];
const DEFAULT_VALUE: LengthPercentage = {
@ -16,7 +17,7 @@ export const transformOrigin: IPropertyListDescriptor<TransformOrigin> = {
initialValue: '50% 50%',
prefix: true,
type: PropertyDescriptorParsingType.LIST,
parse: (tokens: CSSValue[]) => {
parse: (_context: Context, tokens: CSSValue[]) => {
const origins: LengthPercentage[] = tokens.filter(isLengthPercentage);
if (origins.length !== 2) {

View File

@ -1,6 +1,7 @@
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue} from '../syntax/parser';
import {NumberValueToken, TokenType} from '../syntax/tokenizer';
import {Context} from '../../core/context';
export type Matrix = [number, number, number, number, number, number];
export type Transform = Matrix | null;
@ -9,7 +10,7 @@ export const transform: IPropertyValueDescriptor<Transform> = {
initialValue: 'none',
prefix: true,
type: PropertyDescriptorParsingType.VALUE,
parse: (token: CSSValue) => {
parse: (_context: Context, token: CSSValue) => {
if (token.type === TokenType.IDENT_TOKEN && token.value === 'none') {
return null;
}
@ -27,14 +28,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

@ -1,5 +1,6 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export enum VISIBILITY {
import {Context} from '../../core/context';
export const enum VISIBILITY {
VISIBLE = 0,
HIDDEN = 1,
COLLAPSE = 2
@ -10,7 +11,7 @@ export const visibility: IPropertyIdentValueDescriptor<VISIBILITY> = {
initialValue: 'none',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (visibility: string) => {
parse: (_context: Context, visibility: string) => {
switch (visibility) {
case 'hidden':
return VISIBILITY.HIDDEN;

View File

@ -0,0 +1,8 @@
import {IPropertyTypeValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
export const webkitTextStrokeColor: IPropertyTypeValueDescriptor = {
name: `-webkit-text-stroke-color`,
initialValue: 'currentcolor',
prefix: false,
type: PropertyDescriptorParsingType.TYPE_VALUE,
format: 'color'
};

View File

@ -0,0 +1,15 @@
import {CSSValue, isDimensionToken} from '../syntax/parser';
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {Context} from '../../core/context';
export const webkitTextStrokeWidth: IPropertyValueDescriptor<number> = {
name: `-webkit-text-stroke-width`,
initialValue: '0',
type: PropertyDescriptorParsingType.VALUE,
prefix: false,
parse: (_context: Context, token: CSSValue): number => {
if (isDimensionToken(token)) {
return token.number;
}
return 0;
}
};

View File

@ -1,4 +1,5 @@
import {IPropertyIdentValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {Context} from '../../core/context';
export enum WORD_BREAK {
NORMAL = 'normal',
BREAK_ALL = 'break-all',
@ -10,7 +11,7 @@ export const wordBreak: IPropertyIdentValueDescriptor<WORD_BREAK> = {
initialValue: 'normal',
prefix: false,
type: PropertyDescriptorParsingType.IDENT_VALUE,
parse: (wordBreak: string): WORD_BREAK => {
parse: (_context: Context, wordBreak: string): WORD_BREAK => {
switch (wordBreak) {
case 'break-all':
return WORD_BREAK.BREAK_ALL;

View File

@ -1,6 +1,7 @@
import {IPropertyValueDescriptor, PropertyDescriptorParsingType} from '../IPropertyDescriptor';
import {CSSValue, isNumberToken} from '../syntax/parser';
import {TokenType} from '../syntax/tokenizer';
import {Context} from '../../core/context';
interface zIndex {
order: number;
@ -12,7 +13,7 @@ export const zIndex: IPropertyValueDescriptor<zIndex> = {
initialValue: 'auto',
prefix: false,
type: PropertyDescriptorParsingType.VALUE,
parse: (token: CSSValue): zIndex => {
parse: (_context: Context, token: CSSValue): zIndex => {
if (token.type === TokenType.IDENT_TOKEN) {
return {auto: true, order: 0};
}

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

@ -2,7 +2,7 @@
import {fromCodePoint, toCodePoints} from 'css-line-break';
export enum TokenType {
export const enum TokenType {
STRING_TOKEN,
BAD_STRING_TOKEN,
LEFT_PARENTHESIS_TOKEN,
@ -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;
}
@ -654,7 +657,7 @@ export class Tokenizer {
}
private consumeStringSlice(count: number): string {
const SLICE_STACK_SIZE = 60000;
const SLICE_STACK_SIZE = 50000;
let value = '';
while (count > 0) {
const amount = Math.min(SLICE_STACK_SIZE, count);
@ -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

@ -1,8 +1,9 @@
import {strictEqual} from 'assert';
import {asString, color, isTransparent, pack} from '../color';
import {Parser} from '../../syntax/parser';
import {Context} from '../../../core/context';
const parse = (value: string) => color.parse(Parser.parseValue(value));
const parse = (value: string) => color.parse({} as Context, Parser.parseValue(value));
describe('types', () => {
describe('<color>', () => {

View File

@ -5,30 +5,38 @@ import {color, pack} from '../color';
import {FLAG_INTEGER, TokenType} from '../../syntax/tokenizer';
import {deg} from '../angle';
const parse = (value: string) => image.parse(Parser.parseValue(value));
const colorParse = (value: string) => color.parse(Parser.parseValue(value));
const parse = (context: Context, value: string) => image.parse(context, Parser.parseValue(value));
const colorParse = (context: Context, value: string) => color.parse(context, Parser.parseValue(value));
jest.mock('../../../core/cache-storage');
jest.mock('../../../core/features');
jest.mock('../../../core/context');
import {Context} from '../../../core/context';
describe('types', () => {
let context: Context;
beforeEach(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
context = new Context({} as any, {} as any);
});
describe('<image>', () => {
describe('parsing', () => {
describe('url', () => {
it('url(test.jpg)', () =>
deepStrictEqual(parse('url(http://example.com/test.jpg)'), {
deepStrictEqual(parse(context, 'url(http://example.com/test.jpg)'), {
url: 'http://example.com/test.jpg',
type: CSSImageType.URL
}));
it('url("test.jpg")', () =>
deepStrictEqual(parse('url("http://example.com/test.jpg")'), {
deepStrictEqual(parse(context, 'url("http://example.com/test.jpg")'), {
url: 'http://example.com/test.jpg',
type: CSSImageType.URL
}));
});
describe('linear-gradient', () => {
it('linear-gradient(#f69d3c, #3f87a6)', () =>
deepStrictEqual(parse('linear-gradient(#f69d3c, #3f87a6)'), {
deepStrictEqual(parse(context, 'linear-gradient(#f69d3c, #3f87a6)'), {
angle: deg(180),
type: CSSImageType.LINEAR_GRADIENT,
stops: [
@ -37,45 +45,60 @@ describe('types', () => {
]
}));
it('linear-gradient(yellow, blue)', () =>
deepStrictEqual(parse('linear-gradient(yellow, blue)'), {
deepStrictEqual(parse(context, '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(context, 'yellow'), stop: null},
{color: colorParse(context, 'blue'), stop: null}
]
}));
it('linear-gradient(to bottom, yellow, blue)', () =>
deepStrictEqual(parse('linear-gradient(to bottom, yellow, blue)'), {
deepStrictEqual(parse(context, '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(context, 'yellow'), stop: null},
{color: colorParse(context, 'blue'), stop: null}
]
}));
it('linear-gradient(180deg, yellow, blue)', () =>
deepStrictEqual(parse('linear-gradient(180deg, yellow, blue)'), {
deepStrictEqual(parse(context, '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(context, 'yellow'), stop: null},
{color: colorParse(context, 'blue'), stop: null}
]
}));
it('linear-gradient(to top, blue, yellow)', () =>
deepStrictEqual(parse('linear-gradient(to top, blue, yellow)'), {
deepStrictEqual(parse(context, '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(context, 'blue'), stop: null},
{color: colorParse(context, 'yellow'), stop: null}
]
}));
it('linear-gradient(to top right, blue, yellow)', () =>
deepStrictEqual(parse('linear-gradient(to top right, blue, yellow)'), {
deepStrictEqual(parse(context, 'linear-gradient(to top right, blue, yellow)'), {
angle: [
{type: TokenType.PERCENTAGE_TOKEN, number: 100, flags: 4},
{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(context, 'blue'), stop: null},
{color: colorParse(context, 'yellow'), stop: null}
]
}));
it('linear-gradient(to bottom, yellow 0%, blue 100%)', () =>
deepStrictEqual(parse('linear-gradient(to bottom, yellow 0%, blue 100%)'), {
deepStrictEqual(parse(context, 'linear-gradient(to bottom, yellow 0%, blue 100%)'), {
angle: deg(180),
type: CSSImageType.LINEAR_GRADIENT,
stops: [
{
color: colorParse('yellow'),
color: colorParse(context, 'yellow'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 0,
@ -83,7 +106,7 @@ describe('types', () => {
}
},
{
color: colorParse('blue'),
color: colorParse(context, 'blue'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 100,
@ -94,7 +117,7 @@ describe('types', () => {
}));
it('linear-gradient(to top left, lightpink, lightpink 5px, white 5px, white 10px)', () =>
deepStrictEqual(
parse('linear-gradient(to top left, lightpink, lightpink 5px, white 5px, white 10px)'),
parse(context, 'linear-gradient(to top left, lightpink, lightpink 5px, white 5px, white 10px)'),
{
angle: [
{type: TokenType.PERCENTAGE_TOKEN, number: 100, flags: 4},
@ -102,9 +125,9 @@ describe('types', () => {
],
type: CSSImageType.LINEAR_GRADIENT,
stops: [
{color: colorParse('lightpink'), stop: null},
{color: colorParse(context, 'lightpink'), stop: null},
{
color: colorParse('lightpink'),
color: colorParse(context, 'lightpink'),
stop: {
type: TokenType.DIMENSION_TOKEN,
number: 5,
@ -113,7 +136,7 @@ describe('types', () => {
}
},
{
color: colorParse('white'),
color: colorParse(context, 'white'),
stop: {
type: TokenType.DIMENSION_TOKEN,
number: 5,
@ -122,7 +145,7 @@ describe('types', () => {
}
},
{
color: colorParse('white'),
color: colorParse(context, 'white'),
stop: {
type: TokenType.DIMENSION_TOKEN,
number: 10,
@ -137,13 +160,16 @@ describe('types', () => {
describe('-prefix-linear-gradient', () => {
it('-webkit-linear-gradient(left, #cedbe9 0%, #aac5de 17%, #3a8bc2 84%, #26558b 100%)', () =>
deepStrictEqual(
parse('-webkit-linear-gradient(left, #cedbe9 0%, #aac5de 17%, #3a8bc2 84%, #26558b 100%)'),
parse(
context,
'-webkit-linear-gradient(left, #cedbe9 0%, #aac5de 17%, #3a8bc2 84%, #26558b 100%)'
),
{
angle: deg(90),
type: CSSImageType.LINEAR_GRADIENT,
stops: [
{
color: colorParse('#cedbe9'),
color: colorParse(context, '#cedbe9'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 0,
@ -151,7 +177,7 @@ describe('types', () => {
}
},
{
color: colorParse('#aac5de'),
color: colorParse(context, '#aac5de'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 17,
@ -159,7 +185,7 @@ describe('types', () => {
}
},
{
color: colorParse('#3a8bc2'),
color: colorParse(context, '#3a8bc2'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 84,
@ -167,7 +193,7 @@ describe('types', () => {
}
},
{
color: colorParse('#26558b'),
color: colorParse(context, '#26558b'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 100,
@ -178,12 +204,12 @@ describe('types', () => {
}
));
it('-moz-linear-gradient(top, #cce5f4 0%, #00263c 100%)', () =>
deepStrictEqual(parse('-moz-linear-gradient(top, #cce5f4 0%, #00263c 100%)'), {
deepStrictEqual(parse(context, '-moz-linear-gradient(top, #cce5f4 0%, #00263c 100%)'), {
angle: deg(180),
type: CSSImageType.LINEAR_GRADIENT,
stops: [
{
color: colorParse('#cce5f4'),
color: colorParse(context, '#cce5f4'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 0,
@ -191,7 +217,7 @@ describe('types', () => {
}
},
{
color: colorParse('#00263c'),
color: colorParse(context, '#00263c'),
stop: {
type: TokenType.PERCENTAGE_TOKEN,
number: 100,

View File

@ -3,6 +3,7 @@ import {TokenType} from '../syntax/tokenizer';
import {ITypeDescriptor} from '../ITypeDescriptor';
import {HUNDRED_PERCENT, ZERO_LENGTH} from './length-percentage';
import {GradientCorner} from './image';
import {Context} from '../../core/context';
const DEG = 'deg';
const GRAD = 'grad';
@ -11,7 +12,7 @@ const TURN = 'turn';
export const angle: ITypeDescriptor<number> = {
name: 'angle',
parse: (value: CSSValue): number => {
parse: (_context: Context, value: CSSValue): number => {
if (value.type === TokenType.DIMENSION_TOKEN) {
switch (value.unit) {
case DEG:
@ -41,7 +42,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

@ -1,19 +1,20 @@
import {CSSValue, nonFunctionArgSeparator} from '../syntax/parser';
import {CSSValue, nonFunctionArgSeparator, Parser} from '../syntax/parser';
import {TokenType} from '../syntax/tokenizer';
import {ITypeDescriptor} from '../ITypeDescriptor';
import {angle, deg} from './angle';
import {getAbsoluteValue, isLengthPercentage} from './length-percentage';
import {Context} from '../../core/context';
export type Color = number;
export const color: ITypeDescriptor<Color> = {
name: 'color',
parse: (value: CSSValue): Color => {
parse: (context: Context, value: CSSValue): Color => {
if (value.type === TokenType.FUNCTION) {
const colorFunction = SUPPORTED_COLOR_FUNCTIONS[value.name];
if (typeof colorFunction === 'undefined') {
throw new Error(`Attempting to parse an unsupported color function "${value.name}"`);
}
return colorFunction(value.values);
return colorFunction(context, value.values);
}
if (value.type === TokenType.HASH_TOKEN) {
@ -59,9 +60,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);
@ -85,7 +86,7 @@ const getTokenColorValue = (token: CSSValue, i: number): number => {
return 0;
};
const rgb = (args: CSSValue[]): number => {
const rgb = (_context: Context, args: CSSValue[]): number => {
const tokens = args.filter(nonFunctionArgSeparator);
if (tokens.length === 3) {
@ -120,11 +121,11 @@ function hue2rgb(t1: number, t2: number, hue: number): number {
}
}
const hsl = (args: CSSValue[]): number => {
const hsl = (context: Context, args: CSSValue[]): number => {
const tokens = args.filter(nonFunctionArgSeparator);
const [hue, saturation, lightness, alpha] = tokens;
const h = (hue.type === TokenType.NUMBER_TOKEN ? deg(hue.number) : angle.parse(hue)) / (Math.PI * 2);
const h = (hue.type === TokenType.NUMBER_TOKEN ? deg(hue.number) : angle.parse(context, hue)) / (Math.PI * 2);
const s = isLengthPercentage(saturation) ? saturation.number / 100 : 0;
const l = isLengthPercentage(lightness) ? lightness.number / 100 : 0;
const a = typeof alpha !== 'undefined' && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1;
@ -143,7 +144,7 @@ const hsl = (args: CSSValue[]): number => {
};
const SUPPORTED_COLOR_FUNCTIONS: {
[key: string]: (args: CSSValue[]) => number;
[key: string]: (context: Context, args: CSSValue[]) => number;
} = {
hsl: hsl,
hsla: hsl,
@ -151,6 +152,9 @@ const SUPPORTED_COLOR_FUNCTIONS: {
rgba: rgb
};
export const parseColor = (context: Context, value: string): Color =>
color.parse(context, Parser.create(value).parseComponentValue());
export const COLORS: {[key: string]: Color} = {
ALICEBLUE: 0xf0f8ffff,
ANTIQUEWHITE: 0xfaebd7ff,

View File

@ -3,8 +3,9 @@ import {CSSImageType, CSSLinearGradientImage, GradientCorner, UnprocessedGradien
import {TokenType} from '../../syntax/tokenizer';
import {isAngle, angle as angleType, parseNamedSide, deg} from '../angle';
import {parseColorStop} from './gradient';
import {Context} from '../../../core/context';
export const prefixLinearGradient = (tokens: CSSValue[]): CSSLinearGradientImage => {
export const prefixLinearGradient = (context: Context, tokens: CSSValue[]): CSSLinearGradientImage => {
let angle: number | GradientCorner = deg(180);
const stops: UnprocessedGradientColorStop[] = [];
@ -18,11 +19,11 @@ export const prefixLinearGradient = (tokens: CSSValue[]): CSSLinearGradientImage
angle = parseNamedSide(arg);
return;
} else if (isAngle(firstToken)) {
angle = (angleType.parse(firstToken) + deg(270)) % deg(360);
angle = (angleType.parse(context, firstToken) + deg(270)) % deg(360);
return;
}
}
const colorStop = parseColorStop(arg);
const colorStop = parseColorStop(context, arg);
stops.push(colorStop);
});

View File

@ -20,8 +20,9 @@ import {
FARTHEST_CORNER,
FARTHEST_SIDE
} from './radial-gradient';
import {Context} from '../../../core/context';
export const prefixRadialGradient = (tokens: CSSValue[]): CSSRadialGradientImage => {
export const prefixRadialGradient = (context: Context, tokens: CSSValue[]): CSSRadialGradientImage => {
let shape: CSSRadialShape = CSSRadialShape.CIRCLE;
let size: CSSRadialSize = CSSRadialExtent.FARTHEST_CORNER;
const stops: UnprocessedGradientColorStop[] = [];
@ -90,7 +91,7 @@ export const prefixRadialGradient = (tokens: CSSValue[]): CSSRadialGradientImage
}
if (isColorStop) {
const colorStop = parseColorStop(arg);
const colorStop = parseColorStop(context, arg);
stops.push(colorStop);
}
});

View File

@ -12,13 +12,17 @@ import {deg} from '../angle';
import {TokenType} from '../../syntax/tokenizer';
import {color as colorType} from '../color';
import {HUNDRED_PERCENT, LengthPercentage, ZERO_LENGTH} from '../length-percentage';
import {Context} from '../../../core/context';
export const webkitGradient = (tokens: CSSValue[]): CSSLinearGradientImage | CSSRadialGradientImage => {
let angle = deg(180);
export const webkitGradient = (
context: Context,
tokens: CSSValue[]
): CSSLinearGradientImage | CSSRadialGradientImage => {
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];
@ -34,15 +38,15 @@ export const webkitGradient = (tokens: CSSValue[]): CSSLinearGradientImage | CSS
if (firstToken.type === TokenType.FUNCTION) {
if (firstToken.name === 'from') {
const color = colorType.parse(firstToken.values[0]);
const color = colorType.parse(context, firstToken.values[0]);
stops.push({stop: ZERO_LENGTH, color});
} else if (firstToken.name === 'to') {
const color = colorType.parse(firstToken.values[0]);
const color = colorType.parse(context, firstToken.values[0]);
stops.push({stop: HUNDRED_PERCENT, color});
} else if (firstToken.name === 'color-stop') {
const values = firstToken.values.filter(nonFunctionArgSeparator);
if (values.length === 2) {
const color = colorType.parse(values[1]);
const color = colorType.parse(context, values[1]);
const stop = values[0];
if (isNumberToken(stop)) {
stops.push({

View File

@ -5,9 +5,10 @@ import {CSSImageType, CSSRadialExtent, CSSRadialShape} from '../../image';
import {color} from '../../color';
import {TokenType} from '../../../syntax/tokenizer';
import {FIFTY_PERCENT, HUNDRED_PERCENT} from '../../length-percentage';
import {Context} from '../../../../core/context';
const parse = (value: string) => radialGradient((Parser.parseValues(value)[0] as CSSFunction).values);
const colorParse = (value: string) => color.parse(Parser.parseValue(value));
const parse = (value: string) => radialGradient({} as Context, (Parser.parseValues(value)[0] as CSSFunction).values);
const colorParse = (value: string) => color.parse({} as Context, Parser.parseValue(value));
describe('functions', () => {
describe('radial-gradient', () => {
@ -55,7 +56,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

@ -4,12 +4,9 @@ import {contains} from '../../../core/bitwise';
import {CSSParsedCounterDeclaration} from '../../index';
export class CounterState {
readonly counters: {[key: string]: number[]};
constructor() {
this.counters = {};
}
private readonly counters: {[key: string]: number[]} = {};
getCounterValue(name: string) {
getCounterValue(name: string): number {
const counter = this.counters[name];
if (counter && counter.length) {
@ -18,13 +15,13 @@ export class CounterState {
return 1;
}
getCounterValues(name: string): number[] {
getCounterValues(name: string): readonly number[] {
const counter = this.counters[name];
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,10 +30,13 @@ 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;
if (!counter.length) {
counter.push(1);
}
counter[Math.max(0, counter.length - 1)] += entry.increment;
}
});
@ -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

@ -9,9 +9,10 @@ import {
} from '../image';
import {color as colorType} from '../color';
import {getAbsoluteValue, HUNDRED_PERCENT, isLengthPercentage, ZERO_LENGTH} from '../length-percentage';
import {Context} from '../../../core/context';
export const parseColorStop = (args: CSSValue[]): UnprocessedGradientColorStop => {
const color = colorType.parse(args[0]);
export const parseColorStop = (context: Context, args: CSSValue[]): UnprocessedGradientColorStop => {
const color = colorType.parse(context, args[0]);
const stop = args[1];
return stop && isLengthPercentage(stop) ? {color, stop} : {color, stop: null};
};
@ -98,7 +99,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

@ -3,8 +3,9 @@ import {TokenType} from '../../syntax/tokenizer';
import {isAngle, angle as angleType, parseNamedSide, deg} from '../angle';
import {CSSImageType, CSSLinearGradientImage, GradientCorner, UnprocessedGradientColorStop} from '../image';
import {parseColorStop} from './gradient';
import {Context} from '../../../core/context';
export const linearGradient = (tokens: CSSValue[]): CSSLinearGradientImage => {
export const linearGradient = (context: Context, tokens: CSSValue[]): CSSLinearGradientImage => {
let angle: number | GradientCorner = deg(180);
const stops: UnprocessedGradientColorStop[] = [];
@ -15,11 +16,11 @@ export const linearGradient = (tokens: CSSValue[]): CSSLinearGradientImage => {
angle = parseNamedSide(arg);
return;
} else if (isAngle(firstToken)) {
angle = angleType.parse(firstToken);
angle = angleType.parse(context, firstToken);
return;
}
}
const colorStop = parseColorStop(arg);
const colorStop = parseColorStop(context, arg);
stops.push(colorStop);
});

View File

@ -10,6 +10,7 @@ import {
import {parseColorStop} from './gradient';
import {FIFTY_PERCENT, HUNDRED_PERCENT, isLengthPercentage, LengthPercentage, ZERO_LENGTH} from '../length-percentage';
import {isLength} from '../length';
import {Context} from '../../../core/context';
export const CLOSEST_SIDE = 'closest-side';
export const FARTHEST_SIDE = 'farthest-side';
export const CLOSEST_CORNER = 'closest-corner';
@ -19,7 +20,7 @@ export const ELLIPSE = 'ellipse';
export const COVER = 'cover';
export const CONTAIN = 'contain';
export const radialGradient = (tokens: CSSValue[]): CSSRadialGradientImage => {
export const radialGradient = (context: Context, tokens: CSSValue[]): CSSRadialGradientImage => {
let shape: CSSRadialShape = CSSRadialShape.CIRCLE;
let size: CSSRadialSize = CSSRadialExtent.FARTHEST_CORNER;
const stops: UnprocessedGradientColorStop[] = [];
@ -85,7 +86,7 @@ export const radialGradient = (tokens: CSSValue[]): CSSRadialGradientImage => {
}
if (isColorStop) {
const colorStop = parseColorStop(arg);
const colorStop = parseColorStop(context, arg);
stops.push(colorStop);
}
});

View File

@ -4,13 +4,13 @@ import {Color} from './color';
import {linearGradient} from './functions/linear-gradient';
import {prefixLinearGradient} from './functions/-prefix-linear-gradient';
import {ITypeDescriptor} from '../ITypeDescriptor';
import {CacheStorage} from '../../core/cache-storage';
import {LengthPercentage} from './length-percentage';
import {webkitGradient} from './functions/-webkit-gradient';
import {radialGradient} from './functions/radial-gradient';
import {prefixRadialGradient} from './functions/-prefix-radial-gradient';
import {Context} from '../../core/context';
export enum CSSImageType {
export const enum CSSImageType {
URL,
LINEAR_GRADIENT,
RADIAL_GRADIENT
@ -56,12 +56,12 @@ export interface CSSLinearGradientImage extends ICSSGradientImage {
type: CSSImageType.LINEAR_GRADIENT;
}
export enum CSSRadialShape {
export const enum CSSRadialShape {
CIRCLE,
ELLIPSE
}
export enum CSSRadialExtent {
export const enum CSSRadialExtent {
CLOSEST_SIDE,
FARTHEST_SIDE,
CLOSEST_CORNER,
@ -79,10 +79,10 @@ export interface CSSRadialGradientImage extends ICSSGradientImage {
export const image: ITypeDescriptor<ICSSImage> = {
name: 'image',
parse: (value: CSSValue): ICSSImage => {
parse: (context: Context, value: CSSValue): ICSSImage => {
if (value.type === TokenType.URL_TOKEN) {
const image: CSSURLImage = {url: value.value, type: CSSImageType.URL};
CacheStorage.getInstance().addImage(value.value);
context.cache.addImage(value.value);
return image;
}
@ -91,18 +91,21 @@ export const image: ITypeDescriptor<ICSSImage> = {
if (typeof imageFunction === 'undefined') {
throw new Error(`Attempting to parse an unsupported image function "${value.name}"`);
}
return imageFunction(value.values);
return imageFunction(context, value.values);
}
throw new Error(`Unsupported image type`);
throw new Error(`Unsupported image type ${value.type}`);
}
};
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.IDENT_TOKEN && value.value === 'none') &&
(value.type !== TokenType.FUNCTION || !!SUPPORTED_IMAGE_FUNCTIONS[value.name])
);
}
const SUPPORTED_IMAGE_FUNCTIONS: Record<string, (args: CSSValue[]) => ICSSImage> = {
const SUPPORTED_IMAGE_FUNCTIONS: Record<string, (context: Context, args: CSSValue[]) => ICSSImage> = {
'linear-gradient': linearGradient,
'-moz-linear-gradient': prefixLinearGradient,
'-ms-linear-gradient': prefixLinearGradient,

View File

@ -1 +1 @@
export type CSSTypes = 'angle' | 'color' | 'image' | 'length' | 'length-percentage';
export type CSSTypes = 'angle' | 'color' | 'image' | 'length' | 'length-percentage' | 'time';

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;
}

20
src/css/types/time.ts Normal file
View File

@ -0,0 +1,20 @@
import {CSSValue} from '../syntax/parser';
import {TokenType} from '../syntax/tokenizer';
import {ITypeDescriptor} from '../ITypeDescriptor';
import {Context} from '../../core/context';
export const time: ITypeDescriptor<number> = {
name: 'time',
parse: (_context: Context, value: CSSValue): number => {
if (value.type === TokenType.DIMENSION_TOKEN) {
switch (value.unit.toLowerCase()) {
case 's':
return 1000 * value.number;
case 'ms':
return value.number;
}
}
throw new Error(`Unsupported time type`);
}
};

View File

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

View File

@ -2,29 +2,40 @@ import {Bounds} from '../css/layout/bounds';
import {
isBodyElement,
isCanvasElement,
isCustomElement,
isElementNode,
isHTMLElementNode,
isIFrameElement,
isImageElement,
isScriptElement,
isSelectElement,
isSlotElement,
isStyleElement,
isSVGElementNode,
isTextareaElement,
isTextNode
isTextNode,
isVideoElement
} from './node-parser';
import {Logger} from '../core/logger';
import {isIdentToken, nonFunctionArgSeparator} from '../css/syntax/parser';
import {TokenType} from '../css/syntax/tokenizer';
import {CounterState, createCounterText} from '../css/types/functions/counter';
import {LIST_STYLE_TYPE, listStyleType} from '../css/property-descriptors/list-style-type';
import {CSSParsedCounterDeclaration, CSSParsedPseudoDeclaration} from '../css/index';
import {getQuote} from '../css/property-descriptors/quotes';
import {Context} from '../core/context';
import {DebuggerType, isDebugging} from '../core/debugger';
export interface CloneOptions {
id: string;
ignoreElements?: (element: Element) => boolean;
onclone?: (document: Document) => void;
onclone?: (document: Document, element: HTMLElement) => void;
allowTaint?: boolean;
}
export interface WindowOptions {
scrollX: number;
scrollY: number;
windowWidth: number;
windowHeight: number;
}
export type CloneConfigurations = CloneOptions & {
@ -36,15 +47,17 @@ const IGNORE_ATTRIBUTE = 'data-html2canvas-ignore';
export class DocumentCloner {
private readonly scrolledElements: [Element, number, number][];
private readonly options: CloneConfigurations;
private readonly referenceElement: HTMLElement;
clonedReferenceElement?: HTMLElement;
private readonly documentElement: HTMLElement;
private readonly counters: CounterState;
private quoteDepth: number;
constructor(element: HTMLElement, options: CloneConfigurations) {
this.options = options;
constructor(
private readonly context: Context,
element: HTMLElement,
private readonly options: CloneConfigurations
) {
this.scrolledElements = [];
this.referenceElement = element;
this.counters = new CounterState();
@ -53,7 +66,7 @@ export class DocumentCloner {
throw new Error('Cloned element does not have an owner document');
}
this.documentElement = this.cloneNode(element.ownerDocument.documentElement) as HTMLElement;
this.documentElement = this.cloneNode(element.ownerDocument.documentElement, false) as HTMLElement;
}
toIFrame(ownerDocument: Document, windowSize: Bounds): Promise<HTMLIFrameElement> {
@ -81,15 +94,21 @@ export class DocumentCloner {
/(iPad|iPhone|iPod)/g.test(navigator.userAgent) &&
(cloneWindow.scrollY !== windowSize.top || cloneWindow.scrollX !== windowSize.left)
) {
documentClone.documentElement.style.top = -windowSize.top + 'px';
documentClone.documentElement.style.left = -windowSize.left + 'px';
documentClone.documentElement.style.position = 'absolute';
this.context.logger.warn('Unable to restore scroll position for cloned document');
this.context.windowBounds = this.context.windowBounds.add(
cloneWindow.scrollX - windowSize.left,
cloneWindow.scrollY - windowSize.top,
0,
0
);
}
}
const onclone = this.options.onclone;
if (typeof this.clonedReferenceElement === 'undefined') {
const referenceElement = this.clonedReferenceElement;
if (typeof referenceElement === 'undefined') {
return Promise.reject(`Error finding the ${this.referenceElement.nodeName} in the cloned document`);
}
@ -97,9 +116,13 @@ export class DocumentCloner {
await documentClone.fonts.ready;
}
if (/(AppleWebKit)/g.test(navigator.userAgent)) {
await imagesReady(documentClone);
}
if (typeof onclone === 'function') {
return Promise.resolve()
.then(() => onclone(documentClone))
.then(() => onclone(documentClone, referenceElement))
.then(() => iframe);
}
@ -117,25 +140,42 @@ export class DocumentCloner {
}
createElementClone<T extends HTMLElement | SVGElement>(node: T): HTMLElement | SVGElement {
if (isDebugging(node, DebuggerType.CLONE)) {
debugger;
}
if (isCanvasElement(node)) {
return this.createCanvasClone(node);
}
/*
if (isIFrameElement(node)) {
return this.createIFrameClone(node);
if (isVideoElement(node)) {
return this.createVideoClone(node);
}
*/
if (isStyleElement(node)) {
return this.createStyleClone(node);
}
const clone = node.cloneNode(false) as T;
// @ts-ignore
if (isImageElement(clone) && clone.loading === 'lazy') {
// @ts-ignore
clone.loading = 'eager';
if (isImageElement(clone)) {
if (isImageElement(node) && node.currentSrc && node.currentSrc !== node.src) {
clone.src = node.currentSrc;
clone.srcset = '';
}
if (clone.loading === 'lazy') {
clone.loading = 'eager';
}
}
if (isCustomElement(clone)) {
return this.createCustomElementClone(clone);
}
return clone;
}
createCustomElementClone(node: HTMLElement): HTMLElement {
const clone = document.createElement('html2canvascustomelement');
copyCSSStyles(node.style, clone);
return clone;
}
@ -155,7 +195,7 @@ export class DocumentCloner {
}
} catch (e) {
// accessing node.sheet.cssRules throws a DOMException
Logger.getInstance(this.options.id).error('Unable to access cssRules property', e);
this.context.logger.error('Unable to access cssRules property', e);
if (e.name !== 'SecurityError') {
throw e;
}
@ -170,7 +210,7 @@ export class DocumentCloner {
img.src = canvas.toDataURL();
return img;
} catch (e) {
Logger.getInstance(this.options.id).info(`Unable to clone canvas contents, canvas is tainted`);
this.context.logger.info(`Unable to inline canvas contents, canvas is tainted`, canvas);
}
}
@ -182,79 +222,88 @@ export class DocumentCloner {
const ctx = canvas.getContext('2d');
const clonedCtx = clonedCanvas.getContext('2d');
if (clonedCtx) {
if (ctx) {
if (!this.options.allowTaint && ctx) {
clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
} else {
const gl = canvas.getContext('webgl2') ?? canvas.getContext('webgl');
if (gl) {
const attribs = gl.getContextAttributes();
if (attribs?.preserveDrawingBuffer === false) {
this.context.logger.warn(
'Unable to clone WebGL context as it has preserveDrawingBuffer=false',
canvas
);
}
}
clonedCtx.drawImage(canvas, 0, 0);
}
}
return clonedCanvas;
} catch (e) {}
} catch (e) {
this.context.logger.info(`Unable to clone canvas as it is tainted`, canvas);
}
return clonedCanvas;
}
/*
createIFrameClone(iframe: HTMLIFrameElement) {
const tempIframe = <HTMLIFrameElement>iframe.cloneNode(false);
const iframeKey = generateIframeKey();
tempIframe.setAttribute('data-html2canvas-internal-iframe-key', iframeKey);
const {width, height} = parseBounds(iframe);
createVideoClone(video: HTMLVideoElement): HTMLCanvasElement {
const canvas = video.ownerDocument.createElement('canvas');
this.resourceLoader.cache[iframeKey] = getIframeDocumentElement(iframe, this.options)
.then(documentElement => {
return this.renderer(
documentElement,
{
allowTaint: this.options.allowTaint,
backgroundColor: '#ffffff',
canvas: null,
imageTimeout: this.options.imageTimeout,
logging: this.options.logging,
proxy: this.options.proxy,
removeContainer: this.options.removeContainer,
scale: this.options.scale,
foreignObjectRendering: this.options.foreignObjectRendering,
useCORS: this.options.useCORS,
target: new CanvasRenderer(),
width,
height,
x: 0,
y: 0,
windowWidth: documentElement.ownerDocument.defaultView.innerWidth,
windowHeight: documentElement.ownerDocument.defaultView.innerHeight,
scrollX: documentElement.ownerDocument.defaultView.pageXOffset,
scrollY: documentElement.ownerDocument.defaultView.pageYOffset
},
);
})
.then(
(canvas: HTMLCanvasElement) =>
new Promise((resolve, reject) => {
const iframeCanvas = document.createElement('img');
iframeCanvas.onload = () => resolve(canvas);
iframeCanvas.onerror = (event) => {
// Empty iframes may result in empty "data:," URLs, which are invalid from the <img>'s point of view
// and instead of `onload` cause `onerror` and unhandled rejection warnings
// https://github.com/niklasvh/html2canvas/issues/1502
iframeCanvas.src == 'data:,' ? resolve(canvas) : reject(event);
};
iframeCanvas.src = canvas.toDataURL();
if (tempIframe.parentNode && iframe.ownerDocument && iframe.ownerDocument.defaultView) {
tempIframe.parentNode.replaceChild(
copyCSSStyles(
iframe.ownerDocument.defaultView.getComputedStyle(iframe),
iframeCanvas
),
tempIframe
);
}
})
);
return tempIframe;
canvas.width = video.offsetWidth;
canvas.height = video.offsetHeight;
const ctx = canvas.getContext('2d');
try {
if (ctx) {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
if (!this.options.allowTaint) {
ctx.getImageData(0, 0, canvas.width, canvas.height);
}
}
return canvas;
} catch (e) {
this.context.logger.info(`Unable to clone video as it is tainted`, video);
}
const blankCanvas = video.ownerDocument.createElement('canvas');
blankCanvas.width = video.offsetWidth;
blankCanvas.height = video.offsetHeight;
return blankCanvas;
}
*/
cloneNode(node: Node): Node {
appendChildNode(clone: HTMLElement | SVGElement, child: Node, copyStyles: boolean): void {
if (
!isElementNode(child) ||
(!isScriptElement(child) &&
!child.hasAttribute(IGNORE_ATTRIBUTE) &&
(typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child)))
) {
if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) {
clone.appendChild(this.cloneNode(child, copyStyles));
}
}
}
cloneChildNodes(node: Element, clone: HTMLElement | SVGElement, copyStyles: boolean): void {
for (
let child = node.shadowRoot ? node.shadowRoot.firstChild : node.firstChild;
child;
child = child.nextSibling
) {
if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === 'function') {
const assignedNodes = child.assignedNodes() as ChildNode[];
if (assignedNodes.length) {
assignedNodes.forEach((assignedNode) => this.appendChildNode(clone, assignedNode, copyStyles));
}
} else {
this.appendChildNode(clone, child, copyStyles);
}
}
}
cloneNode(node: Node, copyStyles: boolean): Node {
if (isTextNode(node)) {
return document.createTextNode(node.data);
}
@ -267,6 +316,7 @@ export class DocumentCloner {
if (window && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
const clone = this.createElementClone(node);
clone.style.transitionProperty = 'none';
const style = window.getComputedStyle(node);
const styleBefore = window.getComputedStyle(node, ':before');
@ -279,20 +329,15 @@ export class DocumentCloner {
createPseudoHideStyles(clone);
}
const counters = this.counters.parse(new CSSParsedCounterDeclaration(style));
const counters = this.counters.parse(new CSSParsedCounterDeclaration(this.context, style));
const before = this.resolvePseudoContent(node, clone, styleBefore, PseudoElementType.BEFORE);
for (let child = node.firstChild; child; child = child.nextSibling) {
if (
!isElementNode(child) ||
(!isScriptElement(child) &&
!child.hasAttribute(IGNORE_ATTRIBUTE) &&
(typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child)))
) {
if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) {
clone.appendChild(this.cloneNode(child));
}
}
if (isCustomElement(node)) {
copyStyles = true;
}
if (!isVideoElement(node)) {
this.cloneChildNodes(node, clone, copyStyles);
}
if (before) {
@ -306,12 +351,13 @@ export class DocumentCloner {
this.counters.pop(counters);
if (style && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node)) {
if (
(style && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node)) ||
copyStyles
) {
copyCSSStyles(style, clone);
}
//this.inlineAllImages(clone);
if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
this.scrolledElements.push([clone, node.scrollLeft, node.scrollTop]);
}
@ -345,13 +391,13 @@ export class DocumentCloner {
return;
}
this.counters.parse(new CSSParsedCounterDeclaration(style));
const declaration = new CSSParsedPseudoDeclaration(style);
this.counters.parse(new CSSParsedCounterDeclaration(this.context, style));
const declaration = new CSSParsedPseudoDeclaration(this.context, style);
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) {
@ -373,7 +419,7 @@ export class DocumentCloner {
const counterState = this.counters.getCounterValue(counter.value);
const counterType =
counterStyle && isIdentToken(counterStyle)
? listStyleType.parse(counterStyle.value)
? listStyleType.parse(this.context, counterStyle.value)
: LIST_STYLE_TYPE.DECIMAL;
anonymousReplacedElement.appendChild(
@ -386,11 +432,11 @@ export class DocumentCloner {
const counterStates = this.counters.getCounterValues(counter.value);
const counterType =
counterStyle && isIdentToken(counterStyle)
? listStyleType.parse(counterStyle.value)
? listStyleType.parse(this.context, counterStyle.value)
: 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));
@ -464,6 +510,25 @@ const createIFrameContainer = (ownerDocument: Document, bounds: Bounds): HTMLIFr
return cloneIframeContainer;
};
const imageReady = (img: HTMLImageElement): Promise<Event | void | string> => {
return new Promise((resolve) => {
if (img.complete) {
resolve();
return;
}
if (!img.src) {
resolve();
return;
}
img.onload = resolve;
img.onerror = resolve;
});
};
const imagesReady = (document: HTMLDocument): Promise<unknown[]> => {
return Promise.all([].slice.call(document.images, 0).map(imageReady));
};
const iframeLoader = (iframe: HTMLIFrameElement): Promise<HTMLIFrameElement> => {
return new Promise((resolve, reject) => {
const cloneWindow = iframe.contentWindow;
@ -474,8 +539,8 @@ const iframeLoader = (iframe: HTMLIFrameElement): Promise<HTMLIFrameElement> =>
const documentClone = cloneWindow.document;
cloneWindow.onload = iframe.onload = documentClone.onreadystatechange = () => {
cloneWindow.onload = iframe.onload = documentClone.onreadystatechange = null;
cloneWindow.onload = iframe.onload = () => {
cloneWindow.onload = iframe.onload = null;
const interval = setInterval(() => {
if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
clearInterval(interval);
@ -486,12 +551,17 @@ const iframeLoader = (iframe: HTMLIFrameElement): Promise<HTMLIFrameElement> =>
});
};
const ignoredStyleProperties = [
'all', // #2476
'd', // #2483
'content' // Safari shows pseudoelements if content is set
];
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);
// Safari shows pseudoelements if content is set
if (property !== 'content') {
if (ignoredStyleProperties.indexOf(property) === -1) {
target.style.setProperty(property, style.getPropertyValue(property));
}
}

View File

@ -2,29 +2,45 @@ import {CSSParsedDeclaration} from '../css/index';
import {TextContainer} from './text-container';
import {Bounds, parseBounds} from '../css/layout/bounds';
import {isHTMLElementNode} from './node-parser';
import {Context} from '../core/context';
import {DebuggerType, isDebugging} from '../core/debugger';
export const enum FLAGS {
CREATES_STACKING_CONTEXT = 1 << 1,
CREATES_REAL_STACKING_CONTEXT = 1 << 2,
IS_LIST_OWNER = 1 << 3
IS_LIST_OWNER = 1 << 3,
DEBUG_RENDER = 1 << 4
}
export class ElementContainer {
readonly styles: CSSParsedDeclaration;
readonly textNodes: TextContainer[];
readonly elements: ElementContainer[];
readonly textNodes: TextContainer[] = [];
readonly elements: ElementContainer[] = [];
bounds: Bounds;
flags: number;
flags = 0;
constructor(element: Element) {
this.styles = new CSSParsedDeclaration(window.getComputedStyle(element, null));
this.textNodes = [];
this.elements = [];
if (this.styles.transform !== null && isHTMLElementNode(element)) {
// getBoundingClientRect takes transforms into account
element.style.transform = 'none';
constructor(protected readonly context: Context, element: Element) {
if (isDebugging(element, DebuggerType.PARSE)) {
debugger;
}
this.styles = new CSSParsedDeclaration(context, window.getComputedStyle(element, null));
if (isHTMLElementNode(element)) {
if (this.styles.animationDuration.some((duration) => duration > 0)) {
element.style.animationDuration = '0s';
}
if (this.styles.transform !== null) {
// getBoundingClientRect takes transforms into account
element.style.transform = 'none';
}
}
this.bounds = parseBounds(this.context, element);
if (isDebugging(element, DebuggerType.RENDER)) {
this.flags |= FLAGS.DEBUG_RENDER;
}
this.bounds = parseBounds(element);
this.flags = 0;
}
}

View File

@ -1,9 +1,10 @@
import {ElementContainer} from '../element-container';
import {Context} from '../../core/context';
export class LIElementContainer extends ElementContainer {
readonly value: number;
constructor(element: HTMLLIElement) {
super(element);
constructor(context: Context, element: HTMLLIElement) {
super(context, element);
this.value = element.value;
}
}

View File

@ -1,10 +1,11 @@
import {ElementContainer} from '../element-container';
import {Context} from '../../core/context';
export class OLElementContainer extends ElementContainer {
readonly start: number;
readonly reversed: boolean;
constructor(element: HTMLOListElement) {
super(element);
constructor(context: Context, element: HTMLOListElement) {
super(context, element);
this.start = element.start;
this.reversed = typeof element.reversed === 'boolean' && element.reversed === true;
}

Some files were not shown because too many files have changed in this diff Show More